From 28ecef207e740a90892e58cee7f41e196f196b99 Mon Sep 17 00:00:00 2001 From: Joe Martella Date: Sat, 27 Feb 2021 06:29:13 +0000 Subject: [PATCH 01/18] 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/18] 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/18] 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/18] =?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/18] =?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/18] =?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/18] =?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/18] =?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/18] =?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 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 10/18] =?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 11/18] =?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 12/18] =?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 13/18] =?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 14/18] =?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 15/18] =?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 16/18] =?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 17/18] =?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 18/18] =?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