From 32943e191d4d9cb71e507b1f6e6af200e6bcd3ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 6 Dec 2021 18:26:37 +0100 Subject: [PATCH 01/56] =?UTF-8?q?=F0=9F=9A=A8=20Get=20rid=20of=20an=20"imp?= =?UTF-8?q?"=20deprecation=20warning?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Our distutils import used to determine the current interpreter's site-packages directory caused an import warning. Switching to a different method of determining the path solved the error and is also way cleaner. Found here: https://stackoverflow.com/a/52638888 --- src/octoprint/plugin/core.py | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index e4c8228d9..4c6d6e07c 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -907,13 +907,9 @@ class PluginManager(object): def _detect_python_environment(self): import sys - from distutils.command.install import install as cmd_install - from distutils.dist import Distribution + import sysconfig - cmd = cmd_install(Distribution()) - cmd.finalize_options() - - self._python_install_dir = cmd.install_lib + self._python_install_dir = sysconfig.get_path("purelib") self._python_prefix = os.path.realpath(sys.prefix) self._python_virtual_env = hasattr(sys, "real_prefix") or ( hasattr(sys, "base_prefix") From dc4b57213cdb945617e435caa8691ac0e521f405 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 9 Dec 2021 14:08:34 +0100 Subject: [PATCH 02/56] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20availalbe=20=3D>=20a?= =?UTF-8?q?vailable?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit And also make string easier to translate. --- .../templates/softwareupdate_settings.jinja2 | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 b/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 index 0e3056f59..4427d44aa 100644 --- a/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 +++ b/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 @@ -130,14 +130,13 @@ - = {{ _('Update notifications enabled') }}, - = {{ _('Update notifications muted') }}, - {{ _('click to toggle') }}. - {% trans %} - "Update all" will update all items for which updates are availalbe & - update notifications are enabled as well, "Update all available" will - update all items for which updates are available regardless of update - notifications being enabled or muted. + {% trans enabled_icon="", muted_icon="" %} + {{ enabled_icon }} = Update notifications enabled, {{ muted_icon }} = + Update notifications muted, click to toggle. "Update all" will update + all items for which updates are available & update notifications are + enabled as well, "Update all available" will update all items for + which updates are available regardless of update notifications being + enabled or muted. {% endtrans %} From d3d407e00044f14c8bb626e92ea071d515e6dedb Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 13 Dec 2021 07:14:12 -0500 Subject: [PATCH 03/56] Cache requirement computation (#4340) This was roughly 5% of my 6178-2021-12-11T14:36:27-05:00.json trace, now 0%. Hopefully most people keep their plugin count under 127 plugins. --- src/octoprint/plugins/pluginmanager/__init__.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 21fcf6113..2b641112e 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -19,6 +19,7 @@ from datetime import datetime import filetype import pkg_resources +import pylru import requests import sarge from flask import Response, abort, jsonify, request @@ -2111,6 +2112,11 @@ class PluginManagerPlugin( } +@pylru.lrudecorator(size=127) +def parse_requirement(line): + return pkg_resources.Requirement.parse(line) + + def _filter_relevant_notification(notification, plugin_version, octoprint_version): if "pluginversions" in notification: pluginversions = notification["pluginversions"] @@ -2118,7 +2124,7 @@ def _filter_relevant_notification(notification, plugin_version, octoprint_versio is_range = lambda x: "=" in x or ">" in x or "<" in x version_ranges = list( map( - lambda x: pkg_resources.Requirement.parse(notification["plugin"] + x), + lambda x: parse_requirement(notification["plugin"] + x), filter(is_range, pluginversions), ) ) From 5cf2f9ecd792e3e2fedca8c12d1b57a9a402a964 Mon Sep 17 00:00:00 2001 From: Didi Kohen Date: Mon, 13 Dec 2021 16:21:06 +0200 Subject: [PATCH 04/56] Paused print doesn't return ready (#4336) --- AUTHORS.md | 1 + src/octoprint/printer/standard.py | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/AUTHORS.md b/AUTHORS.md index 55974884f..397bd03dc 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -157,6 +157,7 @@ date of first contribution): * [Christian Würthner](https://github.com/crysxd) * [Maciej Urbański](https://github.com/rooterkyberian) * [Adam Wolf](https://github.com/adamwolf) + * [Didi Kohen](https://github.com/kohend) OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by [Daid Braam](https://github.com/daid). Parts of its communication layer and diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index 66b55ed4f..bd19a8e75 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -921,7 +921,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): def is_ready(self, *args, **kwargs): return ( self.is_operational() - and not self.is_printing() + and not self._comm.isBusy() + # isBusy is true when paused and not self._comm.isStreaming() ) From 0f41a4219b4069aba5ecf26f0812ee629e0fe144 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 13 Dec 2021 17:37:23 +0100 Subject: [PATCH 05/56] =?UTF-8?q?=F0=9F=94=92=EF=B8=8F=20Use=20custom=20sa?= =?UTF-8?q?fe(r)=20pickler=20for=20webassets?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Just in case someone might somehow find a way to tamper with the cached compiled assets on disk (e.g. through a 3rd party plugin), this should now be better protected against abuse. See also #4339 --- src/octoprint/server/util/flask.py | 13 ++++++-- src/octoprint/util/safe_pickle.py | 48 ++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 3 deletions(-) create mode 100644 src/octoprint/util/safe_pickle.py diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index e35062f9b..04170e445 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -175,11 +175,12 @@ def enable_additional_translations(default_locale="en", additional_folders=None) def fix_webassets_cache(): from webassets import cache + import octoprint.util.safe_pickle + error_logger = logging.getLogger(__name__ + ".fix_webassets_cache") def fixed_set(self, key, data): import os - import pickle import shutil import tempfile @@ -194,7 +195,7 @@ def fix_webassets_cache(): fd, temp_filename = tempfile.mkstemp(prefix="." + md5, dir=self.directory) try: with os.fdopen(fd, "wb") as f: - pickle.dump(data, f) + octoprint.util.safe_pickle.dump(data, f) f.flush() shutil.move(temp_filename, filename) except Exception: @@ -238,7 +239,13 @@ def fix_webassets_cache(): finally: f.close() - unpickled = webassets.cache.safe_unpickle(result) + try: + unpickled = octoprint.util.safe_pickle.safe_loads(result) + except Exception: + error_logger.exception( + "Got an exception while trying to load webasset file {}".format(filename) + ) + return None if unpickled is None: warnings.warn("Ignoring corrupted cache file %s" % filename) return unpickled diff --git a/src/octoprint/util/safe_pickle.py b/src/octoprint/util/safe_pickle.py new file mode 100644 index 000000000..de4b676ca --- /dev/null +++ b/src/octoprint/util/safe_pickle.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2021 The OctoPrint Project - Released under terms of the AGPLv3 License" + + +import io + + +def _validate(module, name, allowed=None): + if allowed is None: + return None + return allowed.get((module, name), None) + + +try: + import cPickle as pickle # Python 2 + + def safe_load(f, allowed=None): + unpickler = pickle.Unpickler(f) + unpickler.find_global = lambda m, n: _validate(m, n, allowed=allowed) + return unpickler.load() + + def safe_loads(s, allowed=None): + return safe_load(io.BytesIO(s), allowed=allowed) + + +except ImportError: + import pickle # Python 3 + + class RestrictedUnpickler(pickle.Unpickler): + def __init__(self, f, *args, **kwargs): + self.allowed = kwargs.get("allowed") + super(RestrictedUnpickler, self).__init__(f, *args, **kwargs) + + def find_class(self, module, name): + return _validate(module, name, allowed=self.allowed) + + def safe_load(f, allowed=None): + return RestrictedUnpickler(f, allowed=allowed).load() + + def safe_loads(s, allowed=None): + return safe_load(io.BytesIO(s), allowed=allowed) + + +dump = pickle.dump +dumps = pickle.dumps From e4f8ee9689ab23298ac29a9041b0bd9929e8cd2b Mon Sep 17 00:00:00 2001 From: Taylor Talkington Date: Wed, 15 Dec 2021 05:15:48 -0500 Subject: [PATCH 06/56] =?UTF-8?q?=F0=9F=92=AC=20Default=20ffmpeg=20option?= =?UTF-8?q?=20-framerate=20instead=20of=20-r=20(#4344)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In timelapse settings, use -framerate instead of -r. This addresses #4153 for new installations. --- AUTHORS.md | 1 + src/octoprint/settings.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/AUTHORS.md b/AUTHORS.md index 397bd03dc..c1a8399aa 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -158,6 +158,7 @@ date of first contribution): * [Maciej Urbański](https://github.com/rooterkyberian) * [Adam Wolf](https://github.com/adamwolf) * [Didi Kohen](https://github.com/kohend) + * [Taylor Talkington](https://github.com/The-EG) OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by [Daid Braam](https://github.com/daid). Parts of its communication layer and diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index e655a2e96..b1fdf31f9 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -262,7 +262,7 @@ default_settings = { "flipH": False, "flipV": False, "rotate90": False, - "ffmpegCommandline": '{ffmpeg} -r {fps} -i "{input}" -vcodec {videocodec} -threads {threads} -b:v {bitrate} -f {containerformat} -y {filters} "{output}"', + "ffmpegCommandline": '{ffmpeg} -framerate {fps} -i "{input}" -vcodec {videocodec} -threads {threads} -b:v {bitrate} -f {containerformat} -y {filters} "{output}"', "timelapse": { "type": "off", "options": {}, From ff543a422ed5a948db385e41d1ddf0bd51b7b5f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 15 Dec 2021 11:25:36 +0100 Subject: [PATCH 07/56] =?UTF-8?q?Revert=20"=F0=9F=94=92=EF=B8=8F=20Use=20c?= =?UTF-8?q?ustom=20safe(r)=20pickler=20for=20webassets"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 0f41a4219b4069aba5ecf26f0812ee629e0fe144. --- src/octoprint/server/util/flask.py | 13 ++------ src/octoprint/util/safe_pickle.py | 48 ------------------------------ 2 files changed, 3 insertions(+), 58 deletions(-) delete mode 100644 src/octoprint/util/safe_pickle.py diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index 04170e445..e35062f9b 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -175,12 +175,11 @@ def enable_additional_translations(default_locale="en", additional_folders=None) def fix_webassets_cache(): from webassets import cache - import octoprint.util.safe_pickle - error_logger = logging.getLogger(__name__ + ".fix_webassets_cache") def fixed_set(self, key, data): import os + import pickle import shutil import tempfile @@ -195,7 +194,7 @@ def fix_webassets_cache(): fd, temp_filename = tempfile.mkstemp(prefix="." + md5, dir=self.directory) try: with os.fdopen(fd, "wb") as f: - octoprint.util.safe_pickle.dump(data, f) + pickle.dump(data, f) f.flush() shutil.move(temp_filename, filename) except Exception: @@ -239,13 +238,7 @@ def fix_webassets_cache(): finally: f.close() - try: - unpickled = octoprint.util.safe_pickle.safe_loads(result) - except Exception: - error_logger.exception( - "Got an exception while trying to load webasset file {}".format(filename) - ) - return None + unpickled = webassets.cache.safe_unpickle(result) if unpickled is None: warnings.warn("Ignoring corrupted cache file %s" % filename) return unpickled diff --git a/src/octoprint/util/safe_pickle.py b/src/octoprint/util/safe_pickle.py deleted file mode 100644 index de4b676ca..000000000 --- a/src/octoprint/util/safe_pickle.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" -__copyright__ = "Copyright (C) 2021 The OctoPrint Project - Released under terms of the AGPLv3 License" - - -import io - - -def _validate(module, name, allowed=None): - if allowed is None: - return None - return allowed.get((module, name), None) - - -try: - import cPickle as pickle # Python 2 - - def safe_load(f, allowed=None): - unpickler = pickle.Unpickler(f) - unpickler.find_global = lambda m, n: _validate(m, n, allowed=allowed) - return unpickler.load() - - def safe_loads(s, allowed=None): - return safe_load(io.BytesIO(s), allowed=allowed) - - -except ImportError: - import pickle # Python 3 - - class RestrictedUnpickler(pickle.Unpickler): - def __init__(self, f, *args, **kwargs): - self.allowed = kwargs.get("allowed") - super(RestrictedUnpickler, self).__init__(f, *args, **kwargs) - - def find_class(self, module, name): - return _validate(module, name, allowed=self.allowed) - - def safe_load(f, allowed=None): - return RestrictedUnpickler(f, allowed=allowed).load() - - def safe_loads(s, allowed=None): - return safe_load(io.BytesIO(s), allowed=allowed) - - -dump = pickle.dump -dumps = pickle.dumps From 85b3d26992b4087ceec761f7e2db9678beedf16d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 15 Dec 2021 13:38:50 +0100 Subject: [PATCH 08/56] =?UTF-8?q?=F0=9F=94=A5=20Get=20rid=20of=20the=20web?= =?UTF-8?q?assets=20cache?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We should rarely if ever regenerate the webassets in production and can wait a few seconds for regeneration in development, if it means we can get rid of a whole monkey patch and an internal use of pickle with non-tamperproof files. So disable the bundle component cache and switch the manifest over to use a json file. Ensure the latter is also removed on server start, just like the other webassets related generated files. Better solution to what was discussed in #4339 and originally to be solved with the now reverted 0f41a42. --- src/octoprint/server/__init__.py | 97 +++++++++++++++++------------- src/octoprint/server/util/flask.py | 76 ----------------------- 2 files changed, 55 insertions(+), 118 deletions(-) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index e8d43911e..95f04a512 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -1962,7 +1962,6 @@ class Server(object): global assets global pluginManager - util.flask.fix_webassets_cache() util.flask.fix_webassets_filtertool() base_folder = self._settings.getBaseFolder("generated") @@ -1972,14 +1971,21 @@ class Server(object): import errno import shutil - for entry in ("webassets", ".webassets-cache"): + for entry, recreate in ( + ("webassets", True), + (".webassets-cache", False), # no longer used, but clean up just in case + (".webassets-manifest.json", False), + ): path = os.path.join(base_folder, entry) # delete path if it exists - if os.path.isdir(path): + if os.path.exists(path): try: self._logger.debug("Deleting {path}...".format(**locals())) - shutil.rmtree(path) + if os.path.isdir(path): + shutil.rmtree(path) + else: + os.remove(path) except Exception: self._logger.exception( "Error while trying to delete {path}, " @@ -1987,52 +1993,53 @@ class Server(object): ) continue - # re-create path - self._logger.debug("Creating {path}...".format(**locals())) - error_text = ( - "Error while trying to re-create {path}, that might cause " - "errors with the webassets cache".format(**locals()) - ) - try: - os.makedirs(path) - except OSError as e: - if e.errno == errno.EACCES: - # that might be caused by the user still having the folder open somewhere, let's try again after - # waiting a bit - import time + # re-create path if necessary + if recreate: + self._logger.debug("Creating {path}...".format(**locals())) + error_text = ( + "Error while trying to re-create {path}, that might cause " + "errors with the webassets cache".format(**locals()) + ) + try: + os.makedirs(path) + except OSError as e: + if e.errno == errno.EACCES: + # that might be caused by the user still having the folder open somewhere, let's try again after + # waiting a bit + import time - for n in range(3): - time.sleep(0.5) - self._logger.debug( - "Creating {path}: Retry #{retry} after {time}s".format( - path=path, retry=n + 1, time=(n + 1) * 0.5 - ) - ) - try: - os.makedirs(path) - break - except Exception: - if self._logger.isEnabledFor(logging.DEBUG): - self._logger.exception( - "Ignored error while creating " - "directory {path}".format(**locals()) + for n in range(3): + time.sleep(0.5) + self._logger.debug( + "Creating {path}: Retry #{retry} after {time}s".format( + path=path, retry=n + 1, time=(n + 1) * 0.5 ) - pass + ) + try: + os.makedirs(path) + break + except Exception: + if self._logger.isEnabledFor(logging.DEBUG): + self._logger.exception( + "Ignored error while creating " + "directory {path}".format(**locals()) + ) + pass + else: + # this will only get executed if we never did + # successfully execute makedirs above + self._logger.exception(error_text) + continue else: - # this will only get executed if we never did - # successfully execute makedirs above + # not an access error, so something we don't understand + # went wrong -> log an error and stop self._logger.exception(error_text) continue - else: - # not an access error, so something we don't understand + except Exception: + # not an OSError, so something we don't understand # went wrong -> log an error and stop self._logger.exception(error_text) continue - except Exception: - # not an OSError, so something we don't understand - # went wrong -> log an error and stop - self._logger.exception(error_text) - continue self._logger.info("Reset webasset folder {path}...".format(**locals())) @@ -2050,6 +2057,12 @@ class Server(object): assets = CustomDirectoryEnvironment(app) assets.debug = not self._settings.getBoolean(["devel", "webassets", "bundle"]) + # we should rarely if ever regenerate the webassets in production and can wait a + # few seconds for regeneration in development, if it means we can get rid of + # a whole monkey patch and in internal use of pickle with non-tamperproof files + assets.cache = False + assets.manifest = "json:.webassets-manifest.json" + UpdaterType = type(util.flask.SettingsCheckUpdater)( util.flask.SettingsCheckUpdater.__name__, (util.flask.SettingsCheckUpdater,), diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index e35062f9b..3a09e34f9 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -8,7 +8,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import functools -import io import logging import os import threading @@ -172,81 +171,6 @@ def enable_additional_translations(default_locale="en", additional_folders=None) flask_babel.get_translations = fixed_get_translations -def fix_webassets_cache(): - from webassets import cache - - error_logger = logging.getLogger(__name__ + ".fix_webassets_cache") - - def fixed_set(self, key, data): - import os - import pickle - import shutil - import tempfile - - if not os.path.exists(self.directory): - error_logger.warning( - "Cache directory {} doesn't exist, not going " - "to attempt to write cache file".format(self.directory) - ) - - md5 = "%s" % cache.make_md5(self.V, key) - filename = os.path.join(self.directory, md5) - fd, temp_filename = tempfile.mkstemp(prefix="." + md5, dir=self.directory) - try: - with os.fdopen(fd, "wb") as f: - pickle.dump(data, f) - f.flush() - shutil.move(temp_filename, filename) - except Exception: - os.remove(temp_filename) - raise - - def fixed_get(self, key): - import errno - import os - import warnings - - from webassets.cache import make_md5 - - if not os.path.exists(self.directory): - error_logger.warning( - "Cache directory {} doesn't exist, not going " - "to attempt to read cache file".format(self.directory) - ) - return None - - try: - hash = make_md5(self.V, key) - except IOError as e: - if e.errno != errno.ENOENT: - raise - return None - - filename = os.path.join(self.directory, "%s" % hash) - try: - f = io.open(filename, "rb") - except IOError as e: - if e.errno != errno.ENOENT: - error_logger.exception( - "Got an exception while trying to open webasset file {}".format( - filename - ) - ) - return None - try: - result = f.read() - finally: - f.close() - - unpickled = webassets.cache.safe_unpickle(result) - if unpickled is None: - warnings.warn("Ignoring corrupted cache file %s" % filename) - return unpickled - - cache.FilesystemCache.set = fixed_set - cache.FilesystemCache.get = fixed_get - - def fix_webassets_filtertool(): from webassets.merge import FilterTool, MemoryHunk, log From 008df45024e13de57ee0a7064a5c7ca25134df88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 15 Dec 2021 14:05:13 +0100 Subject: [PATCH 09/56] =?UTF-8?q?=E2=9C=A8=20New=20serialization/deseriali?= =?UTF-8?q?zation=20helper?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Might be useful for #4339 --- src/octoprint/util/__init__.py | 53 ++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 1233e1f5a..37e2f88cc 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -14,6 +14,7 @@ import collections import contextlib import copy import io +import json import logging import os import re @@ -24,6 +25,7 @@ import threading import time import traceback import warnings +import zlib from functools import wraps from typing import Union @@ -1798,3 +1800,54 @@ def generate_api_key(): def map_boolean(value, true_text, false_text): return true_text if value else false_text + + +def serialize(filename, data, encoding="utf-8", compressed=True): + """ + Serializes data to a file + + In the current implementation this uses json.dumps and - if compressed is True (the + default) - zlib.compress. Only data that can be serialized by json.dumps in the stock + configuration is supported. + + This is not thread-safe, if concurrent access is required, the caller needs to ensure + that only one thread is writing to the file at any given time. + + Arguments: + filename (str): The file to write to + data (object): The data to serialize + encoding (str): The encoding to use for the file + compressed (bool): Whether to compress the data before writing it to the file + """ + serialized = json.dumps(data).encode(encoding) + + if compressed: + serialized = zlib.compress(serialized) + + with io.open(filename, "wb") as f: + f.write(serialized) + + +def deserialize(filename, encoding="utf-8"): + """ + Deserializes data from a file + + In the current implementation this uses json.loads and - if the file is found to be + compressed - zlib.decompress. + + Arguments: + filename (str): The file to deserialize from + encoding (str): The encoding to use for the file, defaults to utf-8 + + Returns: + The deserialized data structure + """ + with io.open(filename, "rb") as f: + serialized = f.read() + + try: + serialized = zlib.decompress(serialized) + except zlib.error: + pass + + return json.loads(serialized.decode(encoding)) From 53eb9bf979246db739c4326fda1f186b91840554 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20W=C3=BCrthner?= Date: Thu, 16 Dec 2021 16:10:25 +0100 Subject: [PATCH 10/56] =?UTF-8?q?=E2=9C=A8=20Create=20new=20plugin=20versi?= =?UTF-8?q?on=20list=20endpoint=20(#4337)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/plugins/pluginmanager/__init__.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 2b641112e..f3441fa9f 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -28,7 +28,7 @@ from past.builtins import basestring import octoprint.plugin import octoprint.plugin.core -from octoprint.access import ADMIN_GROUP +from octoprint.access import ADMIN_GROUP, READONLY_GROUP, USER_GROUP from octoprint.access.permissions import Permissions from octoprint.events import Events from octoprint.server import safe_mode @@ -227,6 +227,13 @@ class PluginManagerPlugin( def get_additional_permissions(self): return [ + { + "key": "LIST", + "name": "List plugins", + "description": gettext("Allows to list installed plugins."), + "default_groups": [READONLY_GROUP, USER_GROUP, ADMIN_GROUP], + "roles": ["manage"], + }, { "key": "MANAGE", "name": "Manage plugins", @@ -498,6 +505,13 @@ class PluginManagerPlugin( unless=lambda: refresh, )(view)() + @octoprint.plugin.BlueprintPlugin.route("/plugins/versions") + @Permissions.PLUGIN_PLUGINMANAGER_LIST.require(403) + def retrieve_plugin_list(self): + return jsonify( + {p["key"]: p["version"] for p in self._get_plugins() if p["enabled"]} + ) + @octoprint.plugin.BlueprintPlugin.route("/plugins/") @Permissions.PLUGIN_PLUGINMANAGER_MANAGE.require(403) def retrieve_specific_plugin(self, key): From 77d57076119178ff5b63b5f9d63836143ab3c630 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 17 Jan 2022 14:45:08 +0100 Subject: [PATCH 11/56] =?UTF-8?q?=F0=9F=92=AC=20event=20mgr:=20Add=20note?= =?UTF-8?q?=20that=20event=20handlers=20are=20async?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #4352 --- .../eventmanager/templates/eventmanager_settings.jinja2 | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/octoprint/plugins/eventmanager/templates/eventmanager_settings.jinja2 b/src/octoprint/plugins/eventmanager/templates/eventmanager_settings.jinja2 index 414c51078..27408c35d 100644 --- a/src/octoprint/plugins/eventmanager/templates/eventmanager_settings.jinja2 +++ b/src/octoprint/plugins/eventmanager/templates/eventmanager_settings.jinja2 @@ -56,6 +56,9 @@ +

+ {{ _('Please note that any event handlers you define here will be processed asynchronously to OctoPrint\'s own processing of the event. You cannot stall, block or otherwise influence internal execution with event handlers.') }} +