diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 635af1309..ff59a7fb0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -95,7 +95,7 @@ jobs: test-e2e: name: 🧪 E2E tests needs: build - runs-on: ubuntu-16.04 + runs-on: ubuntu-18.04 steps: - name: ⬇ Checkout code uses: actions/checkout@v2 diff --git a/.github/workflows/pr_automation.yml b/.github/workflows/pr_automation.yml index d0e04b09b..c1f115ecf 100644 --- a/.github/workflows/pr_automation.yml +++ b/.github/workflows/pr_automation.yml @@ -12,6 +12,29 @@ jobs: with: repo-token: "${{ secrets.GITHUB_TOKEN }}" + - uses: actions/github-script@v2 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + let labels = []; + let setLabels = false; + context.payload.pull_request.labels.forEach(label => { labels.push(label.name) }); + + let target = context.payload.pull_request.base.ref; + if (["maintenance", "devel", "staging/maintenance", "staging/devel", "master"].includes(target)) { + labels.push(`targets ${target}`); + setLabels = true; + } + + if (setLabels) { + github.issues.setLabels({ + issue_number: context.issue.number, + owner: context.repo.owner, + repo: context.repo.repo, + labels: labels + }) + } + - uses: OctoPrint/actions/pr-validation@main with: repo-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.ignore b/.ignore new file mode 100644 index 000000000..c4d12f75e --- /dev/null +++ b/.ignore @@ -0,0 +1,4 @@ +# ripgrep ignore file + +src/octoprint/static/vendor/ +src/octoprint/vendor/ diff --git a/AUTHORS.md b/AUTHORS.md index 1016145b9..8c6e18395 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -148,6 +148,10 @@ date of first contribution): * [ldursw](https://github.com/ldursw) * [Ian Wilt](https://github.com/ianwiltdotcom) * [Ben Sycha](https://github.com/Sycha) + * [John Boiles](https://github.com/johnboiles) + * [Adam DeMuri](https://github.com/ademuri) + * [Daniel Shenkle](https://github.com/DShenkle) + * [Bryan Kenote](https://github.com/bryankenote) 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/SUPPORTERS.md b/SUPPORTERS.md index 132c90268..36ef22907 100644 --- a/SUPPORTERS.md +++ b/SUPPORTERS.md @@ -25,7 +25,6 @@ thanks to everyone who contributed! * David Bounds * DeltaMaker 3D Printers * Dennis Breining - * Douglas Floyd * Dr. Frank Wester * Eric Betts * Ernesto Martinez @@ -48,6 +47,7 @@ thanks to everyone who contributed! * LA 3D Printer Repair * Lachlan Bell * Lee Dohm + * Lefteris Lertas * LulzBot * Makespace Madrid * Mark Walker @@ -78,4 +78,4 @@ thanks to everyone who contributed! * Ulderico Cirello * Ulrich Kempken -and 2352 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [GitHub Sponsors](https://github.com/users/foosel/sponsorship)! +and 2247 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [GitHub Sponsors](https://github.com/users/foosel/sponsorship)! diff --git a/docs/development/environment.rst b/docs/development/environment.rst index f8dcfb258..2e5000959 100644 --- a/docs/development/environment.rst +++ b/docs/development/environment.rst @@ -199,6 +199,10 @@ You'll need a user account with administrator privileges. * ``ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"`` * ``brew install python`` + * Install `pip `_ + + * ``python -m ensurepip --upgrade`` + * Install `virtualenv `_ * ``pip install virtualenv`` diff --git a/docs/plugins/concepts.rst b/docs/plugins/concepts.rst index 5e1c624cf..1be34d43b 100644 --- a/docs/plugins/concepts.rst +++ b/docs/plugins/concepts.rst @@ -35,9 +35,22 @@ any :ref:`settings overlays =2021.2.23", - "OctoPrint-FirmwareCheck>=2021.2.4", + "OctoPrint-FirmwareCheck>=2021.10.11", "OctoPrint-PiSupport>=2021.8.2", # the following dependencies are non trivial to update since later versions # introduce backwards incompatible changes that might affect plugins, or due to # other observed problems "regex!=2018.11.6", # avoid broken 2018.11.6. See #2874 + "wrapt>=1.12.1,<1.13", # newer versions fail to build on OctoPi 0.15 # anything below this should be checked on releases for new versions "tornado>=6.0.4,<7", "markdown>=3.2.2,<4", diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index ff8632fe9..d1462fc62 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -364,10 +364,9 @@ def init_logging( config_from_file = {} if os.path.exists(logging_file) and os.path.isfile(logging_file): - import yaml + from octoprint.util import yaml - with open(logging_file, encoding="utf-8") as f: - config_from_file = yaml.safe_load(f) + config_from_file = yaml.load_from_file(path=logging_file) # we merge that with the default config if config_from_file is not None and isinstance(config_from_file, dict): @@ -713,9 +712,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None): import time import requests - import yaml - from octoprint.util import bom_aware_open from octoprint.util.version import is_octoprint_compatible, is_python_compatible logger = log.getLogger(__name__ + ".startup") @@ -781,8 +778,9 @@ def get_plugin_blacklist(settings, connectivity_checker=None): if os.stat(path).st_mtime + ttl < time.time(): return None - with bom_aware_open(path, encoding="utf-8", mode="rt") as f: - result = yaml.safe_load(f) + from octoprint.util import yaml + + result = yaml.load_from_file(path=path) if isinstance(result, list): return result @@ -795,8 +793,9 @@ def get_plugin_blacklist(settings, connectivity_checker=None): if cache is not None: try: - with bom_aware_open(cache, encoding="utf-8", mode="wt") as f: - yaml.safe_dump(result, f) + from octoprint.util import yaml + + yaml.save_to_file(result, path=cache) except Exception as e: logger.info( "Fetched plugin blacklist but couldn't write it to its cache file: %s", diff --git a/src/octoprint/access/groups.py b/src/octoprint/access/groups.py index 00c6f0d41..9265798e0 100644 --- a/src/octoprint/access/groups.py +++ b/src/octoprint/access/groups.py @@ -6,12 +6,10 @@ import logging import os from functools import partial -import yaml - from octoprint.access import ADMIN_GROUP, GUEST_GROUP, READONLY_GROUP, USER_GROUP from octoprint.access.permissions import OctoPrintPermission, Permissions from octoprint.settings import settings -from octoprint.util import atomic_write +from octoprint.util import atomic_write, yaml from octoprint.vendor.flask_principal import Need, Permission GroupNeed = partial(Need, "group") @@ -226,8 +224,7 @@ class FilebasedGroupManager(GroupManager): def _load(self): if os.path.exists(self._groupfile) and os.path.isfile(self._groupfile): try: - with open(self._groupfile, encoding="utf-8") as f: - data = yaml.safe_load(f) + data = yaml.load_from_file(path=self._groupfile) if "groups" not in data: groups = data @@ -343,11 +340,7 @@ class FilebasedGroupManager(GroupManager): with atomic_write( self._groupfile, mode="wt", permissions=0o600, max_permissions=0o666 ) as f: - import yaml - - yaml.safe_dump( - data, f, default_flow_style=False, indent=2, allow_unicode=True - ) + yaml.save_to_file(data, file=f, pretty=True) self._dirty = False self._load() diff --git a/src/octoprint/access/users.py b/src/octoprint/access/users.py index a327bf22f..7717d743c 100644 --- a/src/octoprint/access/users.py +++ b/src/octoprint/access/users.py @@ -8,7 +8,6 @@ import time import uuid import wrapt -import yaml from flask_login import AnonymousUserMixin, UserMixin from werkzeug.local import LocalProxy @@ -17,7 +16,7 @@ from octoprint.access.permissions import OctoPrintPermission, Permissions from octoprint.settings import settings as s from octoprint.util import atomic_write, deprecated, generate_api_key from octoprint.util import get_fully_qualified_classname as fqcn -from octoprint.util import to_bytes +from octoprint.util import to_bytes, yaml class UserManager(GroupChangeListener): @@ -512,64 +511,60 @@ class FilebasedUserManager(UserManager): def _load(self): if os.path.exists(self._userfile) and os.path.isfile(self._userfile): - # noinspection PyBroadException - with open(self._userfile, encoding="utf-8") as f: - data = yaml.safe_load(f) + data = yaml.load_from_file(path=self._userfile) - if not data or not isinstance(data, dict): - self._logger.fatal( - "{} does not contain a valid map of users. Fix " - "the file, or remove it, then restart OctoPrint.".format( - self._userfile - ) + if not data or not isinstance(data, dict): + self._logger.fatal( + "{} does not contain a valid map of users. Fix " + "the file, or remove it, then restart OctoPrint.".format( + self._userfile ) - raise CorruptUserStorage() + ) + raise CorruptUserStorage() - for name, attributes in data.items(): - if not isinstance(attributes, dict): - continue + for name, attributes in data.items(): + if not isinstance(attributes, dict): + continue - permissions = [] - if "permissions" in attributes: - permissions = attributes["permissions"] + permissions = [] + if "permissions" in attributes: + permissions = attributes["permissions"] - if "groups" in attributes: - groups = set(attributes["groups"]) - else: - groups = {self._group_manager.user_group} + if "groups" in attributes: + groups = set(attributes["groups"]) + else: + groups = {self._group_manager.user_group} - # migrate from roles to permissions - if "roles" in attributes and "permissions" not in attributes: - self._logger.info( - "Migrating user {} to new granular permission system".format( - name - ) - ) - - groups |= set(self._migrate_roles_to_groups(attributes["roles"])) - self._dirty = True - - apikey = None - if "apikey" in attributes: - apikey = attributes["apikey"] - settings = {} - if "settings" in attributes: - settings = attributes["settings"] - - self._users[name] = User( - username=name, - passwordHash=attributes["password"], - active=attributes["active"], - permissions=self._to_permissions(*permissions), - groups=self._to_groups(*groups), - apikey=apikey, - settings=settings, + # migrate from roles to permissions + if "roles" in attributes and "permissions" not in attributes: + self._logger.info( + f"Migrating user {name} to new granular permission system" ) - for sessionid in self._sessionids_by_userid.get(name, set()): - if sessionid in self._session_users_by_session: - self._session_users_by_session[sessionid].update_user( - self._users[name] - ) + + groups |= set(self._migrate_roles_to_groups(attributes["roles"])) + self._dirty = True + + apikey = None + if "apikey" in attributes: + apikey = attributes["apikey"] + settings = {} + if "settings" in attributes: + settings = attributes["settings"] + + self._users[name] = User( + username=name, + passwordHash=attributes["password"], + active=attributes["active"], + permissions=self._to_permissions(*permissions), + groups=self._to_groups(*groups), + apikey=apikey, + settings=settings, + ) + for sessionid in self._sessionids_by_userid.get(name, set()): + if sessionid in self._session_users_by_session: + self._session_users_by_session[sessionid].update_user( + self._users[name] + ) if self._dirty: self._save() @@ -601,9 +596,7 @@ class FilebasedUserManager(UserManager): with atomic_write( self._userfile, mode="wt", permissions=0o600, max_permissions=0o666 ) as f: - yaml.safe_dump( - data, f, default_flow_style=False, indent=2, allow_unicode=True - ) + yaml.save_to_file(data, file=f, pretty=True) self._dirty = False self._load() diff --git a/src/octoprint/cli/analysis.py b/src/octoprint/cli/analysis.py index 94d7fa28d..f2d93b4a9 100644 --- a/src/octoprint/cli/analysis.py +++ b/src/octoprint/cli/analysis.py @@ -5,6 +5,8 @@ import sys import click +from octoprint.util import yaml + click.disable_unicode_literals_warning = True # ~~ "octoprint util" commands @@ -94,8 +96,6 @@ def gcode_command( import time - import yaml - from octoprint.util.gcodeInterpreter import gcode throttle_callback = None @@ -151,14 +151,7 @@ def gcode_command( ) sys.exit(-1) click.echo("RESULTS:") - click.echo( - yaml.safe_dump( - interpreter.get_result(), - default_flow_style=False, - indent=2, - allow_unicode=True, - ) - ) + click.echo(yaml.dump(interpreter.get_result(), pretty=True)) if __name__ == "__main__": diff --git a/src/octoprint/cli/client.py b/src/octoprint/cli/client.py index 212485e66..d3739fc6a 100644 --- a/src/octoprint/cli/client.py +++ b/src/octoprint/cli/client.py @@ -9,6 +9,7 @@ import click import octoprint_client from octoprint import FatalStartupError, init_settings from octoprint.cli import bulk_options, get_ctx_obj_option +from octoprint.util import yaml click.disable_unicode_literals_warning = True @@ -171,10 +172,7 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout): with open(file_path) as fp: data = json.load(fp) else: - import yaml - - with open(file_path) as fp: - data = yaml.safe_load(fp) + data = yaml.load_from_file(path=file_path) r = ctx.obj.client.post_json(path, data, timeout=timeout) else: diff --git a/src/octoprint/cli/config.py b/src/octoprint/cli/config.py index 7af142247..b7fd050bc 100644 --- a/src/octoprint/cli/config.py +++ b/src/octoprint/cli/config.py @@ -7,10 +7,10 @@ import logging import pprint import click -import yaml from octoprint import FatalStartupError, init_settings from octoprint.cli import get_ctx_obj_option, standard_options +from octoprint.util import yaml click.disable_unicode_literals_warning = True @@ -214,9 +214,7 @@ def get_command(ctx, path, as_json=False, as_yaml=False, as_raw=False): if as_json: output = json.dumps(value) elif as_yaml: - output = yaml.safe_dump( - value, default_flow_style=False, indent=2, allow_unicode=True - ) + output = yaml.dump(value, pretty=True) elif as_raw: output = value else: @@ -240,9 +238,7 @@ def effective_command(ctx, as_json=False, as_yaml=False, as_raw=False): if as_json: output = json.dumps(value) elif as_yaml: - output = yaml.safe_dump( - value, default_flow_style=False, indent=2, allow_unicode=True - ) + output = yaml.dump(value, pretty=True) elif as_raw: output = value else: diff --git a/src/octoprint/environment.py b/src/octoprint/environment.py index 6711dc02b..fd4f0053f 100644 --- a/src/octoprint/environment.py +++ b/src/octoprint/environment.py @@ -8,9 +8,9 @@ import sys import threading import psutil -import yaml from octoprint.plugin import EnvironmentDetectionPlugin +from octoprint.util import yaml from octoprint.util.platform import get_os from octoprint.util.version import get_python_version_string @@ -165,9 +165,7 @@ class EnvironmentDetector: self.run_detection() environment = copy.deepcopy(self._cache) - dumped_environment = yaml.safe_dump( - environment, default_flow_style=False, indent=2, allow_unicode=True - ).strip() + dumped_environment = yaml.dump(environment, pretty=True).strip() environment_lines = "\n".join( map(lambda l: f"| {l}", dumped_environment.split("\n")) ) diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py index eae8287e7..a372e0798 100644 --- a/src/octoprint/filemanager/__init__.py +++ b/src/octoprint/filemanager/__init__.py @@ -12,6 +12,7 @@ import octoprint.plugin import octoprint.util from octoprint.events import Events, eventManager from octoprint.util import get_fully_qualified_classname as fqcn +from octoprint.util import yaml from .analysis import AnalysisQueue, QueueEntry # noqa: F401 from .destinations import FileDestinations # noqa: F401 @@ -935,8 +936,6 @@ class FileManager: def save_recovery_data(self, origin, path, pos): import time - import yaml - from octoprint.util import atomic_write data = { @@ -947,9 +946,7 @@ class FileManager: } try: with atomic_write(self._recovery_file, mode="wt", max_permissions=0o666) as f: - yaml.safe_dump( - data, stream=f, default_flow_style=False, indent=2, allow_unicode=True - ) + yaml.save_to_file(data, file=f, pretty=True) except Exception: self._logger.exception( f"Could not write recovery data to file {self._recovery_file}" @@ -970,11 +967,9 @@ class FileManager: if not os.path.isfile(self._recovery_file): return None - import yaml - try: - with open(self._recovery_file, encoding="utf-8") as f: - data = yaml.safe_load(f) + data = yaml.load_from_file(path=self._recovery_file) + if not isinstance(data, dict) or not all( map(lambda x: x in data, ("origin", "path", "pos", "date")) ): diff --git a/src/octoprint/filemanager/analysis.py b/src/octoprint/filemanager/analysis.py index fedcca891..b6c01de93 100644 --- a/src/octoprint/filemanager/analysis.py +++ b/src/octoprint/filemanager/analysis.py @@ -14,6 +14,7 @@ from octoprint.events import Events, eventManager from octoprint.settings import settings from octoprint.util import dict_merge from octoprint.util import get_fully_qualified_classname as fqcn +from octoprint.util import yaml from octoprint.util.platform import CLOSE_FDS EMPTY_RESULT = { @@ -401,7 +402,6 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): import sys import sarge - import yaml if self._current.analysis and all( map( @@ -495,7 +495,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): raise RuntimeError("No analysis result found") else: _, output = output.split("RESULTS:") - analysis = yaml.safe_load(output) + analysis = yaml.load_from_file(file=output) result["printingArea"] = analysis["printing_area"] result["dimensions"] = analysis["dimensions"] diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index fd6d6a579..eb78e770e 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -12,7 +12,14 @@ from os import scandir, walk import pylru import octoprint.filemanager -from octoprint.util import atomic_write, is_hidden_path, time_this, to_bytes, to_unicode +from octoprint.util import ( + atomic_write, + is_hidden_path, + time_this, + to_bytes, + to_unicode, + yaml, +) from octoprint.util.files import sanitize_filename @@ -502,10 +509,7 @@ class LocalFileStorage(StorageInterface): if os.path.exists(old_metadata_path): # load the old metadata file try: - with open(old_metadata_path, encoding="utf-8") as f: - import yaml - - self._old_metadata = yaml.safe_load(f) + self._old_metadata = yaml.load_from_file(path=old_metadata_path) except Exception: self._logger.exception("Error while loading old metadata file") @@ -1887,8 +1891,6 @@ class LocalFileStorage(StorageInterface): # we switched to json in 1.3.9 - if we still have yaml here, migrate it now import json - import yaml - with self._get_persisted_metadata_lock(path): metadata_path_yaml = os.path.join(path, ".metadata.yaml") metadata_path_json = os.path.join(path, ".metadata.json") @@ -1909,16 +1911,13 @@ class LocalFileStorage(StorageInterface): ) return - with open(metadata_path_yaml, encoding="utf-8") as f: - try: - metadata = yaml.safe_load(f) - except Exception: - self._logger.exception( - "Error while reading .metadata.yaml from {path}".format( - **locals() - ) - ) - return + try: + metadata = yaml.load_from_file(path=metadata_path_yaml) + except Exception: + self._logger.exception( + "Error while reading .metadata.yaml from {path}".format(**locals()) + ) + return if not isinstance(metadata, dict): # looks invalid, ignore it diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index 1c4d63dd5..744f03983 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -2385,9 +2385,15 @@ class Plugin: pass def on_plugin_enabled(self): + """ + Called by the plugin core when the plugin was enabled. Override this to react to the event. + """ pass def on_plugin_disabled(self): + """ + Called by the plugin core when the plugin was disabled. Override this to react to the event. + """ pass diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index b3be4b0cb..e1ede3b5d 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -123,6 +123,14 @@ class OctoPrintPlugin(Plugin): os.makedirs(self._data_folder) return self._data_folder + def on_plugin_pending_uninstall(self): + """ + Called by the plugin manager when the plugin is pending uninstall. Override this to react to the event. + + NOT called during plugin uninstalls triggered outside of OctoPrint! + """ + pass + class ReloadNeedingPlugin(Plugin): """ diff --git a/src/octoprint/plugins/appkeys/__init__.py b/src/octoprint/plugins/appkeys/__init__.py index ca8ff3024..e2b7518dd 100644 --- a/src/octoprint/plugins/appkeys/__init__.py +++ b/src/octoprint/plugins/appkeys/__init__.py @@ -4,7 +4,6 @@ import time from collections import defaultdict import flask -import yaml from flask_babel import gettext import octoprint.plugin @@ -13,7 +12,7 @@ from octoprint.access.permissions import Permissions from octoprint.server import NO_CONTENT, admin_permission, current_user from octoprint.server.util.flask import no_firstrun_access, restricted_access from octoprint.settings import valid_boolean_trues -from octoprint.util import ResettableTimer, atomic_write, generate_api_key +from octoprint.util import ResettableTimer, atomic_write, generate_api_key, yaml CUTOFF_TIME = 10 * 60 # 10min POLL_TIMEOUT = 5 # 5 seconds @@ -438,8 +437,7 @@ class AppKeysPlugin( return try: - with open(self._key_path, encoding="utf-8", errors="strict") as f: - persisted = yaml.safe_load(f) + persisted = yaml.load_from_file(path=self._key_path) except Exception: self._logger.exception( f"Could not load application keys from {self._key_path}" @@ -464,7 +462,7 @@ class AppKeysPlugin( try: with atomic_write(self._key_path, mode="wt") as f: - yaml.safe_dump(to_persist, f, allow_unicode=True) + yaml.save_to_file(to_persist, file=f) except Exception: self._logger.exception( f"Could not write application keys to {self._key_path}" diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index 13174e9d8..1072ac691 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -10,7 +10,7 @@ from octoprint.events import Events from octoprint.server import NO_CONTENT from octoprint.server.util.flask import no_firstrun_access from octoprint.settings import default_settings -from octoprint.util import is_hidden_path, to_bytes +from octoprint.util import is_hidden_path, to_bytes, yaml from octoprint.util.pip import create_pip_caller from octoprint.util.platform import is_os_compatible from octoprint.util.version import ( @@ -1190,10 +1190,7 @@ class BackupPlugin( on_restore_failed(path) return False - import yaml - - with open(configfile, encoding="utf-8") as f: - configdata = yaml.safe_load(f) + configdata = yaml.load_from_file(path=configfile) userfile = os.path.join(temp, "basedir", "users.yaml") if not os.path.exists(userfile): diff --git a/src/octoprint/plugins/errortracking/__init__.py b/src/octoprint/plugins/errortracking/__init__.py index 1972451f7..144918d64 100644 --- a/src/octoprint/plugins/errortracking/__init__.py +++ b/src/octoprint/plugins/errortracking/__init__.py @@ -18,10 +18,10 @@ from octoprint.util.version import ( ) SENTRY_URL_SERVER = ( - "https://d697280f99f544d5a0705e7ae9880dd5@o118517.ingest.sentry.io/1373987" + "https://3d510fcb31be49c8a811639b7ed18377@o118517.ingest.sentry.io/1373987" ) SENTRY_URL_COREUI = ( - "https://c82d12e144df4a848e57cd18912239f4@o118517.ingest.sentry.io/1374096" + "https://c6ab43a97f224198ae62a6e11e253cf0@o118517.ingest.sentry.io/1374096" ) SETTINGS_DEFAULTS = { diff --git a/src/octoprint/plugins/logging/__init__.py b/src/octoprint/plugins/logging/__init__.py index a27da578c..344be014b 100644 --- a/src/octoprint/plugins/logging/__init__.py +++ b/src/octoprint/plugins/logging/__init__.py @@ -4,7 +4,6 @@ __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms import os from os import scandir -import yaml from flask import abort, jsonify, request, url_for from flask_babel import gettext from werkzeug.exceptions import BadRequest @@ -16,7 +15,7 @@ from octoprint.access.permissions import Permissions from octoprint.server import NO_CONTENT from octoprint.server.util.flask import no_firstrun_access, redirect_to_tornado from octoprint.settings import settings -from octoprint.util import is_hidden_path +from octoprint.util import is_hidden_path, yaml class LoggingPlugin( @@ -180,10 +179,7 @@ class LoggingPlugin( config_from_file = {} if os.path.exists(logging_file) and os.path.isfile(logging_file): - import yaml - - with open(logging_file, encoding="utf-8") as f: - config_from_file = yaml.safe_load(f) + config_from_file = yaml.load_from_file(path=logging_file) return config_from_file def _get_logging_levels(self): @@ -233,9 +229,7 @@ class LoggingPlugin( with octoprint.util.atomic_write( self._get_logging_file(), mode="wt", max_permissions=0o666 ) as f: - yaml.safe_dump( - config, f, default_flow_style=False, indent=2, allow_unicode=True - ) + yaml.save_to_file(config, file=f, pretty=True) # set runtime logging levels now for logger, level in new_levels.items(): diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 912f99249..627748214 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -1251,6 +1251,14 @@ class PluginManagerPlugin( ) abort(500, description="Could not uninstall plugin, its origin is unknown") + if plugin.implementation: + try: + plugin.implementation.on_plugin_pending_uninstall() + except Exception: + self._logger.exception( + "Error while calling on_plugin_pending_uninstall on the plugin, proceeding regardless" + ) + if plugin.origin.type == "entry_point": # plugin is installed through entry point, need to use pip to uninstall it origin = plugin.origin[3] diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index 50f618867..babb42360 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -27,7 +27,7 @@ from octoprint.server.util.flask import ( no_firstrun_access, with_revalidation_checking, ) -from octoprint.util import dict_merge, get_formatted_size, to_unicode +from octoprint.util import dict_merge, get_formatted_size, to_unicode, yaml from octoprint.util.pip import create_pip_caller from octoprint.util.version import ( get_comparable_version, @@ -37,10 +37,10 @@ from octoprint.util.version import ( from . import cli, exceptions, updaters, util, version_checks -# OctoPi 0.15+ -MINIMUM_PYTHON = "2.7.9" -MINIMUM_SETUPTOOLS = "39.0.1" -MINIMUM_PIP = "9.0.3" +# OctoPi 0.16+ +MINIMUM_PYTHON = "2.7.13" +MINIMUM_SETUPTOOLS = "40.7.1" +MINIMUM_PIP = "19.0.1" DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S" @@ -465,11 +465,8 @@ class SoftwareUpdatePlugin( if not os.path.isfile(self._version_cache_path): return - import yaml - try: - with open(self._version_cache_path, encoding="utf-8") as f: - data = yaml.safe_load(f) + data = yaml.load_from_file(path=self._version_cache_path) timestamp = os.stat(self._version_cache_path).st_mtime except Exception: self._logger.exception("Error while loading version cache from disk") @@ -506,8 +503,6 @@ class SoftwareUpdatePlugin( self._logger.exception("Error parsing in version cache data") def _save_version_cache(self): - import yaml - from octoprint._version import get_versions from octoprint.util import atomic_write @@ -517,13 +512,7 @@ class SoftwareUpdatePlugin( with atomic_write( self._version_cache_path, mode="wt", max_permissions=0o666 ) as file_obj: - yaml.safe_dump( - self._version_cache, - stream=file_obj, - default_flow_style=False, - indent=2, - allow_unicode=True, - ) + yaml.save_to_file(self._version_cache, file=file_obj, pretty=True) self._version_cache_dirty = False self._version_cache_timestamp = time.time() @@ -541,11 +530,8 @@ class SoftwareUpdatePlugin( if not os.path.isfile(self._update_log_path): return - import yaml - try: - with open(self._update_log_path, encoding="utf-8") as f: - data = yaml.safe_load(f) + data = yaml.load_from_file(path=self._update_log_path) except Exception: self._logger.exception("Error while loading update log from disk") else: @@ -575,20 +561,16 @@ class SoftwareUpdatePlugin( self._logger.info("Loaded update log from disk") def _save_update_log(self): - import yaml - from octoprint.util import atomic_write with self._update_log_mutex: with atomic_write( self._update_log_path, mode="wt", max_permissions=0o666 ) as file_obj: - yaml.safe_dump( + yaml.save_to_file( sorted(self._update_log, key=lambda x: x["datetime"]), - stream=file_obj, - default_flow_style=False, - indent=2, - allow_unicode=True, + file=file_obj, + pretty=True, ) self._update_log_dirty = False diff --git a/src/octoprint/printer/profile.py b/src/octoprint/printer/profile.py index 2d16336f9..44b3be3fa 100644 --- a/src/octoprint/printer/profile.py +++ b/src/octoprint/printer/profile.py @@ -150,7 +150,13 @@ import os from os import scandir from octoprint.settings import settings -from octoprint.util import dict_contains_keys, dict_merge, dict_sanitize, is_hidden_path +from octoprint.util import ( + dict_contains_keys, + dict_merge, + dict_sanitize, + is_hidden_path, + yaml, +) class SaveError(Exception): @@ -500,10 +506,7 @@ class PrinterProfileManager: if not os.path.exists(path) or not os.path.isfile(path): return None - import yaml - - with open(path, encoding="utf-8") as f: - profile = yaml.safe_load(f) + profile = yaml.load_from_file(path=path) if profile is None or not isinstance(profile, dict): raise InvalidProfileError("Profile is None or not a dictionary") @@ -535,15 +538,11 @@ class PrinterProfileManager: "Profile %s already exists and not allowed to overwrite" % profile["id"] ) - import yaml - from octoprint.util import atomic_write try: with atomic_write(path, mode="wt", max_permissions=0o666) as f: - yaml.safe_dump( - profile, f, default_flow_style=False, indent=2, allow_unicode=True - ) + yaml.save_to_file(profile, file=f, pretty=True) except Exception as e: self._logger.exception( "Error while trying to save profile %s" % profile["id"] diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 3562ad064..6c1ac15d4 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -1385,6 +1385,10 @@ class Server: @app.before_request def before_request(): g.locale = self._get_locale() + + # used for performance measurement + g.start_time = octoprint.util.monotonic_time() + if self._debug and "perfprofile" in request.args: try: from pyinstrument import Profiler @@ -1408,6 +1412,11 @@ class Server: output_html = g.perfprofiler.output_html() return make_response(output_html) + if hasattr(g, "start_time"): + end_time = octoprint.util.monotonic_time() + duration_ms = int((end_time - g.start_time) * 1000) + response.headers.add("Server-Timing", f"app;dur={duration_ms}") + return response from octoprint.util.jinja import MarkdownFilter diff --git a/src/octoprint/server/api/languages.py b/src/octoprint/server/api/languages.py index 8c86b6386..b7198bc5e 100644 --- a/src/octoprint/server/api/languages.py +++ b/src/octoprint/server/api/languages.py @@ -17,6 +17,7 @@ from octoprint.plugin import plugin_manager from octoprint.server.api import api from octoprint.server.util.flask import no_firstrun_access from octoprint.settings import settings +from octoprint.util import yaml @api.route("/languages", methods=["GET"]) @@ -40,11 +41,8 @@ def getInstalledLanguagePacks(): meta_path = os.path.join(path, "meta.yaml") if os.path.isfile(meta_path): - import yaml - try: - with open(meta_path, encoding="utf-8") as f: - meta = yaml.safe_load(f) + meta = yaml.load_from_file(path=meta_path) except Exception: logging.getLogger(__name__).exception("Could not load %s", meta_path) pass diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index f1063dae3..0440021d8 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -124,6 +124,7 @@ def getSettings(): "streamUrl": s.get(["webcam", "stream"]), "streamRatio": s.get(["webcam", "streamRatio"]), "streamTimeout": s.getInt(["webcam", "streamTimeout"]), + "streamWebrtcIceServers": s.get(["webcam", "streamWebrtcIceServers"]), "snapshotUrl": s.get(["webcam", "snapshot"]), "snapshotTimeout": s.getInt(["webcam", "snapshotTimeout"]), "snapshotSslValidation": s.getBoolean(["webcam", "snapshotSslValidation"]), @@ -528,6 +529,13 @@ def _saveSettings(data): s.set(["webcam", "streamRatio"], data["webcam"]["streamRatio"]) if "streamTimeout" in data["webcam"]: s.setInt(["webcam", "streamTimeout"], data["webcam"]["streamTimeout"]) + if "streamWebrtcIceServers" in data["webcam"] and isinstance( + data["webcam"]["streamWebrtcIceServers"], (list, tuple) + ): + s.set( + ["webcam", "streamWebrtcIceServers"], + data["webcam"]["streamWebrtcIceServers"], + ) if "snapshotUrl" in data["webcam"]: s.set(["webcam", "snapshot"], data["webcam"]["snapshotUrl"]) if "snapshotTimeout" in data["webcam"]: @@ -1093,7 +1101,7 @@ def _saveSettings(data): plugin.on_settings_save(data["plugins"][plugin_id]) except TypeError: logger.warning( - "Could not save settings for plugin {name} ({version}) since it called super(...)".format( + "Could not save settings for plugin {name} ({version}). It may have called super(...)".format( name=plugin._plugin_name, version=plugin._plugin_version ) ) @@ -1104,7 +1112,8 @@ def _saveSettings(data): "Please contact the plugin's author and ask to update the plugin to use a direct call like" ) logger.warning( - "octoprint.plugin.SettingsPlugin.on_settings_save(self, data) instead." + "octoprint.plugin.SettingsPlugin.on_settings_save(self, data) instead.", + exc_info=True, ) except Exception: logger.exception( diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index 0234d22eb..51368b5a1 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -30,7 +30,7 @@ import octoprint.server import octoprint.vendor.flask_principal as flask_principal from octoprint.events import Events, eventManager from octoprint.settings import settings -from octoprint.util import DefaultOrderedDict, deprecated +from octoprint.util import DefaultOrderedDict, deprecated, yaml from octoprint.util.json import JsonEncoding from octoprint.util.net import is_lan_address @@ -1008,13 +1008,10 @@ class PreemptiveCache: return all_data def get_all_data(self): - import yaml - cache_data = None with self._lock: try: - with open(self.cachefile) as f: - cache_data = yaml.safe_load(f) + cache_data = yaml.load_from_file(path=self.cachefile) except OSError as e: import errno @@ -1037,20 +1034,12 @@ class PreemptiveCache: return cache_data.get(root, list()) def set_all_data(self, data): - import yaml - from octoprint.util import atomic_write with self._lock: try: with atomic_write(self.cachefile, "wt", max_permissions=0o666) as handle: - yaml.safe_dump( - data, - handle, - default_flow_style=False, - indent=2, - allow_unicode=True, - ) + yaml.save_to_file(data, file=handle, pretty=True) except Exception: self._logger.exception(f"Error while writing {self.cachefile}") diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index df7b3f763..2d4be1f76 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -20,7 +20,6 @@ __author__ = "Gina Häußge " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" -import copy import fnmatch import logging import os @@ -30,10 +29,17 @@ import time from collections import ChainMap from collections.abc import KeysView -import yaml -import yaml.parser +# noinspection PyCompatibilitys +from yaml import YAMLError -from octoprint.util import CaseInsensitiveSet, atomic_write, dict_merge, is_hidden_path +from octoprint.util import ( + CaseInsensitiveSet, + atomic_write, + dict_merge, + fast_deepcopy, + is_hidden_path, + yaml, +) _APPNAME = "OctoPrint" @@ -225,6 +231,7 @@ default_settings = { "stream": None, "streamRatio": "16:9", "streamTimeout": 5, + "streamWebrtcIceServers": ["stun:stun.l.google.com:19302"], "snapshot": None, "snapshotTimeout": 5, "snapshotSslValidation": True, @@ -518,17 +525,16 @@ class DuplicateFolderPaths(InvalidSettings): class HierarchicalChainMap(ChainMap): - def deep_dict(self, root=None): - if root is None: - root = self + def deep_dict(self): + def deep_dict_inner(root): + return { + key: deep_dict_inner(self.__class__._get_next(key, root)) + if isinstance(value, dict) + else value + for key, value in root.items() + } - result = {} - for key, value in root.items(): - if isinstance(value, dict): - result[key] = self.deep_dict(root=self.__class__._get_next(key, root)) - else: - result[key] = value - return result + return deep_dict_inner(self) def has_path(self, path, only_local=False, only_defaults=False): if only_defaults: @@ -927,9 +933,7 @@ class Settings: @property def effective_yaml(self): - import yaml - - return yaml.safe_dump(self.effective) + return yaml.dump(self.effective) @property def effective_hash(self): @@ -945,9 +949,7 @@ class Settings: @property def config_yaml(self): - import yaml - - return yaml.safe_dump(self._config) + return yaml.dump(self._config) @property def config_hash(self): @@ -999,10 +1001,10 @@ class Settings: if os.path.exists(self._configfile) and os.path.isfile(self._configfile): with open(self._configfile, encoding="utf-8", errors="replace") as f: try: - self._config = yaml.safe_load(f) + self._config = yaml.load_from_file(file=f) self._mtime = self.last_modified - except yaml.YAMLError as e: + except YAMLError as e: details = str(e) if hasattr(e, "problem_mark"): @@ -1066,8 +1068,7 @@ class Settings: if isinstance(overlay, str): if os.path.exists(overlay) and os.path.isfile(overlay): - with open(overlay, encoding="utf-8", errors="replace") as f: - config = yaml.safe_load(f) + config = yaml.load_from_file(path=overlay) elif isinstance(overlay, dict): config = overlay else: @@ -1088,7 +1089,7 @@ class Settings: assert isinstance(overlay, dict) if key is None: - overlay_yaml = yaml.safe_dump(overlay) + overlay_yaml = yaml.dump(overlay) import hashlib hash = hashlib.md5() @@ -1657,13 +1658,7 @@ class Settings: permissions=0o600, max_permissions=0o666, ) as configFile: - yaml.safe_dump( - self._config, - configFile, - default_flow_style=False, - indent=2, - allow_unicode=True, - ) + yaml.save_to_file(self._config, file=configFile) self._dirty = False except Exception: self._logger.exception("Error while saving config.yaml!") @@ -1759,19 +1754,13 @@ class Settings: except KeyError: raise NoSuchSettingsPath() - if preprocessors is not None: - try: - preprocessor = self._get_by_path(path, preprocessors) - except Exception: - pass - - if callable(preprocessor): - value = preprocessor(value) + if callable(preprocessor): + value = preprocessor(value) if do_copy: if isinstance(value, KeysView): value = list(value) - value = copy.deepcopy(value) + value = fast_deepcopy(value) if asdict: results[key] = value diff --git a/src/octoprint/static/js/app/helpers.js b/src/octoprint/static/js/app/helpers.js index ef6ac98e8..4ce150ac0 100644 --- a/src/octoprint/static/js/app/helpers.js +++ b/src/octoprint/static/js/app/helpers.js @@ -1543,6 +1543,10 @@ var copyToClipboard = function (text) { var determineWebcamStreamType = function (streamUrl) { if (streamUrl) { + if (streamUrl.startsWith("webrtc")) { + return "webrtc"; + } + var lastDotPosition = streamUrl.lastIndexOf("."); var firstQuotationSignPosition = streamUrl.indexOf("?"); if ( @@ -1619,3 +1623,82 @@ var deepMerge = function (target, source) { return target; }; + +var isWebRTCAvailable = function () { + return ( + typeof RTCPeerConnection == "function" && + typeof RTCPeerConnection.prototype.addEventListener == "function" && + typeof RTCPeerConnection.prototype.addTransceiver == "function" && + typeof RTCPeerConnection.prototype.createOffer == "function" && + typeof RTCPeerConnection.prototype.setLocalDescription == "function" && + typeof RTCPeerConnection.prototype.removeEventListener == "function" && + typeof RTCPeerConnection.prototype.addEventListener == "function" && + typeof RTCPeerConnection.prototype.setRemoteDescription == "function" + ); +}; + +var negotiateWebRTC = function (streamUrl) { + pc.addTransceiver("video", {direction: "recvonly"}); + pc.addTransceiver("audio", {direction: "recvonly"}); + return pc + .createOffer() + .then(function (offer) { + return pc.setLocalDescription(offer); + }) + .then(function () { + // Wait for ICE gathering to complete + return new Promise(function (resolve) { + if (pc.iceGatheringState === "complete") { + resolve(); + } else { + function checkState() { + if (pc.iceGatheringState === "complete") { + pc.removeEventListener("icegatheringstatechange", checkState); + resolve(); + } + } + pc.addEventListener("icegatheringstatechange", checkState); + } + }); + }) + .then(function () { + var offer = pc.localDescription; + // webrtc://host.com becomes http://host.com + // webrtcs://host.com becomes https://host.com + streamUrl = "http" + streamUrl.slice("webrtc".length); + return $.ajax({ + url: streamUrl, + type: "POST", + dataType: "json", + data: JSON.stringify({ + sdp: offer.sdp, + type: offer.type + }), + contentType: "application/json; charset=UTF-8" + }); + }) + .then(function (response) { + return pc.setRemoteDescription(response); + }) + .catch(function (e) { + console.error(e); + }); +}; + +var startWebRTC = function (videoElement, streamUrl, iceServers) { + var config = { + sdpSemantics: "unified-plan" + }; + if (iceServers) { + config.iceServers = [{urls: iceServers}]; + } + pc = new RTCPeerConnection(config); + pc.addEventListener("track", function (evt) { + if (evt.track.kind == "video") { + videoElement.srcObject = evt.streams[0]; + } + }); + + negotiateWebRTC(streamUrl); + return pc; +}; diff --git a/src/octoprint/static/js/app/viewmodels/control.js b/src/octoprint/static/js/app/viewmodels/control.js index 2fefcef18..553a21715 100644 --- a/src/octoprint/static/js/app/viewmodels/control.js +++ b/src/octoprint/static/js/app/viewmodels/control.js @@ -41,7 +41,9 @@ $(function () { self.webcamLoaded = ko.observable(false); self.webcamMjpgEnabled = ko.observable(false); self.webcamHlsEnabled = ko.observable(false); + self.webcamWebRTCEnabled = ko.observable(false); self.webcamError = ko.observable(false); + self.webRTCPeerConnection = null; self.keycontrolActive = ko.observable(false); self.keycontrolHelpActive = ko.observable(false); @@ -524,6 +526,8 @@ $(function () { self._switchToMjpgWebcam(); } else if (streamType == "hls") { self._switchToHlsWebcam(); + } else if (isWebRTCAvailable() && streamType == "webrtc") { + self._switchToWebRTCWebcam(); } else { throw "Unknown stream type " + streamType; } @@ -708,6 +712,7 @@ $(function () { self.webcamHlsEnabled(false); self.webcamMjpgEnabled(true); + self.webcamWebRTCEnabled(false); } }; @@ -729,6 +734,36 @@ $(function () { self.webcamMjpgEnabled(false); self.webcamHlsEnabled(true); + self.webcamWebRTCEnabled(false); + }; + + self._switchToWebRTCWebcam = function () { + if (!isWebRTCAvailable()) { + return; + } + var video = document.getElementById("webcam_webrtc"); + + // Close any existing, disconnected connection + if ( + self.webRTCPeerConnection != null && + self.webRTCPeerConnection.connectionState != "connected" + ) { + self.webRTCPeerConnection.close(); + self.webRTCPeerConnection = null; + } + + // Open a new connection if necessary + if (self.webRTCPeerConnection == null) { + self.webRTCPeerConnection = startWebRTC( + video, + self.settings.webcam_streamUrl(), + self.settings.webcam_streamWebrtcIceServers() + ); + } + + self.webcamMjpgEnabled(false); + self.webcamHlsEnabled(false); + self.webcamWebRTCEnabled(true); }; } diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js index ab0dfa877..290a43873 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -153,6 +153,7 @@ $(function () { self.webcam_streamUrl = ko.observable(undefined); self.webcam_streamRatio = ko.observable(undefined); self.webcam_streamTimeout = ko.observable(undefined); + self.webcam_streamWebrtcIceServers = ko.observable(undefined); self.webcam_snapshotUrl = ko.observable(undefined); self.webcam_snapshotTimeout = ko.observable(undefined); self.webcam_snapshotSslValidation = ko.observable(undefined); @@ -439,6 +440,7 @@ $(function () { ); var streamType = determineWebcamStreamType(self.webcam_streamUrl()); var webcam_element; + var webrtc_peer_connection; if (streamType == "mjpg") { webcam_element = $(''); } else if (streamType == "hls") { @@ -453,6 +455,17 @@ $(function () { hls.loadSource(self.webcam_streamUrl()); hls.attachMedia(video_element); } + } else if (isWebRTCAvailable() && streamType == "webrtc") { + webcam_element = $( + '