diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 37ced9f93..4a219563a 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -50,7 +50,7 @@ jobs: name: 🧪 Unit tests strategy: matrix: - python: ["3.7", "3.8", "3.9"] + python: ["3.7", "3.8", "3.9", "3.10"] runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 @@ -70,7 +70,7 @@ jobs: needs: build strategy: matrix: - python: ["3.7", "3.8", "3.9"] + python: ["3.7", "3.8", "3.9", "3.10"] installable: ["wheel", "sdist"] runs-on: ubuntu-latest steps: diff --git a/.github/workflows/issue_automation.yml b/.github/workflows/issue_automation.yml index 40a89ba60..3e5b9e016 100644 --- a/.github/workflows/issue_automation.yml +++ b/.github/workflows/issue_automation.yml @@ -109,6 +109,11 @@ jobs: issue_number: context.issue.number, }) const comment = comments.data.find(c => c.user.login === "github-actions[bot]" && c.body.includes(marker)); + if (comment) { + console.log("Found comment, id=" + comment.id); + } else { + console.log("No comment found"); + } if (!labels.includes("triage") || labels.includes("approved")) { console.log("Deleting comment if it exists..."); @@ -127,20 +132,20 @@ jobs: if (!found) { console.log("No bundle found, posting/updating reminder"); const text = REMINDER + "\n" + marker; - if (comment && comment.body !== text) { - await github.rest.issues.updateComment({ - owner: context.repo.owner, - repo: context.repo.repo, - comment_id: comment.id, - body: text - }); - } else { + if (!comment) { await github.rest.issues.createComment({ owner: context.repo.owner, repo: context.repo.repo, issue_number: context.issue.number, body: text }); + } else if (comment.body !== text) { + await github.rest.issues.updateComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: comment.id, + body: text + }); } } else if (found && comment) { console.log("Bundle found, saying thanks"); diff --git a/.github/workflows/test_install.yml b/.github/workflows/test_install.yml index aae343c08..37e64bc49 100644 --- a/.github/workflows/test_install.yml +++ b/.github/workflows/test_install.yml @@ -14,7 +14,7 @@ jobs: strategy: matrix: os: ["ubuntu-latest"] - python: ["3.7", "3.8", "3.9"] + python: ["3.7", "3.8", "3.9", "3.10"] branch: ["master"] runs-on: ${{ matrix.os }} steps: @@ -49,7 +49,7 @@ jobs: strategy: matrix: os: ["ubuntu-latest"] - python: ["3.7", "3.8", "3.9"] + python: ["3.7", "3.8", "3.9", "3.10"] runs-on: ${{ matrix.os }} steps: - name: 👀 Determine latest release diff --git a/AUTHORS.md b/AUTHORS.md index 211070883..16a42ce8d 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -154,6 +154,9 @@ date of first contribution): * [Bryan Kenote](https://github.com/bryankenote) * [Quinn Damerell](https://github.com/QuinnDamerell) * [Sven Samoray](https://github.com/thelastWallE) + * [Christian Würthner](https://github.com/crysxd) + * [Maciej Urbański](https://github.com/rooterkyberian) + * [Adam Wolf](https://github.com/adamwolf) * [Carey Metcalfe](https://github.com/pR0Ps) OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 51c1e7d19..89706c7cf 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -97,7 +97,7 @@ following section *completely* and also follow the instructions in the **safe mode**, either by selecting "Restart OctoPrint in safe mode" from the "System" menu, or by starting OctoPrint from the command line with `octoprint serve --safe`. Then try to reproduce your issue. Find out - more about safe mode in the [docs](http://docs.octoprint.org/en/master/features/safemode.html). + more about safe mode in the [docs](https://docs.octoprint.org/en/master/features/safemode.html). You might also want to try the current development version of OctoPrint (if you aren't already). Refer to the [FAQ](https://faq.octoprint.org) diff --git a/README.md b/README.md index 62cd644d9..e4ade6a0c 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@

OctoPrint provides a snappy web interface for controlling consumer 3D printers. It is Free Software -and released under the [GNU Affero General Public License V3](http://www.gnu.org/licenses/agpl.html). +and released under the [GNU Affero General Public License V3](https://www.gnu.org/licenses/agpl-3.0.html). Its website can be found at [octoprint.org](https://octoprint.org/?utm_source=github&utm_medium=readme). @@ -27,7 +27,7 @@ An invite to the Discord server can be found at [discord.octoprint.org](https:// The FAQ can be accessed by following [faq.octoprint.org](https://faq.octoprint.org/?utm_source=github&utm_medium=readme). -The documentation is located at [docs.octoprint.org](http://docs.octoprint.org). +The documentation is located at [docs.octoprint.org](https://docs.octoprint.org). The official plugin repository can be reached at [plugins.octoprint.org](https://plugins.octoprint.org/?utm_source=github&utm_medium=readme). @@ -38,14 +38,14 @@ If you enjoy OctoPrint, please consider becoming a regular supporter!** You are currently looking at the source code repository of OctoPrint. If you already installed it (e.g. by using the Raspberry Pi targeted distribution [OctoPi](https://github.com/guysoft/OctoPi)) and only -want to find out how to use it, [the documentation](http://docs.octoprint.org/) might be of more interest for you. You might also want to subscribe to join +want to find out how to use it, [the documentation](https://docs.octoprint.org/) might be of more interest for you. You might also want to subscribe to join [the community forum at community.octoprint.org](https://community.octoprint.org) where there are other active users who might be able to help you with any questions you might have. ## Contributing Contributions of all kinds are welcome, not only in the form of code but also with regards to the -[official documentation](http://docs.octoprint.org/), debugging help +[official documentation](https://docs.octoprint.org/), debugging help in the [bug tracker](https://github.com/OctoPrint/OctoPrint/issues), support of other users on [the community forum at community.octoprint.org](https://community.octoprint.org) or [the official discord at discord.octoprint.org](https://discord.octoprint.org) @@ -140,7 +140,7 @@ which is located at `~/.octoprint` on Linux, at `%APPDATA%/OctoPrint` on Windows at `~/Library/Application Support/OctoPrint` on MacOS. A comprehensive overview of all available configuration settings can be found -[in the docs](http://docs.octoprint.org/en/master/configuration/config_yaml.html). +[in the docs](https://docs.octoprint.org/en/master/configuration/config_yaml.html). Please note that the most commonly used configuration settings can also easily be edited from OctoPrint's settings dialog. diff --git a/docs/api/push.rst b/docs/api/push.rst index 5210ad599..a9796b663 100644 --- a/docs/api/push.rst +++ b/docs/api/push.rst @@ -50,7 +50,70 @@ Clients must ignore any unknown messages. The data model of the attached payloads is described further below. -OctoPrint's SockJS socket also accepts two commands from the client to the server. +OctoPrint's SockJS socket also accepts three commands from the client to the server. + + * ``subscribe`` (since 1.8.0): With the ``subscribe`` message, clients may selectively + subscribe to certain message types. The payload should be a dict of message types with + supported keys as follows: + + * ``state``: Either a boolean value indicating whether to generally receive state updates (``current`` and ``history``) + or not, or a dict with further options for received state updates. Currently the following options are recognized here: + + * ``logs``: A boolean value whether to include all log lines (``True``, default) or not (``False``). Alternatively a string with + a regex pattern can be provided, in which case only log lines matching the pattern will be returned. + * ``messages``: Like ``logs`` but for the returned message lines. + + * ``plugins``: Either a boolean value indicating whether to generally receive plugin messages, or a list of plugin + identifiers to receive plugin messages for. + * ``events``: Either a boolean value indicating whether to generally receive event messages, or a list of event + types to receive event messages for. + + If you send a ``subscribe`` message, OctoPrint will default the connection to not subscribe you to anything you did't explicitly + request. ``subscribe`` messages do replace previous ones. + + Example for a ``subscribe`` message subscribing only to updates from plugin ``example`` but neither state nor events: + + .. sourcecode:: javascript + + { + "subscribe": { + "plugins": ["example"] + } + } + + Example for a ``subscribe`` message subscribing to state, event and plugin updates, + but filtering logs in state updates to only contain lines matching ``^Recv: Cap`` and also + filtering out all messages: + + .. sourcecode:: javascript + + { + "subscribe": { + "state": { + "logs": "^Recv: Cap", + "messages": false + }, + "events": true, + "plugins": true + } + } + + Example for a ``subscribe`` message subscribing only to events of type ``PrintFailed``: + + .. sourcecode:: javascript + + { + "subscribe": { + "events": ["PrintFailed"] + } + } + + .. note:: + + Per default, OctoPrint will subscribe connecting clients to all state, event and plugin updates + without any filtering in place. If you wish to have your more selective subscription active + right from the start of your socket session, be sure to send the ``subscribe`` message + **before** the ``auth`` message. * ``auth`` (since 1.3.10): With the ``auth`` message, clients may associate an existing user session with the socket. That is of special importance to receive diff --git a/docs/development/environment.rst b/docs/development/environment.rst index 2e5000959..4234cbed5 100644 --- a/docs/development/environment.rst +++ b/docs/development/environment.rst @@ -134,7 +134,7 @@ Open the Git Bash you just installed and in that: cd /c/Devel git clone https://github.com/OctoPrint/OctoPrint.git cd OctoPrint - virtualenv --python=C:\Python38\python.exe venv + virtualenv --python=C:/Python3/python.exe venv3 source ./venv/Scripts/activate python -m pip install --upgrade pip python -m pip install -e '.[develop,plugins,docs]' @@ -394,7 +394,7 @@ Visual Studio Code (vscode) } ] } - + In the terminal install the python extension by running this command: .. code-block:: bash @@ -414,7 +414,7 @@ Visual Studio Code (vscode) * Your terminal inside vscode uses the virtual python environment * Saving a file will run an auto formatter and import sort - + * ``Ctrl+Shift+B`` can be used to run the ``build docs`` task to rebuild the documentation - + diff --git a/docs/features/accesscontrol.rst b/docs/features/accesscontrol.rst index 62a548768..1c3ee2583 100644 --- a/docs/features/accesscontrol.rst +++ b/docs/features/accesscontrol.rst @@ -184,6 +184,7 @@ further down there's also a dedicated list of steps for OctoPi specifically. autologinAs: "" localNetworks: - "127.0.0.0/8" + - "::1/128" - "" 4. Restart OctoPrint, check that everything works. diff --git a/docs/images/plugins_lifecycle.png b/docs/images/plugins_lifecycle.png deleted file mode 100644 index f0fe1e2d6..000000000 Binary files a/docs/images/plugins_lifecycle.png and /dev/null differ diff --git a/docs/images/plugins_lifecycle.svg b/docs/images/plugins_lifecycle.svg new file mode 100644 index 000000000..785e984e9 --- /dev/null +++ b/docs/images/plugins_lifecycle.svg @@ -0,0 +1,4 @@ + + + +
load
load
disabled
disabled
enabled
enabled
enable
enable
disable
disable
plugin_manager.plugins
plugin_manager.plugins
plugin.disable
deregister hooks
deregister implementation
plugin.implementation.on_plugin_disabled
plugin.disable...
plugin.enable
register hooks
register implementation
plugin.implementation.on_plugin_enabled

If/as soon as framework has started up:
inject dependencies into implementation
plugin.implementation.initialize

plugin.enable...
plugin.load
plugin.load
unload
unload
plugin.unload
plugin.unload
plugin_manager.enabled_plugins
plug...
plugin_manager.disabled_plugins
plug...
Viewer does not support full SVG 1.1
\ No newline at end of file diff --git a/docs/index.rst b/docs/index.rst index cdfa4b217..91643ca58 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -7,7 +7,7 @@ Welcome to OctoPrint's documentation! :align: right OctoPrint provides a snappy web interface for controlling consumer 3D printers. It is Free Software -and released under the `GNU Affero General Public License V3 `_. +and released under the `GNU Affero General Public License V3 `_. Its website can be found at `octoprint.org `_. diff --git a/docs/plugins/concepts.rst b/docs/plugins/concepts.rst index 1be34d43b..4019164dc 100644 --- a/docs/plugins/concepts.rst +++ b/docs/plugins/concepts.rst @@ -52,6 +52,6 @@ regardless of whether the plugin requires a restart of OctoPrint to be fully uni that the Plugin Manager is not the only way to uninstall a plugin from the system, a user may also uninstall it manually through the command line, circumventing Plugin Manager completely. -.. image:: ../images/plugins_lifecycle.png +.. image:: ../images/plugins_lifecycle.svg :align: center :alt: The lifecycle of OctoPrint plugins. diff --git a/setup.py b/setup.py index 39e27cfdf..7bcfe9b3c 100644 --- a/setup.py +++ b/setup.py @@ -52,17 +52,16 @@ INSTALL_REQUIRES = [ "pkginfo>=1.5.0.1,<2", "requests>=2.23.0,<3", "semantic_version>=2.8.5,<3", - "psutil>=5.7,<6", - "Click>=7.1.2,<8", + "psutil>=5.8,<6", + "Click>=8.0.3,<9", "feedparser>=6.0.8,<7", "future>=0.18.2,<1", # not really needed anymore, but leaving in for py2/3 compat plugins - "websocket-client>=0.57,<1", + "websocket-client>=1.2.1,<2", "wrapt>=1.12.1,<2", - "emoji>=0.5.4,<1", - "immutabledict>=2.1,<3", - "sentry-sdk>=0.15.1,<1", + "emoji>=1.4.2,<2", + "sentry-sdk>=1.5.0,<2", "filetype>=1.0.7,<2", - "zeroconf>=0.33,<0.34", + "zeroconf>=0.33,<0.34", # breaking changes can happen on minor version increases "zipstream-ng>=1.3.1,<2.0.0", "pathvalidate>=2.4.1,<3", "colorlog>=5.0.1,<6", @@ -80,7 +79,8 @@ INSTALL_REQUIRES_OSX = [ EXTRA_REQUIRES = { "develop": [ # Testing dependencies - "pytest>=5.4.3,<6", + "mock>=4,<5", + "pytest>=6.2.5,<7", "pytest-doctest-custom>=1.0.0,<2", "ddt", # pre-commit @@ -230,6 +230,8 @@ def params(): "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: JavaScript", "Topic :: Printing", diff --git a/src/octoprint/cli/systeminfo.py b/src/octoprint/cli/systeminfo.py index bb08c31f5..cb5e2d107 100644 --- a/src/octoprint/cli/systeminfo.py +++ b/src/octoprint/cli/systeminfo.py @@ -1,7 +1,8 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" -__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" +__copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License" +import datetime import logging import os @@ -13,7 +14,9 @@ from octoprint.cli import init_platform_for_cli, standard_options click.disable_unicode_literals_warning = True -def get_systeminfo(environment_detector, connectivity_checker, additional_fields=None): +def get_systeminfo( + environment_detector, connectivity_checker, settings, additional_fields=None +): from octoprint import __version__ from octoprint.util import dict_flatten @@ -22,10 +25,30 @@ def get_systeminfo(environment_detector, connectivity_checker, additional_fields environment_detector.run_detection(notify_plugins=False) + safe_mode_file = os.path.join(settings.getBaseFolder("data"), "last_safe_mode") + last_safe_mode = {"date": "unknown", "reason": "unknown"} + try: + if os.path.exists(safe_mode_file): + with open(safe_mode_file) as f: + last_safe_mode["reason"] = f.readline().strip() + last_safe_mode["date"] = ( + datetime.datetime.utcfromtimestamp( + os.path.getmtime(safe_mode_file) + ).isoformat()[:19] + + "Z" + ) + except Exception as ex: + logging.getLogger(__name__).error( + "Error while retrieving last safe mode information from {}: {}".format( + safe_mode_file, ex + ) + ) + systeminfo = { - "octoprint": {"version": __version__}, + "octoprint": {"version": __version__, "last_safe_mode": last_safe_mode}, "connectivity": connectivity_checker.as_dict(), "env": environment_detector.environment, + "systeminfo": {"generated": datetime.datetime.utcnow().isoformat()[:19] + "Z"}, } # flatten and filter diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index 2f66ea43f..979769cc6 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -834,7 +834,7 @@ class PluginManager: processed_blacklist = [] for entry in plugin_blacklist: - if isinstance(entry, tuple): + if isinstance(entry, (tuple, list)): key, version = entry try: processed_blacklist.append( diff --git a/src/octoprint/plugins/appkeys/__init__.py b/src/octoprint/plugins/appkeys/__init__.py index e2b7518dd..270926d94 100644 --- a/src/octoprint/plugins/appkeys/__init__.py +++ b/src/octoprint/plugins/appkeys/__init__.py @@ -7,10 +7,15 @@ import flask from flask_babel import gettext import octoprint.plugin -from octoprint.access import ADMIN_GROUP +from octoprint.access import ADMIN_GROUP, USER_GROUP from octoprint.access.permissions import Permissions from octoprint.server import NO_CONTENT, admin_permission, current_user -from octoprint.server.util.flask import no_firstrun_access, restricted_access +from octoprint.server.util import require_login_with +from octoprint.server.util.flask import ( + add_non_caching_response_headers, + no_firstrun_access, + restricted_access, +) from octoprint.settings import valid_boolean_trues from octoprint.util import ResettableTimer, atomic_write, generate_api_key, yaml @@ -120,7 +125,14 @@ class AppKeysPlugin( "roles": ["admin"], "dangerous": True, "default_groups": [ADMIN_GROUP], - } + }, + { + "key": "GRANT", + "name": "Grant access", + "description": gettext("Allows to grant app access"), + "roles": ["user"], + "default_groups": [USER_GROUP], + }, ] ##~~ TemplatePlugin @@ -164,6 +176,9 @@ class AppKeysPlugin( user_id = data["user"] app_token, user_token = self._add_pending_decision(app_name, user_id=user_id) + auth_dialog = flask.url_for( + "plugin.appkeys.handle_auth_dialog", app_token=app_token, _external=True + ) + (f"?user={user_id}" if user_id else "") self._plugin_manager.send_plugin_message( self._identifier, @@ -174,7 +189,7 @@ class AppKeysPlugin( "user_id": user_id, }, ) - response = flask.jsonify(app_token=app_token) + response = flask.jsonify(app_token=app_token, auth_dialog=auth_dialog) response.status_code = 201 response.headers["Location"] = flask.url_for( ".handle_decision_poll", app_token=app_token, _external=True @@ -199,12 +214,59 @@ class AppKeysPlugin( return flask.abort(404) + @octoprint.plugin.BlueprintPlugin.route("/auth/") + @no_firstrun_access + def handle_auth_dialog(self, app_token): + user_id = current_user.get_name() + required_user = flask.request.args.get("user", None) + + pendings = self._get_pending_by_app_token(app_token) + if not pendings: + return flask.abort(404) + + response = require_login_with( + permissions=[Permissions.PLUGIN_APPKEYS_GRANT], user_id=required_user + ) + if response: + return response + + pending = None + for p in pendings: + if p.user_id == required_user or (not required_user and p.user_id == user_id): + pending = p + break + else: + return flask.abort(404) + + app_id = pending.app_id + user_token = pending.user_token + redirect_url = flask.request.args.get("redirect", "") + + response = flask.make_response( + flask.render_template( + "plugin_appkeys/appkeys_authdialog.jinja2", + app=app_id, + user=user_id, + user_token=user_token, + redirect_url=redirect_url, + theming=[], + request_text=gettext( + '"%(app)s" has requested access to control OctoPrint through the API.' + ).replace("%(app)s", app_id), + ) + ) + return add_non_caching_response_headers(response) + @octoprint.plugin.BlueprintPlugin.route("/decision/", methods=["POST"]) @restricted_access def handle_decision(self, user_token): data = flask.request.json if "decision" not in data: flask.abort(400, description="No decision provided") + + if not Permissions.PLUGIN_APPKEYS_GRANT.can(): + flask.abort(403, description="No permission to grant app access") + decision = data["decision"] in valid_boolean_trues user_id = current_user.get_name() diff --git a/src/octoprint/plugins/appkeys/static/css/authdialog.css b/src/octoprint/plugins/appkeys/static/css/authdialog.css new file mode 100644 index 000000000..0a3363f17 --- /dev/null +++ b/src/octoprint/plugins/appkeys/static/css/authdialog.css @@ -0,0 +1 @@ +body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}#auth-choice,#auth-done,#auth-error,#auth-offline{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,.05);box-shadow:0 1px 2px rgba(0,0,0,.05);text-align:center}.form-auth-heading{margin-bottom:10px} \ No newline at end of file diff --git a/src/octoprint/plugins/appkeys/static/js/authdialog.js b/src/octoprint/plugins/appkeys/static/js/authdialog.js new file mode 100644 index 000000000..25fac9ed0 --- /dev/null +++ b/src/octoprint/plugins/appkeys/static/js/authdialog.js @@ -0,0 +1,91 @@ +/* + * Will get included into the auth dialog, NOT into the regular OctoPrint + * web application. + */ + +$(function () { + var OctoPrint = window.OctoPrint; + + OctoPrint.authui = { + startedUp: false + }; + + var offlineElement = $("#auth-offline"); + var grantButtonElement = $("#auth-grant"); + var rejectButtonElement = $("#auth-reject"); + + var choiceElement = $("#auth-choice"); + var doneElement = $("#auth-done"); + var errorElement = $("#auth-error"); + + var showDone = function () { + choiceElement.hide(); + doneElement.show(); + }; + var showError = function () { + choiceElement.hide(); + errorElement.show(); + }; + var showOffline = function () { + choiceElement.hide(); + offlineElement.show(); + }; + + grantButtonElement.click(function () { + errorElement.removeClass("in"); + + OctoPrint.plugins.appkeys + .decide(USER_TOKEN, true) + .done(function () { + if (REDIRECT_URL) { + window.location.href = REDIRECT_URL; + } else { + showDone(); + } + }) + .fail(showError); + + return false; + }); + rejectButtonElement.click(function () { + OctoPrint.plugins.appkeys + .decide(USER_TOKEN, false) + .done(function () { + if (REDIRECT_URL) { + window.location.href = REDIRECT_URL; + } else { + showDone(); + } + }) + .fail(showError); + + return false; + }); + + OctoPrint.options.baseurl = BASE_URL; + + OctoPrint.socket.onConnected = function () { + OctoPrint.browser.passiveLogin().done(function (login) { + OctoPrint.socket.sendAuth(login.name, login.session); + OctoPrint.authui.startedUp = true; + }); + }; + + OctoPrint.socket.onDisconnected = function () { + showOffline(); + }; + + OctoPrint.socket.onMessage("plugin", function (event) { + if (event.data.plugin !== "appkeys") return; + + var type = event.data.data.type; + if (type !== "end_request") return; + + var token = event.data.data.user_token; + if (token !== USER_TOKEN) return; + + showDone(); + }); + + OctoPrint.socket.connect(); +}); diff --git a/src/octoprint/plugins/appkeys/static/less/authdialog.less b/src/octoprint/plugins/appkeys/static/less/authdialog.less new file mode 100644 index 000000000..4f2fe4eea --- /dev/null +++ b/src/octoprint/plugins/appkeys/static/less/authdialog.less @@ -0,0 +1,27 @@ +body { + padding-top: 40px; + padding-bottom: 40px; + background-color: #f5f5f5; +} + +#auth-choice, +#auth-done, +#auth-error, +#auth-offline { + max-width: 300px; + padding: 19px 29px 29px; + margin: 0 auto 20px; + background-color: #fff; + border: 1px solid #e5e5e5; + -webkit-border-radius: 5px; + -moz-border-radius: 5px; + border-radius: 5px; + -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); + -moz-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); + text-align: center; +} + +.form-auth-heading { + margin-bottom: 10px; +} diff --git a/src/octoprint/plugins/appkeys/templates/appkeys_authdialog.jinja2 b/src/octoprint/plugins/appkeys/templates/appkeys_authdialog.jinja2 new file mode 100644 index 000000000..b043fe74d --- /dev/null +++ b/src/octoprint/plugins/appkeys/templates/appkeys_authdialog.jinja2 @@ -0,0 +1,77 @@ + + + + OctoPrint App Authentication + + + + + + + + + + + + + + + + {% for url in theming %} + + {% endfor %} + + + + + + + + + + {% assets "js_client" %} + + {% endassets %} + + + + +
+
+

{{ _('Access Request') }}

+ +

{% trans %}Hello {{ user }}!{% endtrans %}

+

{{ request_text }}

+

{% trans %} + Do you want to allow access to this application with your user account? + {% endtrans %}

+ + + +
+ +
+

{% trans %} + The access request has been processed. You may now close this tab. + {% endtrans %}

+
+ +
+

{% trans %} + Something went wrong while processing the access request. You may now close this tab. + {% endtrans %}

+
+ +
+

{% trans %} + The server has gone offline. You may now close this tab. + {% endtrans %}

+
+
+ + diff --git a/src/octoprint/plugins/discovery/__init__.py b/src/octoprint/plugins/discovery/__init__.py index 28d0e5fab..f8b6c4432 100644 --- a/src/octoprint/plugins/discovery/__init__.py +++ b/src/octoprint/plugins/discovery/__init__.py @@ -786,7 +786,7 @@ class DiscoveryPlugin( __plugin_name__ = "Discovery" __plugin_author__ = "Gina Häußge" -__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/discovery.html" +__plugin_url__ = "https://docs.octoprint.org/en/master/bundledplugins/discovery.html" __plugin_description__ = ( "Makes the OctoPrint instance discoverable via Bonjour/Avahi/Zeroconf and uPnP" ) diff --git a/src/octoprint/plugins/gcodeviewer/static/js/viewer/renderer.js b/src/octoprint/plugins/gcodeviewer/static/js/viewer/renderer.js index 3946f17d2..6dfd2a047 100644 --- a/src/octoprint/plugins/gcodeviewer/static/js/viewer/renderer.js +++ b/src/octoprint/plugins/gcodeviewer/static/js/viewer/renderer.js @@ -617,12 +617,19 @@ GCODE.renderer = (function () { ctx.circle(0, 0, 2); ctx.stroke(); - ctx.strokeStyle = renderOptions["colorGrid"]; - ctx.lineWidth = lineWidthFactor; - //~~ grid starting from origin - ctx.beginPath(); + ctx.strokeStyle = renderOptions["colorGrid"]; + var gridline = 0; for (x = 0; x <= maxX; x += gridStep) { + ctx.beginPath(); + if (gridline % 5 === 0) { + // every fifth line, including the center + ctx.lineWidth = 1.5 * lineWidthFactor; + } else { + ctx.lineWidth = lineWidthFactor; + } + gridline += 1; + ctx.moveTo(x, minY); ctx.lineTo(x, maxY); @@ -630,11 +637,20 @@ GCODE.renderer = (function () { ctx.moveTo(-1 * x, minY); ctx.lineTo(-1 * x, maxY); } + ctx.stroke(); } - ctx.stroke(); - ctx.beginPath(); + gridline = 0; for (y = 0; y <= maxY; y += gridStep) { + ctx.beginPath(); + if (gridline % 5 === 0) { + // every fifth line, including the center + ctx.lineWidth = 1.5 * lineWidthFactor; + } else { + ctx.lineWidth = lineWidthFactor; + } + gridline += 1; + ctx.moveTo(minX, y); ctx.lineTo(maxX, y); @@ -642,8 +658,8 @@ GCODE.renderer = (function () { ctx.moveTo(minX, -1 * y); ctx.lineTo(maxX, -1 * y); } + ctx.stroke(); } - ctx.stroke(); }; var drawCircularGrid = function () { diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 627748214..8dc5b1303 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -2121,7 +2121,7 @@ def _register_custom_events(*args, **kwargs): __plugin_name__ = "Plugin Manager" __plugin_author__ = "Gina Häußge" -__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/pluginmanager.html" +__plugin_url__ = "https://docs.octoprint.org/en/master/bundledplugins/pluginmanager.html" __plugin_description__ = "Allows installing and managing OctoPrint plugins" __plugin_license__ = "AGPLv3" __plugin_pythoncompat__ = ">=2.7,<4" diff --git a/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css b/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css index 4525678b4..ea8c55eea 100644 --- a/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css +++ b/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css @@ -1 +1 @@ -#settings_plugin_pluginmanager_pluginlist{height:calc(100vh - 450px);display:block;width:auto;overflow-x:hidden;padding-right:2px;margin-bottom:1em;position:relative;border-top:1px solid #eee;padding-top:6px}#settings_plugin_pluginmanager_pluginlist>table{margin-top:0}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name .prop,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name .prop{white-space:nowrap}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_orphanlist{display:block;width:auto;max-height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_id,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_id{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a.disabled,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:400px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty div,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .meta{white-space:nowrap;text-overflow:ellipsis;overflow:hidden}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .stats .prop{white-space:nowrap}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009} \ No newline at end of file +#settings_plugin_pluginmanager_pluginlist{height:calc(100vh - 450px);display:block;width:auto;overflow-x:hidden;padding-right:2px;margin-bottom:1em;position:relative;border-top:1px solid #eee;padding-top:6px}#settings_plugin_pluginmanager_pluginlist>table{margin-top:0}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_checkbox,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_checkbox{text-align:center;width:10px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_checkbox input[type=checkbox],#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_checkbox input[type=checkbox]{margin-top:0}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name .prop,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name .prop{white-space:nowrap}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_orphanlist{display:block;width:auto;max-height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_id,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_id{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a.disabled,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:400px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty div,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .meta{white-space:nowrap;text-overflow:ellipsis;overflow:hidden}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .stats .prop{white-space:nowrap}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009} \ No newline at end of file diff --git a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js index 28f515056..4381e7d4c 100644 --- a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js +++ b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js @@ -58,6 +58,10 @@ $(function () { ], 0 ); + self.plugins.currentFilters.subscribe(function () { + self.clearPluginsSelection(); + }); + self.pluginLookup = {}; self.repositoryplugins = new ItemListHelper( "plugin.pluginmanager.repositoryplugins", @@ -169,6 +173,8 @@ $(function () { 0 ); + self.selectedPlugins = ko.observableArray([]); + self.uploadElement = $("#settings_plugin_pluginmanager_repositorydialog_upload"); self.uploadButton = $( "#settings_plugin_pluginmanager_repositorydialog_upload_start" @@ -274,14 +280,21 @@ $(function () { return !self.printerState.isBusy(); }); - self.enableToggle = function (data) { + self.enableBulk = function (data) { + return self.enableToggle(data, true) && !data.bundled; + }; + + self.enableToggle = function (data, ignoreToggling) { var command = self._getToggleCommand(data); var not_safemode_victim = !data.safe_mode_victim; var not_blacklisted = !data.blacklisted; var not_incompatible = !data.incompatible; + + ignoreToggling = !!ignoreToggling; + return ( self.enableManagement() && - !self.toggling() && + (ignoreToggling || !self.toggling()) && (command === "disable" || (not_safemode_victim && not_blacklisted && not_incompatible)) && data.key !== "pluginmanager" @@ -508,7 +521,9 @@ $(function () { var installedPlugins = []; var noticeCount = 0; + var lookup = {}; _.each(data, function (plugin) { + lookup[plugin.key] = plugin; installedPlugins.push(plugin.key); if (evalNotices && plugin.notifications && plugin.notifications.length) { @@ -537,6 +552,7 @@ $(function () { if (evalNotices) self.noticeCount(noticeCount); self.installedPlugins(installedPlugins); self.plugins.updateItems(data); + self.pluginLookup = lookup; }; self.fromOrphanResponse = function (data) { @@ -802,6 +818,171 @@ $(function () { } }; + self._bulkOperation = function ( + plugins, + title, + message, + successText, + failureText, + statusText, + callback, + alreadyCheck + ) { + var deferred = $.Deferred(); + var promise = deferred.promise(); + var options = { + title: title, + message: _.sprintf(message, {count: plugins.length}), + max: plugins.length, + output: true + }; + showProgressModal(options, promise); + + var handle = function (key) { + var d = $.Deferred(); + + var plugin = self.pluginLookup[key]; + if (!plugin) { + deferred.notify( + _.sprintf( + gettext("Can't resolve plugin with key %(key)s, skipping..."), + {key: key} + ), + false + ); + d.reject(); + return d.promise(); + } + if (!self.enableBulk(plugin)) { + deferred.notify( + _.sprintf( + gettext( + "Plugin %(plugin)s doesn't support bulk operations, skipping..." + ), + {plugin: plugin.name || key} + ), + false + ); + d.reject(); + return d.promise(); + } + if (alreadyCheck(plugin)) { + deferred.notify( + _.sprintf( + gettext( + "Plugin %(plugin)s is already %(status)s (or pending), skipping..." + ), + { + plugin: plugin.name || key, + status: statusText + } + ), + true + ); + d.reject(); + return d.promise(); + } + + callback(plugin) + .done(function () { + deferred.notify( + _.sprintf(successText, {plugin: plugin.name || key}), + true + ); + d.resolve(); + }) + .fail(function () { + deferred.notify( + _.sprintf(failureText, {plugin: plugin.name || key}), + false + ); + d.reject(); + }); + return d.promise(); + }; + + var operations = []; + _.each(plugins, function (key) { + operations.push(handle(key)); + }); + $.when.apply($, _.map(operations, wrapPromiseWithAlways)).done(function () { + deferred.resolve(); + self.requestPluginData(); + }); + return promise; + }; + + self.enableSelectedPlugins = function () { + if (self.selectedPlugins().length === 0) return; + + var callback = function (plugin) { + return OctoPrint.plugins.pluginmanager.enable(plugin.key); + }; + var check = function (plugin) { + return plugin.enabled || plugin.pending_enable; + }; + + self.toggling(true); + self._bulkOperation( + self.selectedPlugins(), + gettext("Enabling plugins"), + gettext("Enabling %(count)i plugins"), + gettext("Enabled plugin %(plugin)s..."), + gettext("Enabling plugin %(plugin)s failed, continuing..."), + gettext("enabled"), + callback, + check + ) + .done(function () { + self.selectedPlugins([]); + }) + .always(function () { + self.toggling(false); + }); + }; + + self.disableSelectedPlugins = function () { + if (self.selectedPlugins().length === 0) return; + + var callback = function (plugin) { + return OctoPrint.plugins.pluginmanager.disable(plugin.key); + }; + var check = function (plugin) { + return !plugin.enabled || plugin.pending_disable; + }; + + self.toggling(true); + self._bulkOperation( + self.selectedPlugins(), + gettext("Disabling plugins"), + gettext("Disabling %(count)i plugins"), + gettext("Disabled plugin %(plugin)s..."), + gettext("Disabling plugin %(plugin)s failed, continuing..."), + gettext("disabled"), + callback, + check + ) + .done(function () { + self.selectedPlugins([]); + }) + .always(function () { + self.toggling(false); + }); + }; + + self.selectAllVisiblePlugins = function () { + var selection = []; + _.each(self.plugins.paginatedItems(), function (plugin) { + if (!self.enableBulk(plugin)) return; + selection.push(plugin.key); + }); + self.selectedPlugins(selection); + }; + + self.clearPluginsSelection = function () { + self.selectedPlugins([]); + }; + self.showRepository = function () { self.repositoryDialog.modal({ minHeight: function () { diff --git a/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less b/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less index 5ddbbc00d..70b30f573 100644 --- a/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less +++ b/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less @@ -19,6 +19,15 @@ table { th, td { + &.settings_plugin_plugin_manager_plugins_checkbox { + text-align: center; + width: 10px; + + input[type="checkbox"] { + margin-top: 0; + } + } + &.settings_plugin_plugin_manager_plugins_name { text-overflow: ellipsis; text-align: left; diff --git a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 index ea2ff3f15..8f536a848 100644 --- a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 +++ b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 @@ -107,6 +107,16 @@
+
@@ -124,12 +134,17 @@ + +
+ {{ _('Name') }} {{ _('Actions') }}
+ +
()
@@ -151,6 +166,7 @@
+ {{ _('Please note that bundled and incompatible plugins do not support bulk operations.') }}
diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index babb42360..cae6e5984 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -33,6 +33,8 @@ from octoprint.util.version import ( get_comparable_version, get_python_version_string, is_python_compatible, + is_released_octoprint_version, + is_stable, ) from . import cli, exceptions, updaters, util, version_checks @@ -60,6 +62,7 @@ class SoftwareUpdatePlugin( COMMIT_TRACKING_TYPES = ("github_commit", "bitbucket_commit") CURRENT_TRACKING_TYPES = COMMIT_TRACKING_TYPES + ("etag", "lastmodified", "jsondata") + RELEASE_TRACKING_TYPES = ("github_release",) OCTOPRINT_RESTART_TYPES = ("pip", "single_file_plugin") @@ -1529,6 +1532,9 @@ class SoftwareUpdatePlugin( if not check: continue + if "type" not in check: + continue + try: populated_check = self._populated_check(target, check) future = executor.submit( @@ -2177,12 +2183,6 @@ class SoftwareUpdatePlugin( result = dict(check) if target == "octoprint": - - from octoprint.util.version import ( - is_released_octoprint_version, - is_stable_octoprint_version, - ) - displayName = check.get("displayName") if displayName is None: # displayName missing or set to None @@ -2195,13 +2195,6 @@ class SoftwareUpdatePlugin( displayVersion = "{octoprint_version}" result["displayVersion"] = to_unicode(displayVersion, errors="replace") - stable_branch = "master" - release_branches = [] - if "stable_branch" in check: - release_branches.append(check["stable_branch"]["branch"]) - stable_branch = check["stable_branch"]["branch"] - if "prerelease_branches" in check: - release_branches += [x["branch"] for x in check["prerelease_branches"]] result["released_version"] = is_released_octoprint_version() if check["type"] in self.COMMIT_TRACKING_TYPES: @@ -2209,39 +2202,6 @@ class SoftwareUpdatePlugin( else: result["current"] = VERSION - if check["type"] == "github_release" and ( - check.get("prerelease", None) or not is_stable_octoprint_version() - ): - # we are tracking github releases and are either also tracking prerelease OR are currently running - # a non stable version => we need to change some parameters - - # we compare versions fully, not just the base so that we see a difference - # between RCs + stable for the same version release - result["force_base"] = False - - if check.get("prerelease", None): - # we are tracking prereleases => we want to be on the correct prerelease channel/branch - channel = check.get("prerelease_channel", None) - if channel: - # if we have a release channel, we also set our update_branch here to our release channel - # in case it's not already set - result["update_branch"] = check.get("update_branch", channel) - - else: - # we are not tracking prereleases, but aren't on the stable branch either => switch back - # to stable branch on update - result["update_branch"] = check.get( - "update_branch", stable_branch - ) - - if check.get("update_script", None): - # we force an exact version & python unequality check, to be able to downgrade - result["force_exact_version"] = True - result["release_compare"] = "python_unequal" - elif check.get("pip", None): - # we force python unequality check for pip installs, to be able to downgrade - result["release_compare"] = "python_unequal" - elif target == "pip": import pkg_resources @@ -2284,6 +2244,43 @@ class SoftwareUpdatePlugin( "current", check.get("displayVersion", None) ) + if ( + check["type"] in self.RELEASE_TRACKING_TYPES + and result["current"] + and (check.get("prerelease", None) or not is_stable(result["current"])) + ): + # we are tracking releases and are either also tracking prerelease OR are currently running + # a non stable version => we need to change some parameters + + # we compare versions fully, not just the base so that we see a difference + # between RCs + stable for the same version release + result["force_base"] = False + + if check["type"] == "github_release": + if check.get("prerelease", None): + # we are tracking prereleases => we want to be on the correct prerelease channel/branch + channel = check.get("prerelease_channel", None) + if channel: + # if we have a release channel, we also set our update_branch here to our release channel + # in case it's not already set + result["update_branch"] = check.get("update_branch", channel) + + else: + # we are not tracking prereleases, but aren't on the stable branch either => switch back + # to stable branch on update + result["update_branch"] = check.get( + "update_branch", + check.get("stable_branch", {"branch": "main"})["branch"], + ) + + if check.get("update_script", None): + # we force an exact version & python unequality check, to be able to downgrade + result["force_exact_version"] = True + result["release_compare"] = "python_unequal" + elif check.get("pip", None): + # we force python unequality check for pip installs, to be able to downgrade + result["release_compare"] = "python_unequal" + if result.get("pip", None): if "pip_command" not in result: local_pip_command = self._settings.global_get( @@ -2408,7 +2405,7 @@ def _register_custom_events(*args, **kwargs): __plugin_name__ = "Software Update" __plugin_author__ = "Gina Häußge" -__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html" +__plugin_url__ = "https://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html" __plugin_description__ = "Allows receiving update notifications and performing updates of OctoPrint and plugins" __plugin_disabling_discouraged__ = gettext( "Without this plugin OctoPrint will no longer be able to " diff --git a/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js b/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js index f812219d7..d98069c23 100644 --- a/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js +++ b/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js @@ -82,6 +82,10 @@ $(function () { }); self.enableUpdateAll = ko.pureComputed(function () { + return self.enableUpdate() && self.availableAndPossible().length > 0; + }); + + self.enableUpdateEnabled = ko.pureComputed(function () { return ( self.enableUpdate() && self.availableAndPossibleAndEnabled().length > 0 ); @@ -370,6 +374,17 @@ $(function () { }); }; + information.notificationIconTitle = function () { + var update = information.updateAvailable + ? gettext("Update available") + : gettext("Up-to-date"); + var notifications = information.disabled + ? gettext("notifications are muted") + : gettext("notifications are enabled"); + + return update + " (" + notifications + ")"; + }; + return information; }; diff --git a/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 b/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 index 3bf2516d5..0e3056f59 100644 --- a/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 +++ b/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 @@ -12,7 +12,7 @@ If you have a local OctoPrint checkout folder switched to another branch, simply switching over to "Commit" tracking will already take care of that. Otherwise please take a look at the - Documentation. + Documentation.

{% endtrans %}
{% trans %} @@ -85,28 +85,31 @@
- - +
+ + + +
+
+ + + +

{{ _('Current versions') }}

-
- -
- {{ _('Last cache refresh:') }} - - -
-
-
- +
- + @@ -126,6 +129,17 @@
+ + = {{ _('Update notifications enabled') }}, + = {{ _('Update notifications muted') }}, + {{ _('click to toggle') }}. + {% trans %} + "Update all" will update all items for which updates are availalbe & + update notifications are enabled as well, "Update all available" will + update all items for which updates are available regardless of update + notifications being enabled or muted. + {% endtrans %} +
diff --git a/src/octoprint/plugins/virtual_printer/__init__.py b/src/octoprint/plugins/virtual_printer/__init__.py index f21185844..3d2b07c0d 100644 --- a/src/octoprint/plugins/virtual_printer/__init__.py +++ b/src/octoprint/plugins/virtual_printer/__init__.py @@ -71,6 +71,8 @@ class VirtualPrinterPlugin( "enable_eeprom": True, "support_M503": True, "resend_ratio": 0, + "locked": False, + "passcode": "1234", } def get_settings_version(self): diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py index 8f5ebb9c5..a4ea78b75 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -165,6 +165,8 @@ class VirtualPrinter: self._capabilities = self._settings.get(["capabilities"], merged=True) + self._locked = self._settings.get_boolean(["locked"]) + self._temperature_reporter = None self._sdstatus_reporter = None self._pos_reporter = None @@ -185,6 +187,7 @@ class VirtualPrinter: self._calculate_resend_every_n(self._settings.get_int(["resend_ratio"])) self._dont_answer = False + self._broken_klipper_connection = False self._debug_drop_connection = False @@ -268,6 +271,7 @@ class VirtualPrinter: self._sleepAfter.clear() self._dont_answer = False + self._broken_klipper_connection = False self._debug_drop_connection = False @@ -294,6 +298,8 @@ class VirtualPrinter: for item in self._settings.get(["resetLines"]): self._send(item + "\n") + self._locked = self._settings.get_boolean(["locked"]) + @property def timeout(self): return self._read_timeout @@ -488,9 +494,19 @@ class VirtualPrinter: # actual command handling command_match = VirtualPrinter.command_regex.match(data) if command_match is not None: + if self._broken_klipper_connection: + self._send("!! Lost communication with MCU 'mcu'") + self._sendOk() + continue + command = command_match.group(0) letter = command_match.group(1) + if self._locked and command != "M511": + self._send("echo:Printer locked! (Unlock with M511 or LCD)") + self._sendOk() + continue + try: # if we have a method _gcode_G, _gcode_M or _gcode_T, execute that first letter_handler = f"_gcode_{letter}" @@ -835,6 +851,22 @@ class VirtualPrinter: else: time.sleep(timeout) + # Passcode Feature - lock with M510, unlock with M511 P. + # https://marlinfw.org/docs/gcode/M510.html / https://marlinfw.org/docs/gcode/M511.html + + def _gcode_M510(self, data): + self._locked = True + + def _gcode_M511(self, data): + if self._locked: + matchP = re.search(r"P([0-9]+)", data) + if matchP: + passcode = matchP.group(1) + if passcode == self._settings.get(["passcode"]): + self._locked = False + else: + self._send("Incorrect passcode") + # EEPROM management commands def _gcode_M500(self, data): @@ -1202,6 +1234,9 @@ class VirtualPrinter: resend_ratio | Sets the resend ratio to the given percentage, simulating noisy lines. | Set to 0 to disable noise simulation. + toggle_klipper_connection + | Toggles the Klipper connection state. If disabled, the printer will + | respond to all commands with "!! Lost communication with MCU 'mcu'" # Reply Timing / Sleeping @@ -1241,6 +1276,8 @@ class VirtualPrinter: self._send("// action:disconnect") elif data == "dont_answer": self._dont_answer = True + elif data == "toggle_klipper_connection": + self._broken_klipper_connection = not self._broken_klipper_connection elif data == "trigger_resend_lineno": self._prepared_errors.append( lambda cur, last, ln: self._triggerResend(expected=last, actual=last + 1) @@ -1380,6 +1417,8 @@ class VirtualPrinter: dosname = get_dos_filename( entry.name, existing_filenames=list(result.keys()) ).lower() + if entry.name.startswith("."): + dosname = "." + dosname result[dosname] = { "name": entry.name, "path": entry.path, diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index a9f5238d3..f47f6abc8 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -12,7 +12,7 @@ import os import threading import time -from immutabledict import immutabledict +from frozendict import frozendict import octoprint.util.json from octoprint import util as util @@ -47,7 +47,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): self._logger_job = logging.getLogger(f"{__name__}.job") self._dict = ( - immutabledict + frozendict if settings().getBoolean(["devel", "useFrozenDictForPrinterState"]) else dict ) @@ -192,7 +192,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): @property def firmware_info(self): - return immutabledict(self._firmware_info) if self._firmware_info else None + return frozendict(self._firmware_info) if self._firmware_info else None # ~~ handling of PrinterCallbacks @@ -819,11 +819,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): return self._comm.getErrorString() def get_current_data(self, *args, **kwargs): - return util.thaw_immutabledict(self._stateMonitor.get_current_data()) + return util.thaw_frozendict(self._stateMonitor.get_current_data()) def get_current_job(self, *args, **kwargs): currentData = self._stateMonitor.get_current_data() - return util.thaw_immutabledict(currentData["job"]) + return util.thaw_frozendict(currentData["job"]) def get_current_temperatures(self, *args, **kwargs): if self._comm is not None: diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 40eb1133e..8a0754604 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -300,6 +300,9 @@ class Server: debug = self._debug safe_mode = self._safe_mode + if safe_mode: + self._log_safe_mode_start(safe_mode) + if self._v6_only and not octoprint.util.net.HAS_V6: raise RuntimeError( "IPv6 only mode configured but system doesn't support IPv6" @@ -334,6 +337,7 @@ class Server: # monkey patch/fix some stuff util.tornado.fix_json_encode() util.tornado.fix_websocket_check_origin() + util.tornado.enable_per_message_deflate_extension() util.flask.fix_flask_jsonify() cli_key = self._setup_cli_key() @@ -1270,6 +1274,16 @@ class Server: ) self._logger.exception("Stacktrace follows:") + def _log_safe_mode_start(self, self_mode): + self_mode_file = os.path.join( + self._settings.getBaseFolder("data"), "last_safe_mode" + ) + try: + with open(self_mode_file, "w+", encoding="utf-8") as f: + f.write(self_mode) + except Exception as ex: + self._logger.warn(f"Could not write safe mode file {self_mode_file}: {ex}") + def _create_socket_connection(self, session): global printer, fileManager, analysisQueue, userManager, eventManager, connectivityChecker return util.sockjs.PrinterStateConnection( diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index 0440021d8..0a44826e5 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -145,6 +145,7 @@ def getSettings(): "keyboardControl": s.getBoolean(["feature", "keyboardControl"]), "pollWatched": s.getBoolean(["feature", "pollWatched"]), "modelSizeDetection": s.getBoolean(["feature", "modelSizeDetection"]), + "rememberFileFolder": s.getBoolean(["feature", "rememberFileFolder"]), "printStartConfirmation": s.getBoolean(["feature", "printStartConfirmation"]), "printCancelConfirmation": s.getBoolean( ["feature", "printCancelConfirmation"] @@ -258,6 +259,7 @@ def getSettings(): "capExtendedM20": s.getBoolean(["serial", "capabilities", "extended_m20"]), "resendRatioThreshold": s.getInt(["serial", "resendRatioThreshold"]), "resendRatioStart": s.getInt(["serial", "resendRatioStart"]), + "ignoreEmptyPorts": s.getBoolean(["serial", "ignoreEmptyPorts"]), }, "folder": { "uploads": s.getBaseFolder("uploads"), @@ -449,9 +451,9 @@ def _saveSettings(data): for folder in FOLDER_TYPES: future[folder] = s.getBaseFolder(folder) if folder in folders: - future[folder] = data["folder"][folder] + future[folder] = folders[folder] - for folder in data["folder"]: + for folder in folders: if folder not in FOLDER_TYPES: continue for other_folder in FOLDER_TYPES: @@ -616,6 +618,11 @@ def _saveSettings(data): s.setBoolean( ["feature", "modelSizeDetection"], data["feature"]["modelSizeDetection"] ) + if "rememberFileFolder" in data["feature"]: + s.setBoolean( + ["feature", "rememberFileFolder"], + data["feature"]["rememberFileFolder"], + ) if "printStartConfirmation" in data["feature"]: s.setBoolean( ["feature", "printStartConfirmation"], @@ -935,6 +942,10 @@ def _saveSettings(data): ) if "resendRatioStart" in data["serial"]: s.setInt(["serial", "resendRatioStart"], data["serial"]["resendRatioStart"]) + if "ignoreEmptyPorts" in data["serial"]: + s.setBoolean( + ["serial", "ignoreEmptyPorts"], data["serial"]["ignoreEmptyPorts"] + ) oldLog = s.getBoolean(["serial", "log"]) if "log" in data["serial"]: diff --git a/src/octoprint/server/api/system.py b/src/octoprint/server/api/system.py index f9ad467f0..3f7180fab 100644 --- a/src/octoprint/server/api/system.py +++ b/src/octoprint/server/api/system.py @@ -44,6 +44,7 @@ def getSystemInfo(): systeminfo = get_systeminfo( environmentDetector, connectivityChecker, + s(), { "browser.user_agent": request.headers.get("User-Agent"), "octoprint.safe_mode": safe_mode is not None, diff --git a/src/octoprint/server/util/__init__.py b/src/octoprint/server/util/__init__.py index 68b6f0812..f3dfcbed3 100644 --- a/src/octoprint/server/util/__init__.py +++ b/src/octoprint/server/util/__init__.py @@ -365,6 +365,43 @@ def has_permissions(*permissions): return all(map(lambda p: p.can(), permissions)) +def require_login_with(permissions=None, user_id=None): + """ + Requires a login with the given permissions and/or user id. + + Args: + permissions: list of all permissions required to pass the check + user_id: required user to pass the check + + Returns: a flask redirect response to return if a login is required, or None + """ + + from octoprint.server import current_user, userManager + + login_kwargs = {"redirect": _flask.request.script_root + _flask.request.full_path} + if ( + _flask.request.headers.get("X-Preemptive-Recording", "no") == "no" + and userManager.has_been_customized() + ): + requires_login = False + + if current_user.is_anonymous: + requires_login = True + + if permissions is not None and not has_permissions(*permissions): + requires_login = True + login_kwargs["permissions"] = ",".join([x.key for x in permissions]) + + if user_id is not None and current_user.get_id() != user_id: + requires_login = True + login_kwargs["user_id"] = user_id + + if requires_login: + return _flask.redirect(_flask.url_for("login", **login_kwargs)) + + return None + + def require_login(*permissions): """ Returns a redirect response to the login view if the permission requirements are diff --git a/src/octoprint/server/util/sockjs.py b/src/octoprint/server/util/sockjs.py index 5fb7663aa..763824862 100644 --- a/src/octoprint/server/util/sockjs.py +++ b/src/octoprint/server/util/sockjs.py @@ -3,6 +3,7 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import logging +import re import threading import time @@ -167,6 +168,10 @@ class PrinterStateConnection( self._registered = False self._authed = False + self._initial_data_sent = False + + self._subscriptions_active = False + self._subscriptions = {"state": False, "plugins": [], "events": []} @staticmethod def _get_remote_address(info): @@ -310,10 +315,77 @@ class PrinterStateConnection( ) ) + elif "subscribe" in message: + if not self._subscriptions_active: + self._subscriptions_active = True + self._logger.debug("Client makes use of subscriptions") + + def list_or_boolean(value): + if isinstance(value, list): + return value + elif isinstance(value, bool): + return [] if not value else None + else: + raise ValueError("value must be a list or boolean") + + def regex_or_boolean(value): + if isinstance(value, str): + try: + return re.compile(value) + except Exception: + raise ValueError("value must be a valid regex") + elif isinstance(value, bool): + return value + else: + raise ValueError("value must be a string or boolean") + + try: + subscribe = message["subscribe"] + + state = subscribe.get("state", False) + if isinstance(state, bool): + if state: + state = {"logs": True, "messages": False} + elif isinstance(state, dict): + logs = regex_or_boolean(state.get("logs", False)) + messages = regex_or_boolean(state.get("messages", False)) + state = { + "logs": logs, + "messages": messages, + } + + plugins = list_or_boolean(subscribe.get("plugins", [])) + events = list_or_boolean(subscribe.get("events", [])) + + except ValueError as e: + self._logger.warning( + "Got invalid subscription message from client {}, ignoring: {!r} ({}) ".format( + self._remoteAddress, message["subscribe"], str(e) + ) + ) + else: + old_state = self._subscriptions["state"] + self._subscriptions["state"] = state + self._subscriptions["plugins"] = plugins + self._subscriptions["events"] = events + + if state and not old_state: + # trigger initial data + self._printer.send_initial_callback(self) + elif old_state and not state: + self._initial_data_sent = False + def on_printer_send_current_data(self, data): if not self._user.has_permission(Permissions.STATUS): return + if self._subscriptions_active and not self._subscriptions["state"]: + return + + if not self._initial_data_sent: + self._logger.debug("Initial data not yet send, dropping current message") + return + # make sure we rate limit the updates according to our throttle factor with self._held_back_mutex: if self._held_back_current is not None: @@ -339,11 +411,11 @@ class PrinterStateConnection( self._temperatureBacklog = [] with self._logBacklogMutex: - logs = self._logBacklog + logs = self._filter_logs(self._logBacklog) self._logBacklog = [] with self._messageBacklogMutex: - messages = self._messageBacklog + messages = self._filter_messages(self._messageBacklog) self._messageBacklog = [] busy_files = [ @@ -370,7 +442,7 @@ class PrinterStateConnection( { "serverTime": time.time(), "temps": temperatures, - "logs": logs, + "logs": self._filter_logs(logs), "messages": messages, "busyFiles": busy_files, } @@ -378,10 +450,32 @@ class PrinterStateConnection( self._emit("current", payload=data) def on_printer_send_initial_data(self, data): + self._initial_data_sent = True + if self._subscriptions_active and not self._subscriptions["state"]: + self._logger.debug("Not subscribed to state, dropping history") + return + data_to_send = dict(data) + data_to_send["logs"] = self._filter_logs(data_to_send.get("logs", [])) + data_to_send["messages"] = self._filter_messages(data_to_send.get("messages", [])) data_to_send["serverTime"] = time.time() self._emit("history", payload=data_to_send) + def _filter_state_subscription(self, sub, values): + if not self._subscriptions_active or self._subscriptions["state"][sub] is True: + return values + + if self._subscriptions["state"][sub] is False: + return [] + + return [line for line in values if self._subscriptions["state"][sub].search(line)] + + def _filter_logs(self, logs): + return self._filter_state_subscription("logs", logs) + + def _filter_messages(self, messages): + return self._filter_state_subscription("messages", messages) + def sendEvent(self, type, payload=None): permissions = self._event_permissions.get(type, self._event_permissions["*"]) permissions = [x(self._user) if callable(x) else x for x in permissions] @@ -420,6 +514,13 @@ class PrinterStateConnection( self._emit("renderProgress", {"progress": progress}) def on_plugin_message(self, plugin, data, permissions=None): + if ( + self._subscriptions_active + and self._subscriptions["plugins"] is not None + and plugin not in self._subscriptions["plugins"] + ): + return + self._emit( "plugin", payload={"plugin": plugin, "data": data}, permissions=permissions ) @@ -470,6 +571,13 @@ class PrinterStateConnection( self._sendReauthRequired("modified") def _onEvent(self, event, payload): + if ( + self._subscriptions_active + and self._subscriptions["events"] is not None + and event not in self._subscriptions["events"] + ): + return + self.sendEvent(event, payload) def _register(self): diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py index 78fe36402..16e35f251 100644 --- a/src/octoprint/server/util/tornado.py +++ b/src/octoprint/server/util/tornado.py @@ -45,6 +45,18 @@ def fix_json_encode(): tornado.escape.json_encode = fixed_json_encode +def enable_per_message_deflate_extension(): + """ + This configures tornado.websocket.WebSocketHandler.get_compression_options to support the permessage-deflate extension + to the websocket protocol, minimizing data bandwidth if clients support the extension as well + """ + + def get_compression_options(self): + return {"compression_level": 1, "mem_level": 1} + + tornado.websocket.WebSocketHandler.get_compression_options = get_compression_options + + def fix_websocket_check_origin(): """ This fixes tornado.websocket.WebSocketHandler.check_origin to do the same origin check against the Host @@ -1560,6 +1572,7 @@ class SystemInfoBundleHandler(CorsSupportMixin, tornado.web.RequestHandler): systeminfo = get_systeminfo( environmentDetector, connectivityChecker, + settings(), { "browser.user_agent": self.request.headers.get("User-Agent"), "octoprint.safe_mode": safe_mode is not None, diff --git a/src/octoprint/server/views.py b/src/octoprint/server/views.py index 974a750a8..2c110318a 100644 --- a/src/octoprint/server/views.py +++ b/src/octoprint/server/views.py @@ -38,7 +38,7 @@ from octoprint.server import ( # noqa: F401 preemptiveCache, userManager, ) -from octoprint.server.util import has_permissions, require_login +from octoprint.server.util import has_permissions, require_login_with from octoprint.settings import settings from octoprint.util import sv, to_bytes, to_unicode from octoprint.util.version import get_python_version_string @@ -184,13 +184,18 @@ def login(): if not permissions: permissions = [Permissions.STATUS, Permissions.SETTINGS_READ] - if has_permissions(*permissions): + user_id = request.args.get("user_id", "") + + if (not user_id or current_user.get_id() == user_id) and has_permissions( + *permissions + ): return redirect(redirect_url) render_kwargs = { "theming": [], "redirect_url": redirect_url, "permission_names": map(lambda x: x.get_name(), permissions), + "user_id": user_id, "logged_in": not current_user.is_anonymous, } @@ -211,7 +216,7 @@ def login(): @app.route("/recovery") @app.route("/recovery/") def recovery(): - response = require_login(Permissions.ADMIN) + response = require_login_with(permissions=[Permissions.ADMIN]) if response: return response @@ -623,7 +628,7 @@ def index(): plugin.implementation, octoprint.plugin.UiPlugin ): permissions = plugin.implementation.get_ui_permissions() - response = require_login(*permissions) + response = require_login_with(permissions=permissions) if not response: response = plugin_view(plugin.implementation) if _logger.isEnabledFor(logging.DEBUG) and isinstance( @@ -633,7 +638,7 @@ def index(): "X-Ui-Plugin" ] = plugin.implementation._identifier else: - response = require_login(*default_permissions) + response = require_login_with(permissions=default_permissions) if not response: response = default_view() if _logger.isEnabledFor(logging.DEBUG) and isinstance(response, Response): @@ -649,7 +654,7 @@ def index(): if plugin.will_handle_ui(request): # plugin claims responsibility, let it render the UI permissions = plugin.get_ui_permissions() - response = require_login(*permissions) + response = require_login_with(permissions=permissions) if not response: response = plugin_view(plugin) if response is not None: @@ -672,7 +677,7 @@ def index(): extra={"plugin": plugin._identifier}, ) else: - response = require_login(*default_permissions) + response = require_login_with(permissions=default_permissions) if not response: response = default_view() if _logger.isEnabledFor(logging.DEBUG) and isinstance(response, Response): diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index dfa40b2cb..35011a31b 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -166,6 +166,7 @@ default_settings = { }, "resendRatioThreshold": 10, "resendRatioStart": 100, + "ignoreEmptyPorts": False, # command specific flags "triggerOkForM29": True, }, @@ -267,6 +268,7 @@ default_settings = { "keyboardControl": True, "pollWatched": False, "modelSizeDetection": True, + "rememberFileFolder": False, "printStartConfirmation": False, "printCancelConfirmation": True, "uploadOverwriteConfirmation": True, diff --git a/src/octoprint/static/js/app/dataupdater.js b/src/octoprint/static/js/app/dataupdater.js index 8eb42ca73..526645385 100644 --- a/src/octoprint/static/js/app/dataupdater.js +++ b/src/octoprint/static/js/app/dataupdater.js @@ -344,6 +344,7 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) { hide: false }); } else if (type === "Error" && payload.error) { + severity = "error"; switch (payload.reason) { case "firmware": { title = gettext("Error reported by printer"); @@ -388,7 +389,13 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) { break; } case "autodetect": { - // ignore + title = gettext("Could not autodetect your printer"); + text = _.sprintf( + gettext( + 'No working connection parameters could be found. Are you sure your printer is physically connected and supported? Refer to the FAQ for help in debugging this.' + ), + {url: "https://faq.octoprint.org/connection-error"} + ); break; } default: { @@ -410,7 +417,7 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) { self._printerErrorDisconnectNotification = new PNotify({ title: title, text: text, - type: "error", + type: severity, hide: false }); } diff --git a/src/octoprint/static/js/app/helpers.js b/src/octoprint/static/js/app/helpers.js index 4ce150ac0..2d031df41 100644 --- a/src/octoprint/static/js/app/helpers.js +++ b/src/octoprint/static/js/app/helpers.js @@ -56,9 +56,10 @@ function ItemListHelper( for (var i = 0; i < itemList.length; i++) { if (matcher(itemList[i])) { self.selectedItem(itemList[i]); - break; + return true; } } + return false; }; self.selectNone = function () { diff --git a/src/octoprint/static/js/app/viewmodels/connection.js b/src/octoprint/static/js/app/viewmodels/connection.js index e85f29f45..d9885cbad 100644 --- a/src/octoprint/static/js/app/viewmodels/connection.js +++ b/src/octoprint/static/js/app/viewmodels/connection.js @@ -38,11 +38,38 @@ $(function () { self.isReady = ko.observable(undefined); self.isLoading = ko.observable(undefined); + self.enableConnect = ko.pureComputed(function () { + return self.enablePort() || !self.isErrorOrClosed(); + }); + self.buttonText = ko.pureComputed(function () { if (self.isErrorOrClosed()) return gettext("Connect"); else return gettext("Disconnect"); }); + self.portCaption = ko.pureComputed(function () { + return self.validPort() ? "AUTO" : gettext("No serial port found"); + }); + + self.validPort = ko.pureComputed(function () { + return ( + self.portOptions().length > 0 || + self.settings.settings.serial.ignoreEmptyPorts() + ); + }); + + self.enablePort = ko.pureComputed(function () { + return self.validPort() && self.isErrorOrClosed(); + }); + + self.enableSaveSettings = ko.pureComputed(function () { + return self.enableConnect() && self.isErrorOrClosed(); + }); + + self.enableAutoConnect = ko.pureComputed(function () { + return self.enableConnect() && self.isErrorOrClosed(); + }); + self.previousIsOperational = undefined; self.refreshVisible = ko.observable(true); diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js index c97bfddde..10d268c70 100644 --- a/src/octoprint/static/js/app/viewmodels/files.js +++ b/src/octoprint/static/js/app/viewmodels/files.js @@ -117,7 +117,27 @@ $(function () { self.uploadFilename = ko.observable(undefined); self.allItems = ko.observable(undefined); + + var optionsLocalStorageKey = "gcodeFiles.options"; + self._toLocalStorage = function () { + saveToLocalStorage(optionsLocalStorageKey, {currentPath: self.currentPath()}); + }; + + self._fromLocalStorage = function () { + var data = loadFromLocalStorage(optionsLocalStorageKey); + if ( + data["currentPath"] !== undefined && + self.settingsViewModel.feature_rememberFileFolder() + ) { + self.currentPath(data["currentPath"]); + } + }; + self.currentPath = ko.observable(""); + self.currentPath.subscribe(function () { + self._toLocalStorage(); + }); + self.uploadProgressText = ko.observable(); self.uploadProgressPercentage = ko.observable(); @@ -232,6 +252,7 @@ $(function () { listHelperExclusiveFilters, 0 ); + self.selectedFile = undefined; self.availableFiletypes = ko.pureComputed(function () { var mapping = { @@ -311,34 +332,47 @@ $(function () { ); }); - self.printerState.filepath.subscribe(function (newValue) { - self.highlightFilename(newValue); - }); - - self.highlightCurrentFilename = function () { - self.highlightFilename(self.printerState.filepath()); + self.highlightCurrentFile = function () { + self.highlightFile(self.selectedFile); }; - self.highlightFilename = function (filename) { - if (filename === undefined || filename === null) { + self.highlightFile = function (file) { + if (!file || !file.origin || !file.path) { + self.listHelper.selectNone(); + return; + } + + var result = self.listHelper.selectItem(function (item) { + if (item.origin !== file.origin) return false; + + if (item.type === "folder") { + return _.startsWith(file.path, item.path + "/"); + } else { + return item.path === file.path; + } + }); + if (!result) { + if (log.getLevel() <= log.levels.DEBUG) { + log.info( + "Couldn't find file " + + file.origin + + ":" + + file.path + + " in current items, not selecting" + ); + } self.listHelper.selectNone(); - } else { - self.listHelper.selectItem(function (item) { - if (item.type === "folder") { - return _.startsWith(filename, item.path + "/"); - } else { - return item.path === filename; - } - }); } }; self.fromCurrentData = function (data) { self._processStateData(data.state); + self._processJobData(data.job); }; self.fromHistoryData = function (data) { self._processStateData(data.state); + self._processJobData(data.job); }; self._processStateData = function (data) { @@ -352,6 +386,21 @@ $(function () { self.isSdReady(data.flags.sdReady); }; + self._processJobData = function (data) { + if (!data) return; + + if ( + self.selectedFile && + self.file && + self.selectedFile.origin === data.file.origin && + self.selectedFile.path === data.file.path + ) + return; + + self.selectedFile = data.file; + self.highlightFile(data.file); + }; + self._otherRequestInProgress = undefined; self._focus = undefined; self._switchToPath = undefined; @@ -512,7 +561,7 @@ $(function () { self.totalSpace(response.total); } - self.highlightCurrentFilename(); + self.highlightCurrentFile(); }; self.changeFolder = function (data) { @@ -525,7 +574,7 @@ $(function () { self.currentPath(data.path); self.listHelper.updateItems(data.children); - self.highlightCurrentFilename(); + self.highlightCurrentFile(); }; self.navigateUp = function () { @@ -543,7 +592,7 @@ $(function () { self.currentPath(""); self.listHelper.updateItems(self.allItems()); } - self.highlightCurrentFilename(); + self.highlightCurrentFile(); }; self.showAddFolderDialog = function () { @@ -652,7 +701,9 @@ $(function () { if ( printAfterLoad && - self.listHelper.isSelected(data) && + self.listHelper.isSelectedByMatcher(function (item) { + return item && item.origin === data.origin && item.path === data.path; + }) && self.enablePrint(data) ) { // file was already selected, just start the print job @@ -1248,6 +1299,7 @@ $(function () { self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () { self.updateButtons(); self.requestData(); + self._fromLocalStorage(); }; self.onStartup = function () { diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js index 290a43873..d555982d4 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -173,6 +173,7 @@ $(function () { self.feature_keyboardControl = ko.observable(undefined); self.feature_pollWatched = ko.observable(undefined); self.feature_modelSizeDetection = ko.observable(undefined); + self.feature_rememberFileFolder = ko.observable(undefined); self.feature_printStartConfirmation = ko.observable(undefined); self.feature_printCancelConfirmation = ko.observable(undefined); self.feature_uploadOverwriteConfirmation = ko.observable(undefined); diff --git a/src/octoprint/static/js/login/login.js b/src/octoprint/static/js/login/login.js index afc60e873..61a881723 100644 --- a/src/octoprint/static/js/login/login.js +++ b/src/octoprint/static/js/login/login.js @@ -37,9 +37,14 @@ $(function () { window.location.href = REDIRECT_URL; }) .fail(function () { - usernameElement.val(""); + usernameElement.val(USER_ID); passwordElement.val(""); - usernameElement.focus(); + + if (USER_ID) { + passwordElement.focus(); + } else { + usernameElement.focus(); + } overlayElement.removeClass("in"); errorElement.addClass("in"); diff --git a/src/octoprint/templates/dialogs/about/about.jinja2 b/src/octoprint/templates/dialogs/about/about.jinja2 index 4097650ea..062eedaf3 100644 --- a/src/octoprint/templates/dialogs/about/about.jinja2 +++ b/src/octoprint/templates/dialogs/about/about.jinja2 @@ -9,7 +9,7 @@
  • Community Forum: community.octoprint.org
  • Discord Server: discord.octoprint.org
  • FAQ: faq.octoprint.org
  • -
  • Documentation: docs.octoprint.org
  • +
  • Documentation: docs.octoprint.org
  • Source Code: github.com/OctoPrint/OctoPrint
  • Changelog: github.com/OctoPrint/OctoPrint/releases
  • Financial Support: support.octoprint.org
  • diff --git a/src/octoprint/templates/dialogs/about/systeminfo.jinja2 b/src/octoprint/templates/dialogs/about/systeminfo.jinja2 index 9eb51ad74..d13a7e210 100644 --- a/src/octoprint/templates/dialogs/about/systeminfo.jinja2 +++ b/src/octoprint/templates/dialogs/about/systeminfo.jinja2 @@ -1,11 +1,14 @@

    {{ _('System Information') }}

    -

    {% trans %}Please always share a Systeminfo Bundle when requesting support on the forums or - when opening a new bug report:{% endtrans %}

    +

    {% trans %}Sharing a Systeminfo Bundle when requesting support on the forums or + when opening a new bug report is mandatory!{% endtrans %}

    + +

    {% trans %}Download the bundle and share as provided. Do not rename, unpack, + repack or otherwise modify, provide exactly as downloaded.{% endtrans %}

    {{ _('Download Systeminfo Bundle') }}

    -

    {% trans %}You can view Systeminfo Bundles at bundleviewer.octoprint.org{% endtrans %}

    +

    {% trans %}You can view Systeminfo Bundles at bundleviewer.octoprint.org{% endtrans %}

    @@ -13,7 +16,5 @@

    :

    - - {{ _('Copy') }}
    diff --git a/src/octoprint/templates/dialogs/settings/features.jinja2 b/src/octoprint/templates/dialogs/settings/features.jinja2 index 6d979da65..38fb3e49e 100644 --- a/src/octoprint/templates/dialogs/settings/features.jinja2 +++ b/src/octoprint/templates/dialogs/settings/features.jinja2 @@ -14,6 +14,13 @@
    +
    +
    + +
    +