From cd7f44cb57a9056aa0c6918f79bc24b012bcbdb5 Mon Sep 17 00:00:00 2001 From: JoveToo Date: Wed, 25 May 2022 16:01:31 +0200 Subject: [PATCH 01/12] There are not files with \r-only line endings (#4450) --- src/octoprint/plugins/gcodeviewer/static/js/gcodeviewer.js | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/octoprint/plugins/gcodeviewer/static/js/gcodeviewer.js b/src/octoprint/plugins/gcodeviewer/static/js/gcodeviewer.js index bb6adadfc..95b77f04b 100644 --- a/src/octoprint/plugins/gcodeviewer/static/js/gcodeviewer.js +++ b/src/octoprint/plugins/gcodeviewer/static/js/gcodeviewer.js @@ -522,10 +522,6 @@ $(function () { var findThis = self.settings.settings.plugins.gcodeviewer.skipUntilThis(); if (findThis && findThis !== "") { var indexPos = response.indexOf("\n" + findThis); - // Try windows newlines if not found - if (indexPos === -1) { - indexPos = response.indexOf("\r" + findThis); - } if (indexPos !== -1) { // Slice and make sure we comment out any string left back after slicing - so if a user configures something like "G1" we dont end up with a snippet of gcode commands // Yes it would be prettier to parse it line by line and remove the entire line, that is very slow and uses mem - this way we find the string, and remove it From c491f4fedc11e19972b278e389698cb2217752ef Mon Sep 17 00:00:00 2001 From: Charlie Powell <31997505+cp2004@users.noreply.github.com> Date: Mon, 30 May 2022 10:04:51 +0100 Subject: [PATCH 02/12] :arrow_up: Bump wrapt to fix Python 3.11 compatibility (#4530) Fully tested on 3.7, 3.10 and 3.11 - any issues that did exist appear to have been resolved. --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 6a174f76c..57106dee6 100644 --- a/setup.py +++ b/setup.py @@ -63,7 +63,7 @@ core_deps = [ "watchdog>=1,<2", "websocket-client>=1.2.1,<2", "werkzeug>=2.1,<2.2", # breaking changes can happen on minor version increases - "wrapt>=1.13.3,<1.14", + "wrapt>=1.14,<1.15", "zeroconf>=0.33,<0.34", # breaking changes can happen on minor version increases "zipstream-ng>=1.3.4,<2.0.0", ] From e2349b4565f5b1a41a0efde7feeaf372600b0b55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 30 May 2022 14:45:16 +0200 Subject: [PATCH 03/12] =?UTF-8?q?=F0=9F=91=B7=20Ignore=20errors=20on=20Dis?= =?UTF-8?q?cord=20hook=20&=20e2e?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit e2e are too flaky, discord hook might be unconfigured in a fork. --- .github/workflows/build.yml | 1 + .github/workflows/test_install.yml | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 4a219563a..fbc3ed47c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -96,6 +96,7 @@ jobs: name: ๐Ÿงช E2E tests needs: build runs-on: ubuntu-latest + continue-on-error: true steps: - name: โฌ‡ Checkout code uses: actions/checkout@v2 diff --git a/.github/workflows/test_install.yml b/.github/workflows/test_install.yml index 37e64bc49..76d7b2e23 100644 --- a/.github/workflows/test_install.yml +++ b/.github/workflows/test_install.yml @@ -31,12 +31,14 @@ jobs: run: | pip install . - name: ๐Ÿ“ง Discord success notification + continue-on-error: true env: DISCORD_WEBHOOK: ${{ secrets.discord_webhook }} uses: Ilshidur/action-discord@master with: args: "โ˜‘๏ธ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ matrix.branch }}` was successful" - name: ๐Ÿ“ง Discord failure notification + continue-on-error: true if: failure() env: DISCORD_WEBHOOK: ${{ secrets.discord_webhook }} @@ -65,12 +67,14 @@ jobs: run: | pip install https://github.com/OctoPrint/OctoPrint/archive/${{ steps.latest.outputs.release }}.zip - name: ๐Ÿ“ง Discord success notification + continue-on-error: true env: DISCORD_WEBHOOK: ${{ secrets.discord_webhook }} uses: Ilshidur/action-discord@master with: args: "โ˜‘๏ธ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ steps.latest.outputs.release }}` was successful" - name: ๐Ÿ“ง Discord failure notification + continue-on-error: true if: failure() env: DISCORD_WEBHOOK: ${{ secrets.discord_webhook }} From 53b9b6185781c07e8c4744a6e28462e96448f249 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 30 May 2022 14:51:54 +0200 Subject: [PATCH 04/12] =?UTF-8?q?=F0=9F=91=B7=20Only=20trigger=20release?= =?UTF-8?q?=20jobs=20on=20main=20repo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/build.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index fbc3ed47c..44d27367b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -142,7 +142,7 @@ jobs: publish-on-testpypi: name: ๐Ÿ“ฆ Publish on TestPyPI - if: github.event_name == 'release' + if: github.event_name == 'release' && github.repository == 'OctoPrint/OctoPrint' needs: - pre-commit - test-unit @@ -164,7 +164,7 @@ jobs: publish-on-pypi: name: ๐Ÿ“ฆ Publish tagged releases to PyPI - if: github.event_name == 'release' + if: github.event_name == 'release' && github.repository == 'OctoPrint/OctoPrint' needs: publish-on-testpypi runs-on: ubuntu-latest steps: @@ -180,7 +180,7 @@ jobs: notify-custopizer-build: name: ๐Ÿ“ง Notify OctoPi-UpToDate - if: github.event_name == 'release' + if: github.event_name == 'release' && github.repository == 'OctoPrint/OctoPrint' needs: publish-on-pypi runs-on: ubuntu-latest steps: From fe84605f2477ed050bb4f9daa8533f418008aeac Mon Sep 17 00:00:00 2001 From: Billy Richardson Date: Tue, 31 May 2022 05:16:47 -0700 Subject: [PATCH 05/12] =?UTF-8?q?=F0=9F=91=B7=20Add=20JS=20QUnit=20tests?= =?UTF-8?q?=20to=20build=20workflow=20with=20node-qunit-puppeteer=20(#4534?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/build.yml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 44d27367b..84c8c2f39 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -65,6 +65,19 @@ jobs: run: | pytest + test-js-unit: + name: ๐Ÿงช JavaScript unit tests + needs: build + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: ๐Ÿ— Set up test dependencies + run: | + npm -g install node-qunit-puppeteer@2.1.0 + - name: ๐Ÿš€ Run helpers.js test suite + run: | + node-qunit-puppeteer tests/static/js/test-helpers.html + test-install: name: ๐Ÿงช Installation tests needs: build @@ -146,6 +159,7 @@ jobs: needs: - pre-commit - test-unit + - test-js-unit - test-install - test-e2e runs-on: ubuntu-latest From e8be86c15f8de90b2b429e80ca75594c44345e0c Mon Sep 17 00:00:00 2001 From: Billy Richardson Date: Tue, 31 May 2022 05:17:27 -0700 Subject: [PATCH 06/12] =?UTF-8?q?=E2=9C=85=20Add=20a=20few=20unit=20tests?= =?UTF-8?q?=20for=20helpers.js=20(#4529)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/static/js/app/helpers.js | 8 +- tests/static/js/test-helpers.js | 221 +++++++++++++++++++++++++ 2 files changed, 227 insertions(+), 2 deletions(-) diff --git a/src/octoprint/static/js/app/helpers.js b/src/octoprint/static/js/app/helpers.js index fe6b9d649..8a3c015cc 100644 --- a/src/octoprint/static/js/app/helpers.js +++ b/src/octoprint/static/js/app/helpers.js @@ -1555,7 +1555,7 @@ var copyToClipboard = function (text) { }; var getExternalHostUrl = function () { - var loc = window.location; + var loc = fetchWindowLocation(); var port = ""; if ( (loc.protocol === "http:" && loc.port !== "80") || @@ -1576,7 +1576,7 @@ var validateWebcamUrl = function (streamUrl) { if (lower.startsWith("//")) { // protocol relative - toParse = window.location.protocol + streamUrl; + toParse = fetchWindowLocation().protocol + streamUrl; } else if (lower.startsWith("/")) { // host relative toParse = getExternalHostUrl() + streamUrl; @@ -1751,3 +1751,7 @@ var startWebRTC = function (videoElement, streamUrl, iceServers) { negotiateWebRTC(streamUrl); return pc; }; + +var fetchWindowLocation = function () { + return window.location; +}; diff --git a/tests/static/js/test-helpers.js b/tests/static/js/test-helpers.js index 89b947a06..ccf34fc5a 100644 --- a/tests/static/js/test-helpers.js +++ b/tests/static/js/test-helpers.js @@ -189,3 +189,224 @@ QUnit.cases( "As expected: " + String(params.expected) ); }); + +QUnit.module("determineWebcamStreamType"); +QUnit.cases( + (function () { + var cases = []; + + var params = [ + { + streamUrl: undefined, + exceptionExpected: "Empty streamUrl. Cannot determine stream type.", + expectedResult: undefined + }, + { + streamUrl: "invalidUrl", + exceptionExpected: "Invalid streamUrl. Cannot determine stream type.", + expectedResult: undefined + }, + { + streamUrl: "webrtc://localhost/stream", + exceptionExpected: undefined, + expectedResult: "webrtc" + }, + { + streamUrl: "webrtcs://localhost/stream", + exceptionExpected: undefined, + expectedResult: "webrtc" + }, + { + streamUrl: "https://localhost/stream.m3u8", + exceptionExpected: undefined, + expectedResult: "hls" + }, + { + streamUrl: "https://localhost/stream", + exceptionExpected: undefined, + expectedResult: "mjpg" + } + ]; + + var param, i; + for (i = 0; i < params.length; i++) { + param = params[i]; + param["title"] = + String(param.streamUrl) + + String(param.exceptionExpected) + + String(param.expectedResult); + cases.push(param); + } + + return cases; + })() +).test("determineWebcamStreamType", function (params, assert) { + var exceptionMessage = undefined; + var result = undefined; + + try { + result = determineWebcamStreamType(params.streamUrl); + } catch (ex) { + exceptionMessage = ex; + } + + assert.equal( + params.exceptionExpected, + exceptionMessage, + "Exception expected: " + String(params.exceptionExpected) + ); + + assert.equal( + params.expectedResult, + result, + "As expected: " + String(params.expectedResult) + ); +}); + +QUnit.module("validateWebcamUrl"); +QUnit.cases( + (function () { + var cases = []; + + var params = [ + { + streamUrl: undefined, + expected: false, + windowLocationOverride: undefined + }, + { + streamUrl: "//localhost/stream", + expected: new URL("https://localhost/stream"), + windowLocationOverride: {protocol: "https:"} + }, + { + streamUrl: "/stream", + expected: new URL("https://localhost/stream"), + windowLocationOverride: { + protocol: "https:", + port: "443", + hostname: "localhost" + } + }, + { + streamUrl: "http://localhost/stream", + expected: new URL("http://localhost/stream"), + windowLocationOverride: undefined + }, + { + streamUrl: "https://localhost/stream", + expected: new URL("https://localhost/stream"), + windowLocationOverride: undefined + }, + { + streamUrl: "webrtc://localhost/stream", + expected: new URL("webrtc://localhost/stream"), + windowLocationOverride: undefined + }, + { + streamUrl: "webrtcs://localhost/stream", + expected: new URL("webrtcs://localhost/stream"), + windowLocationOverride: undefined + }, + { + streamUrl: "invalid", + expected: false, + windowLocationOverride: undefined + }, + { + streamUrl: "//exception", + expected: false, + windowLocationOverride: {protocol: ":"} + } + ]; + + var param, i; + for (i = 0; i < params.length; i++) { + param = params[i]; + param["title"] = String(param.streamUrl) + String(param.expected); + cases.push(param); + } + + return cases; + })() +).test("validateWebcamUrl", function (params, assert) { + if (params.windowLocationOverride) { + fetchWindowLocation = function () { + return params.windowLocationOverride; + }; + } + + var result = validateWebcamUrl(params.streamUrl); + + assert.equal( + params.expected.toString(), + result.toString(), + "As expected: " + String(params.expected) + ); +}); + +QUnit.module("getExternalHostUrl"); +QUnit.cases( + (function () { + var cases = []; + + var params = [ + { + windowLocation: { + protocol: "https:", + port: "443", + hostname: "localhost" + }, + expected: "https://localhost" + }, + { + windowLocation: { + protocol: "https:", + port: "8000", + hostname: "localhost" + }, + expected: "https://localhost:8000" + }, + + { + windowLocation: { + protocol: "http:", + port: "80", + hostname: "localhost" + }, + expected: "http://localhost" + }, + { + windowLocation: { + protocol: "http:", + port: "8000", + hostname: "localhost" + }, + expected: "http://localhost:8000" + } + ]; + + var param, i; + for (i = 0; i < params.length; i++) { + param = params[i]; + param["title"] = + String(param.windowLocation.protocol) + + "//" + + String(param.windowLocation.hostname) + + String(param.windowLocation.port); + cases.push(param); + } + + return cases; + })() +).test("getExternalHostUrl", function (params, assert) { + if (params.windowLocation) { + fetchWindowLocation = function () { + return params.windowLocation; + }; + } + + var result = getExternalHostUrl(); + + assert.equal(params.expected, result, "As expected: " + String(params.expected)); +}); From 999ccac2308d613903448aaf654a4f38f767a870 Mon Sep 17 00:00:00 2001 From: luzpaz Date: Tue, 31 May 2022 08:18:38 -0400 Subject: [PATCH 07/12] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20misc.=20typos?= =?UTF-8?q?=20(#4533)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Found via `codespell -q 3 -S *.po` --- docs/api/timelapse.rst | 4 ++-- docs/api/util.rst | 2 +- docs/features/accesscontrol.rst | 4 ++-- docs/plugins/hooks.rst | 2 +- docs/plugins/python3_migration.rst | 2 +- src/octoprint/plugins/pluginmanager/__init__.py | 2 +- src/octoprint/static/js/app/viewmodels/control.js | 2 +- src/octoprint/static/js/recovery/recovery.js | 2 +- src/octoprint/static/less/bootstrap/reset.less | 2 +- src/octoprint/util/json/serializing.py | 2 +- src/octoprint/util/pip.py | 2 +- tests/filemanager/test_localstorage.py | 2 +- 12 files changed, 14 insertions(+), 14 deletions(-) diff --git a/docs/api/timelapse.rst b/docs/api/timelapse.rst index ebe291e83..e739b43ee 100644 --- a/docs/api/timelapse.rst +++ b/docs/api/timelapse.rst @@ -76,7 +76,7 @@ Change current timelapse config .. http:post:: /api/timelapse Save a new :ref:`timelapse configuration ` to use for the next print. Set the optional ``save`` flag in the - configuration to ``true`` in order to make the new configuration persist accross restarts. + configuration to ``true`` in order to make the new configuration persist across restarts. The configuration is expected as the request body. @@ -220,7 +220,7 @@ Timelapse configuration * - ``save`` - 1 - bool - - Optional flag to be included when when saving a configuration to make the configuration persist accross restarts + - Optional flag to be included when when saving a configuration to make the configuration persist across restarts Further fields are timelapse type specific, see below for details. diff --git a/docs/api/util.rst b/docs/api/util.rst index bb1271240..e3ea44b29 100644 --- a/docs/api/util.rst +++ b/docs/api/util.rst @@ -76,7 +76,7 @@ Various tests * ``content_type_whitelist``: Optional array of supported content types. If set and the URL returns a content type not included in this list, the test will fail. E.g. ``["image/*", "text/plain"]``. * ``content_type_blacklist``: Optional array of unsupported content types. If set and the URL returns a content - type included in this list, the test wil fail. E.g. ``["video/*"]``. Can be used together with ``content_type_whitelist`` + type included in this list, the test will fail. E.g. ``["video/*"]``. Can be used together with ``content_type_whitelist`` to further limit broader content type definition, e.g. by putting ``image/*`` into the whitelist, but disallowing PNG by including ``image/png`` on the blacklist. diff --git a/docs/features/accesscontrol.rst b/docs/features/accesscontrol.rst index 218e3bb9c..97c166a07 100644 --- a/docs/features/accesscontrol.rst +++ b/docs/features/accesscontrol.rst @@ -110,7 +110,7 @@ The subnet to use is usually the IP address range of your LAN, which sounds scar actually isn't. Just `figure out your PC's IP address and subnet mask `_ and then combine both with a / in between. -On OctoPi (or another Linux distribution) you can use the follwing command: +On OctoPi (or another Linux distribution) you can use the following command: .. code-block:: @@ -189,7 +189,7 @@ further down there's also a dedicated list of steps for OctoPi specifically. 4. Restart OctoPrint, check that everything works. -This will automatically log you in as the user you specified whenver you connect to +This will automatically log you in as the user you specified whenever you connect to OctoPrint from an address in the address range (e.g. a device on your local network). OctoPi specific steps diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst index 6d1b32709..47822eb48 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -1433,7 +1433,7 @@ octoprint.server.http.access_validator Allows adding additional access validators to the default tornado routers. - Your plugin might need to this to restrict acccess to downloads and webcam snapshots further. + Your plugin might need to this to restrict access to downloads and webcam snapshots further. .. important:: diff --git a/docs/plugins/python3_migration.rst b/docs/plugins/python3_migration.rst index cbf9ccaf4..d90b74e22 100644 --- a/docs/plugins/python3_migration.rst +++ b/docs/plugins/python3_migration.rst @@ -235,7 +235,7 @@ will now fail with an error. You'll need to explicitly make the import a relativ from . import my_sub_package -To make your code behave the same in that regard unter both Python 2 and Python 3, you should add the corresponding +To make your code behave the same in that regard in both Python 2 and Python 3, you should add the corresponding future import: .. code-block:: python diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 4b338e668..1c8a5f6be 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -97,7 +97,7 @@ def map_repository_entry(entry): entry["compatibility"]["python"] ) else: - # we default to only assume py2 compatiblity for now + # we default to only assume py2 compatibility for now result["is_compatible"]["python"] = is_python_compatible(">=2.7,<3") return result diff --git a/src/octoprint/static/js/app/viewmodels/control.js b/src/octoprint/static/js/app/viewmodels/control.js index ca8c4cb4b..81fd783d4 100644 --- a/src/octoprint/static/js/app/viewmodels/control.js +++ b/src/octoprint/static/js/app/viewmodels/control.js @@ -868,7 +868,7 @@ $(function () { // If we found the rotation container, the view is rotated 90 degrees. This // means we need to manually calculate the player dimensions and apply them // to the rotation target where height = width and width = height (to - // accomodate the rotation). The target is centered in the container and + // accommodate the rotation). The target is centered in the container and // rotated around its center, so after we manually resized the container // everything will layout nicely. if (rotationContainer && player.videoWidth && player.videoHeight) { diff --git a/src/octoprint/static/js/recovery/recovery.js b/src/octoprint/static/js/recovery/recovery.js index 6f5bc671e..1ce4cbc6e 100644 --- a/src/octoprint/static/js/recovery/recovery.js +++ b/src/octoprint/static/js/recovery/recovery.js @@ -41,7 +41,7 @@ $(function () { // system commands self.systemCommands = ko.observableArray([]); - // systen info + // system info self.systemInfo = ko.observableArray([]); // printer diff --git a/src/octoprint/static/less/bootstrap/reset.less b/src/octoprint/static/less/bootstrap/reset.less index cf00d9c23..7afdcaecb 100644 --- a/src/octoprint/static/less/bootstrap/reset.less +++ b/src/octoprint/static/less/bootstrap/reset.less @@ -77,7 +77,7 @@ sub { img { /* Responsive images (ensure images don't scale beyond their parents) */ - max-width: 100%; /* Part 1: Set a maxium relative to the parent */ + max-width: 100%; /* Part 1: Set a maximum relative to the parent */ width: auto\9; /* IE7-8 need help adjusting responsive images */ height: auto; /* Part 2: Scale the height according to the width, otherwise you get stretching */ diff --git a/src/octoprint/util/json/serializing.py b/src/octoprint/util/json/serializing.py index 668bf4bd7..d8b9ab970 100644 --- a/src/octoprint/util/json/serializing.py +++ b/src/octoprint/util/json/serializing.py @@ -57,7 +57,7 @@ class SerializableJsonEncoding(JsonEncoding): def encode(cls, val): """ Recursively replace all instances of encodable types with their encoded - value. This is useful over the ``default=`` functionallity of the JSON + value. This is useful over the ``default=`` functionality of the JSON encoder because JSON will not call default for tuples, lists, ints, etc: https://docs.python.org/3/library/json.html#json.JSONEncoder diff --git a/src/octoprint/util/pip.py b/src/octoprint/util/pip.py index 5dc5c9340..ff25391e1 100644 --- a/src/octoprint/util/pip.py +++ b/src/octoprint/util/pip.py @@ -83,7 +83,7 @@ def is_python_mismatch(lines): def is_egg_problem(lines): """ - Returns whether the given output lines indicates an occurence of the "egg-problem". + Returns whether the given output lines indicates an occurrence of the "egg-problem". If something (target or dependency of target) was installed as an egg at an earlier date (e.g. thanks to just running python setup.py install), pip install will throw an diff --git a/tests/filemanager/test_localstorage.py b/tests/filemanager/test_localstorage.py index 508446f26..13fe028a1 100644 --- a/tests/filemanager/test_localstorage.py +++ b/tests/filemanager/test_localstorage.py @@ -896,7 +896,7 @@ class LocalStorageTest(unittest.TestCase): """ Adds a folder to the storage. - Verifies existance of folder. + Verifies existence of folder. Returns sanitized path. """ From 64ad527753873cb8cd78a800d07eb0c879581022 Mon Sep 17 00:00:00 2001 From: Federico Nembrini <25205086+FedericoNembrini@users.noreply.github.com> Date: Tue, 7 Jun 2022 13:43:50 +0200 Subject: [PATCH 08/12] =?UTF-8?q?=E2=9C=A8=20Record=20last=20fan=20speed?= =?UTF-8?q?=20(#4531)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add fan speed record to record last, pause and cancel fan speed Update doc. * Replace fan speed record with simple fan speed variable Update doc. --- docs/features/gcode_scripts.rst | 4 ++++ src/octoprint/util/comm.py | 25 +++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/docs/features/gcode_scripts.rst b/docs/features/gcode_scripts.rst index aa8fb1329..bccce9e66 100644 --- a/docs/features/gcode_scripts.rst +++ b/docs/features/gcode_scripts.rst @@ -84,6 +84,8 @@ All GCODE scripts have access to the following template variables through the te to the corresponding temperature in degrees Celsius. Note that not all tools your printer has must necessarily be present here, neither must the heated bed - it depends on whether OctoPrint has values for a tool or the bed. Also note that ``actual`` and ``target`` might be ``None``. + * ``last_fanspeed``: Last fan speed set. It contains the value taken from command (M106 and M107) sent through OctoPrint. + The value might be ``None`` if no fan speed has been set. * ``script``: An object wrapping the script's type (``gcode``) and name (e.g. ``afterPrintCancelled``) as ``script.type`` and ``script.name`` respectively. * ``plugins``: An object containing variables provided by plugins (e.g ``plugins.myplugin.myvariable``) @@ -99,6 +101,7 @@ There are a few additional template variables available for the following specif "Log position on pause" under Settings > Serial > Advanced options! * ``pause_temperature``: Last known temperature values when the print was paused. See ``last_temperature`` above for the structure to expect here. + * ``pause_fanspeed``: Last known fan speed value when the print was paused. See ``last_fanspeed`` above for the structure to expect here. * ``afterPrintCancelled`` @@ -109,6 +112,7 @@ There are a few additional template variables available for the following specif "Log position on cancel" under Settings > Serial > Advanced options! * ``cancel_temperature``: Last known temperature values when the print was cancelled. See ``last_temperature`` above for the structure to expect here. + * ``cancel_fanspeed``: Last known fan speed value when the print was cancelled. See ``last_fanspeed`` above for the structure to expect here. * ``beforeToolChange`` and ``afterToolChange`` diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 567506f88..7fe003bc2 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -760,6 +760,10 @@ class MachineCom: self.pause_position = PositionRecord() self.cancel_position = PositionRecord() + self.last_fanspeed = None + self.pause_fanspeed = None + self.cancel_fanspeed = None + self._record_pause_data = False self._record_cancel_data = False @@ -1299,6 +1303,7 @@ class MachineCom: "printer_profile": self._printerProfileManager.get_current_or_default(), "last_position": self.last_position, "last_temperature": self.last_temperature.as_script_dict(), + "last_fanspeed": self.last_fanspeed, } ) @@ -1307,6 +1312,7 @@ class MachineCom: { "pause_position": self.pause_position, "pause_temperature": self.pause_temperature.as_script_dict(), + "pause_fanspeed": self.pause_fanspeed, } ) elif scriptName == "afterPrintCancelled": @@ -1314,6 +1320,7 @@ class MachineCom: { "cancel_position": self.cancel_position, "cancel_temperature": self.cancel_temperature.as_script_dict(), + "cancel_fanspeed": self.cancel_fanspeed, } ) @@ -2616,6 +2623,7 @@ class MachineCom: self._record_pause_data = False self.pause_position.copy_from(self.last_position) self.pause_temperature.copy_from(self.last_temperature) + self.pause_fanspeed = self.last_fanspeed self._pause_preparation_done() if self._record_cancel_data: @@ -2623,6 +2631,7 @@ class MachineCom: self._record_cancel_data = False self.cancel_position.copy_from(self.last_position) self.cancel_temperature.copy_from(self.last_temperature) + self.cancel_fanspeed = self.last_fanspeed self._cancel_preparation_done() self._callback.on_comm_position_update( @@ -5371,6 +5380,22 @@ class MachineCom: self._timeout = self._get_new_communication_timeout() + _timeout self._dwelling_until = time.monotonic() + _timeout + def _gcode_M106_sent( + self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs + ): + s_match = regexes_parameters["intS"].search(cmd) + + fanspeed = 0 + if s_match: + fanspeed = int(s_match.group("value")) + + self.last_fanspeed = fanspeed + + def _gcode_M107_sent( + self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs + ): + self.last_fanspeed = 0 + def _emergency_force_send(self, cmd, message, gcode=None, *args, **kwargs): # only jump the queue with our command if the EMERGENCY_PARSER capability is available if not self._capability_supported(self.CAPABILITY_EMERGENCY_PARSER): From 10ec9cd4e4edf536c1dcf2a62a4bdb5e442670f9 Mon Sep 17 00:00:00 2001 From: Billy Richardson Date: Wed, 8 Jun 2022 03:03:23 -0700 Subject: [PATCH 09/12] =?UTF-8?q?=E2=9C=85=20Add=20more=20unit=20tests=20f?= =?UTF-8?q?or=20`helpers.js`=20(#4536)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/static/js/app/helpers.js | 2 +- tests/static/js/test-helpers.html | 1 + tests/static/js/test-helpers.js | 822 ++++++++++++++++++++++--- 3 files changed, 749 insertions(+), 76 deletions(-) diff --git a/src/octoprint/static/js/app/helpers.js b/src/octoprint/static/js/app/helpers.js index 8a3c015cc..4e506e40d 100644 --- a/src/octoprint/static/js/app/helpers.js +++ b/src/octoprint/static/js/app/helpers.js @@ -1497,7 +1497,7 @@ var sizeObservable = function (observable) { var getQueryParameterByName = function (name, url) { // from http://stackoverflow.com/a/901144/2028598 if (!url) { - url = window.location.href; + url = fetchWindowLocation().href; } name = name.replace(/[\[\]]/g, "\\$&"); var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), diff --git a/tests/static/js/test-helpers.html b/tests/static/js/test-helpers.html index 298c31afe..454332791 100644 --- a/tests/static/js/test-helpers.html +++ b/tests/static/js/test-helpers.html @@ -10,6 +10,7 @@
+ diff --git a/tests/static/js/test-helpers.js b/tests/static/js/test-helpers.js index ccf34fc5a..f56bc7188 100644 --- a/tests/static/js/test-helpers.js +++ b/tests/static/js/test-helpers.js @@ -7,36 +7,34 @@ QUnit.cases( var params = [ // empty inputs - {input: undefined, expected: undefined}, - {input: "", expected: undefined}, + {title: "UndefinedSize", input: undefined, expected: undefined}, + {title: "EmptySize", input: "", expected: undefined}, // unknown units - {input: "1 PB", expected: undefined}, - {input: "234.5 unknown", expected: undefined}, - {input: "234.5unknown", expected: undefined}, + {title: "UnknownPBSuffix", input: "1 PB", expected: undefined}, + {title: "UnknownSuffixSpace", input: "234.5 unknown", expected: undefined}, + {title: "UnknownSuffix", input: "234.5unknown", expected: undefined}, // conversion - {input: "1", expected: 1}, - {input: "1b", expected: 1}, - {input: "1 B", expected: 1}, - {input: "1 byte", expected: 1}, - {input: "1 bYtES", expected: 1}, - {input: "1.1", expected: 1.1}, - {input: ".1", expected: 0.1}, - {input: "1 KB", expected: 1024}, - {input: "2 KB", expected: 2048}, - {input: "1 MB", expected: Math.pow(1024, 2)}, - {input: "500mb", expected: 500 * Math.pow(1024, 2)}, - {input: "500.2mb", expected: 500.2 * Math.pow(1024, 2)}, - {input: "1 GB", expected: Math.pow(1024, 3)}, - {input: "1 TB", expected: Math.pow(1024, 4)} + {title: "WholeByteNoSuffix", input: "1", expected: 1}, + {title: "WholeByteAbbreviatedSuffix", input: "1b", expected: 1}, + {title: "WholeByteAbbreviatedSuffixSpace", input: "1 B", expected: 1}, + {title: "WholeByteWordSuffix", input: "1 byte", expected: 1}, + {title: "WholeByteWordSuffixCapitalization", input: "1 bYtES", expected: 1}, + {title: "WholeFractionalBytesNoSuffix", input: "1.1", expected: 1.1}, + {title: "FractionalBytesNoSuffix", input: ".1", expected: 0.1}, + {title: "OneKilobyte", input: "1 KB", expected: 1024}, + {title: "TwoKilobytes", input: "2 KB", expected: 2048}, + {title: "OneMegabyte", input: "1 MB", expected: Math.pow(1024, 2)}, + {title: "WholeMB", input: "500mb", expected: 500 * Math.pow(1024, 2)}, + {title: "DecimalMB", input: "500.2mb", expected: 500.2 * Math.pow(1024, 2)}, + {title: "OneGigabyte", input: "1 GB", expected: Math.pow(1024, 3)}, + {title: "OneTerabyte", input: "1 TB", expected: Math.pow(1024, 4)} ]; var param, i; for (i = 0; i < params.length; i++) { param = params[i]; - param["title"] = - param.input != undefined ? '"' + String(param.input) + '"' : "undefined"; cases.push(param); } @@ -44,8 +42,8 @@ QUnit.cases( })() ).test("bytesFromSize", function (params, assert) { assert.equal( - params.expected, bytesFromSize(params.input), + params.expected, "As expected: " + String(params.expected) ); }); @@ -56,23 +54,22 @@ QUnit.cases( var cases = []; var params = [ - {input: undefined, expected: "-"}, - {input: "", expected: "-"}, - {input: 1, expected: "1.0bytes"}, - {input: 1.1, expected: "1.1bytes"}, - {input: 1024, expected: "1.0KB"}, - {input: 2048, expected: "2.0KB"}, - {input: 2.2 * 1024, expected: "2.2KB"}, - {input: 23.5 * Math.pow(1024, 2), expected: "23.5MB"}, - {input: 23.5 * Math.pow(1024, 3), expected: "23.5GB"}, - {input: 23.5 * Math.pow(1024, 4), expected: "23.5TB"}, - {input: 2 * Math.pow(1024, 5), expected: "2048.0TB"} + {title: "UndefinedSize", input: undefined, expected: "-"}, + {title: "EmptySize", input: "", expected: "-"}, + {title: "WholeByte", input: 1, expected: "1.0bytes"}, + {title: "FractionalBytes", input: 1.1, expected: "1.1bytes"}, + {title: "OneKilobyte", input: 1024, expected: "1.0KB"}, + {title: "TwoKilobytes", input: 2048, expected: "2.0KB"}, + {title: "FractionalKilobytes", input: 2.2 * 1024, expected: "2.2KB"}, + {title: "FractionalMB", input: 23.5 * Math.pow(1024, 2), expected: "23.5MB"}, + {title: "FractionalGB", input: 23.5 * Math.pow(1024, 3), expected: "23.5GB"}, + {title: "FractionalTB", input: 23.5 * Math.pow(1024, 4), expected: "23.5TB"}, + {title: "PetabyteAsTB", input: 2 * Math.pow(1024, 5), expected: "2048.0TB"} ]; var param, i; for (i = 0; i < params.length; i++) { param = params[i]; - param["title"] = String(param.input); cases.push(param); } @@ -80,8 +77,8 @@ QUnit.cases( })() ).test("formatSize", function (params, assert) { assert.equal( - params.expected, formatSize(params.input), + params.expected, "As expected: " + String(params.expected) ); }); @@ -93,6 +90,7 @@ QUnit.cases( var params = [ { + title: "UndefinedTemperature", input: undefined, showF: undefined, useUnicode: undefined, @@ -100,6 +98,7 @@ QUnit.cases( expected: "-" }, { + title: "EmptyTemperature", input: "", showF: undefined, useUnicode: undefined, @@ -107,6 +106,7 @@ QUnit.cases( expected: "-" }, { + title: "TemperatureUnderOffThreshold", input: 1.0, showF: undefined, useUnicode: undefined, @@ -114,6 +114,7 @@ QUnit.cases( expected: "off" }, { + title: "TemperatureEqualToOffThreshold", input: 1.0, showF: undefined, useUnicode: undefined, @@ -121,6 +122,7 @@ QUnit.cases( expected: "1.0°C" }, { + title: "TemperatureWithNoOffThreshold", input: 1.0, showF: undefined, useUnicode: undefined, @@ -128,6 +130,7 @@ QUnit.cases( expected: "1.0°C" }, { + title: "TemperatureWithFahrenheit", input: 1.0, showF: true, useUnicode: undefined, @@ -135,6 +138,7 @@ QUnit.cases( expected: "1.0°C (33.8°F)" }, { + title: "TemperatureWithFahrenheitUnicode", input: 1.0, showF: true, useUnicode: true, @@ -142,6 +146,7 @@ QUnit.cases( expected: "1.0\u00B0C (33.8\u00B0F)" }, { + title: "TemperatureHtmlEntities", input: 1.0, showF: undefined, useUnicode: false, @@ -149,6 +154,7 @@ QUnit.cases( expected: "1.0°C" }, { + title: "TemperatureUnicode", input: 1.0, showF: undefined, useUnicode: true, @@ -156,6 +162,7 @@ QUnit.cases( expected: "1.0\u00B0C" }, { + title: "TemperatureIncrease", input: 1.1, showF: undefined, useUnicode: undefined, @@ -167,11 +174,6 @@ QUnit.cases( var param, i; for (i = 0; i < params.length; i++) { param = params[i]; - param["title"] = - String(param.input) + - String(param.showF) + - String(param.offThreshold) + - String(param.useUnicode); cases.push(param); } @@ -179,13 +181,13 @@ QUnit.cases( })() ).test("formatTemperature", function (params, assert) { assert.equal( - params.expected, formatTemperature( params.input, params.showF, params.offThreshold, params.useUnicode ), + params.expected, "As expected: " + String(params.expected) ); }); @@ -197,31 +199,37 @@ QUnit.cases( var params = [ { + title: "UndefinedUrlThrowsException", streamUrl: undefined, exceptionExpected: "Empty streamUrl. Cannot determine stream type.", expectedResult: undefined }, { + title: "InvalidUrlThrowsException", streamUrl: "invalidUrl", exceptionExpected: "Invalid streamUrl. Cannot determine stream type.", expectedResult: undefined }, { + title: "Webrtc", streamUrl: "webrtc://localhost/stream", exceptionExpected: undefined, expectedResult: "webrtc" }, { + title: "Webrtcs", streamUrl: "webrtcs://localhost/stream", exceptionExpected: undefined, expectedResult: "webrtc" }, { + title: "HlsPlaylist", streamUrl: "https://localhost/stream.m3u8", exceptionExpected: undefined, expectedResult: "hls" }, { + title: "DefaultMjpg", streamUrl: "https://localhost/stream", exceptionExpected: undefined, expectedResult: "mjpg" @@ -231,10 +239,6 @@ QUnit.cases( var param, i; for (i = 0; i < params.length; i++) { param = params[i]; - param["title"] = - String(param.streamUrl) + - String(param.exceptionExpected) + - String(param.expectedResult); cases.push(param); } @@ -251,14 +255,14 @@ QUnit.cases( } assert.equal( - params.exceptionExpected, exceptionMessage, + params.exceptionExpected, "Exception expected: " + String(params.exceptionExpected) ); assert.equal( - params.expectedResult, result, + params.expectedResult, "As expected: " + String(params.expectedResult) ); }); @@ -270,60 +274,68 @@ QUnit.cases( var params = [ { + title: "UndefinedUrlReturnsFalse", streamUrl: undefined, - expected: false, - windowLocationOverride: undefined + windowLocationOverride: undefined, + expected: false }, { + title: "RelativeProtocolUrl", streamUrl: "//localhost/stream", - expected: new URL("https://localhost/stream"), - windowLocationOverride: {protocol: "https:"} + windowLocationOverride: {protocol: "https:"}, + expected: new URL("https://localhost/stream") }, { + title: "RelativePathUrl", streamUrl: "/stream", - expected: new URL("https://localhost/stream"), windowLocationOverride: { protocol: "https:", port: "443", hostname: "localhost" - } + }, + expected: new URL("https://localhost/stream") }, { + title: "Http", streamUrl: "http://localhost/stream", - expected: new URL("http://localhost/stream"), - windowLocationOverride: undefined + windowLocationOverride: undefined, + expected: new URL("http://localhost/stream") }, { + title: "Https", streamUrl: "https://localhost/stream", - expected: new URL("https://localhost/stream"), - windowLocationOverride: undefined + windowLocationOverride: undefined, + expected: new URL("https://localhost/stream") }, { + title: "Webrtc", streamUrl: "webrtc://localhost/stream", - expected: new URL("webrtc://localhost/stream"), - windowLocationOverride: undefined + windowLocationOverride: undefined, + expected: new URL("webrtc://localhost/stream") }, { + title: "Webrtcs", streamUrl: "webrtcs://localhost/stream", - expected: new URL("webrtcs://localhost/stream"), - windowLocationOverride: undefined + windowLocationOverride: undefined, + expected: new URL("webrtcs://localhost/stream") }, { + title: "InvalidUrlReturnsFalse", streamUrl: "invalid", - expected: false, - windowLocationOverride: undefined + windowLocationOverride: undefined, + expected: false }, { + title: "ParsingExceptionReturnsFalse", streamUrl: "//exception", - expected: false, - windowLocationOverride: {protocol: ":"} + windowLocationOverride: {protocol: ":"}, + expected: false } ]; var param, i; for (i = 0; i < params.length; i++) { param = params[i]; - param["title"] = String(param.streamUrl) + String(param.expected); cases.push(param); } @@ -339,8 +351,8 @@ QUnit.cases( var result = validateWebcamUrl(params.streamUrl); assert.equal( - params.expected.toString(), result.toString(), + params.expected.toString(), "As expected: " + String(params.expected) ); }); @@ -352,6 +364,7 @@ QUnit.cases( var params = [ { + title: "HttpsDefaultPortOmitted", windowLocation: { protocol: "https:", port: "443", @@ -360,6 +373,7 @@ QUnit.cases( expected: "https://localhost" }, { + title: "HttpsNonDefaultPortNotOmitted", windowLocation: { protocol: "https:", port: "8000", @@ -367,8 +381,8 @@ QUnit.cases( }, expected: "https://localhost:8000" }, - { + title: "HttpDefaultPortOmitted", windowLocation: { protocol: "http:", port: "80", @@ -377,6 +391,7 @@ QUnit.cases( expected: "http://localhost" }, { + title: "HttpNonDefaultPortNotOmitted", windowLocation: { protocol: "http:", port: "8000", @@ -389,11 +404,6 @@ QUnit.cases( var param, i; for (i = 0; i < params.length; i++) { param = params[i]; - param["title"] = - String(param.windowLocation.protocol) + - "//" + - String(param.windowLocation.hostname) + - String(param.windowLocation.port); cases.push(param); } @@ -407,6 +417,668 @@ QUnit.cases( } var result = getExternalHostUrl(); - - assert.equal(params.expected, result, "As expected: " + String(params.expected)); + assert.equal(result, params.expected, "As expected: " + String(params.expected)); +}); + +QUnit.module("escapeUnprintableCharacters"); +QUnit.cases( + (function () { + var cases = []; + + var params = [ + { + title: "EmptyText", + input: "", + isExpectingException: false, + expectedResult: "" + }, + { + title: "UndefinedText", + input: undefined, + isExpectingException: true, + expectedResult: undefined + }, + { + title: "PrintableTextUnchanged", + input: "Test123", + isExpectingException: false, + expectedResult: "Test123" + }, + { + title: "MultipleCharacterAsHex", + input: "\x00\x01\x02", + isExpectingException: false, + expectedResult: "\\x00\\x01\\x02" + }, + { + title: "MixedPrintableNonPrintable", + input: "\x00Hello123\x01", + isExpectingException: false, + expectedResult: "\\x00Hello123\\x01" + }, + { + title: "NullCharacterAsHex", + input: "\x00", + isExpectingException: false, + expectedResult: "\\x00" + }, + { + title: "UnitSeparatorCharacterAsHex", + input: "\x1F", + isExpectingException: false, + expectedResult: "\\x1f" + }, + { + title: "DeleteCharacterAsHex", + input: "\x7F", + isExpectingException: false, + expectedResult: "\\x7f" + }, + { + title: "ExtendedAsciiEuroAsHex", + input: "\x80", + isExpectingException: false, + expectedResult: "\\x80" + }, + { + title: "ExtendedAsciiCapitalYumlAsHex", + input: "\x9F", + isExpectingException: false, + expectedResult: "\\x9f" + }, + { + title: "ExtendedAsciiYumlAsHex", + input: "\xFF", + isExpectingException: false, + expectedResult: "\\xff" + }, + { + title: "SpaceCharacterUnchanged", + input: " ", + isExpectingException: false, + expectedResult: " " + }, + { + title: "TabCharacterUnchanged", + input: "\t", + isExpectingException: false, + expectedResult: "\t" + }, + { + title: "LineFeedCharacterUnchanged", + input: "\x0A", + isExpectingException: false, + expectedResult: "\x0A" + }, + { + title: "CarriageReturnCharacterUnchanged", + input: "\x0D", + isExpectingException: false, + expectedResult: "\x0D" + }, + { + title: "UnicodeUnchanged", + input: "\u1F419", + isExpectingException: false, + expectedResult: "\u1F419" + } + ]; + + var param, i; + for (i = 0; i < params.length; i++) { + param = params[i]; + cases.push(param); + } + + return cases; + })() +).test("escapeUnprintableCharacters", function (params, assert) { + var result = undefined; + var exceptionThrown = false; + + try { + result = escapeUnprintableCharacters(params.input); + } catch (ex) { + exceptionThrown = true; + } + + assert.equal( + result, + params.expectedResult, + "As expected: " + String(params.expectedResult) + ); + assert.equal( + exceptionThrown, + params.isExpectingException, + "As expected: " + String(params.expectedException) + ); +}); + +QUnit.module("getQueryParameterByName"); +QUnit.cases( + (function () { + var cases = []; + + var params = [ + { + title: "WindowLocationFirstParameter", + inputName: "parameter1", + inputUrl: undefined, + windowLocation: { + href: "https://localhost/stream?parameter1=test¶meter2=value" + }, + expected: "test" + }, + { + title: "WindowLocationSecondParameter", + inputName: "parameter2", + inputUrl: undefined, + windowLocation: { + href: "https://localhost/stream?parameter1=test¶meter2=value" + }, + expected: "value" + }, + { + title: "UrlFirstParameter", + inputName: "parameter1", + inputUrl: "https://localhost/stream?parameter1=test¶meter2=value", + windowLocation: undefined, + expected: "test" + }, + { + title: "UrlSecondParameter", + inputName: "parameter2", + inputUrl: "https://localhost/stream?parameter1=test¶meter2=value", + windowLocation: undefined, + expected: "value" + }, + { + title: "ArrayParameter", + inputName: "array[0]", + inputUrl: "https://localhost/stream?array[0]=first&array[1]=second", + windowLocation: undefined, + expected: "first" + }, + { + title: "NoParameters", + inputName: "array[0]", + inputUrl: "https://localhost/stream", + windowLocation: undefined, + expected: null + }, + { + title: "UnknownParameter", + inputName: "unknown", + inputUrl: "https://localhost/stream?parameter=first", + windowLocation: undefined, + expected: null + }, + { + title: "EmptyParameter", + inputName: "parameter", + inputUrl: "https://localhost/stream?parameter=", + windowLocation: undefined, + expected: "" + }, + { + title: "EmptyParameterNoEqual", + inputName: "parameter", + inputUrl: "https://localhost/stream?parameter", + windowLocation: undefined, + expected: "" + }, + { + title: "PlusReplacedBySpace", + inputName: "Sentence", + inputUrl: "https://localhost/stream?Sentence=Hello+World", + windowLocation: undefined, + expected: "Hello World" + } + ]; + + var param, i; + for (i = 0; i < params.length; i++) { + param = params[i]; + cases.push(param); + } + + return cases; + })() +).test("getQueryParameterByName", function (params, assert) { + if (params.windowLocation) { + fetchWindowLocation = function () { + return params.windowLocation; + }; + } + + var result = getQueryParameterByName(params.inputName, params.inputUrl); + assert.equal(result, params.expected, "As expected: " + String(params.expected)); +}); + +QUnit.module("formatNumberK"); +QUnit.cases( + (function () { + var cases = []; + + var params = [ + { + title: "UndefinedNumber", + input: undefined, + expectedException: "[sprintf] expecting number but found undefined", + expectedResult: undefined + }, + { + title: "Text", + input: "text", + expectedException: "[sprintf] expecting number but found string", + expectedResult: undefined + }, + { + title: "Zero", + input: 0, + expectedException: undefined, + expectedResult: "0" + }, + { + title: "Thousand", + input: 1000, + expectedException: undefined, + expectedResult: "1000" + }, + { + title: "ThousandOne", + input: 1001, + expectedException: undefined, + expectedResult: "1.00k" + }, + { + title: "ThousandTen", + input: 1010, + expectedException: undefined, + expectedResult: "1.01k" + }, + { + title: "Decimal", + input: 0.1, + expectedException: undefined, + expectedResult: "0" + }, + { + title: "Negative", + input: -1, + expectedException: undefined, + expectedResult: "-1" + }, + { + title: "NegativeThousandOne", + input: -1001, + expectedException: undefined, + expectedResult: "-1001" + } + ]; + + var param, i; + for (i = 0; i < params.length; i++) { + param = params[i]; + cases.push(param); + } + + return cases; + })() +).test("formatNumberK", function (params, assert) { + var result = undefined; + var exceptionMessage = undefined; + + try { + result = formatNumberK(params.input); + } catch (ex) { + exceptionMessage = ex.message; + } + + assert.equal( + result, + params.expectedResult, + "As expected: " + String(params.expectedResult) + ); + assert.equal( + exceptionMessage, + params.expectedException, + "As expected: " + String(params.expectedException) + ); +}); + +QUnit.module("formatHuman"); +QUnit.cases( + (function () { + var cases = []; + + var params = [ + { + title: "UndefinedNumber", + input: undefined, + expected: "-" + }, + { + title: "Text", + input: "text", + expected: "-NaNK" + }, + { + title: "Zero", + input: 0, + expected: "0" + }, + { + title: "Thousand", + input: 1000, + expected: "1.0K" + }, + { + title: "ThousandOne", + input: 1001, + expected: "1.0K" + }, + { + title: "ThousandTen", + input: 1100, + expected: "1.1K" + }, + { + title: "Decimal", + input: 0.1, + expected: "0.1" + }, + { + title: "Negative", + input: -1, + expected: "-1" + }, + { + title: "NegativeThousandOne", + input: -1001, + expected: "-1001" + } + ]; + + var param, i; + for (i = 0; i < params.length; i++) { + param = params[i]; + cases.push(param); + } + + return cases; + })() +).test("formatHuman", function (params, assert) { + var result = formatHuman(params.input); + assert.equal(result, params.expected, "As expected: " + String(params.expected)); +}); + +QUnit.module("cleanTemperature"); +QUnit.cases( + (function () { + var cases = []; + + var params = [ + { + title: "UndefinedNumber", + temp: undefined, + offThreshold: undefined, + expected: "-" + }, + { + title: "EmptyNumber", + temp: "", + offThreshold: undefined, + expected: "-" + }, + { + title: "Text", + temp: "A", + offThreshold: undefined, + expected: "-" + }, + { + title: "One", + temp: 1, + offThreshold: undefined, + expected: "1" + }, + { + title: "Zero", + temp: 0, + offThreshold: undefined, + expected: "0" + }, + { + title: "BelowThreshold", + temp: 0, + offThreshold: 1, + expected: "off" + }, + { + title: "AboveThreshold", + temp: 1, + offThreshold: 0, + expected: "1" + } + ]; + + var param, i; + for (i = 0; i < params.length; i++) { + param = params[i]; + cases.push(param); + } + + return cases; + })() +).test("cleanTemperature", function (params, assert) { + var result = cleanTemperature(params.temp, params.offThreshold); + assert.equal(result, params.expected, "As expected: " + String(params.expected)); +}); + +QUnit.module("formatFilament"); +QUnit.cases( + (function () { + var cases = []; + + var params = [ + { + title: "UndefinedFilament", + filament: undefined, + expected: "-" + }, + { + title: "UndefinedLength", + filament: {length: undefined}, + expected: "-" + }, + { + title: "PositiveFilamentNoVolume", + filament: {length: 1}, + expected: "0.00m" + }, + { + title: "PositiveFilamentDecimal", + filament: {length: 10}, + expected: "0.01m" + }, + { + title: "OneMeterFilament", + filament: {length: 1000}, + expected: "1.00m" + }, + { + title: "PositiveFilamentUndefinedVolume", + filament: {length: 1, volume: undefined}, + expected: "0.00m" + }, + { + title: "PositiveFilamentWithVolume", + filament: {length: 1, volume: 1}, + expected: "0.00m / 1.00cm\u00B3" + } + ]; + + var param, i; + for (i = 0; i < params.length; i++) { + param = params[i]; + cases.push(param); + } + + return cases; + })() +).test("formatFilament", function (params, assert) { + var result = formatFilament(params.filament); + assert.equal(result, params.expected, "As expected: " + String(params.expected)); +}); + +QUnit.module("formatTimeAgo"); +QUnit.cases( + (function () { + var cases = []; + + var params = [ + { + title: "UndefinedTimestamp", + unixTimestamp: undefined, + expected: "-" + }, + { + title: "ZeroTimestamp", + unixTimestamp: 0, + expected: "-" + }, + { + title: "RecentTimestamp", + unixTimestamp: moment().unix() - 1, + expected: "a few seconds ago" + } + ]; + + var param, i; + for (i = 0; i < params.length; i++) { + param = params[i]; + cases.push(param); + } + + return cases; + })() +).test("formatTimeAgo", function (params, assert) { + var result = formatTimeAgo(params.unixTimestamp); + assert.equal(result, params.expected, "As expected: " + String(params.expected)); +}); + +QUnit.module("splitTextToArray"); +QUnit.cases( + (function () { + var cases = []; + + var params = [ + { + title: "EmptyText", + input: "", + sep: undefined, + stripEmpty: false, + filter: undefined, + expected: [""] + }, + { + title: "EmptyTextStripEmpty", + input: "", + sep: undefined, + stripEmpty: true, + filter: undefined, + expected: [] + }, + { + title: "Text", + input: "text", + sep: undefined, + stripEmpty: false, + filter: undefined, + expected: ["text"] + }, + { + title: "TextSeparator", + input: "te#xt", + sep: "#", + stripEmpty: false, + filter: undefined, + expected: ["te", "xt"] + }, + { + title: "TrimmedText", + input: "te # xt", + sep: "#", + stripEmpty: false, + filter: undefined, + expected: ["te", "xt"] + } + ]; + + var param, i; + for (i = 0; i < params.length; i++) { + param = params[i]; + cases.push(param); + } + + return cases; + })() +).test("splitTextToArray", function (params, assert) { + var result = splitTextToArray( + params.input, + params.sep, + params.stripEmpty, + params.filter + ); + assert.equal( + JSON.stringify(result), + JSON.stringify(params.expected), + "As expected: " + String(params.expected) + ); +}); + +QUnit.module("formatDate"); +QUnit.cases( + (function () { + var cases = []; + + var params = [ + { + title: "UndefinedTimestamp", + unixTimestamp: undefined, + options: undefined, + expected: "-" + }, + { + title: "Millennium", + unixTimestamp: 946684800, + options: undefined, + expected: moment.unix(946684800).format("YYYY-MM-DD HH:mm") + }, + { + title: "ExplicitNoSeconds", + unixTimestamp: 10, + options: {seconds: false}, + expected: moment.unix(10).format("YYYY-MM-DD HH:mm") + }, + { + title: "WithSeconds", + unixTimestamp: 10, + options: {seconds: true}, + expected: moment.unix(10).format("YYYY-MM-DD HH:mm:ss") + } + ]; + + var param, i; + for (i = 0; i < params.length; i++) { + param = params[i]; + cases.push(param); + } + + return cases; + })() +).test("formatDate", function (params, assert) { + var result = formatDate(params.unixTimestamp, params.options); + assert.equal(result, params.expected, "As expected: " + String(params.expected)); }); From 8a8c0b16a2191950c2c78ba2e1e3933f0bfcae4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 9 Jun 2022 12:43:22 +0200 Subject: [PATCH 10/12] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Migrate=20default=20?= =?UTF-8?q?settings=20to=20pydantic=20model?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Currently using pydantic-settings for with_attrs_docs decorator to retrieve doc strings as descriptions. Should be replaced with vendored utility. --- setup.py | 2 + src/octoprint/schema/__init__.py | 2 + src/octoprint/schema/config/__init__.py | 54 +++ src/octoprint/schema/config/access_control.py | 52 +++ src/octoprint/schema/config/api.py | 18 + src/octoprint/schema/config/appearance.py | 164 ++++++++ src/octoprint/schema/config/controls.py | 86 ++++ src/octoprint/schema/config/devel.py | 55 +++ src/octoprint/schema/config/estimation.py | 29 ++ src/octoprint/schema/config/events.py | 40 ++ src/octoprint/schema/config/feature.py | 45 ++ src/octoprint/schema/config/folder.py | 49 +++ src/octoprint/schema/config/gcode_analysis.py | 34 ++ src/octoprint/schema/config/plugins.py | 19 + .../schema/config/printer_parameters.py | 12 + .../schema/config/printer_profiles.py | 13 + src/octoprint/schema/config/scripts.py | 31 ++ src/octoprint/schema/config/serial.py | 238 +++++++++++ src/octoprint/schema/config/server.py | 206 +++++++++ src/octoprint/schema/config/slicing.py | 19 + src/octoprint/schema/config/system.py | 31 ++ src/octoprint/schema/config/temperature.py | 37 ++ .../schema/config/terminalfilters.py | 35 ++ src/octoprint/schema/config/webcam.py | 107 +++++ .../{settings.py => settings/__init__.py} | 391 +----------------- 25 files changed, 1382 insertions(+), 387 deletions(-) create mode 100644 src/octoprint/schema/__init__.py create mode 100644 src/octoprint/schema/config/__init__.py create mode 100644 src/octoprint/schema/config/access_control.py create mode 100644 src/octoprint/schema/config/api.py create mode 100644 src/octoprint/schema/config/appearance.py create mode 100644 src/octoprint/schema/config/controls.py create mode 100644 src/octoprint/schema/config/devel.py create mode 100644 src/octoprint/schema/config/estimation.py create mode 100644 src/octoprint/schema/config/events.py create mode 100644 src/octoprint/schema/config/feature.py create mode 100644 src/octoprint/schema/config/folder.py create mode 100644 src/octoprint/schema/config/gcode_analysis.py create mode 100644 src/octoprint/schema/config/plugins.py create mode 100644 src/octoprint/schema/config/printer_parameters.py create mode 100644 src/octoprint/schema/config/printer_profiles.py create mode 100644 src/octoprint/schema/config/scripts.py create mode 100644 src/octoprint/schema/config/serial.py create mode 100644 src/octoprint/schema/config/server.py create mode 100644 src/octoprint/schema/config/slicing.py create mode 100644 src/octoprint/schema/config/system.py create mode 100644 src/octoprint/schema/config/temperature.py create mode 100644 src/octoprint/schema/config/terminalfilters.py create mode 100644 src/octoprint/schema/config/webcam.py rename src/octoprint/{settings.py => settings/__init__.py} (83%) diff --git a/setup.py b/setup.py index 57106dee6..c69a81724 100644 --- a/setup.py +++ b/setup.py @@ -66,6 +66,8 @@ core_deps = [ "wrapt>=1.14,<1.15", "zeroconf>=0.33,<0.34", # breaking changes can happen on minor version increases "zipstream-ng>=1.3.4,<2.0.0", + "pydantic>=1.9.1,<2", + "pydantic-settings>0.25,<1", # TODO: replace with vendored with_attrs_docs ] vendored_deps = [ "blinker>=1.4,<2", # dependency of flask_principal diff --git a/src/octoprint/schema/__init__.py b/src/octoprint/schema/__init__.py new file mode 100644 index 000000000..3103d3cb6 --- /dev/null +++ b/src/octoprint/schema/__init__.py @@ -0,0 +1,2 @@ +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" diff --git a/src/octoprint/schema/config/__init__.py b/src/octoprint/schema/config/__init__.py new file mode 100644 index 000000000..2bcc7ca2c --- /dev/null +++ b/src/octoprint/schema/config/__init__.py @@ -0,0 +1,54 @@ +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" + +from typing import List, Union + +from pydantic import BaseModel +from pydantic_settings import with_attrs_docs + +from .access_control import AccessControlConfig +from .api import ApiConfig +from .appearance import AppearanceConfig +from .controls import ContainerConfig, ControlConfig +from .devel import DevelConfig +from .estimation import EstimationConfig +from .events import EventsConfig +from .feature import FeatureConfig +from .folder import FolderConfig +from .gcode_analysis import GcodeAnalysisConfig +from .plugins import PluginsConfig +from .printer_parameters import PrinterParametersConfig +from .printer_profiles import PrinterProfilesConfig +from .scripts import ScriptsConfig +from .serial import SerialConfig +from .server import ServerConfig +from .slicing import SlicingConfig +from .system import SystemConfig +from .temperature import TemperatureConfig +from .terminalfilters import DEFAULT_TERMINAL_FILTERS, TerminalFilterEntry +from .webcam import WebcamConfig + + +@with_attrs_docs +class Config(BaseModel): + accessControl: AccessControlConfig = AccessControlConfig() + api: ApiConfig = ApiConfig() + appearance: AppearanceConfig = AppearanceConfig() + controls: List[Union[ControlConfig, ContainerConfig]] = [] + devel: DevelConfig = DevelConfig() + estimation: EstimationConfig = EstimationConfig() + events: EventsConfig = EventsConfig() + feature: FeatureConfig = FeatureConfig() + folder: FolderConfig = FolderConfig() + gcodeAnalysis: GcodeAnalysisConfig = GcodeAnalysisConfig() + plugins: PluginsConfig = PluginsConfig() + printerParameters: PrinterParametersConfig = PrinterParametersConfig() + printerProfiles: PrinterProfilesConfig = PrinterProfilesConfig() + scripts: ScriptsConfig = ScriptsConfig() + serial: SerialConfig = SerialConfig() + server: ServerConfig = ServerConfig() + slicing: SlicingConfig = SlicingConfig() + system: SystemConfig = SystemConfig() + temperature: TemperatureConfig = TemperatureConfig() + terminalFilters: List[TerminalFilterEntry] = DEFAULT_TERMINAL_FILTERS + webcam: WebcamConfig = WebcamConfig() diff --git a/src/octoprint/schema/config/access_control.py b/src/octoprint/schema/config/access_control.py new file mode 100644 index 000000000..5546bc020 --- /dev/null +++ b/src/octoprint/schema/config/access_control.py @@ -0,0 +1,52 @@ +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" + +from typing import List, Optional + +from pydantic import BaseModel +from pydantic_settings import with_attrs_docs + + +@with_attrs_docs +class AccessControlConfig(BaseModel): + salt: Optional[str] = None + """Secret salt used for password hashing. **DO NOT TOUCH!** If changed you will no longer be able to log in with your existing accounts. Default unset, generated on first run.""" + + userManager: str = "octoprint.access.users.FilebasedUserManager" + """The user manager implementation to use for accessing user information. Currently only a filebased user manager is implemented which stores configured accounts in a YAML file (Default: `users.yaml` in the default configuration folder).""" + + groupManager: str = "octoprint.access.groups.FilebasedGroupManager" + """The group manager implementation to use for accessing group information. Currently only a filebased user manager is implemented which stores configured groups in a YAML file (Default: `groups.yaml` in the default configuration folder).""" + + permissionManager: str = "octoprint.access.permissions.PermissionManager" + """The permission manager implementation to use.""" + + userfile: Optional[str] = None + """The YAML user file to use. If left out defaults to `users.yaml` in the default configuration folder.""" + + groupfile: Optional[str] = None + """The YAML group file to use. If left out defaults to `groups.yaml` in the default configuration folder.""" + + autologinLocal: bool = False + """If set to true, will automatically log on clients originating from any of the networks defined in `localNetworks` as the user defined in `autologinAs`.""" + + localNetworks: List[str] = ["127.0.0.0/8", "::1/128"] + """A list of networks or IPs for which an automatic logon as the user defined in `autologinAs` will take place. If available OctoPrint will evaluate the `X-Forwarded-For` HTTP header for determining the client's IP address. Defaults to anything originating from localhost.""" + + autologinAs: Optional[str] = None + """The name of the user to automatically log on clients originating from `localNetworks` as. Must be the name of one of your configured users.""" + + trustBasicAuthentication: bool = False + """Whether to trust Basic Authentication headers. If you have setup Basic Authentication in front of OctoPrint and the user names you use there match OctoPrint accounts, by setting this to true users will be logged into OctoPrint as the user user during Basic Authentication. **ONLY ENABLE THIS** if your OctoPrint instance is only accessible through a connection locked down through Basic Authentication!""" + + checkBasicAuthenticationPassword: bool = True + """Whether to also check the password provided through Basic Authentication, if the Basic Authentication header is to be trusted. Disabling this will only match the user name in the Basic Authentication header and login the user without further checks, thus disable with caution.""" + + trustRemoteUser: bool = False + """Whether to trust remote user headers. If you have setup authentication in front of OctoPrint and the user names you use there match OctoPrint accounts, by setting this to true users will be logged into OctoPrint as the user provided in the header. **ONLY ENABLE THIS** if your OctoPrint instance is only accessible through a connection locked down through an authenticating reverse proxy!""" + + remoteUserHeader: str = "REMOTE_USER" + """Header used by the reverse proxy to convey the authenticated user.""" + + addRemoteUsers: bool = False + """If a remote user is not found, add them. Use this only if all users from the remote system can use OctoPrint.""" diff --git a/src/octoprint/schema/config/api.py b/src/octoprint/schema/config/api.py new file mode 100644 index 000000000..cd0b1ae86 --- /dev/null +++ b/src/octoprint/schema/config/api.py @@ -0,0 +1,18 @@ +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" + +from typing import Dict + +from pydantic import BaseModel +from pydantic_settings import with_attrs_docs + + +@with_attrs_docs +class ApiConfig(BaseModel): + key: str = None + """Global API key, deprecated, use User API keys instead. Unset by default, will be generated on first run.""" + + apps: Dict[str, str] = {} + + allowCrossOrigin: bool = False + """Whether to allow cross origin access to the API or not.""" diff --git a/src/octoprint/schema/config/appearance.py b/src/octoprint/schema/config/appearance.py new file mode 100644 index 000000000..234052422 --- /dev/null +++ b/src/octoprint/schema/config/appearance.py @@ -0,0 +1,164 @@ +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" + +from enum import Enum +from typing import List + +from pydantic import BaseModel +from pydantic_settings import with_attrs_docs + + +class ColorEnum(str, Enum): + red = "red" + orange = "orange" + yellow = "yellow" + green = "green" + blue = "blue" + violet = "violet" + default = "default" + + +@with_attrs_docs +class ComponentOrderConfig(BaseModel): + navbar: List[str] = [ + "settings", + "systemmenu", + "plugin_announcements", + "plugin_logging_seriallog", + "plugin_logging_plugintimingslog", + "plugin_pi_support", + "login", + ] + """Order of navbar items.""" + + sidebar: List[str] = [ + "plugin_firmware_check_warning", + "plugin_firmware_check_info", + "connection", + "state", + "files", + ] + """Order of sidebar items.""" + + tab: List[str] = [ + "temperature", + "control", + "plugin_gcodeviewer", + "terminal", + "timelapse", + ] + """Order of tabs.""" + + settings: List[str] = [ + "section_printer", + "serial", + "printerprofiles", + "temperatures", + "terminalfilters", + "gcodescripts", + "section_features", + "features", + "webcam", + "accesscontrol", + "plugin_gcodeviewer", + "api", + "plugin_appkeys", + "section_octoprint", + "server", + "folders", + "appearance", + "plugin_logging", + "plugin_pluginmanager", + "plugin_softwareupdate", + "plugin_announcements", + "plugin_eventmanager", + "plugin_backup", + "plugin_tracking", + "plugin_errortracking", + "plugin_pi_support", + ] + """Order of settings.""" + + usersettings: List[str] = ["access", "interface"] + """Order of user settings.""" + + wizard: List[str] = [ + "plugin_softwareupdate_update", + "plugin_backup", + "plugin_corewizard_acl", + "plugin_corewizard_onlinecheck", + ] + """Order of wizards.""" + + about: List[str] = [ + "about", + "plugin_pi_support", + "supporters", + "authors", + "changelog", + "license", + "thirdparty", + "plugin_pluginmanager", + ] + """Order of about dialog items.""" + + generic: List[str] = [] + """Order of generic items.""" + + +@with_attrs_docs +class ComponentDisabledConfig(BaseModel): + navbar: List[str] = [] + """Disabled navbar items.""" + sidebar: List[str] = [] + """Disabled sidebar items.""" + tab: List[str] = [] + """Disabled tabs.""" + settings: List[str] = [] + """Disabled settings.""" + usersettings: List[str] = [] + """Disabled user settings.""" + wizard: List[str] = [] + """Disabled wizards.""" + about: List[str] = [] + """Disabled about dialog items.""" + generic: List[str] = [] + """Disabled generic items.""" + + +@with_attrs_docs +class ComponentConfig(BaseModel): + order: ComponentOrderConfig = ComponentOrderConfig() + """Defines the order of the components within their respective containers.""" + + disabled: ComponentDisabledConfig = ComponentDisabledConfig() + """Disabled components per container. If a component is included here it will not be included in OctoPrint's UI at all. Note that this might mean that critical functionality will not be available if no replacement is registered.""" + + +@with_attrs_docs +class AppearanceConfig(BaseModel): + name: str = "" + """Use this to give your OctoPrint instance a name. It will be displayed in the title bar (as " [OctoPrint]") and in the navigation bar (as "OctoPrint: <>")""" + + color: ColorEnum = "default" + """Use this to color the navigation bar.""" + + colorTransparent: bool = False + """Makes the color of the navigation bar "transparent". In case your printer uses acrylic for its frame ๐Ÿ˜‰.""" + + colorIcon: bool = True + + defaultLanguage: str = "_default" + """Default language of OctoPrint. If left unset OctoPrint will try to match up available languages with the user's browser settings.""" + + showFahrenheitAlso: bool = False + + fuzzyTimes: bool = True + + closeModalsWithClick: bool = True + + showInternalFilename: bool = True + """Show the internal filename in the files sidebar, if necessary.""" + + components: ComponentConfig = ComponentConfig() + """Configures the order and availability of the UI components.""" diff --git a/src/octoprint/schema/config/controls.py b/src/octoprint/schema/config/controls.py new file mode 100644 index 000000000..13dcf9649 --- /dev/null +++ b/src/octoprint/schema/config/controls.py @@ -0,0 +1,86 @@ +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" + +from enum import Enum +from typing import List, Optional, Union + +from pydantic import BaseModel +from pydantic_settings import with_attrs_docs + + +class LayoutEnum(str, Enum): + horizontal = "horizontal" + vertical = "vertical" + + +class ControlSliderInputConfig(BaseModel): + min: int = 0 + """Minimum value of the slider.""" + + max: int = 255 + """Maximum value of the slider.""" + + step: int = 1 + """Step size per slider tick.""" + + +class ControlInputConfig(BaseModel): + name: str + """Name to display for the input field.""" + + parameter: str + """Internal parameter name for the input field, used as a placeholder in `command`/`commands`.""" + + default: Union[str, int, float, bool] + """Default value for the input field.""" + + slider: Optional[ControlSliderInputConfig] = None + """If this attribute is included, instead of an input field a slider control will be rendered.""" + + +@with_attrs_docs +class ContainerConfig(BaseModel): + children: "List[Union[ContainerConfig, ControlConfig]]" = [] + """A list of children controls or containers contained within this container.""" + + name: Optional[str] = None + """A name to display above the container, basically a section header.""" + + layout: LayoutEnum = "vertical" + """The layout to use for laying out the contained children, either from top to bottom (`vertical`) or from left to right (`horizontal`).""" + + +@with_attrs_docs +class ControlConfig(BaseModel): + name: str + """The name of the control, will be displayed either on the button if it's a control sending a command or as a label for controls which only display output.""" + + command: Optional[str] = None + """A single GCODE command to send to the printer. Will be rendered as a button which sends the command to the printer upon click. The button text will be the value of the `name` attribute. Mutually exclusive with `commands` and `script`. The rendered button be disabled if the printer is currently offline or printing or alternatively if the requirements defined via the `enabled` attribute are not met.""" + + commands: Optional[List[str]] = None + """A list of GCODE commands to send to the printer. Will be rendered as a button which sends the commands to the printer upon click. The button text will be the value of the `name` attribute. Mutually exclusive with `command` and `script`. The rendered button will be disabled if the printer is currently offline or printing or alternatively if the requirements defined via the `enabled` attribute are not met.""" + + script: Optional[str] = None + """The name of a full blown [GCODE script]() to send to the printer. Will be rendered as a button which sends the script to the printer upon click. The button text will be the value of the `name` attribute. Mutually exclusive with `command` and `commands`. The rendered button will be disabled if the printer is currently offline or printing or alternatively if the requirements defined via the `enabled` attribute are not met. Values of input parameters will be available in the template context under the `parameter` variable (e.g. an input parameter `speed` will be available in the script template as `parameter.speed`). On top of that all other variables defined in the [GCODE template context]() will be available.""" + + javascript: Optional[str] = None + """A JavaScript snippet to be executed when the button rendered for `command` or `commands` is clicked. This allows to override the direct sending of the command or commands to the printer with more sophisticated behaviour. The JavaScript snippet is `eval`'d and processed in a context where the control it is part of is provided as local variable `data` and the `ControlViewModel` is available as `self`.""" + + additionalClasses: Optional[str] = None + """Additional classes to apply to the button of a `command`, `commands`, `script` or `javascript` control, other than the default `btn`. Can be used to visually style the button, e.g. set to `btn-danger` to turn the button red.""" + + enabled: Optional[str] = None + """A JavaScript snippet returning either `true` or `false` determining whether the control should be enabled or not. This allows to override the default logic for the enable state of the control (disabled if printer is offline). The JavaScript snippet is `eval`'d and processed in a context where the control it is part of is provided as local variable `data` and the `ControlViewModel` is available as `self`.""" + + input: Optional[List[ControlInputConfig]] = [] + """A list of definitions of input parameters for a `command` or `commands`, to be rendered as additional input fields. `command`/`commands` may contain placeholders to be replaced by the values obtained from the user for the defined input fields.""" + + regex: Optional[str] = None + """A [regular expression ](https://docs.python.org/3/library/re.html#regular-expression-syntax) to match against lines received from the printer to retrieve information from it (e.g. specific output). Together with `template` this allows rendition of received data from the printer within the UI.""" + + template: Optional[str] = None + r"""A template to use for rendering the match of `regex`. May contain placeholders in [Python Format String Syntax](https://docs.python.org/3/library/string.html#formatstrings) for either named groups within the regex (e.g. `Temperature: {temperature}` for a regex `T:\s*(?P\d+(\.\d*)`) or positional groups within the regex (e.g. `Position: X={0}, Y={1}, Z={2}, E={3}` for a regex `X:([0-9.]+) Y:([0-9.]+) Z:([0-9.]+) E:([0-9.]+)`).""" + + confirm: Optional[str] = None + """A text to display to the user to confirm his button press. Can be used with sensitive custom controls like changing EEPROM values in order to prevent accidental clicks. The text will be displayed in a confirmation dialog.""" diff --git a/src/octoprint/schema/config/devel.py b/src/octoprint/schema/config/devel.py new file mode 100644 index 000000000..c14f8ee9e --- /dev/null +++ b/src/octoprint/schema/config/devel.py @@ -0,0 +1,55 @@ +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" + +from enum import Enum + +from pydantic import BaseModel +from pydantic_settings import with_attrs_docs + + +class StylesheetEnum(str, Enum): + css = "css" + less = "less" + + +@with_attrs_docs +class DevelWebassetsConfig(BaseModel): + bundle: bool = True + """If set to true, OctoPrint will merge all JS, all CSS and all Less files into one file per type to reduce request count. Setting it to false will load all assets individually. Note: if this is set to false, no minification will take place regardless of the `minify` setting.""" + + clean_on_startup: bool = True + """Whether to delete generated web assets on server startup (forcing a regeneration).""" + + minify: bool = True + """If set to true, OctoPrint will the core and library javascript assets. Note: if `bundle` is set to false, no minification will take place either.""" + + minify_plugins: bool = False + """If set to true, OctoPrint will also minify the third party plugin javascript assets. Note: if `bundle` or `minify` are set to false, no minification of the plugin assets will take place either.""" + + +class DevelCacheConfig(BaseModel): + enabled: bool = True + """Whether to enable caching. Defaults to true. Setting it to false will cause the UI to alway be fully rerendered on request to `/` on the server.""" + + preemptive: bool = True + """Whether to enable the preemptive cache.""" + + +@with_attrs_docs +class DevelConfig(BaseModel): + stylesheet: StylesheetEnum = "css" + """Settings for stylesheet preference. OctoPrint will prefer to use the stylesheet type specified here. Usually (on a production install) that will be the compiled css (default). Developers may specify less here too.""" + + cache: DevelCacheConfig = DevelCacheConfig() + """Settings for OctoPrint's internal caching.""" + + webassets: DevelWebassetsConfig = DevelWebassetsConfig() + """Settings for OctoPrint's web asset merging and minifying.""" + + useFrozenDictForPrinterState: bool = True + + showLoadingAnimation: bool = True + """Enable or disable the loading animation.""" + + sockJsConnectTimeout: float = 30 + pluginTimings: bool = False diff --git a/src/octoprint/schema/config/estimation.py b/src/octoprint/schema/config/estimation.py new file mode 100644 index 000000000..147602215 --- /dev/null +++ b/src/octoprint/schema/config/estimation.py @@ -0,0 +1,29 @@ +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" + +from pydantic import BaseModel +from pydantic_settings import with_attrs_docs + + +@with_attrs_docs +class PrintTimeEstimationConfig(BaseModel): + statsWeighingUntil: float = 0.5 + """Until which percentage to do a weighted mixture of statistical duration (analysis or past prints) with the result from the calculated estimate if that's already available. Utilized to compensate for the fact that the earlier in a print job, the least accuracy even a stable calculated estimate provides.""" + + validityRange: float = 0.15 + """Range the assumed percentage (based on current estimated statistical, calculated or mixed total vs elapsed print time so far) needs to be around the actual percentage for the result to be used.""" + + forceDumbFromPercent: float = 0.3 + """If no estimate could be calculated until this percentage and no statistical data is available, use dumb linear estimate. Value between 0 and 1.0.""" + + forceDumbAfterMin: float = 30.0 + """If no estimate could be calculated until this many minutes into the print and no statistical data is available, use dumb linear estimate.""" + + stableThreshold: int = 60 + """Average fluctuation between individual calculated estimates to consider in stable range. Seconds of difference.""" + + +@with_attrs_docs +class EstimationConfig(BaseModel): + printTime: PrintTimeEstimationConfig = PrintTimeEstimationConfig() + """Parameters for the print time estimation during an ongoing print job.""" diff --git a/src/octoprint/schema/config/events.py b/src/octoprint/schema/config/events.py new file mode 100644 index 000000000..54455ced1 --- /dev/null +++ b/src/octoprint/schema/config/events.py @@ -0,0 +1,40 @@ +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" + +from enum import Enum +from typing import List + +from pydantic import BaseModel +from pydantic_settings import with_attrs_docs + + +class SubscriptionTypeEnum(str, Enum): + system = "system" + gcode = "gcode" + + +@with_attrs_docs +class EventSubscription(BaseModel): + event: str + """The event to subscribe to.""" + + command: str + """The command to execute when the event is triggered, either a GCODE or a system command.""" + + type: SubscriptionTypeEnum + """The type of the command.""" + + enabled: bool = True + """Whether the event subscription should be enabled.""" + + debug: bool = False + """If set to `true`, OctoPrint will log the command after performing all placeholder replacements.""" + + +@with_attrs_docs +class EventsConfig(BaseModel): + enabled: bool = True + """Whether event subscriptions should be enabled or not.""" + + subscriptions: List[EventSubscription] = [] + """A list of event subscriptions.""" diff --git a/src/octoprint/schema/config/feature.py b/src/octoprint/schema/config/feature.py new file mode 100644 index 000000000..88f07111d --- /dev/null +++ b/src/octoprint/schema/config/feature.py @@ -0,0 +1,45 @@ +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" + +from typing import List + +from pydantic import BaseModel +from pydantic_settings import with_attrs_docs + + +@with_attrs_docs +class FeatureConfig(BaseModel): + temperatureGraph: bool = True + """Whether to enable the temperature graph in the UI or not.""" + + sdSupport: bool = True + """Specifies whether support for SD printing and file management should be enabled.""" + + keyboardControl: bool = True + """Whether to enable the keyboard control feature in the control tab.""" + + pollWatched: bool = False + """Whether to actively poll the watched folder (true) or to rely on the OS's file system notifications instead (false).""" + + modelSizeDetection: bool = True + """Whether to enable model size detection and warning (true) or not (false).""" + + rememberFileFolder: bool = False + """Whether to remember the selected folder on the file manager.""" + + printStartConfirmation: bool = False + """Whether to show a confirmation on print start (true) or not (false)""" + + printCancelConfirmation: bool = True + """Whether to show a confirmation on print cancelling (true) or not (false)""" + + uploadOverwriteConfirmation: bool = True + + autoUppercaseBlacklist: List[str] = ["M117", "M118"] + """Commands that should never be auto-uppercased when sent to the printer through the Terminal tab.""" + + g90InfluencesExtruder: bool = False + """Whether `G90`/`G91` also influence absolute/relative mode of extruders.""" + + enforceReallyUniversalFilenames: bool = False + """Replace all special characters and spaces with text equivalent to make them universally compatible. Most OS filesystems work fine with unicode characters, but just in case you can revert to the older behaviour by setting this to true.""" diff --git a/src/octoprint/schema/config/folder.py b/src/octoprint/schema/config/folder.py new file mode 100644 index 000000000..fdaa22a2d --- /dev/null +++ b/src/octoprint/schema/config/folder.py @@ -0,0 +1,49 @@ +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" + +from typing import Optional + +from pydantic import BaseModel +from pydantic_settings import with_attrs_docs + + +@with_attrs_docs +class FolderConfig(BaseModel): + uploads: Optional[str] = None + """Absolute path where to store gcode uploads. Defaults to the `uploads` folder in OctoPrint's base folder.""" + + timelapse: Optional[str] = None + """Absolute path where to store finished timelase recordings. Defaults to the `timelapse` folder in OctoPrint's base folder.""" + + timelapse_tmp: Optional[str] = None + """Absolute path where to store temporary timelapse snapshots. Defaults to the `timelapse/tmp` folder in OctoPrint's base folder.""" + + logs: Optional[str] = None + """Absolute path where to store logs. Defaults to the `logs` folder in OctoPrint's base folder.""" + + virtualSd: Optional[str] = None + """Absolute path where to store the virtual printer's SD card files. Defaults to the `virtualSd` folder in OctoPrint's base folder.""" + + watched: Optional[str] = None + """Absolute path to the watched folder. Defaults to the `watched` folder in OctoPrint's base folder.""" + + plugins: Optional[str] = None + """Absolute path where to locate and install single file plugins. Defaults to the `plugins` folder in OctoPrint's base folder.""" + + slicingProfiles: Optional[str] = None + """Absolute path where to store slicing profiles. Defaults to the `slicingProfiles` folder in OctoPrint's base folder.""" + + printerProfiles: Optional[str] = None + """Absolute path where to store printer profiles. Defaults to the `printerProfiles` folder in OctoPrint's base folder.""" + + scripts: Optional[str] = None + """Absolute path where to store (GCODE) scripts. Defaults to the `scripts` folder in OctoPrint's base folder.""" + + translations: Optional[str] = None + """Absolute path where to store additional translations. Defaults to the `translations` folder in OctoPrint's base folder.""" + + generated: Optional[str] = None + """Absolute path where to store generated files. Defaults to the `generated` folder in OctoPrint's base folder.""" + + data: Optional[str] = None + """Absolute path where to store additional data. Defaults to the `data` folder in OctoPrint's base folder.""" diff --git a/src/octoprint/schema/config/gcode_analysis.py b/src/octoprint/schema/config/gcode_analysis.py new file mode 100644 index 000000000..2d66865f4 --- /dev/null +++ b/src/octoprint/schema/config/gcode_analysis.py @@ -0,0 +1,34 @@ +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" + +from enum import Enum + +from pydantic import BaseModel +from pydantic_settings import with_attrs_docs + + +class RunAtEnum(str, Enum): + never: str = "never" + idle: str = "idle" + always: str = "always" + + +@with_attrs_docs +class GcodeAnalysisConfig(BaseModel): + maxExtruders: int = 10 + """Maximum number of extruders to support/to sanity check for.""" + + throttle_normalprio: float = 0.01 + """Pause between each processed GCODE line batch in normal priority mode, seconds.""" + + throttle_highprio: float = 0.0 + """Pause between each processed GCODE line batch in high priority mode (e.g. on fresh uploads), seconds.""" + + throttle_lines: int = 100 + """GCODE line batch size.""" + + runAt: RunAtEnum = "idle" + """Whether to run the analysis only when idle (not printing), regardless of printing state or never.""" + + bedZ: float = 0.0 + """Z position considered the location of the bed.""" diff --git a/src/octoprint/schema/config/plugins.py b/src/octoprint/schema/config/plugins.py new file mode 100644 index 000000000..f9abd68c0 --- /dev/null +++ b/src/octoprint/schema/config/plugins.py @@ -0,0 +1,19 @@ +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" + +from typing import Dict, List + +from pydantic import BaseModel, Field +from pydantic_settings import with_attrs_docs + + +@with_attrs_docs +class PluginsConfig(BaseModel): + disabled: List[str] = Field([], alias="_disabled") + """Identifiers of installed but disabled plugins.""" + + forced_compatible: List[str] = Field([], alias="_forcedCompatible") + """Identifiers of plugins for which python compatibility information will be ignored and the plugin considered compatible in any case. Only for development, do **NOT** use in production.""" + + sorting_order: Dict[str, Dict[str, int]] = Field({}, alias="_sortingOrder") + """Custom sorting of hooks and implementations provided by plugins. Two-tiered dictionary structure, plugin identifier mapping to a dictionary of order overrides mapped by sorting context/hook name.""" diff --git a/src/octoprint/schema/config/printer_parameters.py b/src/octoprint/schema/config/printer_parameters.py new file mode 100644 index 000000000..9219b63d6 --- /dev/null +++ b/src/octoprint/schema/config/printer_parameters.py @@ -0,0 +1,12 @@ +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" + +from typing import List + +from pydantic import BaseModel +from pydantic_settings import with_attrs_docs + + +@with_attrs_docs +class PrinterParametersConfig(BaseModel): + pauseTriggers: List[str] = [] diff --git a/src/octoprint/schema/config/printer_profiles.py b/src/octoprint/schema/config/printer_profiles.py new file mode 100644 index 000000000..b1aa439d5 --- /dev/null +++ b/src/octoprint/schema/config/printer_profiles.py @@ -0,0 +1,13 @@ +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" + +from typing import Optional + +from pydantic import BaseModel +from pydantic_settings import with_attrs_docs + + +@with_attrs_docs +class PrinterProfilesConfig(BaseModel): + default: Optional[str] = None + """Name of the printer profile to default to.""" diff --git a/src/octoprint/schema/config/scripts.py b/src/octoprint/schema/config/scripts.py new file mode 100644 index 000000000..fbec21646 --- /dev/null +++ b/src/octoprint/schema/config/scripts.py @@ -0,0 +1,31 @@ +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" + +from typing import Dict, Optional + +from pydantic import BaseModel +from pydantic_settings import with_attrs_docs + + +@with_attrs_docs +class GcodeScriptsConfig(BaseModel): + afterPrinterConnected: Optional[str] = None + beforePrinterDisconnected: Optional[str] = None + beforePrintStarted: Optional[str] = None + afterPrintCancelled: Optional[ + str + ] = "; disable motors\nM84\n\n;disable all heaters\n{% snippet 'disable_hotends' %}\n{% snippet 'disable_bed' %}\n;disable fan\nM106 S0" + afterPrintDone: Optional[str] = None + beforePrintPaused: Optional[str] = None + afterPrintResumed: Optional[str] = None + beforeToolChange: Optional[str] = None + afterToolChange: Optional[str] = None + snippets: Dict[str, str] = { + "disable_hotends": "{% if printer_profile.extruder.sharedNozzle %}M104 T0 S0\n{% else %}{% for tool in range(printer_profile.extruder.count) %}M104 T{{ tool }} S0\n{% endfor %}{% endif %}", + "disable_bed": "{% if printer_profile.heatedBed %}M140 S0\n{% endif %}", + } + + +@with_attrs_docs +class ScriptsConfig(BaseModel): + gcode: GcodeScriptsConfig = GcodeScriptsConfig() diff --git a/src/octoprint/schema/config/serial.py b/src/octoprint/schema/config/serial.py new file mode 100644 index 000000000..e336dc0e4 --- /dev/null +++ b/src/octoprint/schema/config/serial.py @@ -0,0 +1,238 @@ +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" + +from enum import Enum +from typing import List, Optional + +from pydantic import BaseModel +from pydantic_settings import with_attrs_docs + + +class AlwaysDetectNeverEnum(str, Enum): + always = "always" + detect = "detect" + never = "never" + + +class InfoWarnNeverEnum(str, Enum): + info = "info" + warn = "warn" + never = "never" + + +@with_attrs_docs +class SerialTimeoutConfig(BaseModel): + detectionFirst: float = 10.0 + detectionConsecutive: float = 2.0 + + connection: float = 10.0 + """Timeout for waiting to establish a connection with the selected port, in seconds""" + + communication: float = 30.0 + """Timeout during serial communication, in seconds""" + + communicationBusy: float = 3.0 + """Timeout during serial communication when busy protocol support is detected, in seconds""" + + temperature: float = 5.0 + """Timeout after which to query temperature when no target is set""" + + temperatureTargetSet: float = 2.0 + """Timeout after which to query temperature when a target is set""" + + temperatureAutoreport: float = 2.0 + + sdStatus: float = 1.0 + """Timeout after which to query the SD status while SD printing""" + + sdStatusAutoreport: float = 1.0 + posAutoreport: float = 5.0 + resendOk: float = 0.5 + baudrateDetectionPause: float = 1.0 + positionLogWait: float = 10.0 + + +@with_attrs_docs +class SerialMaxTimeouts(BaseModel): + idle: int = 2 + """Max. timeouts when the printer is idle""" + + printing: int = 5 + """Max. timeouts when the printer is printing""" + + long: int = 5 + """Max. timeouts when a long running command is active""" + + +@with_attrs_docs +class SerialCapabilities(BaseModel): + autoreport_temp: bool = True + """Whether to enable temperature autoreport in the firmware if its support is detected""" + + autoreport_sdstatus: bool = True + autoreport_pos: bool = True + + busy_protocol: bool = True + """Whether to shorten the communication timeout if the firmware seems to support the busy protocol""" + + emergency_parser: bool = True + extended_m20: bool = True + + +@with_attrs_docs +class SerialConfig(BaseModel): + port: Optional[str] = None + """The default port to use to connect to the printer. If unset or set to `AUTO`, the port will be auto-detected.""" + + baudrate: Optional[int] = None + """The default baudrate to use to connect to the printer. If unset or set to 0, the baudrate will be auto-detected.""" + + exclusive: bool = True + """Whether to request the serial port exclusively or not""" + + lowLatency: bool = False + """Whether to request low latency mode on the serial port or not""" + + autoconnect: bool = False + """Whether to try to automatically connect to the printer on startup or not""" + + log: bool = False + """Whether to log whole communication to serial.log (warning: might decrease performance)""" + + timeout: SerialTimeoutConfig = SerialTimeoutConfig() + """Timeouts used for the serial connection to the printer, you might want to adjust these if you are experiencing connection problems""" + + maxCommunicationTimeouts: SerialMaxTimeouts = SerialMaxTimeouts() + + maxWritePasses: int = 5 + """Maximum number of write attempts to serial during which nothing can be written before the communication with the printer is considered dead and OctoPrint will disconnect with an error""" + + additionalPorts: List[str] = [] + """Use this to define additional patterns to consider for serial port listing. Must be a valid ["glob" pattern](http://docs.python.org/3/library/glob.html)""" + + additionalBaudrates: List[int] = [] + """Use this to define additional baud rates to offer for connecting to serial ports. Must be a valid integer""" + + blacklistedPorts: List[str] = [] + blacklistedBaudrates: List[int] = [] + + longRunningCommands: List[str] = [ + "G4", + "G28", + "G29", + "G30", + "G32", + "M400", + "M226", + "M600", + ] + """Commands which are known to take a long time to be acknowledged by the firmware, e.g. homing, dwelling, auto leveling etc.""" + + blockedCommands: List[str] = ["M0", "M1"] + """Commands which should not be sent to the printer, e.g. because they are known to block serial communication until physical interaction with the printer as is the case on most firmwares with the default M0 and M1.""" + + ignoredCommands: List[str] = [] + """Commands which should not be sent to the printer and just silently ignored. An example of when you may wish to use this could be useful if you wish to manually change a filament on M600, by using that as a Pausing command.""" + + pausingCommands: List[str] = ["M0", "M1", "M25"] + """Commands which should cause OctoPrint to pause any ongoing prints.""" + + emergencyCommands: List[str] = ["M112", "M108", "M410"] + + checksumRequiringCommands: List[str] = ["M110"] + """Commands which need to always be send with a checksum.""" + + helloCommand: str = "M110 N0" + """Command to send in order to initiate a handshake with the printer.""" + + disconnectOnErrors: bool = True + """Whether to disconnect from the printer on errors or not.""" + + ignoreErrorsFromFirmware: bool = False + """Whether to completely ignore errors from the firmware or not.""" + + terminalLogSize: int = 20 + lastLineBufferSize: int = 50 + + logResends: bool = True + """Whether to log resends to octoprint.log or not. Invaluable debug tool without performance impact, leave on if possible please.""" + + supportResendsWithoutOk: AlwaysDetectNeverEnum = "detect" + """Whether to support resends without follow-up ok or not.""" + + logPositionOnPause: bool = True + logPositionOnCancel: bool = False + abortHeatupOnCancel: bool = True + + waitForStartOnConnect: bool = False + """Whether OctoPrint should wait for the `start` response from the printer before trying to send commands during connect.""" + + alwaysSendChecksum: bool = False + """Specifies whether OctoPrint should send linenumber + checksum with every printer command. Needed for successful communication with Repetier firmware.""" + + neverSendChecksum: bool = False + + sendChecksumWithUnknownCommands: bool = False + r"""Specifies whether OctoPrint should also send linenumber + checksum with commands that are *not* detected as valid GCODE (as in, they do not match the regular expression `^\s*([GM]\d+|T)`).""" + + unknownCommandsNeedAck: bool = False + r"""Specifies whether OctoPrint should also use up acknowledgments (`ok`) for commands that are *not* detected as valid GCODE (as in, they do not match the regular expression `^\s*([GM]\d+|T)`).""" + + sdRelativePath: bool = False + """Specifies whether firmware expects relative paths for selecting SD files.""" + + sdAlwaysAvailable: bool = False + """Whether to always assume that an SD card is present in the printer. Needed by some firmwares which don't report the SD card status properly.""" + + sdLowerCase: bool = False + sdCancelCommand: str = "M25" + maxNotSdPrinting: int = 2 + swallowOkAfterResend: bool = True + + repetierTargetTemp: bool = False + """Whether the printer sends repetier style target temperatures in the format `TargetExtr0:` instead of attaching that information to the regular `M105` responses.""" + + externalHeatupDetection: bool = True + """Whether to enable external heatup detection (to detect heatup triggered e.g. through the printer's LCD panel or while printing from SD) or not. Causes issues with Repetier's "first ok then response" approach to communication, so disable for printers running Repetier firmware.""" + + supportWait: bool = True + + ignoreIdenticalResends: bool = False + """Whether to ignore identical resends from the printer (true, repetier) or not (false).""" + + identicalResendsCountdown: int = 7 + """If `ignoreIdenticalResends` is true, how many consecutive identical resends to ignore.""" + + supportFAsCommand: bool = False + """Whether to support `F` on its own as a valid GCODE command (true) or not (false).""" + + firmwareDetection: bool = True + """Whether to attempt to auto detect the firmware of the printer and adjust settings accordingly (true) or not and rely on manual configuration (false).""" + + blockWhileDwelling: bool = False + """Whether to block all sending to the printer while a G4 (dwell) command is active (true, repetier) or not (false).""" + + useParityWorkaround: AlwaysDetectNeverEnum = "detect" + maxConsecutiveResends: int = 10 + sendM112OnError: bool = True + disableSdPrintingDetection: bool = False + ackMax: int = 1 + sanityCheckTools: bool = True + notifySuppressedCommands: InfoWarnNeverEnum = "warn" + capabilities: SerialCapabilities = SerialCapabilities() + + resendRatioThreshold: int = 10 + """Percentage of resend requests among all sent lines that should be considered critical.""" + + resendRatioStart: int = 100 + ignoreEmptyPorts: bool = False + + encoding: str = "ascii" + """Encoding to use when talking to a machine. `ascii` limits access to characters 0-127, `latin_1` enables access to the "extended" ascii characters 0-255. Other values can be used, see [Python's standard encodings](https://docs.python.org/3/library/codecs.html#standard-encodings).""" + + enableShutdownActionCommand: bool = False + """Whether to enable support for the shutdown action command, allowing the printer to shut down OctoPrint and the system it's running on.""" + + # command specific flags + triggerOkForM29: bool = True + """Whether to automatically trigger an ok for `M29` (a lot of versions of this command are buggy and the response skips on the ok).""" diff --git a/src/octoprint/schema/config/server.py b/src/octoprint/schema/config/server.py new file mode 100644 index 000000000..206217a81 --- /dev/null +++ b/src/octoprint/schema/config/server.py @@ -0,0 +1,206 @@ +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" + +from enum import Enum +from typing import Dict, List, Optional + +from pydantic import BaseModel +from pydantic_settings import with_attrs_docs + +CONST_15MIN = 15 * 60 +CONST_1GB = 1024 * 1024 * 1024 +CONST_500MB = 500 * 1024 * 1024 +CONST_200MB = 200 * 1024 * 1024 +CONST_100KB = 100 * 1024 + + +@with_attrs_docs +class ReverseProxyConfig(BaseModel): + prefixHeader: Optional[str] = None + """The request header from which to determine the URL prefix under which OctoPrint is served by the reverse proxy.""" + + schemeHeader: Optional[str] = None + """The request header from which to determine the scheme (http or https) under which a specific request to OctoPrint was made to the reverse proxy.""" + + hostHeader: Optional[str] = None + """The request header from which to determine the host under which OctoPrint is served by the reverse proxy.""" + + serverHeader: Optional[str] = None + + portHeader: Optional[str] = None + + prefixFallback: Optional[str] = None + """Use this option to define an optional URL prefix (with a leading /, so absolute to your server's root) under which to run OctoPrint. This should only be needed if you want to run OctoPrint behind a reverse proxy under a different root endpoint than `/` and can't configure said reverse proxy to send a prefix HTTP header (X-Script-Name by default, see above) with forwarded requests.""" + + schemeFallback: Optional[str] = None + """Use this option to define an optional forced scheme (http or https) under which to run OctoPrint. This should only be needed if you want to run OctoPrint behind a reverse proxy that also does HTTPS determination but can't configure said reverse proxy to send a scheme HTTP header (X-Scheme by default, see above) with forwarded requests.""" + + hostFallback: Optional[str] = None + """Use this option to define an optional forced host under which to run OctoPrint. This should only be needed if you want to run OctoPrint behind a reverse proxy with a different hostname than OctoPrint itself but can't configure said reverse proxy to send a host HTTP header (X-Forwarded-Host by default, see above) with forwarded requests.""" + + serverFallback: Optional[str] = None + + portFallback: Optional[str] = None + + trustedDownstream: List[str] = [] + """List of trusted downstream servers for which to ignore the IP address when trying to determine the connecting client's IP address. If you have OctoPrint behind more than one reverse proxy you should add their IPs here so that they won't be interpreted as the client's IP. One reverse proxy will be handled correctly by default.""" + + +@with_attrs_docs +class UploadsConfig(BaseModel): + maxSize: int = CONST_1GB + """Maximum size of uploaded files in bytes, defaults to 1GB.""" + + nameSuffix: str = "name" + """Suffix used for storing the filename in the file upload headers when streaming uploads.""" + + pathSuffix: str = "path" + """Suffix used for storing the path to the temporary file in the file upload headers when streaming uploads.""" + + +@with_attrs_docs +class CommandsConfig(BaseModel): + systemShutdownCommand: Optional[str] = None + """Command to shut down the system OctoPrint is running on.""" + + systemRestartCommand: Optional[str] = None + """Command to restart the system OctoPrint is running on.""" + + serverRestartCommand: Optional[str] = None + """Command to restart OctoPrint.""" + + localPipCommand: Optional[str] = None + """pip command associated with OctoPrint, used for installing plugins and updates, if unset (default) the command will be autodetected based on the current python executable - unless you have a really special setup this is the right way to do it and there should be no need to ever touch this setting.""" + + +@with_attrs_docs +class OnlineCheckConfig(BaseModel): + enabled: Optional[bool] = None + """Whether the online check is enabled. Ships unset, the user will be asked to make a decision as part of the setup wizard.""" + + interval: int = CONST_15MIN + """Interval in which to check for online connectivity (in seconds), defaults to 15 minutes.""" + + host: str = "1.1.1.1" + """DNS host against which to check, defaults to Cloudflare's DNS.""" + + port: int = 53 + """DNS port against which to check, defaults to the standard DNS port.""" + + name: str = "octoprint.org" + """Host name for which to check name resolution, defaults to OctoPrint's main domain.""" + + +@with_attrs_docs +class PluginBlacklistConfig(BaseModel): + enabled: Optional[bool] = None + """Whether use of the blacklist is enabled. If unset, the user will be asked to make a decision as part of the setup wizard.""" + + url: str = "https://plugins.octoprint.org/blacklist.json" + """The URL from which to fetch the blacklist.""" + + ttl: int = CONST_15MIN + """Time to live of the cached blacklist, in seconds (default: 15 minutes).""" + + +@with_attrs_docs +class DiskspaceConfig(BaseModel): + warning: int = CONST_500MB + """Threshold (bytes) after which to consider disk space becoming sparse, defaults to 500MB.""" + + critical: int = CONST_200MB + """Threshold (bytes) after which to consider disk space becoming critical, defaults to 200MB.""" + + +@with_attrs_docs +class PreemptiveCacheConfig(BaseModel): + exceptions: List[str] = [] + """Which server paths to exclude from the preemptive cache, e.g. `/some/path`.""" + + until: int = 7 + """How many days to leave unused entries in the preemptive cache config.""" + + +@with_attrs_docs +class IpCheckConfig(BaseModel): + enabled: bool = True + """Whether to enable the check.""" + + trustedSubnets: List[str] = [] + """Additional non-local subnets to consider trusted, in CIDR notation, e.g. `192.168.1.0/24`.""" + + +class SameSiteEnum(str, Enum): + strict = "Strict" + lax = "Lax" + none = "None" + + +@with_attrs_docs +class CookiesConfig(BaseModel): + secure: bool = False + """Whether to set the `Secure` flag to true on cookies. Only set to true if you are running OctoPrint behind a reverse proxy taking care of SSL termination.""" + + samesite: Optional[SameSiteEnum] = None + """`SameSite` setting to use on the cookies. Possible values are `None`, `Lax` and `Strict`. Defaults to unset. Be advised that many browsers now default to `Lax` unless you configure cookies to be set with `Secure` flag set, explicitly set `SameSite` setting here and also serve OctoPrint over https. The `Lax` setting is known to cause with embedding OctoPrint in frames. See also ["Feature: Cookies default to SameSite=Lax"](https://www.chromestatus.com/feature/5088147346030592), ["Feature: Reject insecure SameSite=None cookies"](https://www.chromestatus.com/feature/5633521622188032) and [issue #3482](https://github.com/OctoPrint/OctoPrint/issues/3482).""" + + +@with_attrs_docs +class ServerConfig(BaseModel): + host: Optional[str] = None + """Use this option to define the host to which to bind the server. If unset, OctoPrint will attempt to bind on all available interfaces, IPv4 and v6 unless either is disabled.""" + + port: int = 5000 + """Use this option to define the port to which to bind the server.""" + + firstRun: bool = True + """If this option is true, OctoPrint will show the First Run wizard and set the setting to false after that completes.""" + + startOnceInSafeMode: bool = False + """If this option is true, OctoPrint will enable safe mode on the next server start and reset the setting to false""" + + ignoreIncompleteStartup: bool = False + """Set this to true to make OctoPrint ignore incomplete startups. Helpful for development.""" + + incompleteStartup: bool = False + """Signals to OctoPrint that the last startup was incomplete. OctoPrint will then startup in safe mode.""" + + seenWizards: Dict[str, str] = {} + + secretKey: Optional[str] = None + """Secret key for encrypting cookies and such, randomly generated on first run.""" + + heartbeat: int = CONST_15MIN + + reverseProxy: ReverseProxyConfig = ReverseProxyConfig() + """Settings if OctoPrint is running behind a reverse proxy (haproxy, nginx, apache, ...) that doesn't correctly set the [required headers](https://community.octoprint.org/t/reverse-proxy-configuration-examples/1107). These are necessary in order to make OctoPrint generate correct external URLs so that AJAX requests and download URLs work, and so that client IPs are read correctly.""" + + uploads: UploadsConfig = UploadsConfig() + """Settings for file uploads to OctoPrint, such as maximum allowed file size and header suffixes to use for streaming uploads. OctoPrint does some nifty things internally in order to allow streaming of large file uploads to the application rather than just storing them in memory. For that it needs to do some rewriting of the incoming upload HTTP requests, storing the uploaded file to a temporary location on disk and then sending an internal request to the application containing the original filename and the location of the temporary file.""" + + maxSize: int = CONST_100KB + """Maximum size of requests other than file uploads in bytes, defaults to 100KB.""" + + commands: CommandsConfig = CommandsConfig() + """Commands to restart/shutdown octoprint or the system it's running on.""" + + onlineCheck: OnlineCheckConfig = OnlineCheckConfig() + """Configuration of the regular online connectivity check.""" + + pluginBlacklist: PluginBlacklistConfig = PluginBlacklistConfig() + """Configuration of the plugin blacklist.""" + + diskspace: DiskspaceConfig = DiskspaceConfig() + """Settings of when to display what disk space warning.""" + + preemptiveCache: PreemptiveCacheConfig = PreemptiveCacheConfig() + """Configuration of the preemptive cache.""" + + ipCheck: IpCheckConfig = IpCheckConfig() + """Configuration of the client IP check to warn about connections from external networks.""" + + allowFraming: bool = False + """Whether to allow OctoPrint to be embedded in a frame or not. Note that depending on your setup you might have to set SameSite to None, Secure to true and serve OctoPrint through a reverse proxy that enables https for cookies and thus logging in to work.""" + + cookies: CookiesConfig = CookiesConfig() + """Settings for further configuration of the cookies that OctoPrint sets (login, remember me, ...).""" diff --git a/src/octoprint/schema/config/slicing.py b/src/octoprint/schema/config/slicing.py new file mode 100644 index 000000000..446a41f9f --- /dev/null +++ b/src/octoprint/schema/config/slicing.py @@ -0,0 +1,19 @@ +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" + +from typing import Dict, Optional + +from pydantic import BaseModel +from pydantic_settings import with_attrs_docs + + +@with_attrs_docs +class SlicingConfig(BaseModel): + enabled: bool = True + """Whether to enable slicing support or not.""" + + defaultSlicer: Optional[str] = None + """Default slicer to use.""" + + defaultProfiles: Dict[str, str] = {} + """Default slicing profiles per slicer, maps slicer identifier to profile identifier.""" diff --git a/src/octoprint/schema/config/system.py b/src/octoprint/schema/config/system.py new file mode 100644 index 000000000..016ea11e4 --- /dev/null +++ b/src/octoprint/schema/config/system.py @@ -0,0 +1,31 @@ +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" + +from typing import List, Optional + +from pydantic import BaseModel, Field +from pydantic_settings import with_attrs_docs + + +@with_attrs_docs +class ActionConfig(BaseModel): + action: str + """The identifier used internally to identify the action. Set to `divider` to generate a divider in the menu.""" + + name: Optional[str] = None + """The name of the action that will be shown on the menu. Must be set if the action is not a divider.""" + + command: Optional[str] = None + """The command to execute when the action is selected. Must be set if the action is not a divider.""" + + async_: bool = Field(False, alias="async") + """Whether to run the command asynchronously.""" + + confirm: Optional[str] = None + """An optional confirmation message to show before executing the command.""" + + +@with_attrs_docs +class SystemConfig(BaseModel): + actions: List[ActionConfig] = [] + """A list of system actions to show in the UI.""" diff --git a/src/octoprint/schema/config/temperature.py b/src/octoprint/schema/config/temperature.py new file mode 100644 index 000000000..68bc6353d --- /dev/null +++ b/src/octoprint/schema/config/temperature.py @@ -0,0 +1,37 @@ +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" + +from typing import List + +from pydantic import BaseModel +from pydantic_settings import with_attrs_docs + + +@with_attrs_docs +class TemperatureProfile(BaseModel): + name: str + """Name of the profile.""" + + extruder: int + """Hotend temperature to set with the profile.""" + + bed: int + """Bed temperature to set with the profile.""" + + +@with_attrs_docs +class TemperatureConfig(BaseModel): + profiles: List[TemperatureProfile] = [ + TemperatureProfile(name="ABS", extruder=210, bed=100), + TemperatureProfile(name="PLA", extruder=180, bed=60), + ] + """Temperature profiles to offer in the UI for quick pre-heating.""" + + cutoff: int = 30 + """Cut off time for the temperature data, in minutes.""" + + sendAutomatically: bool = False + """Whether to send new temperature settings made in the UI automatically.""" + + sendAutomaticallyAfter: int = 1 + """After what time to send the new temperature settings automatically, in seconds.""" diff --git a/src/octoprint/schema/config/terminalfilters.py b/src/octoprint/schema/config/terminalfilters.py new file mode 100644 index 000000000..5882b595e --- /dev/null +++ b/src/octoprint/schema/config/terminalfilters.py @@ -0,0 +1,35 @@ +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" + +from pydantic import BaseModel +from pydantic_settings import with_attrs_docs + + +@with_attrs_docs +class TerminalFilterEntry(BaseModel): + name: str + """The name of the filter.""" + + regex: str + """The regular expression to match. Use [JavaScript regular expressions](https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions).""" + + +DEFAULT_TERMINAL_FILTERS = [ + TerminalFilterEntry( + name="Suppress temperature messages", + regex=r"(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+([PBN]\d+\s+)*)?([BCLPR]|T\d*):-?\d+)", + ), + TerminalFilterEntry( + name="Suppress SD status messages", + regex=r"(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)|(Recv: Not SD printing)", + ), + TerminalFilterEntry( + name="Suppress position messages", + regex=r"(Send:\s+(N\d+\s+)?M114)|(Recv:\s+(ok\s+)?X:[+-]?([0-9]*[.])?[0-9]+\s+Y:[+-]?([0-9]*[.])?[0-9]+\s+Z:[+-]?([0-9]*[.])?[0-9]+\s+E\d*:[+-]?([0-9]*[.])?[0-9]+).*", + ), + TerminalFilterEntry(name="Suppress wait responses", regex=r"Recv: wait"), + TerminalFilterEntry( + name="Suppress processing responses", + regex=r"Recv: (echo:\s*)?busy:\s*processing", + ), +] diff --git a/src/octoprint/schema/config/webcam.py b/src/octoprint/schema/config/webcam.py new file mode 100644 index 000000000..fdf394f60 --- /dev/null +++ b/src/octoprint/schema/config/webcam.py @@ -0,0 +1,107 @@ +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" + +from enum import Enum +from typing import List, Optional + +from pydantic import BaseModel +from pydantic_settings import with_attrs_docs + + +class RatioEnum(str, Enum): + sixteen_nine = "16:9" + four_three = "4:3" + + +class TimelapseTypeEnum(str, Enum): + off = "off" + zchange = "zchange" + timed = "timed" + + +@with_attrs_docs +class TimelapseOptions(BaseModel): + interval: Optional[int] = None + """`timed` timelapses only: The interval which to leave between images in seconds.""" + + capturePostRoll: Optional[bool] = None + """`timed` timelapses only: Whether to capture the snapshots for the post roll (true) or just copy the last captured snapshot from the print over and over again (false).""" + + retractionZHop: Optional[float] = None + """`zchange` timelapses only: z-hop height during retractions to ignore for capturing snapshots.""" + + +@with_attrs_docs +class TimelapseConfig(BaseModel): + type: TimelapseTypeEnum = "off" + """The timelapse type.""" + + fps: int = 25 + """The framerate at which to render the movie.""" + + postRoll: int = 0 + """The number of seconds in the rendered video to add after a finished print. The exact way how the additional images will be recorded depends on timelapse type. `zchange` timelapses will take one final picture and add it `fps * postRoll` times. `timed` timelapses continue to record just like at the beginning, so the recording will continue another `fps * postRoll * interval` seconds. This behaviour can be overridden by setting the `capturePostRoll` option to `false`, in which case the post roll will be created identically to `zchange` mode.""" + + options: TimelapseOptions = TimelapseOptions() + """Additional options depending on the timelapse type.""" + + +@with_attrs_docs +class WebcamConfig(BaseModel): + webcamEnabled: bool = True + """Use this option to enable display of a webcam stream in the UI, e.g. via MJPG-Streamer. Webcam support will be disabled if not set.""" + + timelapseEnabled: bool = True + """Use this option to enable timelapse support via snapshot, e.g. via MJPG-Streamer. Timelapse support will be disabled if not set.""" + + stream: Optional[str] = None + + streamRatio: RatioEnum = "16:9" + + streamTimeout: int = 5 + + streamWebrtcIceServers: List[str] = ["stun:stun.l.google.com:19302"] + + snapshot: Optional[str] = None + + snapshotTimeout: int = 5 + + snapshotSslValidation: bool = True + + ffmpeg: Optional[str] = None + """Path to ffmpeg binary to use for creating timelapse recordings. Timelapse support will be disabled if not set.""" + + ffmpegThreads: int = 1 + """Number of how many threads to instruct ffmpeg to use for encoding.""" + + ffmpegVideoCodec: str = "libx264" + """Videocodec to be used for encoding.""" + + bitrate: str = "10000k" + """The bitrate to use for rendering the timelapse video. This gets directly passed to ffmpeg.""" + + watermark: bool = True + """Whether to include a "created with OctoPrint" watermark in the generated timelapse recordings.""" + + flipH: bool = False + """Whether to flip the webcam horizontally.""" + + flipV: bool = False + """Whether to flip the webcam vertically.""" + + rotate90: bool = False + """Whether to rotate the webcam 90ยฐ counter clockwise.""" + + ffmpegCommandline: str = '{ffmpeg} -framerate {fps} -i "{input}" -vcodec {videocodec} -threads {threads} -b:v {bitrate} -f {containerformat} -y {filters} "{output}"' + + ffmpegThumbnailCommandline: str = ( + '{ffmpeg} -sseof -1 -i "{input}" -update 1 -q:v 0.7 "{output}"' + ) + + timelapse: TimelapseConfig = TimelapseConfig() + """The default timelapse settings.""" + + cleanTmpAfterDays: int = 7 + """After how many days unrendered timelapses will be deleted.""" + + cacheBuster: bool = False diff --git a/src/octoprint/settings.py b/src/octoprint/settings/__init__.py similarity index 83% rename from src/octoprint/settings.py rename to src/octoprint/settings/__init__.py index 71b494c23..746a5e055 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings/__init__.py @@ -31,6 +31,7 @@ from collections.abc import KeysView from yaml import YAMLError +from octoprint.schema.config import Config from octoprint.util import ( CaseInsensitiveSet, atomic_write, @@ -86,393 +87,9 @@ def settings(init=False, basedir=None, configfile=None, overlays=None): return _instance -default_settings = { - "serial": { - "port": None, - "baudrate": None, - "exclusive": True, - "lowLatency": False, - "autoconnect": False, - "log": False, - "timeout": { - "detectionFirst": 10, - "detectionConsecutive": 2, - "connection": 10, - "communication": 30, - "communicationBusy": 3, - "temperature": 5, - "temperatureTargetSet": 2, - "temperatureAutoreport": 2, - "sdStatus": 1, - "sdStatusAutoreport": 1, - "posAutoreport": 5, - "resendOk": 0.5, - "baudrateDetectionPause": 1.0, - "positionLogWait": 10.0, - }, - "maxCommunicationTimeouts": {"idle": 2, "printing": 5, "long": 5}, - "maxWritePasses": 5, - "additionalPorts": [], - "additionalBaudrates": [], - "blacklistedPorts": [], - "blacklistedBaudrates": [], - "longRunningCommands": ["G4", "G28", "G29", "G30", "G32", "M400", "M226", "M600"], - "blockedCommands": ["M0", "M1"], - "ignoredCommands": [], - "pausingCommands": ["M0", "M1", "M25"], - "emergencyCommands": ["M112", "M108", "M410"], - "checksumRequiringCommands": ["M110"], - "helloCommand": "M110 N0", - "disconnectOnErrors": True, - "ignoreErrorsFromFirmware": False, - "terminalLogSize": 20, - "lastLineBufferSize": 50, - "logResends": True, - "supportResendsWithoutOk": "detect", - "logPositionOnPause": True, - "logPositionOnCancel": False, - "abortHeatupOnCancel": True, - "waitForStartOnConnect": False, - "alwaysSendChecksum": False, - "neverSendChecksum": False, - "sendChecksumWithUnknownCommands": False, - "unknownCommandsNeedAck": False, - "sdRelativePath": False, - "sdAlwaysAvailable": False, - "sdLowerCase": False, - "sdCancelCommand": "M25", - "maxNotSdPrinting": 2, - "swallowOkAfterResend": True, - "repetierTargetTemp": False, - "externalHeatupDetection": True, - "supportWait": True, - "ignoreIdenticalResends": False, - "identicalResendsCountdown": 7, - "supportFAsCommand": False, - "firmwareDetection": True, - "blockWhileDwelling": False, - "useParityWorkaround": "detect", - "maxConsecutiveResends": 10, - "sendM112OnError": True, - "disableSdPrintingDetection": False, - "ackMax": 1, - "sanityCheckTools": True, - "notifySuppressedCommands": "warn", - "capabilities": { - "autoreport_temp": True, - "autoreport_sdstatus": True, - "autoreport_pos": True, - "busy_protocol": True, - "emergency_parser": True, - "extended_m20": True, - }, - "resendRatioThreshold": 10, - "resendRatioStart": 100, - "ignoreEmptyPorts": False, - "encoding": "ascii", - "enableShutdownActionCommand": False, - # command specific flags - "triggerOkForM29": True, - }, - "server": { - "host": None, - "port": 5000, - "firstRun": True, - "startOnceInSafeMode": False, - "ignoreIncompleteStartup": False, - "incompleteStartup": False, - "seenWizards": {}, - "secretKey": None, - "heartbeat": 15 * 60, # 15 min - "reverseProxy": { - "prefixHeader": None, - "schemeHeader": None, - "hostHeader": None, - "serverHeader": None, - "portHeader": None, - "prefixFallback": None, - "schemeFallback": None, - "hostFallback": None, - "serverFallback": None, - "portFallback": None, - "trustedDownstream": [], - }, - "uploads": { - "maxSize": 1 * 1024 * 1024 * 1024, # 1GB - "nameSuffix": "name", - "pathSuffix": "path", - }, - "maxSize": 100 * 1024, # 100 KB - "commands": { - "systemShutdownCommand": None, - "systemRestartCommand": None, - "serverRestartCommand": None, - "localPipCommand": None, - }, - "onlineCheck": { - "enabled": None, - "interval": 15 * 60, # 15 min - "host": "1.1.1.1", - "port": 53, - "name": "octoprint.org", - }, - "pluginBlacklist": { - "enabled": None, - "url": "https://plugins.octoprint.org/blacklist.json", - "ttl": 15 * 60, # 15 min - }, - "diskspace": { - "warning": 500 * 1024 * 1024, # 500 MB - "critical": 200 * 1024 * 1024, # 200 MB - }, - "preemptiveCache": {"exceptions": [], "until": 7}, - "ipCheck": {"enabled": True, "trustedSubnets": []}, - "allowFraming": False, - "cookies": {"secure": False, "samesite": None}, - }, - "webcam": { - "webcamEnabled": True, - "timelapseEnabled": True, - "stream": None, - "streamRatio": "16:9", - "streamTimeout": 5, - "streamWebrtcIceServers": ["stun:stun.l.google.com:19302"], - "snapshot": None, - "snapshotTimeout": 5, - "snapshotSslValidation": True, - "ffmpeg": None, - "ffmpegThreads": 1, - "ffmpegVideoCodec": "libx264", - "bitrate": "10000k", - "watermark": True, - "flipH": False, - "flipV": False, - "rotate90": False, - "ffmpegCommandline": '{ffmpeg} -framerate {fps} -i "{input}" -vcodec {videocodec} -threads {threads} -b:v {bitrate} -f {containerformat} -y {filters} "{output}"', - "ffmpegThumbnailCommandline": '{ffmpeg} -sseof -1 -i "{input}" -update 1 -q:v 0.7 "{output}"', - "timelapse": { - "type": "off", - "options": {}, - "postRoll": 0, - "fps": 25, - }, - "cleanTmpAfterDays": 7, - "cacheBuster": False, - }, - "gcodeAnalysis": { - "maxExtruders": 10, - "throttle_normalprio": 0.01, - "throttle_highprio": 0.0, - "throttle_lines": 100, - "runAt": "idle", # 'never', 'idle', 'always' - "bedZ": 0.0, - }, - "feature": { - "temperatureGraph": True, - "sdSupport": True, - "keyboardControl": True, - "pollWatched": False, - "modelSizeDetection": True, - "rememberFileFolder": False, - "printStartConfirmation": False, - "printCancelConfirmation": True, - "uploadOverwriteConfirmation": True, - "autoUppercaseBlacklist": ["M117", "M118"], - "g90InfluencesExtruder": False, - "enforceReallyUniversalFilenames": False, - }, - "folder": { - "uploads": None, - "timelapse": None, - "timelapse_tmp": None, - "logs": None, - "virtualSd": None, - "watched": None, - "plugins": None, - "slicingProfiles": None, - "printerProfiles": None, - "scripts": None, - "translations": None, - "generated": None, - "data": None, - }, - "temperature": { - "profiles": [ - {"name": "ABS", "extruder": 210, "bed": 100}, - {"name": "PLA", "extruder": 180, "bed": 60}, - ], - "cutoff": 30, - "sendAutomatically": False, - "sendAutomaticallyAfter": 1, - }, - "printerProfiles": {"default": None}, - "printerParameters": {"pauseTriggers": []}, - "appearance": { - "name": "", - "color": "default", - "colorTransparent": False, - "colorIcon": True, - "defaultLanguage": "_default", - "showFahrenheitAlso": False, - "fuzzyTimes": True, - "closeModalsWithClick": True, - "showInternalFilename": True, - "components": { - "order": { - "navbar": [ - "settings", - "systemmenu", - "plugin_announcements", - "plugin_logging_seriallog", - "plugin_logging_plugintimingslog", - "plugin_pi_support", - "login", - ], - "sidebar": [ - "plugin_firmware_check_warning", - "plugin_firmware_check_info", - "connection", - "state", - "files", - ], - "tab": [ - "temperature", - "control", - "plugin_gcodeviewer", - "terminal", - "timelapse", - ], - "settings": [ - "section_printer", - "serial", - "printerprofiles", - "temperatures", - "terminalfilters", - "gcodescripts", - "section_features", - "features", - "webcam", - "accesscontrol", - "plugin_gcodeviewer", - "api", - "plugin_appkeys", - "section_octoprint", - "server", - "folders", - "appearance", - "plugin_logging", - "plugin_pluginmanager", - "plugin_softwareupdate", - "plugin_announcements", - "plugin_eventmanager", - "plugin_backup", - "plugin_tracking", - "plugin_errortracking", - "plugin_pi_support", - ], - "usersettings": ["access", "interface"], - "wizard": [ - "plugin_softwareupdate_update", - "plugin_backup", - "plugin_corewizard_acl", - "plugin_corewizard_onlinecheck", - ], - "about": [ - "about", - "plugin_pi_support", - "supporters", - "authors", - "changelog", - "license", - "thirdparty", - "plugin_pluginmanager", - ], - "generic": [], - }, - "disabled": { - "navbar": [], - "sidebar": [], - "tab": [], - "settings": [], - "usersettings": [], - "generic": [], - }, - }, - }, - "controls": [], - "system": {"actions": []}, - "accessControl": { - "salt": None, - "userManager": "octoprint.access.users.FilebasedUserManager", - "groupManager": "octoprint.access.groups.FilebasedGroupManager", - "permissionManager": "octoprint.access.permissions.PermissionManager", - "userfile": None, - "groupfile": None, - "autologinLocal": False, - "localNetworks": ["127.0.0.0/8", "::1/128"], - "autologinAs": None, - "trustBasicAuthentication": False, - "checkBasicAuthenticationPassword": True, - "trustRemoteUser": False, - "remoteUserHeader": "REMOTE_USER", - "addRemoteUsers": False, - }, - "slicing": {"enabled": True, "defaultSlicer": None, "defaultProfiles": {}}, - "events": {"enabled": True, "subscriptions": []}, - "api": {"key": None, "allowCrossOrigin": False, "apps": {}}, - "terminalFilters": [ - { - "name": "Suppress temperature messages", - "regex": r"(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+([PBN]\d+\s+)*)?([BCLPR]|T\d*):-?\d+)", - }, - { - "name": "Suppress SD status messages", - "regex": r"(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)|(Recv: Not SD printing)", - }, - { - "name": "Suppress position messages", - "regex": r"(Send:\s+(N\d+\s+)?M114)|(Recv:\s+(ok\s+)?X:[+-]?([0-9]*[.])?[0-9]+\s+Y:[+-]?([0-9]*[.])?[0-9]+\s+Z:[+-]?([0-9]*[.])?[0-9]+\s+E\d*:[+-]?([0-9]*[.])?[0-9]+).*", - }, - {"name": "Suppress wait responses", "regex": r"Recv: wait"}, - { - "name": "Suppress processing responses", - "regex": r"Recv: (echo:\s*)?busy:\s*processing", - }, - ], - "plugins": {"_disabled": [], "_forcedCompatible": [], "_sortingOrder": {}}, - "scripts": { - "gcode": { - "afterPrintCancelled": "; disable motors\nM84\n\n;disable all heaters\n{% snippet 'disable_hotends' %}\n{% snippet 'disable_bed' %}\n;disable fan\nM106 S0", - "snippets": { - "disable_hotends": "{% if printer_profile.extruder.sharedNozzle %}M104 T0 S0\n{% else %}{% for tool in range(printer_profile.extruder.count) %}M104 T{{ tool }} S0\n{% endfor %}{% endif %}", - "disable_bed": "{% if printer_profile.heatedBed %}M140 S0\n{% endif %}", - }, - } - }, - "estimation": { - "printTime": { - "statsWeighingUntil": 0.5, - "validityRange": 0.15, - "forceDumbFromPercent": 0.3, - "forceDumbAfterMin": 30, - "stableThreshold": 60, - } - }, - "devel": { - "stylesheet": "css", - "cache": {"enabled": True, "preemptive": True}, - "webassets": { - "bundle": True, - "clean_on_startup": True, - "minify": True, - "minify_plugins": False, - }, - "useFrozenDictForPrinterState": True, - "showLoadingAnimation": True, - "sockJsConnectTimeout": 30, - "pluginTimings": False, - }, -} +# TODO: This is a temporary solution to get the default settings from the pydantic model. +_config = Config() +default_settings = _config.dict(by_alias=True) """The default settings of the core application.""" valid_boolean_trues = CaseInsensitiveSet(True, "true", "yes", "y", "1", 1) From 9a18fa0f244241c4dea7239a16853c63e5877c8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 9 Jun 2022 13:04:10 +0200 Subject: [PATCH 11/12] =?UTF-8?q?=F0=9F=90=9B=20Fix=20version=20of=20pydan?= =?UTF-8?q?tic-settings?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index c69a81724..180ed4618 100644 --- a/setup.py +++ b/setup.py @@ -67,7 +67,7 @@ core_deps = [ "zeroconf>=0.33,<0.34", # breaking changes can happen on minor version increases "zipstream-ng>=1.3.4,<2.0.0", "pydantic>=1.9.1,<2", - "pydantic-settings>0.25,<1", # TODO: replace with vendored with_attrs_docs + "pydantic-settings>0.2.5,<1", # TODO: replace with vendored with_attrs_docs ] vendored_deps = [ "blinker>=1.4,<2", # dependency of flask_principal From 8174a8e16b3bc8ffaaddee97f938246e964a005a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 9 Jun 2022 13:08:09 +0200 Subject: [PATCH 12/12] =?UTF-8?q?=F0=9F=90=9B=20Fix=20version=20of=20pydan?= =?UTF-8?q?tic-settings,=202nd=20try?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 180ed4618..c95f55ac6 100644 --- a/setup.py +++ b/setup.py @@ -67,7 +67,7 @@ core_deps = [ "zeroconf>=0.33,<0.34", # breaking changes can happen on minor version increases "zipstream-ng>=1.3.4,<2.0.0", "pydantic>=1.9.1,<2", - "pydantic-settings>0.2.5,<1", # TODO: replace with vendored with_attrs_docs + "pydantic-settings>=0.2.5,<1", # TODO: replace with vendored with_attrs_docs ] vendored_deps = [ "blinker>=1.4,<2", # dependency of flask_principal