diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index e34fb27e1..62cfaacba 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 549db9c6f..8d382e324 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -12,35 +12,21 @@ repos: - id: check-merge-conflict - id: fix-encoding-pragma args: ["--remove"] + - repo: https://github.com/asottile/pyupgrade + rev: v2.10.0 + hooks: + - id: pyupgrade - repo: https://github.com/OctoPrint/codemods rev: 0.4.0 hooks: - id: codemod_detect_past_builtins_imports args: ["--ignore", "src/octoprint/vendor"] - - id: codemod_dict_comprehension_to_literal - args: ["--ignore", "src/octoprint/vendor"] - - id: codemod_dict_to_literal - args: ["--ignore", "src/octoprint/vendor"] - id: codemod_not_in args: ["--ignore", "src/octoprint/vendor"] - - id: codemod_oserror_merge - args: ["--ignore", "src/octoprint/vendor"] - - id: codemod_py3_class_inheritance - args: ["--ignore", "src/octoprint/vendor"] - - id: codemod_py3_super - args: ["--ignore", "src/octoprint/vendor"] - - id: codemod_remove_builtins_imports - args: ["--ignore", "src/octoprint/vendor"] - id: codemod_remove_float_conversion args: ["--ignore", "src/octoprint/vendor"] - id: codemod_remove_future_imports args: ["--ignore", "src/octoprint/vendor"] - - id: codemod_set_to_literal - args: ["--ignore", "src/octoprint/vendor"] - - id: codemod_string_encoding - args: ["--ignore", "src/octoprint/vendor"] - - id: codemod_yield_from_generator - args: ["--ignore", "src/octoprint/vendor"] - repo: https://github.com/pre-commit/mirrors-isort rev: v5.5.4 hooks: 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 diff --git a/src/octoprint/_version.py b/src/octoprint/_version.py index 7920e56d2..77b78b683 100644 --- a/src/octoprint/_version.py +++ b/src/octoprint/_version.py @@ -97,7 +97,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: @@ -299,7 +299,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/analysis.py b/src/octoprint/cli/analysis.py index 1b335aa76..a1fedb377 100644 --- a/src/octoprint/cli/analysis.py +++ b/src/octoprint/cli/analysis.py @@ -66,6 +66,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( @@ -78,6 +79,7 @@ def gcode_command( throttle, throttle_lines, g90_extruder, + bedz, progress, ): """Runs a GCODE file analysis.""" @@ -123,6 +125,7 @@ def gcode_command( throttle=throttle_callback, max_extruders=maxt, g90_extruder=g90_extruder, + bed_z=bedz, ) click.echo("DONE:{}s".format(time.monotonic() - start_time)) diff --git a/src/octoprint/events.py b/src/octoprint/events.py index 2a349717b..3e3aa0325 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -317,7 +317,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/filemanager/analysis.py b/src/octoprint/filemanager/analysis.py index 3e611d539..af9cad273 100644 --- a/src/octoprint/filemanager/analysis.py +++ b/src/octoprint/filemanager/analysis.py @@ -410,6 +410,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"] @@ -425,6 +426,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/plugin/types.py b/src/octoprint/plugin/types.py index a8fb9b869..4cf1d661d 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -1276,7 +1276,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 @@ -1294,7 +1294,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 @@ -1324,7 +1324,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() @@ -1474,9 +1474,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/plugins/action_command_notification/__init__.py b/src/octoprint/plugins/action_command_notification/__init__.py index 060539d66..3dfb4a09b 100644 --- a/src/octoprint/plugins/action_command_notification/__init__.py +++ b/src/octoprint/plugins/action_command_notification/__init__.py @@ -66,7 +66,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_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()}); }; diff --git a/src/octoprint/plugins/action_command_prompt/__init__.py b/src/octoprint/plugins/action_command_prompt/__init__.py index 8d6305126..4a523eb50 100644 --- a/src/octoprint/plugins/action_command_prompt/__init__.py +++ b/src/octoprint/plugins/action_command_prompt/__init__.py @@ -123,10 +123,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): @@ -138,7 +138,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 40af06709..7aecedd1a 100644 --- a/src/octoprint/plugins/announcements/__init__.py +++ b/src/octoprint/plugins/announcements/__init__.py @@ -286,7 +286,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 c3c7110d3..d49bbcb3b 100644 --- a/src/octoprint/plugins/appkeys/__init__.py +++ b/src/octoprint/plugins/appkeys/__init__.py @@ -155,10 +155,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 @@ -206,7 +206,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 0ad10d229..204b19648 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -197,12 +197,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" @@ -230,9 +231,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/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/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 %} diff --git a/src/octoprint/plugins/logging/__init__.py b/src/octoprint/plugins/logging/__init__.py index 62f202ce9..e0f367680 100644 --- a/src/octoprint/plugins/logging/__init__.py +++ b/src/octoprint/plugins/logging/__init__.py @@ -6,7 +6,7 @@ import os from os import scandir 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 @@ -17,6 +17,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 class LoggingPlugin( @@ -81,8 +82,12 @@ 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): - return make_response("File not found: %s" % filename, 404) + if ( + not os.path.exists(secure) + or is_hidden_path(secure) + or not filename.endswith(".log") + ): + abort(404) os.remove(secure) @@ -107,15 +112,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 @@ -135,6 +140,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/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')}}
diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 6c3607f46..68dd969e0 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -19,7 +19,7 @@ import filetype import pkg_resources import requests import sarge -from flask import jsonify, make_response +from flask import Response, abort, jsonify, request from flask_babel import gettext import octoprint.plugin @@ -27,13 +27,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 +from octoprint.util import TemporaryDirectory, deprecated, to_bytes 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 @@ -358,7 +359,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] @@ -369,9 +370,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] @@ -398,7 +399,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, @@ -419,16 +420,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(): + abort(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(): + abort(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 @@ -458,97 +602,23 @@ 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) + 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, @@ -568,7 +638,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) + abort(404, description="Unknown plugin") plugin = self._plugin_manager.plugins[plugin_name] return self.command_uninstall(plugin, cleanup=data.get("cleanup", False)) @@ -589,11 +659,44 @@ 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) + abort(404, description="Unknown plugin") 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(): + abort(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) @@ -1076,15 +1179,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( @@ -1092,7 +1195,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 @@ -1105,9 +1208,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": @@ -1142,7 +1245,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( @@ -1330,7 +1433,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/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 b0a72ccfe..7d7eba04b 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"], @@ -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') }}

diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index b3949b0ff..a30f161ff 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -1012,8 +1012,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(): @@ -1078,30 +1081,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( @@ -1124,7 +1128,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() @@ -1796,7 +1800,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", { @@ -1813,7 +1819,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 1c9716e34..e10e15131 100644 --- a/src/octoprint/plugins/softwareupdate/updaters/pip.py +++ b/src/octoprint/plugins/softwareupdate/updaters/pip.py @@ -98,7 +98,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc target_version=target_version, target=target_version ) - logger.debug("Target: %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 c27eb4b77..2bf31153f 100644 --- a/src/octoprint/plugins/softwareupdate/updaters/update_script.py +++ b/src/octoprint/plugins/softwareupdate/updaters/update_script.py @@ -79,7 +79,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) @@ -100,7 +100,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: @@ -116,7 +118,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 9dbb37d1f..66c298426 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py @@ -90,6 +90,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 2840f6784..c5f226018 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/commandline.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/commandline.py @@ -56,6 +56,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 72f431b7f..96ab26569 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/git_commit.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/git_commit.py @@ -98,7 +98,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 42e548c56..56187b0fe 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py @@ -94,6 +94,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 0f6ef6228..19690a3c4 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/github_release.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/github_release.py @@ -355,7 +355,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 08d75bad2..756a79656 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -701,7 +701,10 @@ class VirtualPrinter: def _gcode_M117(self, data: 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: str) -> None: matchS = re.search(r"S([0-9]+)", data) diff --git a/src/octoprint/printer/profile.py b/src/octoprint/printer/profile.py index b1c28a5aa..cd7d44831 100644 --- a/src/octoprint/printer/profile.py +++ b/src/octoprint/printer/profile.py @@ -549,7 +549,7 @@ class PrinterProfileManager: 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 929b73657..9d1d2eadf 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -37,6 +37,7 @@ from flask_login import ( # noqa: F401 ) from watchdog.observers import Observer from watchdog.observers.polling import PollingObserver +from werkzeug.exceptions import HTTPException import octoprint.util import octoprint.util.net @@ -60,8 +61,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") @@ -745,10 +746,13 @@ class Server: 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, ) } @@ -759,12 +763,23 @@ class Server: 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, ) } @@ -839,6 +854,7 @@ class Server: }, download_handler_kwargs, log_permission_validator, + log_path_validator, ), ), # zipped log file bundles @@ -1411,7 +1427,7 @@ class Server: 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 @@ -1714,12 +1730,19 @@ class Server: # 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()) + ( + 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()) @@ -1731,8 +1754,16 @@ class Server: 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() + api_prefixes = [] blueprint_plugins = octoprint.plugin.plugin_manager().get_implementations( octoprint.plugin.BlueprintPlugin @@ -1740,6 +1771,9 @@ class Server: 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( @@ -1749,7 +1783,7 @@ class Server: ) continue - return blueprints + return blueprints, api_prefixes def _prepare_asset_plugins(self): blueprints = OrderedDict() diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index 6d3ff2204..59323a036 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -7,6 +7,7 @@ import logging from flask import ( Blueprint, + Response, abort, current_app, g, @@ -77,24 +78,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 for {name}, can't proceed".format( - name=name - ), - 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: @@ -117,24 +134,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 for {name}, can't proceed".format( - name=name - ), - 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: @@ -250,14 +262,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(): @@ -299,7 +303,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 @@ -336,12 +340,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"]) @@ -585,12 +589,7 @@ def _test_url(data): try: 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"] - ), - 400, - ) + abort(400, description="timeout is invalid") if "validSsl" in data: valid_ssl = data["validSsl"] in valid_boolean_trues @@ -614,13 +613,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"]) ) @@ -701,28 +700,18 @@ 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 - ) + abort(400, description="Invalid value for port") timeout = 3.05 if "timeout" in data: try: 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"] - ), - 400, - ) + abort(400, description="Invalid value for timeout") 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), - 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 21d7659e9..a41badce9 100644 --- a/src/octoprint/server/api/access.py +++ b/src/octoprint/server/api/access.py @@ -2,9 +2,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 @@ -36,19 +35,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"] @@ -87,12 +83,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 = {} @@ -146,22 +139,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"] @@ -204,12 +193,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: @@ -221,9 +210,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( @@ -258,27 +244,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: %s" % username, 404, [])) + abort(404) return jsonify(SUCCESS) else: - return make_response(("Forbidden", 403, [])) + abort(403) @api.route("/access/users//settings", methods=["GET"]) @@ -292,12 +275,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: %s" % username, 404) + abort(404) @api.route("/access/users//settings", methods=["PATCH"]) @@ -311,21 +294,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: %s" % username, 404) + abort(404) @api.route("/access/users//apikey", methods=["DELETE"]) @@ -342,10 +322,10 @@ def delete_apikey_for_user(username): try: userManager.delete_api_key(username) except users.UnknownUser: - return make_response(("Unknown user: %s" % username, 404, [])) + abort(404) return jsonify(SUCCESS) else: - return make_response(("Forbidden", 403, [])) + abort(403) @api.route("/access/users//apikey", methods=["POST"]) @@ -365,10 +345,10 @@ def generate_apikey_for_user(username): try: apikey = userManager.generate_api_key(username) except users.UnknownUser: - return make_response(("Unknown user: %s" % username, 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 0475aec2b..ed612cd63 100644 --- a/src/octoprint/server/api/connection.py +++ b/src/octoprint/server/api/connection.py @@ -2,7 +2,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 @@ -46,15 +46,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) + 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: %d" % 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: %s" % printerProfile, 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 b06ba6611..4ad77af5e 100644 --- a/src/octoprint/server/api/files.py +++ b/src/octoprint/server/api/files.py @@ -8,7 +8,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 @@ -177,7 +177,7 @@ def readGcodeFiles(): ) def readGcodeFilesForOrigin(origin): if origin not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: - return make_response("Unknown origin: %s" % origin, 404) + abort(404) filter = request.values.get("filter", False) recursive = request.values.get("recursive", "false") in valid_boolean_trues @@ -213,7 +213,10 @@ def readGcodeFilesForOrigin(origin): ) def readGcodeFile(target, filename): if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: - return make_response("Unknown target: %s" % target, 404) + abort(404) + + if filename != fileManager.sanitize(target, filename): + abort(404) recursive = False if "recursive" in request.values: @@ -221,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) + abort(404) return jsonify(file) @@ -447,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) + abort(404) upload = octoprint.filemanager.util.DiskFileWrapper( request.values[input_upload_name], request.values[input_upload_path] @@ -461,12 +464,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 = ( @@ -486,14 +489,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: @@ -511,9 +512,7 @@ def uploadGcodeFile(target): futureFilename = None if futureFilename is None: - return make_response( - "Can not upload file %s, wrong format?" % upload.filename, 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" @@ -530,10 +529,9 @@ 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, + abort( 409, + description="Trying to overwrite file that is currently being printed", ) reselect = printer.is_current_file(futureFullPathInStorage, sd) @@ -591,16 +589,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'.format( - upload.filename - ), - 400, - ) + abort(400, description="Could not upload file, invalid type") else: - return make_response( - 'Could not upload the file "{}"'.format(upload.filename), 500 - ) + abort(500, description="Could not upload file") if octoprint.filemanager.valid_file_type(added_file, "stl"): filename = added_file @@ -685,13 +676,13 @@ def uploadGcodeFile(target): foldername = request.values["foldername"] if target not in [FileDestinations.LOCAL]: - return make_response("Unknown target: %s" % 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( @@ -700,10 +691,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, - 409, - ) + abort(409, description="Can't create folder, please try another name") try: added_folder = fileManager.add_folder( @@ -711,11 +699,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) - ) + abort(400, description="Could not create folder, invalid directory") else: - return make_response("Could not create folder {}".format(futureName)) + abort(500, description="Could not create folder") location = url_for( ".readGcodeFile", @@ -735,14 +721,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: %s" % target, 404) + abort(404) + + if filename != fileManager.sanitize(target, filename): + abort(404) # valid file commands, dict mapping command name to mandatory parameters valid_commands = { @@ -762,31 +751,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 on '%s': %s" % (target, filename), 404 - ) + abort(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() - ), + 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 @@ -801,9 +787,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 - ) + abort(404) try: if "slicer" in data: @@ -816,14 +800,9 @@ def gcodeFileCommand(filename, target): slicer_instance = slicingManager.get_slicer("cura") else: - return make_response( - "Cannot slice {filename}, no slicer available".format(**locals()), - 415, - ) - except octoprint.slicing.UnknownSlicer as e: - return make_response( - "Slicer {slicer} is not available".format(slicer=e.slicer), 400 - ) + abort(415, description="Cannot slice file, no slicer available") + except octoprint.slicing.UnknownSlicer: + abort(404) if not any( [ @@ -833,9 +812,7 @@ def gcodeFileCommand(filename, target): ) ] ): - return make_response( - "Cannot slice {filename}, not a model file".format(**locals()), 415 - ) + abort(415, description="Cannot slice file, not a model file") cores = psutil.cpu_count() if ( @@ -844,11 +821,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 {slicer} while printing on single core systems or systems of unknown core count due to performance reasons".format( - **locals() - ), + 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"]: @@ -892,10 +867,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: %s" - % full_path, + abort( 409, + description="Trying to slice into file that is currently being printed", ) if "profile" in data and data["profile"]: @@ -925,17 +899,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 @@ -977,11 +952,8 @@ def gcodeFileCommand(filename, target): ), ) except octoprint.slicing.UnknownProfile: - return make_response( - "Profile {profile} doesn't exist".format(**locals()), 400 - ) + abort(404, description="Unknown profile") - files = {} location = url_for( ".readGcodeFile", target=target, filename=full_path, _external=True ) @@ -1007,9 +979,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 - ) + abort(404) printer_profile = None if "printerProfile" in data and data["printerProfile"]: @@ -1018,24 +988,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 - ) + 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, target), 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 on {}: {}".format(target, filename), 404 - ) + abort(404) path, name = fileManager.split_path(target, filename) @@ -1056,22 +1020,14 @@ def gcodeFileCommand(filename, target): if _verifyFileExists(target, destination) or _verifyFolderExists( target, destination ): - return make_response( - "File or folder does already exist on {}: {}".format( - target, destination - ), - 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( - "{} on {} is neither file or folder, can't {}".format( - filename, target, command - ), - 400, + abort( + 400, description="Neither file nor folder, can't {}".format(command) ) if command == "copy": @@ -1079,12 +1035,7 @@ def gcodeFileCommand(filename, target): if _verifyFileExists(target, destination) or _verifyFolderExists( target, destination ): - return make_response( - "File or folder does already exist on {}: {}".format( - target, destination - ), - 409, - ) + abort(409, description="File or folder does already exist") if is_file: fileManager.copy_file(target, filename, destination) @@ -1094,11 +1045,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: {}".format( - filename - ), + abort( 409, + description="Trying to move a file or folder that is currently in use", ) # destination already there AND not ourselves (= display rename)? error... @@ -1106,12 +1055,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 on {}: {}".format( - target, destination - ), - 409, - ) + abort(409, description="File or folder does already exist") # deselect the file if it's currently selected currentOrigin, currentFilename = _getCurrentFile() @@ -1152,21 +1096,20 @@ def gcodeFileCommand(filename, target): @no_firstrun_access @Permissions.FILES_DELETE.require(403) def deleteGcodeFile(filename, target): + if filename != fileManager.sanitize(target, filename): + abort(404) + if not _verifyFileExists(target, filename) and not _verifyFolderExists( target, filename ): - return make_response( - "File/Folder not found on '%s': %s" % (target, filename), 404 - ) + abort(404) + + if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: + abort(404) if _verifyFileExists(target, filename): - if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: - return make_response("Unknown target: %s" % target, 400) - if _isBusy(target, filename): - return make_response( - "Trying to delete a file that is currently in use: %s" % filename, 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() @@ -1184,14 +1127,10 @@ def deleteGcodeFile(filename, target): fileManager.remove_file(target, filename) elif _verifyFolderExists(target, filename): - if target not in [FileDestinations.LOCAL]: - return make_response("Unknown target: %s" % 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, + 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 be202e0d3..4de446326 100644 --- a/src/octoprint/server/api/job.py +++ b/src/octoprint/server/api/job.py @@ -2,7 +2,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 @@ -14,7 +14,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": []} @@ -31,22 +31,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": @@ -56,17 +57,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'".format( - action - ), - 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 9cac453bd..7815cfdbd 100644 --- a/src/octoprint/server/api/languages.py +++ b/src/octoprint/server/api/languages.py @@ -10,7 +10,7 @@ import zipfile from collections import defaultdict from os import scandir -from flask import jsonify, make_response, request +from flask import abort, jsonify, request from flask_babel import Locale from octoprint.access.permissions import Permissions @@ -127,7 +127,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] @@ -138,8 +138,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") @@ -149,7 +150,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 8fc1f8d45..b892df317 100644 --- a/src/octoprint/server/api/printer.py +++ b/src/octoprint/server/api/printer.py @@ -4,8 +4,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import re -from flask import Response, jsonify, make_response, request -from werkzeug.exceptions import BadRequest +from flask import Response, abort, jsonify, request from octoprint.access.permissions import Permissions from octoprint.printer import UnknownScript @@ -21,7 +20,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 = [] @@ -71,7 +70,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"], @@ -92,9 +91,7 @@ def printerToolCommand(): if command == "select": tool = data["tool"] if not isinstance(tool, str) or re.match(validation_regex, tool) is None: - return make_response("Invalid tool: %s" % tool, 400) - if not tool.startswith("tool"): - return make_response("Invalid tool for selection: %s" % tool, 400) + abort(400, description="tool is invalid") printer.change_tool(tool, tags=tags) @@ -106,11 +103,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 - ) + abort(400, description="targets contains invalid tool") if not isinstance(value, (int, float)): - return make_response("Not a number for %s: %r" % (tool, value), 400) + abort(400, description="targets contains invalid value") validated_values[tool] = value # perform the actual temperature commands @@ -125,15 +120,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: %s" % tool, 400 - ) - if not isinstance(value, (int, float)): - return make_response("Not a number for %s: %r" % (tool, value), 400) - if not -50 <= value <= 50: - return make_response( - "Offset %s not in range [-50, 50]: %f" % (tool, value), 400 - ) + abort(400, description="offsets contains invalid tool") + if not isinstance(value, (int, float)) or not -50 <= value <= 50: + abort(400, description="offsets contains invalid value") validated_values[tool] = value # set the offsets @@ -143,22 +132,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, float)): - return make_response("Not a number for extrusion amount: %r" % amount, 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, float)): - return make_response("Not a number for flow rate: %r" % factor, 400) + abort(400, description="factor is invalid") 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: + abort(400, description="factor is invalid") return NO_CONTENT @@ -168,7 +157,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)) @@ -181,10 +170,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) @@ -199,7 +188,7 @@ def printerBedCommand(): # make sure the target is a number if not isinstance(target, (int, float)): - return make_response("Not a number: %r" % target, 400) + abort(400, description="target is invalid") # perform the actual temperature command printer.set_temperature("bed", target, tags=tags) @@ -209,10 +198,8 @@ def printerBedCommand(): offset = data["offset"] # make sure the offset is valid - if not isinstance(offset, (int, float)): - return make_response("Not a number: %r" % offset, 400) - if not -50 <= offset <= 50: - return make_response("Offset not in range [-50, 50]: %f" % offset, 400) + if not isinstance(offset, (int, float)) or not -50 <= offset <= 50: + abort(400, description="offset is invalid") # set the offsets printer.set_temperature_offset({"bed": offset}) @@ -225,10 +212,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): @@ -245,10 +232,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) @@ -263,7 +250,7 @@ def printerChamberCommand(): # make sure the target is a number if not isinstance(target, (int, float)): - return make_response("Not a number: %r" % target, 400) + abort(400, description="target is invalid") # perform the actual temperature command printer.set_temperature("chamber", target, tags=tags) @@ -273,10 +260,8 @@ def printerChamberCommand(): offset = data["offset"] # make sure the offset is valid - if not isinstance(offset, (int, float)): - return make_response("Not a number: %r" % offset, 400) - if not -50 <= offset <= 50: - return make_response("Offset not in range [-50, 50]: %f" % offset, 400) + if not isinstance(offset, (int, float)) or not -50 <= offset <= 50: + abort(400, description="offset is invalid") # set the offsets printer.set_temperature_offset({"chamber": offset}) @@ -289,10 +274,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): @@ -315,7 +300,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"} @@ -328,9 +313,7 @@ def printerPrintheadCommand(): if axis in data: value = data[axis] if not isinstance(value, (int, float)): - return make_response( - "Not a number for axis %s: %r" % (axis, value), 400 - ) + abort(400, description="axis value is invalid") validated_values[axis] = value absolute = "absolute" in data and data["absolute"] in valid_boolean_trues @@ -345,7 +328,7 @@ def printerPrintheadCommand(): axes = data["axes"] for axis in axes: if axis not in valid_axes: - return make_response("Invalid axis: %s" % axis, 400) + abort(400, description="axis is invalid") validated_values.append(axis) # execute the home command @@ -354,11 +337,11 @@ def printerPrintheadCommand(): elif command == "feedrate": factor = data["factor"] if not isinstance(factor, (int, float)): - return make_response("Not a number for feed rate: %r" % factor, 400) + abort(400, description="factor is invalid") 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: + abort(400, description="factor is invalid") return NO_CONTENT @@ -371,10 +354,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) @@ -398,7 +381,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()) @@ -411,27 +394,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: @@ -444,7 +422,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 = [] @@ -465,7 +443,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 @@ -480,7 +458,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 149f383fb..55644eb45 100644 --- a/src/octoprint/server/api/printer_profiles.py +++ b/src/octoprint/server/api/printer_profiles.py @@ -5,8 +5,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import copy -from flask import jsonify, make_response, request, url_for -from werkzeug.exceptions import BadRequest +from flask import abort, jsonify, request, url_for from octoprint.access.permissions import Permissions from octoprint.printer.profile import CouldNotOverwriteError, InvalidProfileError @@ -56,18 +55,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"], str): @@ -91,25 +87,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".format( - profile["id"] - ), - 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)}) @@ -120,7 +111,7 @@ def printerProfilesAdd(): def printerProfilesGet(identifier): profile = printerProfileManager.get(identifier) if profile is None: - return make_response("Unknown profile: %s" % identifier, 404) + abort(404) else: return jsonify(_convert_profile(profile)) @@ -131,13 +122,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 - ) + 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: {}".format(identifier), 409) + abort(409, description="Cannot delete default profile") printerProfileManager.remove(identifier, trigger_event=True) return NO_CONTENT @@ -148,18 +137,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 +168,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 4eec18740..705f8f8ee 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -4,9 +4,8 @@ __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 werkzeug.exceptions import BadRequest import octoprint.plugin import octoprint.util @@ -148,7 +147,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"], @@ -365,22 +367,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: {!r}".format(type(data).__name__, data), - 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: @@ -460,7 +451,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"]: @@ -593,6 +584,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/server/api/slicing.py b/src/octoprint/server/api/slicing.py index 12be70275..f2dd80b42 100644 --- a/src/octoprint/server/api/slicing.py +++ b/src/octoprint/server/api/slicing.py @@ -2,8 +2,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 @@ -138,7 +137,7 @@ def slicingListSlicerProfiles(slicer): try: return jsonify(_getSlicingProfilesData(slicer, require_configured=configured)) except (UnknownSlicer, SlicerNotConfigured): - return make_response("Unknown slicer {slicer}".format(**locals()), 404) + abort(404) @api.route("/slicing//profiles/", methods=["GET"]) @@ -148,9 +147,9 @@ 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) + abort(404) except UnknownProfile: - return make_response("Profile not found", 404) + abort(404) result = _getSlicingProfileData(slicer, name, profile) result["data"] = profile.data @@ -162,15 +161,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 @@ -192,7 +187,7 @@ def slicingAddSlicerProfile(slicer, name): description=description, ) except UnknownSlicer: - return make_response("Unknown slicer {slicer}".format(**locals()), 404) + abort(404, description="Unknown slicer") result = _getSlicingProfileData(slicer, name, profile) r = make_response(jsonify(result), 201) @@ -205,24 +200,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 {slicer}".format(**locals()), 404) + return abort(404) except UnknownProfile: - return make_response( - "Profile {name} for slicer {slicer} not found".format(**locals()), 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 @@ -259,13 +248,13 @@ def slicingDelSlicerProfile(slicer, name): try: slicingManager.delete_profile(slicer, name) except UnknownSlicer: - return make_response("Unknown slicer {slicer}".format(**locals()), 404) + abort(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) - ), + 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 b31a58ae0..6e6b52eb3 100644 --- a/src/octoprint/server/api/system.py +++ b/src/octoprint/server/api/system.py @@ -7,7 +7,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 @@ -84,7 +84,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"]) @@ -108,7 +108,7 @@ def retrieveSystemCommandsForSource(source): elif source == "custom": specs = _get_custom_command_specs() else: - return make_response("Unknown system command source: {}".format(source), 404) + abort(404) return jsonify(_to_client_specs(specs)) @@ -120,18 +120,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".format(source, command), 404) + abort(404) if "command" not in command_spec: - return make_response( - "Command {}:{} does not define a command to execute, can't proceed".format( - source, command - ), - 500, + abort( + 500, description="Command does not define a command to execute, can't proceed" ) do_async = command_spec.get("async", False) @@ -154,7 +151,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: @@ -191,13 +188,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 7cb21e4ba..4bd38051a 100644 --- a/src/octoprint/server/api/timelapse.py +++ b/src/octoprint/server/api/timelapse.py @@ -6,7 +6,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 @@ -179,7 +179,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() @@ -205,8 +205,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) @@ -228,68 +228,56 @@ def setTimelapseConfig(): try: postRoll = int(data["postRoll"]) except ValueError: - return make_response( - "Invalid value for postRoll: %r" % data["postRoll"], 400 - ) + abort(400, description="postRoll is invalid") else: if postRoll >= 0: config["postRoll"] = postRoll else: - return make_response("Invalid value for postRoll: %d" % 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: %r" % data["fps"], 400) + abort(400, description="fps is invalid") else: if fps > 0: config["fps"] = fps else: - return make_response("Invalid value for fps: %d" % 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: %r" % data["interval"], 400 - ) + abort(400, description="interval is invalid") else: if interval > 0: config["options"]["interval"] = interval else: - return make_response("Invalid value for interval: %d" % 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: %r" % data["retractionZHop"], 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: %f" % retractionZHop, 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: %r" % data["minDelay"], 400 - ) + abort(400, description="minDelay is invalid") else: if minDelay > 0: config["options"]["minDelay"] = minDelay else: - return make_response( - "Invalid value for minimum delay: %f" % minDelay, 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 b7bc9537e..2bffcb591 100644 --- a/src/octoprint/server/util/__init__.py +++ b/src/octoprint/server/util/__init__.py @@ -44,7 +44,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(): @@ -55,7 +55,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): @@ -117,7 +117,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 7064f7a9a..ffa3b956d 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -1297,11 +1297,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) @@ -1539,7 +1541,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 @@ -1561,9 +1563,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 @@ -1578,34 +1578,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 diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py index 2c3c686e0..37e082677 100644 --- a/src/octoprint/server/util/tornado.py +++ b/src/octoprint/server/util/tornado.py @@ -1181,9 +1181,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): @@ -1326,7 +1330,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 11aa2b8d8..92d6a4b74 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -245,6 +245,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/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 { diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 2a1ae31c7..3ef281f2c 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -334,9 +334,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): @@ -1115,7 +1115,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/gcodeInterpreter.py b/src/octoprint/util/gcodeInterpreter.py index 33ec56344..fccdc25e9 100644 --- a/src/octoprint/util/gcodeInterpreter.py +++ b/src/octoprint/util/gcodeInterpreter.py @@ -143,11 +143,33 @@ class MinMax3D: >>> 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): """ @@ -224,7 +246,9 @@ class gcode: 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 @@ -445,17 +469,17 @@ class gcode: 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: 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"); }; diff --git a/versioneer.py b/versioneer.py index 7c2305223..a2888abc5 100644 --- a/versioneer.py +++ b/versioneer.py @@ -501,7 +501,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: @@ -650,11 +650,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() @@ -686,7 +686,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)) @@ -778,7 +778,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'" @@ -1379,7 +1379,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, ) @@ -1609,7 +1609,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): @@ -1884,7 +1884,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