From 28ecef207e740a90892e58cee7f41e196f196b99 Mon Sep 17 00:00:00 2001 From: Joe Martella Date: Sat, 27 Feb 2021 06:29:13 +0000 Subject: [PATCH 01/43] Changes default sorting of plugin manager to "popularity" --- src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js index b0a72ccfe..2e0a29cec 100644 --- a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js +++ b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js @@ -50,7 +50,7 @@ $(function () { return !item.enabled; } }, - "name", + "popularity", [], [ ["bundled", "3rdparty"], From f5d21618d1040eeec72f618d415168a7d6a41b4e Mon Sep 17 00:00:00 2001 From: Joe Martella Date: Sat, 27 Feb 2021 06:31:32 +0000 Subject: [PATCH 02/43] Adds myself to AUTHORS.md --- AUTHORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/AUTHORS.md b/AUTHORS.md index c996bc1a4..fae1ed362 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -138,6 +138,7 @@ date of first contribution): * [Nils Hofmann](https://github.com/Master92) * [Miroslav Šedivý](https://github.com/eumiro) * [Costas Basdekis](https://github.com/costas-basdekis) + * [Joe Martella](https://github.com/martellaj) 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 From d6e1868569e454619db3adf895e860704c19c60f Mon Sep 17 00:00:00 2001 From: k Date: Sun, 28 Feb 2021 12:29:37 -0600 Subject: [PATCH 03/43] minor fix for M117 with no args --- src/octoprint/plugins/virtual_printer/virtual.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py index 9497d0100..62b8011c7 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -745,7 +745,10 @@ class VirtualPrinter(object): # type: (str) -> None # we'll just use this to echo a message, to allow playing around with pause triggers if self._echoOnM117: - self._send("echo:%s" % re.search(r"M117\s+(.*)", data).group(1)) + try: + self._send("echo:%s" % re.search(r"M117\s+(.*)", data).group(1)) + except AttributeError: + self._send("echo:") def _gcode_M155(self, data): # type: (str) -> None From 00f11bc5811d72bdcb91497b7729dbb9c8b427f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 2 Mar 2021 14:08:56 +0100 Subject: [PATCH 04/43] =?UTF-8?q?=E2=9E=96=20Remove=20rsa=20dependency?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Leftover, should have gotten kicked for 1.4.0 already. --- setup.py | 1 - 1 file changed, 1 deletion(-) diff --git a/setup.py b/setup.py index b7917d6f1..db02066ba 100644 --- a/setup.py +++ b/setup.py @@ -32,7 +32,6 @@ INSTALL_REQUIRES = [ "markupsafe>=1.1,<2.0", # Jinja dependency, newer versions require Python 3 "tornado==5.1.1", # newer versions require Python 3 "markdown>=3.1,<3.2", # newer versions require Python 3 - "rsa==4.0", # newer versions require Python 3 "regex!=2018.11.6", # avoid broken 2018.11.6. See #2874 # anything below this should be checked on releases for new versions "flask>=1.1.2,<2", From ffea45ce5499a267a3b717df3c2030cd2d2ae7cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 3 Mar 2021 12:37:54 +0100 Subject: [PATCH 05/43] =?UTF-8?q?=F0=9F=90=9B=20Fix=20ETag=20header=20form?= =?UTF-8?q?at?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Better fix for the problem targeted by #4029. Huge thanks to @encetamasb for the heads-up! --- src/octoprint/server/util/tornado.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py index 05ac4754a..bc2327db9 100644 --- a/src/octoprint/server/util/tornado.py +++ b/src/octoprint/server/util/tornado.py @@ -1200,9 +1200,13 @@ class LargeResponseHandler( def compute_etag(self): if self._etag_generator is not None: - return self._etag_generator(self) + etag = self._etag_generator(self) else: - return self.get_content_version(self.absolute_path) + etag = str(self.get_content_version(self.absolute_path)) + + if not etag.endswith('"'): + etag = '"{}"'.format(etag) + return etag # noinspection PyAttributeOutsideInit def get_content_type(self): From 4c4570e2e168acedd91c67a68c1ba5e7748d5830 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 4 Mar 2021 12:49:13 +0100 Subject: [PATCH 06/43] =?UTF-8?q?=F0=9F=90=9B=20GCode=20analysis=20&=20vie?= =?UTF-8?q?wer:=20Assume=20bed=20at=20Z=200.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit People might not actually always have a home command in their GCODE files, so let's just depend on the so far pretty universal truth that printers have a bed at z=0 and that is just always the lowest Z of a printed object. And just in case, let's make this value configurable because the printer gods only know what some people might come up with in terms of experimental printer mechanics that end up with negative z coordinates or a bed at z=100. Closes #4036 --- src/octoprint/cli/analysis.py | 3 ++ src/octoprint/filemanager/analysis.py | 2 + .../gcodeviewer/static/js/gcodeviewer.js | 3 +- .../gcodeviewer/static/js/viewer/reader.js | 16 ++++---- .../gcodeviewer/static/js/viewer/ui.js | 3 +- .../gcodeviewer/static/js/viewer/worker.js | 1 + src/octoprint/server/api/settings.py | 7 +++- src/octoprint/settings.py | 1 + src/octoprint/util/gcodeInterpreter.py | 40 +++++++++++++++---- 9 files changed, 58 insertions(+), 18 deletions(-) diff --git a/src/octoprint/cli/analysis.py b/src/octoprint/cli/analysis.py index 98155753a..bf40b53b4 100644 --- a/src/octoprint/cli/analysis.py +++ b/src/octoprint/cli/analysis.py @@ -69,6 +69,7 @@ def util(): @click.option("--offset", "offset", type=(float, float), multiple=True) @click.option("--max-t", "maxt", type=int, default=10) @click.option("--g90-extruder", "g90_extruder", is_flag=True) +@click.option("--bed-z", "bedz", type=float, default=0) @click.option("--progress", "progress", is_flag=True) @click.argument("path", type=click.Path()) def gcode_command( @@ -81,6 +82,7 @@ def gcode_command( throttle, throttle_lines, g90_extruder, + bedz, progress, ): """Runs a GCODE file analysis.""" @@ -127,6 +129,7 @@ def gcode_command( throttle=throttle_callback, max_extruders=maxt, g90_extruder=g90_extruder, + bed_z=bedz, ) click.echo("DONE:{}s".format(monotonic_time() - start_time)) diff --git a/src/octoprint/filemanager/analysis.py b/src/octoprint/filemanager/analysis.py index 5b62230ca..e0923e7c5 100644 --- a/src/octoprint/filemanager/analysis.py +++ b/src/octoprint/filemanager/analysis.py @@ -419,6 +419,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"]) max_extruders = settings().getInt(["gcodeAnalysis", "maxExtruders"]) g90_extruder = settings().getBoolean(["feature", "g90InfluencesExtruder"]) + bed_z = settings().getFloat(["gcodeAnalysis", "bedZ"]) speedx = self._current.printer_profile["axes"]["x"]["speed"] speedy = self._current.printer_profile["axes"]["y"]["speed"] offsets = self._current.printer_profile["extruder"]["offsets"] @@ -434,6 +435,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): "--max-t={}".format(max_extruders), "--throttle={}".format(throttle), "--throttle-lines={}".format(throttle_lines), + "--bed-z={}".format(bed_z), ] for offset in offsets[1:]: command += ["--offset", str(offset[0]), str(offset[1])] diff --git a/src/octoprint/plugins/gcodeviewer/static/js/gcodeviewer.js b/src/octoprint/plugins/gcodeviewer/static/js/gcodeviewer.js index 5f194574a..9986b0b8a 100644 --- a/src/octoprint/plugins/gcodeviewer/static/js/gcodeviewer.js +++ b/src/octoprint/plugins/gcodeviewer/static/js/gcodeviewer.js @@ -365,7 +365,8 @@ $(function () { onLayerSelected: self._onLayerSelected, bed: self._retrieveBedDimensions(), toolOffsets: self._retrieveToolOffsets(), - invertAxes: self._retrieveAxesConfiguration() + invertAxes: self._retrieveAxesConfiguration(), + bedZ: self.settings.settings.gcodeAnalysis.bedZ() }); if (!initResult) { diff --git a/src/octoprint/plugins/gcodeviewer/static/js/viewer/reader.js b/src/octoprint/plugins/gcodeviewer/static/js/viewer/reader.js index 48dd4e49c..507976f8a 100644 --- a/src/octoprint/plugins/gcodeviewer/static/js/viewer/reader.js +++ b/src/octoprint/plugins/gcodeviewer/static/js/viewer/reader.js @@ -39,7 +39,8 @@ GCODE.gCodeReader = (function () { centeredOrigin: undefined }, ignoreOutsideBed: false, - g90InfluencesExtruder: false + g90InfluencesExtruder: false, + bedZ: 0 }; var percentageTree = undefined; @@ -166,7 +167,8 @@ GCODE.gCodeReader = (function () { toolOffsets: gCodeOptions["toolOffsets"], bed: gCodeOptions["bed"], ignoreOutsideBed: gCodeOptions["ignoreOutsideBed"], - g90InfluencesExtruder: gCodeOptions["g90InfluencesExtruder"] + g90InfluencesExtruder: gCodeOptions["g90InfluencesExtruder"], + bedZ: gCodeOptions["bedZ"] } } }); @@ -174,11 +176,11 @@ GCODE.gCodeReader = (function () { setOption: function (options) { var dirty = false; - for (var opt in options) { - if (options[opt] === undefined) continue; - dirty = dirty || gCodeOptions[opt] != options[opt]; - gCodeOptions[opt] = options[opt]; - } + _.forOwn(options, function (value, key) { + if (value === undefined) return; + dirty = dirty || gCodeOptions[key] !== value; + gCodeOptions[key] = value; + }); if (dirty) { if (model && model.length > 0) this.passDataToRenderer(); } diff --git a/src/octoprint/plugins/gcodeviewer/static/js/viewer/ui.js b/src/octoprint/plugins/gcodeviewer/static/js/viewer/ui.js index e8c3863ee..50e1410b5 100644 --- a/src/octoprint/plugins/gcodeviewer/static/js/viewer/ui.js +++ b/src/octoprint/plugins/gcodeviewer/static/js/viewer/ui.js @@ -156,7 +156,8 @@ GCODE.ui = (function () { }); GCODE.gCodeReader.setOption({ toolOffsets: options.toolOffsets, - bed: options.bed + bed: options.bed, + bedZ: options.bedZ }); GCODE.renderer.render(0, 0); diff --git a/src/octoprint/plugins/gcodeviewer/static/js/viewer/worker.js b/src/octoprint/plugins/gcodeviewer/static/js/viewer/worker.js index 350102285..b75b7f15e 100644 --- a/src/octoprint/plugins/gcodeviewer/static/js/viewer/worker.js +++ b/src/octoprint/plugins/gcodeviewer/static/js/viewer/worker.js @@ -715,6 +715,7 @@ var parseGCode = function (message) { bed = message.options.bed; ignoreOutsideBed = message.options.ignoreOutsideBed; g90InfluencesExtruder = message.options.g90InfluencesExtruder; + boundingBox.minZ = min.z = message.options.bedZ; doParse(); gcode = []; diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index 7c80590a2..11ebe6c6f 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -153,7 +153,10 @@ def getSettings(): "g90InfluencesExtruder": s.getBoolean(["feature", "g90InfluencesExtruder"]), "autoUppercaseBlacklist": s.get(["feature", "autoUppercaseBlacklist"]), }, - "gcodeAnalysis": {"runAt": s.get(["gcodeAnalysis", "runAt"])}, + "gcodeAnalysis": { + "runAt": s.get(["gcodeAnalysis", "runAt"]), + "bedZ": s.getFloat(["gcodeAnalysis", "bedZ"]), + }, "serial": { "port": connectionOptions["portPreference"], "baudrate": connectionOptions["baudratePreference"], @@ -614,6 +617,8 @@ def _saveSettings(data): if "gcodeAnalysis" in data: if "runAt" in data["gcodeAnalysis"]: s.set(["gcodeAnalysis", "runAt"], data["gcodeAnalysis"]["runAt"]) + if "bedZ" in data["gcodeAnalysis"]: + s.setBoolean(["gcodeAnalysis", "bedZ"], data["gcodeAnalysis"]["bedZ"]) if "serial" in data: if "autoconnect" in data["serial"]: diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 73a7fc3e4..103c0eb4a 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -270,6 +270,7 @@ default_settings = { "throttle_highprio": 0.0, "throttle_lines": 100, "runAt": "idle", # 'never', 'idle', 'always' + "bedZ": 0.0, }, "feature": { "temperatureGraph": True, diff --git a/src/octoprint/util/gcodeInterpreter.py b/src/octoprint/util/gcodeInterpreter.py index 2f076f23a..34f1520f8 100644 --- a/src/octoprint/util/gcodeInterpreter.py +++ b/src/octoprint/util/gcodeInterpreter.py @@ -146,11 +146,33 @@ class MinMax3D(object): >>> empty = MinMax3D() >>> empty.size == Vector3D(0.0, 0.0, 0.0) True + >>> weird = MinMax3D(min_z=-1.0) + >>> weird.record(Vector3D(2.0, 2.0, 2.0)) + >>> weird.record(Vector3D(1.0, 2.0, 3.0)) + >>> weird.min.z == -1.0 + True + >>> weird.size == Vector3D(1.0, 0.0, 4.0) + True """ - def __init__(self): - self.min = Vector3D(float("inf"), float("inf"), float("inf")) - self.max = Vector3D(-float("inf"), -float("inf"), -float("inf")) + def __init__( + self, + min_x=None, + min_y=None, + min_z=None, + max_x=None, + max_y=None, + max_z=None, + ): + min_x = min_x if min_x is not None else float("inf") + min_y = min_y if min_y is not None else float("inf") + min_z = min_z if min_z is not None else float("inf") + max_x = max_x if max_x is not None else -float("inf") + max_y = max_y if max_y is not None else -float("inf") + max_z = max_z if max_z is not None else -float("inf") + + self.min = Vector3D(min_x, min_y, min_z) + self.max = Vector3D(max_x, max_y, max_z) def record(self, coordinate): """ @@ -227,7 +249,9 @@ class gcode(object): offsets=None, max_extruders=10, g90_extruder=False, + bed_z=0.0, ): + self._minMax.min.z = bed_z if os.path.isfile(filename): self.filename = filename self._fileSize = os.stat(filename).st_size @@ -448,17 +472,17 @@ class gcode(object): x = getCodeFloat(line, "X") y = getCodeFloat(line, "Y") z = getCodeFloat(line, "Z") - center = Vector3D(0.0, 0.0, 0.0) + origin = Vector3D(0.0, 0.0, 0.0) if x is None and y is None and z is None: - pos = center + pos = origin else: pos = Vector3D(pos) if x is not None: - pos.x = center.x + pos.x = origin.x if y is not None: - pos.y = center.y + pos.y = origin.y if z is not None: - pos.z = center.z + pos.z = origin.z elif gcode == "G90": # Absolute position relativeMode = False if g90_extruder: From e79c41abf9db7e5b443c74b560266b7c4df9b2a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 4 Mar 2021 12:53:47 +0100 Subject: [PATCH 07/43] =?UTF-8?q?=F0=9F=90=9B=20acn:=20fix=20wrong=20local?= =?UTF-8?q?=20storage=20identifier?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../static/js/action_command_notification.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/plugins/action_command_notification/static/js/action_command_notification.js b/src/octoprint/plugins/action_command_notification/static/js/action_command_notification.js index c9f092d75..6574cad0e 100644 --- a/src/octoprint/plugins/action_command_notification/static/js/action_command_notification.js +++ b/src/octoprint/plugins/action_command_notification/static/js/action_command_notification.js @@ -85,7 +85,7 @@ $(function () { } }; - var optionsLocalStorageKey = "core.gcodeviewer.options"; + var optionsLocalStorageKey = "plugin.action_command_notification.options"; self._toLocalStorage = function () { saveToLocalStorage(optionsLocalStorageKey, {sortDesc: self.sortDesc()}); }; From 25cf5379318807e3a88ded674870087924654cd7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 4 Mar 2021 12:54:19 +0100 Subject: [PATCH 08/43] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20gcv:=20Better=20iden?= =?UTF-8?q?itifiers=20in=20settings=20dialog?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../templates/gcodeviewer_settings.jinja2 | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/octoprint/plugins/gcodeviewer/templates/gcodeviewer_settings.jinja2 b/src/octoprint/plugins/gcodeviewer/templates/gcodeviewer_settings.jinja2 index 1520023a1..1ba49d79b 100644 --- a/src/octoprint/plugins/gcodeviewer/templates/gcodeviewer_settings.jinja2 +++ b/src/octoprint/plugins/gcodeviewer/templates/gcodeviewer_settings.jinja2 @@ -1,9 +1,9 @@
- +
- +
{{ _('on desktop')}}
@@ -19,12 +19,10 @@
-
- -
- -
+
+
+ {% trans %}If provided, the GCode Viewer will search for a line beginning with this string. If found, all GCode up to that point will be skipped. This can be used to skip "purge/nozzle wipe" GCode in the viewer. Note the search is case sensitive. Example: ; layer 1{% endtrans %} From 084625fe7cc9a908f4732059fa02937414d7f68b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 4 Mar 2021 18:37:30 +0100 Subject: [PATCH 09/43] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20pmgr:=20Split=20API?= =?UTF-8?q?=20endpoint?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit api/plugin/pluginmanager has been deprecated in favor of plugin/pluginmanager/plugins, plugin/pluginmanager/orphans and plugin/pluginmanager/repository. Additionally, there's now plugin/pluginmanager/plugin/ to retrieve info for a specific plugin by its identifier. Repository and orphans are only fetched on opening of the Settings dialog, plugins and notifications on login with required permissions. All list endpoints make use of ETag headers. The former simple API endpoint api/plugin/pluginmanager has been left in the code for now but marked as deprecated. Same goes for the clientJS API. Implements #4035 --- .../plugins/pluginmanager/__init__.py | 261 ++++++++++++------ .../static/clientjs/pluginmanager.js | 32 +++ .../pluginmanager/static/js/pluginmanager.js | 192 ++++++++----- .../templates/pluginmanager_settings.jinja2 | 2 +- 4 files changed, 345 insertions(+), 142 deletions(-) diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index cdf71ff15..6c6d6f59c 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -21,7 +21,7 @@ import filetype import pkg_resources import requests import sarge -from flask import jsonify, make_response +from flask import Response, abort, jsonify, make_response, request from flask_babel import gettext from past.builtins import basestring @@ -30,13 +30,14 @@ import octoprint.plugin.core from octoprint.access import ADMIN_GROUP from octoprint.access.permissions import Permissions from octoprint.events import Events +from octoprint.server import safe_mode from octoprint.server.util.flask import ( check_etag, no_firstrun_access, with_revalidation_checking, ) from octoprint.settings import valid_boolean_trues -from octoprint.util import TemporaryDirectory, to_bytes, to_native_str +from octoprint.util import TemporaryDirectory, deprecated, to_bytes, to_native_str from octoprint.util.net import download_file from octoprint.util.pip import create_pip_caller from octoprint.util.platform import get_os, is_os_compatible @@ -427,16 +428,159 @@ class PluginManagerPlugin( def export_plugin_list(self): import json - import flask - plugins = self.generate_plugins_json(self._settings, self._plugin_manager) - return flask.Response( + return Response( json.dumps(plugins), mimetype="text/plain", headers={"Content-Disposition": 'attachment; filename="plugin_list.json"'}, ) + def _plugin_response(self): + return { + "plugins": self._get_plugins(), + "os": get_os(), + "octoprint": get_octoprint_version_string(), + "pip": { + "available": self._pip_caller.available, + "version": self._pip_caller.version_string, + "install_dir": self._pip_caller.install_dir, + "use_user": self._pip_caller.use_user, + "virtual_env": self._pip_caller.virtual_env, + "additional_args": self._settings.get(["pip_args"]), + "python": sys.executable, + }, + "safe_mode": safe_mode, + "online": self._connectivity_checker.online, + } + + @octoprint.plugin.BlueprintPlugin.route("/plugins") + @Permissions.PLUGIN_PLUGINMANAGER_MANAGE.require(403) + def retrieve_plugins(self): + refresh = request.values.get("refresh", "false") in valid_boolean_trues + if refresh or not self._is_notices_cache_valid(): + self._notices_available = self._refresh_notices() + + def view(): + return jsonify(**self._plugin_response()) + + def etag(): + import hashlib + + hash = hashlib.sha1() + + def hash_update(value): + value = value.encode("utf-8") + hash.update(value) + + hash_update(repr(self._get_plugins())) + hash_update(str(self._notices_available)) + hash_update(repr(self._notices)) + hash_update(repr(safe_mode)) + hash_update(repr(self._connectivity_checker.online)) + hash_update(repr(_DATA_FORMAT_VERSION)) + return hash.hexdigest() + + def condition(): + return check_etag(etag()) + + return with_revalidation_checking( + etag_factory=lambda *args, **kwargs: etag(), + condition=lambda *args, **kwargs: condition(), + unless=lambda: refresh, + )(view)() + + @octoprint.plugin.BlueprintPlugin.route("/plugins/") + @Permissions.PLUGIN_PLUGINMANAGER_MANAGE.require(403) + def retrieve_specific_plugin(self, key): + plugin = self._plugin_manager.get_plugin_info(key, require_enabled=False) + if plugin is None: + return abort(404) + + return jsonify(plugin=self._to_external_plugin(plugin)) + + def _orphan_response(self): + return {"orphan_data": self._get_orphans()} + + @octoprint.plugin.BlueprintPlugin.route("/orphans") + @Permissions.PLUGIN_PLUGINMANAGER_MANAGE.require(403) + def retrieve_plugin_orphans(self): + if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can(): + return make_response("Insufficient rights", 403) + + refresh = request.values.get("refresh", "false") in valid_boolean_trues + if refresh: + self._get_orphans(refresh=True) + + def view(): + return jsonify(**self._orphan_response()) + + def etag(): + import hashlib + + hash = hashlib.sha1() + + def hash_update(value): + value = value.encode("utf-8") + hash.update(value) + + hash_update(repr(self._get_orphans())) + hash_update(repr(_DATA_FORMAT_VERSION)) + return hash.hexdigest() + + def condition(): + return check_etag(etag()) + + return with_revalidation_checking( + etag_factory=lambda *args, **kwargs: etag(), + condition=lambda *args, **kwargs: condition(), + unless=lambda: refresh, + )(view)() + + def _repository_response(self): + return { + "repository": { + "available": self._repository_available, + "plugins": self._repository_plugins, + } + } + + @octoprint.plugin.BlueprintPlugin.route("/repository") + @Permissions.PLUGIN_PLUGINMANAGER_MANAGE.require(403) + def retrieve_plugin_repository(self): + if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can(): + return make_response("Insufficient rights", 403) + + refresh = request.values.get("refresh", "false") in valid_boolean_trues + if refresh or not self._is_repository_cache_valid(): + self._repository_available = self._refresh_repository() + + def view(): + return jsonify(**self._repository_response()) + + def etag(): + import hashlib + + hash = hashlib.sha1() + + def hash_update(value): + value = value.encode("utf-8") + hash.update(value) + + hash_update(str(self._repository_available)) + hash_update(repr(self._repository_plugins)) + hash_update(repr(_DATA_FORMAT_VERSION)) + return hash.hexdigest() + + def condition(): + return check_etag(etag()) + + return with_revalidation_checking( + etag_factory=lambda *args, **kwargs: etag(), + condition=lambda *args, **kwargs: condition(), + unless=lambda: refresh, + )(view)() + def is_blueprint_protected(self): return False @@ -466,80 +610,6 @@ class PluginManagerPlugin( "refresh_repository": [], } - def on_api_get(self, request): - if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can(): - return make_response("Insufficient rights", 403) - - from octoprint.server import safe_mode - - refresh_repository = ( - request.values.get("refresh_repository", "false") in valid_boolean_trues - ) - if refresh_repository or not self._is_repository_cache_valid(): - self._repository_available = self._refresh_repository() - - refresh_notices = ( - request.values.get("refresh_notices", "false") in valid_boolean_trues - ) - if refresh_notices or not self._is_notices_cache_valid(): - self._notices_available = self._refresh_notices() - - refresh_orphan = ( - request.values.get("refresh_orphans", "false") in valid_boolean_trues - ) - - def view(): - return jsonify( - plugins=self._get_plugins(), - repository={ - "available": self._repository_available, - "plugins": self._repository_plugins, - }, - orphan_data=self._get_orphans(refresh=refresh_orphan), - os=get_os(), - octoprint=get_octoprint_version_string(), - pip={ - "available": self._pip_caller.available, - "version": self._pip_caller.version_string, - "install_dir": self._pip_caller.install_dir, - "use_user": self._pip_caller.use_user, - "virtual_env": self._pip_caller.virtual_env, - "additional_args": self._settings.get(["pip_args"]), - "python": sys.executable, - }, - safe_mode=safe_mode, - online=self._connectivity_checker.online, - ) - - def etag(): - import hashlib - - hash = hashlib.sha1() - - def hash_update(value): - value = value.encode("utf-8") - hash.update(value) - - hash_update(repr(self._get_plugins())) - hash_update(str(self._repository_available)) - hash_update(repr(self._repository_plugins)) - hash_update(str(self._notices_available)) - hash_update(repr(self._notices)) - hash_update(repr(self._get_orphans())) - hash_update(repr(safe_mode)) - hash_update(repr(self._connectivity_checker.online)) - hash_update(repr(_DATA_FORMAT_VERSION)) - return hash.hexdigest() - - def condition(): - return check_etag(etag()) - - return with_revalidation_checking( - etag_factory=lambda *args, **kwargs: etag(), - condition=lambda *args, **kwargs: condition(), - unless=lambda: refresh_repository or refresh_notices or refresh_orphan, - )(view)() - def on_api_command(self, command, data): if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can(): return make_response("Insufficient rights", 403) @@ -602,6 +672,39 @@ class PluginManagerPlugin( plugin = self._plugin_manager.plugins[plugin_name] return self.command_toggle(plugin, command) + @deprecated( + "Deprecated API endpoint api/plugin/pluginmanager used. " + "Please switch clients to plugin/pluginmanager/*", + since="1.6.0", + ) + def on_api_get(self, r): + if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can(): + return make_response("Insufficient rights", 403) + + refresh_repository = ( + request.values.get("refresh_repository", "false") in valid_boolean_trues + ) + if refresh_repository or not self._is_repository_cache_valid(): + self._repository_available = self._refresh_repository() + + refresh_notices = ( + request.values.get("refresh_notices", "false") in valid_boolean_trues + ) + if refresh_notices or not self._is_notices_cache_valid(): + self._notices_available = self._refresh_notices() + + refresh_orphan = ( + request.values.get("refresh_orphans", "false") in valid_boolean_trues + ) + if refresh_orphan: + self._get_orphans(refresh=True) + + result = {} + result.update(**self._plugin_response()) + result.update(**self._orphan_response()) + result.update(**self._repository_response()) + return jsonify(**result) + # noinspection PyMethodMayBeStatic def _is_archive(self, path): _, ext = os.path.splitext(path) diff --git a/src/octoprint/plugins/pluginmanager/static/clientjs/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/clientjs/pluginmanager.js index 2197e0d45..e240c3fcc 100644 --- a/src/octoprint/plugins/pluginmanager/static/clientjs/pluginmanager.js +++ b/src/octoprint/plugins/pluginmanager/static/clientjs/pluginmanager.js @@ -10,6 +10,10 @@ }; OctoPrintPluginManagerClient.prototype.get = function (refresh, opts) { + console.log( + "Deprecated endpoint OctoPrint.plugin.pluginmanager.get, " + + "please use OctoPrint.plugin.pluginmanager.get*" + ); var refresh_repo, refresh_notices, refresh_orphans; if (_.isPlainObject(refresh)) { refresh_repo = refresh.repo || false; @@ -34,13 +38,41 @@ }; OctoPrintPluginManagerClient.prototype.getWithRefresh = function (opts) { + console.log( + "Deprecated endpoint OctoPrint.plugin.pluginmanager.getWithRefresh, " + + "please use OctoPrint.plugin.pluginmanager.get*" + ); return this.get(true, opts); }; OctoPrintPluginManagerClient.prototype.getWithoutRefresh = function (opts) { + console.log( + "Deprecated endpoint OctoPrint.plugin.pluginmanager.getWithoutRefresh, " + + "please use OctoPrint.plugin.pluginmanager.get*" + ); return this.get(false, opts); }; + OctoPrintPluginManagerClient.prototype.getPlugins = function (refresh, opts) { + var url = this.base.getBlueprintUrl("pluginmanager") + "plugins"; + return this.base.get(url + (refresh ? "?refresh=true" : ""), opts); + }; + + OctoPrintPluginManagerClient.prototype.getPlugin = function (plugin, opts) { + var url = this.base.getBlueprintUrl("pluginmanager") + "plugins/" + plugin; + return this.base.get(url, opts); + }; + + OctoPrintPluginManagerClient.prototype.getOrphans = function (refresh, opts) { + var url = this.base.getBlueprintUrl("pluginmanager") + "orphans"; + return this.base.get(url + (refresh ? "?refresh=true" : ""), opts); + }; + + OctoPrintPluginManagerClient.prototype.getRepository = function (refresh, opts) { + var url = this.base.getBlueprintUrl("pluginmanager") + "repository"; + return this.base.get(url + (refresh ? "?refresh=true" : ""), opts); + }; + OctoPrintPluginManagerClient.prototype.install = function ( pluginUrl, dependencyLinks, diff --git a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js index 2e0a29cec..7d7eba04b 100644 --- a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js +++ b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js @@ -174,7 +174,7 @@ $(function () { "#settings_plugin_pluginmanager_repositorydialog_upload_start" ); - self.repositoryAvailable = ko.observable(false); + self.repositoryAvailable = ko.observable(undefined); self.repositorySearchQuery = ko.observable(); self.repositorySearchQuery.subscribe(function () { @@ -499,17 +499,7 @@ $(function () { return false; }; - self.fromResponse = function (data, options) { - self._fromPluginsResponse(data.plugins, options); - self._fromOrphanResponse(data.orphan_data, options); - self._fromRepositoryResponse(data.repository, options); - self._fromPipResponse(data.pip, options); - - self.safeMode(data.safe_mode || false); - self.online(data.online !== undefined ? data.online : true); - }; - - self._fromPluginsResponse = function (data, options) { + self.fromPluginsResponse = function (data, options) { var evalNotices = options.eval_notices || false; var ignoreNoticeHidden = options.ignore_notice_hidden || false; var ignoreNoticeIgnored = options.ignore_notice_ignored || false; @@ -549,7 +539,7 @@ $(function () { self.plugins.updateItems(data); }; - self._fromOrphanResponse = function (data) { + self.fromOrphanResponse = function (data) { var orphans = []; _.each(data, function (value, key) { orphans.push({ @@ -561,7 +551,7 @@ $(function () { self.orphans.updateItems(orphans); }; - self._fromRepositoryResponse = function (data) { + self.fromRepositoryResponse = function (data) { self.repositoryAvailable(data.available); if (data.available) { self.repositoryplugins.updateItems(data.plugins); @@ -570,7 +560,7 @@ $(function () { } }; - self._fromPipResponse = function (data) { + self.fromPipResponse = function (data) { self.pipAvailable(data.available); if (data.available) { self.pipVersion(data.version); @@ -588,41 +578,23 @@ $(function () { } }; - self.dataDeferred = undefined; - self.requestData = function (options) { + self.dataPluginsDeferred = undefined; + self.requestPluginData = function (options) { if (!_.isPlainObject(options)) { - options = { - refresh_repo: options, - refresh_orphans: false, - refresh_notices: false, - eval_notices: false - }; + options = {}; } - options.refresh_repo = options.refresh_repo || false; - options.refresh_orphans = options.refresh_orphans || false; - options.refresh_notices = options.refresh_notices || false; - options.eval_notices = options.eval_notices || false; - if ( - self.dataDeferred && - self.dataDeferred.state() === "pending" && - !options.refresh_repo && - !options.refresh_orphans && - !options.refresh_notices && - !options.eval_notices + self.dataPluginsDeferred && + self.dataPluginsDeferred.state() === "pending" && + !!!options.refresh ) { - return self.dataDeferred.promise(); + return self.dataPluginsDeferred.promise(); } var deferred = new $.Deferred(); - if ( - !options.refresh_repo && - !options.refresh_orphans && - !options.refresh_notices && - !options.eval_notices - ) { - self.dataDeferred = deferred; + if (!!!options.refresh) { + self.dataPluginsDeferred = deferred; } if ( @@ -635,18 +607,99 @@ $(function () { } OctoPrint.plugins.pluginmanager - .get({ - repo: options.refresh_repo, - notices: options.refresh_notices, - orphans: options.refresh_orphans - }) + .getPlugins(!!options.refresh) .fail(function () { self.requestError(true); deferred.reject(); }) .done(function (data) { self.requestError(false); - self.fromResponse(data, options); + self.fromPluginsResponse(data.plugins, options); + self.fromPipResponse(data.pip); + self.safeMode(data.safe_mode || false); + deferred.resolveWith(data); + }); + + return deferred.promise(); + }; + + self.dataOrphansDeferred = undefined; + self.requestOrphanData = function (options) { + if (!_.isPlainObject(options)) { + options = {}; + } + + if ( + self.dataOrphansDeferred && + self.dataOrphansDeferred.state() === "pending" && + !!!options.refresh + ) { + return self.dataOrphansDeferred.promise(); + } + + var deferred = new $.Deferred(); + if (!!!options.refresh) { + self.dataOrphansDeferred = deferred; + } + + if ( + !self.loginState.hasPermission( + self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE + ) + ) { + deferred.fail(); + return deferred.promise(); + } + + OctoPrint.plugins.pluginmanager + .getOrphans(!!options.refresh) + .fail(function () { + deferred.reject(); + }) + .done(function (data) { + self.fromOrphanResponse(data.orphans); + deferred.resolveWith(data); + }); + + return deferred.promise(); + }; + + self.dataRepositoryDeferred = undefined; + self.requestRepositoryData = function (options) { + if (!_.isPlainObject(options)) { + options = {}; + } + + if ( + self.dataRepositoryDeferred && + self.dataRepositoryDeferred.state() === "pending" && + !!!options.refresh + ) { + return self.dataRepositoryDeferred.promise(); + } + + var deferred = new $.Deferred(); + if (!!!options.refresh) { + self.dataRepositoryDeferred = deferred; + } + + if ( + !self.loginState.hasPermission( + self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE + ) + ) { + deferred.fail(); + return deferred.promise(); + } + + OctoPrint.plugins.pluginmanager + .getRepository(!!options.refresh) + .fail(function () { + deferred.reject(); + }) + .done(function (data) { + self.fromRepositoryResponse(data.repository); + self.online(data.online !== undefined ? data.online : true); deferred.resolveWith(data); }); @@ -669,7 +722,7 @@ $(function () { if (data.key === "pluginmanager") return; var onSuccess = function () { - self.requestData().always(function () { + self.requestPluginData().always(function () { self.toggling(false); }); }, @@ -891,7 +944,7 @@ $(function () { OctoPrint.plugins.pluginmanager .uninstall(data.key, cleanup) .done(function () { - self.requestData(); + self.requestPluginData(); }) .fail(function () { new PNotify({ @@ -947,7 +1000,7 @@ $(function () { OctoPrint.plugins.pluginmanager .cleanup(key) .done(function () { - self.requestData(); + self.requestOrphanData(); }) .fail(function () { new PNotify({ @@ -1019,7 +1072,7 @@ $(function () { ) { return; } - self.requestData({refresh_repo: true}); + self.requestRepositoryData({refresh: true}); }; self.refreshNotices = function () { @@ -1027,8 +1080,8 @@ $(function () { return; } - self.requestData({ - refresh_notices: true, + self.requestPluginData({ + refresh: true, eval_notices: true, ignore_notice_hidden: true, ignore_notice_ignored: true @@ -1040,7 +1093,7 @@ $(function () { return; } - self.requestData({ + self.requestPluginData({ eval_notices: true, ignore_notice_hidden: true, ignore_notice_ignored: true @@ -1098,11 +1151,15 @@ $(function () { self.settingsViewModel.saveData(data, function () { self.configurationDialog.modal("hide"); self._copyConfig(); - self.requestData({ - refresh_repo: true, - refresh_notices: true, + self.requestPluginData({ + refresh: true, eval_notices: true }); + if (self.repositoryAvailable() !== undefined) { + self.requestRepositoryData({ + refresh: true + }); + } }); }; @@ -1601,7 +1658,7 @@ $(function () { if (!self.hiddenNoticeNotifications[key]) return false; return _.any( _.map(self.hiddenNoticeNotifications[key], function (d) { - return date == d; + return date === d; }) ); }; @@ -1656,14 +1713,25 @@ $(function () { self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE ) ) { - self.requestData({eval_notices: true}); + self.requestPluginData({eval_notices: true}); } else { self._resetNotifications(); } }; + self.onSettingsShown = function () { + if ( + self.loginState.hasPermission( + self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE + ) + ) { + self.requestRepositoryData(); + self.requestOrphanData(); + } + }; + self.onEventConnectivityChanged = function (payload) { - self.requestData({eval_notices: true}); + self.requestPluginData({eval_notices: true}); }; self._resetNotifications = function () { @@ -1727,7 +1795,7 @@ $(function () { } self._processPluginManagementResult(data, action, name); - self.requestData(); + self.requestPluginData(); } }; diff --git a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 index 7faddf746..8776ca55f 100644 --- a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 +++ b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 @@ -153,7 +153,7 @@
- +

{{ _('Cleanup') }}

From 33bda8691848b260811bf4cfdfc964277607c210 Mon Sep 17 00:00:00 2001 From: John R Barker Date: Thu, 4 Mar 2021 18:53:32 +0000 Subject: [PATCH 10/43] Contributing.md link to `/issues/new/choose` so people can take advantage of the new issue forms --- CONTRIBUTING.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ba81eaba8..918a339ff 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -51,7 +51,7 @@ into one ticket: One ticket per bug, request, brainstorming thread please. ## How to file a bug report If you encounter an issue with OctoPrint, you are welcome to -[submit a bug report](https://github.com/foosel/OctoPrint/issues/new). +[submit a bug report](https://github.com/OctoPrint/OctoPrint/issues/new/choose). Before you do that for the first time though please take a moment to read the following section *completely* and also follow the instructions in the @@ -126,7 +126,7 @@ there. First of all make sure your use **a descriptive title**. "It doesn't work" and similar unspecific complaints are NOT descriptive titles. -Always fill out the [reporting form](https://github.com/OctoPrint/OctoPrint/issues/new?template=bug_report.yml) **completely** and include as much +Always fill out the [reporting form](https://github.com/OctoPrint/OctoPrint/issues/new/choose) **completely** and include as much information as possible. Provide the same kind and amount of information also when you are just adding on to an @@ -287,6 +287,7 @@ See [the corresponding chapter in the documentation](https://docs.octoprint.org/ * 2020-09-23: Move branch & versioning into development docs * 2020-10-07: Introduce `pre-commit` * 2021-02-04: Issue forms! \o/ + * 2020-03-04: Correct issue forms link ## Footnotes * [1] - If you are wondering why, the problem is that anything that you add From 7f86453f29f4f8538b6b3a49fa2223e053b53a4e Mon Sep 17 00:00:00 2001 From: John R Barker Date: Fri, 5 Mar 2021 12:02:13 +0000 Subject: [PATCH 11/43] Update CONTRIBUTING.md --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 918a339ff..60cd35a81 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -51,7 +51,7 @@ into one ticket: One ticket per bug, request, brainstorming thread please. ## How to file a bug report If you encounter an issue with OctoPrint, you are welcome to -[submit a bug report](https://github.com/OctoPrint/OctoPrint/issues/new/choose). +[submit a bug report](https://github.com/OctoPrint/OctoPrint/issues/new?template=bug_report.yml). Before you do that for the first time though please take a moment to read the following section *completely* and also follow the instructions in the From 2883f7f161a0ac740a13e8dd198c098a048121d5 Mon Sep 17 00:00:00 2001 From: John R Barker Date: Fri, 5 Mar 2021 12:04:20 +0000 Subject: [PATCH 12/43] Update CONTRIBUTING.md --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 60cd35a81..2097ccd8d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -126,7 +126,7 @@ there. First of all make sure your use **a descriptive title**. "It doesn't work" and similar unspecific complaints are NOT descriptive titles. -Always fill out the [reporting form](https://github.com/OctoPrint/OctoPrint/issues/new/choose) **completely** and include as much +Always fill out the [reporting form](https://github.com/OctoPrint/OctoPrint/issues/new?template=bug_report.yml) **completely** and include as much information as possible. Provide the same kind and amount of information also when you are just adding on to an From ab59bd442132681e0e4c11682d712ec2f7c28b15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 9 Mar 2021 11:05:43 +0100 Subject: [PATCH 13/43] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Fix=20a=20deprecatio?= =?UTF-8?q?n=20warning?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #4030 --- src/octoprint/static/js/app/viewmodels/settings.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js index ac9222ce1..ae8074a10 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -770,7 +770,7 @@ $(function () { $(".reload_nonconflicts", self.settingsUpdatedDialog).click(function (e) { e.preventDefault(); self.settingsUpdatedDialog.modal("hide"); - self.requestData(undefined, true); + self.requestData(true); return false; }); @@ -839,14 +839,14 @@ $(function () { self.requestData = function (local) { // handle old parameter format var callback = undefined; - if (arguments.length == 2 || _.isFunction(local)) { + if (arguments.length === 2 || _.isFunction(local)) { var exc = new Error(); log.warn( "The callback parameter of SettingsViewModel.requestData is deprecated, the method now returns a promise, please use that instead. Stacktrace:", exc.stack || exc.stacktrace || "" ); - if (arguments.length == 2) { + if (arguments.length === 2) { callback = arguments[0]; local = arguments[1]; } else { From 47cf12e9f3c8ef951b64ae9fdcbe2365c3674ae0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 9 Mar 2021 12:38:59 +0100 Subject: [PATCH 14/43] =?UTF-8?q?=F0=9F=92=9A=20e2e:=20fix=20pmgr=20endpoi?= =?UTF-8?q?nt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Changed with 084625fe7cc9a908f4732059fa02937414d7f68b --- tests/cypress/util/util.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/cypress/util/util.js b/tests/cypress/util/util.js index 614dd6263..346b5a6dd 100644 --- a/tests/cypress/util/util.js +++ b/tests/cypress/util/util.js @@ -5,7 +5,7 @@ export const prepare_server = () => { cy.route("GET", "/api/settings").as("settings"); cy.route("GET", "/api/files?recursive=true").as("files"); cy.route("GET", "/plugin/softwareupdate/check").as("softwareupdate"); - cy.route("GET", "/api/plugin/pluginmanager").as("pluginmanager"); + cy.route("GET", "/plugin/pluginmanager/plugins").as("pluginmanager"); cy.route("POST", "/api/connection").as("connectionCommand"); cy.route("GET", "/api/connection").as("connectionDetails"); }; From 07c1d53a44c203fd83f7d2fc96b52b3aacadb56d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 9 Mar 2021 14:14:33 +0100 Subject: [PATCH 15/43] =?UTF-8?q?=F0=9F=A5=85=20logging:=20Don't=20manage?= =?UTF-8?q?=20anything=20but=20.log=20files?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit You never know what people might do. --- src/octoprint/plugins/logging/__init__.py | 13 ++++++++++- src/octoprint/server/__init__.py | 27 ++++++++++++++++++----- 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/src/octoprint/plugins/logging/__init__.py b/src/octoprint/plugins/logging/__init__.py index 703d5c8a3..37c91c8c4 100644 --- a/src/octoprint/plugins/logging/__init__.py +++ b/src/octoprint/plugins/logging/__init__.py @@ -19,6 +19,7 @@ from octoprint.access.permissions import Permissions from octoprint.server import NO_CONTENT from octoprint.server.util.flask import no_firstrun_access, redirect_to_tornado from octoprint.settings import settings +from octoprint.util import is_hidden_path try: from os import scandir @@ -88,7 +89,11 @@ class LoggingPlugin( @Permissions.PLUGIN_LOGGING_MANAGE.require(403) def delete_log(self, filename): secure = os.path.join(settings().getBaseFolder("logs"), secure_filename(filename)) - if not os.path.exists(secure): + if ( + not os.path.exists(secure) + or is_hidden_path(secure) + or not filename.endswith(".log") + ): return make_response("File not found: %s" % filename, 404) os.remove(secure) @@ -142,6 +147,12 @@ class LoggingPlugin( files = [] basedir = settings().getBaseFolder("logs", check_writable=False) for entry in scandir(basedir): + if is_hidden_path(entry.path) or not entry.name.endswith(".log"): + continue + + if not entry.is_file(): + continue + files.append( { "name": entry.name, diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index c1adc7451..78e6a1d3a 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -747,10 +747,13 @@ class Server(object): lambda path: not octoprint.util.is_hidden_path(path), status_code=404 ) } + + valid_timelapse = lambda path: not octoprint.util.is_hidden_path( + path + ) and octoprint.timelapse.valid_timelapse(path) timelapse_path_validator = { "path_validation": util.tornado.path_validation_factory( - lambda path: not octoprint.util.is_hidden_path(path) - and octoprint.timelapse.valid_timelapse(path), + valid_timelapse, status_code=404, ) } @@ -761,12 +764,23 @@ class Server(object): status_code=400, ) } + + valid_log = ( + lambda path: not octoprint.util.is_hidden_path(path) + and path.endswith(".log") + and os.path.realpath(os.path.abspath(path)).startswith( + settings().getBaseFolder("logs") + ) + ) + log_path_validator = { + "path_validation": util.tornado.path_validation_factory( + valid_log, + status_code=404, + ) + } logs_path_validator = { "path_validation": util.tornado.path_validation_factory( - lambda path: not octoprint.util.is_hidden_path(path) - and os.path.realpath(os.path.abspath(path)).startswith( - settings().getBaseFolder("logs") - ), + valid_log, status_code=400, ) } @@ -841,6 +855,7 @@ class Server(object): }, download_handler_kwargs, log_permission_validator, + log_path_validator, ), ), # zipped log file bundles From a441e489061b6b22eb1b048dcbc1d7f6fedfcfd0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 9 Mar 2021 14:40:48 +0100 Subject: [PATCH 16/43] =?UTF-8?q?=F0=9F=A5=85=20Don't=20return=20input=20p?= =?UTF-8?q?arams=20in=20error=20messages?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit While we always escape errors in the frontend, other clients or plugins might not and thus this could cause XSS issues. --- src/octoprint/plugins/logging/__init__.py | 2 +- .../plugins/pluginmanager/__init__.py | 4 +- src/octoprint/server/api/__init__.py | 22 +--- src/octoprint/server/api/access.py | 10 +- src/octoprint/server/api/connection.py | 6 +- src/octoprint/server/api/files.py | 122 ++++++------------ src/octoprint/server/api/job.py | 4 +- src/octoprint/server/api/printer.py | 52 ++++---- src/octoprint/server/api/printer_profiles.py | 12 +- src/octoprint/server/api/settings.py | 4 +- src/octoprint/server/api/slicing.py | 18 +-- src/octoprint/server/api/system.py | 8 +- src/octoprint/server/api/timelapse.py | 32 ++--- 13 files changed, 103 insertions(+), 193 deletions(-) diff --git a/src/octoprint/plugins/logging/__init__.py b/src/octoprint/plugins/logging/__init__.py index 37c91c8c4..6ef2e0c1f 100644 --- a/src/octoprint/plugins/logging/__init__.py +++ b/src/octoprint/plugins/logging/__init__.py @@ -94,7 +94,7 @@ class LoggingPlugin( or is_hidden_path(secure) or not filename.endswith(".log") ): - return make_response("File not found: %s" % filename, 404) + return make_response("File not found", 404) os.remove(secure) diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 6c6d6f59c..7a8ec960b 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -646,7 +646,7 @@ class PluginManagerPlugin( elif command == "uninstall": plugin_name = data["plugin"] if plugin_name not in self._plugin_manager.plugins: - return make_response("Unknown plugin: %s" % plugin_name, 404) + return make_response("Unknown plugin", 404) plugin = self._plugin_manager.plugins[plugin_name] return self.command_uninstall(plugin, cleanup=data.get("cleanup", False)) @@ -667,7 +667,7 @@ class PluginManagerPlugin( elif command == "enable" or command == "disable": plugin_name = data["plugin"] if plugin_name not in self._plugin_manager.plugins: - return make_response("Unknown plugin: %s" % plugin_name, 404) + return make_response("Unknown plugin", 404) plugin = self._plugin_manager.plugins[plugin_name] return self.command_toggle(plugin, command) diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index 493af4a9d..feea98729 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -84,9 +84,7 @@ def pluginData(name): if len(api_plugins) > 1: return make_response( - "More than one api provider registered for {name}, can't proceed".format( - name=name - ), + "More than one api provider registered, can't proceed", 500, ) @@ -124,9 +122,7 @@ def pluginCommand(name): if len(api_plugins) > 1: return make_response( - "More than one api provider registered for {name}, can't proceed".format( - name=name - ), + "More than one api provider registered, can't proceed", 500, ) @@ -589,9 +585,7 @@ def _test_url(data): timeout = float(data["timeout"]) except Exception: return make_response( - "{!r} is not a valid value for timeout (must be int or float)".format( - data["timeout"] - ), + "Not a valid value for timeout (must be int or float)", 400, ) @@ -704,9 +698,7 @@ def _test_server(data): try: port = int(data["port"]) except Exception: - return make_response( - "{!r} is not a valid value for port (must be int)".format(data["port"]), 400 - ) + return make_response("Not a valid value for port (must be int)", 400) timeout = 3.05 if "timeout" in data: @@ -714,16 +706,14 @@ def _test_server(data): timeout = float(data["timeout"]) except Exception: return make_response( - "{!r} is not a valid value for timeout (must be int or float)".format( - data["timeout"] - ), + "Not a valid value for timeout (must be int or float)", 400, ) protocol = data.get("protocol", "tcp") if protocol not in ("tcp", "udp"): return make_response( - "{!r} is not a valid value for protocol, must be tcp or udp".format(protocol), + "Not a valid value for protocol, must be tcp or udp", 400, ) diff --git a/src/octoprint/server/api/access.py b/src/octoprint/server/api/access.py index 0090940a0..4ddc9bdc1 100644 --- a/src/octoprint/server/api/access.py +++ b/src/octoprint/server/api/access.py @@ -277,7 +277,7 @@ def change_password_for_user(username): try: userManager.change_user_password(username, data["password"]) except users.UnknownUser: - return make_response(("Unknown user: %s" % username, 404, [])) + return make_response(("Unknown user", 404, [])) return jsonify(SUCCESS) else: @@ -300,7 +300,7 @@ def get_settings_for_user(username): try: return jsonify(userManager.get_all_user_settings(username)) except users.UnknownUser: - return make_response("Unknown user: %s" % username, 404) + return make_response("Unknown user", 404) @api.route("/access/users//settings", methods=["PATCH"]) @@ -328,7 +328,7 @@ def change_settings_for_user(username): userManager.change_user_settings(username, data) return jsonify(SUCCESS) except users.UnknownUser: - return make_response("Unknown user: %s" % username, 404) + return make_response("Unknown user", 404) @api.route("/access/users//apikey", methods=["DELETE"]) @@ -345,7 +345,7 @@ def delete_apikey_for_user(username): try: userManager.delete_api_key(username) except users.UnknownUser: - return make_response(("Unknown user: %s" % username, 404, [])) + return make_response(("Unknown user", 404, [])) return jsonify(SUCCESS) else: return make_response(("Forbidden", 403, [])) @@ -368,7 +368,7 @@ def generate_apikey_for_user(username): try: apikey = userManager.generate_api_key(username) except users.UnknownUser: - return make_response(("Unknown user: %s" % username, 404, [])) + return make_response(("Unknown user", 404, [])) return jsonify({"apikey": apikey}) else: return make_response(("Forbidden", 403, [])) diff --git a/src/octoprint/server/api/connection.py b/src/octoprint/server/api/connection.py index b99da4eed..905302fcd 100644 --- a/src/octoprint/server/api/connection.py +++ b/src/octoprint/server/api/connection.py @@ -49,15 +49,15 @@ def connectionCommand(): if "port" in data: port = data["port"] if port not in connection_options["ports"] and port != "AUTO": - return make_response("Invalid port: %s" % port, 400) + return make_response("Invalid port", 400) if "baudrate" in data: baudrate = data["baudrate"] if baudrate not in connection_options["baudrates"] and baudrate != 0: - return make_response("Invalid baudrate: %d" % baudrate, 400) + return make_response("Invalid baudrate", 400) if "printerProfile" in data: printerProfile = data["printerProfile"] if not printerProfileManager.exists(printerProfile): - return make_response("Invalid printer profile: %s" % printerProfile, 400) + return make_response("Invalid printer profile", 400) if "save" in data and data["save"]: settings().set(["serial", "port"], port) settings().setInt(["serial", "baudrate"], baudrate) diff --git a/src/octoprint/server/api/files.py b/src/octoprint/server/api/files.py index c08699a50..324866159 100644 --- a/src/octoprint/server/api/files.py +++ b/src/octoprint/server/api/files.py @@ -180,7 +180,7 @@ def readGcodeFiles(): ) def readGcodeFilesForOrigin(origin): if origin not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: - return make_response("Unknown origin: %s" % origin, 404) + return make_response("Unknown origin", 404) filter = request.values.get("filter", False) recursive = request.values.get("recursive", "false") in valid_boolean_trues @@ -216,7 +216,7 @@ def readGcodeFilesForOrigin(origin): ) def readGcodeFile(target, filename): if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: - return make_response("Unknown target: %s" % target, 404) + return make_response("Unknown target", 404) recursive = False if "recursive" in request.values: @@ -224,7 +224,7 @@ def readGcodeFile(target, filename): file = _getFileDetails(target, filename, recursive=recursive) if not file: - return make_response("File not found on '%s': %s" % (target, filename), 404) + return make_response("File not found", 404) return jsonify(file) @@ -450,7 +450,7 @@ def uploadGcodeFile(target): ) if input_upload_name in request.values and input_upload_path in request.values: if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: - return make_response("Unknown target: %s" % target, 404) + return make_response("Unknown target", 404) upload = octoprint.filemanager.util.DiskFileWrapper( request.values[input_upload_name], request.values[input_upload_path] @@ -514,9 +514,7 @@ def uploadGcodeFile(target): futureFilename = None if futureFilename is None: - return make_response( - "Can not upload file %s, wrong format?" % upload.filename, 415 - ) + return make_response("Can not upload file, wrong format?", 415) if "path" in request.values and request.values["path"]: # we currently only support uploads to sdcard via local, so first target is local instead of "target" @@ -534,8 +532,7 @@ def uploadGcodeFile(target): if not printer.can_modify_file(futureFullPathInStorage, sd): return make_response( - "Trying to overwrite file that is currently being printed: %s" - % futureFullPath, + "Trying to overwrite file that is currently being printed", 409, ) @@ -595,15 +592,11 @@ def uploadGcodeFile(target): except octoprint.filemanager.storage.StorageError as e: if e.code == octoprint.filemanager.storage.StorageError.INVALID_FILE: return make_response( - 'Could not upload the file "{}", invalid type'.format( - upload.filename - ), + "Could not upload the file, invalid type", 400, ) else: - return make_response( - 'Could not upload the file "{}"'.format(upload.filename), 500 - ) + return make_response("Could not upload the file", 500) if octoprint.filemanager.valid_file_type(added_file, "stl"): filename = added_file @@ -688,7 +681,7 @@ def uploadGcodeFile(target): foldername = request.values["foldername"] if target not in [FileDestinations.LOCAL]: - return make_response("Unknown target: %s" % target, 400) + return make_response("Unknown target", 400) canonPath, canonName = fileManager.canonicalize(target, foldername) futurePath = fileManager.sanitize_path(target, canonPath) @@ -704,7 +697,7 @@ def uploadGcodeFile(target): futureFullPath = fileManager.join_path(target, futurePath, futureName) if octoprint.filemanager.valid_file_type(futureName): return make_response( - "Can't create a folder named %s, please try another name" % futureName, + "Can't create folder, please try another name", 409, ) @@ -714,11 +707,9 @@ def uploadGcodeFile(target): ) except octoprint.filemanager.storage.StorageError as e: if e.code == octoprint.filemanager.storage.StorageError.INVALID_DIRECTORY: - return make_response( - "Could not create folder {}, invalid directory".format(futureName) - ) + return make_response("Could not create folder, invalid directory") else: - return make_response("Could not create folder {}".format(futureName)) + return make_response("Could not create folder") location = url_for( ".readGcodeFile", @@ -745,7 +736,7 @@ def uploadGcodeFile(target): @no_firstrun_access def gcodeFileCommand(filename, target): if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: - return make_response("Unknown target: %s" % target, 404) + return make_response("Invalid target", 400) # valid file commands, dict mapping command name to mandatory parameters valid_commands = { @@ -765,16 +756,12 @@ def gcodeFileCommand(filename, target): if command == "select": with Permissions.FILES_SELECT.require(403): if not _verifyFileExists(target, filename): - return make_response( - "File not found on '%s': %s" % (target, filename), 404 - ) + return make_response("File not found", 404) # selects/loads a file if not octoprint.filemanager.valid_file_type(filename, type="machinecode"): return make_response( - "Cannot select {filename} for printing, not a machinecode file".format( - **locals() - ), + "Cannot select file for printing, not a machinecode file", 415, ) @@ -804,9 +791,7 @@ def gcodeFileCommand(filename, target): elif command == "slice": with Permissions.SLICE.require(403): if not _verifyFileExists(target, filename): - return make_response( - "File not found on '%s': %s" % (target, filename), 404 - ) + return make_response("File not found", 404) try: if "slicer" in data: @@ -820,13 +805,11 @@ def gcodeFileCommand(filename, target): else: return make_response( - "Cannot slice {filename}, no slicer available".format(**locals()), + "Cannot slice file, no slicer available", 415, ) - except octoprint.slicing.UnknownSlicer as e: - return make_response( - "Slicer {slicer} is not available".format(slicer=e.slicer), 400 - ) + except octoprint.slicing.UnknownSlicer: + return make_response("Slicer is not available", 400) if not any( [ @@ -836,9 +819,7 @@ def gcodeFileCommand(filename, target): ) ] ): - return make_response( - "Cannot slice {filename}, not a model file".format(**locals()), 415 - ) + return make_response("Cannot slice file, not a model file", 415) cores = psutil.cpu_count() if ( @@ -848,9 +829,7 @@ def gcodeFileCommand(filename, target): ): # slicer runs on same device as OctoPrint, slicing while printing is hence disabled return make_response( - "Cannot slice on {slicer} while printing on single core systems or systems of unknown core count due to performance reasons".format( - **locals() - ), + "Cannot slice on this slicer while printing on single core systems or systems of unknown core count due to performance reasons", 409, ) @@ -896,8 +875,7 @@ def gcodeFileCommand(filename, target): and (printer.is_printing() or printer.is_paused()) ): make_response( - "Trying to slice into file that is currently being printed: %s" - % full_path, + "Trying to slice into file that is currently being printed", 409, ) @@ -980,11 +958,8 @@ def gcodeFileCommand(filename, target): ), ) except octoprint.slicing.UnknownProfile: - return make_response( - "Profile {profile} doesn't exist".format(**locals()), 400 - ) + return make_response("Profile doesn't exist", 400) - files = {} location = url_for( ".readGcodeFile", target=target, filename=full_path, _external=True ) @@ -1010,9 +985,7 @@ def gcodeFileCommand(filename, target): elif command == "analyse": with Permissions.FILES_UPLOAD.require(403): if not _verifyFileExists(target, filename): - return make_response( - "File not found on '%s': %s" % (target, filename), 404 - ) + return make_response("File not found", 404) printer_profile = None if "printerProfile" in data and data["printerProfile"]: @@ -1021,24 +994,18 @@ def gcodeFileCommand(filename, target): if not fileManager.analyse( target, filename, printer_profile_id=printer_profile ): - return make_response( - "No analysis possible for {} on {}".format(filename, target), 400 - ) + return make_response("No analysis possible", 400) elif command == "copy" or command == "move": with Permissions.FILES_UPLOAD.require(403): # Copy and move are only possible on local storage if target not in [FileDestinations.LOCAL]: - return make_response( - "Unsupported target for {}: {}".format(command, target), 400 - ) + return make_response("Unsupported target for {}".format(command), 400) if not _verifyFileExists(target, filename) and not _verifyFolderExists( target, filename ): - return make_response( - "File or folder not found on {}: {}".format(target, filename), 404 - ) + return make_response("File or folder not found", 404) path, name = fileManager.split_path(target, filename) @@ -1060,9 +1027,7 @@ def gcodeFileCommand(filename, target): target, destination ): return make_response( - "File or folder does already exist on {}: {}".format( - target, destination - ), + "File or folder does already exist", 409, ) @@ -1071,9 +1036,7 @@ def gcodeFileCommand(filename, target): if not (is_file or is_folder): return make_response( - "{} on {} is neither file or folder, can't {}".format( - filename, target, command - ), + "Neither file nor folder, can't {}", 400, ) @@ -1083,9 +1046,7 @@ def gcodeFileCommand(filename, target): target, destination ): return make_response( - "File or folder does already exist on {}: {}".format( - target, destination - ), + "File or folder does already exist", 409, ) @@ -1098,9 +1059,7 @@ def gcodeFileCommand(filename, target): with Permissions.FILES_DELETE.require(403): if _isBusy(target, filename): return make_response( - "Trying to move a file or folder that is currently in use: {}".format( - filename - ), + "Trying to move a file or folder that is currently in use", 409, ) @@ -1110,9 +1069,7 @@ def gcodeFileCommand(filename, target): or _verifyFolderExists(target, destination) ) and sanitized_destination != filename: return make_response( - "File or folder does already exist on {}: {}".format( - target, destination - ), + "File or folder does already exist", 409, ) @@ -1158,18 +1115,14 @@ def deleteGcodeFile(filename, target): if not _verifyFileExists(target, filename) and not _verifyFolderExists( target, filename ): - return make_response( - "File/Folder not found on '%s': %s" % (target, filename), 404 - ) + return make_response("File/folder not found", 404) if _verifyFileExists(target, filename): if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: - return make_response("Unknown target: %s" % target, 400) + return make_response("Unknown target", 400) if _isBusy(target, filename): - return make_response( - "Trying to delete a file that is currently in use: %s" % filename, 409 - ) + return make_response("Trying to delete a file that is currently in use", 409) # deselect the file if it's currently selected currentOrigin, currentPath = _getCurrentFile() @@ -1188,12 +1141,11 @@ def deleteGcodeFile(filename, target): elif _verifyFolderExists(target, filename): if target not in [FileDestinations.LOCAL]: - return make_response("Unknown target: %s" % target, 400) + return make_response("Unknown target", 400) if _isBusy(target, filename): return make_response( - "Trying to delete a folder that contains a file that is currently in use: %s" - % filename, + "Trying to delete a folder that contains a file that is currently in use", 409, ) diff --git a/src/octoprint/server/api/job.py b/src/octoprint/server/api/job.py index afd851642..ce35d9ed5 100644 --- a/src/octoprint/server/api/job.py +++ b/src/octoprint/server/api/job.py @@ -60,9 +60,7 @@ def controlJob(): printer.resume_print(tags=tags, user=user) else: return make_response( - "Unknown action '{}', allowed values for action parameter are 'pause', 'resume' and 'toggle'".format( - action - ), + "Unknown action, allowed values for action parameter are 'pause', 'resume' and 'toggle'", 400, ) elif command == "cancel": diff --git a/src/octoprint/server/api/printer.py b/src/octoprint/server/api/printer.py index 22ef1922f..307fa9e84 100644 --- a/src/octoprint/server/api/printer.py +++ b/src/octoprint/server/api/printer.py @@ -96,9 +96,9 @@ def printerToolCommand(): if command == "select": tool = data["tool"] if not isinstance(tool, basestring) or re.match(validation_regex, tool) is None: - return make_response("Invalid tool: %s" % tool, 400) + return make_response("Invalid tool", 400) if not tool.startswith("tool"): - return make_response("Invalid tool for selection: %s" % tool, 400) + return make_response("Invalid tool for selection", 400) printer.change_tool(tool, tags=tags) @@ -110,11 +110,9 @@ def printerToolCommand(): validated_values = {} for tool, value in targets.items(): if re.match(validation_regex, tool) is None: - return make_response( - "Invalid target for setting temperature: %s" % tool, 400 - ) + return make_response("Invalid target for setting temperature", 400) if not isinstance(value, (int, long, float)): - return make_response("Not a number for %s: %r" % (tool, value), 400) + return make_response("Target is not a number", 400) validated_values[tool] = value # perform the actual temperature commands @@ -129,15 +127,11 @@ def printerToolCommand(): validated_values = {} for tool, value in offsets.items(): if re.match(validation_regex, tool) is None: - return make_response( - "Invalid target for setting temperature: %s" % tool, 400 - ) + return make_response("Invalid target for setting temperature offset", 400) if not isinstance(value, (int, long, float)): - return make_response("Not a number for %s: %r" % (tool, value), 400) + return make_response("Offset is not a number", 400) if not -50 <= value <= 50: - return make_response( - "Offset %s not in range [-50, 50]: %f" % (tool, value), 400 - ) + return make_response("Offset not in range [-50, 50]", 400) validated_values[tool] = value # set the offsets @@ -152,17 +146,17 @@ def printerToolCommand(): amount = data["amount"] speed = data.get("speed", None) if not isinstance(amount, (int, long, float)): - return make_response("Not a number for extrusion amount: %r" % amount, 400) + return make_response("Extrusion amount is not a number", 400) printer.extrude(amount, speed=speed, tags=tags) elif command == "flowrate": factor = data["factor"] if not isinstance(factor, (int, long, float)): - return make_response("Not a number for flow rate: %r" % factor, 400) + return make_response("Flow rate is not a number", 400) try: printer.flow_rate(factor, tags=tags) - except ValueError as e: - return make_response("Invalid value for flow rate: %s" % str(e), 400) + except ValueError: + return make_response("Invalid value for flow rate", 400) return NO_CONTENT @@ -203,7 +197,7 @@ def printerBedCommand(): # make sure the target is a number if not isinstance(target, (int, long, float)): - return make_response("Not a number: %r" % target, 400) + return make_response("Target is not a number", 400) # perform the actual temperature command printer.set_temperature("bed", target, tags=tags) @@ -214,9 +208,9 @@ def printerBedCommand(): # make sure the offset is valid if not isinstance(offset, (int, long, float)): - return make_response("Not a number: %r" % offset, 400) + return make_response("Offset is not a number", 400) if not -50 <= offset <= 50: - return make_response("Offset not in range [-50, 50]: %f" % offset, 400) + return make_response("Offset is not in range [-50, 50]", 400) # set the offsets printer.set_temperature_offset({"bed": offset}) @@ -267,7 +261,7 @@ def printerChamberCommand(): # make sure the target is a number if not isinstance(target, (int, long, float)): - return make_response("Not a number: %r" % target, 400) + return make_response("Target is not a number", 400) # perform the actual temperature command printer.set_temperature("chamber", target, tags=tags) @@ -278,9 +272,9 @@ def printerChamberCommand(): # make sure the offset is valid if not isinstance(offset, (int, long, float)): - return make_response("Not a number: %r" % offset, 400) + return make_response("Offset is not a number", 400) if not -50 <= offset <= 50: - return make_response("Offset not in range [-50, 50]: %f" % offset, 400) + return make_response("Offset is not in range [-50, 50]", 400) # set the offsets printer.set_temperature_offset({"chamber": offset}) @@ -332,9 +326,7 @@ def printerPrintheadCommand(): if axis in data: value = data[axis] if not isinstance(value, (int, long, float)): - return make_response( - "Not a number for axis %s: %r" % (axis, value), 400 - ) + return make_response("Axis value is not a number", 400) validated_values[axis] = value absolute = "absolute" in data and data["absolute"] in valid_boolean_trues @@ -349,7 +341,7 @@ def printerPrintheadCommand(): axes = data["axes"] for axis in axes: if axis not in valid_axes: - return make_response("Invalid axis: %s" % axis, 400) + return make_response("Invalid axis", 400) validated_values.append(axis) # execute the home command @@ -358,11 +350,11 @@ def printerPrintheadCommand(): elif command == "feedrate": factor = data["factor"] if not isinstance(factor, (int, long, float)): - return make_response("Not a number for feed rate: %r" % factor, 400) + return make_response("Feed rate is not a number", 400) try: printer.feed_rate(factor, tags=tags) - except ValueError as e: - return make_response("Invalid value for feed rate: %s" % str(e), 400) + except ValueError: + return make_response("Invalid value for feed rate", 400) return NO_CONTENT diff --git a/src/octoprint/server/api/printer_profiles.py b/src/octoprint/server/api/printer_profiles.py index 887c083ab..cedf7b71f 100644 --- a/src/octoprint/server/api/printer_profiles.py +++ b/src/octoprint/server/api/printer_profiles.py @@ -107,9 +107,7 @@ def printerProfilesAdd(): return make_response("Profile is invalid", 400) except CouldNotOverwriteError: return make_response( - "Profile {} already exists and overwriting was not allowed".format( - profile["id"] - ), + "Profile already exists and overwriting was not allowed", 400, ) except Exception as e: @@ -124,7 +122,7 @@ def printerProfilesAdd(): def printerProfilesGet(identifier): profile = printerProfileManager.get(identifier) if profile is None: - return make_response("Unknown profile: %s" % identifier, 404) + return make_response("Unknown profile", 404) else: return jsonify(_convert_profile(profile)) @@ -135,13 +133,11 @@ def printerProfilesGet(identifier): def printerProfilesDelete(identifier): current_profile = printerProfileManager.get_current() if current_profile and current_profile["id"] == identifier: - return make_response( - "Cannot delete currently selected profile: {}".format(identifier), 409 - ) + return make_response("Cannot delete currently selected profile", 409) default_profile = printerProfileManager.get_default() if default_profile and default_profile["id"] == identifier: - return make_response("Cannot delete default profile: {}".format(identifier), 409) + return make_response("Cannot delete default profile", 409) printerProfileManager.remove(identifier, trigger_event=True) return NO_CONTENT diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index 11ebe6c6f..3dec04a51 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -385,8 +385,8 @@ def setSettings(): if not isinstance(data, dict): return make_response( - "Malformed request, need settings dictionary, " - "got a {} instead: {!r}".format(type(data).__name__, data), + "Malformed request, need settings dictionary" + "got a {} instead".format(type(data).__name__), 400, ) diff --git a/src/octoprint/server/api/slicing.py b/src/octoprint/server/api/slicing.py index 5a4965ed7..94db08035 100644 --- a/src/octoprint/server/api/slicing.py +++ b/src/octoprint/server/api/slicing.py @@ -141,7 +141,7 @@ def slicingListSlicerProfiles(slicer): try: return jsonify(_getSlicingProfilesData(slicer, require_configured=configured)) except (UnknownSlicer, SlicerNotConfigured): - return make_response("Unknown slicer {slicer}".format(**locals()), 404) + return make_response("Unknown slicer", 404) @api.route("/slicing//profiles/", methods=["GET"]) @@ -151,7 +151,7 @@ def slicingGetSlicerProfile(slicer, name): try: profile = slicingManager.load_profile(slicer, name, require_configured=False) except UnknownSlicer: - return make_response("Unknown slicer {slicer}".format(**locals()), 404) + return make_response("Unknown slicer", 404) except UnknownProfile: return make_response("Profile not found", 404) @@ -195,7 +195,7 @@ def slicingAddSlicerProfile(slicer, name): description=description, ) except UnknownSlicer: - return make_response("Unknown slicer {slicer}".format(**locals()), 404) + return make_response("Unknown slicer", 404) result = _getSlicingProfileData(slicer, name, profile) r = make_response(jsonify(result), 201) @@ -213,11 +213,9 @@ def slicingPatchSlicerProfile(slicer, name): try: profile = slicingManager.load_profile(slicer, name, require_configured=False) except UnknownSlicer: - return make_response("Unknown slicer {slicer}".format(**locals()), 404) + return make_response("Unknown slicer", 404) except UnknownProfile: - return make_response( - "Profile {name} for slicer {slicer} not found".format(**locals()), 404 - ) + return make_response("Profile for slicer not found", 404) try: json_data = request.get_json() @@ -262,12 +260,10 @@ def slicingDelSlicerProfile(slicer, name): try: slicingManager.delete_profile(slicer, name) except UnknownSlicer: - return make_response("Unknown slicer {slicer}".format(**locals()), 404) + return make_response("Unknown slicer", 404) except CouldNotDeleteProfile as e: return make_response( - "Could not delete profile {profile} for slicer {slicer}: {cause}".format( - profile=name, slicer=slicer, cause=str(e.cause) - ), + "Could not delete profile for slicer: {cause}".format(cause=str(e.cause)), 500, ) diff --git a/src/octoprint/server/api/system.py b/src/octoprint/server/api/system.py index aaeb190a4..6df204b8a 100644 --- a/src/octoprint/server/api/system.py +++ b/src/octoprint/server/api/system.py @@ -111,7 +111,7 @@ def retrieveSystemCommandsForSource(source): elif source == "custom": specs = _get_custom_command_specs() else: - return make_response("Unknown system command source: {}".format(source), 404) + return make_response("Unknown system command source", 404) return jsonify(_to_client_specs(specs)) @@ -127,13 +127,11 @@ def executeSystemCommand(source, command): command_spec = _get_command_spec(source, command) if not command_spec: - return make_response("Command {}:{} not found".format(source, command), 404) + return make_response("Command not found", 404) if "command" not in command_spec: return make_response( - "Command {}:{} does not define a command to execute, can't proceed".format( - source, command - ), + "Command does not define a command to execute, can't proceed", 500, ) diff --git a/src/octoprint/server/api/timelapse.py b/src/octoprint/server/api/timelapse.py index 247e1246e..80c5f2c28 100644 --- a/src/octoprint/server/api/timelapse.py +++ b/src/octoprint/server/api/timelapse.py @@ -231,68 +231,56 @@ def setTimelapseConfig(): try: postRoll = int(data["postRoll"]) except ValueError: - return make_response( - "Invalid value for postRoll: %r" % data["postRoll"], 400 - ) + return make_response("Invalid value for postRoll", 400) else: if postRoll >= 0: config["postRoll"] = postRoll else: - return make_response("Invalid value for postRoll: %d" % postRoll, 400) + return make_response("Invalid value for postRoll", 400) if "fps" in data: try: fps = int(data["fps"]) except ValueError: - return make_response("Invalid value for fps: %r" % data["fps"], 400) + return make_response("Invalid value for fps", 400) else: if fps > 0: config["fps"] = fps else: - return make_response("Invalid value for fps: %d" % fps, 400) + return make_response("Invalid value for fps", 400) if "interval" in data: try: interval = int(data["interval"]) except ValueError: - return make_response( - "Invalid value for interval: %r" % data["interval"], 400 - ) + return make_response("Invalid value for interval", 400) else: if interval > 0: config["options"]["interval"] = interval else: - return make_response("Invalid value for interval: %d" % interval, 400) + return make_response("Invalid value for interval", 400) if "retractionZHop" in data: try: retractionZHop = float(data["retractionZHop"]) except ValueError: - return make_response( - "Invalid value for retraction Z-Hop: %r" % data["retractionZHop"], 400 - ) + return make_response("Invalid value for retraction z-hop", 400) else: if retractionZHop >= 0: config["options"]["retractionZHop"] = retractionZHop else: - return make_response( - "Invalid value for retraction Z-Hop: %f" % retractionZHop, 400 - ) + return make_response("Invalid value for retraction z-hop", 400) if "minDelay" in data: try: minDelay = float(data["minDelay"]) except ValueError: - return make_response( - "Invalid value for minimum delay: %r" % data["minDelay"], 400 - ) + return make_response("Invalid value for minimum delay", 400) else: if minDelay > 0: config["options"]["minDelay"] = minDelay else: - return make_response( - "Invalid value for minimum delay: %f" % minDelay, 400 - ) + return make_response("Invalid value for minimum delay", 400) if ( admin_permission.can() From 62f03e371fdcb1db434e182a10e67fca28f50351 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 9 Mar 2021 14:47:04 +0100 Subject: [PATCH 17/43] =?UTF-8?q?=F0=9F=A5=85=20Fail=20fast=20on=20invalid?= =?UTF-8?q?=20file=20names?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/server/api/files.py | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/src/octoprint/server/api/files.py b/src/octoprint/server/api/files.py index 324866159..bd3301e57 100644 --- a/src/octoprint/server/api/files.py +++ b/src/octoprint/server/api/files.py @@ -218,6 +218,9 @@ def readGcodeFile(target, filename): if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: return make_response("Unknown target", 404) + if filename != fileManager.sanitize(target, filename): + return make_response("File not found", 404) + recursive = False if "recursive" in request.values: recursive = request.values["recursive"] in valid_boolean_trues @@ -736,7 +739,10 @@ def uploadGcodeFile(target): @no_firstrun_access def gcodeFileCommand(filename, target): if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: - return make_response("Invalid target", 400) + return make_response("Unknown target", 404) + + if filename != fileManager.sanitize(target, filename): + return make_response("File not found", 404) # valid file commands, dict mapping command name to mandatory parameters valid_commands = { @@ -1112,15 +1118,18 @@ def gcodeFileCommand(filename, target): @no_firstrun_access @Permissions.FILES_DELETE.require(403) def deleteGcodeFile(filename, target): + if filename != fileManager.sanitize(target, filename): + return make_response("File not found", 400) + if not _verifyFileExists(target, filename) and not _verifyFolderExists( target, filename ): - return make_response("File/folder not found", 404) + return make_response("File not found", 404) + + if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: + return make_response("Unknown target", 404) if _verifyFileExists(target, filename): - if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: - return make_response("Unknown target", 400) - if _isBusy(target, filename): return make_response("Trying to delete a file that is currently in use", 409) @@ -1140,9 +1149,6 @@ def deleteGcodeFile(filename, target): fileManager.remove_file(target, filename) elif _verifyFolderExists(target, filename): - if target not in [FileDestinations.LOCAL]: - return make_response("Unknown target", 400) - if _isBusy(target, filename): return make_response( "Trying to delete a folder that contains a file that is currently in use", From e66497756a8d699616066621b93c3e4f1a973561 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 9 Mar 2021 16:40:49 +0100 Subject: [PATCH 18/43] =?UTF-8?q?=E2=9C=A8=20logging:=20bulk=20download=20?= =?UTF-8?q?logs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implements #3746 --- .../logging/static/clientjs/logging.js | 6 ++++++ .../plugins/logging/static/js/logging.js | 21 +++++++++++++++++++ .../logging/templates/logging_settings.jinja2 | 1 + 3 files changed, 28 insertions(+) diff --git a/src/octoprint/plugins/logging/static/clientjs/logging.js b/src/octoprint/plugins/logging/static/clientjs/logging.js index bccbfc216..78b739f27 100644 --- a/src/octoprint/plugins/logging/static/clientjs/logging.js +++ b/src/octoprint/plugins/logging/static/clientjs/logging.js @@ -13,6 +13,8 @@ this.setupUrl = this.baseUrl + "setup"; }; + var bulkDownloadUrl = "downloads/logs"; + OctoPrintLoggingClient.prototype.get = function (opts) { return this.base.get(this.baseUrl, opts); }; @@ -31,6 +33,10 @@ return this.base.download(fileUrl, opts); }; + OctoPrintLoggingClient.prototype.bulkDownloadUrl = function (filenames) { + return this.base.bulkDownloadUrl(bulkDownloadUrl, filenames); + }; + OctoPrintLoggingClient.prototype.updateLevels = function (config, opts) { return this.base.putJson(this.setupUrl + "/levels", config, opts); }; diff --git a/src/octoprint/plugins/logging/static/js/logging.js b/src/octoprint/plugins/logging/static/js/logging.js index 53052f376..d403ef0e0 100644 --- a/src/octoprint/plugins/logging/static/js/logging.js +++ b/src/octoprint/plugins/logging/static/js/logging.js @@ -273,6 +273,27 @@ $(function () { ); }; + self.enableBulkDownload = ko.pureComputed(function () { + return self.markedForDeletion().length && !self.bulkDownloadUrlTooLong(); + }); + + self.bulkDownloadUrlTooLong = ko.pureComputed(function () { + return BASEURL.length + self.bulkDownloadUrl().length >= 2000; + }); + + self.bulkDownloadButtonUrl = ko.pureComputed(function () { + var files = self.markedForDeletion(); + if (!files.length || self.bulkDownloadUrlTooLong()) { + return "javascript:void(0)"; + } + return self.bulkDownloadUrl(); + }); + + self.bulkDownloadUrl = function () { + var files = self.markedForDeletion(); + return OctoPrint.plugins.logging.bulkDownloadUrl(files); + }; + self.onServerReconnect = self.onUserLoggedIn = self.onEventSettingsUpdated = self.onSettingsShown = function () { if ( !self.loginState.hasPermission( diff --git a/src/octoprint/plugins/logging/templates/logging_settings.jinja2 b/src/octoprint/plugins/logging/templates/logging_settings.jinja2 index b00b55db5..e19755068 100644 --- a/src/octoprint/plugins/logging/templates/logging_settings.jinja2 +++ b/src/octoprint/plugins/logging/templates/logging_settings.jinja2 @@ -21,6 +21,7 @@
+ {{_('Download selected')}}
From b1596f30d9798078212d8bbe095e044f9b35b43f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 10 Mar 2021 21:37:51 +0100 Subject: [PATCH 19/43] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Use=20flask.abort=20?= =?UTF-8?q?where=20it=20makes=20sense?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit And use a custom error handler to return json error responses on API endpoints. --- src/octoprint/plugin/types.py | 6 +- .../action_command_notification/__init__.py | 2 +- .../plugins/action_command_prompt/__init__.py | 6 +- .../plugins/announcements/__init__.py | 2 +- src/octoprint/plugins/appkeys/__init__.py | 6 +- src/octoprint/plugins/backup/__init__.py | 12 +- src/octoprint/plugins/logging/__init__.py | 10 +- .../plugins/pluginmanager/__init__.py | 46 +++--- .../plugins/softwareupdate/__init__.py | 28 ++-- src/octoprint/server/__init__.py | 14 +- src/octoprint/server/api/__init__.py | 77 +++++----- src/octoprint/server/api/access.py | 90 +++++------ src/octoprint/server/api/connection.py | 8 +- src/octoprint/server/api/files.py | 145 ++++++++---------- src/octoprint/server/api/job.py | 26 ++-- src/octoprint/server/api/languages.py | 11 +- src/octoprint/server/api/printer.py | 106 ++++++------- src/octoprint/server/api/printer_profiles.py | 53 +++---- src/octoprint/server/api/settings.py | 24 +-- src/octoprint/server/api/slicing.py | 43 +++--- src/octoprint/server/api/system.py | 21 ++- src/octoprint/server/api/timelapse.py | 28 ++-- src/octoprint/server/util/__init__.py | 6 +- src/octoprint/server/util/flask.py | 66 +++++--- 24 files changed, 393 insertions(+), 443 deletions(-) diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index c724b9c35..b3db80d55 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -1279,7 +1279,7 @@ class SimpleApiPlugin(OctoPrintPlugin): If your plugin returns nothing here, OctoPrint will return an empty response with return code ``204 No content`` for you. You may also return regular responses as you would return from any Flask view here though, e.g. - ``return flask.jsonify(result="some json result")`` or ``return flask.make_response("Not found", 404)``. + ``return flask.jsonify(result="some json result")`` or ``flask.abort(404)``. :param string command: the command with which the resource was called :param dict data: the full request body of the POST request parsed from JSON into a Python dictionary @@ -1297,7 +1297,7 @@ class SimpleApiPlugin(OctoPrintPlugin): If your plugin returns nothing here, OctoPrint will return an empty response with return code ``204 No content`` for you. You may also return regular responses as you would return from any Flask view here though, e.g. - ``return flask.jsonify(result="some json result")`` or ``return flask.make_response("Not found", 404)``. + ``return flask.jsonify(result="some json result")`` or ``flask.abort(404)``. :param request: the Flask request object :return: ``None`` in which case OctoPrint will generate a ``204 No content`` response with empty body, or optionally @@ -1327,7 +1327,7 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin): @octoprint.plugin.BlueprintPlugin.route("/echo", methods=["GET"]) def myEcho(self): if not "text" in flask.request.values: - return flask.make_response("Expected a text to echo back.", 400) + abort(400, description="Expected a text to echo back.") return flask.request.values["text"] __plugin_implementation__ = MyBlueprintPlugin() diff --git a/src/octoprint/plugins/action_command_notification/__init__.py b/src/octoprint/plugins/action_command_notification/__init__.py index e58007004..1df93cec8 100644 --- a/src/octoprint/plugins/action_command_notification/__init__.py +++ b/src/octoprint/plugins/action_command_notification/__init__.py @@ -69,7 +69,7 @@ class ActionCommandNotificationPlugin( def on_api_get(self, request): if not Permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW.can(): - return flask.abort(403, "Insufficient permissions") + return flask.abort(403) return flask.jsonify( notifications=[ {"timestamp": notification[0], "message": notification[1]} diff --git a/src/octoprint/plugins/action_command_prompt/__init__.py b/src/octoprint/plugins/action_command_prompt/__init__.py index e9cd2e4bb..9a53bc10d 100644 --- a/src/octoprint/plugins/action_command_prompt/__init__.py +++ b/src/octoprint/plugins/action_command_prompt/__init__.py @@ -126,10 +126,10 @@ class ActionCommandPromptPlugin( def on_api_command(self, command, data): if command == "select": if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can(): - return flask.abort(403, "Insufficient permissions") + return flask.abort(403) if self._prompt is None: - return flask.abort(409, "No active prompt") + return flask.abort(409, description="No active prompt") choice = data["choice"] if not isinstance(choice, int) or not self._prompt.validate_choice(choice): @@ -141,7 +141,7 @@ class ActionCommandPromptPlugin( def on_api_get(self, request): if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can(): - return flask.abort(403, "Insufficient permissions") + return flask.abort(403) if self._prompt is None: return flask.jsonify() else: diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py index 7c320d4b8..86465af02 100644 --- a/src/octoprint/plugins/announcements/__init__.py +++ b/src/octoprint/plugins/announcements/__init__.py @@ -289,7 +289,7 @@ class AnnouncementPlugin( elif command == "toggle": if not Permissions.PLUGIN_ANNOUNCEMENTS_MANAGE.can(): - return flask.make_response("Insufficient rights", 403) + flask.abort(403) self._toggle(channel) return NO_CONTENT diff --git a/src/octoprint/plugins/appkeys/__init__.py b/src/octoprint/plugins/appkeys/__init__.py index 855ac50b5..326b95f18 100644 --- a/src/octoprint/plugins/appkeys/__init__.py +++ b/src/octoprint/plugins/appkeys/__init__.py @@ -157,10 +157,10 @@ class AppKeysPlugin( def handle_request(self): data = flask.request.json if data is None: - return flask.make_response("Missing key request", 400) + flask.abort(400, description="Missing key request") if "app" not in data: - return flask.make_response("No app name provided", 400) + flask.abort(400, description="No app name provided") app_name = data["app"] user_id = None @@ -208,7 +208,7 @@ class AppKeysPlugin( def handle_decision(self, user_token): data = flask.request.json if "decision" not in data: - return flask.make_response("No decision provided", 400) + flask.abort(400, description="No decision provided") decision = data["decision"] in valid_boolean_trues user_id = current_user.get_name() diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index 9e204d223..3094a8688 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -203,12 +203,13 @@ class BackupPlugin( if not Permissions.PLUGIN_BACKUP_ACCESS.can() and not self._settings.global_get( ["server", "firstRun"] ): - return flask.abort(403) + flask.abort(403) if not self._restore_supported(self._settings): - return flask.make_response( - "Invalid request, the restores are not supported on the underlying operating system", + flask.abort( 400, + description="Invalid request, the restores are not " + "supported on the underlying operating system", ) input_name = "file" @@ -236,9 +237,10 @@ class BackupPlugin( return flask.abort(404) else: - return flask.make_response( - "Invalid request, neither a file nor a path of a file to restore provided", + flask.abort( 400, + description="Invalid request, neither a file nor a path of a file to " + "restore provided", ) def on_install_plugins(plugins): diff --git a/src/octoprint/plugins/logging/__init__.py b/src/octoprint/plugins/logging/__init__.py index 6ef2e0c1f..3e8728ca4 100644 --- a/src/octoprint/plugins/logging/__init__.py +++ b/src/octoprint/plugins/logging/__init__.py @@ -8,7 +8,7 @@ import io import os import yaml -from flask import jsonify, make_response, request, url_for +from flask import abort, jsonify, request, url_for from flask_babel import gettext from werkzeug.exceptions import BadRequest from werkzeug.utils import secure_filename @@ -94,7 +94,7 @@ class LoggingPlugin( or is_hidden_path(secure) or not filename.endswith(".log") ): - return make_response("File not found", 404) + abort(404) os.remove(secure) @@ -119,15 +119,15 @@ class LoggingPlugin( @Permissions.PLUGIN_LOGGING_MANAGE.require(403) def set_logging_levels_api(self): if "application/json" not in request.headers["Content-Type"]: - return make_response("Expected content-type JSON", 400) + abort(400, description="Expected content-type JSON") try: json_data = request.json except BadRequest: - return make_response("Malformed JSON body in request", 400) + abort(400, description="Malformed JSON body in request") if not isinstance(json_data, dict): - return make_response("Invalid log level configuration", 400) + abort(400, description="Invalid log level configuration") # TODO validate further diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 7a8ec960b..9a6ad46a4 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -21,7 +21,7 @@ import filetype import pkg_resources import requests import sarge -from flask import Response, abort, jsonify, make_response, request +from flask import Response, abort, jsonify, request from flask_babel import gettext from past.builtins import basestring @@ -367,7 +367,7 @@ class PluginManagerPlugin( input_upload_path not in flask.request.values or input_upload_name not in flask.request.values ): - return flask.make_response("No file included", 400) + abort(400, description="No file included") upload_path = flask.request.values[input_upload_path] upload_name = flask.request.values[input_upload_name] @@ -378,9 +378,9 @@ class PluginManagerPlugin( ) ) if not len(exts): - return flask.make_response( - "File doesn't have a valid extension for a plugin archive or a single file plugin", + abort( 400, + description="File doesn't have a valid extension for a plugin archive or a single file plugin", ) ext = exts[0] @@ -407,7 +407,7 @@ class PluginManagerPlugin( with self._install_lock: if self._install_task is not None: - return make_response("There's already a plugin being installed", 409) + abort(409, description="There's already a plugin being installed") self._install_task = threading.Thread( target=perform_install, @@ -506,7 +506,7 @@ class PluginManagerPlugin( @Permissions.PLUGIN_PLUGINMANAGER_MANAGE.require(403) def retrieve_plugin_orphans(self): if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can(): - return make_response("Insufficient rights", 403) + abort(403) refresh = request.values.get("refresh", "false") in valid_boolean_trues if refresh: @@ -549,7 +549,7 @@ class PluginManagerPlugin( @Permissions.PLUGIN_PLUGINMANAGER_MANAGE.require(403) def retrieve_plugin_repository(self): if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can(): - return make_response("Insufficient rights", 403) + abort(403) refresh = request.values.get("refresh", "false") in valid_boolean_trues if refresh or not self._is_repository_cache_valid(): @@ -612,21 +612,21 @@ class PluginManagerPlugin( def on_api_command(self, command, data): if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can(): - return make_response("Insufficient rights", 403) + abort(403) if self._printer.is_printing() or self._printer.is_paused(): # do not update while a print job is running - return make_response("Printer is currently printing or paused", 409) + abort(409, description="Printer is currently printing or paused") if command == "install": if not Permissions.PLUGIN_PLUGINMANAGER_INSTALL.can(): - return make_response("Insufficient rights", 403) + abort(403) url = data["url"] plugin_name = data["plugin"] if "plugin" in data else None with self._install_lock: if self._install_task is not None: - return make_response("There's already a plugin being installed", 409) + abort(409, description="There's already a plugin being installed") self._install_task = threading.Thread( target=self.command_install, @@ -646,7 +646,7 @@ class PluginManagerPlugin( elif command == "uninstall": plugin_name = data["plugin"] if plugin_name not in self._plugin_manager.plugins: - return make_response("Unknown plugin", 404) + abort(404, description="Unknown plugin") plugin = self._plugin_manager.plugins[plugin_name] return self.command_uninstall(plugin, cleanup=data.get("cleanup", False)) @@ -667,7 +667,7 @@ class PluginManagerPlugin( elif command == "enable" or command == "disable": plugin_name = data["plugin"] if plugin_name not in self._plugin_manager.plugins: - return make_response("Unknown plugin", 404) + abort(404, description="Unknown plugin") plugin = self._plugin_manager.plugins[plugin_name] return self.command_toggle(plugin, command) @@ -679,7 +679,7 @@ class PluginManagerPlugin( ) def on_api_get(self, r): if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can(): - return make_response("Insufficient rights", 403) + abort(403) refresh_repository = ( request.values.get("refresh_repository", "false") in valid_boolean_trues @@ -1192,15 +1192,15 @@ class PluginManagerPlugin( def command_uninstall(self, plugin, cleanup=False): if plugin.key == "pluginmanager": - return make_response("Can't uninstall Plugin Manager", 403) + abort(403, description="Can't uninstall Plugin Manager") if not plugin.managable: - return make_response( - "Plugin is not managable and hence cannot be uninstalled", 403 + abort( + 403, description="Plugin is not managable and hence cannot be uninstalled" ) if plugin.bundled: - return make_response("Bundled plugins cannot be uninstalled", 403) + abort(403, description="Bundled plugins cannot be uninstalled") if plugin.origin is None: self._logger.warning( @@ -1208,7 +1208,7 @@ class PluginManagerPlugin( **locals() ) ) - return make_response("Could not uninstall plugin, its origin is unknown") + abort(500, description="Could not uninstall plugin, its origin is unknown") if plugin.origin.type == "entry_point": # plugin is installed through entry point, need to use pip to uninstall it @@ -1221,9 +1221,9 @@ class PluginManagerPlugin( self._call_pip(pip_args) except Exception: self._logger.exception("Could not uninstall plugin via pip") - return make_response( - "Could not uninstall plugin via pip, see the log for more details", + abort( 500, + description="Could not uninstall plugin via pip, see the log for more details", ) elif plugin.origin.type == "folder": @@ -1258,7 +1258,7 @@ class PluginManagerPlugin( **locals() ) ) - return make_response("Could not uninstall plugin, its origin is unknown") + abort(500, description="Could not uninstall plugin, its origin is unknown") needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin) or cleanup needs_refresh = plugin.implementation and isinstance( @@ -1446,7 +1446,7 @@ class PluginManagerPlugin( def command_toggle(self, plugin, command): if plugin.key == "pluginmanager" or (plugin.hidden and plugin.bundled): - return make_response("Can't enable/disable Plugin Manager", 400) + abort(400, description="Can't enable/disable Plugin Manager") pending = (command == "disable" and plugin.key in self._pending_enable) or ( command == "enable" and plugin.key in self._pending_disable diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index 798ffa6c7..550cefcdd 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -1017,8 +1017,11 @@ class SoftwareUpdatePlugin( } ) except exceptions.ConfigurationInvalid as e: - return flask.make_response( - "Update not properly configured, can't proceed: {}".format(e), 500 + flask.abort( + 500, + description="Update not properly configured, can't proceed: {}".format( + e + ), ) def etag(): @@ -1083,30 +1086,31 @@ class SoftwareUpdatePlugin( and not self._settings.get_boolean(["ignore_throttled"]) ): # currently throttled, we refuse to run - return flask.make_response( - "System is currently throttled, refusing to update " - "anything due to possible stability issues", + flask.abort( 409, + description="System is currently throttled, refusing to update " + "anything due to possible stability issues", ) if self._printer.is_printing() or self._printer.is_paused(): # do not update while a print job is running - return flask.make_response("Printer is currently printing or paused", 409) + flask.abort(409, description="Printer is currently printing or paused") if not self._environment_supported: - return flask.make_response( - "Direct updates are not supported in this Python environment", 409 + flask.abort( + 409, + description="Direct updates are not supported in this Python environment", ) if not self._storage_sufficient: - return flask.make_response("Not enough free disk space for updating", 409) + flask.abort(409, description="Not enough free disk space for updating") if "application/json" not in flask.request.headers["Content-Type"]: - return flask.make_response("Expected content-type JSON", 400) + flask.abort(400, description="Expected content-type JSON") json_data = flask.request.get_json(silent=True) if json_data is None: - return flask.make_response("Invalid JSON", 400) + flask.abort(400, description="Invalid JSON") if "targets" in json_data or "checks" in json_data: targets = list( @@ -1129,7 +1133,7 @@ class SoftwareUpdatePlugin( def configure_update(self): json_data = flask.request.get_json(silent=True) if json_data is None: - return flask.make_response("Invalid JSON", 400) + flask.abort(400) checks = self._get_configured_checks() diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 78e6a1d3a..28e06a9e7 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -42,6 +42,7 @@ from flask_login import ( # noqa: F401 from past.builtins import basestring, unicode from watchdog.observers import Observer from watchdog.observers.polling import PollingObserver +from werkzeug.exceptions import HTTPException import octoprint.util import octoprint.util.net @@ -65,8 +66,8 @@ except ImportError: fcntl = None SUCCESS = {} -NO_CONTENT = ("", 204) -NOT_MODIFIED = ("Not Modified", 304) +NO_CONTENT = ("", 204, {"Content-Type": "text/plain"}) +NOT_MODIFIED = ("Not Modified", 304, {"Content-Type": "text/plain"}) app = Flask("octoprint") @@ -1733,9 +1734,11 @@ class Server(object): # do not remove or the index view won't be found import octoprint.server.views # noqa: F401 from octoprint.server.api import api + from octoprint.server.util.flask import make_api_error blueprints = OrderedDict() blueprints["/api"] = api + json_errors = ["/api"] # also register any blueprints defined in BlueprintPlugins blueprints.update(self._prepare_blueprint_plugins()) @@ -1750,6 +1753,13 @@ class Server(object): for url_prefix, blueprint in blueprints.items(): app.register_blueprint(blueprint, url_prefix=url_prefix) + @app.errorhandler(HTTPException) + def _handle_api_error(ex): + if any(map(lambda x: request.path.startswith(x), json_errors)): + return make_api_error(ex.description, ex.code) + else: + return ex + def _prepare_blueprint_plugins(self): blueprints = OrderedDict() diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index feea98729..056d68283 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -10,6 +10,7 @@ import logging from flask import ( Blueprint, + Response, abort, current_app, g, @@ -80,22 +81,40 @@ def pluginData(name): lambda p: p._identifier == name, octoprint.plugin.SimpleApiPlugin ) if not api_plugins: - return make_response("Not found", 404) + abort(404) if len(api_plugins) > 1: - return make_response( - "More than one api provider registered, can't proceed", - 500, - ) + abort(500, description="More than one api provider registered, can't proceed") try: api_plugin = api_plugins[0] if api_plugin.is_api_adminonly() and not current_user.is_admin: - return make_response("Forbidden", 403) + abort(403) response = api_plugin.on_api_get(request) if response is not None: + message = ( + "Rewriting response from {} to use abort(msg, code) - please " + "consider upgrading the implementation accordingly".format(name) + ) + if ( + isinstance(response, Response) + and response.mimetype == "text/html" + and response.status_code >= 300 + ): + # this actually looks like an error response + logging.getLogger(__name__).info(message) + abort(response.status_code, description=response.data) + elif ( + isinstance(response, tuple) + and len(response) == 2 + and isinstance(response[0], (str, bytes)) + and response[1] >= 300 + ): + # this actually looks like an error response + logging.getLogger(__name__).info(message) + abort(response[1], response[0]) return response return NO_CONTENT except HTTPException: @@ -118,22 +137,19 @@ def pluginCommand(name): ) if not api_plugins: - return make_response("Not found", 404) + abort(400) if len(api_plugins) > 1: - return make_response( - "More than one api provider registered, can't proceed", - 500, - ) + abort(500, description="More than one api provider registered, can't proceed") api_plugin = api_plugins[0] try: valid_commands = api_plugin.get_api_commands() if valid_commands is None: - return make_response("Method not allowed", 405) + abort(405) if api_plugin.is_api_adminonly() and not Permissions.ADMIN.can(): - return make_response("Forbidden", 403) + abort(403) command, data, response = get_json_command_from_request(request, valid_commands) if response is not None: @@ -249,14 +265,6 @@ def wizardFinish(): # ~~ system state -@api.route("/state", methods=["GET"]) -@no_firstrun_access -def apiPrinterState(): - return make_response( - ("/api/state has been deprecated, use /api/printer instead", 405, []) - ) - - @api.route("/version", methods=["GET"]) @Permissions.STATUS.require(403) def apiVersion(): @@ -298,7 +306,7 @@ def login(): if user is not None: if octoprint.server.userManager.check_password(username, password): if not user.is_active: - return make_response(("Your account is deactivated", 403, [])) + abort(403) user = octoprint.server.userManager.login_user(user) session["usersession.id"] = user.session @@ -335,12 +343,12 @@ def login(): return r - return make_response(("User unknown or password incorrect", 403, [])) + abort(403) elif "passive" in data: return passive_login() - return make_response("Neither user and pass attributes nor passive flag present", 400) + abort(400, description="Neither user and pass attributes nor passive flag present") @api.route("/logout", methods=["POST"]) @@ -584,10 +592,7 @@ def _test_url(data): try: timeout = float(data["timeout"]) except Exception: - return make_response( - "Not a valid value for timeout (must be int or float)", - 400, - ) + abort(400, description="timeout is invalid") if "validSsl" in data: valid_ssl = data["validSsl"] in valid_boolean_trues @@ -611,13 +616,13 @@ def _test_url(data): if "content_type_whitelist" in data: if not isinstance(data["content_type_whitelist"], (list, tuple)): - return make_response("content_type_whitelist must be a list of mime types") + abort(400, description="content_type_whitelist must be a list of mime types") content_type_whitelist = list( map(util.parse_mime_type, data["content_type_whitelist"]) ) if "content_type_blacklist" in data: if not isinstance(data["content_type_whitelist"], (list, tuple)): - return make_response("content_type_blacklist must be a list of mime types") + abort(400, description="content_type_blacklist must be a list of mime types") content_type_blacklist = list( map(util.parse_mime_type, data["content_type_blacklist"]) ) @@ -698,24 +703,18 @@ def _test_server(data): try: port = int(data["port"]) except Exception: - return make_response("Not a valid value for port (must be int)", 400) + abort(400, description="Invalid value for port") timeout = 3.05 if "timeout" in data: try: timeout = float(data["timeout"]) except Exception: - return make_response( - "Not a valid value for timeout (must be int or float)", - 400, - ) + abort(400, description="Invalid value for timeout") protocol = data.get("protocol", "tcp") if protocol not in ("tcp", "udp"): - return make_response( - "Not a valid value for protocol, must be tcp or udp", - 400, - ) + abort(400, description="Invalid value for protocol") from octoprint.util import server_reachable diff --git a/src/octoprint/server/api/access.py b/src/octoprint/server/api/access.py index 4ddc9bdc1..f024dc6eb 100644 --- a/src/octoprint/server/api/access.py +++ b/src/octoprint/server/api/access.py @@ -5,9 +5,8 @@ __author__ = "Marc Hannappel " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" -from flask import abort, jsonify, make_response, request +from flask import abort, jsonify, request from flask_login import current_user -from werkzeug.exceptions import BadRequest import octoprint.access.groups as groups import octoprint.access.users as users @@ -39,19 +38,16 @@ def get_groups(): @Permissions.SETTINGS.require(403) def add_group(): if "application/json" not in request.headers["Content-Type"]: - return make_response("Expected content-type JSON", 400) + abort(400, description="Expected content-type JSON") - try: - data = request.get_json() - except BadRequest: - return make_response("Malformed JSON body in request", 400) + data = request.get_json() if "key" not in data: - return make_response("Missing mandatory key field", 400) + abort(400, description="key is missing") if "name" not in data: - return make_response("Missing mandatory name field", 400) + abort(400, description="name is missing") if "permissions" not in data: - return make_response("Missing mandatory permissions field", 400) + abort(400, description="permissions are missing") key = data["key"] name = data["name"] @@ -90,12 +86,9 @@ def get_group(key): @Permissions.SETTINGS.require(403) def update_group(key): if "application/json" not in request.headers["Content-Type"]: - return make_response("Expected content-type JSON", 400) + abort(400, description="Expected content-type JSON") - try: - data = request.get_json() - except BadRequest: - return make_response("Malformed JSON body in request", 400) + data = request.get_json() try: kwargs = {} @@ -149,22 +142,18 @@ def get_users(): @Permissions.SETTINGS.require(403) def add_user(): if "application/json" not in request.headers["Content-Type"]: - return make_response("Expected content-type JSON", 400) - - try: - data = request.get_json() - except BadRequest: - return make_response("Malformed JSON body in request", 400) + abort(400, description="Expected content-type JSON") + data = request.get_json() if data is None: - return make_response("Malformed JSON body in request", 400) + abort(400, description="Malformed JSON body in request") if "name" not in data: - return make_response("Missing mandatory name field", 400) + abort(400, description="name is missing") if "password" not in data: - return make_response("Missing mandatory password field", 400) + abort(400, description="password is missing") if "active" not in data: - return make_response("Missing mandatory active field", 400) + abort(400, description="active is missing") name = data["name"] password = data["password"] @@ -207,12 +196,12 @@ def update_user(username): user = userManager.find_user(username) if user is not None: if "application/json" not in request.headers["Content-Type"]: - return make_response("Expected content-type JSON", 400) + abort(400, description="Expected content-type JSON") - try: - data = request.get_json() - except BadRequest: - return make_response("Malformed JSON body in request", 400) + data = request.get_json() + + if data is None: + abort(400, description="Malformed JSON body in request") # change groups if "groups" in data: @@ -224,9 +213,6 @@ def update_user(username): permissions = data["permissions"] userManager.change_user_permissions(username, permissions) - if data is None: - return make_response("Malformed JSON body in request", 400) - # change activation if "active" in data: userManager.change_user_activation( @@ -261,27 +247,24 @@ def change_password_for_user(username): and (current_user.get_name() == username or current_user.is_admin) ): if "application/json" not in request.headers["Content-Type"]: - return make_response("Expected content-type JSON", 400) + abort(400, description="Expected content-type JSON") - try: - data = request.get_json() - except BadRequest: - return make_response("Malformed JSON body in request", 400) + data = request.get_json() if data is None: - return make_response("Malformed JSON body in request", 400) + abort(400, description="Malformed JSON body in request") if "password" not in data or not data["password"]: - return make_response("password is missing from request", 400) + abort(400, description="password is missing") try: userManager.change_user_password(username, data["password"]) except users.UnknownUser: - return make_response(("Unknown user", 404, [])) + abort(404) return jsonify(SUCCESS) else: - return make_response(("Forbidden", 403, [])) + abort(403) @api.route("/access/users//settings", methods=["GET"]) @@ -295,12 +278,12 @@ def get_settings_for_user(username): and not current_user.has_permission(Permissions.ADMIN) ) ): - return make_response("Forbidden", 403) + abort(403) try: return jsonify(userManager.get_all_user_settings(username)) except users.UnknownUser: - return make_response("Unknown user", 404) + abort(404) @api.route("/access/users//settings", methods=["PATCH"]) @@ -314,21 +297,18 @@ def change_settings_for_user(username): and not current_user.has_permission(Permissions.ADMIN) ) ): - return make_response("Forbidden", 403) + abort(403) - try: - data = request.get_json() - except BadRequest: - return make_response("Malformed JSON body in request", 400) + data = request.get_json() if data is None: - return make_response("Malformed JSON body in request", 400) + abort(400, description="Malformed JSON body in request") try: userManager.change_user_settings(username, data) return jsonify(SUCCESS) except users.UnknownUser: - return make_response("Unknown user", 404) + abort(404) @api.route("/access/users//apikey", methods=["DELETE"]) @@ -345,10 +325,10 @@ def delete_apikey_for_user(username): try: userManager.delete_api_key(username) except users.UnknownUser: - return make_response(("Unknown user", 404, [])) + abort(404) return jsonify(SUCCESS) else: - return make_response(("Forbidden", 403, [])) + abort(403) @api.route("/access/users//apikey", methods=["POST"]) @@ -368,10 +348,10 @@ def generate_apikey_for_user(username): try: apikey = userManager.generate_api_key(username) except users.UnknownUser: - return make_response(("Unknown user", 404, [])) + abort(404) return jsonify({"apikey": apikey}) else: - return make_response(("Forbidden", 403, [])) + abort(403) def _to_external_permissions(*permissions): diff --git a/src/octoprint/server/api/connection.py b/src/octoprint/server/api/connection.py index 905302fcd..ba8a2d18e 100644 --- a/src/octoprint/server/api/connection.py +++ b/src/octoprint/server/api/connection.py @@ -5,7 +5,7 @@ __author__ = "Gina Häußge " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" -from flask import jsonify, make_response, request +from flask import abort, jsonify, request from octoprint.access.permissions import Permissions from octoprint.server import NO_CONTENT, printer, printerProfileManager @@ -49,15 +49,15 @@ def connectionCommand(): if "port" in data: port = data["port"] if port not in connection_options["ports"] and port != "AUTO": - return make_response("Invalid port", 400) + abort(400, description="port is invalid") if "baudrate" in data: baudrate = data["baudrate"] if baudrate not in connection_options["baudrates"] and baudrate != 0: - return make_response("Invalid baudrate", 400) + abort(400, description="baudrate is invalid") if "printerProfile" in data: printerProfile = data["printerProfile"] if not printerProfileManager.exists(printerProfile): - return make_response("Invalid printer profile", 400) + abort(400, description="printerProfile is invalid") if "save" in data and data["save"]: settings().set(["serial", "port"], port) settings().setInt(["serial", "baudrate"], baudrate) diff --git a/src/octoprint/server/api/files.py b/src/octoprint/server/api/files.py index bd3301e57..10a0a6a04 100644 --- a/src/octoprint/server/api/files.py +++ b/src/octoprint/server/api/files.py @@ -11,7 +11,7 @@ import os import threading import psutil -from flask import jsonify, make_response, request, url_for +from flask import abort, jsonify, make_response, request, url_for import octoprint.filemanager import octoprint.filemanager.storage @@ -180,7 +180,7 @@ def readGcodeFiles(): ) def readGcodeFilesForOrigin(origin): if origin not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: - return make_response("Unknown origin", 404) + abort(404) filter = request.values.get("filter", False) recursive = request.values.get("recursive", "false") in valid_boolean_trues @@ -216,10 +216,10 @@ def readGcodeFilesForOrigin(origin): ) def readGcodeFile(target, filename): if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: - return make_response("Unknown target", 404) + abort(404) if filename != fileManager.sanitize(target, filename): - return make_response("File not found", 404) + abort(404) recursive = False if "recursive" in request.values: @@ -227,7 +227,7 @@ def readGcodeFile(target, filename): file = _getFileDetails(target, filename, recursive=recursive) if not file: - return make_response("File not found", 404) + abort(404) return jsonify(file) @@ -453,7 +453,7 @@ def uploadGcodeFile(target): ) if input_upload_name in request.values and input_upload_path in request.values: if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: - return make_response("Unknown target", 404) + abort(404) upload = octoprint.filemanager.util.DiskFileWrapper( request.values[input_upload_name], request.values[input_upload_path] @@ -467,12 +467,12 @@ def uploadGcodeFile(target): try: userdata = json.loads(request.values["userdata"]) except Exception: - return make_response("userdata contains invalid JSON", 400) + abort(400, description="userdata contains invalid JSON") if target == FileDestinations.SDCARD and not settings().getBoolean( ["feature", "sdSupport"] ): - return make_response("SD card support is disabled", 404) + abort(404) sd = target == FileDestinations.SDCARD selectAfterUpload = ( @@ -492,14 +492,12 @@ def uploadGcodeFile(target): printer.is_operational() and not (printer.is_printing() or printer.is_paused()) ): - return make_response( - "Can not upload to SD card, printer is either not operational or already busy", + abort( 409, + description="Can not upload to SD card, printer is either not operational or already busy", ) if not printer.is_sd_ready(): - return make_response( - "Can not upload to SD card, not yet initialized", 409 - ) + abort(409, description="Can not upload to SD card, not yet initialized") # determine future filename of file to be uploaded, abort if it can't be uploaded try: @@ -517,7 +515,7 @@ def uploadGcodeFile(target): futureFilename = None if futureFilename is None: - return make_response("Can not upload file, wrong format?", 415) + abort(415, description="Can not upload file, wrong format?") if "path" in request.values and request.values["path"]: # we currently only support uploads to sdcard via local, so first target is local instead of "target" @@ -534,9 +532,9 @@ def uploadGcodeFile(target): ) if not printer.can_modify_file(futureFullPathInStorage, sd): - return make_response( - "Trying to overwrite file that is currently being printed", + abort( 409, + description="Trying to overwrite file that is currently being printed", ) reselect = printer.is_current_file(futureFullPathInStorage, sd) @@ -594,12 +592,9 @@ def uploadGcodeFile(target): ) except octoprint.filemanager.storage.StorageError as e: if e.code == octoprint.filemanager.storage.StorageError.INVALID_FILE: - return make_response( - "Could not upload the file, invalid type", - 400, - ) + abort(400, description="Could not upload file, invalid type") else: - return make_response("Could not upload the file", 500) + abort(500, description="Could not upload file") if octoprint.filemanager.valid_file_type(added_file, "stl"): filename = added_file @@ -684,13 +679,13 @@ def uploadGcodeFile(target): foldername = request.values["foldername"] if target not in [FileDestinations.LOCAL]: - return make_response("Unknown target", 400) + abort(400, description="target is invalid") canonPath, canonName = fileManager.canonicalize(target, foldername) futurePath = fileManager.sanitize_path(target, canonPath) futureName = fileManager.sanitize_name(target, canonName) if not futureName or not futurePath: - return make_response("Can't create a folder with an empty name", 400) + abort(400, description="folder name is empty") if "path" in request.values and request.values["path"]: futurePath = fileManager.sanitize_path( @@ -699,10 +694,7 @@ def uploadGcodeFile(target): futureFullPath = fileManager.join_path(target, futurePath, futureName) if octoprint.filemanager.valid_file_type(futureName): - return make_response( - "Can't create folder, please try another name", - 409, - ) + abort(409, description="Can't create folder, please try another name") try: added_folder = fileManager.add_folder( @@ -710,9 +702,9 @@ def uploadGcodeFile(target): ) except octoprint.filemanager.storage.StorageError as e: if e.code == octoprint.filemanager.storage.StorageError.INVALID_DIRECTORY: - return make_response("Could not create folder, invalid directory") + abort(400, description="Could not create folder, invalid directory") else: - return make_response("Could not create folder") + abort(500, description="Could not create folder") location = url_for( ".readGcodeFile", @@ -732,17 +724,17 @@ def uploadGcodeFile(target): return r else: - return make_response("No file to upload and no folder to create", 400) + abort(400, description="No file to upload and no folder to create") @api.route("/files//", methods=["POST"]) @no_firstrun_access def gcodeFileCommand(filename, target): if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: - return make_response("Unknown target", 404) + abort(404) if filename != fileManager.sanitize(target, filename): - return make_response("File not found", 404) + abort(404) # valid file commands, dict mapping command name to mandatory parameters valid_commands = { @@ -762,27 +754,28 @@ def gcodeFileCommand(filename, target): if command == "select": with Permissions.FILES_SELECT.require(403): if not _verifyFileExists(target, filename): - return make_response("File not found", 404) + abort(404) # selects/loads a file if not octoprint.filemanager.valid_file_type(filename, type="machinecode"): - return make_response( - "Cannot select file for printing, not a machinecode file", + abort( 415, + description="Cannot select file for printing, not a machinecode file", ) if not printer.is_ready(): - return make_response( - "Printer is already printing, cannot select a new file", 409 + abort( + 409, + description="Printer is already printing, cannot select a new file", ) printAfterLoading = False if "print" in data and data["print"] in valid_boolean_trues: with Permissions.PRINT.require(403): if not printer.is_operational(): - return make_response( - "Printer is not operational, cannot directly start printing", + abort( 409, + description="Printer is not operational, cannot directly start printing", ) printAfterLoading = True @@ -797,7 +790,7 @@ def gcodeFileCommand(filename, target): elif command == "slice": with Permissions.SLICE.require(403): if not _verifyFileExists(target, filename): - return make_response("File not found", 404) + abort(404) try: if "slicer" in data: @@ -810,12 +803,9 @@ def gcodeFileCommand(filename, target): slicer_instance = slicingManager.get_slicer("cura") else: - return make_response( - "Cannot slice file, no slicer available", - 415, - ) + abort(415, description="Cannot slice file, no slicer available") except octoprint.slicing.UnknownSlicer: - return make_response("Slicer is not available", 400) + abort(404) if not any( [ @@ -825,7 +815,7 @@ def gcodeFileCommand(filename, target): ) ] ): - return make_response("Cannot slice file, not a model file", 415) + abort(415, description="Cannot slice file, not a model file") cores = psutil.cpu_count() if ( @@ -834,9 +824,9 @@ def gcodeFileCommand(filename, target): and (cores is None or cores < 2) ): # slicer runs on same device as OctoPrint, slicing while printing is hence disabled - return make_response( - "Cannot slice on this slicer while printing on single core systems or systems of unknown core count due to performance reasons", + abort( 409, + description="Cannot slice on this slicer while printing on single core systems or systems of unknown core count due to performance reasons", ) if "destination" in data and data["destination"]: @@ -880,9 +870,9 @@ def gcodeFileCommand(filename, target): and currentOrigin == target and (printer.is_printing() or printer.is_paused()) ): - make_response( - "Trying to slice into file that is currently being printed", + abort( 409, + description="Trying to slice into file that is currently being printed", ) if "profile" in data and data["profile"]: @@ -912,17 +902,18 @@ def gcodeFileCommand(filename, target): select_after_slicing = False if "select" in data and data["select"] in valid_boolean_trues: if not printer.is_operational(): - return make_response( - "Printer is not operational, cannot directly select for printing", + abort( 409, + description="Printer is not operational, cannot directly select for printing", ) select_after_slicing = True print_after_slicing = False if "print" in data and data["print"] in valid_boolean_trues: if not printer.is_operational(): - return make_response( - "Printer is not operational, cannot directly start printing", 409 + abort( + 409, + description="Printer is not operational, cannot directly start printing", ) select_after_slicing = print_after_slicing = True @@ -964,7 +955,7 @@ def gcodeFileCommand(filename, target): ), ) except octoprint.slicing.UnknownProfile: - return make_response("Profile doesn't exist", 400) + abort(404, description="Unknown profile") location = url_for( ".readGcodeFile", target=target, filename=full_path, _external=True @@ -991,7 +982,7 @@ def gcodeFileCommand(filename, target): elif command == "analyse": with Permissions.FILES_UPLOAD.require(403): if not _verifyFileExists(target, filename): - return make_response("File not found", 404) + abort(404) printer_profile = None if "printerProfile" in data and data["printerProfile"]: @@ -1000,18 +991,18 @@ def gcodeFileCommand(filename, target): if not fileManager.analyse( target, filename, printer_profile_id=printer_profile ): - return make_response("No analysis possible", 400) + abort(400, description="No analysis possible") elif command == "copy" or command == "move": with Permissions.FILES_UPLOAD.require(403): # Copy and move are only possible on local storage if target not in [FileDestinations.LOCAL]: - return make_response("Unsupported target for {}".format(command), 400) + abort(400, description="Unsupported target for {}".format(command)) if not _verifyFileExists(target, filename) and not _verifyFolderExists( target, filename ): - return make_response("File or folder not found", 404) + abort(404) path, name = fileManager.split_path(target, filename) @@ -1032,18 +1023,14 @@ def gcodeFileCommand(filename, target): if _verifyFileExists(target, destination) or _verifyFolderExists( target, destination ): - return make_response( - "File or folder does already exist", - 409, - ) + abort(409, description="File or folder does already exist") is_file = fileManager.file_exists(target, filename) is_folder = fileManager.folder_exists(target, filename) if not (is_file or is_folder): - return make_response( - "Neither file nor folder, can't {}", - 400, + abort( + 400, description="Neither file nor folder, can't {}".format(command) ) if command == "copy": @@ -1051,10 +1038,7 @@ def gcodeFileCommand(filename, target): if _verifyFileExists(target, destination) or _verifyFolderExists( target, destination ): - return make_response( - "File or folder does already exist", - 409, - ) + abort(409, description="File or folder does already exist") if is_file: fileManager.copy_file(target, filename, destination) @@ -1064,9 +1048,9 @@ def gcodeFileCommand(filename, target): elif command == "move": with Permissions.FILES_DELETE.require(403): if _isBusy(target, filename): - return make_response( - "Trying to move a file or folder that is currently in use", + abort( 409, + description="Trying to move a file or folder that is currently in use", ) # destination already there AND not ourselves (= display rename)? error... @@ -1074,10 +1058,7 @@ def gcodeFileCommand(filename, target): _verifyFileExists(target, destination) or _verifyFolderExists(target, destination) ) and sanitized_destination != filename: - return make_response( - "File or folder does already exist", - 409, - ) + abort(409, description="File or folder does already exist") # deselect the file if it's currently selected currentOrigin, currentFilename = _getCurrentFile() @@ -1119,19 +1100,19 @@ def gcodeFileCommand(filename, target): @Permissions.FILES_DELETE.require(403) def deleteGcodeFile(filename, target): if filename != fileManager.sanitize(target, filename): - return make_response("File not found", 400) + abort(404) if not _verifyFileExists(target, filename) and not _verifyFolderExists( target, filename ): - return make_response("File not found", 404) + abort(404) if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: - return make_response("Unknown target", 404) + abort(404) if _verifyFileExists(target, filename): if _isBusy(target, filename): - return make_response("Trying to delete a file that is currently in use", 409) + abort(409, description="Trying to delete a file that is currently in use") # deselect the file if it's currently selected currentOrigin, currentPath = _getCurrentFile() @@ -1150,9 +1131,9 @@ def deleteGcodeFile(filename, target): elif _verifyFolderExists(target, filename): if _isBusy(target, filename): - return make_response( - "Trying to delete a folder that contains a file that is currently in use", + abort( 409, + description="Trying to delete a folder that contains a file that is currently in use", ) # deselect the file if it's currently selected diff --git a/src/octoprint/server/api/job.py b/src/octoprint/server/api/job.py index ce35d9ed5..1ba5c6f8d 100644 --- a/src/octoprint/server/api/job.py +++ b/src/octoprint/server/api/job.py @@ -5,7 +5,7 @@ __author__ = "Gina Häußge " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" -from flask import jsonify, make_response, request +from flask import abort, jsonify, request from octoprint.access.permissions import Permissions from octoprint.server import NO_CONTENT, current_user, printer @@ -17,7 +17,7 @@ from octoprint.server.util.flask import get_json_command_from_request, no_firstr @no_firstrun_access def controlJob(): if not printer.is_operational(): - return make_response("Printer is not operational", 409) + abort(409, description="Printer is not operational") valid_commands = {"start": [], "restart": [], "pause": [], "cancel": []} @@ -34,22 +34,23 @@ def controlJob(): with Permissions.PRINT.require(403): if command == "start": if activePrintjob: - return make_response( - "Printer already has an active print job, did you mean 'restart'?", + abort( 409, + description="Printer already has an active print job, did you mean 'restart'?", ) printer.start_print(tags=tags, user=user) elif command == "restart": if not printer.is_paused(): - return make_response( - "Printer does not have an active print job or is not paused", 409 + abort( + 409, + description="Printer does not have an active print job or is not paused", ) printer.start_print(tags=tags, user=user) elif command == "pause": if not activePrintjob: - return make_response( - "Printer is neither printing nor paused, 'pause' command cannot be performed", + abort( 409, + description="Printer is neither printing nor paused, 'pause' command cannot be performed", ) action = data.get("action", "toggle") if action == "toggle": @@ -59,15 +60,12 @@ def controlJob(): elif action == "resume": printer.resume_print(tags=tags, user=user) else: - return make_response( - "Unknown action, allowed values for action parameter are 'pause', 'resume' and 'toggle'", - 400, - ) + abort(400, description="Unknown action") elif command == "cancel": if not activePrintjob: - return make_response( - "Printer is neither printing nor paused, 'cancel' command cannot be performed", + abort( 409, + description="Printer is neither printing nor paused, 'cancel' command cannot be performed", ) printer.cancel_print(tags=tags, user=user) return NO_CONTENT diff --git a/src/octoprint/server/api/languages.py b/src/octoprint/server/api/languages.py index 8ba9a05cf..46710b966 100644 --- a/src/octoprint/server/api/languages.py +++ b/src/octoprint/server/api/languages.py @@ -18,7 +18,7 @@ except ImportError: from collections import defaultdict -from flask import jsonify, make_response, request +from flask import abort, jsonify, request from flask_babel import Locale from octoprint.access.permissions import Permissions @@ -135,7 +135,7 @@ def uploadLanguagePack(): input_name + "." + settings().get(["server", "uploads", "nameSuffix"]) ) if input_upload_path not in request.values or input_upload_name not in request.values: - return make_response("No file included", 400) + abort(400, description="No file included") upload_name = request.values[input_upload_name] upload_path = request.values[input_upload_path] @@ -146,8 +146,9 @@ def uploadLanguagePack(): ) ) if not len(exts): - return make_response( - "File doesn't have a valid extension for a language pack archive", 400 + abort( + 400, + description="File doesn't have a valid extension for a language pack archive", ) target_path = settings().getBaseFolder("translations") @@ -157,7 +158,7 @@ def uploadLanguagePack(): elif zipfile.is_zipfile(upload_path): _unpack_uploaded_zipfile(upload_path, target_path) else: - return make_response("Neither zip file nor tarball included", 400) + abort(400, description="Neither zip file nor tarball included") return getInstalledLanguagePacks() diff --git a/src/octoprint/server/api/printer.py b/src/octoprint/server/api/printer.py index 307fa9e84..aa31caaae 100644 --- a/src/octoprint/server/api/printer.py +++ b/src/octoprint/server/api/printer.py @@ -7,9 +7,8 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import re -from flask import Response, jsonify, make_response, request +from flask import Response, abort, jsonify, request from past.builtins import basestring, long, unicode -from werkzeug.exceptions import BadRequest from octoprint.access.permissions import Permissions from octoprint.printer import UnknownScript @@ -25,7 +24,7 @@ from octoprint.settings import settings, valid_boolean_trues @Permissions.STATUS.require(403) def printerState(): if not printer.is_operational(): - return make_response("Printer is not operational", 409) + abort(409, description="Printer is not operational") # process excludes excludes = [] @@ -75,7 +74,7 @@ def printerState(): @Permissions.CONTROL.require(403) def printerToolCommand(): if not printer.is_operational(): - return make_response("Printer is not operational", 409) + abort(409, description="Printer is not operational") valid_commands = { "select": ["tool"], @@ -96,9 +95,7 @@ def printerToolCommand(): if command == "select": tool = data["tool"] if not isinstance(tool, basestring) or re.match(validation_regex, tool) is None: - return make_response("Invalid tool", 400) - if not tool.startswith("tool"): - return make_response("Invalid tool for selection", 400) + abort(400, description="tool is invalid") printer.change_tool(tool, tags=tags) @@ -110,9 +107,9 @@ def printerToolCommand(): validated_values = {} for tool, value in targets.items(): if re.match(validation_regex, tool) is None: - return make_response("Invalid target for setting temperature", 400) + abort(400, description="targets contains invalid tool") if not isinstance(value, (int, long, float)): - return make_response("Target is not a number", 400) + abort(400, description="targets contains invalid value") validated_values[tool] = value # perform the actual temperature commands @@ -127,11 +124,9 @@ def printerToolCommand(): validated_values = {} for tool, value in offsets.items(): if re.match(validation_regex, tool) is None: - return make_response("Invalid target for setting temperature offset", 400) - if not isinstance(value, (int, long, float)): - return make_response("Offset is not a number", 400) - if not -50 <= value <= 50: - return make_response("Offset not in range [-50, 50]", 400) + abort(400, description="offsets contains invalid tool") + if not isinstance(value, (int, long, float)) or not -50 <= value <= 50: + abort(400, description="offsets contains invalid value") validated_values[tool] = value # set the offsets @@ -141,22 +136,22 @@ def printerToolCommand(): elif command == "extrude": if printer.is_printing(): # do not extrude when a print job is running - return make_response("Printer is currently printing", 409) + abort(409, description="Printer is currently printing") amount = data["amount"] speed = data.get("speed", None) if not isinstance(amount, (int, long, float)): - return make_response("Extrusion amount is not a number", 400) + abort(400, description="amount is invalid") printer.extrude(amount, speed=speed, tags=tags) elif command == "flowrate": factor = data["factor"] if not isinstance(factor, (int, long, float)): - return make_response("Flow rate is not a number", 400) + abort(400, description="factor is invalid") try: printer.flow_rate(factor, tags=tags) except ValueError: - return make_response("Invalid value for flow rate", 400) + abort(400, description="factor is invalid") return NO_CONTENT @@ -166,7 +161,7 @@ def printerToolCommand(): @Permissions.STATUS.require(403) def printerToolState(): if not printer.is_operational(): - return make_response("Printer is not operational", 409) + abort(409, description="Printer is not operational") return jsonify(_get_temperature_data(_keep_tools)) @@ -179,10 +174,10 @@ def printerToolState(): @Permissions.CONTROL.require(403) def printerBedCommand(): if not printer.is_operational(): - return make_response("Printer is not operational", 409) + abort(409, description="Printer is not operational") if not printerProfileManager.get_current_or_default()["heatedBed"]: - return make_response("Printer does not have a heated bed", 409) + abort(409, description="Printer does not have a heated bed") valid_commands = {"target": ["target"], "offset": ["offset"]} command, data, response = get_json_command_from_request(request, valid_commands) @@ -197,7 +192,7 @@ def printerBedCommand(): # make sure the target is a number if not isinstance(target, (int, long, float)): - return make_response("Target is not a number", 400) + abort(400, description="target is invalid") # perform the actual temperature command printer.set_temperature("bed", target, tags=tags) @@ -207,10 +202,8 @@ def printerBedCommand(): offset = data["offset"] # make sure the offset is valid - if not isinstance(offset, (int, long, float)): - return make_response("Offset is not a number", 400) - if not -50 <= offset <= 50: - return make_response("Offset is not in range [-50, 50]", 400) + if not isinstance(offset, (int, long, float)) or not -50 <= offset <= 50: + abort(400, description="offset is invalid") # set the offsets printer.set_temperature_offset({"bed": offset}) @@ -223,10 +216,10 @@ def printerBedCommand(): @Permissions.STATUS.require(403) def printerBedState(): if not printer.is_operational(): - return make_response("Printer is not operational", 409) + abort(409, description="Printer is not operational") if not printerProfileManager.get_current_or_default()["heatedBed"]: - return make_response("Printer does not have a heated bed", 409) + abort(409, description="Printer does not have a heated bed") data = _get_temperature_data(_keep_bed) if isinstance(data, Response): @@ -243,10 +236,10 @@ def printerBedState(): @Permissions.CONTROL.require(403) def printerChamberCommand(): if not printer.is_operational(): - return make_response("Printer is not operational", 409) + abort(409, description="Printer is not operational") if not printerProfileManager.get_current_or_default()["heatedChamber"]: - return make_response("Printer does not have a heated chamber", 409) + abort(409, description="Printer does not have a heated chamber") valid_commands = {"target": ["target"], "offset": ["offset"]} command, data, response = get_json_command_from_request(request, valid_commands) @@ -261,7 +254,7 @@ def printerChamberCommand(): # make sure the target is a number if not isinstance(target, (int, long, float)): - return make_response("Target is not a number", 400) + abort(400, description="target is invalid") # perform the actual temperature command printer.set_temperature("chamber", target, tags=tags) @@ -271,10 +264,8 @@ def printerChamberCommand(): offset = data["offset"] # make sure the offset is valid - if not isinstance(offset, (int, long, float)): - return make_response("Offset is not a number", 400) - if not -50 <= offset <= 50: - return make_response("Offset is not in range [-50, 50]", 400) + if not isinstance(offset, (int, long, float)) or not -50 <= offset <= 50: + abort(400, description="offset is invalid") # set the offsets printer.set_temperature_offset({"chamber": offset}) @@ -287,10 +278,10 @@ def printerChamberCommand(): @Permissions.STATUS.require(403) def printerChamberState(): if not printer.is_operational(): - return make_response("Printer is not operational", 409) + abort(409, description="Printer is not operational") if not printerProfileManager.get_current_or_default()["heatedChamber"]: - return make_response("Printer does not have a heated chamber", 409) + abort(409, description="Printer does not have a heated chamber") data = _get_temperature_data(_keep_chamber) if isinstance(data, Response): @@ -313,7 +304,7 @@ def printerPrintheadCommand(): if not printer.is_operational() or (printer.is_printing() and command != "feedrate"): # do not jog when a print job is running or we don't have a connection - return make_response("Printer is not operational or currently printing", 409) + abort(409, description="Printer is not operational or currently printing") tags = {"source:api", "api:printer.printhead"} @@ -326,7 +317,7 @@ def printerPrintheadCommand(): if axis in data: value = data[axis] if not isinstance(value, (int, long, float)): - return make_response("Axis value is not a number", 400) + abort(400, description="axis value is invalid") validated_values[axis] = value absolute = "absolute" in data and data["absolute"] in valid_boolean_trues @@ -341,7 +332,7 @@ def printerPrintheadCommand(): axes = data["axes"] for axis in axes: if axis not in valid_axes: - return make_response("Invalid axis", 400) + abort(400, description="axis is invalid") validated_values.append(axis) # execute the home command @@ -350,11 +341,11 @@ def printerPrintheadCommand(): elif command == "feedrate": factor = data["factor"] if not isinstance(factor, (int, long, float)): - return make_response("Feed rate is not a number", 400) + abort(400, description="factor is invalid") try: printer.feed_rate(factor, tags=tags) except ValueError: - return make_response("Invalid value for feed rate", 400) + abort(400, description="factor is invalid") return NO_CONTENT @@ -367,10 +358,10 @@ def printerPrintheadCommand(): @Permissions.CONTROL.require(403) def printerSdCommand(): if not settings().getBoolean(["feature", "sdSupport"]): - return make_response("SD support is disabled", 404) + abort(404, description="SD support is disabled") if not printer.is_operational() or printer.is_printing() or printer.is_paused(): - return make_response("Printer is not operational or currently busy", 409) + abort(409, description="Printer is not operational or currently busy") valid_commands = {"init": [], "refresh": [], "release": []} command, data, response = get_json_command_from_request(request, valid_commands) @@ -394,7 +385,7 @@ def printerSdCommand(): @Permissions.STATUS.require(403) def printerSdState(): if not settings().getBoolean(["feature", "sdSupport"]): - return make_response("SD support is disabled", 404) + abort(404, description="SD support is disabled") return jsonify(ready=printer.is_sd_ready()) @@ -407,27 +398,22 @@ def printerSdState(): @Permissions.CONTROL.require(403) def printerCommand(): if not printer.is_operational(): - return make_response("Printer is not operational", 409) + abort(409, description="Printer is not operational") if "application/json" not in request.headers["Content-Type"]: - return make_response("Expected content type JSON", 400) + abort(400, description="Expected content type JSON") - try: - data = request.get_json() - except BadRequest: - return make_response("Malformed JSON body in request", 400) + data = request.get_json() if data is None: - return make_response("Malformed JSON body in request", 400) + abort(400, description="Malformed JSON body in request") if "command" in data and "commands" in data: - return make_response("'command' and 'commands' are mutually exclusive", 400) + abort(400, description="'command' and 'commands' are mutually exclusive") elif ("command" in data or "commands" in data) and "script" in data: - return make_response( - "'command'/'commands' and 'script' are mutually exclusive", 400 - ) + abort(400, description="'command'/'commands' and 'script' are mutually exclusive") elif not ("command" in data or "commands" in data or "script" in data): - return make_response("Need one of 'command', 'commands' or 'script'", 400) + abort(400, description="Need one of 'command', 'commands' or 'script'") parameters = {} if "parameters" in data: @@ -440,7 +426,7 @@ def printerCommand(): commands = [data["command"]] else: if not isinstance(data["commands"], (list, tuple)): - return make_response("'commands' needs to be a list", 400) + abort(400, description="commands is invalid") commands = data["commands"] commandsToSend = [] @@ -461,7 +447,7 @@ def printerCommand(): try: printer.script(script_name, context=context, tags=tags) except UnknownScript: - return make_response("Unknown script: {script_name}".format(**locals()), 404) + abort(404, description="Unknown script") return NO_CONTENT @@ -476,7 +462,7 @@ def getCustomControls(): def _get_temperature_data(preprocessor): if not printer.is_operational(): - return make_response("Printer is not operational", 409) + abort(409, description="Printer is not operational") tempData = printer.get_current_temperatures() diff --git a/src/octoprint/server/api/printer_profiles.py b/src/octoprint/server/api/printer_profiles.py index cedf7b71f..01c69675c 100644 --- a/src/octoprint/server/api/printer_profiles.py +++ b/src/octoprint/server/api/printer_profiles.py @@ -8,9 +8,8 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import copy -from flask import jsonify, make_response, request, url_for +from flask import abort, jsonify, request, url_for from past.builtins import basestring -from werkzeug.exceptions import BadRequest from octoprint.access.permissions import Permissions from octoprint.printer.profile import CouldNotOverwriteError, InvalidProfileError @@ -60,18 +59,15 @@ def printerProfilesList(): @Permissions.SETTINGS.require(403) def printerProfilesAdd(): if "application/json" not in request.headers["Content-Type"]: - return make_response("Expected content-type JSON", 400) + abort(400, description="Expected content-type JSON") - try: - json_data = request.get_json() - except BadRequest: - return make_response("Malformed JSON body in request", 400) + json_data = request.get_json() if json_data is None: - return make_response("Malformed JSON body in request", 400) + abort(400, description="Malformed JSON body in request") if "profile" not in json_data: - return make_response("No profile included in request", 400) + abort(400, description="profile is missing") base_profile = printerProfileManager.get_default() if "basedOn" in json_data and isinstance(json_data["basedOn"], basestring): @@ -95,23 +91,20 @@ def printerProfilesAdd(): profile = dict_merge(base_profile, new_profile) if "id" not in profile: - return make_response("Profile does not contain mandatory 'id' field", 400) + abort(400, description="profile.id is missing") if "name" not in profile: - return make_response("Profile does not contain mandatory 'name' field", 400) + abort(400, description="profile.name is missing") try: saved_profile = printerProfileManager.save( profile, allow_overwrite=False, make_default=make_default, trigger_event=True ) except InvalidProfileError: - return make_response("Profile is invalid", 400) + abort(400, description="profile is invalid") except CouldNotOverwriteError: - return make_response( - "Profile already exists and overwriting was not allowed", - 400, - ) + abort(400, description="Profile already exists and overwriting was not allowed") except Exception as e: - return make_response("Could not save profile: %s" % str(e), 500) + abort(500, description="Could not save profile: %s" % str(e)) else: return jsonify({"profile": _convert_profile(saved_profile)}) @@ -122,7 +115,7 @@ def printerProfilesAdd(): def printerProfilesGet(identifier): profile = printerProfileManager.get(identifier) if profile is None: - return make_response("Unknown profile", 404) + abort(404) else: return jsonify(_convert_profile(profile)) @@ -133,11 +126,11 @@ def printerProfilesGet(identifier): def printerProfilesDelete(identifier): current_profile = printerProfileManager.get_current() if current_profile and current_profile["id"] == identifier: - return make_response("Cannot delete currently selected profile", 409) + abort(409, description="Cannot delete currently selected profile") default_profile = printerProfileManager.get_default() if default_profile and default_profile["id"] == identifier: - return make_response("Cannot delete default profile", 409) + abort(409, description="Cannot delete default profile") printerProfileManager.remove(identifier, trigger_event=True) return NO_CONTENT @@ -148,18 +141,14 @@ def printerProfilesDelete(identifier): @Permissions.SETTINGS.require(403) def printerProfilesUpdate(identifier): if "application/json" not in request.headers["Content-Type"]: - return make_response("Expected content-type JSON", 400) - - try: - json_data = request.get_json() - except BadRequest: - return make_response("Malformed JSON body in request", 400) + abort(400, description="Expected content-type JSON") + json_data = request.get_json() if json_data is None: - return make_response("Malformed JSON body in request", 400) + abort(400, description="Malformed JSON body in request") if "profile" not in json_data: - return make_response("No profile included in request", 400) + abort(400, description="profile missing") profile = printerProfileManager.get(identifier) if profile is None: @@ -183,13 +172,11 @@ def printerProfilesUpdate(identifier): trigger_event=True, ) except InvalidProfileError: - return make_response("Profile is invalid", 400) + abort(400, description="profile is invalid") except CouldNotOverwriteError: - return make_response( - "Profile already exists and overwriting was not allowed", 400 - ) + abort(400, description="Profile already exists and overwriting was not allowed") except Exception as e: - return make_response("Could not save profile: %s" % str(e), 500) + abort(500, description="Could not save profile: %s" % str(e)) else: return jsonify({"profile": _convert_profile(saved_profile)}) diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index 3dec04a51..981ac93ed 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -7,10 +7,9 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import logging -from flask import abort, jsonify, make_response, request +from flask import abort, jsonify, request from flask_login import current_user from past.builtins import basestring -from werkzeug.exceptions import BadRequest import octoprint.plugin import octoprint.util @@ -373,22 +372,11 @@ def _get_plugin_settings(): @Permissions.SETTINGS.require(403) def setSettings(): if "application/json" not in request.headers["Content-Type"]: - return make_response("Expected content-type JSON", 400) + abort(400, description="Expected content-type JSON") - try: - data = request.get_json() - except BadRequest: - return make_response("Malformed JSON body in request", 400) - - if data is None: - return make_response("Malformed JSON body in request", 400) - - if not isinstance(data, dict): - return make_response( - "Malformed request, need settings dictionary" - "got a {} instead".format(type(data).__name__), - 400, - ) + data = request.get_json() + if data is None or not isinstance(data, dict): + abort(400, description="Malformed JSON body in request") response = _saveSettings(data) if response: @@ -484,7 +472,7 @@ def _saveSettings(data): s.setBaseFolder(folder, future[folder]) except Exception: - return make_response("At least one of the configured folders is invalid", 400) + abort(400, description="At least one of the configured folders is invalid") if "api" in data: if "allowCrossOrigin" in data["api"]: diff --git a/src/octoprint/server/api/slicing.py b/src/octoprint/server/api/slicing.py index 94db08035..11ab033f8 100644 --- a/src/octoprint/server/api/slicing.py +++ b/src/octoprint/server/api/slicing.py @@ -5,8 +5,7 @@ __author__ = "Gina Häußge " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" -from flask import jsonify, make_response, request, url_for -from werkzeug.exceptions import BadRequest +from flask import abort, jsonify, make_response, request, url_for from octoprint.access.permissions import Permissions from octoprint.server import slicingManager @@ -141,7 +140,7 @@ def slicingListSlicerProfiles(slicer): try: return jsonify(_getSlicingProfilesData(slicer, require_configured=configured)) except (UnknownSlicer, SlicerNotConfigured): - return make_response("Unknown slicer", 404) + abort(404) @api.route("/slicing//profiles/", methods=["GET"]) @@ -151,9 +150,9 @@ def slicingGetSlicerProfile(slicer, name): try: profile = slicingManager.load_profile(slicer, name, require_configured=False) except UnknownSlicer: - return make_response("Unknown slicer", 404) + abort(404) except UnknownProfile: - return make_response("Profile not found", 404) + abort(404) result = _getSlicingProfileData(slicer, name, profile) result["data"] = profile.data @@ -165,15 +164,11 @@ def slicingGetSlicerProfile(slicer, name): @Permissions.SETTINGS.require(403) def slicingAddSlicerProfile(slicer, name): if "application/json" not in request.headers["Content-Type"]: - return make_response("Expected content-type JSON", 400) - - try: - json_data = request.get_json() - except BadRequest: - return make_response("Malformed JSON body in request", 400) + abort(400, description="Expected content-type JSON") + json_data = request.get_json() if json_data is None: - return make_response("Malformed JSON body in request", 400) + abort(400, description="Malformed JSON body in request") data = {} display_name = None @@ -195,7 +190,7 @@ def slicingAddSlicerProfile(slicer, name): description=description, ) except UnknownSlicer: - return make_response("Unknown slicer", 404) + abort(404, description="Unknown slicer") result = _getSlicingProfileData(slicer, name, profile) r = make_response(jsonify(result), 201) @@ -208,22 +203,18 @@ def slicingAddSlicerProfile(slicer, name): @Permissions.SETTINGS.require(403) def slicingPatchSlicerProfile(slicer, name): if "application/json" not in request.headers["Content-Type"]: - return make_response("Expected content-type JSON", 400) + abort(400, description="Expected content-type JSON") try: profile = slicingManager.load_profile(slicer, name, require_configured=False) except UnknownSlicer: - return make_response("Unknown slicer", 404) + return abort(404) except UnknownProfile: - return make_response("Profile for slicer not found", 404) - - try: - json_data = request.get_json() - except BadRequest: - return make_response("Malformed JSON body in request", 400) + return abort(404) + json_data = request.get_json() if json_data is None: - return make_response("Malformed JSON body in request", 400) + abort(400, description="Malformed JSON body in request") data = {} display_name = None @@ -260,11 +251,13 @@ def slicingDelSlicerProfile(slicer, name): try: slicingManager.delete_profile(slicer, name) except UnknownSlicer: - return make_response("Unknown slicer", 404) + abort(404) except CouldNotDeleteProfile as e: - return make_response( - "Could not delete profile for slicer: {cause}".format(cause=str(e.cause)), + abort( 500, + description="Could not delete profile for slicer: {cause}".format( + cause=str(e.cause) + ), ) return NO_CONTENT diff --git a/src/octoprint/server/api/system.py b/src/octoprint/server/api/system.py index 6df204b8a..f863b3a6c 100644 --- a/src/octoprint/server/api/system.py +++ b/src/octoprint/server/api/system.py @@ -10,7 +10,7 @@ import threading import psutil import sarge -from flask import jsonify, make_response, request, url_for +from flask import abort, jsonify, request, url_for from flask_babel import gettext from octoprint.access.permissions import Permissions @@ -87,7 +87,7 @@ def performSystemAction(): data = request.values if "action" not in data: - return make_response("action to perform is not defined", 400) + abort(400, description="action is missing") return executeSystemCommand("custom", data["action"]) @@ -111,7 +111,7 @@ def retrieveSystemCommandsForSource(source): elif source == "custom": specs = _get_custom_command_specs() else: - return make_response("Unknown system command source", 404) + abort(404) return jsonify(_to_client_specs(specs)) @@ -123,16 +123,15 @@ def executeSystemCommand(source, command): logger = logging.getLogger(__name__) if command == "divider": - return make_response("Dividers cannot be executed", 400) + abort(400, description="Dividers cannot be executed") command_spec = _get_command_spec(source, command) if not command_spec: - return make_response("Command not found", 404) + abort(404) if "command" not in command_spec: - return make_response( - "Command does not define a command to execute, can't proceed", - 500, + abort( + 500, description="Command does not define a command to execute, can't proceed" ) do_async = command_spec.get("async", False) @@ -155,7 +154,7 @@ def executeSystemCommand(source, command): if not do_ignore: error = 'Command "before" for {}:{} failed: {}'.format(source, command, e) logger.warning(error) - return make_response(error, 500) + abort(500, description=error) try: @@ -192,13 +191,13 @@ def executeSystemCommand(source, command): try: execute() except CommandFailed as exc: - return make_response(exc.error, 500) + abort(500, exc.error) except Exception as e: if not do_ignore: error = "Command for {}:{} failed: {}".format(source, command, e) logger.warning(error) - return make_response(error, 500) + abort(500, error) return NO_CONTENT diff --git a/src/octoprint/server/api/timelapse.py b/src/octoprint/server/api/timelapse.py index 80c5f2c28..0c630f46b 100644 --- a/src/octoprint/server/api/timelapse.py +++ b/src/octoprint/server/api/timelapse.py @@ -9,7 +9,7 @@ import logging import os import threading -from flask import jsonify, make_response, request, url_for +from flask import abort, jsonify, request, url_for import octoprint.timelapse import octoprint.util as util @@ -182,7 +182,7 @@ def deleteTimelapse(filename): logging.getLogger(__file__).exception( "Error deleting timelapse file {}".format(full_path) ) - return make_response("Unexpected error: {}".format(ex), 500) + abort(500, description="Unexpected error: {}".format(ex)) return getTimelapseData() @@ -208,8 +208,8 @@ def processUnrenderedTimelapseCommand(name): if command == "render": if printer.is_printing() or printer.is_paused(): - return make_response( - "Printer is currently printing, cannot render timelapse", 409 + abort( + 409, description="Printer is currently printing, cannot render timelapse" ) octoprint.timelapse.render_unrendered_timelapse(name) @@ -231,56 +231,56 @@ def setTimelapseConfig(): try: postRoll = int(data["postRoll"]) except ValueError: - return make_response("Invalid value for postRoll", 400) + abort(400, description="postRoll is invalid") else: if postRoll >= 0: config["postRoll"] = postRoll else: - return make_response("Invalid value for postRoll", 400) + abort(400, description="postRoll is invalid") if "fps" in data: try: fps = int(data["fps"]) except ValueError: - return make_response("Invalid value for fps", 400) + abort(400, description="fps is invalid") else: if fps > 0: config["fps"] = fps else: - return make_response("Invalid value for fps", 400) + abort(400, description="fps is invalid") if "interval" in data: try: interval = int(data["interval"]) except ValueError: - return make_response("Invalid value for interval", 400) + abort(400, description="interval is invalid") else: if interval > 0: config["options"]["interval"] = interval else: - return make_response("Invalid value for interval", 400) + abort(400, description="interval is invalid") if "retractionZHop" in data: try: retractionZHop = float(data["retractionZHop"]) except ValueError: - return make_response("Invalid value for retraction z-hop", 400) + abort(400, description="retractionZHop is invalid") else: if retractionZHop >= 0: config["options"]["retractionZHop"] = retractionZHop else: - return make_response("Invalid value for retraction z-hop", 400) + abort(400, description="retractionZHop is invalid") if "minDelay" in data: try: minDelay = float(data["minDelay"]) except ValueError: - return make_response("Invalid value for minimum delay", 400) + abort(400, description="minDelay is invalid") else: if minDelay > 0: config["options"]["minDelay"] = minDelay else: - return make_response("Invalid value for minimum delay", 400) + abort(400, description="minDelay is invalid") if ( admin_permission.can() diff --git a/src/octoprint/server/util/__init__.py b/src/octoprint/server/util/__init__.py index bf1226797..f92d153c3 100644 --- a/src/octoprint/server/util/__init__.py +++ b/src/octoprint/server/util/__init__.py @@ -46,7 +46,7 @@ def loginFromApiKeyRequestHandler(): if loginUserFromApiKey(): _flask.g.login_via_apikey = True except InvalidApiKeyException: - return _flask.make_response("Invalid API key", 403) + _flask.abort(403) def loginFromAuthorizationHeaderRequestHandler(): @@ -57,7 +57,7 @@ def loginFromAuthorizationHeaderRequestHandler(): if loginUserFromAuthorizationHeader(): _flask.g.login_via_header = True except InvalidApiKeyException: - return _flask.make_response("Invalid API key", 403) + _flask.abort(403) class InvalidApiKeyException(Exception): @@ -118,7 +118,7 @@ def requireLoginRequestHandler(): user = flask_login.current_user if user is None or user.is_anonymous or not user.is_active: - return flask.make_response("Forbidden", 403) + _flask.abort(403) def corsRequestHandler(): diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index e565461bb..b5aa8597d 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -1305,11 +1305,13 @@ def with_revalidation_checking( def decorator(f): @functools.wraps(f) def decorated_function(*args, **kwargs): + from octoprint.server import NOT_MODIFIED + lm = lastmodified_factory() etag = etag_factory(lm) if condition(lm, etag) and not unless(): - return make_response("Not Modified", 304) + return NOT_MODIFIED # generate response response = f(*args, **kwargs) @@ -1544,7 +1546,7 @@ def no_firstrun_access(func): octoprint.server.userManager is None or not octoprint.server.userManager.has_been_customized() ): - return flask.make_response("OctoPrint isn't setup yet", 403) + flask.abort(403) return func(*args, **kwargs) return decorated_view @@ -1566,9 +1568,7 @@ def firstrun_only_access(func): ): return func(*args, **kwargs) else: - return flask.make_response( - "OctoPrint is already setup, this resource is not longer available.", 403 - ) + flask.abort(403) return decorated_view @@ -1583,34 +1583,56 @@ def get_remote_address(request): def get_json_command_from_request(request, valid_commands): content_type = request.headers.get("Content-Type", None) if content_type is None or "application/json" not in content_type: - return None, None, make_response("Expected content-type JSON", 400) + flask.abort(400, description="Expected content-type JSON") data = request.get_json() if data is None: - return ( - None, - None, - make_response("Malformed JSON body or wrong content-type in request", 400), + flask.abort( + 400, description="Malformed JSON body or wrong content-type in request" ) if "command" not in data or data["command"] not in valid_commands: - return None, None, make_response("Expected valid command", 400) + flask.abort(400, description="command is invalid") command = data["command"] - for parameter in valid_commands[command]: - if parameter not in data: - return ( - None, - None, - make_response( - "Mandatory parameter %s missing for command %s" - % (parameter, command), - 400, - ), - ) + if any(map(lambda x: x not in data, valid_commands[command])): + flask.abort(400, description="Mandatory parameters missing") return command, data, None +def make_text_response(message, status): + """ + Helper to generate basic text responses. + + Response will have the provided message as body, the provided status code, and + a content type of "text/plain". + + Args: + message: The message in the response body + status: The HTTP status code + + Returns: + + """ + return make_response(message, status, {"Content-Type": "text/plain"}) + + +def make_api_error(message, status): + """ + Helper to generate API error responses in JSON format. + + Turns something like ``make_api_error("Not Found", 404)`` into a JSON response + with body ``{"error": "Not Found"}``. + + Args: + message: The error message to put into the response + status: The HTTP status code + + Returns: a flask response to return to the client + """ + return make_response(flask.jsonify(error=message), status) + + ##~~ Flask-Assets resolver with plugin asset support From cf2ce1e88bc6755ae6d398112f1fddbeb7b8abcd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 10 Mar 2021 21:54:36 +0100 Subject: [PATCH 20/43] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Default=20to=20JSON?= =?UTF-8?q?=20api=20errors=20for=20blueprints=20as=20well?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Behaviour can be overwritten via BluePrintPlugin .get_blueprint_api_prefixes. --- src/octoprint/plugin/types.py | 15 ++++++++++++++- src/octoprint/server/__init__.py | 13 +++++++++++-- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index b3db80d55..7a50727d6 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -1477,9 +1477,22 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin): If you want your blueprint's endpoints to have specific permissions, return ``False`` for this and do your permissions checks explicitly. """ - return True + # noinspection PyMethodMayBeStatic + def get_blueprint_api_prefixes(self): + """ + Return all prefixes of your endpoint that are an API that should be containing JSON only. + + Anything that matches this will generate JSON error messages in case of flask.abort + calls, instead of the default HTML ones. + + Defaults to all endpoints under the blueprint. Limit this further as needed. E.g., + if you only want your endpoints /foo, /foo/1 and /bar to be declared as API, + return ``["/foo", "/bar"]``. A match will be determined via startswith. + """ + return [""] + class SettingsPlugin(OctoPrintPlugin): """ diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 28e06a9e7..2d36f1f41 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -1741,7 +1741,12 @@ class Server(object): json_errors = ["/api"] # also register any blueprints defined in BlueprintPlugins - blueprints.update(self._prepare_blueprint_plugins()) + ( + blueprint_from_plugins, + api_prefixes_from_plugins, + ) = self._prepare_blueprint_plugins() + blueprints.update(blueprint_from_plugins) + json_errors += api_prefixes_from_plugins # and register a blueprint for serving the static files of asset plugins which are not blueprint plugins themselves blueprints.update(self._prepare_asset_plugins()) @@ -1762,6 +1767,7 @@ class Server(object): def _prepare_blueprint_plugins(self): blueprints = OrderedDict() + api_prefixes = [] blueprint_plugins = octoprint.plugin.plugin_manager().get_implementations( octoprint.plugin.BlueprintPlugin @@ -1769,6 +1775,9 @@ class Server(object): for plugin in blueprint_plugins: try: blueprint, prefix = self._prepare_blueprint_plugin(plugin) + api_prefixes += map( + lambda x: prefix + x, plugin.get_blueprint_api_prefixes() + ) blueprints[prefix] = blueprint except Exception: self._logger.exception( @@ -1778,7 +1787,7 @@ class Server(object): ) continue - return blueprints + return blueprints, api_prefixes def _prepare_asset_plugins(self): blueprints = OrderedDict() From f9745515e1755f6d3f3319279fc9ff3d14a0bf35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 11 Mar 2021 14:34:06 +0100 Subject: [PATCH 21/43] =?UTF-8?q?=F0=9F=8E=A8=20Add=20pyupgrade?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/build.yml | 78 ++----------------- .pre-commit-config.yaml | 11 +-- src/octoprint/_version.py | 4 +- src/octoprint/cli/dev.py | 4 +- src/octoprint/events.py | 2 +- src/octoprint/plugin/core.py | 6 +- src/octoprint/plugins/appkeys/__init__.py | 7 +- src/octoprint/plugins/backup/__init__.py | 4 +- src/octoprint/plugins/corewizard/__init__.py | 12 +-- src/octoprint/plugins/logging/__init__.py | 6 +- .../plugins/softwareupdate/__init__.py | 14 ++-- .../plugins/softwareupdate/updaters/pip.py | 2 +- .../softwareupdate/updaters/update_script.py | 10 ++- .../version_checks/bitbucket_commit.py | 4 +- .../version_checks/commandline.py | 4 +- .../version_checks/git_commit.py | 2 +- .../version_checks/github_commit.py | 4 +- .../version_checks/github_release.py | 8 +- .../plugins/virtual_printer/virtual.py | 2 +- src/octoprint/printer/profile.py | 2 +- src/octoprint/server/__init__.py | 10 +-- src/octoprint/server/api/settings.py | 6 +- src/octoprint/server/api/system.py | 8 +- src/octoprint/server/util/tornado.py | 12 ++- src/octoprint/settings.py | 6 +- src/octoprint/util/__init__.py | 8 +- src/octoprint/util/comm.py | 2 +- src/octoprint/util/commandline.py | 6 +- tests/plugin/test_core.py | 8 +- tests/settings/test_settings.py | 2 +- tests/timelapse/test_timelapse_helpers.py | 2 +- tests/util/test_comm_helpers.py | 4 +- versioneer.py | 16 ++-- 33 files changed, 104 insertions(+), 172 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index d0ac38df5..ada193c26 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -30,8 +30,8 @@ jobs: name: dist path: dist - lint-black: - name: 🧹 black + pre-commit: + name: 🧹 Pre-commit runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 @@ -42,73 +42,9 @@ jobs: - name: 🏗 Set up dev dependencies run: | pip install -e .[develop] - - name: 🚀 Run black + - name: 🚀 Run pre-commit run: | - pre-commit run --hook-stage manual black --all-files --show-diff-on-failure - - lint-isort: - name: 🧹 isort - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: 🏗 Set up Python 3.7 - uses: actions/setup-python@v1 - with: - python-version: 3.7 - - name: 🏗 Set up dev dependencies - run: | - pip install -e .[develop] - - name: 🚀 Run isort - run: | - pre-commit run --hook-stage manual isort --all-files --show-diff-on-failure - - lint-flake8: - name: 🧹 Flake8 - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: 🏗 Set up Python 3.7 - uses: actions/setup-python@v1 - with: - python-version: 3.7 - - name: 🏗 Set up dev dependencies - run: | - pip install -e .[develop] - - name: 🚀 Run flake8 - run: | - pre-commit run --hook-stage manual flake8 --all-files - - lint-prettier: - name: 🧹 prettier - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: 🏗 Set up Python 3.7 - uses: actions/setup-python@v1 - with: - python-version: 3.7 - - name: 🏗 Set up dev dependencies - run: | - pip install -e .[develop] - - name: 🚀 Run prettier - run: | - pre-commit run --hook-stage manual prettier --all-files --show-diff-on-failure - - lint-eslint: - name: 🧹 eslint - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: 🏗 Set up Python 3.7 - uses: actions/setup-python@v1 - with: - python-version: 3.7 - - name: 🏗 Set up dev dependencies - run: | - pip install -e .[develop] - - name: 🚀 Run eslint - run: | - pre-commit run --hook-stage manual eslint --all-files + pre-commit run --all-files --show-diff-on-failure test-unit: name: 🧪 Unit tests @@ -207,11 +143,7 @@ jobs: name: 📦 Publish on TestPyPI if: github.event_name == 'release' needs: - - lint-black - - lint-isort - - lint-flake8 - - lint-prettier - - lint-eslint + - pre-commit - test-unit - test-install - test-e2e diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 1db0fb13e..26e4d5b16 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -11,18 +11,15 @@ repos: - id: check-toml - id: check-merge-conflict - id: fix-encoding-pragma + - repo: https://github.com/asottile/pyupgrade + rev: v2.10.0 + hooks: + - id: pyupgrade - repo: https://github.com/OctoPrint/codemods rev: devel hooks: - - id: codemod_dict_to_literal - args: ["--ignore", "src/octoprint/vendor"] - stages: ["manual"] - - id: codemod_set_to_literal - args: ["--ignore", "src/octoprint/vendor"] - stages: ["manual"] - id: codemod_not_in args: ["--ignore", "src/octoprint/vendor"] - stages: ["manual"] - repo: https://github.com/pre-commit/mirrors-isort rev: v5.5.4 hooks: diff --git a/src/octoprint/_version.py b/src/octoprint/_version.py index 5c78ec1f9..3884142d1 100644 --- a/src/octoprint/_version.py +++ b/src/octoprint/_version.py @@ -100,7 +100,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False): return None else: if verbose: - print("unable to find command, tried %s" % (commands,)) + print("unable to find command, tried {}".format(commands)) return None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: @@ -302,7 +302,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) - pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % ( + pieces["error"] = "tag '{}' doesn't start with prefix '{}'".format( full_tag, tag_prefix, ) diff --git a/src/octoprint/cli/dev.py b/src/octoprint/cli/dev.py index 048bb7805..51f85bd9c 100644 --- a/src/octoprint/cli/dev.py +++ b/src/octoprint/cli/dev.py @@ -196,9 +196,7 @@ class OctoPrintDevelCommands(click.MultiCommand): "plugin_source": source, "plugin_installurl": installurl, } - options = dict( - (k, v) for k, v in raw_options.items() if v is not None - ) + options = {k: v for k, v in raw_options.items() if v is not None} with custom_cookiecutter_prompt(options): cookiecutter.main.cookiecutter( diff --git a/src/octoprint/events.py b/src/octoprint/events.py index fd4847181..eb2e0878e 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -325,7 +325,7 @@ class DebugEventListener(GenericEventListener): def eventCallback(self, event, payload): GenericEventListener.eventCallback(self, event, payload) - self._logger.debug("Received event: %s (Payload: %r)" % (event, payload)) + self._logger.debug("Received event: {} (Payload: {!r})".format(event, payload)) class CommandTrigger(GenericEventListener): diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index c7ce091a6..b84a8157e 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -1341,9 +1341,7 @@ class PluginManager(object): force_reload = [] added, found = self.find_plugins( - existing=dict( - (k, v) for k, v in self.plugins.items() if k not in force_reload - ), + existing={k: v for k, v in self.plugins.items() if k not in force_reload}, incl_all_found=True, ) @@ -2194,7 +2192,7 @@ class PluginManager(object): all_helpers = plugin.helpers if len(helpers): - return dict((k, v) for (k, v) in all_helpers.items() if k in helpers) + return {k: v for (k, v) in all_helpers.items() if k in helpers} else: return all_helpers diff --git a/src/octoprint/plugins/appkeys/__init__.py b/src/octoprint/plugins/appkeys/__init__.py index 326b95f18..f9b77d481 100644 --- a/src/octoprint/plugins/appkeys/__init__.py +++ b/src/octoprint/plugins/appkeys/__init__.py @@ -246,10 +246,9 @@ class AppKeysPlugin( return flask.jsonify( keys=list(map(lambda x: x.external(), keys)), - pending=dict( - (x.user_token, x.external()) - for x in self._get_pending_by_user_id(user_id) - ), + pending={ + x.user_token: x.external() for x in self._get_pending_by_user_id(user_id) + }, ) def on_api_command(self, command, data): diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index 3094a8688..f8e324e68 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -864,9 +864,7 @@ class BackupPlugin( from octoprint.plugins.pluginmanager import map_repository_entry - return dict( - (plugin["id"], plugin) for plugin in map(map_repository_entry, r.json()) - ) + return {plugin["id"]: plugin for plugin in map(map_repository_entry, r.json())} @classmethod def _install_plugin( diff --git a/src/octoprint/plugins/corewizard/__init__.py b/src/octoprint/plugins/corewizard/__init__.py index d5fbec327..3416ce750 100644 --- a/src/octoprint/plugins/corewizard/__init__.py +++ b/src/octoprint/plugins/corewizard/__init__.py @@ -33,11 +33,11 @@ class CoreWizardPlugin( firstrun = self._settings.global_get(["server", "firstRun"]) if not firstrun: - required = dict( - (key, value) + required = { + key: value for key, value in required.items() if not firstrunonly.get(key, lambda: False)() - ) + } result = list() for key, method in required.items(): @@ -85,11 +85,11 @@ class CoreWizardPlugin( firstrun = self._settings.global_get(["server", "firstRun"]) if not firstrun: - required = dict( - (key, value) + required = { + key: value for key, value in required.items() if not firstrunonly.get(key, lambda: False)() - ) + } any_required = any(map(lambda m: m(), required.values())) return any_required diff --git a/src/octoprint/plugins/logging/__init__.py b/src/octoprint/plugins/logging/__init__.py index 3e8728ca4..a1c8b57cb 100644 --- a/src/octoprint/plugins/logging/__init__.py +++ b/src/octoprint/plugins/logging/__init__.py @@ -199,11 +199,11 @@ class LoggingPlugin( if config is None or not isinstance(config, dict): return {} - return dict( - (key, value.get("level")) + return { + key: value.get("level") for key, value in config.get("loggers", {}).items() if isinstance(value, dict) and "level" in value - ) + } def _set_logging_levels(self, new_levels): import logging diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index 550cefcdd..9203baa7d 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -1642,11 +1642,11 @@ class SoftwareUpdatePlugin( updater_thread.daemon = False updater_thread.start() - check_data = dict( - (key, check["displayName"] if "displayName" in check else key) + check_data = { + key: check["displayName"] if "displayName" in check else key for key, check in populated_checks.items() if key in to_be_updated - ) + } return to_be_updated, check_data def _update_worker(self, checks, check_targets, force): @@ -1805,7 +1805,9 @@ class SoftwareUpdatePlugin( populated_check = self._populated_check(target, check) try: - self._logger.info("Starting update of %s to %s..." % (target, target_version)) + self._logger.info( + "Starting update of {} to {}...".format(target, target_version) + ) self._send_client_message( "updating", { @@ -1822,7 +1824,9 @@ class SoftwareUpdatePlugin( target, populated_check, target_version, log_cb=self._log, online=online ) target_result = ("success", update_result) - self._logger.info("Update of %s to %s successful!" % (target, target_version)) + self._logger.info( + "Update of {} to {} successful!".format(target, target_version) + ) trigger_event(True) except exceptions.UnknownUpdateType: diff --git a/src/octoprint/plugins/softwareupdate/updaters/pip.py b/src/octoprint/plugins/softwareupdate/updaters/pip.py index 4a6e234ff..61923ac5b 100644 --- a/src/octoprint/plugins/softwareupdate/updaters/pip.py +++ b/src/octoprint/plugins/softwareupdate/updaters/pip.py @@ -101,7 +101,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc target_version=target_version, target=target_version ) - logger.debug("Target: %s, executing pip install %s" % (target, install_arg)) + logger.debug("Target: {}, executing pip install {}".format(target, install_arg)) pip_args = ["--disable-pip-version-check", "install", install_arg, "--no-cache-dir"] pip_kwargs = { "env": {"PYTHONWARNINGS": b"ignore:DEPRECATION::pip._internal.cli.base_command"} diff --git a/src/octoprint/plugins/softwareupdate/updaters/update_script.py b/src/octoprint/plugins/softwareupdate/updaters/update_script.py index 9b5b47fec..e2a3465a6 100644 --- a/src/octoprint/plugins/softwareupdate/updaters/update_script.py +++ b/src/octoprint/plugins/softwareupdate/updaters/update_script.py @@ -82,7 +82,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True): if pre_update_script is not None: logger.debug( - "Target: %s, running pre-update script: %s" % (target, pre_update_script) + "Target: {}, running pre-update script: {}".format(target, pre_update_script) ) try: caller.checked_call(pre_update_script, cwd=folder) @@ -103,7 +103,9 @@ def perform_update(target, check, target_version, log_cb=None, online=True): force="true" if force_exact_version else "false", ) - logger.debug("Target %s, running update script: %s" % (target, update_command)) + logger.debug( + "Target {}, running update script: {}".format(target, update_command) + ) caller.checked_call(update_command, cwd=folder) except CommandlineError as e: @@ -119,7 +121,9 @@ def perform_update(target, check, target_version, log_cb=None, online=True): if post_update_script is not None: logger.debug( - "Target: %s, running post-update script %s..." % (target, post_update_script) + "Target: {}, running post-update script {}...".format( + target, post_update_script + ) ) try: caller.checked_call(post_update_script, cwd=folder) diff --git a/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py b/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py index 0676b1a2d..f94086742 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py @@ -93,6 +93,8 @@ def get_latest(target, check, online=True, credentials=None, *args, **kwargs): current is not None and current == remote_commit ) or remote_commit is None - logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_commit)) + logger.debug( + "Target: {}, local: {}, remote: {}".format(target, current, remote_commit) + ) return information, is_current diff --git a/src/octoprint/plugins/softwareupdate/version_checks/commandline.py b/src/octoprint/plugins/softwareupdate/version_checks/commandline.py index 634b8eb8e..f344cff2d 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/commandline.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/commandline.py @@ -59,6 +59,8 @@ def get_latest(target, check, online=True, *args, **kwargs): logger = logging.getLogger( "octoprint.plugins.softwareupdate.version_checks.github_commit" ) - logger.debug("Target: %s, local: %s, remote: %s" % (target, local_name, remote_name)) + logger.debug( + "Target: {}, local: {}, remote: {}".format(target, local_name, remote_name) + ) return information, is_current diff --git a/src/octoprint/plugins/softwareupdate/version_checks/git_commit.py b/src/octoprint/plugins/softwareupdate/version_checks/git_commit.py index 99c8052a0..02135b7fd 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/git_commit.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/git_commit.py @@ -101,7 +101,7 @@ def get_latest(target, check, online=True, *args, **kwargs): "octoprint.plugins.softwareupdate.version_checks.git_commit" ) logger.debug( - "Target: %s, local: %s, remote: %s" % (target, local_commit, remote_commit) + "Target: {}, local: {}, remote: {}".format(target, local_commit, remote_commit) ) return information, is_current diff --git a/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py b/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py index cc1d680de..d20a28d20 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py @@ -97,6 +97,8 @@ def get_latest(target, check, online=True, credentials=None, *args, **kwargs): current is not None and current == remote_commit ) or remote_commit is None - logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_commit)) + logger.debug( + "Target: {}, local: {}, remote: {}".format(target, current, remote_commit) + ) return information, is_current diff --git a/src/octoprint/plugins/softwareupdate/version_checks/github_release.py b/src/octoprint/plugins/softwareupdate/version_checks/github_release.py index d8bf8a144..702c36308 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/github_release.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/github_release.py @@ -323,10 +323,10 @@ def get_latest( prerelease_branches = check.get("prerelease_branches", None) if prerelease_branches: # fetch valid commitish list from configured prerelease_branches for selected channel - commitishes = dict( - (x["branch"], x.get("commitish", [x["branch"]])) + commitishes = { + x["branch"]: x.get("commitish", [x["branch"]]) for x in prerelease_branches - ) + } commitish = commitishes.get(prerelease_channel, [prerelease_channel]) force_base = check.get("force_base", False) @@ -360,7 +360,7 @@ def get_latest( "release_notes": release_notes, } - logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_tag)) + logger.debug("Target: {}, local: {}, remote: {}".format(target, current, remote_tag)) return information, _is_current( information, compare_type, custom=custom_compare, force_base=force_base diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py index 62b8011c7..0a7c4b605 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -705,7 +705,7 @@ class VirtualPrinter(object): def _gcode_M114(self, data): # type: (str) -> bool m114FormatString = self._settings.get(["m114FormatString"]) - e = dict((index, value) for index, value in enumerate(self._lastE)) + e = {index: value for index, value in enumerate(self._lastE)} e["current"] = self._lastE[self.currentExtruder] e["all"] = " ".join( [ diff --git a/src/octoprint/printer/profile.py b/src/octoprint/printer/profile.py index c826df750..3a96adc0f 100644 --- a/src/octoprint/printer/profile.py +++ b/src/octoprint/printer/profile.py @@ -556,7 +556,7 @@ class PrinterProfileManager(object): self._logger.exception( "Error while trying to save profile %s" % profile["id"] ) - raise SaveError("Cannot save profile %s: %s" % (profile["id"], str(e))) + raise SaveError("Cannot save profile {}: {}".format(profile["id"], str(e))) def _remove_from_path(self, path): try: diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 2d36f1f41..66580108f 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -1429,7 +1429,7 @@ class Server(object): result.add(locale.language) if locale.territory: # if a territory is specified, add that too - result.add("%s_%s" % (locale.language, locale.territory)) + result.add("{}_{}".format(locale.language, locale.territory)) return result @@ -1655,11 +1655,11 @@ class Server(object): continue additional_request_data = kwargs.get("_additional_request_data", {}) - kwargs = dict( - (k, v) + kwargs = { + k: v for k, v in kwargs.items() if not k.startswith("_") and not k == "plugin" - ) + } kwargs.update(additional_request_data) try: @@ -2357,7 +2357,7 @@ class Server(object): break else: self.send_response(404) - self.wfile.write("Not found".encode("utf-8")) + self.wfile.write(b"Not found") base_path = os.path.realpath( os.path.join(os.path.dirname(__file__), "..", "static") diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index 981ac93ed..b6b03ea55 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -446,10 +446,10 @@ def _saveSettings(data): if "folder" in data: try: - folders = dict( - (FOLDER_MAPPING.get(folder, folder), path) + folders = { + FOLDER_MAPPING.get(folder, folder): path for folder, path in data["folder"].items() - ) + } future = {} for folder in FOLDER_TYPES: future[folder] = s.getBaseFolder(folder) diff --git a/src/octoprint/server/api/system.py b/src/octoprint/server/api/system.py index f863b3a6c..f7ca6faca 100644 --- a/src/octoprint/server/api/system.py +++ b/src/octoprint/server/api/system.py @@ -207,11 +207,9 @@ def _to_client_specs(specs): for spec in specs.values(): if "action" not in spec or "source" not in spec: continue - copied = dict( - (k, v) - for k, v in spec.items() - if k in ("source", "action", "name", "confirm") - ) + copied = { + k: v for k, v in spec.items() if k in ("source", "action", "name", "confirm") + } copied["resource"] = url_for( ".executeSystemCommand", source=spec["source"], diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py index bc2327db9..e49bd80bd 100644 --- a/src/octoprint/server/util/tornado.py +++ b/src/octoprint/server/util/tornado.py @@ -235,9 +235,7 @@ class UploadStorageFallbackHandler(RequestlessExceptionLoggingMixin, CorsSupport self._file_suffix = file_suffix self._path = path - self._suffixes = dict( - (key, key) for key in ("name", "path", "content_type", "size") - ) + self._suffixes = {key: key for key in ("name", "path", "content_type", "size")} for suffix_type, suffix in suffixes.items(): if suffix_type in self._suffixes and suffix is not None: self._suffixes[suffix_type] = suffix @@ -538,9 +536,9 @@ class UploadStorageFallbackHandler(RequestlessExceptionLoggingMixin, CorsSupport if "content_type" in part: parameters["content_type"] = part["content_type"] - fields = dict( - (self._suffixes[key], value) for (key, value) in parameters.items() - ) + fields = { + self._suffixes[key]: value for (key, value) in parameters.items() + } for n, p in fields.items(): if n is None or p is None: continue @@ -1349,7 +1347,7 @@ class UrlProxyHandler( if not extension: return None - return "%s%s" % (self._basename, extension) + return "{}{}".format(self._basename, extension) class StaticDataHandler( diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 103c0eb4a..8abfaf712 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -1634,9 +1634,9 @@ class Settings(object): def _validate_config(self): # validate uniqueness of folder paths folder_keys = self.get(["folder"], merged=True).keys() - folders = dict( - (folder_key, self.getBaseFolder(folder_key)) for folder_key in folder_keys - ) + folders = { + folder_key: self.getBaseFolder(folder_key) for folder_key in folder_keys + } if len(folders.values()) != len(set(folders.values())): raise DuplicateFolderPaths(folders) diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index c2006027b..6648645bf 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -348,9 +348,9 @@ def get_formatted_size(num): for x in ["B", "KB", "MB", "GB"]: if num < 1024: - return "%3.1f%s" % (num, x) + return "{:3.1f}{}".format(num, x) num /= 1024 - return "%3.1f%s" % (num, "TB") + return "{:3.1f}{}".format(num, "TB") def is_allowed_file(filename, extensions): @@ -1079,7 +1079,7 @@ def dict_filter(dictionary, filter_function): """ assert isinstance(dictionary, dict) assert callable(filter_function) - return dict((k, v) for k, v in dictionary.items() if filter_function(k, v)) + return {k: v for k, v in dictionary.items() if filter_function(k, v)} # Source: http://stackoverflow.com/a/6190500/562769 @@ -1123,7 +1123,7 @@ class DefaultOrderedDict(collections.OrderedDict): # noinspection PyMethodOverriding def __repr__(self): - return "OrderedDefaultDict(%s, %s)" % ( + return "OrderedDefaultDict({}, {})".format( self.default_factory, collections.OrderedDict.__repr__(self), ) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 3aa8ac19a..6dcc9f3b7 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -337,7 +337,7 @@ class PositionRecord(object): def as_dict(self): attrs = self._standard_attrs | {key for key in dir(self) if self.valid_e(key)} - return dict((attr, getattr(self, attr)) for attr in attrs) + return {attr: getattr(self, attr) for attr in attrs} class TemperatureRecord(object): diff --git a/src/octoprint/util/commandline.py b/src/octoprint/util/commandline.py index b45358ce1..24e17bd9d 100644 --- a/src/octoprint/util/commandline.py +++ b/src/octoprint/util/commandline.py @@ -176,9 +176,9 @@ class CommandlineCaller(object): # if we are running under windows, make sure there are no unicode strings in the env if get_os() == "windows" and "env" in kwargs: - kwargs["env"] = dict( - (to_native_str(k), to_native_str(v)) for k, v in kwargs["env"].items() - ) + kwargs["env"] = { + to_native_str(k): to_native_str(v) for k, v in kwargs["env"].items() + } delimiter = kwargs.get("delimiter", b"\n") try: diff --git a/tests/plugin/test_core.py b/tests/plugin/test_core.py index f58fe2f97..e15fd3364 100644 --- a/tests/plugin/test_core.py +++ b/tests/plugin/test_core.py @@ -341,7 +341,7 @@ class PluginTestCase(unittest.TestCase): @ddt.unpack def test_has_any_of_hooks(self, hooks_to_test_for, plugin_hooks, expected): plugin = mock.MagicMock() - plugin.hooks = dict((hook, hook) for hook in plugin_hooks) + plugin.hooks = {hook: hook for hook in plugin_hooks} actual = octoprint.plugin.core.PluginManager.has_any_of_hooks( plugin, hooks_to_test_for @@ -350,9 +350,9 @@ class PluginTestCase(unittest.TestCase): def test_has_any_of_hooks_varargs(self): plugin = mock.MagicMock() - plugin.hooks = dict( - (hook, hook) for hook in ["octoprint.some_hook", "octoprint.another_hook"] - ) + plugin.hooks = { + hook: hook for hook in ["octoprint.some_hook", "octoprint.another_hook"] + } result = octoprint.plugin.core.PluginManager.has_any_of_hooks( plugin, "octoprint.some_hook", "octoprint.some_other_hook" diff --git a/tests/settings/test_settings.py b/tests/settings/test_settings.py index e2bd2ac52..2535518e4 100644 --- a/tests/settings/test_settings.py +++ b/tests/settings/test_settings.py @@ -311,7 +311,7 @@ class TestSettings(unittest.TestCase): self.assertGreater(len(data), 1) test_dict = {"enabled": True, "sendWait": True, "waitInterval": 1.0} - test_data = dict((k, v) for k, v in data.items() if k in test_dict) + test_data = {k: v for k, v in data.items() if k in test_dict} self.assertEqual(test_dict, test_data) def test_get_multiple(self): diff --git a/tests/timelapse/test_timelapse_helpers.py b/tests/timelapse/test_timelapse_helpers.py index e1893ab72..05ef704de 100644 --- a/tests/timelapse/test_timelapse_helpers.py +++ b/tests/timelapse/test_timelapse_helpers.py @@ -111,7 +111,7 @@ class TimelapseTest(unittest.TestCase): "tmp_00000.jpg", "tmp_00001.jpg", ] - files = dict((f, None) for f in files) + files = {f: None for f in files} files["old-0.jpg"] = _stat(st_size=10, st_ctime=0, st_mtime=0) now = self.now diff --git a/tests/util/test_comm_helpers.py b/tests/util/test_comm_helpers.py index 1d1969b65..24f76f3e3 100644 --- a/tests/util/test_comm_helpers.py +++ b/tests/util/test_comm_helpers.py @@ -113,14 +113,14 @@ class TestCommHelpers(unittest.TestCase): return m.hexdigest() # rb'' doesn't exist in Python2 - temp_regex = r"T:((\d*\.)\d+)".encode("utf-8") + temp_regex = br"T:((\d*\.)\d+)" temp_template = b"Temp: {}" temp2_template = b"Temperature: {}" temp_key = md5sum(temp_regex) temp_template_key = md5sum(temp_template) temp2_template_key = md5sum(temp2_template) - x_regex = r"X:(?P\d+)".encode("utf-8") + x_regex = br"X:(?P\d+)" x_template = b"X: {x}" x_key = md5sum(x_regex) x_template_key = md5sum(x_template) diff --git a/versioneer.py b/versioneer.py index 87cd8d168..46342e84f 100644 --- a/versioneer.py +++ b/versioneer.py @@ -504,7 +504,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False): return None else: if verbose: - print("unable to find command, tried %s" % (commands,)) + print("unable to find command, tried {}".format(commands)) return None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: @@ -656,11 +656,11 @@ def git_get_keywords(versionfile_abs): f = io.open(versionfile_abs, "rt", encoding="utf-8") for line in f.readlines(): if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) + mo = re.search(r'=\\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) + mo = re.search(r'=\\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) f.close() @@ -692,7 +692,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set(r for r in refs if re.search(r'\d', r)) + tags = set(r for r in refs if re.search(r'\\d', r)) if verbose: print("discarding '%%s', no digits" %% ",".join(refs-tags)) @@ -784,7 +784,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if "-" in git_describe: # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) + mo = re.search(r'^(.+)-(\\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%%s'" @@ -1385,7 +1385,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) - pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % ( + pieces["error"] = "tag '{}' doesn't start with prefix '{}'".format( full_tag, tag_prefix, ) @@ -1615,7 +1615,7 @@ def write_to_version_file(filename, versions): with io.open(filename, "wt", encoding="utf-8") as f: f.write(SHORT_VERSION_PY % contents) - print("set %s to '%s'" % (filename, versions["version"])) + print("set {} to '{}'".format(filename, versions["version"])) def plus_or_dot(pieces): @@ -1890,7 +1890,7 @@ def get_versions(verbose=False): try: ver = versions_from_file(versionfile_abs) if verbose: - print("got version from file %s %s" % (versionfile_abs, ver)) + print("got version from file {} {}".format(versionfile_abs, ver)) return ver except NotThisMethod: pass From fd2ece0f133556f30175ca001cb3084914db34d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 11 Mar 2021 16:01:02 +0100 Subject: [PATCH 22/43] =?UTF-8?q?=F0=9F=8E=A8=20pyupgrade=20--py37-plus?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .pre-commit-config.yaml | 1 + setup.py | 2 +- src/octoprint/__init__.py | 15 ++- src/octoprint/_version.py | 7 +- src/octoprint/access/groups.py | 9 +- src/octoprint/access/users.py | 23 ++-- src/octoprint/cli/analysis.py | 2 +- src/octoprint/cli/client.py | 17 ++- src/octoprint/cli/dev.py | 6 +- src/octoprint/cli/plugins.py | 2 +- src/octoprint/cli/server.py | 6 +- src/octoprint/cli/systeminfo.py | 6 +- src/octoprint/cli/user.py | 20 ++-- src/octoprint/daemon.py | 11 +- src/octoprint/environment.py | 2 +- src/octoprint/events.py | 18 ++- src/octoprint/filemanager/__init__.py | 10 +- src/octoprint/filemanager/analysis.py | 32 +++-- src/octoprint/filemanager/storage.py | 27 ++--- src/octoprint/filemanager/util.py | 2 +- src/octoprint/logging/filters.py | 2 +- src/octoprint/plugin/__init__.py | 6 +- src/octoprint/plugin/core.py | 33 +++--- .../action_command_notification/__init__.py | 2 +- .../plugins/action_command_prompt/__init__.py | 14 +-- .../plugins/announcements/__init__.py | 15 +-- src/octoprint/plugins/appkeys/__init__.py | 9 +- src/octoprint/plugins/backup/__init__.py | 39 +++--- src/octoprint/plugins/corewizard/__init__.py | 6 +- src/octoprint/plugins/discovery/__init__.py | 22 ++-- src/octoprint/plugins/logging/__init__.py | 5 +- src/octoprint/plugins/pi_support/__init__.py | 13 +- .../plugins/pluginmanager/__init__.py | 71 ++++------- .../plugins/softwareupdate/__init__.py | 51 +++----- src/octoprint/plugins/softwareupdate/cli.py | 4 +- .../plugins/softwareupdate/exceptions.py | 2 +- .../scripts/update-octoprint.py | 26 ++-- .../plugins/softwareupdate/updaters/pip.py | 2 +- .../updaters/single_file_plugin.py | 21 ++-- .../softwareupdate/updaters/update_script.py | 8 +- src/octoprint/plugins/softwareupdate/util.py | 4 +- .../softwareupdate/version_checks/__init__.py | 2 +- .../version_checks/bitbucket_commit.py | 12 +- .../version_checks/commandline.py | 4 +- .../version_checks/git_commit.py | 4 +- .../version_checks/github_commit.py | 10 +- .../version_checks/github_release.py | 4 +- .../version_checks/httpheader.py | 2 +- src/octoprint/plugins/tracking/__init__.py | 6 +- .../plugins/virtual_printer/virtual.py | 47 ++++---- src/octoprint/printer/profile.py | 5 +- src/octoprint/printer/standard.py | 66 ++++------- src/octoprint/server/__init__.py | 63 +++++----- src/octoprint/server/api/__init__.py | 15 ++- src/octoprint/server/api/files.py | 8 +- src/octoprint/server/api/languages.py | 3 +- src/octoprint/server/api/system.py | 8 +- src/octoprint/server/api/timelapse.py | 4 +- src/octoprint/server/util/__init__.py | 2 +- src/octoprint/server/util/flask.py | 29 ++--- src/octoprint/server/util/sockjs.py | 22 ++-- src/octoprint/server/util/tornado.py | 10 +- src/octoprint/server/util/watchdog.py | 6 +- src/octoprint/server/views.py | 23 ++-- src/octoprint/settings.py | 27 ++--- src/octoprint/slicing/__init__.py | 4 +- src/octoprint/slicing/exceptions.py | 4 +- src/octoprint/timelapse.py | 41 +++---- src/octoprint/util/__init__.py | 15 ++- src/octoprint/util/comm.py | 112 ++++++++---------- src/octoprint/util/commandline.py | 6 +- src/octoprint/util/connectivity.py | 6 +- src/octoprint/util/dev.py | 2 +- src/octoprint/util/net.py | 5 +- src/octoprint/util/pip.py | 12 +- src/octoprint/util/piptestballoon/setup.py | 6 +- src/octoprint/util/version.py | 2 +- src/octoprint_client/__init__.py | 15 +-- src/octoprint_setuptools/__init__.py | 6 +- tests/filemanager/test_localstorage.py | 7 +- tests/plugin/test_settings.py | 10 +- tests/settings/test_settings.py | 9 +- tests/test_daemon.py | 8 +- tests/util/test_file_helpers.py | 2 +- 84 files changed, 511 insertions(+), 716 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 8d382e324..a20d098c7 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -16,6 +16,7 @@ repos: rev: v2.10.0 hooks: - id: pyupgrade + args: ["--py37-plus"] - repo: https://github.com/OctoPrint/codemods rev: 0.4.0 hooks: diff --git a/setup.py b/setup.py index c0abd505c..04aa9ae42 100644 --- a/setup.py +++ b/setup.py @@ -134,7 +134,7 @@ def md_to_html_build_py_factory(files, baseclass): source = entry dest = os.path.join(target_dir, source + ".html") - print("Rendering markdown from {} to {}".format(source, dest)) + print(f"Rendering markdown from {source} to {dest}") from markdown import markdownFromFile diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index d9fff3dce..1a0ee47f4 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -import io import logging as log import os import sys @@ -356,7 +355,7 @@ def init_logging( if os.path.exists(logging_file) and os.path.isfile(logging_file): import yaml - with io.open(logging_file, "rt", encoding="utf-8") as f: + with open(logging_file, encoding="utf-8") as f: config_from_file = yaml.safe_load(f) # we merge that with the default config @@ -386,7 +385,7 @@ def octoprint_plugin_inject_factory(settings, components): def wrapper(*args, **kwargs): tags = kwargs.get("tags", set()) | { "source:plugin", - "plugin:{}".format(name), + f"plugin:{name}", } kwargs["tags"] = tags return f(*args, **kwargs) @@ -511,7 +510,7 @@ def init_custom_events(plugin_manager): if isinstance(result, (list, tuple)): for event in result: constant, value = octoprint.events.Events.register_event( - event, prefix="plugin_{}_".format(name) + event, prefix=f"plugin_{name}_" ) logger.debug( 'Registered event {} of plugin {} as Events.{} = "{}"'.format( @@ -520,7 +519,7 @@ def init_custom_events(plugin_manager): ) except Exception: logger.exception( - "Error while retrieving custom event list from plugin {}".format(name), + f"Error while retrieving custom event list from plugin {name}", extra={"plugin": name}, ) @@ -647,7 +646,7 @@ def init_pluginsystem( disabled_from_overlays[name] = (disabled_plugins, order) settings_overlays[name] = overlay - logger.debug("Found settings overlay on plugin {}".format(name)) + logger.debug(f"Found settings overlay on plugin {name}") def handle_plugins_loaded( startup=False, initialize_implementations=True, force_reload=None @@ -689,7 +688,7 @@ def init_pluginsystem( def handle_plugin_enabled(name, plugin): if name in settings_overlays: settings.add_overlay(settings_overlays[name]) - logger.info("Added settings overlay from plugin {}".format(name)) + logger.info(f"Added settings overlay from plugin {name}") pm.on_plugin_loaded = handle_plugin_loaded pm.on_plugins_loaded = handle_plugins_loaded @@ -718,7 +717,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None): format_entry = ( lambda x: "{} ({})".format(x[0], x[1]) if isinstance(x, (list, tuple)) and len(x) == 2 - else "{} (any)".format(x) + else f"{x} (any)" ) return ", ".join(map(format_entry, entries)) diff --git a/src/octoprint/_version.py b/src/octoprint/_version.py index 77b78b683..bff3b84f6 100644 --- a/src/octoprint/_version.py +++ b/src/octoprint/_version.py @@ -10,7 +10,6 @@ """Git implementation of _version.py.""" import errno -import io import logging import os import re @@ -97,7 +96,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False): return None else: if verbose: - print("unable to find command, tried {}".format(commands)) + print(f"unable to find command, tried {commands}") return None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: @@ -140,7 +139,7 @@ def git_get_keywords(versionfile_abs): # _version.py. keywords = {} try: - f = io.open(versionfile_abs, "rt", encoding="utf-8") + f = open(versionfile_abs, encoding="utf-8") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) @@ -334,7 +333,7 @@ def git_parse_lookup_file(path): import re lookup = [] - with io.open(path, "rt", encoding="utf-8") as f: + with open(path, encoding="utf-8") as f: for line in f: if "#" in line: line = line[: line.index("#")] diff --git a/src/octoprint/access/groups.py b/src/octoprint/access/groups.py index d63363ff6..00c6f0d41 100644 --- a/src/octoprint/access/groups.py +++ b/src/octoprint/access/groups.py @@ -2,7 +2,6 @@ __author__ = "Marc Hannappel " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" -import io import logging import os from functools import partial @@ -183,13 +182,13 @@ class GroupManager: return None def _notify_listeners(self, action, group, *args, **kwargs): - method = "on_group_{}".format(action) + method = f"on_group_{action}" for listener in self._group_change_listeners: try: getattr(listener, method)(group, *args, **kwargs) except Exception: self._logger.exception( - "Error notifying listener {!r} via {}".format(listener, method) + f"Error notifying listener {listener!r} via {method}" ) @@ -227,7 +226,7 @@ class FilebasedGroupManager(GroupManager): def _load(self): if os.path.exists(self._groupfile) and os.path.isfile(self._groupfile): try: - with io.open(self._groupfile, "rt", encoding="utf-8") as f: + with open(self._groupfile, encoding="utf-8") as f: data = yaml.safe_load(f) if "groups" not in data: @@ -316,7 +315,7 @@ class FilebasedGroupManager(GroupManager): except Exception: self._logger.exception( - "Error while loading groups from file {}".format(self._groupfile) + f"Error while loading groups from file {self._groupfile}" ) def _save(self, force=False): diff --git a/src/octoprint/access/users.py b/src/octoprint/access/users.py index feacd6722..a327bf22f 100644 --- a/src/octoprint/access/users.py +++ b/src/octoprint/access/users.py @@ -2,7 +2,6 @@ __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 hashlib -import io import logging import os import time @@ -83,11 +82,11 @@ class UserManager(GroupChangeListener): listener.on_user_logged_in(user) except Exception: self._logger.exception( - "Error in on_user_logged_in on {!r}".format(listener), + f"Error in on_user_logged_in on {listener!r}", extra={"callback": fqcn(listener)}, ) - self._logger.info("Logged in user: {}".format(user.get_id())) + self._logger.info(f"Logged in user: {user.get_id()}") return user @@ -121,11 +120,11 @@ class UserManager(GroupChangeListener): listener.on_user_logged_out(user, stale=stale) except Exception: self._logger.exception( - "Error in on_user_logged_out on {!r}".format(listener), + f"Error in on_user_logged_out on {listener!r}", extra={"callback": fqcn(listener)}, ) - self._logger.info("Logged out user: {}".format(user.get_id())) + self._logger.info(f"Logged out user: {user.get_id()}") def _cleanup_sessions(self): for session, user in list(self._session_users_by_session.items()): @@ -269,9 +268,7 @@ class UserManager(GroupChangeListener): return False def on_group_removed(self, group): - self._logger.debug( - "Group {} got removed, removing from all users".format(group.key) - ) + self._logger.debug(f"Group {group.key} got removed, removing from all users") self.remove_groups_from_users([group]) def on_group_permissions_changed(self, group, added=None, removed=None): @@ -282,7 +279,7 @@ class UserManager(GroupChangeListener): listener.on_user_modified(user) except Exception: self._logger.exception( - "Error in on_user_modified on {!r}".format(listener), + f"Error in on_user_modified on {listener!r}", extra={"callback": fqcn(listener)}, ) @@ -295,7 +292,7 @@ class UserManager(GroupChangeListener): listener.on_user_modified(user) except Exception: self._logger.exception( - "Error in on_user_modified on {!r}".format(listener), + f"Error in on_user_modified on {listener!r}", extra={"callback": fqcn(listener)}, ) @@ -327,7 +324,7 @@ class UserManager(GroupChangeListener): listener.on_user_modified(user) except Exception: self._logger.exception( - "Error in on_user_modified on {!r}".format(listener), + f"Error in on_user_modified on {listener!r}", extra={"callback": fqcn(listener)}, ) @@ -337,7 +334,7 @@ class UserManager(GroupChangeListener): listener.on_user_removed(username) except Exception: self._logger.exception( - "Error in on_user_removed on {!r}".format(listener), + f"Error in on_user_removed on {listener!r}", extra={"callback": fqcn(listener)}, ) @@ -516,7 +513,7 @@ class FilebasedUserManager(UserManager): def _load(self): if os.path.exists(self._userfile) and os.path.isfile(self._userfile): # noinspection PyBroadException - with io.open(self._userfile, "rt", encoding="utf-8") as f: + with open(self._userfile, encoding="utf-8") as f: data = yaml.safe_load(f) if not data or not isinstance(data, dict): diff --git a/src/octoprint/cli/analysis.py b/src/octoprint/cli/analysis.py index a1fedb377..151de614d 100644 --- a/src/octoprint/cli/analysis.py +++ b/src/octoprint/cli/analysis.py @@ -113,7 +113,7 @@ def gcode_command( if progress: def progress_callback(percentage): - click.echo("PROGRESS:{}".format(percentage)) + click.echo(f"PROGRESS:{percentage}") interpreter = gcode(progress_callback=progress_callback) diff --git a/src/octoprint/cli/client.py b/src/octoprint/cli/client.py index e0d6f809f..212485e66 100644 --- a/src/octoprint/cli/client.py +++ b/src/octoprint/cli/client.py @@ -1,7 +1,6 @@ __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" -import io import json import os @@ -45,11 +44,11 @@ def create_client( if not apikey: cli_key_file = os.path.join(settings.getBaseFolder("generated"), "cli.key") try: - with io.open(cli_key_file, "r", encoding="utf8") as f: + with open(cli_key_file, encoding="utf8") as f: apikey = f.readline() except Exception: raise FatalStartupError( - "Can not authenticate with server at {}:{}, no key".format(host, port) + f"Can not authenticate with server at {host}:{port}, no key" ) baseurl = octoprint_client.build_base_url( @@ -115,10 +114,10 @@ def client(ctx, apikey, host, port, httpuser, httppass, https, prefix): def log_response(response, status_code=True, body=True, headers=False): if status_code: - click.echo("Status Code: {}".format(response.status_code)) + click.echo(f"Status Code: {response.status_code}") if headers: for header, value in response.headers.items(): - click.echo("{}: {}".format(header, value)) + click.echo(f"{header}: {value}") click.echo() if body: click.echo(response.text) @@ -169,17 +168,17 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout): """POSTs JSON data to the specified server path, taking the data from the specified file.""" if json_flag or yaml_flag: if json_flag: - with io.open(file_path, "rt") as fp: + with open(file_path) as fp: data = json.load(fp) else: import yaml - with io.open(file_path, "rt") as fp: + with open(file_path) as fp: data = yaml.safe_load(fp) r = ctx.obj.client.post_json(path, data, timeout=timeout) else: - with io.open(file_path, "rb") as fp: + with open(file_path, "rb") as fp: data = fp.read() r = ctx.obj.client.post(path, data, timeout=timeout) @@ -285,7 +284,7 @@ def listen(ctx): click.echo("--- Connection closed!") def on_error(ws, error): - click.echo("!!! Error: {}".format(error)) + click.echo(f"!!! Error: {error}") def on_sent(ws, data): click.echo(">>> {}".format(json.dumps(data))) diff --git a/src/octoprint/cli/dev.py b/src/octoprint/cli/dev.py index 7da5de9c6..394450670 100644 --- a/src/octoprint/cli/dev.py +++ b/src/octoprint/cli/dev.py @@ -33,9 +33,7 @@ class OctoPrintDevelCommands(click.MultiCommand): return log self.command_caller = CommandlineCaller() - self.command_caller.on_log_call = log_util( - lambda x: click.echo(">> {}".format(x)) - ) + self.command_caller.on_log_call = log_util(lambda x: click.echo(f">> {x}")) self.command_caller.on_log_stdout = log_util(click.echo) self.command_caller.on_log_stderr = log_util(partial(click.echo, err=True)) @@ -53,7 +51,7 @@ class OctoPrintDevelCommands(click.MultiCommand): def _get_commands(self): result = {} for group in self.groups: - for command in self._get_commands_from_prefix_methods("{}_".format(group)): + for command in self._get_commands_from_prefix_methods(f"{group}_"): result[group + self.sep + command.name] = command return result diff --git a/src/octoprint/cli/plugins.py b/src/octoprint/cli/plugins.py index 72d750bf1..642d7f431 100644 --- a/src/octoprint/cli/plugins.py +++ b/src/octoprint/cli/plugins.py @@ -131,7 +131,7 @@ class OctoPrintPluginCommands(click.MultiCommand): result[name + self.sep + command.name] = command except Exception: self._logger.exception( - "Error while retrieving cli commands for plugin {}".format(name), + f"Error while retrieving cli commands for plugin {name}", extra={"plugin": name}, ) diff --git a/src/octoprint/cli/server.py b/src/octoprint/cli/server.py index 16622e2d7..6f48bb3af 100644 --- a/src/octoprint/cli/server.py +++ b/src/octoprint/cli/server.py @@ -44,7 +44,7 @@ def run_server( PluginTimingsLogHandler.arm_rollover() logger.info(get_divider_line("*")) - logger.info("Starting OctoPrint {}".format(__display_version__)) + logger.info(f"Starting OctoPrint {__display_version__}") if safe_mode: logger.info("Starting in SAFE MODE. Third party plugins will be disabled!") if safe_mode == "flag": @@ -55,7 +55,7 @@ def run_server( reason = "problem during last startup" else: reason = "unknown" - logger.info("Reason for safe mode: {}".format(reason)) + logger.info(f"Reason for safe mode: {reason}") if recorder and len(recorder): logger.info(get_divider_line("-", "Logged during platform initialization:")) @@ -98,7 +98,7 @@ def run_server( log_to_handler(logger, handler, level, message) _log(get_divider_line("-", "Log roll over detected")) - _log("OctoPrint {}".format(__display_version__)) + _log(f"OctoPrint {__display_version__}") if safe_mode: _log("SAFE MODE is active. Third party plugins are disabled!") plugin_manager.log_all_plugins(only_to_handler=handler) diff --git a/src/octoprint/cli/systeminfo.py b/src/octoprint/cli/systeminfo.py index 75fe2e773..ccbb66edd 100644 --- a/src/octoprint/cli/systeminfo.py +++ b/src/octoprint/cli/systeminfo.py @@ -135,7 +135,7 @@ def systeminfo_command(ctx, path, **kwargs): if path: # create zip at path zipfilename = os.path.join(path, get_systeminfo_bundle_name()) - click.echo("Writing systeminfo bundle to {}...".format(zipfilename)) + click.echo(f"Writing systeminfo bundle to {zipfilename}...") z = get_systeminfo_bundle(systeminfo, settings.getBaseFolder("logs")) try: @@ -144,9 +144,7 @@ def systeminfo_command(ctx, path, **kwargs): f.write(data) except Exception as e: click.echo(str(e), err=True) - click.echo( - "There was an error writing to {}.".format(zipfilename), err=True - ) + click.echo(f"There was an error writing to {zipfilename}.", err=True) ctx.exit(-1) click.echo("Done!") diff --git a/src/octoprint/cli/user.py b/src/octoprint/cli/user.py index 373ab1d95..b172548c8 100644 --- a/src/octoprint/cli/user.py +++ b/src/octoprint/cli/user.py @@ -130,9 +130,7 @@ def add_user_command(ctx, username, password, groups, permissions, is_admin): click.echo("User created:") click.echo("\t{}".format(_user_to_line(user.as_dict()))) except UserAlreadyExists: - click.echo( - "A user with the name {} does already exist!".format(username), err=True - ) + click.echo(f"A user with the name {username} does already exist!", err=True) @user.command(name="remove") @@ -147,9 +145,9 @@ def remove_user_command(ctx, username): if confirm.lower() == "yes": ctx.obj.user_manager.remove_user(username) - click.echo("User {} removed.".format(username)) + click.echo(f"User {username} removed.") else: - click.echo("User {} not removed.".format(username)) + click.echo(f"User {username} not removed.") @user.command(name="password") @@ -160,9 +158,9 @@ def change_password_command(ctx, username, password): """Change an existing user's password.""" try: ctx.obj.user_manager.change_user_password(username, password) - click.echo("Password changed for user {}.".format(username)) + click.echo(f"Password changed for user {username}.") except UnknownUser: - click.echo("User {} does not exist!".format(username), err=True) + click.echo(f"User {username} does not exist!", err=True) @user.command(name="activate") @@ -172,14 +170,14 @@ def activate_command(ctx, username): """Activate a user account.""" try: ctx.obj.user_manager.change_user_activation(username, True) - click.echo("User {} activated.".format(username)) + click.echo(f"User {username} activated.") user = ctx.obj.user_manager.find_user(username) if user: click.echo("User created:") click.echo("\t{}".format(_user_to_line(user.asDict()))) except UnknownUser: - click.echo("User {} does not exist!".format(username), err=True) + click.echo(f"User {username} does not exist!", err=True) @user.command(name="deactivate") @@ -189,14 +187,14 @@ def deactivate_command(ctx, username): """Activate a user account.""" try: ctx.obj.user_manager.change_user_activation(username, False) - click.echo("User {} activated.".format(username)) + click.echo(f"User {username} activated.") user = ctx.obj.user_manager.find_user(username) if user: click.echo("User created:") click.echo("\t{}".format(_user_to_line(user.asDict()))) except UnknownUser: - click.echo("User {} does not exist!".format(username), err=True) + click.echo(f"User {username} does not exist!", err=True) def _print_list(users): diff --git a/src/octoprint/daemon.py b/src/octoprint/daemon.py index 7548e23c2..07ac5d091 100644 --- a/src/octoprint/daemon.py +++ b/src/octoprint/daemon.py @@ -4,7 +4,6 @@ Generic linux daemon base class Originally from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/#c35 """ -import io import os import signal import sys @@ -63,9 +62,9 @@ class Daemon: # redirect standard file descriptors sys.stdout.flush() sys.stderr.flush() - si = io.open(os.devnull, "rt", encoding="utf-8") - so = io.open(os.devnull, "at+", encoding="utf-8") - se = io.open(os.devnull, "at+", encoding="utf-8") + si = open(os.devnull, encoding="utf-8") + so = open(os.devnull, "at+", encoding="utf-8") + se = open(os.devnull, "at+", encoding="utf-8") os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) @@ -153,7 +152,7 @@ class Daemon: def get_pid(self): """Get the pid from the pidfile.""" try: - with io.open(self.pidfile, "rt", encoding="utf-8") as pf: + with open(self.pidfile, encoding="utf-8") as pf: pid = int(pf.read().strip()) except (OSError, ValueError): pid = None @@ -161,7 +160,7 @@ class Daemon: def set_pid(self, pid): """Write the pid to the pidfile.""" - with io.open(self.pidfile, "wt+", encoding="utf-8") as f: + with open(self.pidfile, "wt+", encoding="utf-8") as f: f.write(str(pid) + "\n") def remove_pidfile(self): diff --git a/src/octoprint/environment.py b/src/octoprint/environment.py index 59e7cd65f..6711dc02b 100644 --- a/src/octoprint/environment.py +++ b/src/octoprint/environment.py @@ -169,7 +169,7 @@ class EnvironmentDetector: environment, default_flow_style=False, indent=2, allow_unicode=True ).strip() environment_lines = "\n".join( - map(lambda l: "| {}".format(l), dumped_environment.split("\n")) + map(lambda l: f"| {l}", dumped_environment.split("\n")) ) return "Detected environment is Python {} under {} ({}). Details:\n{}".format( environment["python"]["version"], diff --git a/src/octoprint/events.py b/src/octoprint/events.py index 3e3aa0325..f93553ee9 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -160,7 +160,7 @@ class EventManager: def __init__(self): self._registeredListeners = collections.defaultdict(list) self._logger = logging.getLogger(__name__) - self._logger_fire = logging.getLogger("{}.fire".format(__name__)) + self._logger_fire = logging.getLogger(f"{__name__}.fire") self._startup_signaled = False self._shutdown_signaled = False @@ -184,12 +184,10 @@ class EventManager: self._shutdown_signaled = True eventListeners = self._registeredListeners[event] - self._logger_fire.debug( - "Firing event: {} (Payload: {!r})".format(event, payload) - ) + self._logger_fire.debug(f"Firing event: {event} (Payload: {payload!r})") for listener in eventListeners: - self._logger.debug("Sending action to {!r}".format(listener)) + self._logger.debug(f"Sending action to {listener!r}") try: listener(event, payload) except Exception: @@ -256,9 +254,7 @@ class EventManager: return self._registeredListeners[event].append(callback) - self._logger.debug( - "Subscribed listener {!r} for event {}".format(callback, event) - ) + self._logger.debug(f"Subscribed listener {callback!r} for event {event}") def unsubscribe(self, event, callback): """ @@ -317,7 +313,7 @@ class DebugEventListener(GenericEventListener): def eventCallback(self, event, payload): GenericEventListener.eventCallback(self, event, payload) - self._logger.debug("Received event: {} (Payload: {!r})".format(event, payload)) + self._logger.debug(f"Received event: {event} (Payload: {payload!r})") class CommandTrigger(GenericEventListener): @@ -364,7 +360,7 @@ class CommandTrigger(GenericEventListener): continue if "enabled" in subscription and not subscription["enabled"]: - self._logger.info("Disabled command trigger: {!r}".format(subscription)) + self._logger.info(f"Disabled command trigger: {subscription!r}") continue events = subscription["event"] @@ -423,7 +419,7 @@ class CommandTrigger(GenericEventListener): def _executeSystemCommand(self, command, debug=False): def commandExecutioner(cmd): if debug: - self._logger.info("Executing system command: {}".format(cmd)) + self._logger.info(f"Executing system command: {cmd}") else: self._logger.info("Executing a system command") # we run this with shell=True since we have to trust whatever diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py index 757617677..555d9c358 100644 --- a/src/octoprint/filemanager/__init__.py +++ b/src/octoprint/filemanager/__init__.py @@ -445,8 +445,6 @@ class FileManager: source_meta = self.get_metadata(source_location, source_path) hash = source_meta.get("hash", "n/a") - import io - links = [("model", {"name": source_path})] _, stl_name = self.split_path(source_location, source_path) file_obj = StreamWrapper( @@ -954,7 +952,7 @@ class FileManager: ) except Exception: self._logger.exception( - "Could not write recovery data to file {}".format(self._recovery_file) + f"Could not write recovery data to file {self._recovery_file}" ) def delete_recovery_data(self): @@ -965,7 +963,7 @@ class FileManager: os.remove(self._recovery_file) except Exception: self._logger.exception( - "Error deleting recovery data file {}".format(self._recovery_file) + f"Error deleting recovery data file {self._recovery_file}" ) def get_recovery_data(self): @@ -975,7 +973,7 @@ class FileManager: import yaml try: - with io.open(self._recovery_file, "rt", encoding="utf-8") as f: + with open(self._recovery_file, encoding="utf-8") as f: data = yaml.safe_load(f) if not isinstance(data, dict) or not all( map(lambda x: x in data, ("origin", "path", "pos", "date")) @@ -984,7 +982,7 @@ class FileManager: return data except Exception: self._logger.exception( - "Could not read recovery data from file {}".format(self._recovery_file) + f"Could not read recovery data from file {self._recovery_file}" ) self.delete_recovery_data() diff --git a/src/octoprint/filemanager/analysis.py b/src/octoprint/filemanager/analysis.py index af9cad273..0391fd513 100644 --- a/src/octoprint/filemanager/analysis.py +++ b/src/octoprint/filemanager/analysis.py @@ -39,7 +39,7 @@ class QueueEntry( """ def __str__(self): - return "{location}:{path}".format(location=self.location, path=self.path) + return f"{self.location}:{self.path}" class AnalysisAborted(Exception): @@ -114,7 +114,7 @@ class AnalysisQueue: callback(entry, result) except Exception: self._logger.exception( - "Error while pushing analysis data to callback {}".format(callback), + f"Error while pushing analysis data to callback {callback}", extra={"callback": fqcn(callback)}, ) eventManager().fire( @@ -185,9 +185,7 @@ class AbstractAnalysisQueue: """ if settings().get(["gcodeAnalysis", "runAt"]) == "never": - self._logger.debug( - "Ignoring entry {entry} for analysis queue".format(entry=entry) - ) + self._logger.debug(f"Ignoring entry {entry} for analysis queue") return elif high_priority: self._logger.debug( @@ -254,7 +252,7 @@ class AbstractAnalysisQueue: while True: (priority, entry, high_priority) = self._queue.get() self._logger.debug( - "Processing entry {} from queue (priority {})".format(entry, priority) + f"Processing entry {entry} from queue (priority {priority})" ) self._active.wait() @@ -273,7 +271,7 @@ class AbstractAnalysisQueue: high_priority, ) ) - self._logger.debug("Running analysis of entry {} aborted".format(entry)) + self._logger.debug(f"Running analysis of entry {entry} aborted") self._queue.task_done() self._done.set() else: @@ -290,7 +288,7 @@ class AbstractAnalysisQueue: try: start_time = time.monotonic() - self._logger.info("Starting analysis of {}".format(entry)) + self._logger.info(f"Starting analysis of {entry}") eventManager().fire( Events.METADATA_ANALYSIS_STARTED, { @@ -311,9 +309,7 @@ class AbstractAnalysisQueue: ) self._finished_callback(self._current, result) except RuntimeError as exc: - self._logger.error( - "Analysis for {} ran into error: {}".format(self._current, exc) - ) + self._logger.error(f"Analysis for {self._current} ran into error: {exc}") finally: self._current = None self._current_progress = None @@ -421,12 +417,12 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): "octoprint", "analysis", "gcode", - "--speed-x={}".format(speedx), - "--speed-y={}".format(speedy), - "--max-t={}".format(max_extruders), - "--throttle={}".format(throttle), - "--throttle-lines={}".format(throttle_lines), - "--bed-z={}".format(bed_z), + f"--speed-x={speedx}", + f"--speed-y={speedy}", + f"--max-t={max_extruders}", + f"--throttle={throttle}", + f"--throttle-lines={throttle_lines}", + f"--bed-z={bed_z}", ] for offset in offsets[1:]: command += ["--offset", str(offset[0]), str(offset[1])] @@ -472,7 +468,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): p.close() output = p.stdout.text - self._logger.debug("Got output: {!r}".format(output)) + self._logger.debug(f"Got output: {output!r}") if "ERROR:" in output: _, error = output.split("ERROR:") diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index c75b75a68..a3aa5db96 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -3,7 +3,6 @@ __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 copy -import io import logging import os import shutil @@ -492,9 +491,7 @@ class LocalFileStorage(StorageInterface): self._initialize_metadata() def _initialize_metadata(self): - self._logger.info( - "Initializing the file metadata for {}...".format(self.basefolder) - ) + self._logger.info(f"Initializing the file metadata for {self.basefolder}...") old_metadata_path = os.path.join(self.basefolder, "metadata.yaml") backup_path = os.path.join(self.basefolder, "metadata.yaml.backup") @@ -502,7 +499,7 @@ class LocalFileStorage(StorageInterface): if os.path.exists(old_metadata_path): # load the old metadata file try: - with io.open(old_metadata_path, "rt", encoding="utf-8") as f: + with open(old_metadata_path, encoding="utf-8") as f: import yaml self._old_metadata = yaml.safe_load(f) @@ -526,7 +523,7 @@ class LocalFileStorage(StorageInterface): self._list_folder(self.basefolder) self._logger.info( - "... file metadata for {} initialized successfully.".format(self.basefolder) + f"... file metadata for {self.basefolder} initialized successfully." ) @property @@ -719,7 +716,7 @@ class LocalFileStorage(StorageInterface): if not os.path.exists(source_fullpath): raise StorageError( - "{} in {} does not exist".format(source_name, source_path), + f"{source_name} in {source_path} does not exist", code=StorageError.INVALID_SOURCE, ) @@ -735,7 +732,7 @@ class LocalFileStorage(StorageInterface): and source_fullpath != destination_fullpath ): raise StorageError( - "{} does already exist in {}".format(destination_name, destination_path), + f"{destination_name} does already exist in {destination_path}", code=StorageError.INVALID_DESTINATION, ) @@ -1208,16 +1205,14 @@ class LocalFileStorage(StorageInterface): while os.path.exists(sanitized_path): counter += 1 sanitized = self.sanitize_name( - "{}_({}){}".format(sanitized_name, counter, sanitized_ext) + f"{sanitized_name}_({counter}){sanitized_ext}" ) sanitized_path = os.path.join(path, sanitized) try: shutil.move(entry_path, sanitized_path) - self._logger.info( - 'Sanitized "{}" to "{}"'.format(entry_path, sanitized_path) - ) + self._logger.info(f'Sanitized "{entry_path}" to "{sanitized_path}"') return sanitized, sanitized_path except Exception: self._logger.exception( @@ -1664,7 +1659,7 @@ class LocalFileStorage(StorageInterface): except Exception: # So something went wrong somewhere while processing this file entry - log that and continue self._logger.exception( - "Error while processing entry {}".format(entry_path) + f"Error while processing entry {entry_path}" ) continue @@ -1734,7 +1729,7 @@ class LocalFileStorage(StorageInterface): blocksize = 65536 hash = hashlib.sha1() - with io.open(path, "rb") as f: + with open(path, "rb") as f: buffer = f.read(blocksize) while len(buffer) > 0: hash.update(buffer) @@ -1815,7 +1810,7 @@ class LocalFileStorage(StorageInterface): metadata = None with self._get_persisted_metadata_lock(path): if os.path.exists(metadata_path): - with io.open(metadata_path, "rt", encoding="utf-8") as f: + with open(metadata_path, encoding="utf-8") as f: try: metadata = json.load(f) except Exception: @@ -1922,7 +1917,7 @@ class LocalFileStorage(StorageInterface): ) return - with io.open(metadata_path_yaml, "rt", encoding="utf-8") as f: + with open(metadata_path_yaml, encoding="utf-8") as f: try: metadata = yaml.safe_load(f) except Exception: diff --git a/src/octoprint/filemanager/util.py b/src/octoprint/filemanager/util.py index a23f81aa9..a86e9a7f2 100644 --- a/src/octoprint/filemanager/util.py +++ b/src/octoprint/filemanager/util.py @@ -72,7 +72,7 @@ class DiskFileWrapper(AbstractFileWrapper): os.chmod(path, permissions) def stream(self): - return io.open(self.path, "rb") + return open(self.path, "rb") class StreamWrapper(AbstractFileWrapper): diff --git a/src/octoprint/logging/filters.py b/src/octoprint/logging/filters.py index fcd545ae0..9df05352e 100644 --- a/src/octoprint/logging/filters.py +++ b/src/octoprint/logging/filters.py @@ -20,7 +20,7 @@ class TornadoAccessFilter(logging.Filter): record.levelname = logging.getLevelName(record.levelno) except Exception: logging.getLogger(__name__).exception( - "Error while filtering log record {!r}".format(record) + f"Error while filtering log record {record!r}" ) return logging.Filter.filter(self, record) diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index 0965586ae..7d12d1ff3 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -186,7 +186,7 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None): get_preprocessors, set_preprocessors = instance.get_settings_preprocessors() except Exception: logging.getLogger(__name__).exception( - "Error while retrieving preprocessors for plugin {}".format(plugin_key) + f"Error while retrieving preprocessors for plugin {plugin_key}" ) return None @@ -263,7 +263,7 @@ def call_plugin( continue if hasattr(plugin, method): - logger.debug("Calling {} on {}".format(method, plugin._identifier)) + logger.debug(f"Calling {method} on {plugin._identifier}") try: result = getattr(plugin, method)(*args, **kwargs) if callback: @@ -601,7 +601,7 @@ class PluginSettings: if item in self.deprecated_access_methods: new = self.deprecated_access_methods[item] decorator = deprecated( - "{old} has been renamed to {new}".format(old=item, new=new), + f"{item} has been renamed to {new}", stacklevel=2, ) item = new diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index 9e7db9af8..71bf3218f 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -24,7 +24,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import fnmatch import inspect -import io import logging import os from collections import OrderedDict, defaultdict, namedtuple @@ -306,7 +305,7 @@ class PluginInfo: def __str__(self): if self.version: - return "{name} ({version})".format(name=self.name, version=self.version) + return f"{self.name} ({self.version})" else: return to_unicode(self.name) @@ -684,14 +683,12 @@ class PluginInfo: # we only support parsing plain text source files return result - self._logger.debug( - "Parsing plugin metadata for {} from AST of {}".format(self.key, path) - ) + self._logger.debug(f"Parsing plugin metadata for {self.key} from AST of {path}") try: import ast - with io.open(path, "rb") as f: + with open(path, "rb") as f: root = ast.parse(f.read(), filename=path) assignments = list( @@ -765,13 +762,11 @@ class PluginInfo: break except SyntaxError: - self._logger.exception( - "Invalid syntax in {} for plugin {}".format(path, self.key) - ) + self._logger.exception(f"Invalid syntax in {path} for plugin {self.key}") self.invalid_syntax = True except Exception: self._logger.exception( - "Error while parsing AST from {} for plugin {}".format(path, self.key) + f"Error while parsing AST from {path} for plugin {self.key}" ) return result @@ -1001,7 +996,7 @@ class PluginManager: module_name = None if package: - module_name = "{}.{}".format(package, key) + module_name = f"{package}.{key}" plugin = self._import_plugin_from_module( key, module_name=module_name, folder=folder, bundled=bundled @@ -1025,7 +1020,7 @@ class PluginManager: ) ) except Exception: - self.logger.exception("Error processing folder {}".format(folder)) + self.logger.exception(f"Error processing folder {folder}") return added, found @@ -1163,7 +1158,7 @@ class PluginManager: else: return None except Exception: - self.logger.exception("Could not locate plugin {key}".format(key=key)) + self.logger.exception(f"Could not locate plugin {key}") return None # Create a simple dummy entry first ... @@ -1181,14 +1176,14 @@ class PluginManager: plugin.bundled = bundled if self._is_plugin_disabled(key): - self.logger.info("Plugin {} is disabled.".format(plugin)) + self.logger.info(f"Plugin {plugin} is disabled.") plugin.forced_disabled = True if self._is_plugin_blacklisted(key) or ( plugin.version is not None and self._is_plugin_version_blacklisted(key, plugin.version) ): - self.logger.warning("Plugin {} is blacklisted.".format(plugin)) + self.logger.warning(f"Plugin {plugin} is blacklisted.") plugin.blacklisted = True python_version = get_python_version_string() @@ -1264,7 +1259,7 @@ class PluginManager: plugin.bundled = bundled except Exception: - self.logger.exception("Error loading plugin {key}".format(key=key)) + self.logger.exception(f"Error loading plugin {key}") return None if plugin.check(): @@ -1386,7 +1381,7 @@ class PluginManager: ): if plugin.blacklisted: self.logger.warning( - "Plugin {} is blacklisted. Not enabling it.".format(plugin) + f"Plugin {plugin} is blacklisted. Not enabling it." ) continue self.enable_plugin( @@ -2272,11 +2267,11 @@ def is_sub_path_of(path, parent): def is_editable_install(install_dir, package, module, location): - package_link = os.path.join(install_dir, "{}.egg-link".format(package)) + package_link = os.path.join(install_dir, f"{package}.egg-link") if os.path.isfile(package_link): expected_target = os.path.normcase(os.path.realpath(location)) try: - with io.open(package_link, "rt", encoding="utf-8") as f: + with open(package_link, encoding="utf-8") as f: contents = f.readlines() for line in contents: target = os.path.normcase( diff --git a/src/octoprint/plugins/action_command_notification/__init__.py b/src/octoprint/plugins/action_command_notification/__init__.py index 3dfb4a09b..a3e147990 100644 --- a/src/octoprint/plugins/action_command_notification/__init__.py +++ b/src/octoprint/plugins/action_command_notification/__init__.py @@ -123,7 +123,7 @@ class ActionCommandNotificationPlugin( self._notifications.append((time.time(), message)) self._plugin_manager.send_plugin_message(self._identifier, {"message": message}) - self._logger.info("Got a notification: {}".format(message)) + self._logger.info(f"Got a notification: {message}") def _clear_notifications(self): self._notifications = [] diff --git a/src/octoprint/plugins/action_command_prompt/__init__.py b/src/octoprint/plugins/action_command_prompt/__init__.py index 4a523eb50..5e3b077e1 100644 --- a/src/octoprint/plugins/action_command_prompt/__init__.py +++ b/src/octoprint/plugins/action_command_prompt/__init__.py @@ -90,7 +90,7 @@ class ActionCommandPromptPlugin( and self._enable == "always" and self._enable_signal_support ): - self._printer.commands(["{command} P1".format(command=self._command)]) + self._printer.commands([f"{self._command} P1"]) elif event == Events.DISCONNECTED: self._close_prompt() @@ -130,9 +130,7 @@ class ActionCommandPromptPlugin( choice = data["choice"] if not isinstance(choice, int) or not self._prompt.validate_choice(choice): - return flask.abort( - 400, "{!r} is not a valid value for choice".format(choice) - ) + return flask.abort(400, f"{choice!r} is not a valid value for choice") self._answer_prompt(choice) @@ -208,7 +206,7 @@ class ActionCommandPromptPlugin( subcode=None, tags=None, *args, - **kwargs + **kwargs, ): if gcode != self._command: return @@ -226,7 +224,7 @@ class ActionCommandPromptPlugin( # noinspection PyProtectedMember return comm_instance._emergency_force_send( - cmd, "Force-sending {} to the printer".format(self._command), gcode=gcode + cmd, f"Force-sending {self._command} to the printer", gcode=gcode ) # ~ capability reporting @@ -237,7 +235,7 @@ class ActionCommandPromptPlugin( if capability == self.CAP_PROMPT_SUPPORT and enabled: self._cap_prompt_support = True if self._enable == "detected" and self._enable_signal_support: - self._printer.commands(["{command} P1".format(command=self._command)]) + self._printer.commands([f"{self._command} P1"]) # ~ prompt handling @@ -277,7 +275,7 @@ class ActionCommandPromptPlugin( self._printer.commands([self._command.format(choice=choice)], force=True) else: self._printer.commands( - ["{command} S{choice}".format(command=self._command, choice=choice)], + [f"{self._command} S{choice}"], force=True, ) diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py index 7aecedd1a..7eaf806c3 100644 --- a/src/octoprint/plugins/announcements/__init__.py +++ b/src/octoprint/plugins/announcements/__init__.py @@ -4,7 +4,6 @@ __copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms import calendar -import io import os import re import sys @@ -434,9 +433,7 @@ class AnnouncementPlugin( now = time.time() if os.stat(channel_path).st_mtime + ttl > now: d = feedparser.parse(channel_path) - self._logger.debug( - "Loaded channel {} from cache at {}".format(key, channel_path) - ) + self._logger.debug(f"Loaded channel {key} from cache at {channel_path}") return d return None @@ -464,7 +461,7 @@ class AnnouncementPlugin( response = r.text channel_path = self._get_channel_cache_path(key) - with io.open(channel_path, mode="wt", encoding="utf-8") as f: + with open(channel_path, mode="wt", encoding="utf-8") as f: f.write(response) return feedparser.parse(response) @@ -518,7 +515,7 @@ class AnnouncementPlugin( """Retrieve cache path for channel key.""" safe_key = sanitize(key) - return os.path.join(self.get_plugin_data_folder(), "{}.cache".format(safe_key)) + return os.path.join(self.get_plugin_data_folder(), f"{safe_key}.cache") _image_tag_re = re.compile(r"") @@ -577,7 +574,7 @@ def _lazy_images(text, placeholder=None): quote = match.group("quote") quoted_src = quote + src + quote img_tag = img_tag.replace( - match.group(0), 'src="{}" data-src={}'.format(placeholder, quoted_src) + match.group(0), f'src="{placeholder}" data-src={quoted_src}' ) return img_tag @@ -602,10 +599,10 @@ def _strip_tags(text): self._fed.append(data) def handle_entityref(self, ref): - self._fed.append("&{};".format(ref)) + self._fed.append(f"&{ref};") def handle_charref(self, ref): - self._fed.append("&#{};".format(ref)) + self._fed.append(f"&#{ref};") def get_data(self): return "".join(self._fed) diff --git a/src/octoprint/plugins/appkeys/__init__.py b/src/octoprint/plugins/appkeys/__init__.py index d49bbcb3b..ca8ff3024 100644 --- a/src/octoprint/plugins/appkeys/__init__.py +++ b/src/octoprint/plugins/appkeys/__init__.py @@ -1,4 +1,3 @@ -import io import os import threading import time @@ -439,13 +438,11 @@ class AppKeysPlugin( return try: - with io.open( - self._key_path, "rt", encoding="utf-8", errors="strict" - ) as f: + with open(self._key_path, encoding="utf-8", errors="strict") as f: persisted = yaml.safe_load(f) except Exception: self._logger.exception( - "Could not load application keys from {}".format(self._key_path) + f"Could not load application keys from {self._key_path}" ) return @@ -470,7 +467,7 @@ class AppKeysPlugin( yaml.safe_dump(to_persist, f, allow_unicode=True) except Exception: self._logger.exception( - "Could not write application keys to {}".format(self._key_path) + f"Could not write application keys to {self._key_path}" ) diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index 204b19648..13174e9d8 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -26,7 +26,6 @@ except ImportError: zlib = None -import io import json import logging import os @@ -506,7 +505,7 @@ class BackupPlugin( if not os.path.isdir(datafolder): os.makedirs(datafolder) - click.echo("Creating backup at {}, please wait...".format(filename)) + click.echo(f"Creating backup at {filename}, please wait...") self._create_backup( filename, exclude=exclude, @@ -550,7 +549,7 @@ class BackupPlugin( path = os.path.join(datafolder, path) if not os.path.exists(path): - click.echo("Backup {} does not exist".format(path), err=True) + click.echo(f"Backup {path} does not exist", err=True) sys.exit(-1) archive = tempfile.NamedTemporaryFile(delete=False) @@ -568,7 +567,7 @@ class BackupPlugin( pip_args = settings.global_get(["plugins", "pluginmanager", "pip_args"]) def log(line): - click.echo("\t{}".format(line)) + click.echo(f"\t{line}") for plugin in plugins: octoprint_compatible = is_octoprint_compatible( @@ -644,9 +643,9 @@ class BackupPlugin( on_log_error=on_log_error, on_invalid_backup=on_log_error, ): - click.echo("Restored from {}".format(path)) + click.echo(f"Restored from {path}") else: - click.echo("Restoring from {} failed".format(path), err=True) + click.echo(f"Restoring from {path} failed", err=True) return [backup_command, restore_command] @@ -725,7 +724,7 @@ class BackupPlugin( try: os.remove(full_path) except Exception: - self._logger.exception("Could not delete {}".format(filename)) + self._logger.exception(f"Could not delete {filename}") raise def _get_backups(self): @@ -754,7 +753,7 @@ class BackupPlugin( 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="rt", encoding="utf-8") as f: + with open(data_file, mode="rt", encoding="utf-8") as f: unknown_plugins = json.load(f) assert isinstance(unknown_plugins, list) @@ -852,7 +851,7 @@ class BackupPlugin( r.raise_for_status() except Exception: logger.exception( - "Error while fetching the plugin repository data from {}".format(url) + f"Error while fetching the plugin repository data from {url}" ) return {} @@ -873,7 +872,7 @@ class BackupPlugin( # prepare pip caller def log(prefix, *lines): for line in lines: - on_log("{} {}".format(prefix, line.rstrip())) + on_log(f"{prefix} {line.rstrip()}") def log_call(*lines): log(">", *lines) @@ -967,7 +966,7 @@ class BackupPlugin( configfile = settings._configfile basedir = settings._basedir - temporary_path = os.path.join(datafolder, ".{}".format(name)) + temporary_path = os.path.join(datafolder, f".{name}") final_path = os.path.join(datafolder, name) own_folder = datafolder @@ -1162,7 +1161,7 @@ class BackupPlugin( temp = tempfile.mkdtemp() try: if callable(on_log_progress): - on_log_progress("Unpacking backup to {}...".format(temp)) + on_log_progress(f"Unpacking backup to {temp}...") abstemp = os.path.abspath(temp) dirs = {} @@ -1193,7 +1192,7 @@ class BackupPlugin( import yaml - with io.open(configfile, "rt", encoding="utf-8") as f: + with open(configfile, encoding="utf-8") as f: configdata = yaml.safe_load(f) userfile = os.path.join(temp, "basedir", "users.yaml") @@ -1211,7 +1210,7 @@ class BackupPlugin( plugins = [] plugin_list_file = os.path.join(temp, "plugin_list.json") if os.path.exists(plugin_list_file): - with io.open(os.path.join(temp, "plugin_list.json"), "rb") as f: + with open(os.path.join(temp, "plugin_list.json"), "rb") as f: plugins = json.load(f) known_plugins = [] @@ -1261,16 +1260,12 @@ class BackupPlugin( basedir_extracted = os.path.join(temp, "basedir") if callable(on_log_progress): - on_log_progress( - "Renaming {} to {}...".format(basedir, basedir_backup) - ) + on_log_progress(f"Renaming {basedir} to {basedir_backup}...") shutil.move(basedir, basedir_backup) try: if callable(on_log_progress): - on_log_progress( - "Moving {} to {}...".format(basedir_extracted, basedir) - ) + on_log_progress(f"Moving {basedir_extracted} to {basedir}...") shutil.move(basedir_extracted, basedir) except Exception: if callable(on_log_error): @@ -1297,7 +1292,7 @@ class BackupPlugin( datafolder, UNKNOWN_PLUGINS_FILE ) try: - with io.open(unknown_plugins_path, mode="wb") as f: + with open(unknown_plugins_path, mode="wb") as f: f.write(to_bytes(json.dumps(unknown_plugins))) except Exception: if callable(on_log_error): @@ -1351,7 +1346,7 @@ class BackupPlugin( except Exception: if callable(on_log_error): on_log_error( - "Error while restarting via command {}".format(restart_command), + f"Error while restarting via command {restart_command}", exc_info=sys.exc_info(), ) on_log_error("Please restart OctoPrint manually") diff --git a/src/octoprint/plugins/corewizard/__init__.py b/src/octoprint/plugins/corewizard/__init__.py index 043cac4af..0096f5822 100644 --- a/src/octoprint/plugins/corewizard/__init__.py +++ b/src/octoprint/plugins/corewizard/__init__.py @@ -54,9 +54,9 @@ class CoreWizardPlugin( config = { "type": "wizard", "name": name, - "template": "corewizard_{}_wizard.jinja2".format(key), - "div": "wizard_plugin_corewizard_{}".format(key), - "suffix": "_{}".format(key), + "template": f"corewizard_{key}_wizard.jinja2", + "div": f"wizard_plugin_corewizard_{key}", + "suffix": f"_{key}", } if key in additional: additional_result = additional[key]() diff --git a/src/octoprint/plugins/discovery/__init__.py b/src/octoprint/plugins/discovery/__init__.py index 054288b80..28d0e5fab 100644 --- a/src/octoprint/plugins/discovery/__init__.py +++ b/src/octoprint/plugins/discovery/__init__.py @@ -228,15 +228,15 @@ class DiscoveryPlugin( name, addresses=addresses, port=port, - server="{}.local.".format(socket.gethostname()), + server=f"{socket.gethostname()}.local.", properties=txt_record, ) self._zeroconf.register_service(info, allow_name_change=True) self._zeroconf_registrations[key].append(info) - self._logger.info("Registered '{}' for {}".format(name, reg_type)) + self._logger.info(f"Registered '{name}' for {reg_type}") except Exception: self._logger.exception( - "Could not register {} for {} on port {}".format(name, reg_type, port) + f"Could not register {name} for {reg_type} on port {port}" ) def zeroconf_unregister(self, reg_type, port=None): @@ -260,10 +260,10 @@ class DiscoveryPlugin( try: for info in infos: self._zeroconf.unregister_service(info) - self._logger.debug("Unregistered {} on port {}".format(reg_type, port)) + self._logger.debug(f"Unregistered {reg_type} on port {port}") except Exception: self._logger.exception( - "Could not (fully) unregister {} on port {}".format(reg_type, port) + f"Could not (fully) unregister {reg_type} on port {port}" ) def zeroconf_browse( @@ -349,9 +349,7 @@ class DiscoveryPlugin( for address in map(lambda x: socket.inet_ntoa(x), info.addresses): result.append(to_result(info, address)) - self._logger.debug( - "Browsing Zeroconf for {service_type}".format(service_type=service_type) - ) + self._logger.debug(f"Browsing Zeroconf for {service_type}") def browse(): listener = ZeroconfListener(self._logger) @@ -706,7 +704,7 @@ class DiscoveryPlugin( + socket.inet_aton("0.0.0.0"), ) - self._logger.info("Registered {} for SSDP".format(self.get_instance_name())) + self._logger.info(f"Registered {self.get_instance_name()} for SSDP") self._ssdp_notify(alive=True) @@ -728,7 +726,7 @@ class DiscoveryPlugin( interface_address = octoprint.util.address_for_client( *address, addresses=self._settings.get(["addresses"]), - interfaces=self._settings.get(["interfaces"]) + interfaces=self._settings.get(["interfaces"]), ) if not interface_address: continue @@ -772,9 +770,9 @@ class DiscoveryPlugin( def get_instance_name(self): name = self._settings.global_get(["appearance", "name"]) if name: - return 'OctoPrint instance "{}"'.format(name) + return f'OctoPrint instance "{name}"' else: - return "OctoPrint instance on {}".format(socket.gethostname()) + return f"OctoPrint instance on {socket.gethostname()}" def get_interface_addresses(self): addresses = self._settings.get(["addresses"]) diff --git a/src/octoprint/plugins/logging/__init__.py b/src/octoprint/plugins/logging/__init__.py index e0f367680..a27da578c 100644 --- a/src/octoprint/plugins/logging/__init__.py +++ b/src/octoprint/plugins/logging/__init__.py @@ -1,7 +1,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" -import io import os from os import scandir @@ -183,7 +182,7 @@ class LoggingPlugin( if os.path.exists(logging_file) and os.path.isfile(logging_file): import yaml - with io.open(logging_file, "rt", encoding="utf-8") as f: + with open(logging_file, encoding="utf-8") as f: config_from_file = yaml.safe_load(f) return config_from_file @@ -242,7 +241,7 @@ class LoggingPlugin( for logger, level in new_levels.items(): level = logging.getLevelName(level) - self._logger.info("Setting logger {} level to {}".format(logger, level)) + self._logger.info(f"Setting logger {logger} level to {level}") self._logger.manager.loggerDict[logger].setLevel(level) def _is_managed_logger(self, logger): diff --git a/src/octoprint/plugins/pi_support/__init__.py b/src/octoprint/plugins/pi_support/__init__.py index 63ad242ac..850d28ef2 100644 --- a/src/octoprint/plugins/pi_support/__init__.py +++ b/src/octoprint/plugins/pi_support/__init__.py @@ -1,7 +1,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" -import io import os import flask @@ -95,7 +94,7 @@ class ThrottleState: self._past_throttled = False for key, value in kwargs.items(): - local_key = "_{}".format(key) + local_key = f"_{key}" if hasattr(self, local_key) and isinstance(value, bool): setattr(self, local_key, value) @@ -141,7 +140,7 @@ class ThrottleState: @property def raw_value_hex(self): - return "0x{:X}".format(self._raw_value) + return f"0x{self._raw_value:X}" def __eq__(self, other): if not isinstance(other, ThrottleState): @@ -176,7 +175,7 @@ def get_proc_dt_model(): global _proc_dt_model if _proc_dt_model is None: - with io.open(_PROC_DT_MODEL_PATH, "rt", encoding="utf-8") as f: + with open(_PROC_DT_MODEL_PATH, encoding="utf-8") as f: _proc_dt_model = f.readline().strip(" \t\r\n\0") return _proc_dt_model @@ -189,7 +188,7 @@ def get_vcgencmd_throttled_state(command): output = sarge.get_stdout(command, close_fds=CLOSE_FDS) if "throttled=0x" not in output: - raise ValueError('cannot parse "{}" output: {}'.format(command, output)) + raise ValueError(f'cannot parse "{command}" output: {output}') value = output[len("throttled=") :].strip(" \t\r\n\0") value = int(value, 0) @@ -207,7 +206,7 @@ def get_octopi_version(): global _octopi_version if _octopi_version is None: - with io.open(_OCTOPI_VERSION_PATH, "rt", encoding="utf-8") as f: + with open(_OCTOPI_VERSION_PATH, encoding="utf-8") as f: _octopi_version = f.readline().strip(" \t\r\n\0") return _octopi_version @@ -362,7 +361,7 @@ class PiSupportPlugin( def _check_throttled_state(self): command = self._settings.get(["vcgencmd_throttle_check_command"]) - self._logger.debug('Retrieving throttle state via "{}"'.format(command)) + self._logger.debug(f'Retrieving throttle state via "{command}"') try: state = get_vcgencmd_throttled_state(command) except ValueError: diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 68dd969e0..375412f8d 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -3,7 +3,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import copy -import io import logging import os import re @@ -705,7 +704,7 @@ class PluginManagerPlugin( kind = filetype.guess(path) if kind: - return ".{}".format(kind.extension) in PluginManagerPlugin.ARCHIVE_EXTENSIONS + return f".{kind.extension}" in PluginManagerPlugin.ARCHIVE_EXTENSIONS return False def _is_pythonfile(self, path): @@ -714,13 +713,11 @@ class PluginManagerPlugin( import ast try: - with io.open(path, "rb") as f: + with open(path, "rb") as f: ast.parse(f.read(), filename=path) return True except Exception as exc: - self._logger.exception( - "Could not parse {} as python file: {}".format(path, exc) - ) + self._logger.exception(f"Could not parse {path} as python file: {exc}") return False @@ -767,12 +764,12 @@ class PluginManagerPlugin( raise exceptions.InvalidPackageFormat() except requests.exceptions.HTTPError as e: - self._logger.error("Could not fetch plugin from server, got {}".format(e)) + self._logger.error(f"Could not fetch plugin from server, got {e}") result = { "result": False, "source": source, "source_type": source_type, - "reason": "Could not fetch plugin from server, got {}".format(e), + "reason": f"Could not fetch plugin from server, got {e}", } self._send_result_notification("install", result) @@ -863,7 +860,7 @@ class PluginManagerPlugin( lambda line: path_url in line.lower() ) # lower case in case of windows - self._logger.info("Installing plugin from {}".format(source)) + self._logger.info(f"Installing plugin from {source}") pip_args = [ "--disable-pip-version-check", "install", @@ -909,7 +906,7 @@ class PluginManagerPlugin( ) force = True except Exception as e: - self._logger.exception("Could not install plugin from {}".format(source)) + self._logger.exception(f"Could not install plugin from {source}") self._logger.exception("Reason: {}".format(repr(e))) result = { "result": False, @@ -930,9 +927,7 @@ class PluginManagerPlugin( try: returncode, stdout, stderr = self._call_pip(pip_args) except Exception as e: - self._logger.exception( - "Could not install plugin from {}".format(source) - ) + self._logger.exception(f"Could not install plugin from {source}") self._logger.exception("Reason: {}".format(repr(e))) result = { "result": False, @@ -1092,7 +1087,7 @@ class PluginManagerPlugin( if name is None: name = os.path.basename(path) - self._logger.info("Installing single file plugin {} from {}".format(name, source)) + self._logger.info(f"Installing single file plugin {name} from {source}") all_plugins_before = self._plugin_manager.find_plugins(existing={}) @@ -1100,10 +1095,10 @@ class PluginManagerPlugin( plugin_id, _ = os.path.splitext(name) try: - self._log_call("cp {} {}".format(path, destination)) + self._log_call(f"cp {path} {destination}") shutil.copy(path, destination) except Exception: - self._logger.exception("Installing plugin from {} failed".format(source)) + self._logger.exception(f"Installing plugin from {source} failed") result = { "result": False, "source": source, @@ -1221,22 +1216,16 @@ class PluginManagerPlugin( if os.path.isdir(full_path): # plugin is installed via a plugin folder, need to use rmtree to get rid of it - self._log_stdout( - "Deleting plugin from {folder}".format(folder=plugin.location) - ) + self._log_stdout(f"Deleting plugin from {plugin.location}") shutil.rmtree(full_path) elif os.path.isfile(full_path): - self._log_stdout( - "Deleting plugin from {file}".format(file=plugin.location) - ) + self._log_stdout(f"Deleting plugin from {plugin.location}") os.remove(full_path) if full_path.endswith(".py"): pyc_file = "{full_path}c".format(**locals()) if os.path.isfile(pyc_file): - self._log_stdout( - "Deleting plugin from {file}".format(file=pyc_file) - ) + self._log_stdout(f"Deleting plugin from {pyc_file}") os.remove(pyc_file) else: @@ -1270,9 +1259,7 @@ class PluginManagerPlugin( if plugin.enabled: self._plugin_manager.disable_plugin(plugin.key, plugin=plugin) except octoprint.plugin.core.PluginLifecycleException as e: - self._logger.exception( - "Problem disabling plugin {name}".format(name=plugin.key) - ) + self._logger.exception(f"Problem disabling plugin {plugin.key}") result = { "result": False, "uninstalled": True, @@ -1287,9 +1274,7 @@ class PluginManagerPlugin( if plugin.loaded: self._plugin_manager.unload_plugin(plugin.key) except octoprint.plugin.core.PluginLifecycleException as e: - self._logger.exception( - "Problem unloading plugin {name}".format(name=plugin.key) - ) + self._logger.exception(f"Problem unloading plugin {plugin.key}") result = { "result": False, "uninstalled": True, @@ -1316,7 +1301,7 @@ class PluginManagerPlugin( "plugin": self._to_external_plugin(plugin), } self._send_result_notification("uninstall", result) - self._logger.info("Plugin {} uninstalled".format(plugin.key)) + self._logger.info(f"Plugin {plugin.key} uninstalled") self._cleanup_disabled(plugin.key) if cleanup: @@ -1337,7 +1322,7 @@ class PluginManagerPlugin( key = plugin.key result_value = self._to_external_plugin(plugin) - message = "Cleaning up plugin {}...".format(key) + message = f"Cleaning up plugin {key}..." self._logger.info(message) self._log_stdout(message) @@ -1351,7 +1336,7 @@ class PluginManagerPlugin( # delete plugin data folder result_data = True if not self._cleanup_data(key): - message = "Could not delete data folder of plugin {}".format(key) + message = f"Could not delete data folder of plugin {key}" self._logger.exception(message) self._log_stderr(message) result_data = False @@ -1425,7 +1410,7 @@ class PluginManagerPlugin( return True except Exception: self._logger.exception( - "Could not delete plugin data folder at {}".format(data_folder) + f"Could not delete plugin data folder at {data_folder}" ) return False else: @@ -1679,9 +1664,7 @@ class PluginManagerPlugin( try: import json - with io.open( - self._repository_cache_path, "rt", encoding="utf-8" - ) as f: + with open(self._repository_cache_path, encoding="utf-8") as f: repo_data = json.load(f) self._repository_mtime = mtime self._logger.info( @@ -1707,9 +1690,7 @@ class PluginManagerPlugin( try: r = requests.get(repository_url, timeout=30) r.raise_for_status() - self._logger.info( - "Loaded plugin repository data from {}".format(repository_url) - ) + self._logger.info(f"Loaded plugin repository data from {repository_url}") except Exception as e: self._logger.exception( "Could not fetch plugins from repository at {repository_url}: {message}".format( @@ -1721,13 +1702,13 @@ class PluginManagerPlugin( try: repo_data = r.json() except Exception as e: - self._logger.exception("Error while reading repository data: {}".format(e)) + self._logger.exception(f"Error while reading repository data: {e}") return None # validation if not isinstance(repo_data, (list, tuple)): self._logger.warning( - "Invalid repository data: expected a list, got {!r}".format(repo_data) + f"Invalid repository data: expected a list, got {repo_data!r}" ) return None @@ -1774,7 +1755,7 @@ class PluginManagerPlugin( try: import json - with io.open(self._notices_cache_path, "rt", encoding="utf-8") as f: + with open(self._notices_cache_path, encoding="utf-8") as f: notice_data = json.load(f) self._notices_mtime = mtime self._logger.info("Loaded notice data from disk, was still valid") @@ -1798,7 +1779,7 @@ class PluginManagerPlugin( try: r = requests.get(notices_url, timeout=30) r.raise_for_status() - self._logger.info("Loaded plugin notices data from {}".format(notices_url)) + self._logger.info(f"Loaded plugin notices data from {notices_url}") except Exception as e: self._logger.exception( "Could not fetch notices from {notices_url}: {message}".format( diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index a30f161ff..f821fa89f 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -5,7 +5,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import copy import hashlib -import io import logging import logging.handlers import os @@ -334,9 +333,7 @@ class SoftwareUpdatePlugin( data = psutil.disk_usage(path) info["free"] = data.free except Exception: - self._logger.exception( - "Error while determining disk usage of {}".format(path) - ) + self._logger.exception(f"Error while determining disk usage of {path}") continue storage_info[key] = info @@ -372,15 +369,13 @@ class SoftwareUpdatePlugin( ) def _get_check_overlay(self, url): - self._logger.info("Fetching check overlays from {}".format(url)) + self._logger.info(f"Fetching check overlays from {url}") try: r = requests.get(url, timeout=3.1) r.raise_for_status() data = r.json() except Exception as exc: - self._logger.error( - "Could not fetch check overlay from {}: {}".format(url, exc) - ) + self._logger.error(f"Could not fetch check overlay from {url}: {exc}") return {} else: return data @@ -426,7 +421,7 @@ class SoftwareUpdatePlugin( import yaml try: - with io.open(self._version_cache_path, "rt", encoding="utf-8") as f: + with open(self._version_cache_path, encoding="utf-8") as f: data = yaml.safe_load(f) timestamp = os.stat(self._version_cache_path).st_mtime except Exception: @@ -1140,9 +1135,7 @@ class SoftwareUpdatePlugin( try: populated_check = self._populated_check(target, checks[target]) except exceptions.UnknownCheckType: - self._logger.debug( - "Ignoring unknown check type for target {}".format(target) - ) + self._logger.debug(f"Ignoring unknown check type for target {target}") continue except Exception: self._logger.exception( @@ -1310,7 +1303,7 @@ class SoftwareUpdatePlugin( continue except Exception: self._logger.exception( - "Could not check {} for updates".format(target) + f"Could not check {target} for updates" ) continue @@ -1461,7 +1454,7 @@ class SoftwareUpdatePlugin( if isinstance(value, dict): lines.append("{!r}: {}".format(key, dict_to_sorted_repr(value))) else: - lines.append("{!r}: {!r}".format(key, value)) + lines.append(f"{key!r}: {value!r}") return "{" + ", ".join(lines) + "}" @@ -1538,7 +1531,7 @@ class SoftwareUpdatePlugin( error = "unknown_check" except exceptions.NetworkError: self._logger.warning( - "Could not check {} for updates due to a network error".format(target) + f"Could not check {target} for updates due to a network error" ) update_possible = False error = "network" @@ -1552,12 +1545,12 @@ class SoftwareUpdatePlugin( error = "ratelimit" except exceptions.CheckError: self._logger.warning( - "Could not check {} for updates due to a check error".format(target) + f"Could not check {target} for updates due to a check error" ) update_possible = False error = "check" except Exception: - self._logger.exception("Could not check {} for updates".format(target)) + self._logger.exception(f"Could not check {target} for updates") update_possible = False error = "unknown" else: @@ -1567,9 +1560,7 @@ class SoftwareUpdatePlugin( target, check, online=online ) except Exception: - self._logger.exception( - "Error while checking if {} can be updated".format(target) - ) + self._logger.exception(f"Error while checking if {target} can be updated") update_possible = False self._version_cache[target] = { @@ -1609,9 +1600,7 @@ class SoftwareUpdatePlugin( try: populated_checks[target] = self._populated_check(target, check) except exceptions.UnknownCheckType: - self._logger.debug( - "Ignoring unknown check type for target {}".format(target) - ) + self._logger.debug(f"Ignoring unknown check type for target {target}") except Exception: self._logger.exception( "Error while populating check prior to update for target {}".format( @@ -1800,9 +1789,7 @@ class SoftwareUpdatePlugin( populated_check = self._populated_check(target, check) try: - self._logger.info( - "Starting update of {} to {}...".format(target, target_version) - ) + self._logger.info(f"Starting update of {target} to {target_version}...") self._send_client_message( "updating", { @@ -1819,9 +1806,7 @@ class SoftwareUpdatePlugin( target, populated_check, target_version, log_cb=self._log, online=online ) target_result = ("success", update_result) - self._logger.info( - "Update of {} to {} successful!".format(target, target_version) - ) + self._logger.info(f"Update of {target} to {target_version} successful!") trigger_event(True) except exceptions.UnknownUpdateType: @@ -1926,10 +1911,10 @@ class SoftwareUpdatePlugin( util.execute(restart_command, evaluate_returncode=False, do_async=True) except exceptions.ScriptError as e: self._logger.exception( - "Error while restarting via command {}".format(restart_command) + f"Error while restarting via command {restart_command}" ) - self._logger.warning("Restart stdout:\n{}".format(e.stdout)) - self._logger.warning("Restart stderr:\n{}".format(e.stderr)) + self._logger.warning(f"Restart stdout:\n{e.stdout}") + self._logger.warning(f"Restart stderr:\n{e.stderr}") raise exceptions.RestartFailed() def _populated_check(self, target, check): @@ -2067,7 +2052,7 @@ class SoftwareUpdatePlugin( data={"loglines": [{"line": line, "stream": stream} for line in lines]}, ) for line in lines: - self._console_logger.debug("{} {}".format(prefix, line)) + self._console_logger.debug(f"{prefix} {line}") def _send_client_message(self, message_type, data=None): self._plugin_manager.send_plugin_message( diff --git a/src/octoprint/plugins/softwareupdate/cli.py b/src/octoprint/plugins/softwareupdate/cli.py index 0c9b2c0f4..4590f0b96 100644 --- a/src/octoprint/plugins/softwareupdate/cli.py +++ b/src/octoprint/plugins/softwareupdate/cli.py @@ -62,7 +62,7 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs): try: r.raise_for_status() except requests.exceptions.HTTPError as e: - click.echo("Could not get update information from server, got {}".format(e)) + click.echo(f"Could not get update information from server, got {e}") sys.exit(1) data = r.json() @@ -230,7 +230,7 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs): try: r.raise_for_status() except requests.exceptions.HTTPError as e: - click.echo("Could not get update information from server, got {}".format(e)) + click.echo(f"Could not get update information from server, got {e}") sys.exit(1) data = r.json() diff --git a/src/octoprint/plugins/softwareupdate/exceptions.py b/src/octoprint/plugins/softwareupdate/exceptions.py index 6d6d0d892..93fb909b7 100644 --- a/src/octoprint/plugins/softwareupdate/exceptions.py +++ b/src/octoprint/plugins/softwareupdate/exceptions.py @@ -29,7 +29,7 @@ class NetworkError(Exception): if self.message is not None: return self.message elif self.cause is not None: - return "NetworkError caused by {}".format(self.cause) + return f"NetworkError caused by {self.cause}" else: return "NetworkError" diff --git a/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py b/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py index 9f03044cd..0a9873553 100644 --- a/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py +++ b/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py @@ -91,14 +91,12 @@ def _execute(command, **kwargs): if not p.commands[0].process: # the process might have been set to None in case of any exception print( - "Error while trying to run command {}".format(joined_command), + f"Error while trying to run command {joined_command}", file=sys.stderr, ) return None, [], [] except Exception: - print( - "Error while trying to run command {}".format(joined_command), file=sys.stderr - ) + print(f"Error while trying to run command {joined_command}", file=sys.stderr) traceback.print_exc(file=sys.stderr) return None, [], [] @@ -214,7 +212,7 @@ def _rescue_changes(git_executable, folder): ) if returncode is None or returncode != 0: raise RuntimeError( - 'Could not update, "git diff" failed with returncode {}'.format(returncode) + f'Could not update, "git diff" failed with returncode {returncode}' ) if stdout and "".join(stdout).strip(): # we got changes in the working tree, maybe from the user, so we'll now rescue those into a patch @@ -222,9 +220,9 @@ def _rescue_changes(git_executable, folder): import time timestamp = time.strftime("%Y%m%d%H%M") - patch = os.path.join(folder, "{}-preupdate.patch".format(timestamp)) + patch = os.path.join(folder, f"{timestamp}-preupdate.patch") - print(">>> Running: git diff and saving output to {}".format(patch)) + print(f">>> Running: git diff and saving output to {patch}") returncode, stdout, stderr = _git(["diff"], folder, git_executable=git_executable) if returncode is None or returncode != 0: raise RuntimeError( @@ -233,9 +231,7 @@ def _rescue_changes(git_executable, folder): ) ) - import io - - with io.open(patch, "wt", encoding="utf-8", errors="replace") as f: + with open(patch, "wt", encoding="utf-8", errors="replace") as f: for line in stdout: f.write(line) @@ -274,11 +270,11 @@ def update_source(git_executable, folder, target, force=False, branch=None): returncode, stdout, stderr = _git(["fetch"], folder, git_executable=git_executable) if returncode is None or returncode != 0: raise RuntimeError( - 'Could not update, "git fetch" failed with returncode {}'.format(returncode) + f'Could not update, "git fetch" failed with returncode {returncode}' ) if branch is not None and branch.strip() != "": - print(">>> Running: git checkout {}".format(branch)) + print(f">>> Running: git checkout {branch}") returncode, stdout, stderr = _git( ["checkout", branch], folder, git_executable=git_executable ) @@ -293,7 +289,7 @@ def update_source(git_executable, folder, target, force=False, branch=None): returncode, stdout, stderr = _git(["pull"], folder, git_executable=git_executable) if returncode is None or returncode != 0: raise RuntimeError( - 'Could not update, "git pull" failed with returncode {}'.format(returncode) + f'Could not update, "git pull" failed with returncode {returncode}' ) if force: @@ -316,7 +312,7 @@ def install_source(python_executable, folder, user=False, sudo=False): print(">>> Running: python setup.py clean") returncode, stdout, stderr = _python(["setup.py", "clean"], folder, python_executable) if returncode is None or returncode != 0: - print('"python setup.py clean" failed with returncode {}'.format(returncode)) + print(f'"python setup.py clean" failed with returncode {returncode}') print("Continuing anyways") print(">>> Running: python setup.py install") @@ -407,7 +403,7 @@ def main(): if python_executable.endswith('"'): python_executable = python_executable[:-1] - print("Python executable: {!r}".format(python_executable)) + print(f"Python executable: {python_executable!r}") folder = args.folder diff --git a/src/octoprint/plugins/softwareupdate/updaters/pip.py b/src/octoprint/plugins/softwareupdate/updaters/pip.py index e10e15131..b1dfbcdcb 100644 --- a/src/octoprint/plugins/softwareupdate/updaters/pip.py +++ b/src/octoprint/plugins/softwareupdate/updaters/pip.py @@ -98,7 +98,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc target_version=target_version, target=target_version ) - logger.debug("Target: {}, executing pip install {}".format(target, install_arg)) + logger.debug(f"Target: {target}, executing pip install {install_arg}") pip_args = ["--disable-pip-version-check", "install", install_arg, "--no-cache-dir"] pip_kwargs = { "env": {"PYTHONWARNINGS": b"ignore:DEPRECATION::pip._internal.cli.base_command"} diff --git a/src/octoprint/plugins/softwareupdate/updaters/single_file_plugin.py b/src/octoprint/plugins/softwareupdate/updaters/single_file_plugin.py index 9e39ea6c5..6af58a171 100644 --- a/src/octoprint/plugins/softwareupdate/updaters/single_file_plugin.py +++ b/src/octoprint/plugins/softwareupdate/updaters/single_file_plugin.py @@ -2,7 +2,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp __copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License" import ast -import io import logging import os import shutil @@ -46,7 +45,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc folder = None try: try: - _log_message("Download file from {}".format(url)) + _log_message(f"Download file from {url}") folder = TemporaryDirectory() path = download_file(url, folder.name) except Exception as exc: @@ -55,29 +54,25 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc filename = os.path.basename(path) _, ext = os.path.splitext(filename) if ext not in (".py",): - raise exceptions.UpdateError( - "File is not a python file: {}".format(filename), None - ) + raise exceptions.UpdateError(f"File is not a python file: {filename}", None) try: - with io.open(path, "rb") as f: + with open(path, "rb") as f: ast.parse(f.read(), filename=path) except Exception: - logger.exception("Could not parse {} as python file".format(path), None) + logger.exception(f"Could not parse {path} as python file", None) raise exceptions.UpdateError( - "Could not parse {} as python file.".format(filename), None + f"Could not parse {filename} as python file.", None ) destination = os.path.join(settings().getBaseFolder("plugins"), filename) try: - _log_message("Copy {} to {}".format(path, destination)) + _log_message(f"Copy {path} to {destination}") shutil.copy(path, destination) except Exception: - logger.exception("Could not copy {} to {}".format(path, destination)) - raise exceptions.UpdateError( - "Could not copy {} to {}".format(path, destination), None - ) + logger.exception(f"Could not copy {path} to {destination}") + raise exceptions.UpdateError(f"Could not copy {path} to {destination}", None) return "ok" finally: diff --git a/src/octoprint/plugins/softwareupdate/updaters/update_script.py b/src/octoprint/plugins/softwareupdate/updaters/update_script.py index 2bf31153f..d0b1ee44c 100644 --- a/src/octoprint/plugins/softwareupdate/updaters/update_script.py +++ b/src/octoprint/plugins/softwareupdate/updaters/update_script.py @@ -78,9 +78,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True): ### pre update if pre_update_script is not None: - logger.debug( - "Target: {}, running pre-update script: {}".format(target, pre_update_script) - ) + logger.debug(f"Target: {target}, running pre-update script: {pre_update_script}") try: caller.checked_call(pre_update_script, cwd=folder) except CommandlineError as e: @@ -100,9 +98,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True): force="true" if force_exact_version else "false", ) - logger.debug( - "Target {}, running update script: {}".format(target, update_command) - ) + logger.debug(f"Target {target}, running update script: {update_command}") caller.checked_call(update_command, cwd=folder) except CommandlineError as e: diff --git a/src/octoprint/plugins/softwareupdate/util.py b/src/octoprint/plugins/softwareupdate/util.py index 69f83dcc2..f9b2a2922 100644 --- a/src/octoprint/plugins/softwareupdate/util.py +++ b/src/octoprint/plugins/softwareupdate/util.py @@ -27,9 +27,7 @@ def execute(command, cwd=None, evaluate_returncode=True, **kwargs): async_=do_async, ) except Exception: - logging.getLogger(__name__).exception( - "Error while executing command: {}".format(command) - ) + logging.getLogger(__name__).exception(f"Error while executing command: {command}") returncode = p.returncode if p is not None else None stdout = p.stdout.text if p is not None and p.stdout is not None else "" stderr = p.stderr.text if p is not None and p.stderr is not None else "" diff --git a/src/octoprint/plugins/softwareupdate/version_checks/__init__.py b/src/octoprint/plugins/softwareupdate/version_checks/__init__.py index b831968d5..737fbe3ce 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/__init__.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/__init__.py @@ -21,7 +21,7 @@ from . import ( # noqa: F401 class GithubRateLimitCheckError(RateLimitCheckError): def __init__(self, remaining, ratelimit, reset): if reset: - message = "Github rate limit exceeded, reset at {}".format(reset) + message = f"Github rate limit exceeded, reset at {reset}" else: message = "Github rate limit exceeded" super().__init__(message, remaining=remaining, limit=ratelimit, reset=reset) diff --git a/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py b/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py index 66c298426..45a51d824 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py @@ -24,7 +24,7 @@ def _get_latest_commit(user, repo, branch, api_user=None, api_password=None): auth_value = base64.b64encode( b"{user}:{pw}".format(user=api_user, pw=api_password) ) - headers["authorization"] = "Basic {}".format(auth_value) + headers["authorization"] = f"Basic {auth_value}" try: r = requests.get(url, headers=headers, timeout=(3.05, 30)) @@ -79,19 +79,13 @@ def get_latest(target, check, online=True, credentials=None, *args, **kwargs): remote_commit = _get_latest_commit( check["user"], check["repo"], branch, api_user, api_password ) - remote_name = ( - "Commit {commit}".format(commit=remote_commit) - if remote_commit is not None - else "-" - ) + remote_name = f"Commit {remote_commit}" if remote_commit is not None else "-" information["remote"] = {"name": remote_name, "value": remote_commit} is_current = ( current is not None and current == remote_commit ) or remote_commit is None - logger.debug( - "Target: {}, local: {}, remote: {}".format(target, current, remote_commit) - ) + logger.debug(f"Target: {target}, local: {current}, remote: {remote_commit}") return information, is_current diff --git a/src/octoprint/plugins/softwareupdate/version_checks/commandline.py b/src/octoprint/plugins/softwareupdate/version_checks/commandline.py index c5f226018..42ec5d963 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/commandline.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/commandline.py @@ -56,8 +56,6 @@ def get_latest(target, check, online=True, *args, **kwargs): logger = logging.getLogger( "octoprint.plugins.softwareupdate.version_checks.github_commit" ) - logger.debug( - "Target: {}, local: {}, remote: {}".format(target, local_name, remote_name) - ) + logger.debug(f"Target: {target}, local: {local_name}, remote: {remote_name}") return information, is_current diff --git a/src/octoprint/plugins/softwareupdate/version_checks/git_commit.py b/src/octoprint/plugins/softwareupdate/version_checks/git_commit.py index 96ab26569..1fa0e3591 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/git_commit.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/git_commit.py @@ -97,8 +97,6 @@ def get_latest(target, check, online=True, *args, **kwargs): logger = logging.getLogger( "octoprint.plugins.softwareupdate.version_checks.git_commit" ) - logger.debug( - "Target: {}, local: {}, remote: {}".format(target, local_commit, remote_commit) - ) + logger.debug(f"Target: {target}, local: {local_commit}, remote: {remote_commit}") return information, is_current diff --git a/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py b/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py index 56187b0fe..551dd7d69 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py @@ -83,19 +83,13 @@ def get_latest(target, check, online=True, credentials=None, *args, **kwargs): remote_commit = _get_latest_commit( check["user"], check["repo"], branch, apikey=apikey ) - remote_name = ( - "Commit {commit}".format(commit=remote_commit) - if remote_commit is not None - else "-" - ) + remote_name = f"Commit {remote_commit}" if remote_commit is not None else "-" information["remote"] = {"name": remote_name, "value": remote_commit} is_current = ( current is not None and current == remote_commit ) or remote_commit is None - logger.debug( - "Target: {}, local: {}, remote: {}".format(target, current, remote_commit) - ) + logger.debug(f"Target: {target}, local: {current}, remote: {remote_commit}") return information, is_current diff --git a/src/octoprint/plugins/softwareupdate/version_checks/github_release.py b/src/octoprint/plugins/softwareupdate/version_checks/github_release.py index 19690a3c4..c755bf639 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/github_release.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/github_release.py @@ -198,7 +198,7 @@ def _get_comparable_version_semantic(version_string, force_base=True): version = semantic_version.Version.coerce(version_string, partial=False) if force_base: - version_string = "{}.{}.{}".format(version.major, version.minor, version.patch) + version_string = f"{version.major}.{version.minor}.{version.patch}" version = semantic_version.Version.coerce(version_string, partial=False) return version @@ -355,7 +355,7 @@ def get_latest( "release_notes": release_notes, } - logger.debug("Target: {}, local: {}, remote: {}".format(target, current, remote_tag)) + logger.debug(f"Target: {target}, local: {current}, remote: {remote_tag}") return information, _is_current( information, compare_type, custom=custom_compare, force_base=force_base diff --git a/src/octoprint/plugins/softwareupdate/version_checks/httpheader.py b/src/octoprint/plugins/softwareupdate/version_checks/httpheader.py index ce8232e63..0d1d48107 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/httpheader.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/httpheader.py @@ -26,7 +26,7 @@ def get_latest(target, check, online=True, *args, **kwargs): method = check.get("header_method", "head") prefix = check.get("header_prefix", header) if prefix: - prefix = "{} ".format(prefix) + prefix = f"{prefix} " try: with requests.request(method, url) as r: diff --git a/src/octoprint/plugins/tracking/__init__.py b/src/octoprint/plugins/tracking/__init__.py index 1119ef04f..20cf99e52 100644 --- a/src/octoprint/plugins/tracking/__init__.py +++ b/src/octoprint/plugins/tracking/__init__.py @@ -479,7 +479,7 @@ class TrackingPlugin( # Don't print the URL or UUID! That would expose the UUID in forums/tickets # if pasted. It's okay for the user to know their uuid, but it shouldn't be shared. - headers = {"User-Agent": "OctoPrint/{}".format(get_octoprint_version_string())} + headers = {"User-Agent": f"OctoPrint/{get_octoprint_version_string()}"} try: params = urlencode(kwargs, doseq=True).replace("+", "%20") @@ -488,9 +488,7 @@ class TrackingPlugin( else: requests.get(url, params=params, timeout=3.1, headers=headers) - self._logger.info( - "Sent tracking event {}, payload: {!r}".format(event, kwargs) - ) + self._logger.info(f"Sent tracking event {event}, payload: {kwargs!r}") except Exception: if self._logger.isEnabledFor(logging.DEBUG): self._logger.exception( diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py index 756a79656..8ab167149 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -3,7 +3,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp import collections -import io import json import math import os @@ -300,7 +299,7 @@ class VirtualPrinter: @timeout.setter def timeout(self, value): - self._logger.debug("Setting read timeout to {}s".format(value)) + self._logger.debug(f"Setting read timeout to {value}s") self._read_timeout = value @property @@ -309,7 +308,7 @@ class VirtualPrinter: @write_timeout.setter def write_timeout(self, value): - self._logger.debug("Setting write timeout to {}s".format(value)) + self._logger.debug(f"Setting write timeout to {value}s") self._write_timeout = value @property @@ -493,7 +492,7 @@ class VirtualPrinter: try: # if we have a method _gcode_G, _gcode_M or _gcode_T, execute that first - letter_handler = "_gcode_{}".format(letter) + letter_handler = f"_gcode_{letter}" if hasattr(self, letter_handler): code = command_match.group(2) handled = getattr(self, letter_handler)(code, data) @@ -501,7 +500,7 @@ class VirtualPrinter: continue # then look for a method _gcode_ and execute that if it exists - command_handler = "_gcode_{}".format(command) + command_handler = f"_gcode_{command}" if hasattr(self, command_handler): handled = getattr(self, command_handler)(data) if handled: @@ -541,7 +540,7 @@ class VirtualPrinter: self.currentExtruder = t self._send("Active Extruder: %d" % self.currentExtruder) else: - self._send("echo:T{} Invalid extruder ".format(t)) + self._send(f"echo:T{t} Invalid extruder ") # noinspection PyUnusedLocal def _gcode_F(self, code, data): @@ -685,7 +684,7 @@ class VirtualPrinter: if not self._okBeforeCommandOutput: ok = self._ok() if ok: - output = "{} {}".format(self._ok(), output) + output = f"{self._ok()} {output}" self._send(output) return True @@ -1233,7 +1232,7 @@ class VirtualPrinter: | Unsets the busy loop. """ for line in usage.split("\n"): - self._send("echo: {}".format(line.strip())) + self._send(f"echo: {line.strip()}") elif data == "action_pause": self._send("// action:pause") elif data == "action_resume": @@ -1303,9 +1302,7 @@ class VirtualPrinter: if sleep_match is not None: interval = int(sleep_match.group(1)) - self._send( - "// sleeping for {interval} seconds".format(interval=interval) - ) + self._send(f"// sleeping for {interval} seconds") self._debug_sleep = interval elif sleep_after_match is not None: command = sleep_after_match.group(1) @@ -1460,7 +1457,7 @@ class VirtualPrinter: ["smoothieTemperatureReporting"] ): continue - temps["T{}".format(i)] = (self.temp[i], self.targetTemp[i]) + temps[f"T{i}"] = (self.temp[i], self.targetTemp[i]) if self._settings.get_boolean(["hasBed"]): temps["B"] = (self.bedTemp, self.bedTargetTemp) @@ -1497,7 +1494,7 @@ class VirtualPrinter: if includeOk: ok = self._ok() if ok: - output = "{} {}".format(ok, output) + output = f"{ok} {output}" self._send(output) def _parseHotendCommand( @@ -1739,7 +1736,7 @@ class VirtualPrinter: handle = None try: - handle = io.open(file, "wt", encoding="utf-8") + handle = open(file, "wt", encoding="utf-8") except Exception: self._send("error writing to file") self._writingToSdHandle = handle @@ -1761,7 +1758,7 @@ class VirtualPrinter: def _sdPrintingWorker(self): self._selectedSdFilePos = 0 try: - with io.open(self._selectedSdFile, "rt", encoding="utf-8") as f: + with open(self._selectedSdFile, encoding="utf-8") as f: for line in iter(f.readline, ""): if self._killed or not self._sdPrinting: break @@ -1922,7 +1919,7 @@ class VirtualPrinter: def loop(): while self._busy: - self._send("echo:busy {}".format(self._busy)) + self._send(f"echo:busy {self._busy}") time.sleep(self._busyInterval) self._sendOk() @@ -1936,9 +1933,9 @@ class VirtualPrinter: def _showPrompt(self, text, choices): self._hidePrompt() - self._send("//action:prompt_begin {}".format(text)) + self._send(f"//action:prompt_begin {text}") for choice in choices: - self._send("//action:prompt_button {}".format(choice)) + self._send(f"//action:prompt_button {choice}") self._send("//action:prompt_show") def _hidePrompt(self): @@ -1962,7 +1959,7 @@ class VirtualPrinter: return 0 if b"M112" in data and self._supportM112: - self._seriallog.info("<<< {}".format(u_data)) + self._seriallog.info(f"<<< {u_data}") self._kill() return len(data) @@ -1970,7 +1967,7 @@ class VirtualPrinter: written = self.incoming.put( data, timeout=self._write_timeout, partial=True ) - self._seriallog.info("<<< {}".format(u_data)) + self._seriallog.info(f"<<< {u_data}") return written except queue.Full: self._logger.info( @@ -2008,7 +2005,7 @@ class VirtualPrinter: try: # fetch a line from the queue, wait no longer than timeout line = to_unicode(self.outgoing.get(timeout=timeout), errors="replace") - self._seriallog.info(">>> {}".format(line.strip())) + self._seriallog.info(f">>> {line.strip()}") self.outgoing.task_done() return to_bytes(line) except queue.Empty: @@ -2062,13 +2059,13 @@ class VirtualEEPROM: def _initialise_eeprom(self): if os.path.exists(self._eeprom_file_path): # file exists, read it - with io.open(self._eeprom_file_path, "rt", encoding="utf-8") as eeprom_file: + with open(self._eeprom_file_path, encoding="utf-8") as eeprom_file: data = json.load(eeprom_file) return data else: # no eeprom file, make new one with defaults data = self.get_default_settings() - with io.open(self._eeprom_file_path, "wt", encoding="utf-8") as eeprom_file: + with open(self._eeprom_file_path, "wt", encoding="utf-8") as eeprom_file: eeprom_file.write(to_unicode(json.dumps(data))) return data @@ -2179,7 +2176,7 @@ class VirtualEEPROM: def save_settings(self): # M500 behind-the-scenes - with io.open(self._eeprom_file_path, "wt", encoding="utf-8") as eeprom_file: + with open(self._eeprom_file_path, "wt", encoding="utf-8") as eeprom_file: eeprom_file.write(to_unicode(json.dumps(self._eeprom))) def read_settings(self): @@ -2187,7 +2184,7 @@ class VirtualEEPROM: if not os.path.exists(self._eeprom_file_path): self.load_defaults() self.save_settings() - with io.open(self._eeprom_file_path, "rt") as eeprom_file: + with open(self._eeprom_file_path) as eeprom_file: self._eeprom = json.load(eeprom_file) def load_defaults(self): diff --git a/src/octoprint/printer/profile.py b/src/octoprint/printer/profile.py index cd7d44831..2d16336f9 100644 --- a/src/octoprint/printer/profile.py +++ b/src/octoprint/printer/profile.py @@ -145,7 +145,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import copy -import io import logging import os from os import scandir @@ -475,7 +474,7 @@ class PrinterProfileManager: try: profile = self._load_from_path(path) except InvalidProfileError: - self._logger.warning("Profile {} is invalid, skipping".format(identifier)) + self._logger.warning(f"Profile {identifier} is invalid, skipping") continue if profile is None: @@ -503,7 +502,7 @@ class PrinterProfileManager: import yaml - with io.open(path, "rt", encoding="utf-8") as f: + with open(path, encoding="utf-8") as f: profile = yaml.safe_load(f) if profile is None or not isinstance(profile, dict): diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index ffea6cc7a..8adc36a53 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -44,7 +44,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): from collections import deque self._logger = logging.getLogger(__name__) - self._logger_job = logging.getLogger("{}.job".format(__name__)) + self._logger_job = logging.getLogger(f"{__name__}.job") self._dict = ( frozendict @@ -104,13 +104,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): try: estimator = hook() if estimator is not None: - self._logger.info( - "Using print time estimator provided by {}".format(name) - ) + self._logger.info(f"Using print time estimator provided by {name}") self._estimator_factory = estimator except Exception: self._logger.exception( - "Error while processing analysis queues from {}".format(name), + f"Error while processing analysis queues from {name}", extra={"plugin": name}, ) @@ -277,7 +275,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): plugin_data[name] = additional except ValueError: self._logger.exception( - "Invalid additional data from plugin {}".format(name), + f"Invalid additional data from plugin {name}", extra={"plugin": name}, ) except Exception: @@ -444,7 +442,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): # this code preserves existing CamelCase event_name = name[0].upper() + name[1:] - event_start = "GcodeScript{}Running".format(event_name) + event_start = f"GcodeScript{event_name}Running" payload = context.get("event", None) if isinstance(context, dict) else None eventManager().fire(event_start, payload) @@ -458,7 +456,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): if not result and must_be_set: raise UnknownScript(name) - event_end = "GcodeScript{}Finished".format(event_name) + event_end = f"GcodeScript{event_name}Finished" eventManager().fire(event_end, payload) def jog(self, axes, relative=True, speed=None, *args, **kwargs): @@ -470,9 +468,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): raise ValueError("amount not set") amount = args[0] if not isinstance(amount, (int, float)): - raise ValueError( - "amount must be a valid number: {amount}".format(amount=amount) - ) + raise ValueError(f"amount must be a valid number: {amount}") axes = {} axes[axis] = amount @@ -489,7 +485,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): ) command = "G1 {}".format( - " ".join(["{}{}".format(axis.upper(), amt) for axis, amt in axes.items()]) + " ".join([f"{axis.upper()}{amt}" for axis, amt in axes.items()]) ) if speed is None: @@ -497,7 +493,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): speed = min([printer_profile["axes"][axis]["speed"] for axis in axes]) if speed and not isinstance(speed, bool): - command += " F{}".format(speed) + command += f" F{speed}" if relative: commands = ["G91", command, "G90"] @@ -511,9 +507,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): if isinstance(axes, str): axes = [axes] else: - raise ValueError( - "axes is neither a list nor a string: {axes}".format(axes=axes) - ) + raise ValueError(f"axes is neither a list nor a string: {axes}") validated_axes = list( filter( @@ -521,7 +515,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): ) ) if len(axes) != len(validated_axes): - raise ValueError("axes contains invalid axes: {axes}".format(axes=axes)) + raise ValueError(f"axes contains invalid axes: {axes}") self.commands( [ @@ -534,9 +528,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): def extrude(self, amount, speed=None, *args, **kwargs): if not isinstance(amount, (int, float)): - raise ValueError( - "amount must be a valid number: {amount}".format(amount=amount) - ) + raise ValueError(f"amount must be a valid number: {amount}") printer_profile = self._printerProfileManager.get_current_or_default() @@ -557,7 +549,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): def change_tool(self, tool, *args, **kwargs): if not PrinterInterface.valid_tool_regex.match(tool): - raise ValueError('tool must match "tool[0-9]+": {tool}'.format(tool=tool)) + raise ValueError(f'tool must match "tool[0-9]+": {tool}') tool_num = int(tool[len("tool") :]) self.commands( @@ -574,9 +566,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): ) if not isinstance(value, (int, float)) or value < 0: - raise ValueError( - "value must be a valid number >= 0: {value}".format(value=value) - ) + raise ValueError(f"value must be a valid number >= 0: {value}") tags = kwargs.get("tags", set()) | {"trigger:printer.set_temperature"} @@ -586,15 +576,15 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): shared_nozzle = printer_profile["extruder"]["sharedNozzle"] if extruder_count > 1 and not shared_nozzle: toolNum = int(heater[len("tool") :]) - self.commands("M104 T{} S{}".format(toolNum, value), tags=tags) + self.commands(f"M104 T{toolNum} S{value}", tags=tags) else: - self.commands("M104 S{}".format(value), tags=tags) + self.commands(f"M104 S{value}", tags=tags) elif heater == "bed": - self.commands("M140 S{}".format(value), tags=tags) + self.commands(f"M140 S{value}", tags=tags) elif heater == "chamber": - self.commands("M141 S{}".format(value), tags=tags) + self.commands(f"M141 S{value}", tags=tags) def set_temperature_offset(self, offsets=None, *args, **kwargs): if offsets is None: @@ -611,13 +601,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): ) if len(validated_keys) != len(offsets): - raise ValueError( - "offsets contains invalid keys: {offsets}".format(offsets=offsets) - ) + raise ValueError(f"offsets contains invalid keys: {offsets}") if len(validated_values) != len(offsets): - raise ValueError( - "offsets contains invalid values: {offsets}".format(offsets=offsets) - ) + raise ValueError(f"offsets contains invalid values: {offsets}") if self._comm is None: return @@ -633,9 +619,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): factor = int(factor * 100) if min_val and factor < min_val: - raise ValueError("factor must be a value >={}".format(min_val)) + raise ValueError(f"factor must be a value >={min_val}") elif max_val and factor > max_val: - raise ValueError("factor must be a value <={}".format(max_val)) + raise ValueError(f"factor must be a value <={max_val}") return factor @@ -973,7 +959,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): sd_upload_succeeded, sd_upload_failed, *args, - **kwargs + **kwargs, ) if result is not None: return result @@ -1163,7 +1149,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): ) except Exception: self._logger.exception( - "Error while estimating print time via {}".format(estimator) + f"Error while estimating print time via {estimator}" ) return self._dict( @@ -1212,9 +1198,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): def _validateJob(self, filename, sd): if not valid_file_type(filename, type="machinecode"): - raise InvalidFileType( - "{} is not a machinecode file, cannot print".format(filename) - ) + raise InvalidFileType(f"{filename} is not a machinecode file, cannot print") if sd: return diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 9d1d2eadf..534c28e91 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -4,7 +4,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import atexit import base64 -import io import logging import logging.config import mimetypes @@ -393,7 +392,7 @@ class Server: analysis_queue_factories.update(**additional_factories) except Exception: self._logger.exception( - "Error while processing analysis queues from {}".format(name), + f"Error while processing analysis queues from {name}", extra={"plugin": name}, ) analysisQueue = octoprint.filemanager.analysis.AnalysisQueue( @@ -497,7 +496,7 @@ class Server: groupManager = factory(components, self._settings) if groupManager is not None: self._logger.debug( - "Created group manager instance from factory {}".format(name) + f"Created group manager instance from factory {name}" ) break except Exception: @@ -531,7 +530,7 @@ class Server: userManager = factory(components, self._settings) if userManager is not None: self._logger.debug( - "Created user manager instance from factory {}".format(name) + f"Created user manager instance from factory {name}" ) break except Exception: @@ -562,13 +561,11 @@ class Server: try: printer = factory(components) if printer is not None: - self._logger.debug( - "Created printer instance from factory {}".format(name) - ) + self._logger.debug(f"Created printer instance from factory {name}") break except Exception: self._logger.exception( - "Error while creating printer instance from factory {}".format(name), + f"Error while creating printer instance from factory {name}", extra={"plugin": name}, ) else: @@ -1095,7 +1092,7 @@ class Server: connectionOptions = printer.__class__.get_connection_options() if port in connectionOptions["ports"] or port == "AUTO" or port is None: self._logger.info( - "Trying to connect to configured serial port {}".format(port) + f"Trying to connect to configured serial port {port}" ) printer.connect( port=port, @@ -1152,9 +1149,7 @@ class Server: if self._host == "::": if self._v6_only: # only v6 - self._logger.info( - "Listening on http://[::]:{port}".format(port=self._port) - ) + self._logger.info(f"Listening on http://[::]:{self._port}") else: # all v4 and v6 self._logger.info( @@ -1327,7 +1322,7 @@ class Server: logger.info("Server heartbeat <3") interval = settings().getFloat(["server", "heartbeat"]) - logger.info("Starting server heartbeat, {}s interval".format(interval)) + logger.info(f"Starting server heartbeat, {interval}s interval") timer = octoprint.util.RepeatedTimer(interval, log_heartbeat) timer.start() @@ -1427,7 +1422,7 @@ class Server: result.add(locale.language) if locale.territory: # if a territory is specified, add that too - result.add("{}_{}".format(locale.language, locale.territory)) + result.add(f"{locale.language}_{locale.territory}") return result @@ -1495,7 +1490,7 @@ class Server: tag += ' target="_blank" rel="noreferrer noopener"' content = match.group("content") - return "<{tag}>{content}".format(tag=tag, content=content) + return f"<{tag}>{content}" return html_link_regex.sub(repl, text) @@ -1820,7 +1815,7 @@ class Server: if plugin.is_blueprint_protected(): blueprint.before_request(requireLoginRequestHandler) - url_prefix = "/plugin/{name}".format(name=name) + url_prefix = f"/plugin/{name}" app.register_blueprint(blueprint, url_prefix=url_prefix) if self._logger: @@ -1835,7 +1830,7 @@ class Server: def _prepare_asset_plugin(self, plugin): name = plugin._identifier - url_prefix = "/plugin/{name}".format(name=name) + url_prefix = f"/plugin/{name}" blueprint = Blueprint( "plugin." + name, name, static_folder=plugin.get_asset_folder() ) @@ -1895,7 +1890,7 @@ class Server: cli_key_file = os.path.join(self._settings.getBaseFolder("generated"), "cli.key") cli_key = generate_api_key() - with io.open(cli_key_file, "w", encoding="utf8") as f: + with open(cli_key_file, "w", encoding="utf8") as f: f.write(cli_key) return cli_key @@ -2178,7 +2173,7 @@ class Server: js_plugins_bundle = Bundle( *js_plugins.values(), output="webassets/packed_plugins.js", - filters=",".join(js_plugin_filters) + filters=",".join(js_plugin_filters), ) js_app_bundle = Bundle( @@ -2191,7 +2186,7 @@ class Server: js_client_core_bundle = Bundle( *clientjs_core, output="webassets/packed_client_core.js", - filters=",".join(js_filters) + filters=",".join(js_filters), ) if len(clientjs_plugins) == 0: @@ -2200,7 +2195,7 @@ class Server: js_client_plugins_bundle = Bundle( *clientjs_plugins.values(), output="webassets/packed_client_plugins.js", - filters=",".join(js_plugin_filters) + filters=",".join(js_plugin_filters), ) js_client_bundle = Bundle( @@ -2231,7 +2226,7 @@ class Server: css_core_bundle = Bundle( *css_core, output="webassets/packed_core.css", - filters=",".join(css_filters) + filters=",".join(css_filters), ) if len(css_plugins) == 0: @@ -2240,7 +2235,7 @@ class Server: css_plugins_bundle = Bundle( *css_plugins, output="webassets/packed_plugins.css", - filters=",".join(css_filters) + filters=",".join(css_filters), ) css_app_bundle = Bundle( @@ -2265,7 +2260,7 @@ class Server: less_core_bundle = Bundle( *less_core, output="webassets/packed_core.less", - filters=",".join(less_filters) + filters=",".join(less_filters), ) if len(less_plugins) == 0: @@ -2274,7 +2269,7 @@ class Server: less_plugins_bundle = Bundle( *less_plugins, output="webassets/packed_plugins.less", - filters=",".join(less_filters) + filters=",".join(less_filters), ) less_app_bundle = Bundle( @@ -2290,13 +2285,13 @@ class Server: assets.register("js_client_core", js_client_core_bundle) for plugin, bundle in clientjs_plugins.items(): # register our collected clientjs plugin bundles so that they are bound to the environment - assets.register("js_client_plugin_{}".format(plugin), bundle) + assets.register(f"js_client_plugin_{plugin}", bundle) assets.register("js_client_plugins", js_client_plugins_bundle) assets.register("js_client", js_client_bundle) assets.register("js_core", js_core_bundle) for plugin, bundle in js_plugins.items(): # register our collected plugin bundles so that they are bound to the environment - assets.register("js_plugin_{}".format(plugin), bundle) + assets.register(f"js_plugin_{plugin}", bundle) assets.register("js_plugins", js_plugins_bundle) assets.register("js_app", js_app_bundle) assets.register("css_libs", css_libs_bundle) @@ -2387,7 +2382,7 @@ class Server: if not os.path.isfile(path): return "" - with io.open(path, "rb") as f: + with open(path, "rb") as f: data = f.read() return data @@ -2442,9 +2437,7 @@ class Server: if host == "::": if self._v6_only: - self._logger.debug( - "Starting intermediary server on http://[::]:{port}".format(port=port) - ) + self._logger.debug(f"Starting intermediary server on http://[::]:{port}") else: self._logger.debug( "Starting intermediary server on http://0.0.0.0:{port} and http://[::]:{port}".format( @@ -2532,7 +2525,7 @@ class Server: return "{}: {}".format(plugin, definition["name"]) def permission_role(plugin, role): - return "plugin_{}_{}".format(plugin, role) + return f"plugin_{plugin}_{role}" def process_regular_permission(plugin_info, definition): permissions = [] @@ -2562,7 +2555,7 @@ class Server: plugin=plugin_info.key, dangerous=dangerous, default_groups=default_groups, - *roles_and_permissions + *roles_and_permissions, ) setattr( octoprint.access.permissions.Permissions, @@ -2573,7 +2566,7 @@ class Server: plugin=plugin_info.key, dangerous=dangerous, default_groups=default_groups, - *roles_and_permissions + *roles_and_permissions, ), ) @@ -2621,7 +2614,7 @@ class Server: postponed.append((plugin_info, p)) except Exception: self._logger.exception( - "Error while creating permission instance/s from {}".format(name) + f"Error while creating permission instance/s from {name}" ) # final resolution passes diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index 59323a036..83b625e74 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -2,7 +2,6 @@ __author__ = "Gina Häußge " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" -import io import logging from flask import ( @@ -118,7 +117,7 @@ def pluginData(name): raise except Exception: logging.getLogger(__name__).exception( - "Error calling SimpleApiPlugin {}".format(name), extra={"plugin": name} + f"Error calling SimpleApiPlugin {name}", extra={"plugin": name} ) return abort(500) @@ -160,7 +159,7 @@ def pluginCommand(name): raise except Exception: logging.getLogger(__name__).exception( - "Error while executing SimpleApiPlugin {}".format(name), + f"Error while executing SimpleApiPlugin {name}", extra={"plugin": name}, ) return abort(500) @@ -268,7 +267,7 @@ def apiVersion(): return jsonify( server=octoprint.server.VERSION, api=VERSION, - text="OctoPrint {}".format(octoprint.server.DISPLAY_VERSION), + text=f"OctoPrint {octoprint.server.DISPLAY_VERSION}", ) @@ -481,7 +480,7 @@ def _test_path(data): os.makedirs(path) except Exception: logging.getLogger(__name__).exception( - "Error while trying to create {}".format(path) + f"Error while trying to create {path}" ) return jsonify( path=path, @@ -514,12 +513,12 @@ def _test_path(data): if check_writable_dir and check_type == "dir": try: test_path = os.path.join(path, ".testballoon.txt") - with io.open(test_path, "wb") as f: + with open(test_path, "wb") as f: f.write(b"Test") os.remove(test_path) except Exception: logging.getLogger(__name__).exception( - "Error while testing if {} is really writable".format(path) + f"Error while testing if {path} is really writable" ) return jsonify( path=path, @@ -684,7 +683,7 @@ def _test_url(data): response_result["content"] = content except Exception: logging.getLogger(__name__).exception( - "Error while running a test {} request on {}".format(method, url) + f"Error while running a test {method} request on {url}" ) outcome = False diff --git a/src/octoprint/server/api/files.py b/src/octoprint/server/api/files.py index 4ad77af5e..9f61fe403 100644 --- a/src/octoprint/server/api/files.py +++ b/src/octoprint/server/api/files.py @@ -288,7 +288,7 @@ def _getFileList( ) with _file_cache_mutex: - cache_key = "{}:{}:{}:{}".format(origin, path, recursive, filter) + cache_key = f"{origin}:{path}:{recursive}:{filter}" files, lastmodified = _file_cache.get(cache_key, ([], None)) # recursive needs to be True for lastmodified queries so we get lastmodified of whole subtree - #3422 if ( @@ -994,7 +994,7 @@ def gcodeFileCommand(filename, target): with Permissions.FILES_UPLOAD.require(403): # Copy and move are only possible on local storage if target not in [FileDestinations.LOCAL]: - abort(400, description="Unsupported target for {}".format(command)) + abort(400, description=f"Unsupported target for {command}") if not _verifyFileExists(target, filename) and not _verifyFolderExists( target, filename @@ -1026,9 +1026,7 @@ def gcodeFileCommand(filename, target): is_folder = fileManager.folder_exists(target, filename) if not (is_file or is_folder): - abort( - 400, description="Neither file nor folder, can't {}".format(command) - ) + abort(400, description=f"Neither file nor folder, can't {command}") if command == "copy": # destination already there? error... diff --git a/src/octoprint/server/api/languages.py b/src/octoprint/server/api/languages.py index 7815cfdbd..8c86b6386 100644 --- a/src/octoprint/server/api/languages.py +++ b/src/octoprint/server/api/languages.py @@ -2,7 +2,6 @@ __author__ = "Gina Häußge " __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" -import io import logging import os import tarfile @@ -44,7 +43,7 @@ def getInstalledLanguagePacks(): import yaml try: - with io.open(meta_path, "rt", encoding="utf-8") as f: + with open(meta_path, encoding="utf-8") as f: meta = yaml.safe_load(f) except Exception: logging.getLogger(__name__).exception("Could not load %s", meta_path) diff --git a/src/octoprint/server/api/system.py b/src/octoprint/server/api/system.py index 6e6b52eb3..bbe5576d0 100644 --- a/src/octoprint/server/api/system.py +++ b/src/octoprint/server/api/system.py @@ -142,14 +142,14 @@ def executeSystemCommand(source, command): ) ) else: - logger.info("Performing command for {}:{}".format(source, command)) + logger.info(f"Performing command for {source}:{command}") try: if "before" in command_spec and callable(command_spec["before"]): command_spec["before"]() except Exception as e: if not do_ignore: - error = 'Command "before" for {}:{} failed: {}'.format(source, command, e) + error = f'Command "before" for {source}:{command} failed: {e}' logger.warning(error) abort(500, description=error) @@ -192,7 +192,7 @@ def executeSystemCommand(source, command): except Exception as e: if not do_ignore: - error = "Command for {}:{} failed: {}".format(source, command, e) + error = f"Command for {source}:{command} failed: {e}" logger.warning(error) abort(500, error) @@ -297,7 +297,7 @@ def _get_custom_command_specs(): action = spec["action"] if action == "divider": dividers += 1 - action = "divider_{}".format(dividers) + action = f"divider_{dividers}" specs[action] = copied return specs diff --git a/src/octoprint/server/api/timelapse.py b/src/octoprint/server/api/timelapse.py index 4bd38051a..6440eaa84 100644 --- a/src/octoprint/server/api/timelapse.py +++ b/src/octoprint/server/api/timelapse.py @@ -177,9 +177,9 @@ def deleteTimelapse(filename): os.remove(full_path) except Exception as ex: logging.getLogger(__file__).exception( - "Error deleting timelapse file {}".format(full_path) + f"Error deleting timelapse file {full_path}" ) - abort(500, description="Unexpected error: {}".format(ex)) + abort(500, description=f"Unexpected error: {ex}") return getTimelapseData() diff --git a/src/octoprint/server/util/__init__.py b/src/octoprint/server/util/__init__.py index 2bffcb591..68b6f0812 100644 --- a/src/octoprint/server/util/__init__.py +++ b/src/octoprint/server/util/__init__.py @@ -318,7 +318,7 @@ def get_authorization_header(request): def get_plugin_hash(): from octoprint.plugin import plugin_manager - plugin_signature = lambda impl: "{}:{}".format(impl._identifier, impl._plugin_version) + plugin_signature = lambda impl: f"{impl._identifier}:{impl._plugin_version}" template_plugins = list( map( plugin_signature, diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index ffa3b956d..7b38990a9 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -5,7 +5,6 @@ __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 functools -import io import logging import os import threading @@ -151,9 +150,7 @@ def enable_additional_translations(default_locale="en", additional_folders=None) ) break else: - logger.debug( - "No translations for locale {} in core folders".format(locale) - ) + logger.debug(f"No translations for locale {locale} in core folders") translations = translations.merge(core_translations) ctx.babel_translations = translations @@ -215,7 +212,7 @@ def fix_webassets_cache(): filename = os.path.join(self.directory, "%s" % hash) try: - f = io.open(filename, "rb") + f = open(filename, "rb") except OSError as e: if e.errno != errno.ENOENT: error_logger.exception( @@ -615,7 +612,7 @@ def _local_networks(): continue local_networks.add(network) - logger.debug("Added network {} to localNetworks".format(network)) + logger.debug(f"Added network {network} to localNetworks") if network.version == 4: network_v6 = network.ipv6() @@ -664,9 +661,7 @@ def passive_login(): def determine_user(u): if not u.is_anonymous and u.is_active: # known active user - logger.info( - "Passively logging in user {} from {}".format(u.get_id(), remote_address) - ) + logger.info(f"Passively logging in user {u.get_id()} from {remote_address}") elif ( settings().getBoolean(["accessControl", "autologinLocal"]) @@ -998,9 +993,7 @@ class PreemptiveCache: entries = cleanup_function(root, entries) if not entries: del all_data[root] - self._logger.debug( - "Removed root {} from preemptive cache".format(root) - ) + self._logger.debug(f"Removed root {root} from preemptive cache") elif len(entries) < old_count: all_data[root] = entries self._logger.debug( @@ -1018,7 +1011,7 @@ class PreemptiveCache: cache_data = None with self._lock: try: - with io.open(self.cachefile, "rt") as f: + with open(self.cachefile) as f: cache_data = yaml.safe_load(f) except OSError as e: import errno @@ -1026,7 +1019,7 @@ class PreemptiveCache: if e.errno != errno.ENOENT: raise except Exception: - self._logger.exception("Error while reading {}".format(self.cachefile)) + self._logger.exception(f"Error while reading {self.cachefile}") if cache_data is None: cache_data = {} @@ -1057,7 +1050,7 @@ class PreemptiveCache: allow_unicode=True, ) except Exception: - self._logger.exception("Error while writing {}".format(self.cachefile)) + self._logger.exception(f"Error while writing {self.cachefile}") def set_data(self, root, data): with self._lock: @@ -1106,12 +1099,12 @@ class PreemptiveCache: to_persist = copy.deepcopy(data) to_persist["_timestamp"] = time.time() to_persist["_count"] = 1 - self._logger.info("Adding entry for {} and {!r}".format(root, to_persist)) + self._logger.info(f"Adding entry for {root} and {to_persist!r}") else: to_persist["_timestamp"] = time.time() to_persist["_count"] = to_persist.get("_count", 0) + 1 self._logger.debug( - "Updating timestamp and counter for {} and {!r}".format(root, data) + f"Updating timestamp and counter for {root} and {data!r}" ) self.set_data(root, [to_persist] + other) @@ -1150,7 +1143,7 @@ def preemptively_cached(cache, data, unless=None): cache.record(data, unless=unless) except Exception: logging.getLogger(__name__).exception( - "Error while recording preemptive cache entry: {!r}".format(data) + f"Error while recording preemptive cache entry: {data!r}" ) return f(*args, **kwargs) diff --git a/src/octoprint/server/util/sockjs.py b/src/octoprint/server/util/sockjs.py index 845810db6..ac6b33b9a 100644 --- a/src/octoprint/server/util/sockjs.py +++ b/src/octoprint/server/util/sockjs.py @@ -173,9 +173,9 @@ class PrinterStateConnection( def __str__(self): if self._remoteAddress: - return "{!r} connected to {}".format(self, self._remoteAddress) + return f"{self!r} connected to {self._remoteAddress}" else: - return "Unconnected {!r}".format(self) + return f"Unconnected {self!r}" def on_open(self, info): self._pluginManager.register_message_receiver(self.on_plugin_message) @@ -279,7 +279,7 @@ class PrinterStateConnection( self._on_login(user) else: self._logger.warning( - "Unknown user/session combo: {}:{}".format(user_id, user_session) + f"Unknown user/session combo: {user_id}:{user_session}" ) self._on_logout() @@ -437,9 +437,7 @@ class PrinterStateConnection( and hasattr(self._user, "session") and user.session == self._user.session ): - self._logger.info( - "User {} logged out, logging out on socket".format(user.get_id()) - ) + self._logger.info(f"User {user.get_id()} logged out, logging out on socket") self._on_logout() if stale: @@ -453,7 +451,7 @@ class PrinterStateConnection( def on_user_removed(self, userid): if self._user.get_id() == userid: - self._logger.info("User {} deleted, logging out on socket".format(userid)) + self._logger.info(f"User {userid} deleted, logging out on socket") self._on_logout() self._sendReauthRequired("removed") @@ -477,7 +475,7 @@ class PrinterStateConnection( proceed = proceed and hook(self, self._user) except Exception: self._logger.exception( - "Error processing register hook handler for plugin {}".format(name), + f"Error processing register hook handler for plugin {name}", extra={"plugin": name}, ) @@ -542,7 +540,7 @@ class PrinterStateConnection( proceed = proceed and hook(self, self._user, type, payload) except Exception: self._logger.exception( - "Error processing emit hook handler from plugin {}".format(name), + f"Error processing emit hook handler from plugin {name}", extra={"plugin": name}, ) @@ -585,7 +583,7 @@ class PrinterStateConnection( except Exception as e: if self._logger.isEnabledFor(logging.DEBUG): self._logger.exception( - "Could not send message to client {}".format(self._remoteAddress) + f"Could not send message to client {self._remoteAddress}" ) else: self._logger.warning( @@ -608,7 +606,7 @@ class PrinterStateConnection( hook(self, self._user) except Exception: self._logger.exception( - "Error processing authed hook handler for plugin {}".format(name), + f"Error processing authed hook handler for plugin {name}", extra={"plugin": name}, ) @@ -641,6 +639,6 @@ class PrinterStateConnection( hook(self, self._user) except Exception: self._logger.exception( - "Error processing authed hook handler for plugin {}".format(name), + f"Error processing authed hook handler for plugin {name}", extra={"plugin": name}, ) diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py index 37e082677..32ff80e25 100644 --- a/src/octoprint/server/util/tornado.py +++ b/src/octoprint/server/util/tornado.py @@ -1186,7 +1186,7 @@ class LargeResponseHandler( etag = str(self.get_content_version(self.absolute_path)) if not etag.endswith('"'): - etag = '"{}"'.format(etag) + etag = f'"{etag}"' return etag # noinspection PyAttributeOutsideInit @@ -1330,7 +1330,7 @@ class UrlProxyHandler( if not extension: return None - return "{}{}".format(self._basename, extension) + return f"{self._basename}{extension}" class StaticDataHandler( @@ -1373,7 +1373,7 @@ class DeprecatedEndpointHandler(CorsSupportMixin, tornado.web.RequestHandler): def _handle_method(self, *args, **kwargs): to_url = self._url.format(*args) self._logger.info( - "Redirecting deprecated endpoint {} to {}".format(self.request.path, to_url) + f"Redirecting deprecated endpoint {self.request.path} to {to_url}" ) self.redirect(to_url, permanent=True) @@ -1431,7 +1431,7 @@ class StaticZipBundleHandler(CorsSupportMixin, tornado.web.RequestHandler): if self._as_attachment: self.set_header( "Content-Disposition", - 'attachment; filename="{}"'.format(self.get_attachment_name()), + f'attachment; filename="{self.get_attachment_name()}"', ) import zipstream @@ -1576,7 +1576,7 @@ class SystemInfoBundleHandler(CorsSupportMixin, tornado.web.RequestHandler): self.set_header("Content-Type", "application/zip") self.set_header( "Content-Disposition", - 'attachment; filename="{}"'.format(get_systeminfo_bundle_name()), + f'attachment; filename="{get_systeminfo_bundle_name()}"', ) for chunk in z: diff --git a/src/octoprint/server/util/watchdog.py b/src/octoprint/server/util/watchdog.py index 3d0aa85dc..f060685e0 100644 --- a/src/octoprint/server/util/watchdog.py +++ b/src/octoprint/server/util/watchdog.py @@ -57,7 +57,7 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler): if not self._valid_path(path): continue - self._logger.info("Found {}, trying to add it".format(path)) + self._logger.info(f"Found {path}, trying to add it") self._upload(path) self._logger.info("... initial scan done.") @@ -147,7 +147,7 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler): # file is still there - that should only happen if something went wrong, so mark it as failed # noinspection PyBroadException try: - shutil.move(path, "{}.failed".format(path)) + shutil.move(path, f"{path}.failed") except Exception: # something went really wrong here.... but we can't do anything about it, so just log it self._logger.exception( @@ -190,7 +190,7 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler): last_size = new_size time.sleep(interval) - self._logger.debug("File at {} is stable, moving it".format(path)) + self._logger.debug(f"File at {path} is stable, moving it") self._upload(path) def _valid_path(self, path): diff --git a/src/octoprint/server/views.py b/src/octoprint/server/views.py index 4ba4a5254..04dcf1344 100644 --- a/src/octoprint/server/views.py +++ b/src/octoprint/server/views.py @@ -4,7 +4,6 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms import base64 import datetime -import io import logging import os import re @@ -104,7 +103,7 @@ def _preemptive_data( d.update(data) except Exception: _logger.exception( - "Error collecting data for preemptive cache from plugin {}".format(key) + f"Error collecting data for preemptive cache from plugin {key}" ) # add additional request data if we have any @@ -129,7 +128,7 @@ def _cache_key(ui, url=None, locale=None, additional_key_data=None): if locale is None: locale = g.locale.language if g.locale else "en" - k = "ui:{}:{}:{}".format(ui, url, locale) + k = f"ui:{ui}:{url}:{locale}" if callable(additional_key_data): try: ak = additional_key_data() @@ -160,7 +159,7 @@ def _add_additional_assets(hook): result += assets except Exception: _logger.exception( - "Error fetching theming CSS to include from plugin {}".format(name), + f"Error fetching theming CSS to include from plugin {name}", extra={"plugin": name}, ) return result @@ -273,7 +272,7 @@ def in_cache(): break except Exception: _logger.exception( - "Error while calling plugin {}, skipping it".format(plugin._identifier), + f"Error while calling plugin {plugin._identifier}, skipping it", extra={"plugin": plugin._identifier}, ) else: @@ -297,9 +296,7 @@ def in_cache(): ) return response elif util.flask.is_in_cache(key): - _logger.info( - "Found path {} in cache (key: {}), signaling as cached".format(path, key) - ) + _logger.info(f"Found path {path} in cache (key: {key}), signaling as cached") return response elif util.flask.is_cache_bypassed(key): _logger.info( @@ -309,9 +306,7 @@ def in_cache(): ) return response else: - _logger.debug( - "Path {} not yet cached (key: {}), signaling as missing".format(path, key) - ) + _logger.debug(f"Path {path} not yet cached (key: {key}), signaling as missing") return abort(404) @@ -619,7 +614,7 @@ def index(): if forced_view: # we have view forced by the preemptive cache - _logger.debug("Forcing rendering of view {}".format(forced_view)) + _logger.debug(f"Forcing rendering of view {forced_view}") if forced_view != "_default": plugin = pluginManager.get_plugin_info(forced_view, require_enabled=True) if plugin is not None and isinstance( @@ -706,7 +701,7 @@ def _get_render_kwargs(templates, plugin_names, plugin_vars, now): permissions = [permission.as_dict() for permission in Permissions.all()] filetypes = list(sorted(full_extension_tree().keys())) - extensions = list(map(lambda ext: ".{}".format(ext), get_all_extensions())) + extensions = list(map(lambda ext: f".{ext}", get_all_extensions())) # ~~ prepare full set of template vars for rendering @@ -1684,7 +1679,7 @@ def _get_translations(locale, domain): def messages_from_po(path, locale, domain): messages = {} - with io.open(path, mode="rt", encoding="utf-8") as f: + with open(path, mode="rt", encoding="utf-8") as f: catalog = read_po(f, locale=locale, domain=domain) for message in catalog: diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 92d6a4b74..c911a2b12 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -22,7 +22,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import copy import fnmatch -import io import logging import os import re @@ -976,7 +975,7 @@ class Settings: def load(self, migrate=False): if os.path.exists(self._configfile) and os.path.isfile(self._configfile): - with io.open(self._configfile, "rt", encoding="utf-8", errors="replace") as f: + with open(self._configfile, encoding="utf-8", errors="replace") as f: try: self._config = yaml.safe_load(f) self._mtime = self.last_modified @@ -1017,11 +1016,9 @@ class Settings: try: overlay_config = self.load_overlay(path, migrate=migrate) self.add_overlay(overlay_config) - self._logger.info("Added config overlay from {}".format(path)) + self._logger.info(f"Added config overlay from {path}") except Exception: - self._logger.exception( - "Could not add config overlay from {}".format(path) - ) + self._logger.exception(f"Could not add config overlay from {path}") if os.path.isfile(overlay): process(overlay) @@ -1048,7 +1045,7 @@ class Settings: if isinstance(overlay, str): if os.path.exists(overlay) and os.path.isfile(overlay): - with io.open(overlay, "rt", encoding="utf-8", errors="replace") as f: + with open(overlay, encoding="utf-8", errors="replace") as f: config = yaml.safe_load(f) elif isinstance(overlay, dict): config = overlay @@ -1059,7 +1056,7 @@ class Settings: if not isinstance(config, dict): raise ValueError( - "Configuration data must be a dict but is a {}".format(config.__class__) + f"Configuration data must be a dict but is a {config.__class__}" ) if migrate: @@ -2000,7 +1997,7 @@ class Settings: preprocessors=None, error_on_path=False, *args, - **kwargs + **kwargs, ): if not path: if error_on_path: @@ -2185,7 +2182,7 @@ def _validate_folder( if not os.path.exists(folder): if os.path.islink(folder): # broken symlink, see #2644 - raise OSError("Folder at {} appears to be a broken symlink".format(folder)) + raise OSError(f"Folder at {folder} appears to be a broken symlink") elif create: # non existing, but we are allowed to create it @@ -2193,7 +2190,7 @@ def _validate_folder( os.makedirs(folder) except Exception: if log_error: - logger.exception("Could not create {}".format(folder)) + logger.exception(f"Could not create {folder}") raise OSError( "Folder for type {} at {} does not exist and creation failed".format( type, folder @@ -2202,11 +2199,11 @@ def _validate_folder( else: # not extisting, not allowed to create it - raise OSError("No such folder: {}".format(folder)) + raise OSError(f"No such folder: {folder}") elif os.path.isfile(folder): # hardening against misconfiguration, see #1953 - raise OSError("Expected a folder at {} but found a file instead".format(folder)) + raise OSError(f"Expected a folder at {folder} but found a file instead") elif check_writable: # make sure we can also write into the folder @@ -2221,10 +2218,10 @@ def _validate_folder( # to determine whether things are *actually* writable testfile = os.path.join(folder, ".testballoon.txt") try: - with io.open(testfile, "wt", encoding="utf-8") as f: + with open(testfile, "wt", encoding="utf-8") as f: f.write("test") os.remove(testfile) except Exception: if log_error: - logger.exception("Could not write test file to {}".format(folder)) + logger.exception(f"Could not write test file to {folder}") raise OSError(error) diff --git a/src/octoprint/slicing/__init__.py b/src/octoprint/slicing/__init__.py index c22f74b7a..a005ff8fb 100644 --- a/src/octoprint/slicing/__init__.py +++ b/src/octoprint/slicing/__init__.py @@ -724,9 +724,7 @@ class SlicingManager: name = self._sanitize(name) - path = os.path.join( - self.get_slicer_profile_path(slicer), "{name}.profile".format(name=name) - ) + path = os.path.join(self.get_slicer_profile_path(slicer), f"{name}.profile") if not os.path.realpath(path).startswith(os.path.realpath(self._profile_path)): raise OSError( "Path to profile {name} tried to break out of allows sub path".format( diff --git a/src/octoprint/slicing/exceptions.py b/src/octoprint/slicing/exceptions.py index 7d0d68287..0036890bb 100644 --- a/src/octoprint/slicing/exceptions.py +++ b/src/octoprint/slicing/exceptions.py @@ -67,7 +67,7 @@ class SlicerNotConfigured(SlicerException): def __init__(self, slicer, *args, **kwargs): SlicerException.__init__(self, slicer, *args, **kwargs) - self.message = "Slicer not configured: {slicer}".format(slicer=slicer) + self.message = f"Slicer not configured: {slicer}" class UnknownSlicer(SlicerException): @@ -77,7 +77,7 @@ class UnknownSlicer(SlicerException): def __init__(self, slicer, *args, **kwargs): SlicerException.__init__(self, slicer, *args, **kwargs) - self.message = "No such slicer: {slicer}".format(slicer=slicer) + self.message = f"No such slicer: {slicer}" class ProfileException(Exception): diff --git a/src/octoprint/timelapse.py b/src/octoprint/timelapse.py index 637a78859..3117f9384 100644 --- a/src/octoprint/timelapse.py +++ b/src/octoprint/timelapse.py @@ -5,7 +5,6 @@ import collections import datetime import fnmatch import glob -import io import logging import os import queue @@ -201,7 +200,7 @@ def delete_unrendered_timelapse(name): except Exception: if logging.getLogger(__name__).isEnabledFor(logging.DEBUG): logging.getLogger(__name__).exception( - "Error while processing file {} during cleanup".format(entry.name) + f"Error while processing file {entry.name} during cleanup" ) @@ -259,14 +258,12 @@ def delete_old_unrendered_timelapses(): except Exception: if logging.getLogger(__name__).isEnabledFor(logging.DEBUG): logging.getLogger(__name__).exception( - "Error while processing file {} during cleanup".format(entry.name) + f"Error while processing file {entry.name} during cleanup" ) for prefix in prefixes_to_clean: delete_unrendered_timelapse(prefix) - logging.getLogger(__name__).info( - "Deleted old unrendered timelapse {}".format(prefix) - ) + logging.getLogger(__name__).info(f"Deleted old unrendered timelapse {prefix}") def _create_render_start_handler(name, gcode=None): @@ -682,7 +679,7 @@ class Timelapse: ) self._image_number += 1 - self._logger.debug("Capturing image to {}".format(filename)) + self._logger.debug(f"Capturing image to {filename}") entry = { "type": self.__class__.QUEUE_ENTRY_TYPE_CAPTURE, "filename": filename, @@ -728,9 +725,7 @@ class Timelapse: eventManager().fire(Events.CAPTURE_START, {"file": filename}) try: - self._logger.debug( - "Going to capture {} from {}".format(filename, self._snapshot_url) - ) + self._logger.debug(f"Going to capture {filename} from {self._snapshot_url}") r = requests.get( self._snapshot_url, stream=True, @@ -739,18 +734,16 @@ class Timelapse: ) r.raise_for_status() - with io.open(filename, "wb") as f: + with open(filename, "wb") as f: for chunk in r.iter_content(chunk_size=1024): if chunk: f.write(chunk) f.flush() - self._logger.debug( - "Image {} captured from {}".format(filename, self._snapshot_url) - ) + self._logger.debug(f"Image {filename} captured from {self._snapshot_url}") except Exception as e: self._logger.exception( - "Could not capture image {} from {}".format(filename, self._snapshot_url) + f"Could not capture image {filename} from {self._snapshot_url}" ) self._capture_errors += 1 err = e @@ -993,7 +986,7 @@ class TimelapseRenderJob: postfix=self._postfix if self._postfix is not None else "", extension=extension, ) - temporary = os.path.join(self._output_dir, ".{}".format(output_name)) + temporary = os.path.join(self._output_dir, f".{output_name}") output = os.path.join(self._output_dir, output_name) for i in range(4): @@ -1034,7 +1027,7 @@ class TimelapseRenderJob: rotate=rotate, watermark=watermark, ) - self._logger.debug("Executing command: {}".format(command_str)) + self._logger.debug(f"Executing command: {command_str}") with self.render_job_lock: try: @@ -1075,7 +1068,7 @@ class TimelapseRenderJob: os.remove(temporary) except Exception: self._logger.warning( - "Could not delete temporary timelapse {}".format(temporary) + f"Could not delete temporary timelapse {temporary}" ) self._notify_callback("always", output) @@ -1155,7 +1148,7 @@ class TimelapseRenderJob: "-framerate", str(fps), "-i", - '"{}"'.format(input), + f'"{input}"', "-vcodec", videocodec, "-threads", @@ -1174,12 +1167,12 @@ class TimelapseRenderJob: ) if filter_string is not None: - logger.debug("Applying videofilter chain: {}".format(filter_string)) + logger.debug(f"Applying videofilter chain: {filter_string}") command.extend(["-vf", sarge.shell_quote(filter_string)]) # finalize command with output file - logger.debug("Rendering movie to {}".format(output)) - command.append('"{}"'.format(output)) + logger.debug(f"Rendering movie to {output}") + command.append(f'"{output}"') return " ".join(command) @@ -1204,7 +1197,7 @@ class TimelapseRenderJob: ### See unit tests in test/timelapse/test_timelapse_renderjob.py # apply pixel format - filters = ["format={}".format(pixfmt)] + filters = [f"format={pixfmt}"] # flip video if configured if hflip: @@ -1236,7 +1229,7 @@ class TimelapseRenderJob: def _notify_callback(self, callback, *args, **kwargs): """Notifies registered callbacks of type `callback`.""" - name = "_on_{}".format(callback) + name = f"_on_{callback}" method = getattr(self, name, None) if method is not None and callable(method): method(*args, **kwargs) diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 3ef281f2c..143e5111d 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -10,7 +10,6 @@ import collections import contextlib import copy import glob -import io import logging import os import queue @@ -334,7 +333,7 @@ def get_formatted_size(num): for x in ["B", "KB", "MB", "GB"]: if num < 1024: - return "{:3.1f}{}".format(num, x) + return f"{num:3.1f}{x}" num /= 1024 return "{:3.1f}{}".format(num, "TB") @@ -1253,7 +1252,7 @@ else: os.remove(self._path) except Exception as exc: logging.getLogger(__name__).warning( - "Could not delete temporary directory {}: {}".format(self.name, exc) + f"Could not delete temporary directory {self.name}: {exc}" ) def __enter__(self): @@ -1279,13 +1278,13 @@ def bom_aware_open(filename, encoding="ascii", mode="r", **kwargs): # these encodings might have a BOM, so let's see if there is one bom = getattr(codecs, potential_bom_attribute) - with io.open(filename, mode="rb") as f: + with open(filename, mode="rb") as f: header = f.read(4) if header.startswith(bom): encoding += "-sig" - return io.open(filename, encoding=encoding, mode=mode, **kwargs) + return open(filename, encoding=encoding, mode=mode, **kwargs) def is_hidden_path(path): @@ -1764,7 +1763,7 @@ class TypedQueue(PrependableQueue): if item_type is not None: if item_type in self._lookup: raise TypeAlreadyInQueue( - item_type, "Type {} is already in queue".format(item_type) + item_type, f"Type {item_type} is already in queue" ) else: self._lookup.add(item_type) @@ -1785,7 +1784,7 @@ class TypedQueue(PrependableQueue): if item_type is not None: if item_type in self._lookup: raise TypeAlreadyInQueue( - item_type, "Type {} is already in queue".format(item_type) + item_type, f"Type {item_type} is already in queue" ) else: self._lookup.add(item_type) @@ -1842,7 +1841,7 @@ def fqfn(f): f.__self__.__class__.__module__, f.__self__.__class__.__name__, f.__name__ ) else: - return "{}.{}".format(f.__module__, f.__name__) + return f"{f.__module__}.{f.__name__}" def time_this( diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 154255124..b41965569 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -158,9 +158,7 @@ Groups will be as follows: * ``es``: multiple E coordinates if present, to be parsed further with regex_e_positions """ -regex_e_positions = re.compile( - r"E(?P\d+):\s*(?P{float})".format(float=regex_float_pattern) -) +regex_e_positions = re.compile(fr"E(?P\d+):\s*(?P{regex_float_pattern})") """Regex for matching multiple E coordinates in a position report. Groups will be as follows: @@ -248,7 +246,7 @@ def baudrateList(candidates=None): candidates.insert(0, int(additional)) except Exception: _logger.warning( - "{} is not a valid additional baudrate, ignoring it".format(additional) + f"{additional} is not a valid additional baudrate, ignoring it" ) # blacklisted baudrates @@ -354,7 +352,7 @@ class TemperatureRecord: def set_custom(self, identifier, actual=None, target=None): if self.RESERVED_IDENTIFIER_REGEX.match(identifier): - raise ValueError("{} is a reserved identifier".format(identifier)) + raise ValueError(f"{identifier} is a reserved identifier") current = self._custom.get(identifier, (None, None)) self._custom[identifier] = self._to_new_tuple(current, actual, target) @@ -869,7 +867,7 @@ class MachineCom: def _to_logfile_with_terminal(self, message=None, level=logging.INFO): log = "Last lines in terminal:\n" + "\n".join( - map(lambda x: "| {}".format(x), list(self._terminal_log)) + map(lambda x: f"| {x}", list(self._terminal_log)) ) if message is not None: log = message + "\n| " + log @@ -942,7 +940,7 @@ class MachineCom: return "Offline after error" elif state == self.STATE_TRANSFERING_FILE: return "Transferring file to SD" - return "Unknown State ({})".format(self._state) + return f"Unknown State ({self._state})" def getErrorString(self): return self._errorValue @@ -1305,7 +1303,7 @@ class MachineCom: else: return None - additional_tags = {"plugin:{}".format(name)} + additional_tags = {f"plugin:{name}"} if len(retval) == 4: additional_tags |= set(retval[3]) @@ -1356,7 +1354,7 @@ class MachineCom: tags_to_use = tags | { "trigger:comm.send_gcode_script", "source:script", - "script:{}".format(scriptName), + f"script:{scriptName}", } for line in scriptLines: if ( @@ -1401,7 +1399,7 @@ class MachineCom: "Starting job on behalf of plugin {}".format(tag[7:]) ) elif "source:api" in tags: - self._logger.info("Starting job on behalf of user {}".format(user)) + self._logger.info(f"Starting job on behalf of user {user}") try: with self._jobLock: @@ -1435,7 +1433,7 @@ class MachineCom: if pos is not None and isinstance(pos, int) and pos > 0: self._currentFile.pos = pos self.sendCommand( - "M26 S{}".format(pos), + f"M26 S{pos}", part_of_job=True, tags=tags | { @@ -1650,7 +1648,7 @@ class MachineCom: "Cancelling job on behalf of plugin {}".format(tag[7:]) ) elif "source:api" in tags: - self._logger.info("Cancelling job on behalf of user {}".format(user)) + self._logger.info(f"Cancelling job on behalf of user {user}") if self.isStreaming(): # we are streaming, we handle cancelling that differently... @@ -1787,7 +1785,7 @@ class MachineCom: "Pausing/resuming job on behalf of plugin {}".format(tag[7:]) ) elif user: - self._logger.info("Pausing/resuming job on behalf of user {}".format(user)) + self._logger.info(f"Pausing/resuming job on behalf of user {user}") valid_paused_states = (self.STATE_PAUSED, self.STATE_PAUSING) valid_running_states = ( @@ -2005,7 +2003,7 @@ class MachineCom: tags = set() self.sendCommand( - "M110 N{}".format(number), + f"M110 N{number}", part_of_job=part_of_job, tags=tags | { @@ -2052,7 +2050,7 @@ class MachineCom: return except Exception: self._logger.exception( - "Error while processing temperatures in {}, skipping".format(name), + f"Error while processing temperatures in {name}, skipping", extra={"plugin": name}, ) @@ -2462,7 +2460,7 @@ class MachineCom: else: # multiple extruder coordinates provided, find current one self.last_position.e = ( - parsed.get("e{}".format(self._currentTool)) + parsed.get(f"e{self._currentTool}") if not self.isSdFileSelected() else None ) @@ -2590,7 +2588,7 @@ class MachineCom: if not self._firmware_info_received and firmware_name: firmware_name = firmware_name.strip() self._logger.info( - 'Printer reports firmware name "{}"'.format(firmware_name) + f'Printer reports firmware name "{firmware_name}"' ) if self._firmware_detection: @@ -2755,7 +2753,7 @@ class MachineCom: # we actually do send a T command here instead of just settings self._currentTool just in case # we had any scripts or plugins modify stuff due to the prior tool change self.sendCommand( - "T{}".format(fallback_tool), + f"T{fallback_tool}", tags={ "trigger:revert_invalid_tool", }, @@ -3074,9 +3072,7 @@ class MachineCom: # now increment the timeout counter self._consecutive_timeouts += 1 - self._logger.debug( - "Now at {} consecutive timeouts".format(self._consecutive_timeouts) - ) + self._logger.debug(f"Now at {self._consecutive_timeouts} consecutive timeouts") if 0 < consecutive_max < self._consecutive_timeouts: # too many consecutive timeouts, we give up @@ -3133,7 +3129,7 @@ class MachineCom: def _perform_detection_step(self, init=False): def log(message): self._log(message) - self._logger.info("Serial detection: {}".format(message)) + self._logger.info(f"Serial detection: {message}") if init: port = self._port @@ -3191,7 +3187,7 @@ class MachineCom: ) ) self._logger.exception( - "Unexpected error while setting timeout {}".format(timeout) + f"Unexpected error while setting timeout {timeout}" ) else: self._do_send_without_checksum(b"", log=False) # new line to reset things @@ -3220,7 +3216,7 @@ class MachineCom: (p, b) = self._detection_candidates.pop(0) try: - log("Trying port {}, baudrate {}".format(p, b)) + log(f"Trying port {p}, baudrate {b}") if self._serial is None or self._serial.port != p: if not self._open_serial(p, b, trigger_errors=False): log( @@ -3243,9 +3239,7 @@ class MachineCom: b, get_exception_string() ) ) - self._logger.exception( - "Unexpected error while setting baudrate {}".format(b) - ) + self._logger.exception(f"Unexpected error while setting baudrate {b}") error_text = "No more candidates to test, and no working port/baudrate combination detected." self._trigger_error(error_text, "autodetect") @@ -3405,7 +3399,7 @@ class MachineCom: except Exception: interval = 2 self.sendCommand( - "M155 S{}".format(interval), + f"M155 S{interval}", tags={"trigger:comm.set_autoreport_temperature_interval"}, ) @@ -3416,7 +3410,7 @@ class MachineCom: except Exception: interval = 1 self.sendCommand( - "M27 S{}".format(interval), + f"M27 S{interval}", tags={"trigger:comm.set_autoreport_sdstatus_interval"}, ) @@ -3429,7 +3423,7 @@ class MachineCom: except Exception: interval = 2 self.sendCommand( - "M113 S{}".format(interval), + f"M113 S{interval}", tags={"trigger:comm.set_busy_protocol_interval"}, on_sent=callback, ) @@ -3601,7 +3595,7 @@ class MachineCom: def default(_, p, b, timeout): # connect to regular serial port self._dual_log( - "Connecting to port {}, baudrate {}".format(port, baudrate), + f"Connecting to port {port}, baudrate {baudrate}", level=logging.INFO, ) @@ -3841,8 +3835,8 @@ class MachineCom: try: self._log("Recv: {}".format(sanitize_ascii(ret))) except ValueError as e: - self._log("WARN: While reading last line: {}".format(e)) - self._log("Recv: {!r}".format(ret)) + self._log(f"WARN: While reading last line: {e}") + self._log(f"Recv: {ret!r}") if null_pos >= 0: self._logger.warning("Received line:") @@ -3925,8 +3919,8 @@ class MachineCom: line, tags={ "source:file", - "filepos:{}".format(pos), - "fileline:{}".format(lineno), + f"filepos:{pos}", + f"fileline:{lineno}", }, ) self._callback.on_comm_progress() @@ -4419,7 +4413,7 @@ class MachineCom: def _log_command_phase(self, phase, command, *args, **kwargs): if self._phaseLogger.isEnabledFor(logging.DEBUG): output_parts = [ - "phase: {}".format(phase), + f"phase: {phase}", "command: {}".format(to_unicode(command, errors="replace")), ] @@ -4494,8 +4488,8 @@ class MachineCom: hook_results, tags_to_add={ "source:rewrite", - "phase:{}".format(phase), - "plugin:{}".format(name), + f"phase:{phase}", + f"plugin:{name}", }, ) @@ -4598,7 +4592,7 @@ class MachineCom: ) # trigger built-in handler if available - handler = getattr(self, "_atcommand_{}_{}".format(atcommand, phase), None) + handler = getattr(self, f"_atcommand_{atcommand}_{phase}", None) if callable(handler): try: handler(atcommand, parameters, tags=tags) @@ -4931,7 +4925,7 @@ class MachineCom: wait=False, support_r=False, *args, - **kwargs + **kwargs, ): toolNum = self._currentTool toolMatch = regexes_parameters["intT"].search(cmd) @@ -4969,7 +4963,7 @@ class MachineCom: wait=False, support_r=False, *args, - **kwargs + **kwargs, ): match = regexes_parameters["floatS"].search(cmd) if not match and support_r: @@ -4997,7 +4991,7 @@ class MachineCom: wait=False, support_r=False, *args, - **kwargs + **kwargs, ): match = regexes_parameters["floatS"].search(cmd) if not match and support_r: @@ -5087,7 +5081,7 @@ class MachineCom: with self._line_mutex: self._logger.info( - "M110 detected, setting current line number to {}".format(newLineNumber) + f"M110 detected, setting current line number to {newLineNumber}" ) # send M110 command with new line number @@ -5115,9 +5109,7 @@ class MachineCom: for tool in range( self._printerProfileManager.get_current_or_default()["extruder"]["count"] ): - self._do_increment_and_send_with_checksum( - "M104 T{tool} S0".format(tool=tool).encode("ascii") - ) + self._do_increment_and_send_with_checksum(f"M104 T{tool} S0".encode("ascii")) if self._printerProfileManager.get_current_or_default()["heatedBed"]: self._do_increment_and_send_with_checksum(b"M140 S0") @@ -5222,10 +5214,10 @@ class MachineCom: if gcode in self._emergency_commands and gcode != "M112": return self._emergency_force_send( cmd, - "Force-sending {} to the printer".format(gcode), + f"Force-sending {gcode} to the printer", gcode=gcode, *args, - **kwargs + **kwargs, ) if ( @@ -5234,7 +5226,7 @@ class MachineCom: and "trigger:cancel" not in tags and "trigger:pause" not in tags ): - self._logger.info("Pausing print job due to command {}".format(gcode)) + self._logger.info(f"Pausing print job due to command {gcode}") self.setPause(True) if gcode in self._blocked_commands: @@ -5515,9 +5507,7 @@ class PrintingGcodeFileInformation(PrintingFileInformation): """ with self._handle_mutex: if self._handle is None: - self._logger.warning( - "File {} is not open for reading".format(self._filename) - ) + self._logger.warning(f"File {self._filename} is not open for reading") return None, None, None try: @@ -5563,7 +5553,7 @@ class PrintingGcodeFileInformation(PrintingFileInformation): def _report_stats(self): duration = time.monotonic() - self._start_time - self._logger.info("Finished in {:.3f} s.".format(duration)) + self._logger.info(f"Finished in {duration:.3f} s.") pass @@ -5731,7 +5721,7 @@ class SendQueue(PrependableQueue): if item_type is not None: if item_type in self._lookup: raise TypeAlreadyInQueue( - item_type, "Type {} is already in queue".format(item_type) + item_type, f"Type {item_type} is already in queue" ) else: self._lookup.add(item_type) @@ -5748,7 +5738,7 @@ class SendQueue(PrependableQueue): if item_type is not None: if item_type in self._lookup: raise TypeAlreadyInQueue( - item_type, "Type {} is already in queue".format(item_type) + item_type, f"Type {item_type} is already in queue" ) else: self._lookup.add(item_type) @@ -5879,11 +5869,7 @@ def convert_pause_triggers(configured_triggers): for t in triggers.keys(): if len(triggers[t]) > 0: result[t] = re.compile( - "|".join( - map( - lambda pattern: "({pattern})".format(pattern=pattern), triggers[t] - ) - ) + "|".join(map(lambda pattern: f"({pattern})", triggers[t])) ) return result @@ -6500,14 +6486,12 @@ def upload_cli(): def on_comm_file_transfer_started(self, filename, filesize, user=None): # transfer started, report - _logger.info( - "Started file transfer of {}, size {}B".format(filename, filesize) - ) + _logger.info(f"Started file transfer of {filename}, size {filesize}B") self.started = True def on_comm_file_transfer_done(self, filename): # transfer done, report, print stats and finish - _logger.info("Finished file transfer of {}".format(filename)) + _logger.info(f"Finished file transfer of {filename}") self.finished.set() def on_comm_state_change(self, state): diff --git a/src/octoprint/util/commandline.py b/src/octoprint/util/commandline.py index 809c8d26d..68b58b1ec 100644 --- a/src/octoprint/util/commandline.py +++ b/src/octoprint/util/commandline.py @@ -162,7 +162,7 @@ class CommandlineCaller: joined_command = " ".join(command) else: joined_command = command - self._logger.debug("Calling: {}".format(joined_command)) + self._logger.debug(f"Calling: {joined_command}") self.on_log_call(joined_command) delimiter = kwargs.get("delimiter", b"\n") @@ -200,9 +200,7 @@ class CommandlineCaller: if not p.commands[0].process: # the process might have been set to None in case of any exception - self._logger.error( - "Error while trying to run command {}".format(joined_command) - ) + self._logger.error(f"Error while trying to run command {joined_command}") return None, [], [] all_stdout = [] diff --git a/src/octoprint/util/connectivity.py b/src/octoprint/util/connectivity.py index 8059c90cf..eaa39267c 100644 --- a/src/octoprint/util/connectivity.py +++ b/src/octoprint/util/connectivity.py @@ -168,7 +168,7 @@ class ConnectivityChecker: "online": self.online, "enabled": self.enabled, "connection_ok": self._connection_working, - "connection_check": "{}:{}".format(self._host, self._port), + "connection_check": f"{self._host}:{self._port}", } if self._name: result.update( @@ -208,9 +208,7 @@ class ConnectivityChecker: if self._name: if connection_working: - self._logger.debug( - "Checking if we can resolve {}...".format(self._name) - ) + self._logger.debug(f"Checking if we can resolve {self._name}...") resolution_working = len(resolve_host(self._name)) > 0 else: resolution_working = False diff --git a/src/octoprint/util/dev.py b/src/octoprint/util/dev.py index 7100747cc..d3270a431 100644 --- a/src/octoprint/util/dev.py +++ b/src/octoprint/util/dev.py @@ -67,7 +67,7 @@ def log_duration(log=None, with_args=False): arguments = "".join([args_str, sep, kwargs_str]) else: arguments = "..." - context = "{name}({arguments})".format(name=f.__name__, arguments=arguments) + context = f"{f.__name__}({arguments})" with duration_log(context=context, log=log): return f(*args, **kwargs) diff --git a/src/octoprint/util/net.py b/src/octoprint/util/net.py index 911ae2eea..8f9cd05ca 100644 --- a/src/octoprint/util/net.py +++ b/src/octoprint/util/net.py @@ -1,7 +1,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" -import io import logging import os import socket @@ -57,7 +56,7 @@ def get_lan_ranges(additional_private=None): _, prefix = prefix.split("/") addr = strip_interface_tag(address["addr"]) - return netaddr.IPNetwork("{}/{}".format(addr, prefix)) + return netaddr.IPNetwork(f"{addr}/{prefix}") subnets = [] @@ -260,7 +259,7 @@ def download_file(url, folder, max_length=None): path = os.path.abspath(os.path.join(folder, filename)) assert path.startswith(folder) - with io.open(path, "wb") as f: + with open(path, "wb") as f: for chunk in r.iter_content(chunk_size=8192): f.write(chunk) return path diff --git a/src/octoprint/util/pip.py b/src/octoprint/util/pip.py index d0013c09a..67f27cbb7 100644 --- a/src/octoprint/util/pip.py +++ b/src/octoprint/util/pip.py @@ -72,9 +72,7 @@ class PipCaller(CommandlineCaller): # add --no-use-wheel for versions that otherwise break if pip_version in cls.no_use_wheel and "--no-use-wheel" not in args: - logger.debug( - "Version {} needs --no-use-wheel to properly work.".format(pip_version) - ) + logger.debug(f"Version {pip_version} needs --no-use-wheel to properly work.") args.append("--no-use-wheel") # remove --user if it's present and a virtual env is detected @@ -333,7 +331,7 @@ class PipCaller(CommandlineCaller): with _cache_mutex: if not self.ignore_cache and pip_command_str in _cache["version"]: self._logger.debug( - "Using cached pip version information for {}".format(pip_command_str) + f"Using cached pip version information for {pip_command_str}" ) return _cache["version"][pip_command_str] @@ -347,7 +345,7 @@ class PipCaller(CommandlineCaller): if p.returncode != 0: self._logger.warning( - "Error while trying to run pip --version: {}".format(p.stderr.text) + f"Error while trying to run pip --version: {p.stderr.text}" ) return None, None @@ -383,7 +381,7 @@ class PipCaller(CommandlineCaller): ) return None, None - self._logger.info("Version of pip is {}".format(version_segment)) + self._logger.info(f"Version of pip is {version_segment}") result = pip_version, version_segment _cache["version"][pip_command_str] = result @@ -397,7 +395,7 @@ class PipCaller(CommandlineCaller): with _cache_mutex: if not self.ignore_cache and pip_command_str in _cache["setup"]: self._logger.debug( - "Using cached pip setup information for {}".format(pip_command_str) + f"Using cached pip setup information for {pip_command_str}" ) return _cache["setup"][pip_command_str] diff --git a/src/octoprint/util/piptestballoon/setup.py b/src/octoprint/util/piptestballoon/setup.py index a95966768..c0e26335d 100644 --- a/src/octoprint/util/piptestballoon/setup.py +++ b/src/octoprint/util/piptestballoon/setup.py @@ -26,9 +26,9 @@ virtual_env = hasattr(sys, "real_prefix") or ( writable = os.access(install_dir, os.W_OK) lines = [ - "PIP_INSTALL_DIR={}".format(install_dir), - "PIP_VIRTUAL_ENV={}".format(virtual_env), - "PIP_WRITABLE={}".format(writable), + f"PIP_INSTALL_DIR={install_dir}", + f"PIP_VIRTUAL_ENV={virtual_env}", + f"PIP_WRITABLE={writable}", ] # write to stdout diff --git a/src/octoprint/util/version.py b/src/octoprint/util/version.py index 792d66eb5..62e4bce58 100644 --- a/src/octoprint/util/version.py +++ b/src/octoprint/util/version.py @@ -106,7 +106,7 @@ def is_octoprint_compatible(*compatibility_entries, **kwargs): octo_compat.startswith(c) for c in ("<", "<=", "!=", "==", ">=", ">", "~=", "===") ): - octo_compat = ">={}".format(octo_compat) + octo_compat = f">={octo_compat}" s = pkg_resources.Requirement.parse("OctoPrint" + octo_compat) if octoprint_version in s: diff --git a/src/octoprint_client/__init__.py b/src/octoprint_client/__init__.py index 6b5fafb73..6ce5df44f 100644 --- a/src/octoprint_client/__init__.py +++ b/src/octoprint_client/__init__.py @@ -1,7 +1,6 @@ __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" -import io import json import time @@ -13,12 +12,12 @@ def build_base_url( https=False, httpuser=None, httppass=None, host=None, port=None, prefix=None ): protocol = "https" if https else "http" - httpauth = "{}:{}@".format(httpuser, httppass) if httpuser and httppass else "" + httpauth = f"{httpuser}:{httppass}@" if httpuser and httppass else "" host = host if host else "127.0.0.1" - port = ":{}".format(port) if port else ":5000" + port = f":{port}" if port else ":5000" prefix = prefix if prefix else "" - return "{}://{}{}{}{}".format(protocol, httpauth, host, port, prefix) + return f"{protocol}://{httpauth}{host}{port}{prefix}" class SocketTimeout(BaseException): @@ -287,14 +286,12 @@ class Client: import os if not os.path.isfile(file_path): - raise ValueError( - "{} cannot be uploaded since it is not a file".format(file_path) - ) + raise ValueError(f"{file_path} cannot be uploaded since it is not a file") if file_name is None: file_name = os.path.basename(file_path) - with io.open(file_path, "rb") as fp: + with open(file_path, "rb") as fp: if content_type: files = {"file": (file_name, fp, content_type)} else: @@ -411,7 +408,7 @@ class Client: class CustomSocketClient(SocketClient): def auth(self, username, key): - self.send({"auth": "{}:{}".format(username, key)}) + self.send({"auth": f"{username}:{key}"}) def throttle(self, factor): self.send({"throttle": factor}) diff --git a/src/octoprint_setuptools/__init__.py b/src/octoprint_setuptools/__init__.py index 682ee5d0a..80feb3acf 100644 --- a/src/octoprint_setuptools/__init__.py +++ b/src/octoprint_setuptools/__init__.py @@ -485,9 +485,9 @@ class PackTranslation(Command): print("Adding {entry_path} as {new_prefix}".format(**locals())) zip.write(entry_path, new_prefix) - meta_str = "last_update: {date}\n".format(date=now.isoformat()) + meta_str = f"last_update: {now.isoformat()}\n" if self.author: - meta_str += "author: {author}\n".format(author=self.author) + meta_str += f"author: {self.author}\n" zip_locale_root = self.__class__.pack_path_prefix + locale @@ -636,7 +636,7 @@ def create_plugin_setup_parameters( [package] + list( filter( - lambda x: x.startswith("{package}.".format(package=package)), + lambda x: x.startswith(f"{package}."), find_packages(where=source_folder, exclude=ignored_packages), ) ) diff --git a/tests/filemanager/test_localstorage.py b/tests/filemanager/test_localstorage.py index 4fd944d44..4d396b1ce 100644 --- a/tests/filemanager/test_localstorage.py +++ b/tests/filemanager/test_localstorage.py @@ -2,7 +2,6 @@ __author__ = "Gina Häußge " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" -import io import os import os.path import unittest @@ -23,7 +22,7 @@ class FileWrapper: blocksize = 65536 hash = hashlib.sha1() - with io.open(self.path, "rb") as f: + with open(self.path, "rb") as f: buffer = f.read(blocksize) while len(buffer) > 0: hash.update(buffer) @@ -829,7 +828,7 @@ class LocalStorageTest(unittest.TestCase): # prepare import yaml - with io.open(yaml_path, "wt") as f: + with open(yaml_path, "wt") as f: yaml.safe_dump(metadata, f) # migrate @@ -841,7 +840,7 @@ class LocalStorageTest(unittest.TestCase): import json - with io.open(json_path, "rt", encoding="utf-8") as f: + with open(json_path, encoding="utf-8") as f: json_metadata = json.load(f) self.assertDictEqual(metadata, json_metadata) diff --git a/tests/plugin/test_settings.py b/tests/plugin/test_settings.py index 24de2a1f0..200b252a4 100644 --- a/tests/plugin/test_settings.py +++ b/tests/plugin/test_settings.py @@ -161,8 +161,7 @@ class SettingsTestCase(unittest.TestCase): self.assertEqual(1, len(w)) self.assertTrue(issubclass(w[-1].category, DeprecationWarning)) self.assertTrue( - "{old} has been renamed to {new}".format(old=deprecated, new=current) - in str(w[-1].message) + f"{deprecated} has been renamed to {current}" in str(w[-1].message) ) @data( @@ -402,8 +401,7 @@ class SettingsTestCase(unittest.TestCase): self.assertEqual(1, len(w)) self.assertTrue(issubclass(w[-1].category, DeprecationWarning)) self.assertTrue( - "{old} has been renamed to {new}".format(old=deprecated, new=current) - in str(w[-1].message) + f"{deprecated} has been renamed to {current}" in str(w[-1].message) ) def test_global_get_basefolder(self): @@ -419,7 +417,7 @@ class SettingsTestCase(unittest.TestCase): self.settings.getBaseFolder.assert_called_once_with("logs") self.assertEqual( - "/some/folder/plugin_{key}.log".format(key=self.plugin_key), + f"/some/folder/plugin_{self.plugin_key}.log", path.replace(os.sep, "/"), ) @@ -432,7 +430,7 @@ class SettingsTestCase(unittest.TestCase): self.settings.getBaseFolder.assert_called_once_with("logs") self.assertEqual( - "/some/folder/plugin_{key}_mypostfix.log".format(key=self.plugin_key), + f"/some/folder/plugin_{self.plugin_key}_mypostfix.log", path.replace(os.sep, "/"), ) diff --git a/tests/settings/test_settings.py b/tests/settings/test_settings.py index 1457acb0b..dc8bd7b0a 100644 --- a/tests/settings/test_settings.py +++ b/tests/settings/test_settings.py @@ -10,7 +10,6 @@ Tests for OctoPrint's Settings class import contextlib import hashlib -import io import os import re import shutil @@ -27,11 +26,11 @@ import octoprint.settings @ddt.ddt class TestSettings(unittest.TestCase): def _load_yaml(self, fname): - with io.open(fname, "rt", encoding="utf-8") as f: + with open(fname, encoding="utf-8") as f: return yaml.safe_load(f) def _dump_yaml(self, fname, config): - with io.open(fname, "wt", encoding="utf-8") as f: + with open(fname, "wt", encoding="utf-8") as f: yaml.safe_dump(config, f) def setUp(self): @@ -182,7 +181,7 @@ class TestSettings(unittest.TestCase): # can switch to assertIsNone after 3.x upgrade. self.assertFalse( match_result, - "string matched and it shouldn't have: {!r}".format(terminal_string), + f"string matched and it shouldn't have: {terminal_string!r}", ) def test_temperature_regex_matches(self): @@ -208,7 +207,7 @@ class TestSettings(unittest.TestCase): # can switch to assertIsNotNone after 3.x upgrade. self.assertTrue( match_result, - "string did not match and it should have: {!r}".format(terminal_string), + f"string did not match and it should have: {terminal_string!r}", ) ##~~ test getters diff --git a/tests/test_daemon.py b/tests/test_daemon.py index 303d510a3..98a69ff1d 100644 --- a/tests/test_daemon.py +++ b/tests/test_daemon.py @@ -403,7 +403,7 @@ class DaemonTest(unittest.TestCase): # test with mock.patch( _fixups.OPEN_SIGNATURE, - mock.mock_open(read_data="{}\n".format(pid)), + mock.mock_open(read_data=f"{pid}\n"), create=True, ) as m: result = self.daemon.get_pid() @@ -432,7 +432,7 @@ class DaemonTest(unittest.TestCase): # test with mock.patch( _fixups.OPEN_SIGNATURE, - mock.mock_open(read_data="{}\n".format(pid)), + mock.mock_open(read_data=f"{pid}\n"), create=True, ) as m: result = self.daemon.get_pid() @@ -452,7 +452,7 @@ class DaemonTest(unittest.TestCase): # assert m.assert_called_once_with(self.pidfile, "wt+", encoding="utf-8") handle = m() - handle.write.assert_called_once_with("{}\n".format(pid)) + handle.write.assert_called_once_with(f"{pid}\n") def test_set_pid_int(self): # setup @@ -465,7 +465,7 @@ class DaemonTest(unittest.TestCase): # assert m.assert_called_once_with(self.pidfile, "wt+", encoding="utf-8") handle = m() - handle.write.assert_called_once_with("{}\n".format(pid)) + handle.write.assert_called_once_with(f"{pid}\n") @mock.patch("os.path.isfile") @mock.patch("os.remove") diff --git a/tests/util/test_file_helpers.py b/tests/util/test_file_helpers.py index b05d7b455..62c2d889e 100644 --- a/tests/util/test_file_helpers.py +++ b/tests/util/test_file_helpers.py @@ -522,7 +522,7 @@ class IsHiddenPathTest(unittest.TestCase): "path_always_hidden", ): path = getattr(self, attr) - with io.open(path, "wt+", encoding="utf-8") as f: + with open(path, "wt+", encoding="utf-8") as f: f.write(attr) if sys.platform == "win32": From 7668afcff7316fd164e2cb75c72dd3e2d28daf1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 11 Mar 2021 17:06:04 +0100 Subject: [PATCH 23/43] =?UTF-8?q?=F0=9F=92=9A=20Fix=20unit=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit io.open is no longer used, mocks needed adjustments --- tests/_fixups.py | 3 --- tests/filemanager/test_filemanager.py | 8 +++----- tests/plugins/pi_support/test_pi_support.py | 11 ++++------- tests/test_daemon.py | 22 ++++++++++----------- tests/util/test_file_helpers.py | 3 +-- 5 files changed, 18 insertions(+), 29 deletions(-) delete mode 100644 tests/_fixups.py diff --git a/tests/_fixups.py b/tests/_fixups.py deleted file mode 100644 index 1dac32bc3..000000000 --- a/tests/_fixups.py +++ /dev/null @@ -1,3 +0,0 @@ -import sys # noqa: F401 - -OPEN_SIGNATURE = "io.open" diff --git a/tests/filemanager/test_filemanager.py b/tests/filemanager/test_filemanager.py index c92bcb8d0..a8e2836ad 100644 --- a/tests/filemanager/test_filemanager.py +++ b/tests/filemanager/test_filemanager.py @@ -7,8 +7,6 @@ import io import unittest import unittest.mock as mock -import _fixups - import octoprint.filemanager import octoprint.filemanager.util import octoprint.settings @@ -393,7 +391,7 @@ class FileManagerTest(unittest.TestCase): mock_time.return_value = now self.local_storage.path_in_storage.return_value = path - with mock.patch(_fixups.OPEN_SIGNATURE, mock.mock_open(), create=True): + with mock.patch("builtins.open", mock.mock_open(), create=True): self.file_manager.save_recovery_data( octoprint.filemanager.FileDestinations.LOCAL, path, pos ) @@ -429,7 +427,7 @@ class FileManagerTest(unittest.TestCase): mock_yaml_safe_dump.side_effect = RuntimeError - with mock.patch(_fixups.OPEN_SIGNATURE, mock.mock_open(), create=True): + with mock.patch("builtins.open", mock.mock_open(), create=True): self.file_manager.save_recovery_data( octoprint.filemanager.FileDestinations.LOCAL, path, pos ) @@ -480,7 +478,7 @@ class FileManagerTest(unittest.TestCase): } text_data = yaml.dump(data) - with mock.patch(_fixups.OPEN_SIGNATURE, mock.mock_open(read_data=text_data)) as m: + with mock.patch("builtins.open", mock.mock_open(read_data=text_data)) as m: # moved safe_load to here so we could mock up the return value properly with mock.patch("yaml.safe_load", return_value=data) as n: result = self.file_manager.get_recovery_data() diff --git a/tests/plugins/pi_support/test_pi_support.py b/tests/plugins/pi_support/test_pi_support.py index 9e7baf5d5..f837d7ecb 100644 --- a/tests/plugins/pi_support/test_pi_support.py +++ b/tests/plugins/pi_support/test_pi_support.py @@ -1,7 +1,6 @@ import unittest import unittest.mock as mock -import _fixups import ddt from octoprint.util.platform import CLOSE_FDS @@ -19,23 +18,21 @@ class PiSupportTestCase(unittest.TestCase): # import _fixups - with mock.patch(_fixups.OPEN_SIGNATURE, mock.mock_open(), create=True) as m: + with mock.patch("builtins.open", mock.mock_open(), create=True) as m: m.return_value.readline.return_value = OCTOPI_VERSION version = get_octopi_version() - m.assert_called_once_with("/etc/octopi_version", "rt", encoding="utf-8") + m.assert_called_once_with("/etc/octopi_version", encoding="utf-8") self.assertEqual(version, OCTOPI_VERSION) def test_get_proc_dt_model(self): from octoprint.plugins.pi_support import get_proc_dt_model - # import _fixups - - with mock.patch(_fixups.OPEN_SIGNATURE, mock.mock_open(), create=True) as m: + with mock.patch("builtins.open", mock.mock_open(), create=True) as m: m.return_value.readline.return_value = DT_MODEL model = get_proc_dt_model() - m.assert_called_once_with("/proc/device-tree/model", "rt", encoding="utf-8") + m.assert_called_once_with("/proc/device-tree/model", encoding="utf-8") self.assertEqual(model, DT_MODEL) def test_get_vcgencmd_throttle_state(self): diff --git a/tests/test_daemon.py b/tests/test_daemon.py index 98a69ff1d..17b3823f1 100644 --- a/tests/test_daemon.py +++ b/tests/test_daemon.py @@ -1,8 +1,6 @@ import unittest import unittest.mock as mock -import _fixups - import octoprint.daemon @@ -104,7 +102,7 @@ class DaemonTest(unittest.TestCase): @mock.patch("sys.stdout") @mock.patch("sys.stderr") @mock.patch("os.devnull") - @mock.patch(_fixups.OPEN_SIGNATURE) + @mock.patch("builtins.open") @mock.patch("os.dup2") def test_redirect_io( self, mock_dup2, mock_open, mock_devnull, mock_stderr, mock_stdout, mock_stdin @@ -133,7 +131,7 @@ class DaemonTest(unittest.TestCase): self.assertListEqual( mock_open.mock_calls, [ - mock.call(mock_devnull, "rt", encoding="utf-8"), + mock.call(mock_devnull, encoding="utf-8"), mock.call(mock_devnull, "at+", encoding="utf-8"), mock.call(mock_devnull, "at+", encoding="utf-8"), ], @@ -402,7 +400,7 @@ class DaemonTest(unittest.TestCase): # test with mock.patch( - _fixups.OPEN_SIGNATURE, + "builtins.open", mock.mock_open(read_data=f"{pid}\n"), create=True, ) as m: @@ -410,7 +408,7 @@ class DaemonTest(unittest.TestCase): # assert self.assertEqual(result, pid) - m.assert_called_once_with(self.pidfile, "rt", encoding="utf-8") + m.assert_called_once_with(self.pidfile, encoding="utf-8") def test_get_pid_ioerror(self): # setup @@ -418,12 +416,12 @@ class DaemonTest(unittest.TestCase): handle.__enter__.side_effect = IOError() # test - with mock.patch(_fixups.OPEN_SIGNATURE, mock.mock_open(), create=True) as m: + with mock.patch("builtins.open", mock.mock_open(), create=True) as m: result = self.daemon.get_pid() # assert self.assertIsNone(result) - m.assert_called_once_with(self.pidfile, "rt", encoding="utf-8") + m.assert_called_once_with(self.pidfile, encoding="utf-8") def test_get_pid_valueerror(self): # setup @@ -431,7 +429,7 @@ class DaemonTest(unittest.TestCase): # test with mock.patch( - _fixups.OPEN_SIGNATURE, + "builtins.open", mock.mock_open(read_data=f"{pid}\n"), create=True, ) as m: @@ -439,14 +437,14 @@ class DaemonTest(unittest.TestCase): # assert self.assertIsNone(result) - m.assert_called_once_with(self.pidfile, "rt", encoding="utf-8") + m.assert_called_once_with(self.pidfile, encoding="utf-8") def test_set_pid(self): # setup pid = "1234" # test - with mock.patch(_fixups.OPEN_SIGNATURE, mock.mock_open(), create=True) as m: + with mock.patch("builtins.open", mock.mock_open(), create=True) as m: self.daemon.set_pid(pid) # assert @@ -459,7 +457,7 @@ class DaemonTest(unittest.TestCase): pid = 1234 # test - with mock.patch(_fixups.OPEN_SIGNATURE, mock.mock_open(), create=True) as m: + with mock.patch("builtins.open", mock.mock_open(), create=True) as m: self.daemon.set_pid(pid) # assert diff --git a/tests/util/test_file_helpers.py b/tests/util/test_file_helpers.py index 62c2d889e..e4d50259f 100644 --- a/tests/util/test_file_helpers.py +++ b/tests/util/test_file_helpers.py @@ -1,7 +1,6 @@ __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" -import io import os import sys import unittest @@ -77,7 +76,7 @@ class BomAwareOpenTest(unittest.TestCase): def test_bom_aware_open_parameters_text_mode(self): """Tests that the parameters are propagated properly in text mode.""" - with mock.patch("io.open", wraps=io.open) as mock_open: + with mock.patch("builtins.open", wraps=open) as mock_open: with octoprint.util.bom_aware_open( self.filename_utf8_without_bom, mode="rt", From 535587006611c927ec51954b06ea70d1171cbe57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 11 Mar 2021 17:23:06 +0100 Subject: [PATCH 24/43] =?UTF-8?q?=F0=9F=91=B7=20Enable=20nightly=20merge?= =?UTF-8?q?=20maintenance->devel?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Let's give this a try after all --- .github/workflows/nightly_merge.yml | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/.github/workflows/nightly_merge.yml b/.github/workflows/nightly_merge.yml index 4d54ff64c..fc74e5415 100644 --- a/.github/workflows/nightly_merge.yml +++ b/.github/workflows/nightly_merge.yml @@ -23,11 +23,11 @@ jobs: env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - #- name: 🔀 Merge maintenance into devel - # uses: robotology/gh-action-nightly-merge@v1.3.2 - # with: - # stable_branch: "maintenance" - # development_branch: "devel" - # allow_ff: false - # env: - # GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: 🔀 Merge maintenance into devel + uses: robotology/gh-action-nightly-merge@v1.3.2 + with: + stable_branch: "maintenance" + development_branch: "devel" + allow_ff: false + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} From 361162aac2ed906b393d05bc4a69d0e41a8a4457 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 11 Mar 2021 17:43:55 +0100 Subject: [PATCH 25/43] =?UTF-8?q?=F0=9F=91=B7=20Disable=20maintenance->dev?= =?UTF-8?q?el=20again?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Turns out it doesn't trigger the build action, so we'd never see pre-commit runs on those merges - we really really don't want that. Manual it is :/ --- .github/workflows/nightly_merge.yml | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/.github/workflows/nightly_merge.yml b/.github/workflows/nightly_merge.yml index fc74e5415..4d54ff64c 100644 --- a/.github/workflows/nightly_merge.yml +++ b/.github/workflows/nightly_merge.yml @@ -23,11 +23,11 @@ jobs: env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - - name: 🔀 Merge maintenance into devel - uses: robotology/gh-action-nightly-merge@v1.3.2 - with: - stable_branch: "maintenance" - development_branch: "devel" - allow_ff: false - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + #- name: 🔀 Merge maintenance into devel + # uses: robotology/gh-action-nightly-merge@v1.3.2 + # with: + # stable_branch: "maintenance" + # development_branch: "devel" + # allow_ff: false + # env: + # GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} From 90f1a44c2de70496d7ef8c5c6a40aa352a19a28d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 12 Mar 2021 18:11:59 +0100 Subject: [PATCH 26/43] =?UTF-8?q?=F0=9F=94=8A=20Increase=20timings=20loggi?= =?UTF-8?q?ng?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Now can also log on entering the decorated function. --- src/octoprint/filemanager/storage.py | 1 + src/octoprint/server/api/files.py | 2 ++ src/octoprint/util/__init__.py | 39 ++++++++++++++++------------ 3 files changed, 25 insertions(+), 17 deletions(-) diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index 4c9662145..bc3d59d40 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -1508,6 +1508,7 @@ class LocalFileStorage(StorageInterface): logtarget=__name__ + ".timings", message="{func}({func_args},{func_kwargs}) took {timing:.2f}ms", incl_func_args=True, + log_enter=True, ) def _list_folder(self, path, base="", force_refresh=False, **kwargs): def get_size(nodes): diff --git a/src/octoprint/server/api/files.py b/src/octoprint/server/api/files.py index 10a0a6a04..17cd6b038 100644 --- a/src/octoprint/server/api/files.py +++ b/src/octoprint/server/api/files.py @@ -247,6 +247,8 @@ def _getFileDetails(origin, path, recursive=True): logtarget=__name__ + ".timings", message="{func}({func_args},{func_kwargs}) took {timing:.2f}ms", incl_func_args=True, + log_enter=True, + message_enter="Entering {func}({func_args},{func_kwargs})...", ) def _getFileList( origin, path=None, filter=None, recursive=False, level=0, allow_from_cache=True diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 6648645bf..ac27abb8e 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -1900,33 +1900,38 @@ def time_this( expand_logtarget=False, message="{func} took {timing:.2f}ms", incl_func_args=False, + log_enter=False, + message_enter="Entering {func}...", ): def decorator(f): + func = fqfn(f) + + lt = logtarget + if expand_logtarget: + lt += "." + func + + logger = logging.getLogger(lt) + @wraps(f) def wrapper(*args, **kwargs): + data = {"func": func} + if incl_func_args and logger.isEnabledFor(logging.DEBUG): + data.update( + func_args=",".join(map(repr, args)), + func_kwargs=",".join( + map(lambda x: "{}={!r}".format(x[0], x[1]), kwargs.items()) + ), + ) + if log_enter: + logger.debug(message_enter.format(**data), extra=data) + start = time.time() try: return f(*args, **kwargs) finally: timing = (time.time() - start) * 1000 - func = fqfn(f) - - lt = logtarget - if expand_logtarget: - lt += "." + func - - logger = logging.getLogger(lt) if logger.isEnabledFor(logging.DEBUG): - data = {"func": func, "timing": timing} - if incl_func_args: - data.update( - func_args=",".join(map(repr, args)), - func_kwargs=",".join( - map( - lambda x: "{}={!r}".format(x[0], x[1]), kwargs.items() - ) - ), - ) + data.update(timing=timing) logger.debug(message.format(**data), extra=data) return wrapper From 89273598ae987965b7835d9f66d45c5942eba613 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 12 Mar 2021 18:12:38 +0100 Subject: [PATCH 27/43] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20Don't=20calculate=20?= =?UTF-8?q?last=20modified=20twice?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/filemanager/storage.py | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index bc3d59d40..954d18807 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -1536,11 +1536,8 @@ class LocalFileStorage(StorageInterface): try: with self._filelist_cache_mutex: cache = self._filelist_cache.get(path) - if ( - not force_refresh - and cache - and cache[0] >= self.last_modified(path, recursive=True) - ): + lm = self.last_modified(path, recursive=True) + if not force_refresh and cache and cache[0] >= lm: return enrich_folders(cache[1]) metadata = self._get_metadata(path) @@ -1681,7 +1678,7 @@ class LocalFileStorage(StorageInterface): continue self._filelist_cache[path] = ( - self.last_modified(path, recursive=True), + lm, result, ) return enrich_folders(result) From f64abb22b3cd1c2b73d483f8a04edf5b9999b728 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 12 Mar 2021 18:13:11 +0100 Subject: [PATCH 28/43] =?UTF-8?q?=F0=9F=90=9B=20Fix=20file=20name=20valida?= =?UTF-8?q?tion=20never=20validating?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/server/api/files.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/octoprint/server/api/files.py b/src/octoprint/server/api/files.py index 17cd6b038..385daee99 100644 --- a/src/octoprint/server/api/files.py +++ b/src/octoprint/server/api/files.py @@ -218,7 +218,7 @@ def readGcodeFile(target, filename): if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: abort(404) - if filename != fileManager.sanitize(target, filename): + if not _validate(target, filename): abort(404) recursive = False @@ -735,7 +735,7 @@ def gcodeFileCommand(filename, target): if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: abort(404) - if filename != fileManager.sanitize(target, filename): + if not _validate(target, filename): abort(404) # valid file commands, dict mapping command name to mandatory parameters @@ -1101,7 +1101,7 @@ def gcodeFileCommand(filename, target): @no_firstrun_access @Permissions.FILES_DELETE.require(403) def deleteGcodeFile(filename, target): - if filename != fileManager.sanitize(target, filename): + if not _validate(target, filename): abort(404) if not _verifyFileExists(target, filename) and not _verifyFolderExists( @@ -1166,6 +1166,12 @@ def _getCurrentFile(): return None, None +def _validate(target, filename): + return filename == "/".join( + map(lambda x: fileManager.sanitize_name(target, x), filename.split("/")) + ) + + class WerkzeugFileWrapper(octoprint.filemanager.util.AbstractFileWrapper): """ A wrapper around a Werkzeug ``FileStorage`` object. From 1c916681949098176fb6c88cfe7781366eb953b0 Mon Sep 17 00:00:00 2001 From: cp2004 <31997505+cp2004@users.noreply.github.com> Date: Sat, 13 Mar 2021 17:39:16 +0000 Subject: [PATCH 29/43] :bug: Fix log validation `path` in this context is just `octoprint.log`, so the path validation is useless - it will always look in the basedir, because that is where Tornado has been told to look. No other validators do the same as far as I can see (timelapse and files). Closes #4045 :art: Pretty --- src/octoprint/server/__init__.py | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 66580108f..6a92032bb 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -766,13 +766,9 @@ class Server(object): ) } - valid_log = ( - lambda path: not octoprint.util.is_hidden_path(path) - and path.endswith(".log") - and os.path.realpath(os.path.abspath(path)).startswith( - settings().getBaseFolder("logs") - ) - ) + valid_log = lambda path: not octoprint.util.is_hidden_path( + path + ) and path.endswith(".log") log_path_validator = { "path_validation": util.tornado.path_validation_factory( valid_log, From aa9a2335ce6095f40284d85e649434cf3d22c7e9 Mon Sep 17 00:00:00 2001 From: cp2004 <31997505+cp2004@users.noreply.github.com> Date: Sat, 13 Mar 2021 21:36:37 +0000 Subject: [PATCH 30/43] :pencil2: Show meaningful message when software update is blocked And log when it is undervoltage. The problem here was twofold: first, a very generic message asking to check the log confused users. Second, there was nothing logged when it said check the logs. So, this changes that so the message is escaped and displayed in the pnotify and when the update is blocked for undervoltage this is logged. This does not add logging for other methods, since it seems unnecessary to me. Closes #4024 --- src/octoprint/plugins/softwareupdate/__init__.py | 8 ++++++-- .../softwareupdate/static/js/softwareupdate.js | 15 +++++++++++---- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index 9203baa7d..45f951961 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -1086,10 +1086,14 @@ class SoftwareUpdatePlugin( and not self._settings.get_boolean(["ignore_throttled"]) ): # currently throttled, we refuse to run + message = ( + "System is currently throttled, refusing to update " + "anything due to possible stability issues" + ) + self._logger.error(message) flask.abort( 409, - description="System is currently throttled, refusing to update " - "anything due to possible stability issues", + description=message, ) if self._printer.is_printing() or self._printer.is_paused(): diff --git a/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js b/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js index b090c2651..56e8b6f75 100644 --- a/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js +++ b/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js @@ -680,13 +680,20 @@ $(function () { gettext("Updating, please wait.") ); }) - .fail(function () { + .fail(function (response) { self.updateInProgress = false; + var message = + "

" + + gettext( + "The update could not be started. Is it already active? Please consult octoprint.log for details." + ) + + "

" +
+                        _.escape(response.responseJSON.error) +
+                        "
"; + self._showPopup({ title: gettext("Update not started!"), - text: gettext( - "The update could not be started. Is it already active? Please consult octoprint.log for details." - ), + text: message, type: "error", hide: false, buttons: { From 7ea6969e13c9843b858a3d31535db73bcf448595 Mon Sep 17 00:00:00 2001 From: Scott Lahteine Date: Sun, 14 Mar 2021 09:02:17 -0500 Subject: [PATCH 31/43] Prevent script error in build setup --- docs/development/environment.rst | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/development/environment.rst b/docs/development/environment.rst index 93756517b..9f3e05d6b 100644 --- a/docs/development/environment.rst +++ b/docs/development/environment.rst @@ -74,7 +74,7 @@ If you also want to be able to build the documentation that resides in the ``doc the *Python 3* environment and install the docs dependencies as well: * ``source venv3/bin/activate`` (Linux, macOS) or ``source venv3/Scripts/activate`` (Git Bash under Windows, see below) - * ``pip install -e .[develop,plugins,docs]`` + * ``pip install -e '.[develop,plugins,docs]'`` Go to the directory `docs` and you can then build the documentation: @@ -116,10 +116,10 @@ Then: virtualenv --python=python3 venv3 source ./venv2/bin/activate pip install --upgrade pip - pip install -e .[develop,plugins] + pip install -e '.[develop,plugins]' source ./venv3/bin/activate pip install --upgrade pip - pip install -e .[develop,plugins,docs] + pip install -e '.[develop,plugins,docs]' pre-commit install git config blame.ignoreRevsFile .git-blame-ignore-revs @@ -162,10 +162,10 @@ Open the Git Bash you just installed and in that: virtualenv --python=C:\Python38\python.exe venv3 source ./venv2/Scripts/activate python -m pip install --upgrade pip - pip install -e .[develop,plugins] + pip install -e '.[develop,plugins]' source ./venv3/Scripts/activate pip install --upgrade pip - python -m pip install -e .[develop,plugins,docs] + python -m pip install -e '.[develop,plugins,docs]' pre-commit install git config blame.ignoreRevsFile .git-blame-ignore-revs @@ -241,7 +241,7 @@ You'll need a user account with administrator privileges. virtualenv venv source venv/bin/activate pip install --upgrade pip - pip install -e .[develop,plugins] + pip install -e '.[develop,plugins]' pre-commit install git config blame.ignoreRevsFile .git-blame-ignore-revs @@ -291,7 +291,7 @@ PyCharm * Name: Update OctoPrint dependencies * Program: ``$ModuleSdkPath$`` - * Parameters: ``-m pip install -e .[develop,plugins]`` + * Parameters: ``-m pip install -e '.[develop,plugins]'`` * Working directory: ``$ProjectFileDir$`` Note that sadly that seems to cause some hiccups on current PyCharm versions due to ``$PyInterpreterDirectory$`` @@ -320,7 +320,7 @@ PyCharm the documentation, see above on how to set this up. Note that this requires you to also have installed the additional ``docs`` dependencies into the Python 3 venv as - described above via ``pip install -e .[develop,plugins,docs]``. + described above via ``pip install -e '.[develop,plugins,docs]'``. - Settings > Tools > File Watchers (you might have to enable this, it's a bundled plugin), add new: From 9ab2ba29b91d82bf4ef72f2d85b62aa5df278720 Mon Sep 17 00:00:00 2001 From: Scott Lahteine Date: Sun, 14 Mar 2021 06:21:55 -0500 Subject: [PATCH 32/43] Update temperature message regex --- AUTHORS.md | 1 + docs/configuration/config_yaml.rst | 4 ++-- src/octoprint/settings.py | 2 +- src/octoprint/static/js/app/viewmodels/settings.js | 3 ++- 4 files changed, 6 insertions(+), 4 deletions(-) diff --git a/AUTHORS.md b/AUTHORS.md index fae1ed362..81c0070d6 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -139,6 +139,7 @@ date of first contribution): * [Miroslav Šedivý](https://github.com/eumiro) * [Costas Basdekis](https://github.com/costas-basdekis) * [Joe Martella](https://github.com/martellaj) + * [Scott Lahteine](https://github.com/thinkyhead) 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/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index 56a0a5fce..a945a6c2a 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -1132,9 +1132,9 @@ Use `Javascript regular expressions Date: Mon, 15 Mar 2021 14:21:15 +0100 Subject: [PATCH 33/43] =?UTF-8?q?=F0=9F=90=9B=20Fix=20file=20API?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Was broken when debug logging was disabled due to timeThis decorator. --- src/octoprint/util/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index ac27abb8e..b8de4d210 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -1914,7 +1914,7 @@ def time_this( @wraps(f) def wrapper(*args, **kwargs): - data = {"func": func} + data = {"func": func, "func_args": "?", "func_kwargs": "?"} if incl_func_args and logger.isEnabledFor(logging.DEBUG): data.update( func_args=",".join(map(repr, args)), From 770492a955af22bb87d015a3d7918b67504eb938 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 15 Mar 2021 14:57:17 +0100 Subject: [PATCH 34/43] =?UTF-8?q?=F0=9F=94=92=20Make=20sure=20to=20validat?= =?UTF-8?q?e=20log=20paths=20for=20zip=20bundle?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Also do the same for timelapses. For individual files, the LargeResponseHandler takes care of this validation. For zip downloads however, we need to do it. An earlier refactoring accidentally applied the same logic to the invididual downloads as well, though in a broken way, this now fixes behaviour in both variants. --- src/octoprint/server/__init__.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 6a92032bb..961b5600c 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -760,8 +760,10 @@ class Server(object): } timelapses_path_validator = { "path_validation": util.tornado.path_validation_factory( - lambda path: not octoprint.util.is_hidden_path(path) - and octoprint.timelapse.valid_timelapse(path), + lambda path: valid_timelapse(path) + and os.path.realpath(os.path.abspath(path)).startswith( + settings().getBaseFolder("timelapse") + ), status_code=400, ) } @@ -777,7 +779,10 @@ class Server(object): } logs_path_validator = { "path_validation": util.tornado.path_validation_factory( - valid_log, + lambda path: valid_log(path) + and os.path.realpath(os.path.abspath(path)).startswith( + settings().getBaseFolder("logs") + ), status_code=400, ) } From b9374a2d7f5cfaa13a153796a669c62d850ffcd9 Mon Sep 17 00:00:00 2001 From: Karthikeyan Singaravelan Date: Thu, 11 Mar 2021 06:09:03 +0000 Subject: [PATCH 35/43] Import ABC from collections.abc for Python 3.10 compatibility. --- AUTHORS.md | 1 + src/octoprint/util/__init__.py | 16 +++++++++------- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/AUTHORS.md b/AUTHORS.md index fae1ed362..db978f380 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -139,6 +139,7 @@ date of first contribution): * [Miroslav Šedivý](https://github.com/eumiro) * [Costas Basdekis](https://github.com/costas-basdekis) * [Joe Martella](https://github.com/martellaj) + * [Karthikeyan Singaravelan](https://github.com/tirkarthi) 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/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index b8de4d210..33dc92862 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -26,6 +26,13 @@ import warnings from functools import wraps from typing import Union +try: + # Python 3.4+ + from collections.abc import Iterable, MutableMapping, Set +except ImportError: + # Python 2.7 + from collections import Iterable, MutableMapping, Set + import frozendict import past.builtins @@ -978,7 +985,7 @@ def dict_flatten(dictionary, prefix="", separator="."): result = {} for k, v in dictionary.items(): key = prefix + separator + k if prefix else k - if isinstance(v, collections.MutableMapping): + if isinstance(v, MutableMapping): result.update(dict_flatten(v, prefix=key, separator=separator)) else: result[key] = v @@ -1722,11 +1729,6 @@ class CountedEvent(object): class InvariantContainer(object): def __init__(self, initial_data=None, guarantee_invariant=None): - try: - from collections.abc import Iterable - except ImportError: - # Python < 3.8 - from collections import Iterable from threading import RLock if guarantee_invariant is None: @@ -1847,7 +1849,7 @@ class TypeAlreadyInQueue(Exception): self.type = t -class CaseInsensitiveSet(collections.Set): +class CaseInsensitiveSet(Set): """ Basic case insensitive set From ed21f75acf39bae412d7b1c24a27dee13a64a275 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 15 Mar 2021 17:14:39 +0100 Subject: [PATCH 36/43] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Remove=20py2=20stuff?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/util/__init__.py | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index dc2aebad3..681de5b9c 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -21,16 +21,10 @@ import threading import time import traceback import warnings +from collections.abc import Iterable, MutableMapping, Set from functools import wraps from typing import Union -try: - # Python 3.4+ - from collections.abc import Iterable, MutableMapping, Set -except ImportError: - # Python 2.7 - from collections import Iterable, MutableMapping, Set - import frozendict from octoprint import UMASK From 849cea15c139f072ac3145736cfc002b13d28aa6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 15 Mar 2021 17:35:34 +0100 Subject: [PATCH 37/43] =?UTF-8?q?=E2=9E=95=20Use=20immutabledict=20instead?= =?UTF-8?q?=20of=20frozendict=20on=20Py3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit frozendict appears to be unmaintained and is incompatible to Python 3.10+ As discussed in #4043 --- setup.py | 8 ++++++-- src/octoprint/printer/standard.py | 15 ++++++++++----- src/octoprint/util/__init__.py | 23 ++++++++++++++++------- src/octoprint/util/json/__init__.py | 8 ++++++-- 4 files changed, 38 insertions(+), 16 deletions(-) diff --git a/setup.py b/setup.py index db02066ba..fe0010fb1 100644 --- a/setup.py +++ b/setup.py @@ -58,7 +58,6 @@ INSTALL_REQUIRES = [ "websocket-client>=0.57,<1", "wrapt>=1.12.1,<2", "emoji>=0.5.4,<1", - "frozendict>=1.2,<2", "sentry-sdk>=0.15.1,<1", "filetype>=1.0.7,<2", "zipstream-new>=1.1.8,<1.2", @@ -76,10 +75,15 @@ INSTALL_REQUIRES_PYTHON2 = [ "chainmap>=1.0.3,<2", "typing>=3.7.4.1,<4", "enum34>=1.1.10,<1.2", + "frozendict>=1.2,<2", ] # Python 3 specific requirements -INSTALL_REQUIRES_PYTHON3 = ["feedparser>=6.0.2,<7", "zeroconf>=0.24,<0.25"] +INSTALL_REQUIRES_PYTHON3 = [ + "feedparser>=6.0.2,<7", + "zeroconf>=0.24,<0.25", + "immutabledict>=1.2.0,<2", +] # OSX specific requirements INSTALL_REQUIRES_OSX = [ diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index e4cbdfc74..5316b8d1e 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -15,7 +15,12 @@ import os import threading import time -from frozendict import frozendict +try: + from immutabledict import immutabledict +except ImportError: + # Python 2 + from frozendict import frozendict as immutabledict + from past.builtins import basestring, long import octoprint.util.json @@ -51,7 +56,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): self._logger_job = logging.getLogger("{}.job".format(__name__)) self._dict = ( - frozendict + immutabledict if settings().getBoolean(["devel", "useFrozenDictForPrinterState"]) else dict ) @@ -194,7 +199,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): @property def firmware_info(self): - return frozendict(self._firmware_info) if self._firmware_info else None + return immutabledict(self._firmware_info) if self._firmware_info else None # ~~ handling of PrinterCallbacks @@ -820,11 +825,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): return self._comm.getErrorString() def get_current_data(self, *args, **kwargs): - return util.thaw_frozendict(self._stateMonitor.get_current_data()) + return util.thaw_immutabledict(self._stateMonitor.get_current_data()) def get_current_job(self, *args, **kwargs): currentData = self._stateMonitor.get_current_data() - return util.thaw_frozendict(currentData["job"]) + return util.thaw_immutabledict(currentData["job"]) def get_current_temperatures(self, *args, **kwargs): if self._comm is not None: diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 33dc92862..25add714f 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -27,13 +27,17 @@ from functools import wraps from typing import Union try: - # Python 3.4+ from collections.abc import Iterable, MutableMapping, Set except ImportError: # Python 2.7 from collections import Iterable, MutableMapping, Set -import frozendict +try: + from immutabledict import immutabledict +except ImportError: + # Python 2 + from frozendict import frozendict as immutabledict + import past.builtins try: @@ -1367,20 +1371,25 @@ except ImportError: monotonic_time = time.time -def thaw_frozendict(obj): - if not isinstance(obj, (dict, frozendict.frozendict)): - raise ValueError("obj must be a dict or frozendict instance") +def thaw_immutabledict(obj): + if not isinstance(obj, (dict, immutabledict)): + raise ValueError("obj must be a dict or immutabledict instance") # only true love can thaw a frozen dict letitgo = {} for key, value in obj.items(): - if isinstance(value, (dict, frozendict.frozendict)): - letitgo[key] = thaw_frozendict(value) + if isinstance(value, (dict, immutabledict)): + letitgo[key] = thaw_immutabledict(value) else: letitgo[key] = copy.deepcopy(value) return letitgo +thaw_frozendict = deprecated( + "thaw_frozendict has been renamed to thaw_immutabledict", since="1.6.0" +)(thaw_immutabledict) + + def utmify(link, source=None, medium=None, name=None, term=None, content=None): if source is None: return link diff --git a/src/octoprint/util/json/__init__.py b/src/octoprint/util/json/__init__.py index 8b572d719..41a8f30c1 100644 --- a/src/octoprint/util/json/__init__.py +++ b/src/octoprint/util/json/__init__.py @@ -8,7 +8,11 @@ __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms import collections import json -import frozendict +try: + from immutabledict import immutabledict +except ImportError: + # Python 2 + from frozendict import frozendict as immutabledict from octoprint.util import to_unicode @@ -45,5 +49,5 @@ class JsonEncoding(object): raise TypeError -JsonEncoding.add_encoder(frozendict.frozendict, lambda obj: dict(obj)) +JsonEncoding.add_encoder(immutabledict, lambda obj: dict(obj)) JsonEncoding.add_encoder(bytes, lambda obj: to_unicode(obj)) From aa53344304f69476f0433978ec85ae07efab88c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 15 Mar 2021 17:42:34 +0100 Subject: [PATCH 38/43] =?UTF-8?q?=F0=9F=91=B7=20Add=203.9=20to=20python=20?= =?UTF-8?q?test=20matrix?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/build.yml | 4 ++-- .github/workflows/test_install.yml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index ada193c26..712d1d490 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -50,7 +50,7 @@ jobs: name: 🧪 Unit tests strategy: matrix: - python: ["2.7", "3.7", "3.8"] + python: ["2.7", "3.7", "3.8", "3.9"] runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 @@ -70,7 +70,7 @@ jobs: needs: build strategy: matrix: - python: ["2.7", "3.7", "3.8"] + python: ["2.7", "3.7", "3.8", "3.9"] installable: ["wheel", "sdist"] runs-on: ubuntu-latest steps: diff --git a/.github/workflows/test_install.yml b/.github/workflows/test_install.yml index 578737033..ba2dc5875 100644 --- a/.github/workflows/test_install.yml +++ b/.github/workflows/test_install.yml @@ -14,7 +14,7 @@ jobs: strategy: matrix: os: ["ubuntu-latest"] - python: ["2.7", "3.7", "3.8"] + python: ["2.7", "3.7", "3.8", "3.9"] branch: ["master"] runs-on: ${{ matrix.os }} steps: @@ -49,7 +49,7 @@ jobs: strategy: matrix: os: ["ubuntu-latest"] - python: ["2.7", "3.7", "3.8"] + python: ["2.7", "3.7", "3.8", "3.9"] runs-on: ${{ matrix.os }} steps: - name: 👀 Determine latest release From 3feb8deb8cfb8fd6cf4d3a6fc0c65b3710e182a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 15 Mar 2021 17:55:25 +0100 Subject: [PATCH 39/43] =?UTF-8?q?=F0=9F=92=9A=20Fix=20unit=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Some day I'll learn to search in src AND tests... --- tests/util/test_misc.py | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/tests/util/test_misc.py b/tests/util/test_misc.py index 140ab00c3..64de26908 100644 --- a/tests/util/test_misc.py +++ b/tests/util/test_misc.py @@ -8,7 +8,12 @@ __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms import unittest import ddt -from frozendict import frozendict + +try: + from immutabledict import immutabledict +except ImportError: + # Python 2 + from frozendict import frozendict as immutabledict import octoprint.util @@ -66,31 +71,35 @@ class MiscTestCase(unittest.TestCase): self.assertEqual(actual, expected) @ddt.data( - (frozendict(a=1, b=2, c=3), {"a": 1, "b": 2, "c": 3}), + (immutabledict(a=1, b=2, c=3), {"a": 1, "b": 2, "c": 3}), ( - frozendict(a=1, b=2, c=frozendict(c1=1, c2=2)), + immutabledict(a=1, b=2, c=immutabledict(c1=1, c2=2)), {"a": 1, "b": 2, "c": {"c1": 1, "c2": 2}}, ), ({"a": 1, "b": 2, "c": 3}, {"a": 1, "b": 2, "c": 3}), ( - {"a": 1, "b": 2, "c": frozendict(c1=1, c2=2)}, + {"a": 1, "b": 2, "c": immutabledict(c1=1, c2=2)}, {"a": 1, "b": 2, "c": {"c1": 1, "c2": 2}}, ), ( - {"a": 1, "b": 2, "c": {"c1": 1, "c2": 2, "c3": frozendict(c11=11, c12=12)}}, + { + "a": 1, + "b": 2, + "c": {"c1": 1, "c2": 2, "c3": immutabledict(c11=11, c12=12)}, + }, {"a": 1, "b": 2, "c": {"c1": 1, "c2": 2, "c3": {"c11": 11, "c12": 12}}}, ), ) @ddt.unpack - def test_unfreeze_frozendict(self, input, expected): - result = octoprint.util.thaw_frozendict(input) + def test_unfreeze_immutabledict(self, input, expected): + result = octoprint.util.thaw_immutabledict(input) self.assertIsInstance(result, dict) self.assertDictEqual(result, expected) @ddt.data(None, "invalid", 3, [1, 2], (3, 4)) - def test_unfreeze_frozendict_invalid(self, input): + def test_unfreeze_immutabledict_invalid(self, input): try: - octoprint.util.thaw_frozendict(input) + octoprint.util.thaw_immutabledict(input) self.fail("expected ValueError") except ValueError: # expected From bb2c3273c0dcd455bfdc7b0b5818dc8a56612a39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 15 Mar 2021 18:05:34 +0100 Subject: [PATCH 40/43] =?UTF-8?q?=F0=9F=94=A5=20Remove=20deprecated=20thaw?= =?UTF-8?q?=5Ffrozendict?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/util/__init__.py | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 0863b3169..f55167c85 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -1337,11 +1337,6 @@ def thaw_immutabledict(obj): return letitgo -thaw_frozendict = deprecated( - "thaw_frozendict has been renamed to thaw_immutabledict", since="1.6.0" -)(thaw_immutabledict) - - def utmify(link, source=None, medium=None, name=None, term=None, content=None): if source is None: return link From a24d3f26aeaa7572802a18bcf5e430bd44a2532b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 16 Mar 2021 11:02:01 +0100 Subject: [PATCH 41/43] =?UTF-8?q?=F0=9F=90=9B=20Fix=20caching=20behaviour?= =?UTF-8?q?=20on=20SD=20card=20API?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When `force=true` is supplied, the SD card files should be refreshed. Also finally documented the `force` parameter in the API docs. Closes #4051 --- docs/api/files.rst | 8 ++++++-- src/octoprint/printer/standard.py | 20 +++++++++++--------- src/octoprint/server/api/files.py | 4 ++-- 3 files changed, 19 insertions(+), 13 deletions(-) diff --git a/docs/api/files.rst b/docs/api/files.rst index d295ee2b9..0757bde41 100644 --- a/docs/api/files.rst +++ b/docs/api/files.rst @@ -14,7 +14,8 @@ Retrieve all files .. http:get:: /api/files Retrieve information regarding all files currently available and regarding the disk space still available - locally in the system. + locally in the system. The results are cached for performance reasons. If you + want to override the cache, supply the query parameter ``force`` and set it to ``true``. By default only returns the files and folders in the root directory. If the query parameter ``recursive`` is provided and set to ``true``, returns all files and folders. @@ -234,6 +235,7 @@ Retrieve all files "free": "3.2GB" } + :param force: If set to ``true``, forces a refresh, overriding the cache. :param recursive: If set to ``true``, return all files and folders recursively. Otherwise only return items on same level. :statuscode 200: No error @@ -245,7 +247,8 @@ Retrieve files from specific location .. http:get:: /api/files/(string:location) Retrieve information regarding the files currently available on the selected `location` and -- if targeting - the ``local`` location -- regarding the disk space still available locally in the system. + the ``local`` location -- regarding the disk space still available locally in the system. The results are cached for performance reasons. If you + want to override the cache, supply the query parameter ``force`` and set it to ``true``. By default only returns the files and folders in the root directory. If the query parameter ``recursive`` is provided and set to ``true``, returns all files and folders. @@ -305,6 +308,7 @@ Retrieve files from specific location :param location: The origin location from which to retrieve the files. Currently only ``local`` and ``sdcard`` are supported, with ``local`` referring to files stored in OctoPrint's ``uploads`` folder and ``sdcard`` referring to files stored on the printer's SD card (if available). + :param force: If set to ``true``, forces a refresh, overriding the cache. :param recursive: If set to ``true``, return all files and folders recursively. Otherwise only return items on same level. :statuscode 200: No error :statuscode 404: If `location` is neither ``local`` nor ``sdcard`` diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index 5316b8d1e..deef6978a 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -920,16 +920,18 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): # ~~ sd file handling def get_sd_files(self, *args, **kwargs): - if self._comm is None or not self._comm.isSdReady(): - result = [] - else: - result = list( - map( - lambda x: {"name": x[0][1:], "size": x[1], "display": x[2]}, - self._comm.getSdFiles(), - ) + if not self.is_sd_ready(): + return [] + + if kwargs.get("refresh"): + self.refresh_sd_files(blocking=True) + + return list( + map( + lambda x: {"name": x[0][1:], "size": x[1], "display": x[2]}, + self._comm.getSdFiles(), ) - return result + ) def add_sd_file( self, filename, path, on_success=None, on_failure=None, *args, **kwargs diff --git a/src/octoprint/server/api/files.py b/src/octoprint/server/api/files.py index 385daee99..a1608d4a4 100644 --- a/src/octoprint/server/api/files.py +++ b/src/octoprint/server/api/files.py @@ -157,7 +157,7 @@ def readGcodeFiles(): recursive=recursive, allow_from_cache=not force, ) - files.extend(_getFileList(FileDestinations.SDCARD)) + files.extend(_getFileList(FileDestinations.SDCARD, allow_from_cache=not force)) usage = psutil.disk_usage(settings().getBaseFolder("uploads", check_writable=False)) return jsonify(files=files, free=usage.free, total=usage.total) @@ -254,7 +254,7 @@ def _getFileList( origin, path=None, filter=None, recursive=False, level=0, allow_from_cache=True ): if origin == FileDestinations.SDCARD: - sdFileList = printer.get_sd_files() + sdFileList = printer.get_sd_files(refresh=not allow_from_cache) files = [] if sdFileList is not None: From 91733d314f03ab4f57264dcdb8ab84327b624401 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 16 Mar 2021 11:34:17 +0100 Subject: [PATCH 42/43] =?UTF-8?q?=E2=9C=A8=20New=20action=20commands=20for?= =?UTF-8?q?=20SD=20signaling?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/features/action_commands.rst | 21 +++++++++++++++++++++ src/octoprint/util/comm.py | 13 +++++++++++++ 2 files changed, 34 insertions(+) diff --git a/docs/features/action_commands.rst b/docs/features/action_commands.rst index 6e5f8830a..b3d298e2e 100644 --- a/docs/features/action_commands.rst +++ b/docs/features/action_commands.rst @@ -54,6 +54,27 @@ resumed disconnect When this command is received from the printer, OctoPrint will immediately disconnect from it. +sd_inserted + When this command is received from the printer, OctoPrint will assume an SD card is present in the printer, + set the corresponding internal state flags and send a file list request. This command is only recognized + if SD support is enabled in OctoPrint. + + .. versionadded:: 1.6.0 + +sd_ejected + When this command is received from the printer, OctoPrint will assume the SD card has been removed from + the printer and clear the corresponding internal state flags. This command is only recognized + if SD support is enabled in OctoPrint. + + .. versionadded:: 1.6.0 + +sd_updated + When this command is received from the printer, OctoPrint will assume something on the SD card in the + printer has changed and trigger a file list request. This command is only recognized + if SD support is enabled in OctoPrint. + + .. versionadded:: 1.6.0 + If the bundled :ref:`Action Command Prompt Support Plugin ` is enabled (which should be the case by default), OctoPrint will also interactive dialog creation through its :ref:`supported commands `. diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 6dcc9f3b7..ae16eb05a 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -2288,6 +2288,19 @@ class MachineCom(object): elif action_name == "disconnect": self._log("Disconnecting on request of the printer...") self._callback.on_comm_force_disconnect() + elif self._sdEnabled and action_name == "sd_inserted": + self._log("Printer reported SD card as inserted") + self._sdAvailable = True + self.refreshSdFiles() + self._callback.on_comm_sd_state_change(self._sdAvailable) + elif self._sdEnabled and action_name == "sd_ejected": + self._log("Printer reported SD card as ejected") + self._sdAvailable = False + self._sdFiles = [] + self._callback.on_comm_sd_state_change(self._sdAvailable) + elif self._sdEnabled and action_name == "sd_updated": + self._log("Printer reported a change on the SD card") + self.refreshSdFiles() else: for name, hook in self._printer_action_hooks.items(): try: From 08922975f313a887be6051604526c55cf4359b91 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 16 Mar 2021 12:56:41 +0100 Subject: [PATCH 43/43] =?UTF-8?q?=F0=9F=90=9B=20Ignore=20SD=20messages=20i?= =?UTF-8?q?f=20sd=20support=20is=20disabled?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/util/comm.py | 253 +++++++++++++++++++------------------ 1 file changed, 129 insertions(+), 124 deletions(-) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index ae16eb05a..eceeecdd4 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -2339,7 +2339,7 @@ class MachineCom(object): ##~~ SD file list # if we are currently receiving an sd file list, each line is just a filename, so just read it and abort processing - if self._sdFileList and "End file list" not in line: + if self._sdEnabled and self._sdFileList and "End file list" not in line: preprocessed_line = line fileinfo = preprocessed_line.split(None, 2) if len(fileinfo) == 3: @@ -2799,140 +2799,145 @@ class MachineCom(object): ) ##~~ SD Card handling - elif ( - "SD init fail" in line - or "volume.init failed" in line - or "openRoot failed" in line - ): - self._sdAvailable = False - self._sdFiles = [] - self._callback.on_comm_sd_state_change(self._sdAvailable) - elif "SD card ok" in line and not self._sdAvailable: - self._sdAvailable = True - self.refreshSdFiles() - self._callback.on_comm_sd_state_change(self._sdAvailable) - elif "Begin file list" in line: - self._sdFiles = [] - self._sdFileList = True - elif "End file list" in line: - self._sdFileList = False - self._callback.on_comm_sd_files(self.getSdFiles()) - elif "SD printing byte" in line: - # answer to M27, at least on Marlin, Repetier and Sprinter: "SD printing byte %d/%d" - match = regex_sdPrintingByte.search(line) - if match: - try: - current = int(match.group("current")) - total = int(match.group("total")) - except Exception: - self._logger.exception("Error while parsing SD status report") - else: - if ( - current == total == 0 - and self.isSdPrinting() - and not self.isStarting() - and not self.isStarting() - and not self.isFinishing() - ): - # apparently not SD printing - some Marlin versions report it like that for some reason - self._consecutive_not_sd_printing += 1 - if ( - self._consecutive_not_sd_printing - > self._consecutive_not_sd_printing_maximum - ): - self.cancelPrint(external_sd=True) - - else: - self._consecutive_not_sd_printing = 0 - if self.isSdFileSelected(): - - # If we are not yet sd printing, the current does not equal the total, is larger - # than zero and has increased since the last time we saw a position report, then - # yes, this looks like we just started printing due to an external trigger. - if ( - not self.isSdPrinting() - and current != total - and current > 0 - and self._currentFile - and current > self._currentFile.pos - ): - self.startPrint(external_sd=True) - - self._currentFile.pos = current - if self._currentFile.size == 0: - self._currentFile.size = total - - if not self._currentFile.done: - self._callback.on_comm_progress() - elif ( - "Not SD printing" in line - and self.isSdPrinting() - and not self.isStarting() - and not self.isFinishing() - ): - self._consecutive_not_sd_printing += 1 + elif self._sdEnabled: if ( - self._consecutive_not_sd_printing - > self._consecutive_not_sd_printing_maximum + "SD init fail" in line + or "volume.init failed" in line + or "openRoot failed" in line ): - # something went wrong, printer is reporting that we actually are not printing right now... - self.cancelPrint(external_sd=True) - elif "File opened" in line and not self._ignore_select: - # answer to M23, at least on Marlin, Repetier and Sprinter: "File opened:%s Size:%d" - match = regex_sdFileOpened.search(line) - if match: - name = match.group("name") - size = int(match.group("size")) - else: - name = "Unknown" - size = 0 - user = None + self._sdAvailable = False + self._sdFiles = [] + self._callback.on_comm_sd_state_change(self._sdAvailable) + elif "SD card ok" in line and not self._sdAvailable: + self._sdAvailable = True + self.refreshSdFiles() + self._callback.on_comm_sd_state_change(self._sdAvailable) + elif "Begin file list" in line: + self._sdFiles = [] + self._sdFileList = True + elif "End file list" in line: + self._sdFileList = False + self._callback.on_comm_sd_files(self.getSdFiles()) + elif "SD printing byte" in line: + # answer to M27, at least on Marlin, Repetier and Sprinter: "SD printing byte %d/%d" + match = regex_sdPrintingByte.search(line) + if match: + try: + current = int(match.group("current")) + total = int(match.group("total")) + except Exception: + self._logger.exception( + "Error while parsing SD status report" + ) + else: + if ( + current == total == 0 + and self.isSdPrinting() + and not self.isStarting() + and not self.isStarting() + and not self.isFinishing() + ): + # apparently not SD printing - some Marlin versions report it like that for some reason + self._consecutive_not_sd_printing += 1 + if ( + self._consecutive_not_sd_printing + > self._consecutive_not_sd_printing_maximum + ): + self.cancelPrint(external_sd=True) - if self._sdFileToSelect: - name = self._sdFileToSelect - user = self._sdFileToSelectUser + else: + self._consecutive_not_sd_printing = 0 + if self.isSdFileSelected(): - self._sdFileToSelect = None - self._sdFileToSelectUser = None + # If we are not yet sd printing, the current does not equal the total, is larger + # than zero and has increased since the last time we saw a position report, then + # yes, this looks like we just started printing due to an external trigger. + if ( + not self.isSdPrinting() + and current != total + and current > 0 + and self._currentFile + and current > self._currentFile.pos + ): + self.startPrint(external_sd=True) - self._currentFile = PrintingSdFileInformation(name, size, user=user) - elif "File selected" in line: - if self._ignore_select: - self._ignore_select = False - elif self._currentFile is not None and self.isSdFileSelected(): - # final answer to M23, at least on Marlin, Repetier and Sprinter: "File selected" - self._callback.on_comm_file_selected( - self._currentFile.getFilename(), - self._currentFile.getFilesize(), - True, - user=self._currentFile.getUser(), + self._currentFile.pos = current + if self._currentFile.size == 0: + self._currentFile.size = total + + if not self._currentFile.done: + self._callback.on_comm_progress() + elif ( + "Not SD printing" in line + and self.isSdPrinting() + and not self.isStarting() + and not self.isFinishing() + ): + self._consecutive_not_sd_printing += 1 + if ( + self._consecutive_not_sd_printing + > self._consecutive_not_sd_printing_maximum + ): + # something went wrong, printer is reporting that we actually are not printing right now... + self.cancelPrint(external_sd=True) + elif "File opened" in line and not self._ignore_select: + # answer to M23, at least on Marlin, Repetier and Sprinter: "File opened:%s Size:%d" + match = regex_sdFileOpened.search(line) + if match: + name = match.group("name") + size = int(match.group("size")) + else: + name = "Unknown" + size = 0 + user = None + + if self._sdFileToSelect: + name = self._sdFileToSelect + user = self._sdFileToSelectUser + + self._sdFileToSelect = None + self._sdFileToSelectUser = None + + self._currentFile = PrintingSdFileInformation( + name, size, user=user ) - elif "Writing to file" in line and self.isStreaming(): - self._changeState(self.STATE_PRINTING) - elif "Done printing file" in line and self.isSdPrinting(): - # printer is reporting file finished printing - self._changeState(self.STATE_FINISHING) + elif "File selected" in line: + if self._ignore_select: + self._ignore_select = False + elif self._currentFile is not None and self.isSdFileSelected(): + # final answer to M23, at least on Marlin, Repetier and Sprinter: "File selected" + self._callback.on_comm_file_selected( + self._currentFile.getFilename(), + self._currentFile.getFilesize(), + True, + user=self._currentFile.getUser(), + ) + elif "Writing to file" in line and self.isStreaming(): + self._changeState(self.STATE_PRINTING) + elif "Done printing file" in line and self.isSdPrinting(): + # printer is reporting file finished printing + self._changeState(self.STATE_FINISHING) - self._currentFile.done = True - self._currentFile.pos = 0 + self._currentFile.done = True + self._currentFile.pos = 0 - self.sendCommand("M400", part_of_job=True) - self._callback.on_comm_print_job_done() + self.sendCommand("M400", part_of_job=True) + self._callback.on_comm_print_job_done() - def finalize(): - self._changeState(self.STATE_OPERATIONAL) + def finalize(): + self._changeState(self.STATE_OPERATIONAL) - self.sendCommand(SendQueueMarker(finalize), part_of_job=True) - self._continue_sending() - elif "Done saving file" in line: - if self._trigger_ok_for_m29: - # workaround for most versions of Marlin out in the wild - # not sending an ok after saving a file + self.sendCommand(SendQueueMarker(finalize), part_of_job=True) + self._continue_sending() + elif "Done saving file" in line: + if self._trigger_ok_for_m29: + # workaround for most versions of Marlin out in the wild + # not sending an ok after saving a file + self._handle_ok() + elif "File deleted" in line and line.strip().endswith("ok"): + # buggy Marlin version that doesn't send a proper line break after the "File deleted" statement, fixed in + # current versions self._handle_ok() - elif "File deleted" in line and line.strip().endswith("ok"): - # buggy Marlin version that doesn't send a proper line break after the "File deleted" statement, fixed in - # current versions - self._handle_ok() ##~~ Message handling self._callback.on_comm_message(line)