diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 9eb7968ca..dc5625260 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -50,7 +50,7 @@ jobs: name: ๐Ÿงช Unit tests strategy: matrix: - python: ["3.7", "3.8", "3.9", "3.10"] + python: ["3.7", "3.8", "3.9", "3.10", "3.11"] runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 @@ -84,7 +84,7 @@ jobs: needs: build strategy: matrix: - python: ["3.7", "3.8", "3.9", "3.10"] + python: ["3.7", "3.8", "3.9", "3.10", "3.11"] installable: ["wheel", "sdist"] runs-on: ubuntu-latest steps: diff --git a/.github/workflows/test_install.yml b/.github/workflows/test_install.yml index 18f6d7b39..78d839931 100644 --- a/.github/workflows/test_install.yml +++ b/.github/workflows/test_install.yml @@ -14,7 +14,7 @@ jobs: strategy: matrix: os: ["ubuntu-latest"] - python: ["3.7", "3.8", "3.9", "3.10"] + python: ["3.7", "3.8", "3.9", "3.10", "3.11"] branch: ["master"] runs-on: ${{ matrix.os }} steps: @@ -51,7 +51,7 @@ jobs: strategy: matrix: os: ["ubuntu-latest"] - python: ["3.7", "3.8", "3.9", "3.10"] + python: ["3.7", "3.8", "3.9", "3.10", "3.11"] runs-on: ${{ matrix.os }} steps: - name: ๐Ÿ‘€ Determine latest release diff --git a/README.md b/README.md index c68b677fc..43e24dfb0 100644 --- a/README.md +++ b/README.md @@ -87,7 +87,7 @@ access control as necessary. OctoPrint depends on a few python modules to do its job. Those are automatically installed when installing OctoPrint via `pip`. -OctoPrint currently supports Python 3.7, 3.8, 3.9 and 3.10. +OctoPrint currently supports Python 3.7, 3.8, 3.9, 3.10 and 3.11. ## Usage diff --git a/setup.py b/setup.py index 5591d5f90..4cf1038ef 100644 --- a/setup.py +++ b/setup.py @@ -22,7 +22,7 @@ import octoprint_setuptools # noqa: F401,E402 # ---------------------------------------------------------------------------------------- # Supported python versions -PYTHON_REQUIRES = ">=3.7, <4" +PYTHON_REQUIRES = ">=3.7, <3.12" # Requirements for setup.py SETUP_REQUIRES = [] @@ -55,6 +55,7 @@ core_deps = [ "pathvalidate>=2.4.1,<3", "pkginfo>=1.7.1,<2", "psutil>=5.8,<6", + "pydantic>=1.10.2,<2", "pylru>=1.2,<2", "pyserial>=3.4,<4", "PyYAML>=5.4.1,<6", @@ -69,11 +70,10 @@ 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.2.5,<1", # TODO: replace with vendored with_attrs_docs ] vendored_deps = [ "blinker>=1.4,<2", # dependency of flask_principal + "class-doc>=0.2.6,<0.3", # dependency of with_attrs_docs "regex", # dependency of awesome-slugify "unidecode", # dependency of awesome-slugify ] diff --git a/src/octoprint/access/permissions.py b/src/octoprint/access/permissions.py index d766b4b30..2444bbb83 100644 --- a/src/octoprint/access/permissions.py +++ b/src/octoprint/access/permissions.py @@ -185,7 +185,7 @@ class PluginIdentityContext: # check the permission here if not permission.can(): if self.http_exception: - abort(self.http_exception, permission) + abort(self.http_exception) raise PermissionDenied(permission) def __exit__(self, *args): diff --git a/src/octoprint/plugins/eventmanager/__init__.py b/src/octoprint/plugins/eventmanager/__init__.py index 667c783b3..f631d6ecc 100644 --- a/src/octoprint/plugins/eventmanager/__init__.py +++ b/src/octoprint/plugins/eventmanager/__init__.py @@ -17,7 +17,9 @@ class EventManagerPlugin( } events = self._settings.global_get(["events"]) if events: - my_settings["subscriptions"] = events.get("subscriptions", []) + my_settings["subscriptions"] = sorted( + events.get("subscriptions", []), key=(lambda x: x["event"]) + ) return my_settings def on_settings_save(self, data): diff --git a/src/octoprint/plugins/eventmanager/static/js/events.js b/src/octoprint/plugins/eventmanager/static/js/events.js index f30e4972f..9a51ff31d 100644 --- a/src/octoprint/plugins/eventmanager/static/js/events.js +++ b/src/octoprint/plugins/eventmanager/static/js/events.js @@ -16,6 +16,7 @@ $(function () { return { event: ko.observable(""), command: ko.observable(""), + name: ko.observable(""), type: ko.observable(""), enabled: ko.observable(true), debug: ko.observable(false) diff --git a/src/octoprint/plugins/eventmanager/templates/eventmanager_settings.jinja2 b/src/octoprint/plugins/eventmanager/templates/eventmanager_settings.jinja2 index 27408c35d..c0d41b6bd 100644 --- a/src/octoprint/plugins/eventmanager/templates/eventmanager_settings.jinja2 +++ b/src/octoprint/plugins/eventmanager/templates/eventmanager_settings.jinja2 @@ -4,7 +4,7 @@
{{ _('Event') }}
-
{{ _('Command') }}
+
{{ _('Name') }}
@@ -12,7 +12,7 @@
-
+
@@ -32,6 +32,13 @@
+ +
+ +
+ +
+
diff --git a/src/octoprint/plugins/gcodeviewer/static/js/gcodeviewer.js b/src/octoprint/plugins/gcodeviewer/static/js/gcodeviewer.js index 23d1c8552..00d89cffc 100644 --- a/src/octoprint/plugins/gcodeviewer/static/js/gcodeviewer.js +++ b/src/octoprint/plugins/gcodeviewer/static/js/gcodeviewer.js @@ -339,6 +339,7 @@ $(function () { self.loadedFilepath = undefined; self.loadedFileDate = undefined; + self.loadedFileSize = undefined; self.status = "idle"; self.enabled = false; @@ -417,6 +418,7 @@ $(function () { self.enableReload(false); self.loadedFilepath = undefined; self.loadedFileDate = undefined; + self.loadedFileSize = undefined; self.clear(); }; @@ -505,7 +507,7 @@ $(function () { }); }; - self.loadFile = function (path, date) { + self.loadFile = function (path, date, size) { self.enableReload(false); self.needsLoad = false; if (self.status === "idle" && self.errorCount < 3) { @@ -513,9 +515,11 @@ $(function () { self.cachedPath = path; self.cachedDate = date; + self.cachedSize = size; var par = { url: OctoPrint.files.downloadPath("local", path), path: path, + size: size, skipUntil: self.settings.settings.plugins.gcodeviewer.skipUntilThis() }; @@ -535,13 +539,14 @@ $(function () { self._onFileLoaded = function () { self.loadedFilepath = self.cachedPath; self.loadedFileDate = self.cachedDate; + self.loadedFileSize = self.cachedSize; self.status = "idle"; self.enableReload(true); }; self.reload = function () { if (!self.enableReload()) return; - self.loadFile(self.loadedFilepath, self.loadedFileDate); + self.loadFile(self.loadedFilepath, self.loadedFileDate, self.loadedFileSize); }; self.fromHistoryData = function (data) { @@ -576,6 +581,7 @@ $(function () { self.loadedFilepath = undefined; self.loadedFileDate = undefined; + self.loadedFileSize = undefined; self.selectedFile.path(undefined); self.selectedFile.date(undefined); self.selectedFile.size(undefined); @@ -591,7 +597,8 @@ $(function () { if ( self.loadedFilepath && self.loadedFilepath === data.job.file.path && - self.loadedFileDate === data.job.file.date + self.loadedFileDate === data.job.file.date && + self.loadedFileSize === data.job.file.size ) { if ( OctoPrint.coreui.browserTabVisible && @@ -611,7 +618,8 @@ $(function () { self.status !== "request" && (!self.waitForApproval() || self.selectedFile.path() !== data.job.file.path || - self.selectedFile.date() !== data.job.file.date) + self.selectedFile.date() !== data.job.file.date || + self.selectedFile.size() !== data.job.file.size) ) { self.selectedFile.path(data.job.file.path); self.selectedFile.date(data.job.file.date); @@ -627,10 +635,15 @@ $(function () { self.waitForApproval(true); self.loadedFilepath = undefined; self.loadedFileDate = undefined; + self.loadedFileSize = undefined; } else { self.waitForApproval(false); if (self.tabActive) { - self.loadFile(data.job.file.path, data.job.file.date); + self.loadFile( + data.job.file.path, + data.job.file.date, + data.job.file.size + ); } else { self.needsLoad = true; } @@ -647,7 +660,11 @@ $(function () { self.approveLargeFile = function () { self.waitForApproval(false); - self.loadFile(self.selectedFile.path(), self.selectedFile.date()); + self.loadFile( + self.selectedFile.path(), + self.selectedFile.date(), + self.selectedFile.size() + ); }; self._onProgress = function (type, percentage) { @@ -872,7 +889,8 @@ $(function () { self.onTabChange = function (current, previous) { self.tabActive = current === "#gcode"; if (self.tabActive && self.needsLoad) { - self.loadFile(self.selectedFile.path(), self.selectedFile.date()); + self.loadFile(self.selectedFile.path(), self.selectedFile.date()), + self.selectedFile.size(); } }; diff --git a/src/octoprint/plugins/gcodeviewer/static/js/viewer/reader.js b/src/octoprint/plugins/gcodeviewer/static/js/viewer/reader.js index 31df5d3ab..5fca079b1 100644 --- a/src/octoprint/plugins/gcodeviewer/static/js/viewer/reader.js +++ b/src/octoprint/plugins/gcodeviewer/static/js/viewer/reader.js @@ -214,7 +214,7 @@ GCODE.gCodeReader = (function () { gCodeOptions["forceCompression"] || gCodeOptions["alwaysCompress"] || (gCodeOptions["compressionSizeThreshold"] > 0 && - gCodeOptions["compressionSizeThreshold"] <= totalSize); + gCodeOptions["compressionSizeThreshold"] <= reader.size); GCODE.ui.worker.postMessage({ cmd: "downloadAndParseGCode", diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py index ce9717860..2a96c9b0d 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -52,7 +52,7 @@ class VirtualPrinter: self._plugin_data_folder = data_folder self._seriallog = logging.getLogger( - "octoprint.plugin.virtual_printer.VirtualPrinter.serial" + "octoprint.plugins.virtual_printer.VirtualPrinter.serial" ) self._seriallog.setLevel(logging.CRITICAL) self._seriallog.propagate = False diff --git a/src/octoprint/printer/profile.py b/src/octoprint/printer/profile.py index d7322550b..6ca79ee52 100644 --- a/src/octoprint/printer/profile.py +++ b/src/octoprint/printer/profile.py @@ -645,6 +645,18 @@ class PrinterProfileManager: value[path[-1]] = converter(value[path[-1]]) + def validate_value(profile, path, validator): + value = profile + for part in path[:-1]: + if not isinstance(value, dict) or part not in value: + raise RuntimeError("%s is not contained in profile" % ".".join(path)) + value = value[part] + + if not isinstance(value, dict) or path[-1] not in value: + raise RuntimeError("%s is not contained in profile" % ".".join(path)) + + return validator(value[path[-1]]) + # convert ints for path in ( ("extruder", "count"), @@ -696,6 +708,21 @@ class PrinterProfileManager: ) return False + # validate volume size range + for path in ( + ("volume", "width"), + ("volume", "depth"), + ("volume", "height"), + ): + if not validate_value(profile, path, lambda x: x > 0 and x < 10000): + return False + + # validate extruder count range + if not validate_value( + profile, ("extruder", "count"), lambda x: x > 0 and x < 100 + ): + return False + # validate form factor if profile["volume"]["formFactor"] not in BedFormFactor.values(): self._logger.warning( diff --git a/src/octoprint/schema/__init__.py b/src/octoprint/schema/__init__.py index 3103d3cb6..e6938842c 100644 --- a/src/octoprint/schema/__init__.py +++ b/src/octoprint/schema/__init__.py @@ -1,2 +1,9 @@ __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 as PydanticBaseModel + + +class BaseModel(PydanticBaseModel): + class Config: + use_enum_values = True diff --git a/src/octoprint/schema/config/__init__.py b/src/octoprint/schema/config/__init__.py index 2bcc7ca2c..32cc388df 100644 --- a/src/octoprint/schema/config/__init__.py +++ b/src/octoprint/schema/config/__init__.py @@ -3,8 +3,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms from typing import List, Union -from pydantic import BaseModel -from pydantic_settings import with_attrs_docs +from octoprint.schema import BaseModel +from octoprint.vendor.with_attrs_docs import with_attrs_docs from .access_control import AccessControlConfig from .api import ApiConfig diff --git a/src/octoprint/schema/config/access_control.py b/src/octoprint/schema/config/access_control.py index 5546bc020..051ed5f46 100644 --- a/src/octoprint/schema/config/access_control.py +++ b/src/octoprint/schema/config/access_control.py @@ -3,8 +3,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms from typing import List, Optional -from pydantic import BaseModel -from pydantic_settings import with_attrs_docs +from octoprint.schema import BaseModel +from octoprint.vendor.with_attrs_docs import with_attrs_docs @with_attrs_docs diff --git a/src/octoprint/schema/config/api.py b/src/octoprint/schema/config/api.py index 77ee8d097..e2fa51900 100644 --- a/src/octoprint/schema/config/api.py +++ b/src/octoprint/schema/config/api.py @@ -1,8 +1,8 @@ __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 +from octoprint.schema import BaseModel +from octoprint.vendor.with_attrs_docs import with_attrs_docs @with_attrs_docs diff --git a/src/octoprint/schema/config/appearance.py b/src/octoprint/schema/config/appearance.py index 234052422..f72cd25ca 100644 --- a/src/octoprint/schema/config/appearance.py +++ b/src/octoprint/schema/config/appearance.py @@ -4,8 +4,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms from enum import Enum from typing import List -from pydantic import BaseModel -from pydantic_settings import with_attrs_docs +from octoprint.schema import BaseModel +from octoprint.vendor.with_attrs_docs import with_attrs_docs class ColorEnum(str, Enum): @@ -140,7 +140,7 @@ 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" + color: ColorEnum = ColorEnum.default """Use this to color the navigation bar.""" colorTransparent: bool = False diff --git a/src/octoprint/schema/config/controls.py b/src/octoprint/schema/config/controls.py index 13dcf9649..d89c82fa5 100644 --- a/src/octoprint/schema/config/controls.py +++ b/src/octoprint/schema/config/controls.py @@ -4,8 +4,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms from enum import Enum from typing import List, Optional, Union -from pydantic import BaseModel -from pydantic_settings import with_attrs_docs +from octoprint.schema import BaseModel +from octoprint.vendor.with_attrs_docs import with_attrs_docs class LayoutEnum(str, Enum): @@ -46,7 +46,7 @@ class ContainerConfig(BaseModel): name: Optional[str] = None """A name to display above the container, basically a section header.""" - layout: LayoutEnum = "vertical" + layout: LayoutEnum = LayoutEnum.vertical """The layout to use for laying out the contained children, either from top to bottom (`vertical`) or from left to right (`horizontal`).""" diff --git a/src/octoprint/schema/config/devel.py b/src/octoprint/schema/config/devel.py index 66f253f3a..569328963 100644 --- a/src/octoprint/schema/config/devel.py +++ b/src/octoprint/schema/config/devel.py @@ -3,8 +3,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms from enum import Enum -from pydantic import BaseModel -from pydantic_settings import with_attrs_docs +from octoprint.schema import BaseModel +from octoprint.vendor.with_attrs_docs import with_attrs_docs class StylesheetEnum(str, Enum): @@ -37,7 +37,7 @@ class DevelCacheConfig(BaseModel): @with_attrs_docs class DevelConfig(BaseModel): - stylesheet: StylesheetEnum = "css" + stylesheet: StylesheetEnum = 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() diff --git a/src/octoprint/schema/config/estimation.py b/src/octoprint/schema/config/estimation.py index 147602215..3240afcff 100644 --- a/src/octoprint/schema/config/estimation.py +++ b/src/octoprint/schema/config/estimation.py @@ -1,8 +1,8 @@ __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 +from octoprint.schema import BaseModel +from octoprint.vendor.with_attrs_docs import with_attrs_docs @with_attrs_docs diff --git a/src/octoprint/schema/config/events.py b/src/octoprint/schema/config/events.py index 54455ced1..249476e9e 100644 --- a/src/octoprint/schema/config/events.py +++ b/src/octoprint/schema/config/events.py @@ -2,10 +2,10 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" from enum import Enum -from typing import List +from typing import List, Optional -from pydantic import BaseModel -from pydantic_settings import with_attrs_docs +from octoprint.schema import BaseModel +from octoprint.vendor.with_attrs_docs import with_attrs_docs class SubscriptionTypeEnum(str, Enum): @@ -18,6 +18,9 @@ class EventSubscription(BaseModel): event: str """The event to subscribe to.""" + name: Optional[str] = None + """The event name to show on the UI""" + command: str """The command to execute when the event is triggered, either a GCODE or a system command.""" diff --git a/src/octoprint/schema/config/feature.py b/src/octoprint/schema/config/feature.py index 88f07111d..98d70e5de 100644 --- a/src/octoprint/schema/config/feature.py +++ b/src/octoprint/schema/config/feature.py @@ -3,8 +3,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms from typing import List -from pydantic import BaseModel -from pydantic_settings import with_attrs_docs +from octoprint.schema import BaseModel +from octoprint.vendor.with_attrs_docs import with_attrs_docs @with_attrs_docs diff --git a/src/octoprint/schema/config/folder.py b/src/octoprint/schema/config/folder.py index fdaa22a2d..91f1147e3 100644 --- a/src/octoprint/schema/config/folder.py +++ b/src/octoprint/schema/config/folder.py @@ -3,8 +3,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms from typing import Optional -from pydantic import BaseModel -from pydantic_settings import with_attrs_docs +from octoprint.schema import BaseModel +from octoprint.vendor.with_attrs_docs import with_attrs_docs @with_attrs_docs diff --git a/src/octoprint/schema/config/gcode_analysis.py b/src/octoprint/schema/config/gcode_analysis.py index 2d66865f4..1a442f1a0 100644 --- a/src/octoprint/schema/config/gcode_analysis.py +++ b/src/octoprint/schema/config/gcode_analysis.py @@ -3,14 +3,14 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms from enum import Enum -from pydantic import BaseModel -from pydantic_settings import with_attrs_docs +from octoprint.schema import BaseModel +from octoprint.vendor.with_attrs_docs import with_attrs_docs class RunAtEnum(str, Enum): - never: str = "never" - idle: str = "idle" - always: str = "always" + never = "never" + idle = "idle" + always = "always" @with_attrs_docs @@ -27,7 +27,7 @@ class GcodeAnalysisConfig(BaseModel): throttle_lines: int = 100 """GCODE line batch size.""" - runAt: RunAtEnum = "idle" + runAt: RunAtEnum = RunAtEnum.idle """Whether to run the analysis only when idle (not printing), regardless of printing state or never.""" bedZ: float = 0.0 diff --git a/src/octoprint/schema/config/plugins.py b/src/octoprint/schema/config/plugins.py index f9abd68c0..02163aaf6 100644 --- a/src/octoprint/schema/config/plugins.py +++ b/src/octoprint/schema/config/plugins.py @@ -3,8 +3,10 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms from typing import Dict, List -from pydantic import BaseModel, Field -from pydantic_settings import with_attrs_docs +from pydantic import Field + +from octoprint.schema import BaseModel +from octoprint.vendor.with_attrs_docs import with_attrs_docs @with_attrs_docs diff --git a/src/octoprint/schema/config/printer_parameters.py b/src/octoprint/schema/config/printer_parameters.py index 9219b63d6..eec603151 100644 --- a/src/octoprint/schema/config/printer_parameters.py +++ b/src/octoprint/schema/config/printer_parameters.py @@ -3,8 +3,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms from typing import List -from pydantic import BaseModel -from pydantic_settings import with_attrs_docs +from octoprint.schema import BaseModel +from octoprint.vendor.with_attrs_docs import with_attrs_docs @with_attrs_docs diff --git a/src/octoprint/schema/config/printer_profiles.py b/src/octoprint/schema/config/printer_profiles.py index b1aa439d5..bd04a47b7 100644 --- a/src/octoprint/schema/config/printer_profiles.py +++ b/src/octoprint/schema/config/printer_profiles.py @@ -3,8 +3,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms from typing import Optional -from pydantic import BaseModel -from pydantic_settings import with_attrs_docs +from octoprint.schema import BaseModel +from octoprint.vendor.with_attrs_docs import with_attrs_docs @with_attrs_docs diff --git a/src/octoprint/schema/config/scripts.py b/src/octoprint/schema/config/scripts.py index fbec21646..06fb4bd9d 100644 --- a/src/octoprint/schema/config/scripts.py +++ b/src/octoprint/schema/config/scripts.py @@ -3,8 +3,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms from typing import Dict, Optional -from pydantic import BaseModel -from pydantic_settings import with_attrs_docs +from octoprint.schema import BaseModel +from octoprint.vendor.with_attrs_docs import with_attrs_docs @with_attrs_docs diff --git a/src/octoprint/schema/config/serial.py b/src/octoprint/schema/config/serial.py index 163b0be53..61d453580 100644 --- a/src/octoprint/schema/config/serial.py +++ b/src/octoprint/schema/config/serial.py @@ -4,8 +4,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms from enum import Enum from typing import List, Optional -from pydantic import BaseModel -from pydantic_settings import with_attrs_docs +from octoprint.schema import BaseModel +from octoprint.vendor.with_attrs_docs import with_attrs_docs class AlwaysDetectNeverEnum(str, Enum): diff --git a/src/octoprint/schema/config/server.py b/src/octoprint/schema/config/server.py index 4ac86204b..5124abf6b 100644 --- a/src/octoprint/schema/config/server.py +++ b/src/octoprint/schema/config/server.py @@ -4,8 +4,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms from enum import Enum from typing import Dict, List, Optional -from pydantic import BaseModel -from pydantic_settings import with_attrs_docs +from octoprint.schema import BaseModel +from octoprint.vendor.with_attrs_docs import with_attrs_docs CONST_15MIN = 15 * 60 CONST_1GB = 1024 * 1024 * 1024 diff --git a/src/octoprint/schema/config/slicing.py b/src/octoprint/schema/config/slicing.py index 446a41f9f..8b24b6618 100644 --- a/src/octoprint/schema/config/slicing.py +++ b/src/octoprint/schema/config/slicing.py @@ -3,8 +3,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms from typing import Dict, Optional -from pydantic import BaseModel -from pydantic_settings import with_attrs_docs +from octoprint.schema import BaseModel +from octoprint.vendor.with_attrs_docs import with_attrs_docs @with_attrs_docs diff --git a/src/octoprint/schema/config/system.py b/src/octoprint/schema/config/system.py index 016ea11e4..b27a852d2 100644 --- a/src/octoprint/schema/config/system.py +++ b/src/octoprint/schema/config/system.py @@ -3,8 +3,10 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms from typing import List, Optional -from pydantic import BaseModel, Field -from pydantic_settings import with_attrs_docs +from pydantic import Field + +from octoprint.schema import BaseModel +from octoprint.vendor.with_attrs_docs import with_attrs_docs @with_attrs_docs diff --git a/src/octoprint/schema/config/temperature.py b/src/octoprint/schema/config/temperature.py index 68bc6353d..e331be1ea 100644 --- a/src/octoprint/schema/config/temperature.py +++ b/src/octoprint/schema/config/temperature.py @@ -3,8 +3,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms from typing import List -from pydantic import BaseModel -from pydantic_settings import with_attrs_docs +from octoprint.schema import BaseModel +from octoprint.vendor.with_attrs_docs import with_attrs_docs @with_attrs_docs diff --git a/src/octoprint/schema/config/terminalfilters.py b/src/octoprint/schema/config/terminalfilters.py index 5882b595e..923b4677e 100644 --- a/src/octoprint/schema/config/terminalfilters.py +++ b/src/octoprint/schema/config/terminalfilters.py @@ -1,8 +1,8 @@ __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 +from octoprint.schema import BaseModel +from octoprint.vendor.with_attrs_docs import with_attrs_docs @with_attrs_docs diff --git a/src/octoprint/schema/config/webcam.py b/src/octoprint/schema/config/webcam.py index fdf394f60..42587c4cc 100644 --- a/src/octoprint/schema/config/webcam.py +++ b/src/octoprint/schema/config/webcam.py @@ -4,8 +4,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms from enum import Enum from typing import List, Optional -from pydantic import BaseModel -from pydantic_settings import with_attrs_docs +from octoprint.schema import BaseModel +from octoprint.vendor.with_attrs_docs import with_attrs_docs class RatioEnum(str, Enum): @@ -33,7 +33,7 @@ class TimelapseOptions(BaseModel): @with_attrs_docs class TimelapseConfig(BaseModel): - type: TimelapseTypeEnum = "off" + type: TimelapseTypeEnum = TimelapseTypeEnum.off """The timelapse type.""" fps: int = 25 @@ -56,7 +56,7 @@ class WebcamConfig(BaseModel): stream: Optional[str] = None - streamRatio: RatioEnum = "16:9" + streamRatio: RatioEnum = RatioEnum.sixteen_nine streamTimeout: int = 5 diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 08dd56999..59228eba2 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -95,7 +95,19 @@ environmentDetector = None cli_key = None -principals = Principal(app) + +class OctoPrintAnonymousIdentity(AnonymousIdentity): + def __init__(self): + super().__init__() + + user = userManager.anonymous_user_factory() + + self.provides.add(UserNeed(user.get_id())) + for need in user.needs: + self.provides.add(need) + + +principals = Principal(app, anonymous_identity=OctoPrintAnonymousIdentity) import octoprint.access.groups as groups # noqa: E402 import octoprint.access.permissions as permissions # noqa: E402 @@ -357,7 +369,6 @@ class Server: util.tornado.fix_json_encode() util.tornado.fix_websocket_check_origin() util.tornado.enable_per_message_deflate_extension() - util.flask.fix_flask_jsonify() cli_key = self._setup_cli_key() self._setup_mimetypes() @@ -1383,7 +1394,6 @@ class Server: app.jinja_environment = PrefixAwareJinjaEnvironment app.config["TEMPLATES_AUTO_RELOAD"] = True - app.config["JSONIFY_PRETTYPRINT_REGULAR"] = False app.config["REMEMBER_COOKIE_DURATION"] = 90 * 24 * 60 * 60 # 90 days app.config["REMEMBER_COOKIE_HTTPONLY"] = True # REMEMBER_COOKIE_SECURE will be taken care of by our custom cookie handling @@ -1393,6 +1403,7 @@ class Server: # setup octoprint's flask json serialization/deserialization app.json = OctoPrintJsonProvider(app) + app.json.compact = False s = settings() diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index ec0d0b7e5..ded1ea499 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -12,7 +12,7 @@ import os import threading import time from datetime import datetime, timedelta -from typing import Union +from typing import Any, Union import flask import flask.json @@ -237,35 +237,6 @@ def fix_webassets_convert_item_to_flask_url(): flask_assets.FlaskResolver.convert_item_to_flask_url = fixed_convert_item_to_flask_url -def fix_flask_jsonify(): - def fixed_jsonify(*args, **kwargs): - """Backported from https://github.com/pallets/flask/blob/7e714bd28b6e96d82b2848b48cf8ff48b517b09b/flask/json/__init__.py#L257""" - from flask.json import current_app, dumps - - indent = None - separators = (",", ":") - - if current_app.config["JSONIFY_PRETTYPRINT_REGULAR"] or current_app.debug: - indent = 2 - separators = (", ", ": ") - - if args and kwargs: - raise TypeError( - "jsonify() behavior undefined when passed both args and kwargs" - ) - elif len(args) == 1: # single args are passed directly to dumps() - data = args[0] - else: - data = args or kwargs - - return current_app.response_class( - dumps(data, indent=indent, separators=separators, allow_nan=False) + "\n", - mimetype="application/json", - ) - - flask.jsonify = fixed_jsonify - - # ~~ WSGI environment wrapper for reverse proxying @@ -1939,6 +1910,10 @@ class OctoPrintJsonProvider(flask.json.provider.DefaultJSONProvider): except TypeError: return flask.json.provider.DefaultJSONProvider.default(object_) + def dumps(self, obj: Any, **kwargs: Any) -> str: + kwargs.setdefault("allow_nan", False) + return super().dumps(obj, **kwargs) + ##~~ Session signing diff --git a/src/octoprint/static/js/app/viewmodels/loginui.js b/src/octoprint/static/js/app/viewmodels/loginui.js index 667e52a69..79c950651 100644 --- a/src/octoprint/static/js/app/viewmodels/loginui.js +++ b/src/octoprint/static/js/app/viewmodels/loginui.js @@ -12,13 +12,13 @@ $(function () { self.onUserLoggedOut = self.onUserPermissionsChanged = function () { // reload if user now lacks STATUS & SETTINGS_READ permissions and is not in first run setup, or is in - // first run setup but the ACL wizard has already run and ACL is active + // first run setup but the ACL wizard has already run if ( !self.loginState.hasAllPermissions( self.access.permissions.STATUS, self.access.permissions.SETTINGS_READ ) && - CONFIG_ACCESS_CONTROL_ACTIVE + (!CONFIG_FIRST_RUN || (self.coreWizardAcl && self.coreWizardAcl.setup())) ) { location.reload(); } diff --git a/src/octoprint/static/js/app/viewmodels/printerprofiles.js b/src/octoprint/static/js/app/viewmodels/printerprofiles.js index 2c94e2426..bc79621f4 100644 --- a/src/octoprint/static/js/app/viewmodels/printerprofiles.js +++ b/src/octoprint/static/js/app/viewmodels/printerprofiles.js @@ -124,6 +124,14 @@ $(function () { return !self.name(); }); + self.sizeInvalid = ko.pureComputed(function () { + return ( + !(self.volumeWidth() > 0 && self.volumeWidth() < 10000) || + !(self.volumeDepth() > 0 && self.volumeDepth() < 10000) || + !(self.volumeHeight() > 0 && self.volumeHeight() < 10000) + ); + }); + self.identifierInvalid = ko.pureComputed(function () { var identifier = self.identifier(); var placeholder = self.identifierPlaceholder(); @@ -165,7 +173,9 @@ $(function () { }); self.valid = function () { - return !self.nameInvalid() && !self.identifierInvalid(); + return ( + !self.nameInvalid() && !self.identifierInvalid() && !self.sizeInvalid() + ); }; self.availableColors = ko.observable([ @@ -273,11 +283,32 @@ $(function () { } return v; }; - var validFloat = function (value, def) { - return valid(value, parseFloat, def); + var runChecks = function (value, def, checks) { + if (checks.gt !== undefined) { + if (!(value > checks.gt)) { + return def; + } + } + if (checks.lt !== undefined) { + if (!(value < checks.gt)) { + return def; + } + } + return value; }; - var validInt = function (value, def) { - return valid(value, parseInt, def); + var validFloat = function (value, def, checks) { + var v = valid(value, parseFloat, def); + if (checks) { + v = runChecks(value, def, checks); + } + return v; + }; + var validInt = function (value, def, checks) { + var v = valid(value, parseInt, def); + if (checks) { + v = runChecks(value, def, checks); + } + return v; }; var profile = { @@ -286,16 +317,26 @@ $(function () { color: self.color(), model: self.model(), volume: { - width: validFloat(self.volumeWidth(), defaultProfile.volume.width), - depth: validFloat(self.volumeDepth(), defaultProfile.volume.depth), - height: validFloat(self.volumeHeight(), defaultProfile.volume.height), + width: validFloat(self.volumeWidth(), defaultProfile.volume.width, { + gt: 0, + lt: 10000 + }), + depth: validFloat(self.volumeDepth(), defaultProfile.volume.depth, { + gt: 0, + lt: 10000 + }), + height: validFloat( + self.volumeHeight(), + defaultProfile.volume.height, + {gt: 0, lt: 10000} + ), formFactor: self.volumeFormFactor(), origin: self.volumeOrigin() }, heatedBed: self.heatedBed(), heatedChamber: self.heatedChamber(), extruder: { - count: parseInt(self.extruders()), + count: runChecks(parseInt(self.extruders()), 1, {gt: 0, lt: 100}), offsets: [[0.0, 0.0]], nozzleDiameter: validFloat( self.nozzleDiameter(), @@ -309,19 +350,27 @@ $(function () { }, axes: { x: { - speed: validInt(self.axisXSpeed(), defaultProfile.axes.x.speed), + speed: validInt(self.axisXSpeed(), defaultProfile.axes.x.speed, { + gt: 0 + }), inverted: self.axisXInverted() }, y: { - speed: validInt(self.axisYSpeed(), defaultProfile.axes.y.speed), + speed: validInt(self.axisYSpeed(), defaultProfile.axes.y.speed, { + gt: 0 + }), inverted: self.axisYInverted() }, z: { - speed: validInt(self.axisZSpeed(), defaultProfile.axes.z.speed), + speed: validInt(self.axisZSpeed(), defaultProfile.axes.z.speed, { + gt: 0 + }), inverted: self.axisZInverted() }, e: { - speed: validInt(self.axisESpeed(), defaultProfile.axes.e.speed), + speed: validInt(self.axisESpeed(), defaultProfile.axes.e.speed, { + gt: 0 + }), inverted: self.axisEInverted() } } diff --git a/src/octoprint/static/js/app/viewmodels/wizard.js b/src/octoprint/static/js/app/viewmodels/wizard.js index 30c37caf1..64830b051 100644 --- a/src/octoprint/static/js/app/viewmodels/wizard.js +++ b/src/octoprint/static/js/app/viewmodels/wizard.js @@ -18,10 +18,9 @@ $(function () { }; self.showDialog = function () { - if ( - !CONFIG_WIZARD || - !(!CONFIG_ACCESS_CONTROL_ACTIVE || self.loginState.isAdmin()) - ) + // only open a wizard if we have one and either are in first run OR logged in + // as admin + if (!CONFIG_WIZARD || (!CONFIG_FIRST_RUN && !self.loginState.isAdmin())) return; self.getWizardDetails().done(function (response) { diff --git a/src/octoprint/templates/initscript.jinja2 b/src/octoprint/templates/initscript.jinja2 index ab899f4ed..e968d9192 100644 --- a/src/octoprint/templates/initscript.jinja2 +++ b/src/octoprint/templates/initscript.jinja2 @@ -11,9 +11,6 @@ var CONFIG_LOGFILESPERPAGE = 10; var CONFIG_USERSPERPAGE = 10; var CONFIG_GROUPSPERPAGE = 10; - var CONFIG_WEBCAM_STREAM = "{{ webcamStream|e }}"; // deprecated, only left for compatibility reasons - var CONFIG_ACCESS_CONTROL = true; // deprecated, only left for compatibility reasons - var CONFIG_ACCESS_CONTROL_ACTIVE = {% if accessControlActive -%} true; {% else %} false; {%- endif %} var CONFIG_SD_SUPPORT = {% if enableSdSupport -%} true; {% else %} false; {%- endif %} var CONFIG_FIRST_RUN = {% if firstRun -%} true; {% else %} false; {%- endif %} var CONFIG_TEMPERATURE_GRAPH = {% if enableTemperatureGraph -%} true; {% else %} false; {%- endif %} @@ -25,7 +22,6 @@ // sockjs should define CLOSE_NORMAL for us, but they don't (from ws spec) var SOCKJS_CLOSE_NORMAL = 1000; - var UI_API_KEY = ""; // deprecated, only left for compatibility reasons var VERSION = "{{ version.number|e }}"; var DISPLAY_VERSION = "{{ version.display|e }}"; var BRANCH = "{{ version.branch|e }}"; @@ -42,6 +38,13 @@ var ADDITIONAL_VIEWMODELS = []; var OCTOPRINT_ADDITIONAL_BINDINGS = []; + // deprecated stuff only kept for backwards compatibility goes here + var CONFIG_WEBCAM_STREAM = "{{ webcamStream|e }}"; // deprecated, only left for compatibility reasons + var CONFIG_ACCESS_CONTROL = true; // deprecated, only left for compatibility reasons + var CONFIG_ACCESS_CONTROL_ACTIVE = {% if accessControlActive -%} true; {% else %} false; {%- endif %}; // deprecated, only left for compatibility reasons + var UI_API_KEY = ""; // deprecated, only left for compatibility reasons + // end of deprecated stuff + {% if templates.tab.order %} {% set first_tab = templates.tab.order[0] %} {% set entry, data = templates.tab.entries[first_tab] %} diff --git a/src/octoprint/templates/snippets/settings/printerprofiles/profileEditorBuildvolume.jinja2 b/src/octoprint/templates/snippets/settings/printerprofiles/profileEditorBuildvolume.jinja2 index bc8dd35f0..e37505232 100644 --- a/src/octoprint/templates/snippets/settings/printerprofiles/profileEditorBuildvolume.jinja2 +++ b/src/octoprint/templates/snippets/settings/printerprofiles/profileEditorBuildvolume.jinja2 @@ -41,7 +41,7 @@
- + mm
@@ -50,7 +50,7 @@
- + mm
@@ -61,7 +61,7 @@
- + mm
diff --git a/src/octoprint/vendor/flask_principal.py b/src/octoprint/vendor/flask_principal.py index e4fd85a38..95ed4399c 100644 --- a/src/octoprint/vendor/flask_principal.py +++ b/src/octoprint/vendor/flask_principal.py @@ -12,13 +12,10 @@ __version__ = '0.4.0' import sys - +from collections import deque, namedtuple from functools import partial, wraps -from collections import deque -from collections import namedtuple - -from flask import g, session, current_app, abort, request +from flask import abort, current_app, g, request, session from flask.signals import Namespace PY3 = sys.version_info[0] == 3 @@ -375,9 +372,10 @@ class Principal(object): identification. :param skip_static: Whether to ignore static endpoints. """ - def __init__(self, app=None, use_sessions=True, skip_static=False): + def __init__(self, app=None, use_sessions=True, skip_static=False, anonymous_identity=AnonymousIdentity): self.identity_loaders = deque() self.identity_savers = deque() + self.anonymous_identity = anonymous_identity # XXX This will probably vanish for a better API self.use_sessions = use_sessions self.skip_static = skip_static @@ -469,7 +467,7 @@ class Principal(object): if self._is_static_route(): return - g.identity = AnonymousIdentity() + g.identity = self.anonymous_identity() for loader in self.identity_loaders: identity = loader() if identity is not None: diff --git a/src/octoprint/vendor/with_attrs_docs.py b/src/octoprint/vendor/with_attrs_docs.py new file mode 100644 index 000000000..7a7e7d48c --- /dev/null +++ b/src/octoprint/vendor/with_attrs_docs.py @@ -0,0 +1,45 @@ +# Based on pydantic-settings version 0.2.5 by Daniel Daniels, licensed under MIT +# +# https://github.com/danields761/pydantic-settings + +from typing import Type + +from class_doc import extract_docs_from_cls_obj +from pydantic import BaseModel + + +def apply_attributes_docs( + model: Type[BaseModel], override_existing: bool = True +) -> None: + """ + Apply model attributes documentation in-place. Resulted docs are placed + inside :code:`field.schema.description` for *pydantic* model field. + :param model: any pydantic model + :param override_existing: override existing descriptions + """ + docs = extract_docs_from_cls_obj(model) + + for field in model.__fields__.values(): + if field.field_info.description and not override_existing: + continue + + try: + field.field_info.description = '\n'.join(docs[field.name]) + except KeyError: + pass + + +def with_attrs_docs( + model_cls: Type[BaseModel] +) -> Type[BaseModel]: + """ + Applies :py:func:`.apply_attributes_docs`. + """ + + def decorator(maybe_model_cls: Type[BaseModel]) -> Type[BaseModel]: + apply_attributes_docs( + maybe_model_cls + ) + return maybe_model_cls + + return decorator(model_cls)