From 1f93b2355a2816918e11a55e61b42010d15a6720 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 7 Oct 2020 13:13:06 +0200 Subject: [PATCH 01/14] =?UTF-8?q?=F0=9F=8E=A8=20Switch=20to=20black=20form?= =?UTF-8?q?atting?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .editorconfig | 16 +- black.toml | 21 + docs/conf.py | 158 +- docs/sphinxext/codeblockext.py | 400 +- docs/sphinxext/onlineinclude.py | 163 +- run | 7 +- setup.cfg | 17 + setup.py | 453 +- src/octoprint/__init__.py | 1136 +- src/octoprint/__main__.py | 5 +- src/octoprint/_version.py | 192 +- src/octoprint/access/groups.py | 1002 +- src/octoprint/access/permissions.py | 643 +- src/octoprint/access/users.py | 2407 ++-- src/octoprint/cli/__init__.py | 307 +- src/octoprint/cli/analysis.py | 111 +- src/octoprint/cli/client.py | 331 +- src/octoprint/cli/config.py | 289 +- src/octoprint/cli/dev.py | 388 +- src/octoprint/cli/plugins.py | 197 +- src/octoprint/cli/server.py | 571 +- src/octoprint/cli/user.py | 239 +- src/octoprint/daemon.py | 275 +- src/octoprint/environment.py | 272 +- src/octoprint/events.py | 794 +- src/octoprint/filemanager/__init__.py | 1666 ++- src/octoprint/filemanager/analysis.py | 738 +- src/octoprint/filemanager/destinations.py | 7 +- src/octoprint/filemanager/storage.py | 3640 +++--- src/octoprint/filemanager/util.py | 387 +- src/octoprint/logging/__init__.py | 243 +- src/octoprint/logging/handlers.py | 263 +- src/octoprint/plugin/__init__.py | 1038 +- src/octoprint/plugin/core.py | 4124 +++--- src/octoprint/plugin/types.py | 3623 +++--- .../action_command_notification/__init__.py | 192 +- .../plugins/action_command_prompt/__init__.py | 404 +- .../plugins/announcements/__init__.py | 1075 +- src/octoprint/plugins/appkeys/__init__.py | 854 +- src/octoprint/plugins/backup/__init__.py | 2259 ++-- src/octoprint/plugins/corewizard/__init__.py | 174 +- .../plugins/corewizard/subwizards.py | 205 +- src/octoprint/plugins/discovery/__init__.py | 1444 ++- .../plugins/errortracking/__init__.py | 321 +- src/octoprint/plugins/gcodeviewer/__init__.py | 107 +- src/octoprint/plugins/logging/__init__.py | 387 +- src/octoprint/plugins/pi_support/__init__.py | 541 +- .../plugins/pluginmanager/__init__.py | 3155 +++-- .../plugins/softwareupdate/__init__.py | 3636 +++--- src/octoprint/plugins/softwareupdate/cli.py | 394 +- .../plugins/softwareupdate/exceptions.py | 64 +- .../scripts/update-octoprint.py | 552 +- .../softwareupdate/updaters/__init__.py | 2 +- .../plugins/softwareupdate/updaters/pip.py | 202 +- .../softwareupdate/updaters/python_updater.py | 40 +- .../updaters/single_file_plugin.py | 102 +- .../softwareupdate/updaters/sleep_a_bit.py | 19 +- .../softwareupdate/updaters/update_script.py | 157 +- src/octoprint/plugins/softwareupdate/util.py | 43 +- .../softwareupdate/version_checks/__init__.py | 43 +- .../version_checks/always_current.py | 13 +- .../version_checks/bitbucket_commit.py | 103 +- .../version_checks/commandline.py | 72 +- .../version_checks/git_commit.py | 128 +- .../version_checks/github_commit.py | 95 +- .../version_checks/github_release.py | 500 +- .../version_checks/httpheader.py | 57 +- .../softwareupdate/version_checks/jsondata.py | 41 +- .../version_checks/never_current.py | 15 +- .../version_checks/pypi_release.py | 152 +- .../version_checks/python_checker.py | 44 +- src/octoprint/plugins/tracking/__init__.py | 931 +- .../plugins/virtual_printer/__init__.py | 222 +- .../plugins/virtual_printer/virtual.py | 3348 ++--- src/octoprint/printer/__init__.py | 1338 +- src/octoprint/printer/estimation.py | 406 +- src/octoprint/printer/profile.py | 1112 +- src/octoprint/printer/standard.py | 3421 ++--- src/octoprint/server/__init__.py | 4497 ++++--- src/octoprint/server/api/__init__.py | 917 +- src/octoprint/server/api/access.py | 458 +- src/octoprint/server/api/connection.py | 127 +- src/octoprint/server/api/files.py | 1673 ++- src/octoprint/server/api/job.py | 108 +- src/octoprint/server/api/languages.py | 238 +- src/octoprint/server/api/printer.py | 657 +- src/octoprint/server/api/printer_profiles.py | 259 +- src/octoprint/server/api/settings.py | 1414 +- src/octoprint/server/api/slicing.py | 367 +- src/octoprint/server/api/system.py | 347 +- src/octoprint/server/api/timelapse.py | 379 +- src/octoprint/server/api/users.py | 23 +- src/octoprint/server/util/__init__.py | 408 +- src/octoprint/server/util/flask.py | 2608 ++-- src/octoprint/server/util/sockjs.py | 1064 +- src/octoprint/server/util/tornado.py | 2397 ++-- src/octoprint/server/util/watchdog.py | 321 +- src/octoprint/server/util/webassets.py | 233 +- src/octoprint/server/views.py | 2379 ++-- src/octoprint/settings.py | 3845 +++--- src/octoprint/slicing/__init__.py | 1367 +- src/octoprint/slicing/exceptions.py | 153 +- src/octoprint/timelapse.py | 1719 +-- src/octoprint/users.py | 41 +- src/octoprint/util/__init__.py | 2536 ++-- src/octoprint/util/comm.py | 10723 +++++++++------- src/octoprint/util/commandline.py | 398 +- src/octoprint/util/connectivity.py | 326 +- src/octoprint/util/dev.py | 103 +- src/octoprint/util/fixes.py | 57 +- src/octoprint/util/gcodeInterpreter.py | 944 +- src/octoprint/util/jinja.py | 367 +- src/octoprint/util/json/__init__.py | 36 +- src/octoprint/util/net.py | 324 +- src/octoprint/util/paths.py | 25 +- src/octoprint/util/pip.py | 962 +- src/octoprint/util/piptestballoon/setup.py | 41 +- src/octoprint/util/platform/__init__.py | 151 +- src/octoprint/util/version.py | 252 +- src/octoprint_client/__init__.py | 632 +- src/octoprint_setuptools/__init__.py | 975 +- tests/_fixups.py | 2 +- tests/access/__init__.py | 2 +- tests/access/_plugins/permissions_plugin.py | 18 +- tests/access/groups/__init__.py | 2 +- tests/access/groups/test_groupmanager.py | 44 +- tests/access/test_permissions.py | 17 +- tests/access/users/__init__.py | 2 +- tests/access/users/test_usermanager.py | 16 +- tests/access/users/test_users.py | 79 +- tests/filemanager/__init__.py | 2 +- tests/filemanager/test_filemanager.py | 1276 +- tests/filemanager/test_localstorage.py | 1632 +-- tests/manual_tests/always_update.py | 114 +- tests/plugin/__init__.py | 2 +- .../_plugins/another_ordered_hook_plugin.py | 10 +- tests/plugin/_plugins/deprecated_plugin.py | 10 +- tests/plugin/_plugins/hook_plugin.py | 6 +- .../plugin/_plugins/mixed_plugin/__init__.py | 12 +- .../_plugins/one_ordered_hook_plugin.py | 10 +- tests/plugin/_plugins/settings_plugin.py | 2 +- tests/plugin/_plugins/startup_plugin.py | 11 +- tests/plugin/test_core.py | 567 +- tests/plugin/test_settings.py | 553 +- tests/plugin/test_types_blueprint.py | 204 +- tests/plugin/test_types_settings.py | 395 +- tests/plugins/__init__.py | 2 +- tests/plugins/pi_support/__init__.py | 2 +- tests/plugins/pi_support/test_pi_support.py | 269 +- .../pluginmanager/test_notification_filter.py | 165 +- tests/printer/__init__.py | 2 +- tests/printer/test_estimation.py | 124 +- tests/server/__init__.py | 3 +- tests/server/api/__init__.py | 2 +- tests/server/api/test_system.py | 8 +- tests/server/util/__init__.py | 2 +- tests/server/util/test_flask.py | 1064 +- tests/server/util/test_tornado.py | 125 +- tests/server/util/test_webassets.py | 44 +- tests/settings/__init__.py | 2 +- tests/settings/test_settings.py | 1033 +- tests/slicing/__init__.py | 2 +- tests/slicing/test_slicingmanager.py | 289 +- tests/test_daemon.py | 950 +- tests/test_octoprint_setuptools.py | 42 +- tests/test_settings.py | 43 +- tests/timelapse/__init__.py | 2 +- tests/timelapse/test_timelapse_helpers.py | 367 +- tests/timelapse/test_timelapse_renderjob.py | 140 +- tests/util/__init__.py | 2 +- tests/util/test_caseinsensitive_set.py | 20 +- tests/util/test_comm.py | 456 +- tests/util/test_comm_helpers.py | 769 +- tests/util/test_counted_event.py | 190 +- tests/util/test_file_helpers.py | 914 +- tests/util/test_jinja.py | 123 +- tests/util/test_misc.py | 125 +- tests/util/test_net.py | 109 +- tests/util/test_pip.py | 203 +- tests/util/test_platform.py | 85 +- tests/util/test_repeated_timer.py | 246 +- tests/util/test_resettable_timer.py | 62 +- tests/util/test_string_helpers.py | 101 +- versioneer.py | 310 +- 184 files changed, 63526 insertions(+), 51203 deletions(-) create mode 100644 black.toml diff --git a/.editorconfig b/.editorconfig index c67a242b4..03b93fba3 100644 --- a/.editorconfig +++ b/.editorconfig @@ -10,10 +10,6 @@ insert_final_newline = true trim_trailing_whitespace = true [**.py] -indent_style = tab -indent_size = 4 - -[src/octoprint/vendor/sockjs/**.py] indent_style = space indent_size = 4 @@ -21,6 +17,18 @@ indent_size = 4 indent_style = space indent_size = 4 +[src/octoprint/static/js/login/**.js] +indent_style = space +indent_size = 4 + +[src/octoprint/static/js/recovery/**.js] +indent_style = space +indent_size = 4 + +[src/octoprint/static/less/octoprint.less] +indent_style = space +indent_size = 2 + [.travis.yml] indent_style = space indent_size = 2 diff --git a/black.toml b/black.toml new file mode 100644 index 000000000..f60471a5d --- /dev/null +++ b/black.toml @@ -0,0 +1,21 @@ +[tool.black] +line-length = 90 +include = ''' + +( + ( + src + | tests + | .github + ).*\.pyi?$ +)|( + setup\.py +) +''' +exclude = ''' + +( + src/octoprint/vendor # we want to still be able to apply patches from upstream w/o + # match issues +) +''' diff --git a/docs/conf.py b/docs/conf.py index e774cb6bb..5363cca75 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -18,8 +18,8 @@ import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath('../src/')) -sys.path.append(os.path.abspath('sphinxext')) +sys.path.insert(0, os.path.abspath("../src/")) +sys.path.append(os.path.abspath("sphinxext")) import octoprint._version from datetime import date @@ -30,32 +30,46 @@ year_current = date.today().year # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = '1.3' +needs_sphinx = "1.3" # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = ['codeblockext', 'onlineinclude', 'sphinx.ext.todo', 'sphinx.ext.autodoc', 'sphinxcontrib.httpdomain', - 'sphinx.ext.napoleon', 'sphinxcontrib.mermaid', 'sphinx.ext.intersphinx'] +extensions = [ + "codeblockext", + "onlineinclude", + "sphinx.ext.todo", + "sphinx.ext.autodoc", + "sphinxcontrib.httpdomain", + "sphinx.ext.napoleon", + "sphinxcontrib.mermaid", + "sphinx.ext.intersphinx", +] todo_include_todos = True -intersphinx_mapping = {'python': ('https://docs.python.org/3', None), - 'python2': ('https://docs.python.org/2', None), - 'pyserial': ('https://pythonhosted.org/pyserial', None)} +intersphinx_mapping = { + "python": ("https://docs.python.org/3", None), + "python2": ("https://docs.python.org/2", None), + "pyserial": ("https://pythonhosted.org/pyserial", None), +} # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] # The suffix of source filenames. -source_suffix = '.rst' +source_suffix = ".rst" # The encoding of source files. -#source_encoding = 'utf-8-sig' +# source_encoding = 'utf-8-sig' # The master toctree document. -master_doc = 'index' +master_doc = "index" # General information about the project. -project = 'OctoPrint' -copyright = '%d-%d, Gina Häußge' % (year_since, year_current) if year_current > year_since else '%d, Gina Häußge' % year_since +project = "OctoPrint" +copyright = ( + "%d-%d, Gina Häußge" % (year_since, year_current) + if year_current > year_since + else "%d, Gina Häußge" % year_since +) # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -68,133 +82,136 @@ release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. -#language = None +# language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: -#today = '' +# today = '' # Else, today_fmt is used as the format for a strftime call. -#today_fmt = '%B %d, %Y' +# today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ['_build'] +exclude_patterns = ["_build"] # The reST default role (used for this markup: `text`) to use for all documents. -#default_role = None +# default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True +# add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). -#add_module_names = True +# add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. -#show_authors = False +# show_authors = False # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' +pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. -#modindex_common_prefix = [] +# modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. -#keep_warnings = False +# keep_warnings = False numfig = True # -- Options for HTML output --------------------------------------------------- import sphinx_rtd_theme -html_theme = 'sphinx_rtd_theme' + +html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # The theme to use for HTML and HTML Help pages. See the documentation for # a list of built-in themes. -#html_theme = "sphinx_rtd_theme" +# html_theme = "sphinx_rtd_theme" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. -#html_theme_options = {} +# html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. -#html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] +# html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". -#html_title = None +# html_title = None # A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None +# html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. -#html_logo = None +# html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. -#html_favicon = None +# html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the built-in static files, # so a file named "default.css" will overwrite the built-in "default.css". -html_static_path = ['_static'] +html_static_path = ["_static"] + def setup(app): app.add_css_file("theme_overrides.css") + # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' +# html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. -#html_use_smartypants = True +# html_use_smartypants = True # Custom sidebar templates, maps document names to template names. -#html_sidebars = {} +# html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. -#html_additional_pages = {} +# html_additional_pages = {} # If false, no module index is generated. -#html_domain_indices = True +# html_domain_indices = True # If false, no index is generated. -#html_use_index = True +# html_use_index = True # If true, the index is split into individual pages for each letter. -#html_split_index = False +# html_split_index = False # If true, links to the reST sources are added to the pages. -#html_show_sourcelink = True +# html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -#html_show_sphinx = True +# html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -#html_show_copyright = True +# html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. -#html_use_opensearch = '' +# html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = None +# html_file_suffix = None # Output file base name for HTML help builder. -htmlhelp_basename = 'OctoPrintDoc' +htmlhelp_basename = "OctoPrintDoc" # -- Options for LaTeX output -------------------------------------------------- -#latex_elements = { +# latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', @@ -203,47 +220,44 @@ htmlhelp_basename = 'OctoPrintDoc' # Additional stuff for the LaTeX preamble. #'preamble': '', -#} +# } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). -#latex_documents = [ +# latex_documents = [ # ('index', 'OctoPrint.tex', 'OctoPrint Documentation', # 'Gina Häußge', 'manual'), -#] +# ] # The name of an image file (relative to this directory) to place at the top of # the title page. -#latex_logo = None +# latex_logo = None # For "manual" documents, if this is true, then top-level headings are parts, # not chapters. -#latex_use_parts = False +# latex_use_parts = False # If true, show page references after internal links. -#latex_show_pagerefs = False +# latex_show_pagerefs = False # If true, show URL addresses after external links. -#latex_show_urls = False +# latex_show_urls = False # Documents to append as an appendix to all manuals. -#latex_appendices = [] +# latex_appendices = [] # If false, no module index is generated. -#latex_domain_indices = True +# latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). -man_pages = [ - ('index', 'octoprint', 'OctoPrint Documentation', - ['Gina Häußge'], 1) -] +man_pages = [("index", "octoprint", "OctoPrint Documentation", ["Gina Häußge"], 1)] # If true, show URL addresses after external links. -#man_show_urls = False +# man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ @@ -252,19 +266,25 @@ man_pages = [ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - ('index', 'OctoPrint', 'OctoPrint Documentation', - 'Gina Häußge', 'OctoPrint', 'One line description of project.', - 'Miscellaneous'), + ( + "index", + "OctoPrint", + "OctoPrint Documentation", + "Gina Häußge", + "OctoPrint", + "One line description of project.", + "Miscellaneous", + ), ] # Documents to append as an appendix to all manuals. -#texinfo_appendices = [] +# texinfo_appendices = [] # If false, no module index is generated. -#texinfo_domain_indices = True +# texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. -#texinfo_show_urls = 'footnote' +# texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. -#texinfo_no_detailmenu = False +# texinfo_no_detailmenu = False diff --git a/docs/sphinxext/codeblockext.py b/docs/sphinxext/codeblockext.py index f36c16a33..8400ddf26 100644 --- a/docs/sphinxext/codeblockext.py +++ b/docs/sphinxext/codeblockext.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'The MIT License ' +__license__ = "The MIT License " __copyright__ = "Copyright (C) 2015 Gina Häußge - Released under terms of the MIT License" from sphinx.directives.code import CodeBlock @@ -21,235 +21,263 @@ from pygments.lexers.python import PythonConsoleLexer from pygments.util import ClassNotFound if False: - # For type annotation - from typing import Any, Dict, List, Tuple # NOQA + # For type annotation + from typing import Any, Dict, List, Tuple # NOQA + def _merge_dict(a, b): - """ - Little helper to merge two dicts a and b on the fly. - """ - result = dict(a) - result.update(b) - return result + """ + Little helper to merge two dicts a and b on the fly. + """ + result = dict(a) + result.update(b) + return result + class literal_block_ext(nodes.General, nodes.FixedTextElement): - """ - Custom node which is basically the same as a :class:`literal_block`, just with whitespace support and introduced - in order to be able to have a custom visitor. - """ + """ + Custom node which is basically the same as a :class:`literal_block`, just with whitespace support and introduced + in order to be able to have a custom visitor. + """ + + @classmethod + def from_literal_block(cls, block): + """ + Factory method constructing an instance exactly copying all attributes over from ``block`` and settings a + custom ``tagname``. + """ + new = literal_block_ext() + for a in ( + "attributes", + "basic_attributes", + "child_text_separator", + "children", + "document", + "known_attributes", + "line", + "list_attributes", + "local_attributes", + "parent", + "rawsource", + "source", + ): + setattr(new, a, getattr(block, a)) + new.tagname = "literal_block_ext" + return new - @classmethod - def from_literal_block(cls, block): - """ - Factory method constructing an instance exactly copying all attributes over from ``block`` and settings a - custom ``tagname``. - """ - new = literal_block_ext() - for a in ("attributes", "basic_attributes", "child_text_separator", "children", "document", "known_attributes", - "line", "list_attributes", "local_attributes", "parent", "rawsource", "source"): - setattr(new, a, getattr(block, a)) - new.tagname = "literal_block_ext" - return new class CodeBlockExt(CodeBlock): - """ - This is basically an extension of a regular :class:`CodeBlock` directive which just supports an additional option - ``whitespace`` which if present will enable (together with everything else in here) to render whitespace in - code blocks. - """ + """ + This is basically an extension of a regular :class:`CodeBlock` directive which just supports an additional option + ``whitespace`` which if present will enable (together with everything else in here) to render whitespace in + code blocks. + """ - option_spec = _merge_dict(CodeBlock.option_spec, dict(whitespace=directives.flag)) + option_spec = _merge_dict(CodeBlock.option_spec, dict(whitespace=directives.flag)) - def run(self): - # type: () -> List[nodes.Node] - # get result from parent implementation - code_block = CodeBlock.run(self) + def run(self): + # type: () -> List[nodes.Node] + # get result from parent implementation + code_block = CodeBlock.run(self) - def find_and_wrap_literal_block(node): - """ - Recursive method to turn all literal blocks located within a node into :class:`literal_block_ext`. - """ + def find_and_wrap_literal_block(node): + """ + Recursive method to turn all literal blocks located within a node into :class:`literal_block_ext`. + """ - if isinstance(node, nodes.container): - # container node => handle all children - children = [] - for child in node.children: - children.append(find_and_wrap_literal_block(child)) - node.children = children - return node + if isinstance(node, nodes.container): + # container node => handle all children + children = [] + for child in node.children: + children.append(find_and_wrap_literal_block(child)) + node.children = children + return node - elif isinstance(node, nodes.literal_block): - # literal block => replace it - return self._wrap_literal_block(node) + elif isinstance(node, nodes.literal_block): + # literal block => replace it + return self._wrap_literal_block(node) - else: - # no idea what that is => leave it alone - return node + else: + # no idea what that is => leave it alone + return node - # replace all created literal_blocks with literal_block_ext instances - return list(map(find_and_wrap_literal_block, code_block)) + # replace all created literal_blocks with literal_block_ext instances + return list(map(find_and_wrap_literal_block, code_block)) + + def _wrap_literal_block(self, node): + literal = literal_block_ext.from_literal_block(node) + literal["whitespace"] = "whitespace" in self.options + return literal - def _wrap_literal_block(self, node): - literal = literal_block_ext.from_literal_block(node) - literal["whitespace"] = "whitespace" in self.options - return literal class PygmentsBridgeExt(object): - """ - Wrapper for :class:`PygmentsBridge`, delegates everything to the wrapped ``bridge`` but :method:`highlight_block`, - which calls the parent implementation for lexer selection, then - """ + """ + Wrapper for :class:`PygmentsBridge`, delegates everything to the wrapped ``bridge`` but :method:`highlight_block`, + which calls the parent implementation for lexer selection, then + """ - def __init__(self, bridge, whitespace): - self._bridge = bridge - self._whitespace = whitespace + def __init__(self, bridge, whitespace): + self._bridge = bridge + self._whitespace = whitespace - def __getattr__(self, item): - return getattr(self._bridge, item) + def __getattr__(self, item): + return getattr(self._bridge, item) - def highlight_block(self, source, lang, opts=None, warn=None, force=False, **kwargs): - if not self._whitespace: - return self._bridge.highlight_block(source, lang, opts=opts, warn=warn, force=force, **kwargs) + def highlight_block(self, source, lang, opts=None, warn=None, force=False, **kwargs): + if not self._whitespace: + return self._bridge.highlight_block( + source, lang, opts=opts, warn=warn, force=force, **kwargs + ) - # We are still here => we need to basically do everything the parent implementation does (and does so in a very - # inextensible way...), but inject the whitespace filter into the used lexer just before the highlighting run - # and remove it afterwards so the lexer can be safely reused. - # - # For this we define a context manager that will allow us to wrap a lexer and modify its filters on the fly to - # include the whitespace filter. + # We are still here => we need to basically do everything the parent implementation does (and does so in a very + # inextensible way...), but inject the whitespace filter into the used lexer just before the highlighting run + # and remove it afterwards so the lexer can be safely reused. + # + # For this we define a context manager that will allow us to wrap a lexer and modify its filters on the fly to + # include the whitespace filter. - class whitespace(object): - def __init__(self, lexer): - self._lexer = lexer - self._orig_filters = lexer.filters - self._orig_tabsize = lexer.tabsize + class whitespace(object): + def __init__(self, lexer): + self._lexer = lexer + self._orig_filters = lexer.filters + self._orig_tabsize = lexer.tabsize - def __enter__(self): - new_filters = list(self._orig_filters) - new_filters.append(VisibleWhitespaceFilter(spaces=True, tabs=True, tabsize=self._lexer.tabsize)) - self._lexer.filters = new_filters - self._lexer.tabsize = 0 - return self._lexer + def __enter__(self): + new_filters = list(self._orig_filters) + new_filters.append( + VisibleWhitespaceFilter( + spaces=True, tabs=True, tabsize=self._lexer.tabsize + ) + ) + self._lexer.filters = new_filters + self._lexer.tabsize = 0 + return self._lexer - def __exit__(self, type, value, traceback): - self._lexer.filters = self._orig_filters - self._lexer.tabsize = self._orig_tabsize + def __exit__(self, type, value, traceback): + self._lexer.filters = self._orig_filters + self._lexer.tabsize = self._orig_tabsize - # Then a ton of copy-pasted code follows. Sadly, we need to do this since we have no way to inject ourselves - # into the highlighting call otherwise - lexer selection and actual call are tightly coupled in the original - # "highlight_block" method, with no means for external code to inject different functionality. - # - # Unless otherwise marked ("MODIFIED"), any code in this method after this line is copied verbatim from the - # implementation of sphinx.highlighting.PygmentsBridge, released under the Simplified BSD License, the copyright - # lies with the respective authors. + # Then a ton of copy-pasted code follows. Sadly, we need to do this since we have no way to inject ourselves + # into the highlighting call otherwise - lexer selection and actual call are tightly coupled in the original + # "highlight_block" method, with no means for external code to inject different functionality. + # + # Unless otherwise marked ("MODIFIED"), any code in this method after this line is copied verbatim from the + # implementation of sphinx.highlighting.PygmentsBridge, released under the Simplified BSD License, the copyright + # lies with the respective authors. - if not isinstance(source, text_type): - source = source.decode() + if not isinstance(source, text_type): + source = source.decode() - # find out which lexer to use - if lang in ('py', 'python'): - if source.startswith('>>>'): - # interactive session - lexer = sphinx.highlighting.lexers['pycon'] - elif not force: - # maybe Python -- try parsing it - if self.try_parse(source): - lexer = sphinx.highlighting.lexers['python'] - else: - lexer = sphinx.highlighting.lexers['none'] - else: - lexer = sphinx.highlighting.lexers['python'] - elif lang in ('python3', 'py3') and source.startswith('>>>'): - # for py3, recognize interactive sessions, but do not try parsing... - lexer = sphinx.highlighting.lexers['pycon3'] - elif lang == 'guess': -# try: - lexer = sphinx.highlighting.guess_lexer(source) -# except Exception: -# lexer = sphinx.highlighting.lexers['none'] - else: - if lang in sphinx.highlighting.lexers: - lexer = sphinx.highlighting.lexers[lang] - else: - try: - lexer = sphinx.highlighting.lexers[lang] = sphinx.highlighting.get_lexer_by_name(lang, **opts or {}) - except ClassNotFound: - if warn: - warn('Pygments lexer name %r is not known' % lang) - lexer = sphinx.highlighting.lexers['none'] - else: - raise - else: - lexer.add_filter('raiseonerror') + # find out which lexer to use + if lang in ("py", "python"): + if source.startswith(">>>"): + # interactive session + lexer = sphinx.highlighting.lexers["pycon"] + elif not force: + # maybe Python -- try parsing it + if self.try_parse(source): + lexer = sphinx.highlighting.lexers["python"] + else: + lexer = sphinx.highlighting.lexers["none"] + else: + lexer = sphinx.highlighting.lexers["python"] + elif lang in ("python3", "py3") and source.startswith(">>>"): + # for py3, recognize interactive sessions, but do not try parsing... + lexer = sphinx.highlighting.lexers["pycon3"] + elif lang == "guess": + # try: + lexer = sphinx.highlighting.guess_lexer(source) + # except Exception: + # lexer = sphinx.highlighting.lexers['none'] + else: + if lang in sphinx.highlighting.lexers: + lexer = sphinx.highlighting.lexers[lang] + else: + try: + lexer = sphinx.highlighting.lexers[ + lang + ] = sphinx.highlighting.get_lexer_by_name(lang, **opts or {}) + except ClassNotFound: + if warn: + warn("Pygments lexer name %r is not known" % lang) + lexer = sphinx.highlighting.lexers["none"] + else: + raise + else: + lexer.add_filter("raiseonerror") - if not isinstance(source, text_type): - source = source.decode() + if not isinstance(source, text_type): + source = source.decode() - # trim doctest options if wanted - if isinstance(lexer, PythonConsoleLexer) and self._bridge.trim_doctest_flags: - source = doctest.blankline_re.sub('', source) - source = doctest.doctestopt_re.sub('', source) + # trim doctest options if wanted + if isinstance(lexer, PythonConsoleLexer) and self._bridge.trim_doctest_flags: + source = doctest.blankline_re.sub("", source) + source = doctest.doctestopt_re.sub("", source) - # highlight via Pygments - formatter = self._bridge.get_formatter(**kwargs) - try: - # MODIFIED: replaced by whitespace wrapped call - with whitespace(lexer) as l: - hlsource = highlight(source, l, formatter) - # /MODIFIED - except ErrorToken: - # this is most probably not the selected language, - # so let it pass unhighlighted + # highlight via Pygments + formatter = self._bridge.get_formatter(**kwargs) + try: + # MODIFIED: replaced by whitespace wrapped call + with whitespace(lexer) as l: + hlsource = highlight(source, l, formatter) + # /MODIFIED + except ErrorToken: + # this is most probably not the selected language, + # so let it pass unhighlighted + + # MODIFIED: replaced by whitespace wrapped call + with whitespace(sphinx.highlighting.lexers["none"]) as l: + hlsource = highlight(source, l, formatter) + # /MODIFIED + return hlsource - # MODIFIED: replaced by whitespace wrapped call - with whitespace(sphinx.highlighting.lexers["none"]) as l: - hlsource = highlight(source, l, formatter) - # /MODIFIED - return hlsource class whitespace_highlighter(object): - """ - Context manager for adapting the used highlighter on a translator for a given node's whitespace properties. - """ - def __init__(self, translator, node): - self.translator = translator - self.node = node + """ + Context manager for adapting the used highlighter on a translator for a given node's whitespace properties. + """ - self._orig_highlighter = self.translator.highlighter + def __init__(self, translator, node): + self.translator = translator + self.node = node - def __enter__(self): - whitespace = self.node["whitespace"] if "whitespace" in self.node else False - if whitespace: - self.translator.highlighter = PygmentsBridgeExt(self._orig_highlighter, whitespace) - return self.translator + self._orig_highlighter = self.translator.highlighter - def __exit__(self, exc_type, exc_val, exc_tb): - self.translator.highlighter = self._orig_highlighter + def __enter__(self): + whitespace = self.node["whitespace"] if "whitespace" in self.node else False + if whitespace: + self.translator.highlighter = PygmentsBridgeExt( + self._orig_highlighter, whitespace + ) + return self.translator + + def __exit__(self, exc_type, exc_val, exc_tb): + self.translator.highlighter = self._orig_highlighter def visit_literal_block_ext(translator, node): - """ - When our custom code block is visited, we temporarily exchange the highlighter used in the translator, call the - visitor for regular literal blocks, then switch back again. - """ - with whitespace_highlighter(translator, node): - translator.visit_literal_block(node) + """ + When our custom code block is visited, we temporarily exchange the highlighter used in the translator, call the + visitor for regular literal blocks, then switch back again. + """ + with whitespace_highlighter(translator, node): + translator.visit_literal_block(node) def depart_literal_block_ext(translator, node): - """ - Just call the depart function for regular literal blocks. - """ - with whitespace_highlighter(translator, node): - translator.depart_literal_block(node) + """ + Just call the depart function for regular literal blocks. + """ + with whitespace_highlighter(translator, node): + translator.depart_literal_block(node) def setup(app): - # custom directive - app.add_directive("code-block-ext", CodeBlockExt) + # custom directive + app.add_directive("code-block-ext", CodeBlockExt) - # custom node type - handler = (visit_literal_block_ext, depart_literal_block_ext) - app.add_node(literal_block_ext, html=handler, latex=handler, text=handler) + # custom node type + handler = (visit_literal_block_ext, depart_literal_block_ext) + app.add_node(literal_block_ext, html=handler, latex=handler, text=handler) - return dict(version="0.1") + return dict(version="0.1") diff --git a/docs/sphinxext/onlineinclude.py b/docs/sphinxext/onlineinclude.py index ed4a1742a..89103719a 100644 --- a/docs/sphinxext/onlineinclude.py +++ b/docs/sphinxext/onlineinclude.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'The MIT License ' +__license__ = "The MIT License " __copyright__ = "Copyright (C) 2015 Gina Häußge - Released under terms of the MIT License" @@ -10,103 +10,118 @@ import codecs import requests from contextlib import closing -from sphinx.directives.code import LiteralIncludeReader, LiteralInclude, dedent_lines, \ - nodes, parselinenos, logger, container_wrapper +from sphinx.directives.code import ( + LiteralIncludeReader, + LiteralInclude, + dedent_lines, + nodes, + parselinenos, + logger, + container_wrapper, +) from sphinx.util.nodes import set_source_info if False: - # For type annotation - from typing import Any, List # NOQA + # For type annotation + from typing import Any, List # NOQA cache = dict() + class OnlineIncludeReader(LiteralIncludeReader): + def read_file(self, filename, location=None): + # type: (unicode, Any) -> List[unicode] - def read_file(self, filename, location=None): - # type: (unicode, Any) -> List[unicode] + global cache + try: + if filename in cache: + lines = cache[filename] + else: + with closing(requests.get(filename, stream=True)) as r: + r.encoding = self.encoding + lines = r.text.splitlines(True) + cache[filename] = lines - global cache - try: - if filename in cache: - lines = cache[filename] - else: - with closing(requests.get(filename, stream=True)) as r: - r.encoding = self.encoding - lines = r.text.splitlines(True) - cache[filename] = lines + if "tab-width" in self.options: + lines = [line.expandtabs(self.options["tab-width"]) for line in lines] - if 'tab-width' in self.options: - lines = [line.expandtabs(self.options['tab-width']) for line in lines] - - return lines - except (IOError, OSError): - raise IOError('Include file %r not found or reading it failed' % filename) - except UnicodeError: - raise UnicodeError('Encoding %r used for reading included file %r seems to ' - 'be wrong, try giving an :encoding: option' % (self.encoding, filename)) + return lines + except (IOError, OSError): + raise IOError("Include file %r not found or reading it failed" % filename) + except UnicodeError: + raise UnicodeError( + "Encoding %r used for reading included file %r seems to " + "be wrong, try giving an :encoding: option" % (self.encoding, filename) + ) class OnlineIncludeDirective(LiteralInclude): + def run(self): + # type: () -> List[nodes.Node] + document = self.state.document + if not document.settings.file_insertion_enabled: + return [ + document.reporter.warning("File insertion disabled", line=self.lineno) + ] + # convert options['diff'] to absolute path + if "diff" in self.options: + _, path = self.env.relfn2path(self.options["diff"]) + self.options["diff"] = path - def run(self): - # type: () -> List[nodes.Node] - document = self.state.document - if not document.settings.file_insertion_enabled: - return [document.reporter.warning('File insertion disabled', - line=self.lineno)] - # convert options['diff'] to absolute path - if 'diff' in self.options: - _, path = self.env.relfn2path(self.options['diff']) - self.options['diff'] = path + try: + location = self.state_machine.get_source_and_line(self.lineno) + url = self.arguments[0] - try: - location = self.state_machine.get_source_and_line(self.lineno) - url = self.arguments[0] + reader = OnlineIncludeReader(url, self.options, self.config) + text, lines = reader.read(location=location) - reader = OnlineIncludeReader(url, self.options, self.config) - text, lines = reader.read(location=location) + retnode = nodes.literal_block(text, text, source=url) + set_source_info(self, retnode) + if self.options.get("diff"): # if diff is set, set udiff + retnode["language"] = "udiff" + elif "language" in self.options: + retnode["language"] = self.options["language"] + retnode["linenos"] = ( + "linenos" in self.options + or "lineno-start" in self.options + or "lineno-match" in self.options + ) + retnode["classes"] += self.options.get("class", []) + extra_args = retnode["highlight_args"] = {} + if "emphasize-lines" in self.options: + hl_lines = parselinenos(self.options["emphasize-lines"], lines) + if any(i >= lines for i in hl_lines): + logger.warning( + "line number spec is out of range(1-%d): %r" + % (lines, self.options["emphasize-lines"]), + location=location, + ) + extra_args["hl_lines"] = [x + 1 for x in hl_lines if x < lines] + extra_args["linenostart"] = reader.lineno_start - retnode = nodes.literal_block(text, text, source=url) - set_source_info(self, retnode) - if self.options.get('diff'): # if diff is set, set udiff - retnode['language'] = 'udiff' - elif 'language' in self.options: - retnode['language'] = self.options['language'] - retnode['linenos'] = ('linenos' in self.options or - 'lineno-start' in self.options or - 'lineno-match' in self.options) - retnode['classes'] += self.options.get('class', []) - extra_args = retnode['highlight_args'] = {} - if 'emphasize-lines' in self.options: - hl_lines = parselinenos(self.options['emphasize-lines'], lines) - if any(i >= lines for i in hl_lines): - logger.warning('line number spec is out of range(1-%d): %r' % - (lines, self.options['emphasize-lines']), - location=location) - extra_args['hl_lines'] = [x + 1 for x in hl_lines if x < lines] - extra_args['linenostart'] = reader.lineno_start + if "caption" in self.options: + caption = self.options["caption"] or self.arguments[0] + retnode = container_wrapper(self, retnode, caption) - if 'caption' in self.options: - caption = self.options['caption'] or self.arguments[0] - retnode = container_wrapper(self, retnode, caption) + # retnode will be note_implicit_target that is linked from caption and numref. + # when options['name'] is provided, it should be primary ID. + self.add_name(retnode) - # retnode will be note_implicit_target that is linked from caption and numref. - # when options['name'] is provided, it should be primary ID. - self.add_name(retnode) - - return [retnode] - except Exception as exc: - return [document.reporter.warning(str(exc), line=self.lineno)] + return [retnode] + except Exception as exc: + return [document.reporter.warning(str(exc), line=self.lineno)] def visit_onlineinclude(translator, node): - translator.visit_literal_block(node) + translator.visit_literal_block(node) + def depart_onlineinclude(translator, node): - translator.depart_literal_block(node) + translator.depart_literal_block(node) + def setup(app): - app.add_directive("onlineinclude", OnlineIncludeDirective) + app.add_directive("onlineinclude", OnlineIncludeDirective) - handler = (visit_onlineinclude, depart_onlineinclude) - app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler) + handler = (visit_onlineinclude, depart_onlineinclude) + app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler) diff --git a/run b/run index f67e9cbfd..74b043d1d 100755 --- a/run +++ b/run @@ -10,17 +10,20 @@ basedir = os.path.dirname(os.path.realpath(__file__)) old = os.path.join(basedir, "octoprint") if os.path.exists(old): # rename left-overs from old file structure - print(""" + print( + """ Found left-overs from old file structure, renaming to "octoprint.backup". Please remove this manually (I don't dare to do so myself since you might have changes in there I don't know anything about). -""") +""" + ) os.rename(old, os.path.join(basedir, "octoprint.backup")) sys.path.insert(0, os.path.join(basedir, "src")) import octoprint + if len(sys.argv) == 1: sys.argv.append("serve") octoprint.main() diff --git a/setup.cfg b/setup.cfg index 6f5421829..7fbbbf532 100644 --- a/setup.cfg +++ b/setup.cfg @@ -14,11 +14,28 @@ parentdir_prefix = lookupfile = .versioneer-lookup [flake8] +max-line-length = 90 ignore = D E W F401 F523 +extend-ignore = E203 exclude = src/octoprint/vendor + +[isort] +multi_line_output = 3 +include_trailing_comma = True +force_grid_wrap = 0 +use_parentheses = True +ensure_newline_before_comments = True +line_length = 90 +skip = + src/octoprint/vendor +known_first_party = + octoprint + octoprint_setuptools + octoprint_client + diff --git a/setup.py b/setup.py index f52aa8d7c..03e8a0895 100644 --- a/setup.py +++ b/setup.py @@ -6,121 +6,113 @@ import os import versioneer import sys + sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "src")) import octoprint_setuptools import setuptools -#----------------------------------------------------------------------------------------------------------------------- +# ---------------------------------------------------------------------------------------- # Supported python versions # we test against 2.7, 3.6 and 3.7, so that's what we'll mark as supported PYTHON_REQUIRES = ">=2.7.9, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, <4" # Requirements for setup.py -SETUP_REQUIRES = [ - "markdown>=3.1,<3.2" # newer versions require Python 3 -] +SETUP_REQUIRES = ["markdown>=3.1,<3.2"] # newer versions require Python 3 # Requirements for our application INSTALL_REQUIRES = [ - # additional OctoPrint plugins that are maintained on a different release cycle - "OctoPrint-FirmwareCheck>=2020.06.22", - "OctoPrint-FileCheck>=2020.07.06", - - # 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 - - "markupsafe>=1.1,<2.0", # Jinja dependency, newer versions require Python 3 - "tornado==5.1.1", # newer versions require Python 3 - "markdown>=3.1,<3.2", # newer versions require Python 3 - "rsa==4.0", # newer versions require Python 3 - "regex!=2018.11.6", # avoid broken 2018.11.6. See #2874 - - # anything below this should be checked on releases for new versions - - "flask>=1.1.2,<2", - "Jinja2>=2.11.2,<3", - "Flask-Login>=0.5,<0.6", # flask-login doesn't use semver & breaks stuff on minor version increases - "Flask-Babel>=1.0,<2", - "Flask-Assets>=2.0,<3", - "werkzeug>=1.0.1,<2", - "itsdangerous>=1.1.0,<2", - "cachelib>=0.1,<1", - "PyYAML>=5.3.1,<6", - "pyserial>=3.4,<4", - "netaddr>=0.7.19,<1", - "watchdog>=0.10.2,<1", - "sarge==0.1.5post0", - "netifaces>=0.10.9,<1", - "pylru>=1.2,<2", - "pkginfo>=1.5.0.1,<2", - "requests>=2.23.0,<3", - "semantic_version>=2.8.5,<3", - "psutil>=5.7,<6", - "Click>=7.1.2,<8", - "feedparser>=5.2.1,<6", - "future>=0.18.2,<1", - "websocket-client>=0.57,<1", - "wrapt>=1.12.1,<2", - "emoji>=0.5.4,<1", - "frozendict>=1.2,<2", - "sentry-sdk>=0.15.1,<1", - "filetype>=1.0.7,<2", - - # vendor bundle dependencies - "unidecode>=0.04.14,<0.05", # dependency of awesome-slugify - "blinker>=1.4,<2" # dependency of flask_principal + # additional OctoPrint plugins that are maintained on a different release cycle + "OctoPrint-FirmwareCheck>=2020.06.22", + "OctoPrint-FileCheck>=2020.07.06", + # 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 + "markupsafe>=1.1,<2.0", # Jinja dependency, newer versions require Python 3 + "tornado==5.1.1", # newer versions require Python 3 + "markdown>=3.1,<3.2", # newer versions require Python 3 + "rsa==4.0", # newer versions require Python 3 + "regex!=2018.11.6", # avoid broken 2018.11.6. See #2874 + # anything below this should be checked on releases for new versions + "flask>=1.1.2,<2", + "Jinja2>=2.11.2,<3", + "Flask-Login>=0.5,<0.6", # flask-login doesn't use semver & breaks stuff on minor version increases + "Flask-Babel>=1.0,<2", + "Flask-Assets>=2.0,<3", + "werkzeug>=1.0.1,<2", + "itsdangerous>=1.1.0,<2", + "cachelib>=0.1,<1", + "PyYAML>=5.3.1,<6", + "pyserial>=3.4,<4", + "netaddr>=0.7.19,<1", + "watchdog>=0.10.2,<1", + "sarge==0.1.5post0", + "netifaces>=0.10.9,<1", + "pylru>=1.2,<2", + "pkginfo>=1.5.0.1,<2", + "requests>=2.23.0,<3", + "semantic_version>=2.8.5,<3", + "psutil>=5.7,<6", + "Click>=7.1.2,<8", + "feedparser>=5.2.1,<6", + "future>=0.18.2,<1", + "websocket-client>=0.57,<1", + "wrapt>=1.12.1,<2", + "emoji>=0.5.4,<1", + "frozendict>=1.2,<2", + "sentry-sdk>=0.15.1,<1", + "filetype>=1.0.7,<2", + # vendor bundled dependencies + "unidecode>=0.04.14,<0.05", # dependency of awesome-slugify + "blinker>=1.4,<2", # dependency of flask_principal ] # Python 2 specific requirements INSTALL_REQUIRES_PYTHON2 = [ - "futures>=3.3,<4", - "monotonic>=1.5,<2", - "scandir>=1.10,<2", - "chainmap>=1.0.3,<2", - "typing>=3.7.4.1,<4" + "futures>=3.3,<4", + "monotonic>=1.5,<2", + "scandir>=1.10,<2", + "chainmap>=1.0.3,<2", + "typing>=3.7.4.1,<4", ] # Python 3 specific requirements -INSTALL_REQUIRES_PYTHON3 = [ - "zeroconf>=0.24,<0.25" -] +INSTALL_REQUIRES_PYTHON3 = ["zeroconf>=0.24,<0.25"] # OSX specific requirements INSTALL_REQUIRES_OSX = [ - "appdirs>=1.4.4", + "appdirs>=1.4.4", ] # Additional requirements for optional install options EXTRA_REQUIRES = dict( - # Dependencies for developing OctoPrint - develop=[ - # Testing dependencies - SEE ALSO tox.ini - "mock>=3.0.5,<4", - "pytest==4.6.10", - "pytest-doctest-custom>=1.0.0,<2", - "ddt", - - # linter - "flake8", - - # profiler - "pyinstrument", - ], - - # Dependencies for developing OctoPrint plugins - plugins=[ - "cookiecutter>=1.7.2,<1.8" - ], - - # Dependencies for building the documentation - Python 3 required! - docs=[ - "sphinx>=3,<4", - "sphinxcontrib-httpdomain", - "sphinxcontrib-mermaid", - "sphinx_rtd_theme", - "readthedocs-sphinx-ext" - ], + # Dependencies for developing OctoPrint + develop=[ + # Testing dependencies + "mock>=3.0.5,<4", + "pytest==4.6.10", + "pytest-doctest-custom>=1.0.0,<2", + "ddt", + # linter + "flake8", + # formatters + "black", + "isort", + # pre-commit + "pre-commit", + # profiler + "pyinstrument", + ], + # Dependencies for developing OctoPrint plugins + plugins=["cookiecutter>=1.7.2,<1.8"], + # Dependencies for building the documentation - Python 3 required! + docs=[ + "sphinx>=3,<4", + "sphinxcontrib-httpdomain", + "sphinxcontrib-mermaid", + "sphinx_rtd_theme", + "readthedocs-sphinx-ext", + ], ) # Dependency links for any of the aforementioned dependencies @@ -128,175 +120,192 @@ DEPENDENCY_LINKS = [] # adapted from https://hynek.me/articles/conditional-python-dependencies/ if int(setuptools.__version__.split(".", 1)[0]) < 18: - # no bdist_wheel support for setuptools < 18 since we build universal wheels and our optional dependencies - # would get lost there - assert "bdist_wheel" not in sys.argv + # no bdist_wheel support for setuptools < 18 since we build universal wheels and our optional dependencies + # would get lost there + assert "bdist_wheel" not in sys.argv - # add optional dependencies for setuptools versions < 18 that don't yet support environment markers - if sys.version_info[0] < 3: - INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON2 - else: - INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON3 + # add optional dependencies for setuptools versions < 18 that don't yet support environment markers + if sys.version_info[0] < 3: + INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON2 + else: + INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON3 - if sys.platform == "darwin": - INSTALL_REQUIRES += INSTALL_REQUIRES_OSX + if sys.platform == "darwin": + INSTALL_REQUIRES += INSTALL_REQUIRES_OSX else: - # environment markers supported - EXTRA_REQUIRES[":python_version < '3'"] = INSTALL_REQUIRES_PYTHON2 - EXTRA_REQUIRES[":python_version >= '3'"] = INSTALL_REQUIRES_PYTHON3 - EXTRA_REQUIRES[":sys_platform == 'darwin'"] = INSTALL_REQUIRES_OSX + # environment markers supported + EXTRA_REQUIRES[":python_version < '3'"] = INSTALL_REQUIRES_PYTHON2 + EXTRA_REQUIRES[":python_version >= '3'"] = INSTALL_REQUIRES_PYTHON3 + EXTRA_REQUIRES[":sys_platform == 'darwin'"] = INSTALL_REQUIRES_OSX -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Anything below here is just command setup and general setup configuration here = os.path.abspath(os.path.dirname(__file__)) + def read_file_contents(path): - import codecs - with codecs.open(path, encoding="utf-8") as f: - return f.read() + import codecs + + with codecs.open(path, encoding="utf-8") as f: + return f.read() + def md_to_html_build_py_factory(files, baseclass): - class md_to_html_build_py(baseclass): - files = dict() + class md_to_html_build_py(baseclass): + files = dict() - def run(self): - print("RUNNING md_to_html_build_py") - if not self.dry_run: - for directory, files in self.files.items(): - target_dir = os.path.join(self.build_lib, directory) - self.mkpath(target_dir) + def run(self): + print("RUNNING md_to_html_build_py") + if not self.dry_run: + for directory, files in self.files.items(): + target_dir = os.path.join(self.build_lib, directory) + self.mkpath(target_dir) - for entry in files: - if isinstance(entry, tuple): - if len(entry) != 2: - continue - source, dest = entry[0], os.path.join(target_dir, entry[1]) - else: - source = entry - dest = os.path.join(target_dir, source + ".html") + for entry in files: + if isinstance(entry, tuple): + if len(entry) != 2: + continue + source, dest = entry[0], os.path.join(target_dir, entry[1]) + else: + source = entry + dest = os.path.join(target_dir, source + ".html") - print("Rendering markdown from {} to {}".format(source, dest)) + print("Rendering markdown from {} to {}".format(source, dest)) - from markdown import markdownFromFile - markdownFromFile(input=source, - output=dest, - encoding="utf-8") - baseclass.run(self) + from markdown import markdownFromFile + + markdownFromFile(input=source, output=dest, encoding="utf-8") + baseclass.run(self) + + return type(md_to_html_build_py)( + md_to_html_build_py.__name__, (md_to_html_build_py,), dict(files=files) + ) - return type(md_to_html_build_py)(md_to_html_build_py.__name__, - (md_to_html_build_py,), - dict(files=files)) def get_cmdclass(): - # make sure these are always available, even when run by dependabot - global versioneer, octoprint_setuptools, md_to_html_build_py_factory + # make sure these are always available, even when run by dependabot + global versioneer, octoprint_setuptools, md_to_html_build_py_factory - cmdclass = versioneer.get_cmdclass() + cmdclass = versioneer.get_cmdclass() - # add clean command - cmdclass.update(dict(clean=octoprint_setuptools.CleanCommand.for_options(source_folder="src", eggs=["OctoPrint*.egg-info"]))) + # add clean command + cmdclass.update( + dict( + clean=octoprint_setuptools.CleanCommand.for_options( + source_folder="src", eggs=["OctoPrint*.egg-info"] + ) + ) + ) - # add translation commands - translation_dir = "translations" - pot_file = os.path.join(translation_dir, "messages.pot") - bundled_dir = os.path.join("src", "octoprint", "translations") - cmdclass.update(octoprint_setuptools.get_babel_commandclasses(pot_file=pot_file, output_dir=translation_dir, pack_name_prefix="OctoPrint-i18n-", pack_path_prefix="", bundled_dir=bundled_dir)) + # add translation commands + translation_dir = "translations" + pot_file = os.path.join(translation_dir, "messages.pot") + bundled_dir = os.path.join("src", "octoprint", "translations") + cmdclass.update( + octoprint_setuptools.get_babel_commandclasses( + pot_file=pot_file, + output_dir=translation_dir, + pack_name_prefix="OctoPrint-i18n-", + pack_path_prefix="", + bundled_dir=bundled_dir, + ) + ) - cmdclass["build_py"] = md_to_html_build_py_factory({ - "octoprint/templates/_data": [ - "AUTHORS.md", - "SUPPORTERS.md", - "THIRDPARTYLICENSES.md", - ] - }, cmdclass["build_py"] if "build_py" in cmdclass else _build_py) + cmdclass["build_py"] = md_to_html_build_py_factory( + { + "octoprint/templates/_data": [ + "AUTHORS.md", + "SUPPORTERS.md", + "THIRDPARTYLICENSES.md", + ] + }, + cmdclass["build_py"] if "build_py" in cmdclass else _build_py, + ) - return cmdclass + return cmdclass def params(): - # make sure these are always available, even when run by dependabot - global versioneer, get_cmdclass, read_file_contents, here, \ - PYTHON_REQUIRES, SETUP_REQUIRES, INSTALL_REQUIRES, EXTRA_REQUIRES, DEPENDENCY_LINKS + # make sure these are always available, even when run by dependabot + global versioneer, get_cmdclass, read_file_contents, here, PYTHON_REQUIRES, SETUP_REQUIRES, INSTALL_REQUIRES, EXTRA_REQUIRES, DEPENDENCY_LINKS - name = "OctoPrint" - version = versioneer.get_version() - cmdclass = get_cmdclass() + name = "OctoPrint" + version = versioneer.get_version() + cmdclass = get_cmdclass() - description = "The snappy web interface for your 3D printer" - long_description = read_file_contents(os.path.join(here, "README.md")) - long_description_content_type = "text/markdown" + description = "The snappy web interface for your 3D printer" + long_description = read_file_contents(os.path.join(here, "README.md")) + long_description_content_type = "text/markdown" - python_requires = PYTHON_REQUIRES - setup_requires = SETUP_REQUIRES - install_requires = INSTALL_REQUIRES - extras_require = EXTRA_REQUIRES - dependency_links = DEPENDENCY_LINKS + python_requires = PYTHON_REQUIRES + setup_requires = SETUP_REQUIRES + install_requires = INSTALL_REQUIRES + extras_require = EXTRA_REQUIRES + dependency_links = DEPENDENCY_LINKS - classifiers = [ - "Development Status :: 5 - Production/Stable", - "Environment :: Web Environment", - "Framework :: Flask", - "Intended Audience :: Developers", - "Intended Audience :: Education", - "Intended Audience :: End Users/Desktop", - "Intended Audience :: Manufacturing", - "Intended Audience :: Other Audience", - "Intended Audience :: Science/Research", - "License :: OSI Approved :: GNU Affero General Public License v3", - "Natural Language :: English", - "Natural Language :: German", - "Operating System :: OS Independent", - "Programming Language :: Python", - "Programming Language :: Python :: 2", - "Programming Language :: Python :: 2.7", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.6", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: Implementation :: CPython", - "Programming Language :: JavaScript", - "Topic :: Printing", - "Topic :: System :: Monitoring" - ] - author = "Gina Häußge" - author_email = "gina@octoprint.org" - url = "https://octoprint.org" - license = "GNU Affero General Public License v3" - keywords = "3dprinting 3dprinter 3d-printing 3d-printer octoprint" + classifiers = [ + "Development Status :: 5 - Production/Stable", + "Environment :: Web Environment", + "Framework :: Flask", + "Intended Audience :: Developers", + "Intended Audience :: Education", + "Intended Audience :: End Users/Desktop", + "Intended Audience :: Manufacturing", + "Intended Audience :: Other Audience", + "Intended Audience :: Science/Research", + "License :: OSI Approved :: GNU Affero General Public License v3", + "Natural Language :: English", + "Natural Language :: German", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 2", + "Programming Language :: Python :: 2.7", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: JavaScript", + "Topic :: Printing", + "Topic :: System :: Monitoring", + ] + author = "Gina Häußge" + author_email = "gina@octoprint.org" + url = "https://octoprint.org" + license = "GNU Affero General Public License v3" + keywords = "3dprinting 3dprinter 3d-printing 3d-printer octoprint" - project_urls={ - "Community Forum": "https://community.octoprint.org", - "Bug Reports": "https://github.com/foosel/OctoPrint/issues", - "Source": "https://github.com/foosel/OctoPrint", - "Funding": "https://donate.octoprint.org" - } + project_urls = { + "Community Forum": "https://community.octoprint.org", + "Bug Reports": "https://github.com/foosel/OctoPrint/issues", + "Source": "https://github.com/foosel/OctoPrint", + "Funding": "https://donate.octoprint.org", + } - packages = setuptools.find_packages(where="src") - package_dir = { - "": "src", - } - package_data = { - "octoprint": octoprint_setuptools.package_data_dirs('src/octoprint', - ['static', 'templates', 'plugins', 'translations']) - + ['util/piptestballoon/setup.py'] - } + packages = setuptools.find_packages(where="src") + package_dir = { + "": "src", + } + package_data = { + "octoprint": octoprint_setuptools.package_data_dirs( + "src/octoprint", ["static", "templates", "plugins", "translations"] + ) + + ["util/piptestballoon/setup.py"] + } - include_package_data = True - zip_safe = False + include_package_data = True + zip_safe = False - if os.environ.get('READTHEDOCS', None) == 'True': - # we can't tell read the docs to please perform a pip install -e .[docs], so we help - # it a bit here by explicitly adding the development dependencies, which include our - # documentation dependencies - install_requires = install_requires + extras_require['docs'] + if os.environ.get("READTHEDOCS", None) == "True": + # we can't tell read the docs to please perform a pip install -e .[docs], so we help + # it a bit here by explicitly adding the development dependencies, which include our + # documentation dependencies + install_requires = install_requires + extras_require["docs"] - entry_points = { - "console_scripts": [ - "octoprint = octoprint:main" - ] - } + entry_points = {"console_scripts": ["octoprint = octoprint:main"]} + + return locals() - return locals() setuptools.setup(**params()) diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index baead2718..0db6c3dc9 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -7,15 +7,16 @@ import sys import logging as log import os -#~~ version +# ~~ version from ._version import get_versions + versions = get_versions() -__version__ = versions['version'] -__branch__ = versions.get('branch', None) +__version__ = versions["version"] +__branch__ = versions.get("branch", None) __display_version__ = __version__ -__revision__ = versions.get('full-revisionid', versions.get('full', None)) +__revision__ = versions.get("full-revisionid", versions.get("full", None)) del versions del get_versions @@ -30,637 +31,756 @@ urllib3_ssl = True version_info = sys.version_info if version_info.major == 2 and version_info.minor <= 7 and version_info.micro < 9: - try: - # make sure our requests version of urllib3 is properly patched (if possible) - import requests.packages.urllib3.contrib.pyopenssl - requests.packages.urllib3.contrib.pyopenssl.inject_into_urllib3() - except ImportError: - urllib3_ssl = False + try: + # make sure our requests version of urllib3 is properly patched (if possible) + import requests.packages.urllib3.contrib.pyopenssl - try: - import urllib3 + requests.packages.urllib3.contrib.pyopenssl.inject_into_urllib3() + except ImportError: + urllib3_ssl = False - # only proceed if urllib3 is even installed on its own - try: - # urllib3 is there, let's patch that too - import urllib3.contrib.pyopenssl - urllib3.contrib.pyopenssl.inject_into_urllib3() - except ImportError: - urllib3_ssl = False - except ImportError: - pass + try: + import urllib3 + + # only proceed if urllib3 is even installed on its own + try: + # urllib3 is there, let's patch that too + import urllib3.contrib.pyopenssl + + urllib3.contrib.pyopenssl.inject_into_urllib3() + except ImportError: + urllib3_ssl = False + except ImportError: + pass elif version_info.major == 3 and version_info.minor >= 8 and sys.platform == "win32": - # Python 3.8 makes proactor event loop the default on Windows, Tornado doesn't like that - # - # see https://github.com/tornadoweb/tornado/issues/2608 - import asyncio - asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) + # Python 3.8 makes proactor event loop the default on Windows, Tornado doesn't like that + # + # see https://github.com/tornadoweb/tornado/issues/2608 + import asyncio + + asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) del version_info -#~~ custom exceptions +# ~~ custom exceptions + class FatalStartupError(Exception): - def __init__(self, message, cause=None): - self.cause = cause - Exception.__init__(self, message) + def __init__(self, message, cause=None): + self.cause = cause + Exception.__init__(self, message) - def __str__(self): - result = Exception.__str__(self) - if self.cause: - return "{}: {}".format(result, str(self.cause)) - else: - return result + def __str__(self): + result = Exception.__str__(self) + if self.cause: + return "{}: {}".format(result, str(self.cause)) + else: + return result -#~~ init methods to bring up platform -def init_platform(basedir, configfile, use_logging_file=True, logging_file=None, - logging_config=None, debug=False, verbosity=0, uncaught_logger=None, - uncaught_handler=None, safe_mode=False, ignore_blacklist=False, after_preinit_logging=None, - after_settings_init=None, after_logging=None, after_safe_mode=None, after_settings_valid=None, - after_event_manager=None, after_connectivity_checker=None, - after_plugin_manager=None, after_environment_detector=None): - kwargs = {} +# ~~ init methods to bring up platform - logger, recorder = preinit_logging(debug, verbosity, uncaught_logger, uncaught_handler) - kwargs["logger"] = logger - kwargs["recorder"] = recorder - if callable(after_preinit_logging): - after_preinit_logging(**kwargs) +def init_platform( + basedir, + configfile, + use_logging_file=True, + logging_file=None, + logging_config=None, + debug=False, + verbosity=0, + uncaught_logger=None, + uncaught_handler=None, + safe_mode=False, + ignore_blacklist=False, + after_preinit_logging=None, + after_settings_init=None, + after_logging=None, + after_safe_mode=None, + after_settings_valid=None, + after_event_manager=None, + after_connectivity_checker=None, + after_plugin_manager=None, + after_environment_detector=None, +): + kwargs = {} - try: - settings = init_settings(basedir, configfile) - except Exception as ex: - raise FatalStartupError("Could not initialize settings manager", cause=ex) - kwargs["settings"] = settings - if callable(after_settings_init): - after_settings_init(**kwargs) + logger, recorder = preinit_logging( + debug, verbosity, uncaught_logger, uncaught_handler + ) + kwargs["logger"] = logger + kwargs["recorder"] = recorder - try: - logger = init_logging(settings, - use_logging_file=use_logging_file, - logging_file=logging_file, - default_config=logging_config, - debug=debug, - verbosity=verbosity, - uncaught_logger=uncaught_logger, - uncaught_handler=uncaught_handler) - except Exception as ex: - raise FatalStartupError("Could not initialize logging", cause=ex) + if callable(after_preinit_logging): + after_preinit_logging(**kwargs) - kwargs["logger"] = logger - if callable(after_logging): - after_logging(**kwargs) + try: + settings = init_settings(basedir, configfile) + except Exception as ex: + raise FatalStartupError("Could not initialize settings manager", cause=ex) + kwargs["settings"] = settings + if callable(after_settings_init): + after_settings_init(**kwargs) - settings_start_once_in_safemode = "settings" if settings.getBoolean(["server", "startOnceInSafeMode"]) else None - settings_incomplete_startup_safemode = "incomplete_startup" \ - if settings.getBoolean(["server", "incompleteStartup"]) \ - and not settings.getBoolean(["server", "ignoreIncompleteStartup"]) \ - else None - safe_mode = safe_mode or settings_start_once_in_safemode or settings_incomplete_startup_safemode - kwargs["safe_mode"] = safe_mode - if callable(after_safe_mode): - after_safe_mode(**kwargs) + try: + logger = init_logging( + settings, + use_logging_file=use_logging_file, + logging_file=logging_file, + default_config=logging_config, + debug=debug, + verbosity=verbosity, + uncaught_logger=uncaught_logger, + uncaught_handler=uncaught_handler, + ) + except Exception as ex: + raise FatalStartupError("Could not initialize logging", cause=ex) - # now before we continue, let's make sure *all* our folders are sane - try: - settings.sanity_check_folders() - except Exception as ex: - raise FatalStartupError("Configured folders didn't pass sanity check", cause=ex) - if callable(after_settings_valid): - after_settings_valid(**kwargs) + kwargs["logger"] = logger + if callable(after_logging): + after_logging(**kwargs) - try: - event_manager = init_event_manager(settings) - except Exception as ex: - raise FatalStartupError("Could not initialize event manager", cause=ex) + settings_start_once_in_safemode = ( + "settings" if settings.getBoolean(["server", "startOnceInSafeMode"]) else None + ) + settings_incomplete_startup_safemode = ( + "incomplete_startup" + if settings.getBoolean(["server", "incompleteStartup"]) + and not settings.getBoolean(["server", "ignoreIncompleteStartup"]) + else None + ) + safe_mode = ( + safe_mode + or settings_start_once_in_safemode + or settings_incomplete_startup_safemode + ) + kwargs["safe_mode"] = safe_mode + if callable(after_safe_mode): + after_safe_mode(**kwargs) - kwargs["event_manager"] = event_manager - if callable(after_event_manager): - after_event_manager(**kwargs) + # now before we continue, let's make sure *all* our folders are sane + try: + settings.sanity_check_folders() + except Exception as ex: + raise FatalStartupError("Configured folders didn't pass sanity check", cause=ex) + if callable(after_settings_valid): + after_settings_valid(**kwargs) - try: - connectivity_checker = init_connectivity_checker(settings, event_manager) - except Exception as ex: - raise FatalStartupError("Could not initialize connectivity checker", cause=ex) + try: + event_manager = init_event_manager(settings) + except Exception as ex: + raise FatalStartupError("Could not initialize event manager", cause=ex) - kwargs["connectivity_checker"] = connectivity_checker - if callable(after_connectivity_checker): - after_connectivity_checker(**kwargs) + kwargs["event_manager"] = event_manager + if callable(after_event_manager): + after_event_manager(**kwargs) - try: - plugin_manager = init_pluginsystem(settings, - safe_mode=safe_mode, - ignore_blacklist=ignore_blacklist, - connectivity_checker=connectivity_checker) - except Exception as ex: - raise FatalStartupError("Could not initialize plugin manager", cause=ex) + try: + connectivity_checker = init_connectivity_checker(settings, event_manager) + except Exception as ex: + raise FatalStartupError("Could not initialize connectivity checker", cause=ex) - kwargs["plugin_manager"] = plugin_manager - if callable(after_plugin_manager): - after_plugin_manager(**kwargs) + kwargs["connectivity_checker"] = connectivity_checker + if callable(after_connectivity_checker): + after_connectivity_checker(**kwargs) - try: - environment_detector = init_environment_detector(plugin_manager) - except Exception as ex: - raise FatalStartupError("Could not initialize environment detector", cause=ex) + try: + plugin_manager = init_pluginsystem( + settings, + safe_mode=safe_mode, + ignore_blacklist=ignore_blacklist, + connectivity_checker=connectivity_checker, + ) + except Exception as ex: + raise FatalStartupError("Could not initialize plugin manager", cause=ex) - kwargs["environment_detector"] = environment_detector - if callable(after_environment_detector): - after_environment_detector(**kwargs) + kwargs["plugin_manager"] = plugin_manager + if callable(after_plugin_manager): + after_plugin_manager(**kwargs) - return settings, logger, safe_mode, event_manager, connectivity_checker, plugin_manager, environment_detector + try: + environment_detector = init_environment_detector(plugin_manager) + except Exception as ex: + raise FatalStartupError("Could not initialize environment detector", cause=ex) + + kwargs["environment_detector"] = environment_detector + if callable(after_environment_detector): + after_environment_detector(**kwargs) + + return ( + settings, + logger, + safe_mode, + event_manager, + connectivity_checker, + plugin_manager, + environment_detector, + ) def init_settings(basedir, configfile): - """Inits the settings instance based on basedir and configfile to use.""" + """Inits the settings instance based on basedir and configfile to use.""" - from octoprint.settings import settings, InvalidSettings - try: - return settings(init=True, basedir=basedir, configfile=configfile) - except InvalidSettings as e: - message = "Error parsing the configuration file, it appears to be invalid YAML." - if e.line is not None and e.column is not None: - message += " The parser reported an error on line {}, column {}.".format(e.line, e.column) - raise FatalStartupError(message) + from octoprint.settings import settings, InvalidSettings + + try: + return settings(init=True, basedir=basedir, configfile=configfile) + except InvalidSettings as e: + message = "Error parsing the configuration file, it appears to be invalid YAML." + if e.line is not None and e.column is not None: + message += " The parser reported an error on line {}, column {}.".format( + e.line, e.column + ) + raise FatalStartupError(message) -def preinit_logging(debug=False, verbosity=0, uncaught_logger=None, uncaught_handler=None): - config = { - "version": 1, - "formatters": { - "simple": { - "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s" - } - }, - "handlers": { - "console": { - "class": "logging.StreamHandler", - "level": "DEBUG", - "formatter": "simple", - "stream": "ext://sys.stdout" - } - }, - "loggers": { - "octoprint": { - "level": "DEBUG" if debug else "INFO" - }, - "octoprint.util": { - "level": "INFO" - } - }, - "root": { - "level": "WARN", - "handlers": ["console"] - } - } +def preinit_logging( + debug=False, verbosity=0, uncaught_logger=None, uncaught_handler=None +): + config = { + "version": 1, + "formatters": { + "simple": {"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"} + }, + "handlers": { + "console": { + "class": "logging.StreamHandler", + "level": "DEBUG", + "formatter": "simple", + "stream": "ext://sys.stdout", + } + }, + "loggers": { + "octoprint": {"level": "DEBUG" if debug else "INFO"}, + "octoprint.util": {"level": "INFO"}, + }, + "root": {"level": "WARN", "handlers": ["console"]}, + } - logger = set_logging_config(config, debug, verbosity, uncaught_logger, uncaught_handler) + logger = set_logging_config( + config, debug, verbosity, uncaught_logger, uncaught_handler + ) - from octoprint.logging.handlers import RecordingLogHandler - recorder = RecordingLogHandler(level=log.DEBUG) - log.getLogger().addHandler(recorder) + from octoprint.logging.handlers import RecordingLogHandler - return logger, recorder + recorder = RecordingLogHandler(level=log.DEBUG) + log.getLogger().addHandler(recorder) + + return logger, recorder -def init_logging(settings, use_logging_file=True, logging_file=None, default_config=None, debug=False, verbosity=0, uncaught_logger=None, uncaught_handler=None): - """Sets up logging.""" +def init_logging( + settings, + use_logging_file=True, + logging_file=None, + default_config=None, + debug=False, + verbosity=0, + uncaught_logger=None, + uncaught_handler=None, +): + """Sets up logging.""" - import os + import os - from octoprint.util import dict_merge + from octoprint.util import dict_merge - # default logging configuration - if default_config is None: - default_config = { - "version": 1, - "formatters": { - "simple": { - "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s" - }, - "serial": { - "format": "%(asctime)s - %(message)s" - }, - "timings": { - "format": "%(asctime)s - %(message)s" - }, - "timingscsv": { - "format": "%(asctime)s;%(func)s;%(timing)f" - } - }, - "handlers": { - "console": { - "class": "octoprint.logging.handlers.OctoPrintStreamHandler", - "level": "DEBUG", - "formatter": "simple", - "stream": "ext://sys.stdout" - }, - "file": { - "class": "octoprint.logging.handlers.OctoPrintLogHandler", - "level": "DEBUG", - "formatter": "simple", - "when": "D", - "backupCount": 6, - "filename": os.path.join(settings.getBaseFolder("logs"), "octoprint.log") - }, - "serialFile": { - "class": "octoprint.logging.handlers.SerialLogHandler", - "level": "DEBUG", - "formatter": "serial", - "backupCount": 3, - "filename": os.path.join(settings.getBaseFolder("logs"), "serial.log"), - "delay": True - }, - "pluginTimingsFile": { - "class": "octoprint.logging.handlers.PluginTimingsLogHandler", - "level": "DEBUG", - "formatter": "timings", - "backupCount": 3, - "filename": os.path.join(settings.getBaseFolder("logs"), "plugintimings.log"), - "delay": True - }, - "pluginTimingsCsvFile": { - "class": "octoprint.logging.handlers.PluginTimingsLogHandler", - "level": "DEBUG", - "formatter": "timingscsv", - "backupCount": 3, - "filename": os.path.join(settings.getBaseFolder("logs"), "plugintimings.csv"), - "delay": True - } - }, - "loggers": { - "SERIAL": { - "level": "INFO", - "handlers": ["serialFile"], - "propagate": False - }, - "PLUGIN_TIMINGS": { - "level": "INFO", - "handlers": ["pluginTimingsFile", "pluginTimingsCsvFile"], - "propagate": False - }, - "PLUGIN_TIMINGS.octoprint.plugin": { - "level": "INFO" - }, - "octoprint": { - "level": "INFO" - }, - "octoprint.util": { - "level": "INFO" - }, - "octoprint.plugins": { - "level": "INFO" - } - }, - "root": { - "level": "WARN", - "handlers": ["console", "file"] - } - } + # default logging configuration + if default_config is None: + default_config = { + "version": 1, + "formatters": { + "simple": { + "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s" + }, + "serial": {"format": "%(asctime)s - %(message)s"}, + "timings": {"format": "%(asctime)s - %(message)s"}, + "timingscsv": {"format": "%(asctime)s;%(func)s;%(timing)f"}, + }, + "handlers": { + "console": { + "class": "octoprint.logging.handlers.OctoPrintStreamHandler", + "level": "DEBUG", + "formatter": "simple", + "stream": "ext://sys.stdout", + }, + "file": { + "class": "octoprint.logging.handlers.OctoPrintLogHandler", + "level": "DEBUG", + "formatter": "simple", + "when": "D", + "backupCount": 6, + "filename": os.path.join( + settings.getBaseFolder("logs"), "octoprint.log" + ), + }, + "serialFile": { + "class": "octoprint.logging.handlers.SerialLogHandler", + "level": "DEBUG", + "formatter": "serial", + "backupCount": 3, + "filename": os.path.join( + settings.getBaseFolder("logs"), "serial.log" + ), + "delay": True, + }, + "pluginTimingsFile": { + "class": "octoprint.logging.handlers.PluginTimingsLogHandler", + "level": "DEBUG", + "formatter": "timings", + "backupCount": 3, + "filename": os.path.join( + settings.getBaseFolder("logs"), "plugintimings.log" + ), + "delay": True, + }, + "pluginTimingsCsvFile": { + "class": "octoprint.logging.handlers.PluginTimingsLogHandler", + "level": "DEBUG", + "formatter": "timingscsv", + "backupCount": 3, + "filename": os.path.join( + settings.getBaseFolder("logs"), "plugintimings.csv" + ), + "delay": True, + }, + }, + "loggers": { + "SERIAL": { + "level": "INFO", + "handlers": ["serialFile"], + "propagate": False, + }, + "PLUGIN_TIMINGS": { + "level": "INFO", + "handlers": ["pluginTimingsFile", "pluginTimingsCsvFile"], + "propagate": False, + }, + "PLUGIN_TIMINGS.octoprint.plugin": {"level": "INFO"}, + "octoprint": {"level": "INFO"}, + "octoprint.util": {"level": "INFO"}, + "octoprint.plugins": {"level": "INFO"}, + }, + "root": {"level": "WARN", "handlers": ["console", "file"]}, + } - if debug or verbosity > 0: - default_config["loggers"]["octoprint"]["level"] = "DEBUG" - default_config["root"]["level"] = "INFO" - if verbosity > 1: - default_config["loggers"]["octoprint.plugins"]["level"] = "DEBUG" - if verbosity > 2: - default_config["root"]["level"] = "DEBUG" + if debug or verbosity > 0: + default_config["loggers"]["octoprint"]["level"] = "DEBUG" + default_config["root"]["level"] = "INFO" + if verbosity > 1: + default_config["loggers"]["octoprint.plugins"]["level"] = "DEBUG" + if verbosity > 2: + default_config["root"]["level"] = "DEBUG" - config = default_config - if use_logging_file: - # further logging configuration from file... - if logging_file is None: - logging_file = os.path.join(settings.getBaseFolder("base"), "logging.yaml") + config = default_config + if use_logging_file: + # further logging configuration from file... + if logging_file is None: + logging_file = os.path.join(settings.getBaseFolder("base"), "logging.yaml") - config_from_file = {} - if os.path.exists(logging_file) and os.path.isfile(logging_file): - import yaml - with io.open(logging_file, 'rt', encoding='utf-8') as f: - config_from_file = yaml.safe_load(f) + config_from_file = {} + if os.path.exists(logging_file) and os.path.isfile(logging_file): + import yaml - # we merge that with the default config - if config_from_file is not None and isinstance(config_from_file, dict): - config = dict_merge(default_config, config_from_file) + with io.open(logging_file, "rt", encoding="utf-8") as f: + config_from_file = yaml.safe_load(f) - # configure logging globally - return set_logging_config(config, debug, verbosity, uncaught_logger, uncaught_handler) + # we merge that with the default config + if config_from_file is not None and isinstance(config_from_file, dict): + config = dict_merge(default_config, config_from_file) + + # configure logging globally + return set_logging_config(config, debug, verbosity, uncaught_logger, uncaught_handler) def set_logging_config(config, debug, verbosity, uncaught_logger, uncaught_handler): - # configure logging globally - import logging.config as logconfig - logconfig.dictConfig(config) + # configure logging globally + import logging.config as logconfig - # make sure we log any warnings - log.captureWarnings(True) + logconfig.dictConfig(config) - import warnings + # make sure we log any warnings + log.captureWarnings(True) - categories = (DeprecationWarning, PendingDeprecationWarning) - if verbosity > 2: - warnings.simplefilter("always") - elif debug or verbosity > 0: - for category in categories: - warnings.simplefilter("always", category=category) + import warnings - # make sure we also log any uncaught exceptions - if uncaught_logger is None: - logger = log.getLogger(__name__) - else: - logger = log.getLogger(uncaught_logger) + categories = (DeprecationWarning, PendingDeprecationWarning) + if verbosity > 2: + warnings.simplefilter("always") + elif debug or verbosity > 0: + for category in categories: + warnings.simplefilter("always", category=category) - if uncaught_handler is None: - def exception_logger(exc_type, exc_value, exc_tb): - logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_tb)) + # make sure we also log any uncaught exceptions + if uncaught_logger is None: + logger = log.getLogger(__name__) + else: + logger = log.getLogger(uncaught_logger) - uncaught_handler = exception_logger - sys.excepthook = uncaught_handler + if uncaught_handler is None: - return logger + def exception_logger(exc_type, exc_value, exc_tb): + logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_tb)) + + uncaught_handler = exception_logger + sys.excepthook = uncaught_handler + + return logger -def init_pluginsystem(settings, safe_mode=False, ignore_blacklist=True, connectivity_checker=None): - """Initializes the plugin manager based on the settings.""" +def init_pluginsystem( + settings, safe_mode=False, ignore_blacklist=True, connectivity_checker=None +): + """Initializes the plugin manager based on the settings.""" - import os + import os - # we need this so that octoprint.plugins is in sys.modules and no warnings are caused when loading bundled plugins - import octoprint.plugins + # we need this so that octoprint.plugins is in sys.modules and no warnings are caused when loading bundled plugins + import octoprint.plugins - logger = log.getLogger(__name__ + ".startup") + logger = log.getLogger(__name__ + ".startup") - plugin_folders = [(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "plugins")), "octoprint.plugins", True), - settings.getBaseFolder("plugins")] - plugin_entry_points = ["octoprint.plugin"] - plugin_disabled_list = settings.get(["plugins", "_disabled"]) + plugin_folders = [ + ( + os.path.abspath( + os.path.join(os.path.dirname(os.path.realpath(__file__)), "plugins") + ), + "octoprint.plugins", + True, + ), + settings.getBaseFolder("plugins"), + ] + plugin_entry_points = ["octoprint.plugin"] + plugin_disabled_list = settings.get(["plugins", "_disabled"]) - plugin_blacklist = [] - if not ignore_blacklist and settings.getBoolean(["server", "pluginBlacklist", "enabled"]): - plugin_blacklist = get_plugin_blacklist(settings, connectivity_checker=connectivity_checker) + plugin_blacklist = [] + if not ignore_blacklist and settings.getBoolean( + ["server", "pluginBlacklist", "enabled"] + ): + plugin_blacklist = get_plugin_blacklist( + settings, connectivity_checker=connectivity_checker + ) - plugin_validators = [] - if safe_mode: - def validator(phase, plugin_info): - if phase in ("before_import", "before_load", "before_enable"): - setattr(plugin_info, "safe_mode_victim", not plugin_info.bundled) - if not plugin_info.bundled: - return False - return True - plugin_validators.append(validator) + plugin_validators = [] + if safe_mode: - compatibility_ignored_list = settings.get(["plugins", "_forcedCompatible"]) + def validator(phase, plugin_info): + if phase in ("before_import", "before_load", "before_enable"): + setattr(plugin_info, "safe_mode_victim", not plugin_info.bundled) + if not plugin_info.bundled: + return False + return True - from octoprint.plugin import plugin_manager - pm = plugin_manager(init=True, - plugin_folders=plugin_folders, - plugin_entry_points=plugin_entry_points, - plugin_disabled_list=plugin_disabled_list, - plugin_blacklist=plugin_blacklist, - plugin_validators=plugin_validators, - compatibility_ignored_list=compatibility_ignored_list) + plugin_validators.append(validator) - settings_overlays = {} - disabled_from_overlays = {} + compatibility_ignored_list = settings.get(["plugins", "_forcedCompatible"]) - def handle_plugin_loaded(name, plugin): - if plugin.instance and hasattr(plugin.instance, "__plugin_settings_overlay__"): - plugin.needs_restart = True + from octoprint.plugin import plugin_manager - # plugin has a settings overlay, inject it - overlay_definition = getattr(plugin.instance, "__plugin_settings_overlay__") - if isinstance(overlay_definition, (tuple, list)): - overlay_definition, order = overlay_definition - else: - order = None + pm = plugin_manager( + init=True, + plugin_folders=plugin_folders, + plugin_entry_points=plugin_entry_points, + plugin_disabled_list=plugin_disabled_list, + plugin_blacklist=plugin_blacklist, + plugin_validators=plugin_validators, + compatibility_ignored_list=compatibility_ignored_list, + ) - overlay = settings.load_overlay(overlay_definition) + settings_overlays = {} + disabled_from_overlays = {} - if "plugins" in overlay and "_disabled" in overlay["plugins"]: - disabled_plugins = overlay["plugins"]["_disabled"] - del overlay["plugins"]["_disabled"] - disabled_from_overlays[name] = (disabled_plugins, order) + def handle_plugin_loaded(name, plugin): + if plugin.instance and hasattr(plugin.instance, "__plugin_settings_overlay__"): + plugin.needs_restart = True - settings_overlays[name] = overlay - logger.debug("Found settings overlay on plugin {}".format(name)) + # plugin has a settings overlay, inject it + overlay_definition = getattr(plugin.instance, "__plugin_settings_overlay__") + if isinstance(overlay_definition, (tuple, list)): + overlay_definition, order = overlay_definition + else: + order = None - def handle_plugins_loaded(startup=False, initialize_implementations=True, force_reload=None): - if not startup: - return + overlay = settings.load_overlay(overlay_definition) - from octoprint.util import sv + if "plugins" in overlay and "_disabled" in overlay["plugins"]: + disabled_plugins = overlay["plugins"]["_disabled"] + del overlay["plugins"]["_disabled"] + disabled_from_overlays[name] = (disabled_plugins, order) - sorted_disabled_from_overlays = sorted([(key, value[0], value[1]) for key, value in disabled_from_overlays.items()], key=lambda x: (x[2] is None, sv(x[2]), sv(x[0]))) + settings_overlays[name] = overlay + logger.debug("Found settings overlay on plugin {}".format(name)) - disabled_list = pm.plugin_disabled_list - already_processed = [] - for name, addons, _ in sorted_disabled_from_overlays: - if not name in disabled_list and not name.endswith("disabled"): - for addon in addons: - if addon in disabled_list: - continue + def handle_plugins_loaded( + startup=False, initialize_implementations=True, force_reload=None + ): + if not startup: + return - if addon in already_processed: - logger.info("Plugin {} wants to disable plugin {}, but that was already processed".format(name, addon)) + from octoprint.util import sv - if not addon in already_processed and not addon in disabled_list: - disabled_list.append(addon) - logger.info("Disabling plugin {} as defined by plugin {}".format(addon, name)) - already_processed.append(name) + sorted_disabled_from_overlays = sorted( + [(key, value[0], value[1]) for key, value in disabled_from_overlays.items()], + key=lambda x: (x[2] is None, sv(x[2]), sv(x[0])), + ) - def handle_plugin_enabled(name, plugin): - if name in settings_overlays: - settings.add_overlay(settings_overlays[name]) - logger.info("Added settings overlay from plugin {}".format(name)) + disabled_list = pm.plugin_disabled_list + already_processed = [] + for name, addons, _ in sorted_disabled_from_overlays: + if not name in disabled_list and not name.endswith("disabled"): + for addon in addons: + if addon in disabled_list: + continue - pm.on_plugin_loaded = handle_plugin_loaded - pm.on_plugins_loaded = handle_plugins_loaded - pm.on_plugin_enabled = handle_plugin_enabled - pm.reload_plugins(startup=True, initialize_implementations=False) - return pm + if addon in already_processed: + logger.info( + "Plugin {} wants to disable plugin {}, but that was already processed".format( + name, addon + ) + ) + + if not addon in already_processed and not addon in disabled_list: + disabled_list.append(addon) + logger.info( + "Disabling plugin {} as defined by plugin {}".format( + addon, name + ) + ) + already_processed.append(name) + + def handle_plugin_enabled(name, plugin): + if name in settings_overlays: + settings.add_overlay(settings_overlays[name]) + logger.info("Added settings overlay from plugin {}".format(name)) + + pm.on_plugin_loaded = handle_plugin_loaded + pm.on_plugins_loaded = handle_plugins_loaded + pm.on_plugin_enabled = handle_plugin_enabled + pm.reload_plugins(startup=True, initialize_implementations=False) + return pm def get_plugin_blacklist(settings, connectivity_checker=None): - import requests - import os - import time - import yaml + import requests + import os + import time + import yaml - from octoprint.util import bom_aware_open - from octoprint.util.version import is_octoprint_compatible + from octoprint.util import bom_aware_open + from octoprint.util.version import is_octoprint_compatible - logger = log.getLogger(__name__ + ".startup") + logger = log.getLogger(__name__ + ".startup") - if connectivity_checker is not None and not connectivity_checker.online: - logger.info("We don't appear to be online, not fetching plugin blacklist") - return [] + if connectivity_checker is not None and not connectivity_checker.online: + logger.info("We don't appear to be online, not fetching plugin blacklist") + return [] - def format_blacklist(entries): - format_entry = lambda x: "{} ({})".format(x[0], x[1]) if isinstance(x, (list, tuple)) and len(x) == 2 \ - else "{} (any)".format(x) - return ", ".join(map(format_entry, entries)) + def format_blacklist(entries): + format_entry = ( + lambda x: "{} ({})".format(x[0], x[1]) + if isinstance(x, (list, tuple)) and len(x) == 2 + else "{} (any)".format(x) + ) + return ", ".join(map(format_entry, entries)) - def process_blacklist(entries): - result = [] + def process_blacklist(entries): + result = [] - if not isinstance(entries, list): - return result + if not isinstance(entries, list): + return result - for entry in entries: - if not "plugin" in entry: - continue + for entry in entries: + if not "plugin" in entry: + continue - if "octoversions" in entry and not is_octoprint_compatible(*entry["octoversions"]): - continue + if "octoversions" in entry and not is_octoprint_compatible( + *entry["octoversions"] + ): + continue - if "version" in entry: - logger.debug("Blacklisted plugin: {}, version: {}".format(entry["plugin"], entry["version"])) - result.append((entry["plugin"], entry["version"])) - elif "versions" in entry: - logger.debug("Blacklisted plugin: {}, versions: {}".format(entry["plugin"], ", ".join(entry["versions"]))) - for version in entry["versions"]: - result.append((entry["plugin"], version)) - else: - logger.debug("Blacklisted plugin: {}".format(entry["plugin"])) - result.append(entry["plugin"]) + if "version" in entry: + logger.debug( + "Blacklisted plugin: {}, version: {}".format( + entry["plugin"], entry["version"] + ) + ) + result.append((entry["plugin"], entry["version"])) + elif "versions" in entry: + logger.debug( + "Blacklisted plugin: {}, versions: {}".format( + entry["plugin"], ", ".join(entry["versions"]) + ) + ) + for version in entry["versions"]: + result.append((entry["plugin"], version)) + else: + logger.debug("Blacklisted plugin: {}".format(entry["plugin"])) + result.append(entry["plugin"]) - return result + return result - def fetch_blacklist_from_cache(path, ttl): - if not os.path.isfile(path): - return None + def fetch_blacklist_from_cache(path, ttl): + if not os.path.isfile(path): + return None - if os.stat(path).st_mtime + ttl < time.time(): - return 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) + with bom_aware_open(path, encoding="utf-8", mode="rt") as f: + result = yaml.safe_load(f) - if isinstance(result, list): - return result + if isinstance(result, list): + return result - def fetch_blacklist_from_url(url, timeout=3, cache=None): - result = [] - try: - r = requests.get(url, timeout=timeout) - result = process_blacklist(r.json()) + def fetch_blacklist_from_url(url, timeout=3, cache=None): + result = [] + try: + r = requests.get(url, timeout=timeout) + result = process_blacklist(r.json()) - if cache is not None: - try: - with bom_aware_open(cache, encoding="utf-8", mode='wt') as f: - yaml.safe_dump(result, f) - except Exception as e: - logger.info("Fetched plugin blacklist but couldn't write it to its cache file: %s", e) - except Exception as e: - logger.info("Unable to fetch plugin blacklist from {}, proceeding without it: {}".format(url, e)) - return result + if cache is not None: + try: + with bom_aware_open(cache, encoding="utf-8", mode="wt") as f: + yaml.safe_dump(result, f) + except Exception as e: + logger.info( + "Fetched plugin blacklist but couldn't write it to its cache file: %s", + e, + ) + except Exception as e: + logger.info( + "Unable to fetch plugin blacklist from {}, proceeding without it: {}".format( + url, e + ) + ) + return result - try: - # first attempt to fetch from cache - cache_path = os.path.join(settings.getBaseFolder("data"), "plugin_blacklist.yaml") - ttl = settings.getInt(["server", "pluginBlacklist", "ttl"]) - blacklist = fetch_blacklist_from_cache(cache_path, ttl) + try: + # first attempt to fetch from cache + cache_path = os.path.join(settings.getBaseFolder("data"), "plugin_blacklist.yaml") + ttl = settings.getInt(["server", "pluginBlacklist", "ttl"]) + blacklist = fetch_blacklist_from_cache(cache_path, ttl) - if blacklist is None: - # no result from the cache, let's fetch it fresh - url = settings.get(["server", "pluginBlacklist", "url"]) - timeout = settings.getFloat(["server", "pluginBlacklist", "timeout"]) - blacklist = fetch_blacklist_from_url(url, timeout=timeout, cache=cache_path) + if blacklist is None: + # no result from the cache, let's fetch it fresh + url = settings.get(["server", "pluginBlacklist", "url"]) + timeout = settings.getFloat(["server", "pluginBlacklist", "timeout"]) + blacklist = fetch_blacklist_from_url(url, timeout=timeout, cache=cache_path) - if blacklist is None: - # still now result, so no blacklist - blacklist = [] + if blacklist is None: + # still now result, so no blacklist + blacklist = [] - if blacklist: - logger.info("Blacklist processing done, " - "adding {} blacklisted plugin versions: {}".format(len(blacklist), - format_blacklist(blacklist))) - else: - logger.info("Blacklist processing done") + if blacklist: + logger.info( + "Blacklist processing done, " + "adding {} blacklisted plugin versions: {}".format( + len(blacklist), format_blacklist(blacklist) + ) + ) + else: + logger.info("Blacklist processing done") - return blacklist - except Exception: - logger.exception("Something went wrong while processing the plugin blacklist. Proceeding without it.") + return blacklist + except Exception: + logger.exception( + "Something went wrong while processing the plugin blacklist. Proceeding without it." + ) def init_event_manager(settings): - from octoprint.events import eventManager - return eventManager() + from octoprint.events import eventManager + + return eventManager() def init_connectivity_checker(settings, event_manager): - from octoprint.events import Events - from octoprint.util import ConnectivityChecker + from octoprint.events import Events + from octoprint.util import ConnectivityChecker - # start regular check if we are connected to the internet - connectivityEnabled = settings.getBoolean(["server", "onlineCheck", "enabled"]) - connectivityInterval = settings.getInt(["server", "onlineCheck", "interval"]) - connectivityHost = settings.get(["server", "onlineCheck", "host"]) - connectivityPort = settings.getInt(["server", "onlineCheck", "port"]) - connectivityName = settings.get(["server", "onlineCheck", "name"]) + # start regular check if we are connected to the internet + connectivityEnabled = settings.getBoolean(["server", "onlineCheck", "enabled"]) + connectivityInterval = settings.getInt(["server", "onlineCheck", "interval"]) + connectivityHost = settings.get(["server", "onlineCheck", "host"]) + connectivityPort = settings.getInt(["server", "onlineCheck", "port"]) + connectivityName = settings.get(["server", "onlineCheck", "name"]) - def on_connectivity_change(old_value, new_value, connection_working=None, resolution_working=None): - event_manager.fire(Events.CONNECTIVITY_CHANGED, payload={"old": old_value, - "new": new_value, - "connection": connection_working, - "resolution": resolution_working}) + def on_connectivity_change( + old_value, new_value, connection_working=None, resolution_working=None + ): + event_manager.fire( + Events.CONNECTIVITY_CHANGED, + payload={ + "old": old_value, + "new": new_value, + "connection": connection_working, + "resolution": resolution_working, + }, + ) - connectivityChecker = ConnectivityChecker(connectivityInterval, - connectivityHost, - port=connectivityPort, - name=connectivityName, - enabled=connectivityEnabled, - on_change=on_connectivity_change) - connectivityChecker.check_immediately() - connectivityChecker.log_full_report() + connectivityChecker = ConnectivityChecker( + connectivityInterval, + connectivityHost, + port=connectivityPort, + name=connectivityName, + enabled=connectivityEnabled, + on_change=on_connectivity_change, + ) + connectivityChecker.check_immediately() + connectivityChecker.log_full_report() - return connectivityChecker + return connectivityChecker def init_environment_detector(plugin_manager): - from octoprint.environment import EnvironmentDetector - return EnvironmentDetector(plugin_manager) + from octoprint.environment import EnvironmentDetector + + return EnvironmentDetector(plugin_manager) + + +# ~~ server main method -#~~ server main method def main(): - import sys + import sys - # os args are gained differently on win32 - try: - from click.utils import get_os_args - args = get_os_args() - except ImportError: - # for whatever reason we are running an older Click version? - args = sys.argv[1:] + # os args are gained differently on win32 + try: + from click.utils import get_os_args - if len(args) >= len(sys.argv): - # Now some ugly preprocessing of our arguments starts. We have a somewhat difficult situation on our hands - # here if we are running under Windows and want to be able to handle utf-8 command line parameters (think - # plugin parameters such as names or something, e.g. for the "dev plugin:new" command) while at the same - # time also supporting sys.argv rewriting for debuggers etc (e.g. PyCharm). - # - # So what we try to do here is solve this... Generally speaking, sys.argv and whatever Windows returns - # for its CommandLineToArgvW win32 function should have the same length. If it doesn't however and - # sys.argv is shorter than the win32 specific command line arguments, obviously stuff was cut off from - # sys.argv which also needs to be cut off of the win32 command line arguments. - # - # So this is what we do here. + args = get_os_args() + except ImportError: + # for whatever reason we are running an older Click version? + args = sys.argv[1:] - # -1 because first entry is the script that was called - sys_args_length = len(sys.argv) - 1 + if len(args) >= len(sys.argv): + # Now some ugly preprocessing of our arguments starts. We have a somewhat difficult situation on our hands + # here if we are running under Windows and want to be able to handle utf-8 command line parameters (think + # plugin parameters such as names or something, e.g. for the "dev plugin:new" command) while at the same + # time also supporting sys.argv rewriting for debuggers etc (e.g. PyCharm). + # + # So what we try to do here is solve this... Generally speaking, sys.argv and whatever Windows returns + # for its CommandLineToArgvW win32 function should have the same length. If it doesn't however and + # sys.argv is shorter than the win32 specific command line arguments, obviously stuff was cut off from + # sys.argv which also needs to be cut off of the win32 command line arguments. + # + # So this is what we do here. - # cut off stuff from the beginning - args = args[-1 * sys_args_length:] if sys_args_length else [] + # -1 because first entry is the script that was called + sys_args_length = len(sys.argv) - 1 - from octoprint.util.fixes import patch_sarge_async_on_py2 - patch_sarge_async_on_py2() + # cut off stuff from the beginning + args = args[-1 * sys_args_length :] if sys_args_length else [] - from octoprint.cli import octo - octo(args=args, prog_name="octoprint", auto_envvar_prefix="OCTOPRINT") + from octoprint.util.fixes import patch_sarge_async_on_py2 + + patch_sarge_async_on_py2() + + from octoprint.cli import octo + + octo(args=args, prog_name="octoprint", auto_envvar_prefix="OCTOPRINT") if __name__ == "__main__": - main() + main() diff --git a/src/octoprint/__main__.py b/src/octoprint/__main__.py index d866f03e0..865fcc44e 100644 --- a/src/octoprint/__main__.py +++ b/src/octoprint/__main__.py @@ -3,5 +3,6 @@ from __future__ import absolute_import, division, print_function, unicode_literals if __name__ == "__main__": - import octoprint - octoprint.main() + import octoprint + + octoprint.main() diff --git a/src/octoprint/_version.py b/src/octoprint/_version.py index 2533e537d..0b44a145a 100644 --- a/src/octoprint/_version.py +++ b/src/octoprint/_version.py @@ -64,12 +64,14 @@ HANDLERS = {} def register_vcs_handler(vcs, method): # decorator """Decorator to mark a method as the handler for a particular VCS.""" + def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f + return decorate @@ -81,9 +83,12 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False): try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None)) + p = subprocess.Popen( + [c] + args, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr else None), + ) break except EnvironmentError: e = sys.exc_info()[1] @@ -116,12 +121,17 @@ def versions_from_parentdir(parentdir_prefix, root, verbose): dirname = os.path.basename(root) if not dirname.startswith(parentdir_prefix): if verbose: - print("guessing rootdir is '%s', but '%s' doesn't start with " - "prefix '%s'" % (root, dirname, parentdir_prefix)) + print( + "guessing rootdir is '%s', but '%s' doesn't start with " + "prefix '%s'" % (root, dirname, parentdir_prefix) + ) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None} + return { + "version": dirname[len(parentdir_prefix) :], + "full-revisionid": None, + "dirty": False, + "error": None, + } @register_vcs_handler("git", "get_keywords") @@ -163,7 +173,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} + tags = {r[len(TAG) :] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d @@ -172,12 +182,15 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = {r for r in refs if re.search(r'\d', r)} + tags = {r for r in refs if re.search(r"\d", r)} if verbose: - print("discarding '%s', no digits" % ",".join(refs-tags)) + print("discarding '%s', no digits" % ",".join(refs - tags)) - branches = [r for r in refs if not r.startswith(TAG) - and r != "HEAD" and not r.startswith("refs/")] + branches = [ + r + for r in refs + if not r.startswith(TAG) and r != "HEAD" and not r.startswith("refs/") + ] if verbose: print("likely branches: %s" % ",".join(sorted(branches))) branch = None @@ -189,22 +202,28 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] + r = ref[len(tag_prefix) :] if verbose: print("picking %s" % r) - result = {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None} + result = { + "version": r, + "full-revisionid": keywords["full"].strip(), + "dirty": False, + "error": None, + } if branch is not None: result["branch"] = branch return result # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags"} + return { + "version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, + "error": "no suitable tags", + } @register_vcs_handler("git", "pieces_from_vcs") @@ -225,10 +244,19 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): GITS = ["git.cmd", "git.exe"] # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out = run_command(GITS, ["describe", "--tags", "--dirty", - "--always", "--long", - "--match", "%s*" % tag_prefix], - cwd=root) + describe_out = run_command( + GITS, + [ + "describe", + "--tags", + "--dirty", + "--always", + "--long", + "--match", + "%s*" % tag_prefix, + ], + cwd=root, + ) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") @@ -251,12 +279,10 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] + git_describe = git_describe[: git_describe.rindex("-dirty")] # figure out our branch - abbrev_ref_out = run_command(GITS, - ["rev-parse", "--abbrev-ref", "HEAD"], - cwd=root) + abbrev_ref_out = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) if abbrev_ref_out is not None and abbrev_ref_out != "HEAD": pieces["branch"] = abbrev_ref_out.strip() @@ -264,11 +290,10 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if "-" in git_describe: # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) + mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) + pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out return pieces # tag @@ -277,10 +302,12 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" - % (full_tag, tag_prefix)) + pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % ( + full_tag, + tag_prefix, + ) return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] + pieces["closest-tag"] = full_tag[len(tag_prefix) :] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) @@ -291,8 +318,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): else: # HEX: no tags pieces["closest-tag"] = None - count_out = run_command(GITS, ["rev-list", "HEAD", "--count"], - cwd=root) + count_out = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits return pieces @@ -309,11 +335,12 @@ def git_parse_lookup_file(path): return [] import re + lookup = [] with io.open(path, "rt", encoding="utf-8") as f: for line in f: - if '#' in line: - line = line[:line.index("#")] + if "#" in line: + line = line[: line.index("#")] line = line.strip() if not line: continue @@ -353,8 +380,7 @@ def git_pieces_from_lookup(lookup, root, verbose, run_command=run_command): if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] - stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], - cwd=root) + stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) if stdout is None: raise NotThisMethod("git rev-parse --abbrev-ref HEAD failed") @@ -365,37 +391,33 @@ def git_pieces_from_lookup(lookup, root, verbose, run_command=run_command): for matcher, render, tag, ref_commit in lookup: if matcher.match(current_branch): if tag is None or ref_commit is None: - raise NotThisMethod("tag or ref_commit is unset for " - "this branch") + raise NotThisMethod("tag or ref_commit is unset for " "this branch") - stdout = run_command(GITS, - ["rev-list", "%s..HEAD" % ref_commit, - "--count"], - cwd=root) + stdout = run_command( + GITS, ["rev-list", "%s..HEAD" % ref_commit, "--count"], cwd=root + ) if stdout is None: - raise NotThisMethod("git rev-list %s..HEAD " - "--count failed" % ref_commit) + raise NotThisMethod( + "git rev-list %s..HEAD " "--count failed" % ref_commit + ) try: num_commits = int(stdout.strip()) except ValueError: - raise NotThisMethod("git rev-list %s..HEAD --count didn't " - "return a valid number" % ref_commit) + raise NotThisMethod( + "git rev-list %s..HEAD --count didn't " + "return a valid number" % ref_commit + ) - stdout = run_command(GITS, - ["rev-parse", "--short", "HEAD"], - cwd=root) + stdout = run_command(GITS, ["rev-parse", "--short", "HEAD"], cwd=root) if stdout is None: - raise NotThisMethod("git describe rev-parse " - "--short HEAD failed") + raise NotThisMethod("git describe rev-parse " "--short HEAD failed") short_hash = stdout.strip() - stdout = run_command(GITS, - ["describe", "--tags", - "--dirty", "--always"], - cwd=root) + stdout = run_command( + GITS, ["describe", "--tags", "--dirty", "--always"], cwd=root + ) if stdout is None: - raise NotThisMethod("git describe --tags --dirty " - "--always failed") + raise NotThisMethod("git describe --tags --dirty " "--always failed") dirty = stdout.strip().endswith("-dirty") stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) @@ -411,7 +433,7 @@ def git_pieces_from_lookup(lookup, root, verbose, run_command=run_command): "closest-tag": tag, "distance": num_commits, "error": None, - "render": render + "render": render, } raise NotThisMethod("no matching lookup definition found") @@ -442,8 +464,7 @@ def render_pep440(pieces): rendered += ".dirty" else: # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) + rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered @@ -603,10 +624,12 @@ def render_git_describe_long(pieces): def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"]} + return { + "version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"], + } if "render" in pieces and pieces["render"] is not None: style = pieces["render"] @@ -633,8 +656,12 @@ def render(pieces, style): else: raise ValueError("unknown style '%s'" % style) - result = {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None} + result = { + "version": rendered, + "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], + "error": None, + } if "branch" in pieces and pieces["branch"] is not None: result["branch"] = pieces["branch"] return result @@ -651,8 +678,7 @@ def get_versions(): verbose = cfg.verbose try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, - verbose) + return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass @@ -661,14 +687,17 @@ def get_versions(): # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. - for i in cfg.versionfile_source.split('/'): + for i in cfg.versionfile_source.split("/"): root = os.path.dirname(root) except NameError: - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to find root of source tree"} + return { + "version": "0+unknown", + "full-revisionid": None, + "dirty": None, + "error": "unable to find root of source tree", + } - lookupfile = cfg.lookupfile if cfg.lookupfile is not None else ".versioneer-lookup" + lookupfile = cfg.lookupfile if cfg.lookupfile is not None else ".versioneer-lookup" lookuppath = os.path.join(root, lookupfile) if os.path.exists(lookuppath): try: @@ -690,6 +719,9 @@ def get_versions(): except NotThisMethod: pass - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to compute version"} + return { + "version": "0+unknown", + "full-revisionid": None, + "dirty": None, + "error": "unable to compute version", + } diff --git a/src/octoprint/access/groups.py b/src/octoprint/access/groups.py index 1b39d1fe5..eb16b473c 100644 --- a/src/octoprint/access/groups.py +++ b/src/octoprint/access/groups.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Marc Hannappel " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" import io @@ -21,592 +21,700 @@ from octoprint.access.permissions import Permissions, OctoPrintPermission from octoprint.vendor.flask_principal import Need, Permission -GroupNeed = partial(Need, 'group') +GroupNeed = partial(Need, "group") GroupNeed.__doc__ = """A need with the method preset to `"group"`.""" class GroupPermission(Permission): - def __init__(self, key): - need = GroupNeed(key) - super(GroupPermission, self).__init__(need) + def __init__(self, key): + need = GroupNeed(key) + super(GroupPermission, self).__init__(need) class GroupManager(object): - @classmethod - def default_permissions_for_group(cls, group): - result = [] - for permission in Permissions.all(): - if group in permission.default_groups: - result.append(permission) - return result + @classmethod + def default_permissions_for_group(cls, group): + result = [] + for permission in Permissions.all(): + if group in permission.default_groups: + result.append(permission) + return result - def __init__(self): - self._logger = logging.getLogger(__name__) - self._group_change_listeners = [] + def __init__(self): + self._logger = logging.getLogger(__name__) + self._group_change_listeners = [] - self._default_groups = [] - self._init_defaults() + self._default_groups = [] + self._init_defaults() - @property - def groups(self): - return [] + @property + def groups(self): + return [] - @property - def admin_group(self): - return self.find_group(ADMIN_GROUP) + @property + def admin_group(self): + return self.find_group(ADMIN_GROUP) - @property - def user_group(self): - return self.find_group(USER_GROUP) + @property + def user_group(self): + return self.find_group(USER_GROUP) - @property - def guest_group(self): - return self.find_group(GUEST_GROUP) + @property + def guest_group(self): + return self.find_group(GUEST_GROUP) - def _init_defaults(self): - self._default_groups = { - ADMIN_GROUP: {"name": "Admins", - "description": "Administrators", - "permissions": self.default_permissions_for_group(ADMIN_GROUP), - "subgroups": [], - "changeable": False, - "removable": False, - "default": False, - "toggleable": True}, - USER_GROUP: {"name": "Operator", - "description": "Group to gain operator access", - "permissions": self.default_permissions_for_group(USER_GROUP), - "subgroups": [], - "changeable": True, - "default": True, - "removable": False, - "toggleable": True}, - GUEST_GROUP: {"name": "Guests", - "description": "Anyone who is not currently logged in", - "permissions": self.default_permissions_for_group(GUEST_GROUP), - "subgroups": [], - "changeable": True, - "default": False, - "removable": False, - "toggleable": False}, - READONLY_GROUP: {"name": "Read-only Access", - "description": "Group to gain read-only access", - "permissions": self.default_permissions_for_group(READONLY_GROUP), - "subgroups": [], - "changeable": False, - "removable": False, - "default": False, - "toggleable": True} - } + def _init_defaults(self): + self._default_groups = { + ADMIN_GROUP: { + "name": "Admins", + "description": "Administrators", + "permissions": self.default_permissions_for_group(ADMIN_GROUP), + "subgroups": [], + "changeable": False, + "removable": False, + "default": False, + "toggleable": True, + }, + USER_GROUP: { + "name": "Operator", + "description": "Group to gain operator access", + "permissions": self.default_permissions_for_group(USER_GROUP), + "subgroups": [], + "changeable": True, + "default": True, + "removable": False, + "toggleable": True, + }, + GUEST_GROUP: { + "name": "Guests", + "description": "Anyone who is not currently logged in", + "permissions": self.default_permissions_for_group(GUEST_GROUP), + "subgroups": [], + "changeable": True, + "default": False, + "removable": False, + "toggleable": False, + }, + READONLY_GROUP: { + "name": "Read-only Access", + "description": "Group to gain read-only access", + "permissions": self.default_permissions_for_group(READONLY_GROUP), + "subgroups": [], + "changeable": False, + "removable": False, + "default": False, + "toggleable": True, + }, + } - for key, g in self._default_groups.items(): - self.add_group(key, g["name"], g["description"], - g["permissions"], g["subgroups"], - changeable=g.get("changeable", True), - removable=g.get("removable", True), - default=g.get("default", False), - toggleable=g.get("toggleable", True), - save=False) + for key, g in self._default_groups.items(): + self.add_group( + key, + g["name"], + g["description"], + g["permissions"], + g["subgroups"], + changeable=g.get("changeable", True), + removable=g.get("removable", True), + default=g.get("default", False), + toggleable=g.get("toggleable", True), + save=False, + ) + def register_listener(self, listener): + self._group_change_listeners.append(listener) - def register_listener(self, listener): - self._group_change_listeners.append(listener) + def unregister_listener(self, listener): + self._group_change_listeners.remove(listener) - def unregister_listener(self, listener): - self._group_change_listeners.remove(listener) + def add_group( + self, + key, + name, + description, + permissions, + subgroups, + default=False, + removable=True, + changeable=True, + toggleable=True, + save=True, + notify=True, + ): + pass - def add_group(self, key, name, description, permissions, subgroups, - default=False, removable=True, changeable=True, toggleable=True, save=True, notify=True): - pass + def update_group( + self, + key, + description=None, + permissions=None, + subgroups=None, + default=None, + save=True, + notify=True, + ): + pass - def update_group(self, key, description=None, permissions=None, subgroups=None, default=None, save=True, notify=True): - pass + def remove_group(self, key, save=True, notify=True): + pass - def remove_group(self, key, save=True, notify=True): - pass + def find_group(self, key): + return None - def find_group(self, key): - return None + def _to_permissions(self, *permissions): + return list( + filter( + lambda x: x is not None, + [Permissions.find(permission) for permission in permissions], + ) + ) - def _to_permissions(self, *permissions): - return list(filter(lambda x: x is not None, - [Permissions.find(permission) for permission in permissions])) + def _from_permissions(self, *permissions): + return [permission.key for permission in permissions] - def _from_permissions(self, *permissions): - return [permission.key for permission in permissions] + def _from_groups(self, *groups): + return [group.key for group in groups] - def _from_groups(self, *groups): - return [group.key for group in groups] + def _to_groups(self, *groups): + return list(filter(lambda x: x is not None, [self._to_group(g) for g in groups])) - def _to_groups(self, *groups): - return list(filter(lambda x: x is not None, - [self._to_group(g) for g in groups])) + def _to_group(self, group): + # noinspection PyCompatibility + if isinstance(group, Group): + return group + elif isinstance(group, basestring): + return self.find_group(group) + elif isinstance(group, dict): + return self.find_group(group.get("key")) + else: + return None - def _to_group(self, group): - # noinspection PyCompatibility - if isinstance(group, Group): - return group - elif isinstance(group, basestring): - return self.find_group(group) - elif isinstance(group, dict): - return self.find_group(group.get("key")) - else: - return None + def _notify_listeners(self, action, group, *args, **kwargs): + method = "on_group_{}".format(action) + for listener in self._group_change_listeners: + try: + getattr(listener, method)(group, *args, **kwargs) + except Exception: + self._logger.exception( + "Error notifying listener {!r} via {}".format(listener, method) + ) - def _notify_listeners(self, action, group, *args, **kwargs): - method = "on_group_{}".format(action) - for listener in self._group_change_listeners: - try: - getattr(listener, method)(group, *args, **kwargs) - except Exception: - self._logger.exception("Error notifying listener {!r} via {}".format(listener, method)) class GroupChangeListener(object): + def on_group_added(self, group): + pass - def on_group_added(self, group): - pass + def on_group_removed(self, group): + pass - def on_group_removed(self, group): - pass + def on_group_permissions_changed(self, group, added=None, removed=None): + pass - def on_group_permissions_changed(self, group, added=None, removed=None): - pass - - def on_group_subgroups_changed(self, group, added=None, removed=None): - pass + def on_group_subgroups_changed(self, group, added=None, removed=None): + pass class FilebasedGroupManager(GroupManager): - FILE_VERSION = 2 + FILE_VERSION = 2 - def __init__(self, path=None): - if path is None: - path = settings().get(["accessControl", "groupfile"]) - if path is None: - path = os.path.join(settings().getBaseFolder("base"), "groups.yaml") + def __init__(self, path=None): + if path is None: + path = settings().get(["accessControl", "groupfile"]) + if path is None: + path = os.path.join(settings().getBaseFolder("base"), "groups.yaml") - self._groupfile = path - self._groups = {} - self._dirty = False + self._groupfile = path + self._groups = {} + self._dirty = False - GroupManager.__init__(self) + GroupManager.__init__(self) - self._load() + self._load() - def _load(self): - if os.path.exists(self._groupfile) and os.path.isfile(self._groupfile): - try: - with io.open(self._groupfile, 'rt', encoding='utf-8') as f: - data = yaml.safe_load(f) + def _load(self): + if os.path.exists(self._groupfile) and os.path.isfile(self._groupfile): + try: + with io.open(self._groupfile, "rt", encoding="utf-8") as f: + data = yaml.safe_load(f) - if not "groups" in data: - groups = data - data = {"groups": groups} + if not "groups" in data: + groups = data + data = {"groups": groups} - file_version = data.get("_version", 1) - if file_version < self.FILE_VERSION: - # make sure we migrate the file on disk after loading - self._logger.info("Detected file version {} on group " - "storage, migrating to version {}".format(file_version, self.FILE_VERSION)) - self._dirty = True + file_version = data.get("_version", 1) + if file_version < self.FILE_VERSION: + # make sure we migrate the file on disk after loading + self._logger.info( + "Detected file version {} on group " + "storage, migrating to version {}".format( + file_version, self.FILE_VERSION + ) + ) + self._dirty = True - groups = data.get("groups", {}) - tracked_permissions = data.get("tracked", list()) + groups = data.get("groups", {}) + tracked_permissions = data.get("tracked", list()) - for key, attributes in groups.items(): - if key in self._default_groups: - # group is a default group - if not self._default_groups[key].get("changeable", True): - # group may not be changed -> bail - continue + for key, attributes in groups.items(): + if key in self._default_groups: + # group is a default group + if not self._default_groups[key].get("changeable", True): + # group may not be changed -> bail + continue - name = self._default_groups[key].get("name", "") - description = self._default_groups[key].get("description", "") - removable = self._default_groups[key].get("removable", True) - changeable = self._default_groups[key].get("changeable", True) - toggleable = self._default_groups[key].get("toggleable", True) + name = self._default_groups[key].get("name", "") + description = self._default_groups[key].get("description", "") + removable = self._default_groups[key].get("removable", True) + changeable = self._default_groups[key].get("changeable", True) + toggleable = self._default_groups[key].get("toggleable", True) - if file_version == 1: - # 1.4.0/file version 1 has a bug that resets default to True for users group on modification - set_default = self._default_groups[key].get("default", False) - else: - set_default = attributes.get("default", False) - else: - name = attributes.get("name", "") - description = attributes.get("description", "") - removable = True - changeable = True - toggleable = True - set_default = attributes.get("default", False) + if file_version == 1: + # 1.4.0/file version 1 has a bug that resets default to True for users group on modification + set_default = self._default_groups[key].get("default", False) + else: + set_default = attributes.get("default", False) + else: + name = attributes.get("name", "") + description = attributes.get("description", "") + removable = True + changeable = True + toggleable = True + set_default = attributes.get("default", False) - permissions = self._to_permissions(*attributes.get("permissions", [])) - default_permissions = self.default_permissions_for_group(key) - for permission in default_permissions: - if not permission.key in tracked_permissions and not permission in permissions: - permissions.append(permission) + permissions = self._to_permissions(*attributes.get("permissions", [])) + default_permissions = self.default_permissions_for_group(key) + for permission in default_permissions: + if ( + not permission.key in tracked_permissions + and not permission in permissions + ): + permissions.append(permission) - subgroups = attributes.get("subgroups", []) + subgroups = attributes.get("subgroups", []) - group = Group(key, name, - description=description, - permissions=permissions, - subgroups=subgroups, - default=set_default, - removable=removable, - changeable=changeable, - toggleable=toggleable) - self._groups[key] = group + group = Group( + key, + name, + description=description, + permissions=permissions, + subgroups=subgroups, + default=set_default, + removable=removable, + changeable=changeable, + toggleable=toggleable, + ) + self._groups[key] = group - for group in self._groups.values(): - group._subgroups = self._to_groups(*group._subgroups) + for group in self._groups.values(): + group._subgroups = self._to_groups(*group._subgroups) - if self._dirty: - self._save() + if self._dirty: + self._save() - except Exception: - self._logger.exception("Error while loading groups from file {}".format(self._groupfile)) + except Exception: + self._logger.exception( + "Error while loading groups from file {}".format(self._groupfile) + ) - def _save(self, force=False): - if self._groupfile is None or not self._dirty and not force: - return + def _save(self, force=False): + if self._groupfile is None or not self._dirty and not force: + return - groups = {} - for key in self._groups.keys(): - group = self._groups[key] - groups[key] = {"permissions": self._from_permissions(*group._permissions), - "subgroups": self._from_groups(*group._subgroups), - "default": group._default} - if not key in self._default_groups: - groups[key]["name"] = group.get_name() - groups[key]["description"] = group.get_description() + groups = {} + for key in self._groups.keys(): + group = self._groups[key] + groups[key] = { + "permissions": self._from_permissions(*group._permissions), + "subgroups": self._from_groups(*group._subgroups), + "default": group._default, + } + if not key in self._default_groups: + groups[key]["name"] = group.get_name() + groups[key]["description"] = group.get_description() - data = {"_version": self.FILE_VERSION, - "groups": groups, - "tracked": [x.key for x in Permissions.all()]} + data = { + "_version": self.FILE_VERSION, + "groups": groups, + "tracked": [x.key for x in Permissions.all()], + } - 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=4, allow_unicode=True) - self._dirty = False - self._load() + with atomic_write( + self._groupfile, mode="wt", permissions=0o600, max_permissions=0o666 + ) as f: + import yaml - @property - def groups(self): - return list(self._groups.values()) + yaml.safe_dump( + data, f, default_flow_style=False, indent=4, allow_unicode=True + ) + self._dirty = False + self._load() - @property - def default_groups(self): - return [group for group in self._groups.values() if group.is_default()] + @property + def groups(self): + return list(self._groups.values()) - def find_group(self, key): - if key is None: - return None - return self._groups.get(key) + @property + def default_groups(self): + return [group for group in self._groups.values() if group.is_default()] - def add_group(self, key, name, description, permissions, subgroups, default=False, removable=True, - changeable=True, toggleable=True, overwrite=False, notify=True, save=True): - if key in self._groups and not overwrite: - raise GroupAlreadyExists(key) + def find_group(self, key): + if key is None: + return None + return self._groups.get(key) - if not permissions: - permissions = [] + def add_group( + self, + key, + name, + description, + permissions, + subgroups, + default=False, + removable=True, + changeable=True, + toggleable=True, + overwrite=False, + notify=True, + save=True, + ): + if key in self._groups and not overwrite: + raise GroupAlreadyExists(key) - permissions = self._to_permissions(*permissions) - assert(all(map(lambda p: isinstance(p, OctoPrintPermission), permissions))) + if not permissions: + permissions = [] - subgroups = self._to_groups(*subgroups) - assert(all(map(lambda g: isinstance(g, Group), subgroups))) + permissions = self._to_permissions(*permissions) + assert all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)) - group = Group(key, name, - description=description, - permissions=permissions, - subgroups=subgroups, - default=default, - changeable=changeable, - removable=removable, - toggleable=toggleable) - self._groups[key] = group + subgroups = self._to_groups(*subgroups) + assert all(map(lambda g: isinstance(g, Group), subgroups)) - if save: - self._dirty = True - self._save() + group = Group( + key, + name, + description=description, + permissions=permissions, + subgroups=subgroups, + default=default, + changeable=changeable, + removable=removable, + toggleable=toggleable, + ) + self._groups[key] = group - if notify: - self._notify_listeners("added", group) + if save: + self._dirty = True + self._save() - def remove_group(self, key, save=True, notify=True): - """Removes a Group by key""" - group = self._to_group(key) - if group is None: - raise UnknownGroup(key) + if notify: + self._notify_listeners("added", group) - if not group.is_removable(): - raise GroupUnremovable(key) + def remove_group(self, key, save=True, notify=True): + """Removes a Group by key""" + group = self._to_group(key) + if group is None: + raise UnknownGroup(key) - del self._groups[key] - self._dirty = True + if not group.is_removable(): + raise GroupUnremovable(key) - if save: - self._save() + del self._groups[key] + self._dirty = True - if notify: - self._notify_listeners("removed", group) + if save: + self._save() - def update_group(self, key, description=None, permissions=None, subgroups=None, default=None, save=True, notify=True): - group = self._to_group(key) - if group is None: - raise UnknownGroup(key) + if notify: + self._notify_listeners("removed", group) - if not group.is_changeable(): - raise GroupCantBeChanged(key) + def update_group( + self, + key, + description=None, + permissions=None, + subgroups=None, + default=None, + save=True, + notify=True, + ): + group = self._to_group(key) + if group is None: + raise UnknownGroup(key) - if description is not None and description != group.get_description(): - group.change_description(description) - self._dirty = True + if not group.is_changeable(): + raise GroupCantBeChanged(key) - notifications = [] + if description is not None and description != group.get_description(): + group.change_description(description) + self._dirty = True - if permissions is not None: - permissions = self._to_permissions(*permissions) - assert (all(map(lambda p: isinstance(p, OctoPrintPermission), permissions))) + notifications = [] - removed_permissions = list(set(group._permissions) - set(permissions)) - added_permissions = list(set(permissions) - set(group._permissions)) + if permissions is not None: + permissions = self._to_permissions(*permissions) + assert all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)) - if removed_permissions: - self._dirty |= group.remove_permissions_from_group(removed_permissions) - if added_permissions: - self._dirty |= group.add_permissions_to_group(added_permissions) + removed_permissions = list(set(group._permissions) - set(permissions)) + added_permissions = list(set(permissions) - set(group._permissions)) - notifications.append((("permissions_changed", group), - {"added": added_permissions, - "removed": removed_permissions})) + if removed_permissions: + self._dirty |= group.remove_permissions_from_group(removed_permissions) + if added_permissions: + self._dirty |= group.add_permissions_to_group(added_permissions) - if subgroups is not None: - subgroups = self._to_groups(*subgroups) - assert(all(map(lambda g: isinstance(g, Group), subgroups))) + notifications.append( + ( + ("permissions_changed", group), + {"added": added_permissions, "removed": removed_permissions}, + ) + ) - removed_subgroups = list(set(group._subgroups) - set(subgroups)) - added_subgroups = list(set(subgroups) - set(group._subgroups)) + if subgroups is not None: + subgroups = self._to_groups(*subgroups) + assert all(map(lambda g: isinstance(g, Group), subgroups)) - if removed_subgroups: - self._dirty = group.remove_subgroups_from_group(removed_subgroups) - if added_subgroups: - self._dirty = group.add_subgroups_to_group(added_subgroups) + removed_subgroups = list(set(group._subgroups) - set(subgroups)) + added_subgroups = list(set(subgroups) - set(group._subgroups)) - notifications.append((("subgroups_changed", group), - {"added": added_subgroups, - "removed": removed_subgroups})) + if removed_subgroups: + self._dirty = group.remove_subgroups_from_group(removed_subgroups) + if added_subgroups: + self._dirty = group.add_subgroups_to_group(added_subgroups) - if default is not None: - group.change_default(default) - self._dirty = True + notifications.append( + ( + ("subgroups_changed", group), + {"added": added_subgroups, "removed": removed_subgroups}, + ) + ) - if self._dirty: - if save: - self._save() + if default is not None: + group.change_default(default) + self._dirty = True - if notify: - for args, kwargs in notifications: - self._notify_listeners(*args, **kwargs) + if self._dirty: + if save: + self._save() + + if notify: + for args, kwargs in notifications: + self._notify_listeners(*args, **kwargs) class GroupAlreadyExists(Exception): - def __init__(self, key): - Exception.__init__(self, "Group %s already exists" % key) + def __init__(self, key): + Exception.__init__(self, "Group %s already exists" % key) class UnknownGroup(Exception): - def __init__(self, key): - Exception.__init__(self, "Unknown group: %s" % key) + def __init__(self, key): + Exception.__init__(self, "Unknown group: %s" % key) class GroupUnremovable(Exception): - def __init__(self, key): - Exception.__init__(self, "Group can't be removed: %s" % key) + def __init__(self, key): + Exception.__init__(self, "Group can't be removed: %s" % key) class GroupCantBeChanged(Exception): - def __init__(self, key): - Exception.__init__(self, "Group can't be changed: %s" % key) + def __init__(self, key): + Exception.__init__(self, "Group can't be changed: %s" % key) class Group(object): - def __init__(self, key, name, description="", permissions=None, subgroups=None, default=False, removable=True, changeable=True, toggleable=True): - self._key = key - self._name = name - self._description = description - self._permissions = permissions - self._subgroups = subgroups - self._default = default - self._removable = removable - self._changeable = changeable - self._toggleable = toggleable + def __init__( + self, + key, + name, + description="", + permissions=None, + subgroups=None, + default=False, + removable=True, + changeable=True, + toggleable=True, + ): + self._key = key + self._name = name + self._description = description + self._permissions = permissions + self._subgroups = subgroups + self._default = default + self._removable = removable + self._changeable = changeable + self._toggleable = toggleable - def as_dict(self): - from octoprint.access.permissions import OctoPrintPermission - return {"key": self.key, - "name": self.get_name(), - "description": self._description, - "permissions": list(map(lambda p: p.key, self._permissions)), - "subgroups": list(map(lambda g: g.key, self._subgroups)), - "needs": OctoPrintPermission.convert_needs_to_dict(self.needs), - "default": self._default, - "removable": self._removable, - "changeable": self._changeable, - "toggleable": self._toggleable} + def as_dict(self): + from octoprint.access.permissions import OctoPrintPermission - @property - def key(self): - return self._key + return { + "key": self.key, + "name": self.get_name(), + "description": self._description, + "permissions": list(map(lambda p: p.key, self._permissions)), + "subgroups": list(map(lambda g: g.key, self._subgroups)), + "needs": OctoPrintPermission.convert_needs_to_dict(self.needs), + "default": self._default, + "removable": self._removable, + "changeable": self._changeable, + "toggleable": self._toggleable, + } - def get_name(self): - return self._name + @property + def key(self): + return self._key - def get_description(self): - return self._description + def get_name(self): + return self._name - def is_default(self): - return self._default + def get_description(self): + return self._description - def is_changeable(self): - return self._changeable + def is_default(self): + return self._default - def is_removable(self): - return self._removable + def is_changeable(self): + return self._changeable - def is_toggleable(self): - return self._toggleable + def is_removable(self): + return self._removable - def add_permissions_to_group(self, permissions): - """Adds a list of permissions to a group""" - if not self.is_changeable(): - raise GroupCantBeChanged(self.key) + def is_toggleable(self): + return self._toggleable - # Make sure the permissions variable is of type list - if not isinstance(permissions, list): - permissions = [permissions] + def add_permissions_to_group(self, permissions): + """Adds a list of permissions to a group""" + if not self.is_changeable(): + raise GroupCantBeChanged(self.key) - assert(all(map(lambda p: isinstance(p, OctoPrintPermission), permissions))) + # Make sure the permissions variable is of type list + if not isinstance(permissions, list): + permissions = [permissions] - dirty = False - for permission in permissions: - if permissions not in self.permissions: - self._permissions.append(permission) - dirty = True + assert all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)) - return dirty + dirty = False + for permission in permissions: + if permissions not in self.permissions: + self._permissions.append(permission) + dirty = True - def remove_permissions_from_group(self, permissions): - """Removes a list of permissions from a group""" - if not self.is_changeable(): - raise GroupCantBeChanged(self.key) + return dirty - # Make sure the permissions variable is of type list - if not isinstance(permissions, list): - permissions = [permissions] + def remove_permissions_from_group(self, permissions): + """Removes a list of permissions from a group""" + if not self.is_changeable(): + raise GroupCantBeChanged(self.key) - assert(all(map(lambda p: isinstance(p, OctoPrintPermission), permissions))) + # Make sure the permissions variable is of type list + if not isinstance(permissions, list): + permissions = [permissions] - dirty = False - for permission in permissions: - if permission in self._permissions: - self._permissions.remove(permission) - dirty = True + assert all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)) - return dirty + dirty = False + for permission in permissions: + if permission in self._permissions: + self._permissions.remove(permission) + dirty = True - def add_subgroups_to_group(self, subgroups): - """Adds a list of subgroups to a group""" - if not self.is_changeable(): - raise GroupCantBeChanged(self.key) + return dirty - # Make sure the subgroups variable is of type list - if not isinstance(subgroups, list): - subgroups = [subgroups] + def add_subgroups_to_group(self, subgroups): + """Adds a list of subgroups to a group""" + if not self.is_changeable(): + raise GroupCantBeChanged(self.key) - assert(all(map(lambda g: isinstance(g, Group), subgroups))) + # Make sure the subgroups variable is of type list + if not isinstance(subgroups, list): + subgroups = [subgroups] - dirty = False - for group in subgroups: - if group.is_toggleable() and group not in self._subgroups: - self._subgroups.append(group) - dirty = True + assert all(map(lambda g: isinstance(g, Group), subgroups)) - return dirty + dirty = False + for group in subgroups: + if group.is_toggleable() and group not in self._subgroups: + self._subgroups.append(group) + dirty = True - def remove_subgroups_from_group(self, subgroups): - """Removes a list of subgroups from a group""" - """Adds a list of subgroups to a group""" - if not self.is_changeable(): - raise GroupCantBeChanged(self.key) + return dirty - # Make sure the subgroups variable is of type list - if not isinstance(subgroups, list): - subgroups = [subgroups] + def remove_subgroups_from_group(self, subgroups): + """Removes a list of subgroups from a group""" + """Adds a list of subgroups to a group""" + if not self.is_changeable(): + raise GroupCantBeChanged(self.key) - assert (all(map(lambda g: isinstance(g, Group), subgroups))) + # Make sure the subgroups variable is of type list + if not isinstance(subgroups, list): + subgroups = [subgroups] - dirty = False - for group in subgroups: - if group.is_toggleable() and group in self._subgroups: - self._subgroups.remove(group) - dirty = True + assert all(map(lambda g: isinstance(g, Group), subgroups)) - return dirty + dirty = False + for group in subgroups: + if group.is_toggleable() and group in self._subgroups: + self._subgroups.remove(group) + dirty = True - def change_default(self, default): - """Changes the default flag of a Group""" - if not self.is_changeable(): - raise GroupCantBeChanged(self.key) + return dirty - self._default = default + def change_default(self, default): + """Changes the default flag of a Group""" + if not self.is_changeable(): + raise GroupCantBeChanged(self.key) - def change_description(self, description): - """Changes the description of a group""" - self._description = description + self._default = default - @property - def permissions(self): - if Permissions.ADMIN in self._permissions: - return Permissions.all() + def change_description(self, description): + """Changes the description of a group""" + self._description = description - return list(filter(lambda p: p is not None, self._permissions)) + @property + def permissions(self): + if Permissions.ADMIN in self._permissions: + return Permissions.all() - @property - def subgroups(self): - return filter(lambda g: g is not None, self._subgroups) + return list(filter(lambda p: p is not None, self._permissions)) - @property - def needs(self): - needs = set() - needs.add(GroupNeed(self.key)) - for p in self.permissions: - needs = needs.union(p.needs) - for g in self.subgroups: - needs = needs.union(g.needs) + @property + def subgroups(self): + return filter(lambda g: g is not None, self._subgroups) - return needs + @property + def needs(self): + needs = set() + needs.add(GroupNeed(self.key)) + for p in self.permissions: + needs = needs.union(p.needs) + for g in self.subgroups: + needs = needs.union(g.needs) - def has_permission(self, permission): - if Permissions.ADMIN.get_name() in self._permissions: - return True + return needs - return permission.needs.issubset(self.needs) + def has_permission(self, permission): + if Permissions.ADMIN.get_name() in self._permissions: + return True - def __repr__(self): - return '{}("{}", "{}", description="{}", permissions={!r}, ' \ - 'default={}, removable={}, changeable={})'.format(self.__class__.__name__, - self._key, - self._name, - self._description, - self._permissions, - bool(self._default), - bool(self._removable), - bool(self._changeable)) + return permission.needs.issubset(self.needs) - def __hash__(self): - return self.key.__hash__() + def __repr__(self): + return ( + '{}("{}", "{}", description="{}", permissions={!r}, ' + "default={}, removable={}, changeable={})".format( + self.__class__.__name__, + self._key, + self._name, + self._description, + self._permissions, + bool(self._default), + bool(self._removable), + bool(self._changeable), + ) + ) - def __eq__(self, other): - return isinstance(other, Group) and other.key == self.key + def __hash__(self): + return self.key.__hash__() + + def __eq__(self, other): + return isinstance(other, Group) and other.key == self.key diff --git a/src/octoprint/access/permissions.py b/src/octoprint/access/permissions.py index 8a942c147..6486e1ae8 100644 --- a/src/octoprint/access/permissions.py +++ b/src/octoprint/access/permissions.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Marc Hannappel " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" from future.utils import with_metaclass @@ -20,371 +20,444 @@ from octoprint.access import ADMIN_GROUP, USER_GROUP, READONLY_GROUP class OctoPrintPermission(Permission): - @classmethod - def convert_needs_to_dict(cls, needs): - ret_needs = defaultdict(list) - for need in needs: - if need.value not in ret_needs[need.method]: - ret_needs[need.method].append(need.value) - return ret_needs + @classmethod + def convert_needs_to_dict(cls, needs): + ret_needs = defaultdict(list) + for need in needs: + if need.value not in ret_needs[need.method]: + ret_needs[need.method].append(need.value) + return ret_needs - @classmethod - def convert_to_needs(cls, needs): - result = [] - for need in needs: - # noinspection PyCompatibility - if isinstance(need, Need): - result.append(need) - elif isinstance(need, Permission): - result += need.needs - elif isinstance(need, basestring): - result.append(RoleNeed(need)) - return result + @classmethod + def convert_to_needs(cls, needs): + result = [] + for need in needs: + # noinspection PyCompatibility + if isinstance(need, Need): + result.append(need) + elif isinstance(need, Permission): + result += need.needs + elif isinstance(need, basestring): + result.append(RoleNeed(need)) + return result - def __init__(self, name, description, *needs, **kwargs): - self._name = name - self._description = description - self._dangerous = kwargs.pop("dangerous", False) - self._default_groups = kwargs.pop("default_groups", []) + def __init__(self, name, description, *needs, **kwargs): + self._name = name + self._description = description + self._dangerous = kwargs.pop("dangerous", False) + self._default_groups = kwargs.pop("default_groups", []) - self._key = None + self._key = None - Permission.__init__(self, *self.convert_to_needs(needs)) + Permission.__init__(self, *self.convert_to_needs(needs)) - def as_dict(self): - return {"key": self.key, - "name": self.get_name(), - "dangerous": self._dangerous, - "default_groups": self._default_groups, - "description": self.get_description(), - "needs": self.convert_needs_to_dict(self.needs)} + def as_dict(self): + return { + "key": self.key, + "name": self.get_name(), + "dangerous": self._dangerous, + "default_groups": self._default_groups, + "description": self.get_description(), + "needs": self.convert_needs_to_dict(self.needs), + } - @property - def key(self): - return self._key + @property + def key(self): + return self._key - @key.setter - def key(self, value): - self._key = value + @key.setter + def key(self, value): + self._key = value - @property - def default_groups(self): - return self._default_groups + @property + def default_groups(self): + return self._default_groups - def get_name(self): - return self._name + def get_name(self): + return self._name - def get_description(self): - return self._description + def get_description(self): + return self._description - def allows(self, identity): - """Whether the identity can access this permission. - Overridden from Permission.allows to make sure the Identity provides ALL - required needs instead of ANY required need. + def allows(self, identity): + """Whether the identity can access this permission. + Overridden from Permission.allows to make sure the Identity provides ALL + required needs instead of ANY required need. - :param identity: The identity - """ - if self.needs and len(self.needs.intersection(identity.provides)) != len(self.needs): - return False + :param identity: The identity + """ + if self.needs and len(self.needs.intersection(identity.provides)) != len( + self.needs + ): + return False - if self.excludes and self.excludes.intersection(identity.provides): - return False + if self.excludes and self.excludes.intersection(identity.provides): + return False - return True + return True + def union(self, other): + """Create a new OctoPrintPermission with the requirements of the union of this + and other. - def union(self, other): - """Create a new OctoPrintPermission with the requirements of the union of this - and other. + :param other: The other permission + """ + p = self.__class__(self._name, self._description, *self.needs.union(other.needs)) + p.excludes.update(self.excludes.union(other.excludes)) + return p - :param other: The other permission - """ - p = self.__class__(self._name, self._description, *self.needs.union(other.needs)) - p.excludes.update(self.excludes.union(other.excludes)) - return p + def difference(self, other): + """Create a new OctoPrintPermission consisting of requirements in this + permission and not in the other. + """ - def difference(self, other): - """Create a new OctoPrintPermission consisting of requirements in this - permission and not in the other. - """ + p = self.__class__( + self._name, self._description, *self.needs.difference(other.needs) + ) + p.excludes.update(self.excludes.difference(other.excludes)) + return p - p = self.__class__(self._name, self._description, *self.needs.difference(other.needs)) - p.excludes.update(self.excludes.difference(other.excludes)) - return p + def __repr__(self): + return "{}({!r}, {!r}, {})".format( + self.__class__.__name__, + self.get_name(), + self.get_description(), + ", ".join(map(repr, self.needs)), + ) - def __repr__(self): - return '{}({!r}, {!r}, {})'.format(self.__class__.__name__, - self.get_name(), - self.get_description(), - ', '.join(map(repr, self.needs))) + def __hash__(self): + return self.get_name().__hash__() - def __hash__(self): - return self.get_name().__hash__() - - def __eq__(self, other): - return isinstance(other, OctoPrintPermission) and other.get_name() == self.get_name() + def __eq__(self, other): + return ( + isinstance(other, OctoPrintPermission) and other.get_name() == self.get_name() + ) class PluginOctoPrintPermission(OctoPrintPermission): + def __init__(self, *args, **kwargs): + self.plugin = kwargs.pop("plugin", None) + OctoPrintPermission.__init__(self, *args, **kwargs) - def __init__(self, *args, **kwargs): - self.plugin = kwargs.pop("plugin", None) - OctoPrintPermission.__init__(self, *args, **kwargs) - - def as_dict(self): - result = OctoPrintPermission.as_dict(self) - result["plugin"] = self.plugin - return result + def as_dict(self): + result = OctoPrintPermission.as_dict(self) + result["plugin"] = self.plugin + return result class PluginIdentityContext(object): - """Identity context for not initialized Permissions + """Identity context for not initialized Permissions - Needed to support @Permissions.PLUGIN_X_Y.require() + Needed to support @Permissions.PLUGIN_X_Y.require() - Will search the permission when needed - """ - def __init__(self, key, http_exception=None): - self.key = key - self.http_exception = http_exception - """The permission of this principal + Will search the permission when needed + """ + + def __init__(self, key, http_exception=None): + self.key = key + self.http_exception = http_exception + """The permission of this principal """ - @property - def identity(self): - """The identity of this principal - """ - return g.identity + @property + def identity(self): + """The identity of this principal""" + return g.identity - def can(self): - """Whether the identity has access to the permission - """ - permission = getattr(Permissions, self.key) - if permission is None or isinstance(permission, PluginPermissionDecorator): - raise UnknownPermission(self.key) + def can(self): + """Whether the identity has access to the permission""" + permission = getattr(Permissions, self.key) + if permission is None or isinstance(permission, PluginPermissionDecorator): + raise UnknownPermission(self.key) - return permission.can() + return permission.can() - def __call__(self, f): - @wraps(f) - def _decorated(*args, **kw): - with self: - rv = f(*args, **kw) - return rv + def __call__(self, f): + @wraps(f) + def _decorated(*args, **kw): + with self: + rv = f(*args, **kw) + return rv - return _decorated + return _decorated - def __enter__(self): - permission = getattr(Permissions, self.key) - if permission is None or isinstance(permission, PluginPermissionDecorator): - raise UnknownPermission(self.key) + def __enter__(self): + permission = getattr(Permissions, self.key) + if permission is None or isinstance(permission, PluginPermissionDecorator): + raise UnknownPermission(self.key) - # check the permission here - if not permission.can(): - if self.http_exception: - abort(self.http_exception, permission) - raise PermissionDenied(permission) + # check the permission here + if not permission.can(): + if self.http_exception: + abort(self.http_exception, permission) + raise PermissionDenied(permission) - def __exit__(self, *args): - return False + def __exit__(self, *args): + return False class PluginPermissionDecorator(Permission): - """Decorator Class for not initialized Permissions + """Decorator Class for not initialized Permissions - Needed to support @Permissions.PLUGIN_X_Y.require() - """ - def __init__(self, key): - self.key = key + Needed to support @Permissions.PLUGIN_X_Y.require() + """ - def require(self, http_exception=None): - return PluginIdentityContext(self.key, http_exception) + def __init__(self, key): + self.key = key + + def require(self, http_exception=None): + return PluginIdentityContext(self.key, http_exception) class PermissionsMetaClass(type): - permissions = OrderedDict() + permissions = OrderedDict() - def __new__(mcs, name, bases, args): - cls = type.__new__(mcs, name, bases, args) + def __new__(mcs, name, bases, args): + cls = type.__new__(mcs, name, bases, args) - for key, value in args.items(): - if isinstance(value, OctoPrintPermission): - value.key = key - mcs.permissions[key] = value - delattr(cls, key) + for key, value in args.items(): + if isinstance(value, OctoPrintPermission): + value.key = key + mcs.permissions[key] = value + delattr(cls, key) - return cls + return cls - def __setattr__(cls, key, value): - if isinstance(value, OctoPrintPermission): - if key in cls.permissions: - raise PermissionAlreadyExists(key) - value.key = key - cls.permissions[key] = value + def __setattr__(cls, key, value): + if isinstance(value, OctoPrintPermission): + if key in cls.permissions: + raise PermissionAlreadyExists(key) + value.key = key + cls.permissions[key] = value - def __getattr__(cls, key): - permission = cls.permissions.get(key) + def __getattr__(cls, key): + permission = cls.permissions.get(key) - if key.startswith("PLUGIN_") and permission is None: - return PluginPermissionDecorator(key) + if key.startswith("PLUGIN_") and permission is None: + return PluginPermissionDecorator(key) - return permission + return permission - def all(cls): - return list(cls.permissions.values()) + def all(cls): + return list(cls.permissions.values()) - def filter(cls, cb): - return list(filter(cb, cls.all())) + def filter(cls, cb): + return list(filter(cb, cls.all())) - def find(cls, p, filter=None): - key = None - if isinstance(p, OctoPrintPermission): - key = p.key - elif isinstance(p, dict): - key = p.get("key") - elif isinstance(p, basestring): - key = p + def find(cls, p, filter=None): + key = None + if isinstance(p, OctoPrintPermission): + key = p.key + elif isinstance(p, dict): + key = p.get("key") + elif isinstance(p, basestring): + key = p - if key is None: - return None + if key is None: + return None - return cls.match(lambda p: p.key == key, filter=filter) + return cls.match(lambda p: p.key == key, filter=filter) - def match(cls, match, filter=None): - if callable(filter): - permissions = cls.filter(filter) - else: - permissions = cls.all() + def match(cls, match, filter=None): + if callable(filter): + permissions = cls.filter(filter) + else: + permissions = cls.all() - for permission in permissions: - if match(permission): - return permission + for permission in permissions: + if match(permission): + return permission - return None + return None class Permissions(with_metaclass(PermissionsMetaClass)): - # Special permission - ADMIN = OctoPrintPermission("Admin", - gettext("Admin is allowed to do everything"), - RoleNeed("admin"), - dangerous=True, - default_groups=[ADMIN_GROUP]) + # Special permission + ADMIN = OctoPrintPermission( + "Admin", + gettext("Admin is allowed to do everything"), + RoleNeed("admin"), + dangerous=True, + default_groups=[ADMIN_GROUP], + ) - STATUS = OctoPrintPermission("Status", - gettext("Allows to gather basic status information, e.g. job progress, " - "printer state, temperatures, ... Mandatory for the default UI " - "to work"), - RoleNeed("status"), - default_groups=[USER_GROUP, READONLY_GROUP]) + STATUS = OctoPrintPermission( + "Status", + gettext( + "Allows to gather basic status information, e.g. job progress, " + "printer state, temperatures, ... Mandatory for the default UI " + "to work" + ), + RoleNeed("status"), + default_groups=[USER_GROUP, READONLY_GROUP], + ) - CONNECTION = OctoPrintPermission("Connection", - gettext("Allows to connect to and disconnect from a printer"), - RoleNeed("connection"), - default_groups=[USER_GROUP]) + CONNECTION = OctoPrintPermission( + "Connection", + gettext("Allows to connect to and disconnect from a printer"), + RoleNeed("connection"), + default_groups=[USER_GROUP], + ) - WEBCAM = OctoPrintPermission("Webcam", - gettext("Allows to watch the webcam stream"), - RoleNeed("webcam"), - default_groups=[USER_GROUP, READONLY_GROUP]) + WEBCAM = OctoPrintPermission( + "Webcam", + gettext("Allows to watch the webcam stream"), + RoleNeed("webcam"), + default_groups=[USER_GROUP, READONLY_GROUP], + ) - SYSTEM = OctoPrintPermission("System", - gettext("Allows to run system commands, e.g. restart OctoPrint, " - "shutdown or reboot the system"), - RoleNeed("system"), - dangerous=True) + SYSTEM = OctoPrintPermission( + "System", + gettext( + "Allows to run system commands, e.g. restart OctoPrint, " + "shutdown or reboot the system" + ), + RoleNeed("system"), + dangerous=True, + ) - FILES_LIST = OctoPrintPermission("File List", - gettext("Allows to retrieve a list of all uploaded files and folders, including" - "their metadata (e.g. date, file size, analysis results, ...)"), - RoleNeed("files_list"), - default_groups=[USER_GROUP, READONLY_GROUP]) - FILES_UPLOAD = OctoPrintPermission("File Upload", - gettext("Allows users to upload new files, create new folders and copy existing ones. If " - "the File Delete permission is also set, File Upload also allows " - "moving files and folders."), - RoleNeed("files_upload"), - default_groups=[USER_GROUP]) - FILES_DOWNLOAD = OctoPrintPermission("File Download", - gettext("Allows users to download files. The GCODE viewer is " - "affected by this as well."), - RoleNeed("files_download"), - default_groups=[USER_GROUP, READONLY_GROUP]) - FILES_DELETE = OctoPrintPermission("File Delete", - gettext("Allows users to delete files and folders. If the File Upload permission is " - "also set, File Delete also allows moving files and folders."), - RoleNeed("files_delete"), - default_groups=[USER_GROUP]) - FILES_SELECT = OctoPrintPermission("File Select", - gettext("Allows to select a file for printing"), - RoleNeed("files_select"), - default_groups=[USER_GROUP]) + FILES_LIST = OctoPrintPermission( + "File List", + gettext( + "Allows to retrieve a list of all uploaded files and folders, including" + "their metadata (e.g. date, file size, analysis results, ...)" + ), + RoleNeed("files_list"), + default_groups=[USER_GROUP, READONLY_GROUP], + ) + FILES_UPLOAD = OctoPrintPermission( + "File Upload", + gettext( + "Allows users to upload new files, create new folders and copy existing ones. If " + "the File Delete permission is also set, File Upload also allows " + "moving files and folders." + ), + RoleNeed("files_upload"), + default_groups=[USER_GROUP], + ) + FILES_DOWNLOAD = OctoPrintPermission( + "File Download", + gettext( + "Allows users to download files. The GCODE viewer is " + "affected by this as well." + ), + RoleNeed("files_download"), + default_groups=[USER_GROUP, READONLY_GROUP], + ) + FILES_DELETE = OctoPrintPermission( + "File Delete", + gettext( + "Allows users to delete files and folders. If the File Upload permission is " + "also set, File Delete also allows moving files and folders." + ), + RoleNeed("files_delete"), + default_groups=[USER_GROUP], + ) + FILES_SELECT = OctoPrintPermission( + "File Select", + gettext("Allows to select a file for printing"), + RoleNeed("files_select"), + default_groups=[USER_GROUP], + ) - PRINT = OctoPrintPermission("Print", - gettext("Allows to start, pause and cancel a print job"), - RoleNeed("print"), - default_groups=[USER_GROUP]) + PRINT = OctoPrintPermission( + "Print", + gettext("Allows to start, pause and cancel a print job"), + RoleNeed("print"), + default_groups=[USER_GROUP], + ) - GCODE_VIEWER = OctoPrintPermission("GCODE viewer", - gettext("Allows access to the GCODE viewer if the \"File Download\"" - "permission is also set."), - RoleNeed("gcodeviewer"), - default_groups=[USER_GROUP, READONLY_GROUP]) + GCODE_VIEWER = OctoPrintPermission( + "GCODE viewer", + gettext( + 'Allows access to the GCODE viewer if the "File Download"' + "permission is also set." + ), + RoleNeed("gcodeviewer"), + default_groups=[USER_GROUP, READONLY_GROUP], + ) - MONITOR_TERMINAL = OctoPrintPermission("Terminal", - gettext("Allows to watch the terminal tab but not to send commands " - "to the printer from it"), - RoleNeed("monitor_terminal"), - default_groups=[USER_GROUP, READONLY_GROUP]) + MONITOR_TERMINAL = OctoPrintPermission( + "Terminal", + gettext( + "Allows to watch the terminal tab but not to send commands " + "to the printer from it" + ), + RoleNeed("monitor_terminal"), + default_groups=[USER_GROUP, READONLY_GROUP], + ) - CONTROL = OctoPrintPermission("Control", - gettext("Allows to control of the printer by using the temperature controls," - "the control tab or sending commands through the terminal."), - RoleNeed("control"), - default_groups=[USER_GROUP]) + CONTROL = OctoPrintPermission( + "Control", + gettext( + "Allows to control of the printer by using the temperature controls," + "the control tab or sending commands through the terminal." + ), + RoleNeed("control"), + default_groups=[USER_GROUP], + ) - SLICE = OctoPrintPermission("Slice", - gettext("Allows to slice files"), - RoleNeed("slice"), - default_groups=[USER_GROUP]) + SLICE = OctoPrintPermission( + "Slice", + gettext("Allows to slice files"), + RoleNeed("slice"), + default_groups=[USER_GROUP], + ) - TIMELAPSE_LIST = OctoPrintPermission("Timelapse List", - gettext("Allows to list timelapse videos"), - RoleNeed("timelapse_list"), - default_groups=[USER_GROUP, READONLY_GROUP]) - TIMELAPSE_DOWNLOAD = OctoPrintPermission("Timelapse Download", - gettext("Allows to download timelapse videos"), - RoleNeed("timelapse_download"), - default_groups=[USER_GROUP, READONLY_GROUP]) - TIMELAPSE_DELETE = OctoPrintPermission("Timelapse Delete", - gettext("Allows to delete timelapse videos and unrendered timelapses"), - RoleNeed("timelapse_delete"), - default_groups=[USER_GROUP]) - TIMELAPSE_ADMIN = OctoPrintPermission("Timelapse Admin", - gettext("Allows to change the timelapse settings and delete or " - "render unrendered timelapses. Includes the \"Timelapse List\"," - "\"Timelapse Delete\" and \"Timelapse Download\" permissions"), - RoleNeed("timelapse_admin"), TIMELAPSE_LIST, TIMELAPSE_DOWNLOAD, - default_groups=[USER_GROUP]) - - SETTINGS_READ = OctoPrintPermission("Settings Access", - gettext("Allows to read non sensitive settings. Mandatory for the " - "default UI to work."), - RoleNeed("settings_read"), - default_groups=[USER_GROUP, READONLY_GROUP]) - SETTINGS = OctoPrintPermission("Settings Admin", - gettext("Allows to manage settings and also to read sensitive settings"), - RoleNeed("settings"), - dangerous=True) + TIMELAPSE_LIST = OctoPrintPermission( + "Timelapse List", + gettext("Allows to list timelapse videos"), + RoleNeed("timelapse_list"), + default_groups=[USER_GROUP, READONLY_GROUP], + ) + TIMELAPSE_DOWNLOAD = OctoPrintPermission( + "Timelapse Download", + gettext("Allows to download timelapse videos"), + RoleNeed("timelapse_download"), + default_groups=[USER_GROUP, READONLY_GROUP], + ) + TIMELAPSE_DELETE = OctoPrintPermission( + "Timelapse Delete", + gettext("Allows to delete timelapse videos and unrendered timelapses"), + RoleNeed("timelapse_delete"), + default_groups=[USER_GROUP], + ) + TIMELAPSE_ADMIN = OctoPrintPermission( + "Timelapse Admin", + gettext( + "Allows to change the timelapse settings and delete or " + 'render unrendered timelapses. Includes the "Timelapse List",' + '"Timelapse Delete" and "Timelapse Download" permissions' + ), + RoleNeed("timelapse_admin"), + TIMELAPSE_LIST, + TIMELAPSE_DOWNLOAD, + default_groups=[USER_GROUP], + ) + SETTINGS_READ = OctoPrintPermission( + "Settings Access", + gettext( + "Allows to read non sensitive settings. Mandatory for the " + "default UI to work." + ), + RoleNeed("settings_read"), + default_groups=[USER_GROUP, READONLY_GROUP], + ) + SETTINGS = OctoPrintPermission( + "Settings Admin", + gettext("Allows to manage settings and also to read sensitive settings"), + RoleNeed("settings"), + dangerous=True, + ) class PermissionAlreadyExists(Exception): - def __init__(self, permission): - Exception.__init__(self, "Permission %s already exists" % permission) + def __init__(self, permission): + Exception.__init__(self, "Permission %s already exists" % permission) class UnknownPermission(Exception): - def __init__(self, permissionname): - Exception.__init__(self, "Unknown permission: %s" % permissionname) + def __init__(self, permissionname): + Exception.__init__(self, "Unknown permission: %s" % permissionname) diff --git a/src/octoprint/access/users.py b/src/octoprint/access/users.py index 06c16e555..041a85ac1 100644 --- a/src/octoprint/access/users.py +++ b/src/octoprint/access/users.py @@ -1,7 +1,7 @@ # -*- 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" from flask_login import UserMixin, AnonymousUserMixin @@ -21,7 +21,13 @@ from builtins import range, bytes from octoprint.settings import settings as s -from octoprint.util import atomic_write, to_bytes, deprecated, monotonic_time, generate_api_key +from octoprint.util import ( + atomic_write, + to_bytes, + deprecated, + monotonic_time, + generate_api_key, +) from octoprint.util import get_fully_qualified_classname as fqcn from octoprint.access.permissions import Permissions, OctoPrintPermission @@ -29,1256 +35,1429 @@ from octoprint.access.groups import GroupChangeListener, Group from past.builtins import basestring + class UserManager(GroupChangeListener, object): - def __init__(self, group_manager, settings=None): - self._group_manager = group_manager - self._group_manager.register_listener(self) + def __init__(self, group_manager, settings=None): + self._group_manager = group_manager + self._group_manager.register_listener(self) - self._logger = logging.getLogger(__name__) - self._session_users_by_session = {} - self._sessionids_by_userid = {} - self._enabled = True + self._logger = logging.getLogger(__name__) + self._session_users_by_session = {} + self._sessionids_by_userid = {} + self._enabled = True - if settings is None: - settings = s() - self._settings = settings + if settings is None: + settings = s() + self._settings = settings - self._login_status_listeners = [] + self._login_status_listeners = [] - def register_login_status_listener(self, listener): - self._login_status_listeners.append(listener) + def register_login_status_listener(self, listener): + self._login_status_listeners.append(listener) - def unregister_login_status_listener(self, listener): - self._login_status_listeners.remove(listener) + def unregister_login_status_listener(self, listener): + self._login_status_listeners.remove(listener) - def anonymous_user_factory(self): - if self.enabled: - return AnonymousUser([self._group_manager.guest_group]) - else: - return AdminUser([self._group_manager.admin_group, self._group_manager.user_group]) - - def api_user_factory(self): - return ApiUser([self._group_manager.admin_group, self._group_manager.user_group]) - - @property - def enabled(self): - return self._enabled - - @enabled.setter - def enabled(self, value): - self._enabled = value - - def enable(self): - self._enabled = True - - def disable(self): - self._enabled = False - - def login_user(self, user): - self._cleanup_sessions() - - if user is None or user.is_anonymous: - return - - if isinstance(user, LocalProxy): - # noinspection PyProtectedMember - user = user._get_current_object() - - if not isinstance(user, User): - return None - - if not isinstance(user, SessionUser): - user = SessionUser(user) - - self._session_users_by_session[user.session] = user - - userid = user.get_id() - if not userid in self._sessionids_by_userid: - self._sessionids_by_userid[userid] = set() - - self._sessionids_by_userid[userid].add(user.session) - - for listener in self._login_status_listeners: - try: - listener.on_user_logged_in(user) - except Exception: - self._logger.exception("Error in on_user_logged_in on {!r}".format(listener), - extra={"callback": fqcn(listener)}) - - self._logger.info("Logged in user: {}".format(user.get_id())) - - return user - - def logout_user(self, user, stale=False): - if user is None or user.is_anonymous or isinstance(user, AdminUser): - return - - if isinstance(user, LocalProxy): - user = user._get_current_object() - - if not isinstance(user, SessionUser): - return - - userid = user.get_id() - sessionid = user.session - - if userid in self._sessionids_by_userid: - try: - self._sessionids_by_userid[userid].remove(sessionid) - except KeyError: - pass - - if sessionid in self._session_users_by_session: - try: - del self._session_users_by_session[sessionid] - except KeyError: - pass - - for listener in self._login_status_listeners: - try: - listener.on_user_logged_out(user, stale=stale) - except Exception: - self._logger.exception("Error in on_user_logged_out on {!r}".format(listener), - extra={"callback": fqcn(listener)}) - - self._logger.info("Logged out user: {}".format(user.get_id())) - - def _cleanup_sessions(self): - for session, user in list(self._session_users_by_session.items()): - if not isinstance(user, SessionUser): - continue - if user.created + (24 * 60 * 60) < monotonic_time(): - self._logger.info("Cleaning up user session {} for user {}".format(session, user.get_id())) - self.logout_user(user, stale=True) - - @staticmethod - def create_password_hash(password, salt=None, settings=None): - if not salt: - if settings is None: - settings = s() - salt = settings.get(["accessControl", "salt"]) - if salt is None: - import string - from random import choice - chars = string.ascii_lowercase + string.ascii_uppercase + string.digits - salt = "".join(choice(chars) for _ in range(32)) - settings.set(["accessControl", "salt"], salt) - settings.save() - - return hashlib.sha512(to_bytes(password, encoding="utf-8", errors="replace") + to_bytes(salt)).hexdigest() - - def check_password(self, username, password): - user = self.find_user(username) - if not user: - return False - - hash = UserManager.create_password_hash(password, - settings=self._settings) - if user.check_password(hash): - # new hash matches, correct password - return True - else: - # new hash doesn't match, but maybe the old one does, so check that! - oldHash = UserManager.create_password_hash(password, - salt="mvBUTvwzBzD3yPwvnJ4E4tXNf3CGJvvW", - settings=self._settings) - if user.check_password(oldHash): - # old hash matches, we migrate the stored password hash to the new one and return True since it's the correct password - self.change_user_password(username, password) - return True - else: - # old hash doesn't match either, wrong password - return False - - def add_user(self, username, password, active, permissions, groups, overwrite=False): - pass - - def change_user_activation(self, username, active): - pass - - def change_user_permissions(self, username, permissions): - pass - - def add_permissions_to_user(self, username, permissions): - pass - - def remove_permissions_from_user(self, username, permissions): - pass - - def change_user_groups(self, username, groups): - pass - - def add_groups_to_user(self, username, groups): - pass - - def remove_groups_from_user(self, username, groups): - pass - - def remove_groups_from_users(self, group): - pass - - def change_user_password(self, username, password): - pass - - def get_user_setting(self, username, key): - return None - - def get_all_user_settings(self, username): - return {} - - def change_user_setting(self, username, key, value): - pass - - def change_user_settings(self, username, new_settings): - pass - - def remove_user(self, username): - if username in self._sessionids_by_userid: - sessions = self._sessionids_by_userid[username] - for session in sessions: - if session in self._session_users_by_session: - del self._session_users_by_session[session] - del self._sessionids_by_userid[username] - - def validate_user_session(self, userid, session): - if session in self._session_users_by_session: - user = self._session_users_by_session[session] - return userid == user.get_id() - - return False - - def find_user(self, userid=None, session=None): - if session is not None and session in self._session_users_by_session: - user = self._session_users_by_session[session] - if userid is None or userid == user.get_id(): - return user - - return None - - def find_sessions_for(self, matcher): - result = [] - for user in self.get_all_users(): - if matcher(user): - try: - session_ids = self._sessionids_by_userid[user.get_id()] - for session_id in session_ids: - try: - result.append(self._session_users_by_session[session_id]) - except KeyError: - # unknown session after all - continue - except KeyError: - # no session for user - pass - return result - - def get_all_users(self): - return [] - - def has_been_customized(self): - return False - - def on_group_removed(self, group): - self._logger.debug("Group {} got removed, removing from all users".format(group.key)) - self.remove_groups_from_users([group]) - - def on_group_permissions_changed(self, group, added=None, removed=None): - users = self.find_sessions_for(lambda u: group in u.groups) - for listener in self._login_status_listeners: - try: - for user in users: - listener.on_user_modified(user) - except Exception: - self._logger.exception("Error in on_user_modified on {!r}".format(listener), - extra={"callback": fqcn(listener)}) - - def on_group_subgroups_changed(self, group, added=None, removed=None): - users = self.find_sessions_for(lambda u: group in u.groups) - for listener in self._login_status_listeners: - # noinspection PyBroadException - try: - for user in users: - listener.on_user_modified(user) - except Exception: - self._logger.exception("Error in on_user_modified on {!r}".format(listener), - extra={"callback": fqcn(listener)}) - - def _trigger_on_user_modified(self, user): - if isinstance(user, basestring): - # user id - users = [] - try: - session_ids = self._sessionids_by_userid[user] - for session_id in session_ids: - try: - users.append(self._session_users_by_session[session_id]) - except KeyError: - # unknown session id - continue - except KeyError: - # no session for user - return - elif isinstance(user, User) and not isinstance(user, SessionUser): - users = self.find_sessions_for(lambda u: u.get_id() == user.get_id()) - elif isinstance(user, User): - users = [user] - else: - return - - for listener in self._login_status_listeners: - try: - for user in users: - listener.on_user_modified(user) - except Exception: - self._logger.exception("Error in on_user_modified on {!r}".format(listener), - extra={"callback": fqcn(listener)}) - - def _trigger_on_user_removed(self, username): - for listener in self._login_status_listeners: - try: - listener.on_user_removed(username) - except Exception: - self._logger.exception("Error in on_user_removed on {!r}".format(listener), - extra={"callback": fqcn(listener)}) - - #~~ Deprecated methods follow - - # TODO: Remove deprecated methods in OctoPrint 1.5.0 - - @staticmethod - def createPasswordHash(*args, **kwargs): - """ - .. deprecated: 1.4.0 - - Replaced by :func:`~UserManager.create_password_hash` - """ - # we can't use the deprecated decorator here since this method is static - import warnings - warnings.warn("createPasswordHash has been renamed to create_password_hash", DeprecationWarning, stacklevel=2) - return UserManager.create_password_hash(*args, **kwargs) - - @deprecated("changeUserRoles has been replaced by change_user_permissions", - includedoc="Replaced by :func:`change_user_permissions`", - since="1.4.0") - def changeUserRoles(self, username, roles): - user = self.find_user(username) - if user is None: - raise UnknownUser(username) - - removed_roles = set(user._roles) - set(roles) - self.removeRolesFromUser(username, removed_roles, user=user) - - added_roles = set(roles) - set(user._roles) - self.addRolesToUser(username, added_roles, user=user) - - @deprecated("addRolesToUser has been replaced by add_permissions_to_user", - includedoc="Replaced by :func:`add_permissions_to_user`", - since="1.4.0") - def addRolesToUser(self, username, roles, user=None): - if user is None: - user = self.find_user(username) - - if user is None: - raise UnknownUser(username) - - if "admin" in roles: - self.add_groups_to_user(username, self._group_manager.admin_group) - - if "user" in roles: - self.remove_groups_from_user(username, self._group_manager.user_group) - - @deprecated("removeRolesFromUser has been replaced by remove_permissions_from_user", - includedoc="Replaced by :func:`remove_permissions_from_user`", - since="1.4.0") - def removeRolesFromUser(self, username, roles, user=None): - if user is None: - user = self.find_user(username) - - if user is None: - raise UnknownUser(username) - - if "admin" in roles: - self.remove_groups_from_user(username, self._group_manager.admin_group) - self.remove_permissions_from_user(username, Permissions.ADMIN) - - if "user" in roles: - self.remove_groups_from_user(username, self._group_manager.user_group) - - checkPassword = deprecated("checkPassword has been renamed to check_password", - includedoc="Replaced by :func:`check_password`", - since="1.4.0")(check_password) - addUser = deprecated("addUser has been renamed to add_user", - includedoc="Replaced by :func:`add_user`", - since="1.4.0")(add_user) - changeUserActivation = deprecated("changeUserActivation has been renamed to change_user_activation", - includedoc="Replaced by :func:`change_user_activation`", - since="1.4.0")(change_user_activation) - changeUserPassword = deprecated("changeUserPassword has been renamed to change_user_password", - includedoc="Replaced by :func:`change_user_password`", - since="1.4.0")(change_user_password) - getUserSetting = deprecated("getUserSetting has been renamed to get_user_setting", - includedoc="Replaced by :func:`get_user_setting`", - since="1.4.0")(get_user_setting) - getAllUserSettings = deprecated("getAllUserSettings has been renamed to get_all_user_settings", - includedoc="Replaced by :func:`get_all_user_settings`", - since="1.4.0")(get_all_user_settings) - changeUserSetting = deprecated("changeUserSetting has been renamed to change_user_setting", - includedoc="Replaced by :func:`change_user_setting`", - since="1.4.0")(change_user_setting) - changeUserSettings = deprecated("changeUserSettings has been renamed to change_user_settings", - includedoc="Replaced by :func:`change_user_settings`", - since="1.4.0")(change_user_settings) - removeUser = deprecated("removeUser has been renamed to remove_user", - includedoc="Replaced by :func:`remove_user`", - since="1.4.0")(remove_user) - findUser = deprecated("findUser has been renamed to find_user", - includedoc="Replaced by :func:`find_user`", - since="1.4.0")(find_user) - getAllUsers = deprecated("getAllUsers has been renamed to get_all_users", - includedoc="Replaced by :func:`get_all_users`", - since="1.4.0")(get_all_users) - hasBeenCustomized = deprecated("hasBeenCustomized has been renamed to has_been_customized", - includedoc="Replaced by :func:`has_been_customized`", - since="1.4.0")(has_been_customized) + def anonymous_user_factory(self): + if self.enabled: + return AnonymousUser([self._group_manager.guest_group]) + else: + return AdminUser( + [self._group_manager.admin_group, self._group_manager.user_group] + ) + + def api_user_factory(self): + return ApiUser([self._group_manager.admin_group, self._group_manager.user_group]) + + @property + def enabled(self): + return self._enabled + + @enabled.setter + def enabled(self, value): + self._enabled = value + + def enable(self): + self._enabled = True + + def disable(self): + self._enabled = False + + def login_user(self, user): + self._cleanup_sessions() + + if user is None or user.is_anonymous: + return + + if isinstance(user, LocalProxy): + # noinspection PyProtectedMember + user = user._get_current_object() + + if not isinstance(user, User): + return None + + if not isinstance(user, SessionUser): + user = SessionUser(user) + + self._session_users_by_session[user.session] = user + + userid = user.get_id() + if not userid in self._sessionids_by_userid: + self._sessionids_by_userid[userid] = set() + + self._sessionids_by_userid[userid].add(user.session) + + for listener in self._login_status_listeners: + try: + listener.on_user_logged_in(user) + except Exception: + self._logger.exception( + "Error in on_user_logged_in on {!r}".format(listener), + extra={"callback": fqcn(listener)}, + ) + + self._logger.info("Logged in user: {}".format(user.get_id())) + + return user + + def logout_user(self, user, stale=False): + if user is None or user.is_anonymous or isinstance(user, AdminUser): + return + + if isinstance(user, LocalProxy): + user = user._get_current_object() + + if not isinstance(user, SessionUser): + return + + userid = user.get_id() + sessionid = user.session + + if userid in self._sessionids_by_userid: + try: + self._sessionids_by_userid[userid].remove(sessionid) + except KeyError: + pass + + if sessionid in self._session_users_by_session: + try: + del self._session_users_by_session[sessionid] + except KeyError: + pass + + for listener in self._login_status_listeners: + try: + listener.on_user_logged_out(user, stale=stale) + except Exception: + self._logger.exception( + "Error in on_user_logged_out on {!r}".format(listener), + extra={"callback": fqcn(listener)}, + ) + + self._logger.info("Logged out user: {}".format(user.get_id())) + + def _cleanup_sessions(self): + for session, user in list(self._session_users_by_session.items()): + if not isinstance(user, SessionUser): + continue + if user.created + (24 * 60 * 60) < monotonic_time(): + self._logger.info( + "Cleaning up user session {} for user {}".format( + session, user.get_id() + ) + ) + self.logout_user(user, stale=True) + + @staticmethod + def create_password_hash(password, salt=None, settings=None): + if not salt: + if settings is None: + settings = s() + salt = settings.get(["accessControl", "salt"]) + if salt is None: + import string + from random import choice + + chars = string.ascii_lowercase + string.ascii_uppercase + string.digits + salt = "".join(choice(chars) for _ in range(32)) + settings.set(["accessControl", "salt"], salt) + settings.save() + + return hashlib.sha512( + to_bytes(password, encoding="utf-8", errors="replace") + to_bytes(salt) + ).hexdigest() + + def check_password(self, username, password): + user = self.find_user(username) + if not user: + return False + + hash = UserManager.create_password_hash(password, settings=self._settings) + if user.check_password(hash): + # new hash matches, correct password + return True + else: + # new hash doesn't match, but maybe the old one does, so check that! + oldHash = UserManager.create_password_hash( + password, salt="mvBUTvwzBzD3yPwvnJ4E4tXNf3CGJvvW", settings=self._settings + ) + if user.check_password(oldHash): + # old hash matches, we migrate the stored password hash to the new one and return True since it's the correct password + self.change_user_password(username, password) + return True + else: + # old hash doesn't match either, wrong password + return False + + def add_user(self, username, password, active, permissions, groups, overwrite=False): + pass + + def change_user_activation(self, username, active): + pass + + def change_user_permissions(self, username, permissions): + pass + + def add_permissions_to_user(self, username, permissions): + pass + + def remove_permissions_from_user(self, username, permissions): + pass + + def change_user_groups(self, username, groups): + pass + + def add_groups_to_user(self, username, groups): + pass + + def remove_groups_from_user(self, username, groups): + pass + + def remove_groups_from_users(self, group): + pass + + def change_user_password(self, username, password): + pass + + def get_user_setting(self, username, key): + return None + + def get_all_user_settings(self, username): + return {} + + def change_user_setting(self, username, key, value): + pass + + def change_user_settings(self, username, new_settings): + pass + + def remove_user(self, username): + if username in self._sessionids_by_userid: + sessions = self._sessionids_by_userid[username] + for session in sessions: + if session in self._session_users_by_session: + del self._session_users_by_session[session] + del self._sessionids_by_userid[username] + + def validate_user_session(self, userid, session): + if session in self._session_users_by_session: + user = self._session_users_by_session[session] + return userid == user.get_id() + + return False + + def find_user(self, userid=None, session=None): + if session is not None and session in self._session_users_by_session: + user = self._session_users_by_session[session] + if userid is None or userid == user.get_id(): + return user + + return None + + def find_sessions_for(self, matcher): + result = [] + for user in self.get_all_users(): + if matcher(user): + try: + session_ids = self._sessionids_by_userid[user.get_id()] + for session_id in session_ids: + try: + result.append(self._session_users_by_session[session_id]) + except KeyError: + # unknown session after all + continue + except KeyError: + # no session for user + pass + return result + + def get_all_users(self): + return [] + + def has_been_customized(self): + return False + + def on_group_removed(self, group): + self._logger.debug( + "Group {} got removed, removing from all users".format(group.key) + ) + self.remove_groups_from_users([group]) + + def on_group_permissions_changed(self, group, added=None, removed=None): + users = self.find_sessions_for(lambda u: group in u.groups) + for listener in self._login_status_listeners: + try: + for user in users: + listener.on_user_modified(user) + except Exception: + self._logger.exception( + "Error in on_user_modified on {!r}".format(listener), + extra={"callback": fqcn(listener)}, + ) + + def on_group_subgroups_changed(self, group, added=None, removed=None): + users = self.find_sessions_for(lambda u: group in u.groups) + for listener in self._login_status_listeners: + # noinspection PyBroadException + try: + for user in users: + listener.on_user_modified(user) + except Exception: + self._logger.exception( + "Error in on_user_modified on {!r}".format(listener), + extra={"callback": fqcn(listener)}, + ) + + def _trigger_on_user_modified(self, user): + if isinstance(user, basestring): + # user id + users = [] + try: + session_ids = self._sessionids_by_userid[user] + for session_id in session_ids: + try: + users.append(self._session_users_by_session[session_id]) + except KeyError: + # unknown session id + continue + except KeyError: + # no session for user + return + elif isinstance(user, User) and not isinstance(user, SessionUser): + users = self.find_sessions_for(lambda u: u.get_id() == user.get_id()) + elif isinstance(user, User): + users = [user] + else: + return + + for listener in self._login_status_listeners: + try: + for user in users: + listener.on_user_modified(user) + except Exception: + self._logger.exception( + "Error in on_user_modified on {!r}".format(listener), + extra={"callback": fqcn(listener)}, + ) + + def _trigger_on_user_removed(self, username): + for listener in self._login_status_listeners: + try: + listener.on_user_removed(username) + except Exception: + self._logger.exception( + "Error in on_user_removed on {!r}".format(listener), + extra={"callback": fqcn(listener)}, + ) + + # ~~ Deprecated methods follow + + # TODO: Remove deprecated methods in OctoPrint 1.5.0 + + @staticmethod + def createPasswordHash(*args, **kwargs): + """ + .. deprecated: 1.4.0 + + Replaced by :func:`~UserManager.create_password_hash` + """ + # we can't use the deprecated decorator here since this method is static + import warnings + + warnings.warn( + "createPasswordHash has been renamed to create_password_hash", + DeprecationWarning, + stacklevel=2, + ) + return UserManager.create_password_hash(*args, **kwargs) + + @deprecated( + "changeUserRoles has been replaced by change_user_permissions", + includedoc="Replaced by :func:`change_user_permissions`", + since="1.4.0", + ) + def changeUserRoles(self, username, roles): + user = self.find_user(username) + if user is None: + raise UnknownUser(username) + + removed_roles = set(user._roles) - set(roles) + self.removeRolesFromUser(username, removed_roles, user=user) + + added_roles = set(roles) - set(user._roles) + self.addRolesToUser(username, added_roles, user=user) + + @deprecated( + "addRolesToUser has been replaced by add_permissions_to_user", + includedoc="Replaced by :func:`add_permissions_to_user`", + since="1.4.0", + ) + def addRolesToUser(self, username, roles, user=None): + if user is None: + user = self.find_user(username) + + if user is None: + raise UnknownUser(username) + + if "admin" in roles: + self.add_groups_to_user(username, self._group_manager.admin_group) + + if "user" in roles: + self.remove_groups_from_user(username, self._group_manager.user_group) + + @deprecated( + "removeRolesFromUser has been replaced by remove_permissions_from_user", + includedoc="Replaced by :func:`remove_permissions_from_user`", + since="1.4.0", + ) + def removeRolesFromUser(self, username, roles, user=None): + if user is None: + user = self.find_user(username) + + if user is None: + raise UnknownUser(username) + + if "admin" in roles: + self.remove_groups_from_user(username, self._group_manager.admin_group) + self.remove_permissions_from_user(username, Permissions.ADMIN) + + if "user" in roles: + self.remove_groups_from_user(username, self._group_manager.user_group) + + checkPassword = deprecated( + "checkPassword has been renamed to check_password", + includedoc="Replaced by :func:`check_password`", + since="1.4.0", + )(check_password) + addUser = deprecated( + "addUser has been renamed to add_user", + includedoc="Replaced by :func:`add_user`", + since="1.4.0", + )(add_user) + changeUserActivation = deprecated( + "changeUserActivation has been renamed to change_user_activation", + includedoc="Replaced by :func:`change_user_activation`", + since="1.4.0", + )(change_user_activation) + changeUserPassword = deprecated( + "changeUserPassword has been renamed to change_user_password", + includedoc="Replaced by :func:`change_user_password`", + since="1.4.0", + )(change_user_password) + getUserSetting = deprecated( + "getUserSetting has been renamed to get_user_setting", + includedoc="Replaced by :func:`get_user_setting`", + since="1.4.0", + )(get_user_setting) + getAllUserSettings = deprecated( + "getAllUserSettings has been renamed to get_all_user_settings", + includedoc="Replaced by :func:`get_all_user_settings`", + since="1.4.0", + )(get_all_user_settings) + changeUserSetting = deprecated( + "changeUserSetting has been renamed to change_user_setting", + includedoc="Replaced by :func:`change_user_setting`", + since="1.4.0", + )(change_user_setting) + changeUserSettings = deprecated( + "changeUserSettings has been renamed to change_user_settings", + includedoc="Replaced by :func:`change_user_settings`", + since="1.4.0", + )(change_user_settings) + removeUser = deprecated( + "removeUser has been renamed to remove_user", + includedoc="Replaced by :func:`remove_user`", + since="1.4.0", + )(remove_user) + findUser = deprecated( + "findUser has been renamed to find_user", + includedoc="Replaced by :func:`find_user`", + since="1.4.0", + )(find_user) + getAllUsers = deprecated( + "getAllUsers has been renamed to get_all_users", + includedoc="Replaced by :func:`get_all_users`", + since="1.4.0", + )(get_all_users) + hasBeenCustomized = deprecated( + "hasBeenCustomized has been renamed to has_been_customized", + includedoc="Replaced by :func:`has_been_customized`", + since="1.4.0", + )(has_been_customized) class LoginStatusListener(object): + def on_user_logged_in(self, user): + pass - def on_user_logged_in(self, user): - pass + def on_user_logged_out(self, user, stale=False): + pass - def on_user_logged_out(self, user, stale=False): - pass + def on_user_modified(self, user): + pass - def on_user_modified(self, user): - pass - - def on_user_removed(self, userid): - pass + def on_user_removed(self, userid): + pass ##~~ FilebasedUserManager, takes available users from users.yaml file + class FilebasedUserManager(UserManager): - def __init__(self, group_manager, path=None, settings=None): - UserManager.__init__(self, group_manager, settings=settings) - - if path is None: - path = self._settings.get(["accessControl", "userfile"]) - if path is None: - path = os.path.join(s().getBaseFolder("base"), "users.yaml") - - self._userfile = path - - self._users = {} - self._dirty = False - - self._customized = None - self._load() - - def _load(self): - if os.path.exists(self._userfile) and os.path.isfile(self._userfile): - self._customized = True - with io.open(self._userfile, 'rt', encoding='utf-8') as f: - data = yaml.safe_load(f) - - for name, attributes in data.items(): - if not isinstance(attributes, dict): - continue - - permissions = [] - if "permissions" in attributes: - permissions = attributes["permissions"] - - 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 not "permissions" 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) - 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() - - else: - self._customized = False - - def _save(self, force=False): - if not self._dirty and not force: - return - - data = {} - for name, user in self._users.items(): - if not user or not isinstance(user, User): - continue - - data[name] = { - "password": user._passwordHash, - "active": user._active, - "groups": self._from_groups(*user._groups), - "permissions": self._from_permissions(*user._permissions), - "apikey": user._apikey, - "settings": user._settings, - - # TODO: deprecated, remove in 1.5.0 - "roles": user._roles - } - - with atomic_write(self._userfile, mode='wt', permissions=0o600, max_permissions=0o666) as f: - yaml.safe_dump(data, f, default_flow_style=False, indent=4, allow_unicode=True) - self._dirty = False - self._load() - - def _migrate_roles_to_groups(self, roles): - # If admin is inside the roles, just return admin group - if "admin" in roles: - return [self._group_manager.admin_group, self._group_manager.user_group] - else: - return [self._group_manager.user_group] - - def _refresh_groups(self, user): - user._groups = self._to_groups(*map(lambda g: g.key, user.groups)) - - def add_user(self, username, password, active=False, permissions=None, groups=None, apikey=None, overwrite=False): - if not permissions: - permissions = [] - permissions = self._to_permissions(*permissions) - - if not groups: - groups = self._group_manager.default_groups - groups = self._to_groups(*groups) - - if username in self._users and not overwrite: - raise UserAlreadyExists(username) - - self._users[username] = User(username, - UserManager.create_password_hash(password, - settings=self._settings), - active, - permissions, - groups, - apikey=apikey) - self._dirty = True - self._save() - - def change_user_activation(self, username, active): - if username not in self._users: - raise UnknownUser(username) - - if self._users[username].is_active != active: - self._users[username]._active = active - self._dirty = True - self._save() - - self._trigger_on_user_modified(username) - - def change_user_permissions(self, username, permissions): - if username not in self._users: - raise UnknownUser(username) - - user = self._users[username] - - permissions = self._to_permissions(*permissions) - - removed_permissions = list(set(user._permissions) - set(permissions)) - added_permissions = list(set(permissions) - set(user._permissions)) - - if len(removed_permissions) > 0: - user.remove_permissions_from_user(removed_permissions) - self._dirty = True - - if len(added_permissions) > 0: - user.add_permissions_to_user(added_permissions) - self._dirty = True - - if self._dirty: - self._save() - self._trigger_on_user_modified(username) - - def add_permissions_to_user(self, username, permissions): - if username not in self._users: - raise UnknownUser(username) - - if self._users[username].add_permissions_to_user(self._to_permissions(*permissions)): - self._dirty = True - self._save() - self._trigger_on_user_modified(username) - - def remove_permissions_from_user(self, username, permissions): - if username not in self._users: - raise UnknownUser(username) - - if self._users[username].remove_permissions_from_user(self._to_permissions(*permissions)): - self._dirty = True - self._save() - self._trigger_on_user_modified(username) - - def remove_permissions_from_users(self, permissions): - modified = [] - for user in self._users: - dirty = user.remove_permissions_from_user(self._to_permissions(*permissions)) - if dirty: - self._dirty = True - modified.append(user.get_id()) - - if self._dirty: - self._save() - for username in modified: - self._trigger_on_user_modified(username) - - def change_user_groups(self, username, groups): - if username not in self._users: - raise UnknownUser(username) - - user = self._users[username] - - groups = self._to_groups(*groups) - - removed_groups = list(set(user._groups) - set(groups)) - added_groups = list(set(groups) - set(user._groups)) - - if len(removed_groups): - self._dirty |= user.remove_groups_from_user(removed_groups) - if len(added_groups): - self._dirty |= user.add_groups_to_user(added_groups) - - if self._dirty: - self._save() - self._trigger_on_user_modified(username) - - def add_groups_to_user(self, username, groups, save=True, notify=True): - if username not in self._users: - raise UnknownUser(username) - - if self._users[username].add_groups_to_user(self._to_groups(*groups)): - self._dirty = True - - if save: - self._save() - - if notify: - self._trigger_on_user_modified(username) + def __init__(self, group_manager, path=None, settings=None): + UserManager.__init__(self, group_manager, settings=settings) + + if path is None: + path = self._settings.get(["accessControl", "userfile"]) + if path is None: + path = os.path.join(s().getBaseFolder("base"), "users.yaml") + + self._userfile = path + + self._users = {} + self._dirty = False + + self._customized = None + self._load() + + def _load(self): + if os.path.exists(self._userfile) and os.path.isfile(self._userfile): + self._customized = True + with io.open(self._userfile, "rt", encoding="utf-8") as f: + data = yaml.safe_load(f) + + for name, attributes in data.items(): + if not isinstance(attributes, dict): + continue + + permissions = [] + if "permissions" in attributes: + permissions = attributes["permissions"] + + 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 not "permissions" 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, + ) + 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() + + else: + self._customized = False + + def _save(self, force=False): + if not self._dirty and not force: + return + + data = {} + for name, user in self._users.items(): + if not user or not isinstance(user, User): + continue + + data[name] = { + "password": user._passwordHash, + "active": user._active, + "groups": self._from_groups(*user._groups), + "permissions": self._from_permissions(*user._permissions), + "apikey": user._apikey, + "settings": user._settings, + # TODO: deprecated, remove in 1.5.0 + "roles": user._roles, + } + + with atomic_write( + self._userfile, mode="wt", permissions=0o600, max_permissions=0o666 + ) as f: + yaml.safe_dump( + data, f, default_flow_style=False, indent=4, allow_unicode=True + ) + self._dirty = False + self._load() + + def _migrate_roles_to_groups(self, roles): + # If admin is inside the roles, just return admin group + if "admin" in roles: + return [self._group_manager.admin_group, self._group_manager.user_group] + else: + return [self._group_manager.user_group] + + def _refresh_groups(self, user): + user._groups = self._to_groups(*map(lambda g: g.key, user.groups)) + + def add_user( + self, + username, + password, + active=False, + permissions=None, + groups=None, + apikey=None, + overwrite=False, + ): + if not permissions: + permissions = [] + permissions = self._to_permissions(*permissions) + + if not groups: + groups = self._group_manager.default_groups + groups = self._to_groups(*groups) + + if username in self._users and not overwrite: + raise UserAlreadyExists(username) + + self._users[username] = User( + username, + UserManager.create_password_hash(password, settings=self._settings), + active, + permissions, + groups, + apikey=apikey, + ) + self._dirty = True + self._save() + + def change_user_activation(self, username, active): + if username not in self._users: + raise UnknownUser(username) + + if self._users[username].is_active != active: + self._users[username]._active = active + self._dirty = True + self._save() + + self._trigger_on_user_modified(username) + + def change_user_permissions(self, username, permissions): + if username not in self._users: + raise UnknownUser(username) + + user = self._users[username] + + permissions = self._to_permissions(*permissions) + + removed_permissions = list(set(user._permissions) - set(permissions)) + added_permissions = list(set(permissions) - set(user._permissions)) + + if len(removed_permissions) > 0: + user.remove_permissions_from_user(removed_permissions) + self._dirty = True + + if len(added_permissions) > 0: + user.add_permissions_to_user(added_permissions) + self._dirty = True + + if self._dirty: + self._save() + self._trigger_on_user_modified(username) + + def add_permissions_to_user(self, username, permissions): + if username not in self._users: + raise UnknownUser(username) + + if self._users[username].add_permissions_to_user( + self._to_permissions(*permissions) + ): + self._dirty = True + self._save() + self._trigger_on_user_modified(username) + + def remove_permissions_from_user(self, username, permissions): + if username not in self._users: + raise UnknownUser(username) + + if self._users[username].remove_permissions_from_user( + self._to_permissions(*permissions) + ): + self._dirty = True + self._save() + self._trigger_on_user_modified(username) + + def remove_permissions_from_users(self, permissions): + modified = [] + for user in self._users: + dirty = user.remove_permissions_from_user(self._to_permissions(*permissions)) + if dirty: + self._dirty = True + modified.append(user.get_id()) + + if self._dirty: + self._save() + for username in modified: + self._trigger_on_user_modified(username) + + def change_user_groups(self, username, groups): + if username not in self._users: + raise UnknownUser(username) + + user = self._users[username] + + groups = self._to_groups(*groups) + + removed_groups = list(set(user._groups) - set(groups)) + added_groups = list(set(groups) - set(user._groups)) + + if len(removed_groups): + self._dirty |= user.remove_groups_from_user(removed_groups) + if len(added_groups): + self._dirty |= user.add_groups_to_user(added_groups) + + if self._dirty: + self._save() + self._trigger_on_user_modified(username) + + def add_groups_to_user(self, username, groups, save=True, notify=True): + if username not in self._users: + raise UnknownUser(username) + + if self._users[username].add_groups_to_user(self._to_groups(*groups)): + self._dirty = True + + if save: + self._save() + + if notify: + self._trigger_on_user_modified(username) + + def remove_groups_from_user(self, username, groups, save=True, notify=True): + if username not in self._users: + raise UnknownUser(username) + + if self._users[username].remove_groups_from_user(self._to_groups(*groups)): + self._dirty = True - def remove_groups_from_user(self, username, groups, save=True, notify=True): - if username not in self._users: - raise UnknownUser(username) + if save: + self._save() + + if notify: + self._trigger_on_user_modified(username) + + def remove_groups_from_users(self, groups): + modified = [] + for username, user in self._users.items(): + dirty = user.remove_groups_from_user(self._to_groups(*groups)) + if dirty: + self._dirty = True + modified.append(username) + + if self._dirty: + self._save() + + for username in modified: + self._trigger_on_user_modified(username) + + def change_user_password(self, username, password): + if not username in self._users: + raise UnknownUser(username) + + passwordHash = UserManager.create_password_hash(password, settings=self._settings) + user = self._users[username] + if user._passwordHash != passwordHash: + user._passwordHash = passwordHash + self._dirty = True + self._save() + + def change_user_setting(self, username, key, value): + if not username in self._users: + raise UnknownUser(username) + + user = self._users[username] + old_value = user.get_setting(key) + if not old_value or old_value != value: + user.set_setting(key, value) + self._dirty = self._dirty or old_value != value + self._save() + + def change_user_settings(self, username, new_settings): + if not username in self._users: + raise UnknownUser(username) + + user = self._users[username] + for key, value in new_settings.items(): + old_value = user.get_setting(key) + user.set_setting(key, value) + self._dirty = self._dirty or old_value != value + self._save() + + def get_all_user_settings(self, username): + if not username in self._users: + raise UnknownUser(username) + + user = self._users[username] + return user.get_all_settings() + + def get_user_setting(self, username, key): + if not username in self._users: + raise UnknownUser(username) + + user = self._users[username] + return user.get_setting(key) + + def generate_api_key(self, username): + if not username in self._users: + raise UnknownUser(username) + + user = self._users[username] + user._apikey = generate_api_key() + self._dirty = True + self._save() + return user._apikey + + def delete_api_key(self, username): + if not username in self._users: + raise UnknownUser(username) + + user = self._users[username] + user._apikey = None + self._dirty = True + self._save() + + def remove_user(self, username): + UserManager.remove_user(self, username) + + if not username in self._users: + raise UnknownUser(username) + + del self._users[username] + self._dirty = True + self._save() + + def find_user(self, userid=None, apikey=None, session=None): + user = UserManager.find_user(self, userid=userid, session=session) + + if user is not None: + return user + + if userid is not None: + if userid not in self._users: + return None + return self._users[userid] + + elif apikey is not None: + for user in self._users.values(): + if apikey == user._apikey: + return user + return None + + else: + return None + + def get_all_users(self): + return list(self._users.values()) + + def has_been_customized(self): + return self._customized + + def on_group_permissions_changed(self, group, added=None, removed=None): + # refresh our group references + for user in self.get_all_users(): + if group in user.groups: + self._refresh_groups(user) + + # call parent + UserManager.on_group_permissions_changed( + self, group, added=added, removed=removed + ) + + def on_group_subgroups_changed(self, group, added=None, removed=None): + # refresh our group references + for user in self.get_all_users(): + if group in user.groups: + self._refresh_groups(user) + + # call parent + UserManager.on_group_subgroups_changed(self, group, added=added, removed=removed) + + # ~~ Helpers + + def _to_groups(self, *groups): + return list( + set( + filter( + lambda x: x is not None, + (self._group_manager._to_group(group) for group in groups), + ) + ) + ) + + def _to_permissions(self, *permissions): + return list( + set( + filter( + lambda x: x is not None, + (Permissions.find(permission) for permission in permissions), + ) + ) + ) + + def _from_groups(self, *groups): + return list({group.key for group in groups}) + + def _from_permissions(self, *permissions): + return list({permission.key for permission in permissions}) + + # ~~ Deprecated methods follow + + # TODO: Remove deprecated methods in OctoPrint 1.5.0 + + generateApiKey = deprecated( + "generateApiKey has been renamed to generate_api_key", + includedoc="Replaced by :func:`generate_api_key`", + since="1.4.0", + )(generate_api_key) + deleteApiKey = deprecated( + "deleteApiKey has been renamed to delete_api_key", + includedoc="Replaced by :func:`delete_api_key`", + since="1.4.0", + )(delete_api_key) + addUser = deprecated( + "addUser has been renamed to add_user", + includedoc="Replaced by :func:`add_user`", + since="1.4.0", + )(add_user) + changeUserActivation = deprecated( + "changeUserActivation has been renamed to change_user_activation", + includedoc="Replaced by :func:`change_user_activation`", + since="1.4.0", + )(change_user_activation) + changeUserPassword = deprecated( + "changeUserPassword has been renamed to change_user_password", + includedoc="Replaced by :func:`change_user_password`", + since="1.4.0", + )(change_user_password) + getUserSetting = deprecated( + "getUserSetting has been renamed to get_user_setting", + includedoc="Replaced by :func:`get_user_setting`", + since="1.4.0", + )(get_user_setting) + getAllUserSettings = deprecated( + "getAllUserSettings has been renamed to get_all_user_settings", + includedoc="Replaced by :func:`get_all_user_settings`", + since="1.4.0", + )(get_all_user_settings) + changeUserSetting = deprecated( + "changeUserSetting has been renamed to change_user_setting", + includedoc="Replaced by :func:`change_user_setting`", + since="1.4.0", + )(change_user_setting) + changeUserSettings = deprecated( + "changeUserSettings has been renamed to change_user_settings", + includedoc="Replaced by :func:`change_user_settings`", + since="1.4.0", + )(change_user_settings) + removeUser = deprecated( + "removeUser has been renamed to remove_user", + includedoc="Replaced by :func:`remove_user`", + since="1.4.0", + )(remove_user) + findUser = deprecated( + "findUser has been renamed to find_user", + includedoc="Replaced by :func:`find_user`", + since="1.4.0", + )(find_user) + getAllUsers = deprecated( + "getAllUsers has been renamed to get_all_users", + includedoc="Replaced by :func:`get_all_users`", + since="1.4.0", + )(get_all_users) + hasBeenCustomized = deprecated( + "hasBeenCustomized has been renamed to has_been_customized", + includedoc="Replaced by :func:`has_been_customized`", + since="1.4.0", + )(has_been_customized) - if self._users[username].remove_groups_from_user(self._to_groups(*groups)): - self._dirty = True - - if save: - self._save() - - if notify: - self._trigger_on_user_modified(username) - - def remove_groups_from_users(self, groups): - modified = [] - for username, user in self._users.items(): - dirty = user.remove_groups_from_user(self._to_groups(*groups)) - if dirty: - self._dirty = True - modified.append(username) - - if self._dirty: - self._save() - - for username in modified: - self._trigger_on_user_modified(username) - - def change_user_password(self, username, password): - if not username in self._users: - raise UnknownUser(username) - - passwordHash = UserManager.create_password_hash(password, - settings=self._settings) - user = self._users[username] - if user._passwordHash != passwordHash: - user._passwordHash = passwordHash - self._dirty = True - self._save() - - def change_user_setting(self, username, key, value): - if not username in self._users: - raise UnknownUser(username) - - user = self._users[username] - old_value = user.get_setting(key) - if not old_value or old_value != value: - user.set_setting(key, value) - self._dirty = self._dirty or old_value != value - self._save() - - def change_user_settings(self, username, new_settings): - if not username in self._users: - raise UnknownUser(username) - - user = self._users[username] - for key, value in new_settings.items(): - old_value = user.get_setting(key) - user.set_setting(key, value) - self._dirty = self._dirty or old_value != value - self._save() - - def get_all_user_settings(self, username): - if not username in self._users: - raise UnknownUser(username) - - user = self._users[username] - return user.get_all_settings() - - def get_user_setting(self, username, key): - if not username in self._users: - raise UnknownUser(username) - - user = self._users[username] - return user.get_setting(key) - - def generate_api_key(self, username): - if not username in self._users: - raise UnknownUser(username) - - user = self._users[username] - user._apikey = generate_api_key() - self._dirty = True - self._save() - return user._apikey - - def delete_api_key(self, username): - if not username in self._users: - raise UnknownUser(username) - - user = self._users[username] - user._apikey = None - self._dirty = True - self._save() - - def remove_user(self, username): - UserManager.remove_user(self, username) - - if not username in self._users: - raise UnknownUser(username) - - del self._users[username] - self._dirty = True - self._save() - - def find_user(self, userid=None, apikey=None, session=None): - user = UserManager.find_user(self, userid=userid, session=session) - - if user is not None: - return user - - if userid is not None: - if userid not in self._users: - return None - return self._users[userid] - - elif apikey is not None: - for user in self._users.values(): - if apikey == user._apikey: - return user - return None - - else: - return None - - def get_all_users(self): - return list(self._users.values()) - - def has_been_customized(self): - return self._customized - - def on_group_permissions_changed(self, group, added=None, removed=None): - # refresh our group references - for user in self.get_all_users(): - if group in user.groups: - self._refresh_groups(user) - - # call parent - UserManager.on_group_permissions_changed(self, group, added=added, removed=removed) - - def on_group_subgroups_changed(self, group, added=None, removed=None): - # refresh our group references - for user in self.get_all_users(): - if group in user.groups: - self._refresh_groups(user) - - # call parent - UserManager.on_group_subgroups_changed(self, group, added=added, removed=removed) - - #~~ Helpers - - def _to_groups(self, *groups): - return list(set(filter(lambda x: x is not None, - (self._group_manager._to_group(group) for group in groups)))) - - def _to_permissions(self, *permissions): - return list(set(filter(lambda x: x is not None, - (Permissions.find(permission) for permission in permissions)))) - - def _from_groups(self, *groups): - return list({group.key for group in groups}) - - def _from_permissions(self, *permissions): - return list({permission.key for permission in permissions}) - - # ~~ Deprecated methods follow - - # TODO: Remove deprecated methods in OctoPrint 1.5.0 - - generateApiKey = deprecated("generateApiKey has been renamed to generate_api_key", - includedoc="Replaced by :func:`generate_api_key`", - since="1.4.0")(generate_api_key) - deleteApiKey = deprecated("deleteApiKey has been renamed to delete_api_key", - includedoc="Replaced by :func:`delete_api_key`", - since="1.4.0")(delete_api_key) - addUser = deprecated("addUser has been renamed to add_user", - includedoc="Replaced by :func:`add_user`", - since="1.4.0")(add_user) - changeUserActivation = deprecated("changeUserActivation has been renamed to change_user_activation", - includedoc="Replaced by :func:`change_user_activation`", - since="1.4.0")(change_user_activation) - changeUserPassword = deprecated("changeUserPassword has been renamed to change_user_password", - includedoc="Replaced by :func:`change_user_password`", - since="1.4.0")(change_user_password) - getUserSetting = deprecated("getUserSetting has been renamed to get_user_setting", - includedoc="Replaced by :func:`get_user_setting`", - since="1.4.0")(get_user_setting) - getAllUserSettings = deprecated("getAllUserSettings has been renamed to get_all_user_settings", - includedoc="Replaced by :func:`get_all_user_settings`", - since="1.4.0")(get_all_user_settings) - changeUserSetting = deprecated("changeUserSetting has been renamed to change_user_setting", - includedoc="Replaced by :func:`change_user_setting`", - since="1.4.0")(change_user_setting) - changeUserSettings = deprecated("changeUserSettings has been renamed to change_user_settings", - includedoc="Replaced by :func:`change_user_settings`", - since="1.4.0")(change_user_settings) - removeUser = deprecated("removeUser has been renamed to remove_user", - includedoc="Replaced by :func:`remove_user`", - since="1.4.0")(remove_user) - findUser = deprecated("findUser has been renamed to find_user", - includedoc="Replaced by :func:`find_user`", - since="1.4.0")(find_user) - getAllUsers = deprecated("getAllUsers has been renamed to get_all_users", - includedoc="Replaced by :func:`get_all_users`", - since="1.4.0")(get_all_users) - hasBeenCustomized = deprecated("hasBeenCustomized has been renamed to has_been_customized", - includedoc="Replaced by :func:`has_been_customized`", - since="1.4.0")(has_been_customized) ##~~ Exceptions + class UserAlreadyExists(Exception): - def __init__(self, username): - Exception.__init__(self, "User %s already exists" % username) + def __init__(self, username): + Exception.__init__(self, "User %s already exists" % username) class UnknownUser(Exception): - def __init__(self, username): - Exception.__init__(self, "Unknown user: %s" % username) + def __init__(self, username): + Exception.__init__(self, "Unknown user: %s" % username) class UnknownRole(Exception): - def _init_(self, role): - Exception.__init__(self, "Unknown role: %s" % role) + def _init_(self, role): + Exception.__init__(self, "Unknown role: %s" % role) + ##~~ Refactoring helpers + class MethodReplacedByBooleanProperty(object): + def __init__(self, name, message, getter): + self._name = name + self._message = message + self._getter = getter - def __init__(self, name, message, getter): - self._name = name - self._message = message - self._getter = getter + @property + def _attr(self): + return self._getter() - @property - def _attr(self): - return self._getter() + def __call__(self): + from warnings import warn - def __call__(self): - from warnings import warn - warn(DeprecationWarning(self._message.format(name=self._name)), stacklevel=2) - return self._attr + warn(DeprecationWarning(self._message.format(name=self._name)), stacklevel=2) + return self._attr - def __eq__(self, other): - return self._attr == other + def __eq__(self, other): + return self._attr == other - def __ne__(self, other): - return self._attr != other + def __ne__(self, other): + return self._attr != other - def __bool__(self): - # Python 3 - return self._attr + def __bool__(self): + # Python 3 + return self._attr - def __nonzero__(self): - # Python 2 - return self._attr + def __nonzero__(self): + # Python 2 + return self._attr - def __hash__(self): - return hash(self._attr) + def __hash__(self): + return hash(self._attr) - def __repr__(self): - return "MethodReplacedByProperty({}, {}, {})".format(self._name, self._message, self._getter) + def __repr__(self): + return "MethodReplacedByProperty({}, {}, {})".format( + self._name, self._message, self._getter + ) - def __str__(self): - return str(self._attr) + def __str__(self): + return str(self._attr) # TODO: Remove compatibility layer in OctoPrint 1.5.0 class FlaskLoginMethodReplacedByBooleanProperty(MethodReplacedByBooleanProperty): - - def __init__(self, name, getter): - message = "{name} is now a property in Flask-Login versions >= 0.3.0, which OctoPrint now uses. " + \ - "Use {name} instead of {name}(). This compatibility layer will be removed in OctoPrint 1.5.0." - MethodReplacedByBooleanProperty.__init__(self, name, message, getter) + def __init__(self, name, getter): + message = ( + "{name} is now a property in Flask-Login versions >= 0.3.0, which OctoPrint now uses. " + + "Use {name} instead of {name}(). This compatibility layer will be removed in OctoPrint 1.5.0." + ) + MethodReplacedByBooleanProperty.__init__(self, name, message, getter) # TODO: Remove compatibility layer in OctoPrint 1.5.0 class OctoPrintUserMethodReplacedByBooleanProperty(MethodReplacedByBooleanProperty): + def __init__(self, name, getter): + message = ( + "{name} is now a property for consistency reasons with Flask-Login versions >= 0.3.0, which " + + "OctoPrint now uses. Use {name} instead of {name}(). This compatibility layer will be removed " + + "in OctoPrint 1.5.0." + ) + MethodReplacedByBooleanProperty.__init__(self, name, message, getter) - def __init__(self, name, getter): - message = "{name} is now a property for consistency reasons with Flask-Login versions >= 0.3.0, which " + \ - "OctoPrint now uses. Use {name} instead of {name}(). This compatibility layer will be removed " + \ - "in OctoPrint 1.5.0." - MethodReplacedByBooleanProperty.__init__(self, name, message, getter) ##~~ User object + class User(UserMixin): - def __init__(self, username, passwordHash, active, permissions=None, groups=None, apikey=None, settings=None): - if permissions is None: - permissions = [] - if groups is None: - groups = [] + def __init__( + self, + username, + passwordHash, + active, + permissions=None, + groups=None, + apikey=None, + settings=None, + ): + if permissions is None: + permissions = [] + if groups is None: + groups = [] - self._username = username - self._passwordHash = passwordHash - self._active = active - self._permissions = permissions - self._groups = groups - self._apikey = apikey + self._username = username + self._passwordHash = passwordHash + self._active = active + self._permissions = permissions + self._groups = groups + self._apikey = apikey - if settings is None: - settings = {} + if settings is None: + settings = {} - self._settings = settings + self._settings = settings - def as_dict(self): - from octoprint.access.permissions import OctoPrintPermission - return { - "name": self._username, - "active": bool(self.is_active), - "permissions": list(map(lambda p: p.key, self._permissions)), - "groups": list(map(lambda g: g.key, self._groups)), - "needs": OctoPrintPermission.convert_needs_to_dict(self.needs), - "apikey": self._apikey, - "settings": self._settings, + def as_dict(self): + from octoprint.access.permissions import OctoPrintPermission - # TODO: deprecated, remove in 1.5.0 - "admin": self.has_permission(Permissions.ADMIN), - "user": not self.is_anonymous, - "roles": self._roles - } + return { + "name": self._username, + "active": bool(self.is_active), + "permissions": list(map(lambda p: p.key, self._permissions)), + "groups": list(map(lambda g: g.key, self._groups)), + "needs": OctoPrintPermission.convert_needs_to_dict(self.needs), + "apikey": self._apikey, + "settings": self._settings, + # TODO: deprecated, remove in 1.5.0 + "admin": self.has_permission(Permissions.ADMIN), + "user": not self.is_anonymous, + "roles": self._roles, + } - def check_password(self, passwordHash): - return self._passwordHash == passwordHash + def check_password(self, passwordHash): + return self._passwordHash == passwordHash - def get_id(self): - return self.get_name() + def get_id(self): + return self.get_name() - def get_name(self): - return self._username + def get_name(self): + return self._username - @property - def is_anonymous(self): - return FlaskLoginMethodReplacedByBooleanProperty("is_anonymous", lambda: False) + @property + def is_anonymous(self): + return FlaskLoginMethodReplacedByBooleanProperty("is_anonymous", lambda: False) - @property - def is_authenticated(self): - return FlaskLoginMethodReplacedByBooleanProperty("is_authenticated", lambda: True) + @property + def is_authenticated(self): + return FlaskLoginMethodReplacedByBooleanProperty("is_authenticated", lambda: True) - @property - def is_active(self): - return FlaskLoginMethodReplacedByBooleanProperty("is_active", lambda: self._active) + @property + def is_active(self): + return FlaskLoginMethodReplacedByBooleanProperty( + "is_active", lambda: self._active + ) - def get_all_settings(self): - return self._settings + def get_all_settings(self): + return self._settings - def get_setting(self, key): - if not isinstance(key, (tuple, list)): - path = [key] - else: - path = key + def get_setting(self, key): + if not isinstance(key, (tuple, list)): + path = [key] + else: + path = key - return self._get_setting(path) + return self._get_setting(path) - def set_setting(self, key, value): - if not isinstance(key, (tuple, list)): - path = [key] - else: - path = key - return self._set_setting(path, value) + def set_setting(self, key, value): + if not isinstance(key, (tuple, list)): + path = [key] + else: + path = key + return self._set_setting(path, value) - def _get_setting(self, path): - s = self._settings - for p in path: - if isinstance(s, dict) and p in s: - s = s[p] - else: - return None - return s + def _get_setting(self, path): + s = self._settings + for p in path: + if isinstance(s, dict) and p in s: + s = s[p] + else: + return None + return s - def _set_setting(self, path, value): - s = self._settings - for p in path[:-1]: - if p not in s: - s[p] = {} + def _set_setting(self, path, value): + s = self._settings + for p in path[:-1]: + if p not in s: + s[p] = {} - if not isinstance(s[p], dict): - s[p] = {} + if not isinstance(s[p], dict): + s[p] = {} - s = s[p] + s = s[p] - key = path[-1] - s[key] = value - return True + key = path[-1] + s[key] = value + return True - def add_permissions_to_user(self, permissions): - # Make sure the permissions variable is of type list - if not isinstance(permissions, list): - permissions = [permissions] + def add_permissions_to_user(self, permissions): + # Make sure the permissions variable is of type list + if not isinstance(permissions, list): + permissions = [permissions] - assert(all(map(lambda p: isinstance(p, OctoPrintPermission), permissions))) + assert all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)) - dirty = False - for permission in permissions: - if permissions not in self._permissions: - self._permissions.append(permission) - dirty = True + dirty = False + for permission in permissions: + if permissions not in self._permissions: + self._permissions.append(permission) + dirty = True - return dirty + return dirty - def remove_permissions_from_user(self, permissions): - # Make sure the permissions variable is of type list - if not isinstance(permissions, list): - permissions = [permissions] + def remove_permissions_from_user(self, permissions): + # Make sure the permissions variable is of type list + if not isinstance(permissions, list): + permissions = [permissions] - assert(all(map(lambda p: isinstance(p, OctoPrintPermission), permissions))) + assert all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)) - dirty = False - for permission in permissions: - if permission in self._permissions: - self._permissions.remove(permission) - dirty = True + dirty = False + for permission in permissions: + if permission in self._permissions: + self._permissions.remove(permission) + dirty = True - return dirty + return dirty - def add_groups_to_user(self, groups): - # Make sure the groups variable is of type list - if not isinstance(groups, list): - groups = [groups] + def add_groups_to_user(self, groups): + # Make sure the groups variable is of type list + if not isinstance(groups, list): + groups = [groups] - assert(all(map(lambda p: isinstance(p, Group), groups))) + assert all(map(lambda p: isinstance(p, Group), groups)) - dirty = False - for group in groups: - if group.is_toggleable() and group not in self._groups: - self._groups.append(group) - dirty = True + dirty = False + for group in groups: + if group.is_toggleable() and group not in self._groups: + self._groups.append(group) + dirty = True - return dirty + return dirty - def remove_groups_from_user(self, groups): - # Make sure the groups variable is of type list - if not isinstance(groups, list): - groups = [groups] + def remove_groups_from_user(self, groups): + # Make sure the groups variable is of type list + if not isinstance(groups, list): + groups = [groups] - assert(all(map(lambda p: isinstance(p, Group), groups))) + assert all(map(lambda p: isinstance(p, Group), groups)) - dirty = False - for group in groups: - if group.is_toggleable() and group in self._groups: - self._groups.remove(group) - dirty = True + dirty = False + for group in groups: + if group.is_toggleable() and group in self._groups: + self._groups.remove(group) + dirty = True - return dirty + return dirty - @property - def permissions(self): - if self._permissions is None: - return [] + @property + def permissions(self): + if self._permissions is None: + return [] - if Permissions.ADMIN in self._permissions: - return Permissions.all() + if Permissions.ADMIN in self._permissions: + return Permissions.all() - return list(filter(lambda p: p is not None, self._permissions)) + return list(filter(lambda p: p is not None, self._permissions)) - @property - def groups(self): - return list(self._groups) + @property + def groups(self): + return list(self._groups) - @property - def effective_permissions(self): - if self._permissions is None: - return [] - return list(filter(lambda p: p is not None and self.has_permission(p), Permissions.all())) + @property + def effective_permissions(self): + if self._permissions is None: + return [] + return list( + filter(lambda p: p is not None and self.has_permission(p), Permissions.all()) + ) - @property - def needs(self): - needs = set() + @property + def needs(self): + needs = set() - for permission in self.permissions: - if permission is not None: - needs = needs.union(permission.needs) + for permission in self.permissions: + if permission is not None: + needs = needs.union(permission.needs) - for group in self.groups: - if group is not None: - needs = needs.union(group.needs) + for group in self.groups: + if group is not None: + needs = needs.union(group.needs) - return needs + return needs - def has_permission(self, permission): - return self.has_needs(*permission.needs) + def has_permission(self, permission): + return self.has_needs(*permission.needs) - def has_needs(self, *needs): - return set(needs).issubset(self.needs) + def has_needs(self, *needs): + return set(needs).issubset(self.needs) - def __repr__(self): - return "User(id=%s,name=%s,active=%r,user=True,admin=%r,permissions=%s,groups=%s)" % (self.get_id(), self.get_name(), bool(self.is_active), self.has_permission(Permissions.ADMIN), self._permissions, self._groups) + def __repr__(self): + return ( + "User(id=%s,name=%s,active=%r,user=True,admin=%r,permissions=%s,groups=%s)" + % ( + self.get_id(), + self.get_name(), + bool(self.is_active), + self.has_permission(Permissions.ADMIN), + self._permissions, + self._groups, + ) + ) - # ~~ Deprecated methods & properties follow + # ~~ Deprecated methods & properties follow - # TODO: Remove deprecated methods & properties in OctoPrint 1.5.0 + # TODO: Remove deprecated methods & properties in OctoPrint 1.5.0 - asDict = deprecated("asDict has been renamed to as_dict", - includedoc="Replaced by :func:`as_dict`", - since="1.4.0")(as_dict) + asDict = deprecated( + "asDict has been renamed to as_dict", + includedoc="Replaced by :func:`as_dict`", + since="1.4.0", + )(as_dict) - @property - @deprecated("is_user is deprecated, please use has_permission", since="1.4.0") - def is_user(self): - return OctoPrintUserMethodReplacedByBooleanProperty("is_user", lambda: not self.is_anonymous) + @property + @deprecated("is_user is deprecated, please use has_permission", since="1.4.0") + def is_user(self): + return OctoPrintUserMethodReplacedByBooleanProperty( + "is_user", lambda: not self.is_anonymous + ) - @property - @deprecated("is_admin is deprecated, please use has_permission", since="1.4.0") - def is_admin(self): - return OctoPrintUserMethodReplacedByBooleanProperty("is_admin", lambda: self.has_permission(Permissions.ADMIN)) + @property + @deprecated("is_admin is deprecated, please use has_permission", since="1.4.0") + def is_admin(self): + return OctoPrintUserMethodReplacedByBooleanProperty( + "is_admin", lambda: self.has_permission(Permissions.ADMIN) + ) - @property - @deprecated("roles is deprecated, please use has_permission", since="1.4.0") - def roles(self): - return self._roles + @property + @deprecated("roles is deprecated, please use has_permission", since="1.4.0") + def roles(self): + return self._roles - @property - def _roles(self): - """Helper for the deprecated self.roles and serializing to yaml""" - if self.has_permission(Permissions.ADMIN): - return ["user", "admin"] - elif not self.is_anonymous: - return ["user"] - else: - return [] + @property + def _roles(self): + """Helper for the deprecated self.roles and serializing to yaml""" + if self.has_permission(Permissions.ADMIN): + return ["user", "admin"] + elif not self.is_anonymous: + return ["user"] + else: + return [] class AnonymousUser(AnonymousUserMixin, User): - def __init__(self, groups): - User.__init__(self, None, "", True, [], groups) + def __init__(self, groups): + User.__init__(self, None, "", True, [], groups) - @property - def is_anonymous(self): - return FlaskLoginMethodReplacedByBooleanProperty("is_anonymous", lambda: True) + @property + def is_anonymous(self): + return FlaskLoginMethodReplacedByBooleanProperty("is_anonymous", lambda: True) - @property - def is_authenticated(self): - return FlaskLoginMethodReplacedByBooleanProperty("is_authenticated", lambda: False) + @property + def is_authenticated(self): + return FlaskLoginMethodReplacedByBooleanProperty( + "is_authenticated", lambda: False + ) - @property - def is_active(self): - return FlaskLoginMethodReplacedByBooleanProperty("is_active", lambda: self._active) + @property + def is_active(self): + return FlaskLoginMethodReplacedByBooleanProperty( + "is_active", lambda: self._active + ) - def check_password(self, passwordHash): - return True + def check_password(self, passwordHash): + return True - def as_dict(self): - from octoprint.access.permissions import OctoPrintPermission - return { - "needs": OctoPrintPermission.convert_needs_to_dict(self.needs) - } + def as_dict(self): + from octoprint.access.permissions import OctoPrintPermission - def __repr__(self): - return "AnonymousUser(groups=%s)" % self._groups + return {"needs": OctoPrintPermission.convert_needs_to_dict(self.needs)} + + def __repr__(self): + return "AnonymousUser(groups=%s)" % self._groups class SessionUser(wrapt.ObjectProxy): - def __init__(self, user): - wrapt.ObjectProxy.__init__(self, user) + def __init__(self, user): + wrapt.ObjectProxy.__init__(self, user) - self._self_session = "".join('%02X' % z for z in bytes(uuid.uuid4().bytes)) - self._self_created = monotonic_time() - self._self_touched = monotonic_time() + self._self_session = "".join("%02X" % z for z in bytes(uuid.uuid4().bytes)) + self._self_created = monotonic_time() + self._self_touched = monotonic_time() - @property - def session(self): - return self._self_session + @property + def session(self): + return self._self_session - @property - def created(self): - return self._self_created + @property + def created(self): + return self._self_created - @property - def touched(self): - return self._self_touched + @property + def touched(self): + return self._self_touched - def touch(self): - self._self_touched = monotonic_time() + def touch(self): + self._self_touched = monotonic_time() - @deprecated("SessionUser.get_session() has been deprecated, use SessionUser.session instead", since="1.3.5") - def get_session(self): - return self.session + @deprecated( + "SessionUser.get_session() has been deprecated, use SessionUser.session instead", + since="1.3.5", + ) + def get_session(self): + return self.session - def update_user(self, user): - self.__wrapped__ = user + def update_user(self, user): + self.__wrapped__ = user - def as_dict(self): - result = self.__wrapped__.as_dict() - result.update({"session": self.session}) - return result + def as_dict(self): + result = self.__wrapped__.as_dict() + result.update({"session": self.session}) + return result + + def __repr__(self): + return "SessionUser({!r},session={},created={})".format( + self.__wrapped__, self.session, self.created + ) - def __repr__(self): - return "SessionUser({!r},session={},created={})".format(self.__wrapped__, self.session, self.created) ##~~ User object to use when global api key is used to access the API + class ApiUser(User): - def __init__(self, groups): - User.__init__(self, "_api", "", True, [], groups) + def __init__(self, groups): + User.__init__(self, "_api", "", True, [], groups) + ##~~ User object to use when access control is disabled + class AdminUser(User): - def __init__(self, groups): - User.__init__(self, "_admin", "", True, [], groups) + def __init__(self, groups): + User.__init__(self, "_admin", "", True, [], groups) diff --git a/src/octoprint/cli/__init__.py b/src/octoprint/cli/__init__.py index 4a2a8c38b..09a039397 100644 --- a/src/octoprint/cli/__init__.py +++ b/src/octoprint/cli/__init__.py @@ -1,136 +1,201 @@ # -*- 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import click + click.disable_unicode_literals_warning = True import octoprint import sys -#~~ click context +# ~~ click context + class OctoPrintContext(object): - """Custom context wrapping the standard options.""" + """Custom context wrapping the standard options.""" + + def __init__(self, configfile=None, basedir=None, verbosity=0, safe_mode=False): + self.configfile = configfile + self.basedir = basedir + self.verbosity = verbosity + self.safe_mode = safe_mode - def __init__(self, configfile=None, basedir=None, verbosity=0, safe_mode=False): - self.configfile = configfile - self.basedir = basedir - self.verbosity = verbosity - self.safe_mode = safe_mode pass_octoprint_ctx = click.make_pass_decorator(OctoPrintContext, ensure=True) """Decorator to pass in the :class:`OctoPrintContext` instance.""" -#~~ Custom click option to hide from help +# ~~ Custom click option to hide from help + class HiddenOption(click.Option): - """Custom option sub class with empty help.""" - def get_help_record(self, ctx): - pass + """Custom option sub class with empty help.""" + + def get_help_record(self, ctx): + pass + def hidden_option(*param_decls, **attrs): - """Attaches a hidden option to the command. All positional arguments are - passed as parameter declarations to :class:`Option`; all keyword - arguments are forwarded unchanged. This is equivalent to creating an - :class:`Option` instance manually and attaching it to the - :attr:`Command.params` list. - """ + """Attaches a hidden option to the command. All positional arguments are + passed as parameter declarations to :class:`Option`; all keyword + arguments are forwarded unchanged. This is equivalent to creating an + :class:`Option` instance manually and attaching it to the + :attr:`Command.params` list. + """ - import inspect - from click.decorators import _param_memo + import inspect + from click.decorators import _param_memo - def decorator(f): - if 'help' in attrs: - attrs['help'] = inspect.cleandoc(attrs['help']) - _param_memo(f, HiddenOption(param_decls, **attrs)) - return f - return decorator + def decorator(f): + if "help" in attrs: + attrs["help"] = inspect.cleandoc(attrs["help"]) + _param_memo(f, HiddenOption(param_decls, **attrs)) + return f + + return decorator + + +# ~~ helper for setting context options -#~~ helper for setting context options def set_ctx_obj_option(ctx, param, value): - """Helper for setting eager options on the context.""" - if ctx.obj is None: - ctx.obj = OctoPrintContext() - if value != param.default: - setattr(ctx.obj, param.name, value) - elif param.default is not None: - setattr(ctx.obj, param.name, param.default) + """Helper for setting eager options on the context.""" + if ctx.obj is None: + ctx.obj = OctoPrintContext() + if value != param.default: + setattr(ctx.obj, param.name, value) + elif param.default is not None: + setattr(ctx.obj, param.name, param.default) + + +# ~~ helper for retrieving context options -#~~ helper for retrieving context options def get_ctx_obj_option(ctx, key, default, include_parents=True): - if include_parents and hasattr(ctx, "parent") and ctx.parent: - fallback = get_ctx_obj_option(ctx.parent, key, default) - else: - fallback = default - return getattr(ctx.obj, key, fallback) + if include_parents and hasattr(ctx, "parent") and ctx.parent: + fallback = get_ctx_obj_option(ctx.parent, key, default) + else: + fallback = default + return getattr(ctx.obj, key, fallback) + + +# ~~ helper for setting a lot of bulk options -#~~ helper for setting a lot of bulk options def bulk_options(options): - """ - Utility decorator to decorate a function with a list of click decorators. + """ + Utility decorator to decorate a function with a list of click decorators. - The provided list of ``options`` will be reversed to ensure correct - processing order (inverse from what would be intuitive). - """ + The provided list of ``options`` will be reversed to ensure correct + processing order (inverse from what would be intuitive). + """ - def decorator(f): - options.reverse() - for option in options: - option(f) - return f - return decorator + def decorator(f): + options.reverse() + for option in options: + option(f) + return f + + return decorator + + +# ~~ helper for setting --basedir, --config and --verbose options -#~~ helper for setting --basedir, --config and --verbose options def standard_options(hidden=False): - """ - Decorator to add the standard options shared among all "octoprint" commands. + """ + Decorator to add the standard options shared among all "octoprint" commands. - Adds the options ``--basedir``, ``--config`` and ``--verbose``. If ``hidden`` - is set to ``True``, the options will be available on the command but not - listed in its help page. - """ + Adds the options ``--basedir``, ``--config`` and ``--verbose``. If ``hidden`` + is set to ``True``, the options will be available on the command but not + listed in its help page. + """ - factory = click.option - if hidden: - factory = hidden_option + factory = click.option + if hidden: + factory = hidden_option - options = [ - factory("--basedir", "-b", type=click.Path(), callback=set_ctx_obj_option, is_eager=True, expose_value=False, - help="Specify the basedir to use for configs, uploads, timelapses etc."), - factory("--config", "-c", "configfile", type=click.Path(), callback=set_ctx_obj_option, is_eager=True, expose_value=False, - help="Specify the config file to use."), - factory("--verbose", "-v", "verbosity", count=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False, - help="Increase logging verbosity."), - factory("--safe", "safe_mode", is_flag=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False, - help="Enable safe mode; disables all third party plugins.") - ] + options = [ + factory( + "--basedir", + "-b", + type=click.Path(), + callback=set_ctx_obj_option, + is_eager=True, + expose_value=False, + help="Specify the basedir to use for configs, uploads, timelapses etc.", + ), + factory( + "--config", + "-c", + "configfile", + type=click.Path(), + callback=set_ctx_obj_option, + is_eager=True, + expose_value=False, + help="Specify the config file to use.", + ), + factory( + "--verbose", + "-v", + "verbosity", + count=True, + callback=set_ctx_obj_option, + is_eager=True, + expose_value=False, + help="Increase logging verbosity.", + ), + factory( + "--safe", + "safe_mode", + is_flag=True, + callback=set_ctx_obj_option, + is_eager=True, + expose_value=False, + help="Enable safe mode; disables all third party plugins.", + ), + ] - return bulk_options(options) + return bulk_options(options) -#~~ helper for settings legacy options we still have to support on "octoprint" -legacy_options = bulk_options([ - hidden_option("--host", type=click.STRING, callback=set_ctx_obj_option), - hidden_option("--port", type=click.INT, callback=set_ctx_obj_option), - hidden_option("--logging", type=click.Path(), callback=set_ctx_obj_option), - hidden_option("--debug", "-d", is_flag=True, callback=set_ctx_obj_option), - hidden_option("--daemon", type=click.Choice(["start", "stop", "restart"]), callback=set_ctx_obj_option), - hidden_option("--pid", type=click.Path(), default="/tmp/octoprint.pid", callback=set_ctx_obj_option), - hidden_option("--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option), - hidden_option("--ignore-blacklist", "ignore_blacklist", is_flag=True, callback=set_ctx_obj_option) -]) +# ~~ helper for settings legacy options we still have to support on "octoprint" + +legacy_options = bulk_options( + [ + hidden_option("--host", type=click.STRING, callback=set_ctx_obj_option), + hidden_option("--port", type=click.INT, callback=set_ctx_obj_option), + hidden_option("--logging", type=click.Path(), callback=set_ctx_obj_option), + hidden_option("--debug", "-d", is_flag=True, callback=set_ctx_obj_option), + hidden_option( + "--daemon", + type=click.Choice(["start", "stop", "restart"]), + callback=set_ctx_obj_option, + ), + hidden_option( + "--pid", + type=click.Path(), + default="/tmp/octoprint.pid", + callback=set_ctx_obj_option, + ), + hidden_option( + "--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option + ), + hidden_option( + "--ignore-blacklist", + "ignore_blacklist", + is_flag=True, + callback=set_ctx_obj_option, + ), + ] +) """Legacy options available directly on the "octoprint" command in earlier versions. Kept available for reasons of backwards compatibility, but hidden from the generated help pages.""" -#~~ "octoprint" command, merges server_commands and plugin_commands groups +# ~~ "octoprint" command, merges server_commands and plugin_commands groups from .server import server_commands from .plugins import plugin_commands @@ -140,38 +205,60 @@ from .config import config_commands from .analysis import analysis_commands from .user import user_commands -@click.group(name="octoprint", invoke_without_command=True, cls=click.CommandCollection, - sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands, analysis_commands, user_commands]) + +@click.group( + name="octoprint", + invoke_without_command=True, + cls=click.CommandCollection, + sources=[ + server_commands, + plugin_commands, + dev_commands, + client_commands, + config_commands, + analysis_commands, + user_commands, + ], +) @standard_options() @legacy_options @click.version_option(version=octoprint.__version__, allow_from_autoenv=False) @click.pass_context def octo(ctx, **kwargs): - if ctx.invoked_subcommand is None: - # We have to support calling the octoprint command without any - # sub commands to remain backwards compatible. - # - # But better print a message to inform people that they should - # use the sub commands instead. + if ctx.invoked_subcommand is None: + # We have to support calling the octoprint command without any + # sub commands to remain backwards compatible. + # + # But better print a message to inform people that they should + # use the sub commands instead. - def get_value(key): - return get_ctx_obj_option(ctx, key, kwargs.get(key)) - daemon = get_value("daemon") + def get_value(key): + return get_ctx_obj_option(ctx, key, kwargs.get(key)) - if daemon: - click.echo("Daemon operation via \"octoprint --daemon " - "start|stop|restart\" is deprecated, please use " - "\"octoprint daemon start|stop|restart\" from now on") + daemon = get_value("daemon") - if sys.platform == "win32" or sys.platform == "darwin": - click.echo("Sorry, daemon mode is not supported under your operating system right now") - else: - from octoprint.cli.server import daemon_command - ctx.invoke(daemon_command, command=daemon, **kwargs) - else: - click.echo("Starting the server via \"octoprint\" is deprecated, " - "please use \"octoprint serve\" from now on.") + if daemon: + click.echo( + 'Daemon operation via "octoprint --daemon ' + 'start|stop|restart" is deprecated, please use ' + '"octoprint daemon start|stop|restart" from now on' + ) - from octoprint.cli.server import serve_command - ctx.invoke(serve_command, **kwargs) + if sys.platform == "win32" or sys.platform == "darwin": + click.echo( + "Sorry, daemon mode is not supported under your operating system right now" + ) + else: + from octoprint.cli.server import daemon_command + + ctx.invoke(daemon_command, command=daemon, **kwargs) + else: + click.echo( + 'Starting the server via "octoprint" is deprecated, ' + 'please use "octoprint serve" from now on.' + ) + + from octoprint.cli.server import serve_command + + ctx.invoke(serve_command, **kwargs) diff --git a/src/octoprint/cli/analysis.py b/src/octoprint/cli/analysis.py index d549e5424..61a3ab757 100644 --- a/src/octoprint/cli/analysis.py +++ b/src/octoprint/cli/analysis.py @@ -1,22 +1,25 @@ # -*- 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" import click + click.disable_unicode_literals_warning = True -#~~ "octoprint util" commands +# ~~ "octoprint util" commands + @click.group() def analysis_commands(): - pass + pass + @analysis_commands.group(name="analysis") def util(): - """Analysis tools.""" - pass + """Analysis tools.""" + pass @util.command(name="gcode") @@ -30,49 +33,73 @@ def util(): @click.option("--g90-extruder", "g90_extruder", is_flag=True) @click.option("--progress", "progress", is_flag=True) @click.argument("path", type=click.Path()) -def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle_lines, g90_extruder, progress): - """Runs a GCODE file analysis.""" +def gcode_command( + path, + speedx, + speedy, + speedz, + offset, + maxt, + throttle, + throttle_lines, + g90_extruder, + progress, +): + """Runs a GCODE file analysis.""" - import time - import yaml - from octoprint.util import monotonic_time - from octoprint.util.gcodeInterpreter import gcode + import time + import yaml + from octoprint.util import monotonic_time + from octoprint.util.gcodeInterpreter import gcode - throttle_callback = None - if throttle: - def throttle_callback(filePos, readBytes): - if filePos % throttle_lines == 0: - # only apply throttle every $throttle_lines lines - time.sleep(throttle) + throttle_callback = None + if throttle: - offsets = offset - if offsets is None: - offsets = [] - elif isinstance(offset, tuple): - offsets = list(offsets) - offsets = [(0, 0)] + offsets - if len(offsets) < maxt: - offsets += [(0, 0)] * (maxt - len(offsets)) + def throttle_callback(filePos, readBytes): + if filePos % throttle_lines == 0: + # only apply throttle every $throttle_lines lines + time.sleep(throttle) - start_time = monotonic_time() + offsets = offset + if offsets is None: + offsets = [] + elif isinstance(offset, tuple): + offsets = list(offsets) + offsets = [(0, 0)] + offsets + if len(offsets) < maxt: + offsets += [(0, 0)] * (maxt - len(offsets)) - progress_callback = None - if progress: - def progress_callback(percentage): - click.echo("PROGRESS:{}".format(percentage)) - interpreter = gcode(progress_callback=progress_callback) + start_time = monotonic_time() - interpreter.load(path, - speedx=speedx, - speedy=speedy, - offsets=offsets, - throttle=throttle_callback, - max_extruders=maxt, - g90_extruder=g90_extruder) + progress_callback = None + if progress: + + def progress_callback(percentage): + click.echo("PROGRESS:{}".format(percentage)) + + interpreter = gcode(progress_callback=progress_callback) + + interpreter.load( + path, + speedx=speedx, + speedy=speedy, + offsets=offsets, + throttle=throttle_callback, + max_extruders=maxt, + g90_extruder=g90_extruder, + ) + + click.echo("DONE:{}s".format(monotonic_time() - start_time)) + click.echo("RESULTS:") + click.echo( + yaml.safe_dump( + interpreter.get_result(), + default_flow_style=False, + indent=4, + allow_unicode=True, + ) + ) - click.echo("DONE:{}s".format(monotonic_time() - start_time)) - click.echo("RESULTS:") - click.echo(yaml.safe_dump(interpreter.get_result(), default_flow_style=False, indent=4, allow_unicode=True)) if __name__ == "__main__": - gcode_command() + gcode_command() diff --git a/src/octoprint/cli/client.py b/src/octoprint/cli/client.py index 20f40e7b8..9f9e5974d 100644 --- a/src/octoprint/cli/client.py +++ b/src/octoprint/cli/client.py @@ -1,10 +1,11 @@ # -*- 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import click + click.disable_unicode_literals_warning = True import io @@ -17,91 +18,110 @@ from octoprint import init_settings, FatalStartupError from past.builtins import unicode + class JsonStringParamType(click.ParamType): - name = "json" + name = "json" - def convert(self, value, param, ctx): - try: - return json.loads(value) - except Exception: - self.fail("%s is not a valid json string" % value, param, ctx) + def convert(self, value, param, ctx): + try: + return json.loads(value) + except Exception: + self.fail("%s is not a valid json string" % value, param, ctx) -def create_client(settings=None, apikey=None, host=None, port=None, httpuser=None, httppass=None, https=False, prefix=None): - assert(host is not None or settings is not None) - assert(port is not None or settings is not None) - assert(apikey is not None or settings is not None) +def create_client( + settings=None, + apikey=None, + host=None, + port=None, + httpuser=None, + httppass=None, + https=False, + prefix=None, +): + assert host is not None or settings is not None + assert port is not None or settings is not None + assert apikey is not None or settings is not None - if not host: - host = settings.get(["server", "host"]) - host = host if host != "0.0.0.0" else "127.0.0.1" - if not port: - port = settings.getInt(["server", "port"]) + if not host: + host = settings.get(["server", "host"]) + host = host if host != "0.0.0.0" else "127.0.0.1" + if not port: + port = settings.getInt(["server", "port"]) - if not apikey: - apikey = settings.get(["api", "key"]) + if not apikey: + apikey = settings.get(["api", "key"]) - baseurl = octoprint_client.build_base_url(https=https, - httpuser=httpuser, - httppass=httppass, - host=host, - port=port, - prefix=prefix) + baseurl = octoprint_client.build_base_url( + https=https, + httpuser=httpuser, + httppass=httppass, + host=host, + port=port, + prefix=prefix, + ) - return octoprint_client.Client(baseurl, apikey) + return octoprint_client.Client(baseurl, apikey) -client_options = bulk_options([ - click.option("--apikey", "-a", type=click.STRING), - click.option("--host", "-h", type=click.STRING), - click.option("--port", "-p", type=click.INT), - click.option("--httpuser", type=click.STRING), - click.option("--httppass", type=click.STRING), - click.option("--https", is_flag=True), - click.option("--prefix", type=click.STRING) -]) +client_options = bulk_options( + [ + click.option("--apikey", "-a", type=click.STRING), + click.option("--host", "-h", type=click.STRING), + click.option("--port", "-p", type=click.INT), + click.option("--httpuser", type=click.STRING), + click.option("--httppass", type=click.STRING), + click.option("--https", is_flag=True), + click.option("--prefix", type=click.STRING), + ] +) """Common options to configure an API client.""" @click.group() def client_commands(): - pass + pass @client_commands.group("client", context_settings={"ignore_unknown_options": True}) @client_options @click.pass_context def client(ctx, apikey, host, port, httpuser, httppass, https, prefix): - """Basic API client.""" - try: - settings = None - if not host or not port or not apikey: - settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None)) + """Basic API client.""" + try: + settings = None + if not host or not port or not apikey: + settings = init_settings( + get_ctx_obj_option(ctx, "basedir", None), + get_ctx_obj_option(ctx, "configfile", None), + ) - ctx.obj.client = create_client(settings=settings, - apikey=apikey, - host=host, - port=port, - httpuser=httpuser, - httppass=httppass, - https=https, - prefix=prefix) + ctx.obj.client = create_client( + settings=settings, + apikey=apikey, + host=host, + port=port, + httpuser=httpuser, + httppass=httppass, + https=https, + prefix=prefix, + ) - except FatalStartupError as e: - click.echo(e.message, err=True) - click.echo("There was a fatal error initializing the client.", err=True) - ctx.exit(-1) + except FatalStartupError as e: + click.echo(e.message, err=True) + click.echo("There was a fatal error initializing the client.", err=True) + ctx.exit(-1) def log_response(response, status_code=True, body=True, headers=False): - if status_code: - click.echo("Status Code: {}".format(response.status_code)) - if headers: - for header, value in response.headers.items(): - click.echo("{}: {}".format(header, value)) - click.echo() - if body: - click.echo(response.text) + if status_code: + click.echo("Status Code: {}".format(response.status_code)) + if headers: + for header, value in response.headers.items(): + click.echo("{}: {}".format(header, value)) + click.echo() + if body: + click.echo(response.text) @client.command("get") @@ -109,9 +129,9 @@ def log_response(response, status_code=True, body=True, headers=False): @click.option("--timeout", type=float, default=None) @click.pass_context def get(ctx, path, timeout): - """Performs a GET request against the specified server path.""" - r = ctx.obj.client.get(path, timeout=timeout) - log_response(r) + """Performs a GET request against the specified server path.""" + r = ctx.obj.client.get(path, timeout=timeout) + log_response(r) @client.command("post_json") @@ -120,9 +140,9 @@ def get(ctx, path, timeout): @click.option("--timeout", type=float, default=None) @click.pass_context def post_json(ctx, path, data, timeout): - """POSTs JSON data to the specified server path.""" - r = ctx.obj.client.post_json(path, data, timeout=timeout) - log_response(r) + """POSTs JSON data to the specified server path.""" + r = ctx.obj.client.post_json(path, data, timeout=timeout) + log_response(r) @client.command("patch_json") @@ -131,75 +151,118 @@ def post_json(ctx, path, data, timeout): @click.option("--timeout", type=float, default=None, help="Request timeout in seconds") @click.pass_context def patch_json(ctx, path, data, timeout): - """PATCHes JSON data to the specified server path.""" - r = ctx.obj.client.patch(path, data, encoding="json", timeout=timeout) - log_response(r) + """PATCHes JSON data to the specified server path.""" + r = ctx.obj.client.patch(path, data, encoding="json", timeout=timeout) + log_response(r) @client.command("post_from_file") @click.argument("path") -@click.argument("file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True)) +@click.argument( + "file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True) +) @click.option("--json", is_flag=True) @click.option("--yaml", is_flag=True) @click.option("--timeout", type=float, default=None, help="Request timeout in seconds") @click.pass_context def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout): - """POSTs JSON data to the specified server path, taking the data from the specified file.""" - if json_flag or yaml_flag: - if json_flag: - with io.open(file_path, 'rt') as fp: - data = json.load(fp) - else: - import yaml - with io.open(file_path, 'rt') as fp: - data = yaml.safe_load(fp) + """POSTs JSON data to the specified server path, taking the data from the specified file.""" + if json_flag or yaml_flag: + if json_flag: + with io.open(file_path, "rt") as fp: + data = json.load(fp) + else: + import yaml - r = ctx.obj.client.post_json(path, data, timeout=timeout) - else: - with io.open(file_path, 'rb') as fp: - data = fp.read() + with io.open(file_path, "rt") as fp: + data = yaml.safe_load(fp) - r = ctx.obj.client.post(path, data, timeout=timeout) + r = ctx.obj.client.post_json(path, data, timeout=timeout) + else: + with io.open(file_path, "rb") as fp: + data = fp.read() - log_response(r) + r = ctx.obj.client.post(path, data, timeout=timeout) + + log_response(r) @client.command("command") @click.argument("path") @click.argument("command") -@click.option("--str", "-s", "str_params", multiple=True, nargs=2, type=click.Tuple([unicode, unicode])) -@click.option("--int", "-i", "int_params", multiple=True, nargs=2, type=click.Tuple([unicode, int])) -@click.option("--float", "-f", "float_params", multiple=True, nargs=2, type=click.Tuple([unicode, float])) -@click.option("--bool", "-b", "bool_params", multiple=True, nargs=2, type=click.Tuple([unicode, bool])) +@click.option( + "--str", + "-s", + "str_params", + multiple=True, + nargs=2, + type=click.Tuple([unicode, unicode]), +) +@click.option( + "--int", "-i", "int_params", multiple=True, nargs=2, type=click.Tuple([unicode, int]) +) +@click.option( + "--float", + "-f", + "float_params", + multiple=True, + nargs=2, + type=click.Tuple([unicode, float]), +) +@click.option( + "--bool", + "-b", + "bool_params", + multiple=True, + nargs=2, + type=click.Tuple([unicode, bool]), +) @click.option("--timeout", type=float, default=None, help="Request timeout in seconds") @click.pass_context -def command(ctx, path, command, str_params, int_params, float_params, bool_params, timeout): - """Sends a JSON command to the specified server path.""" - data = {} - params = str_params + int_params + float_params + bool_params - for param in params: - data[param[0]] = param[1] - r = ctx.obj.client.post_command(path, command, additional=data, timeout=timeout) - log_response(r, body=False) +def command( + ctx, path, command, str_params, int_params, float_params, bool_params, timeout +): + """Sends a JSON command to the specified server path.""" + data = {} + params = str_params + int_params + float_params + bool_params + for param in params: + data[param[0]] = param[1] + r = ctx.obj.client.post_command(path, command, additional=data, timeout=timeout) + log_response(r, body=False) @client.command("upload") @click.argument("path") -@click.argument("file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True)) -@click.option("--parameter", "-P", "params", multiple=True, nargs=2, type=click.Tuple([unicode, unicode])) +@click.argument( + "file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True) +) +@click.option( + "--parameter", + "-P", + "params", + multiple=True, + nargs=2, + type=click.Tuple([unicode, unicode]), +) @click.option("--file-name", type=click.STRING) @click.option("--content-type", type=click.STRING) @click.option("--timeout", type=float, default=None, help="Request timeout in seconds") @click.pass_context def upload(ctx, path, file_path, params, file_name, content_type, timeout): - """Uploads the specified file to the specified server path.""" - data = {} - for param in params: - data[param[0]] = param[1] + """Uploads the specified file to the specified server path.""" + data = {} + for param in params: + data[param[0]] = param[1] - r = ctx.obj.client.upload(path, file_path, - additional=data, file_name=file_name, content_type=content_type, timeout=timeout) - log_response(r) + r = ctx.obj.client.upload( + path, + file_path, + additional=data, + file_name=file_name, + content_type=content_type, + timeout=timeout, + ) + log_response(r) @client.command("delete") @@ -207,41 +270,45 @@ def upload(ctx, path, file_path, params, file_name, content_type, timeout): @click.option("--timeout", type=float, default=None, help="Request timeout in seconds") @click.pass_context def delete(ctx, path, timeout): - """Sends a DELETE request to the specified server path.""" - r = ctx.obj.client.delete(path, timeout=timeout) - log_response(r) + """Sends a DELETE request to the specified server path.""" + r = ctx.obj.client.delete(path, timeout=timeout) + log_response(r) @client.command("listen") @click.pass_context def listen(ctx): - def on_connect(ws): - click.echo("--- Connected!") + def on_connect(ws): + click.echo("--- Connected!") - def on_close(ws): - click.echo("--- Connection closed!") + def on_close(ws): + click.echo("--- Connection closed!") - def on_error(ws, error): - click.echo("!!! Error: {}".format(error)) + def on_error(ws, error): + click.echo("!!! Error: {}".format(error)) - def on_sent(ws, data): - click.echo(">>> {}".format(json.dumps(data))) + def on_sent(ws, data): + click.echo(">>> {}".format(json.dumps(data))) - def on_heartbeat(ws): - click.echo("<3") + def on_heartbeat(ws): + click.echo("<3") - def on_message(ws, message_type, message_payload): - click.echo("<<< {}, Payload: {}".format(message_type, json.dumps(message_payload))) + def on_message(ws, message_type, message_payload): + click.echo( + "<<< {}, Payload: {}".format(message_type, json.dumps(message_payload)) + ) - socket = ctx.obj.client.create_socket(on_connect=on_connect, - on_close=on_close, - on_error=on_error, - on_sent=on_sent, - on_heartbeat=on_heartbeat, - on_message=on_message) + socket = ctx.obj.client.create_socket( + on_connect=on_connect, + on_close=on_close, + on_error=on_error, + on_sent=on_sent, + on_heartbeat=on_heartbeat, + on_message=on_message, + ) - click.echo("--- Waiting for client to exit") - try: - socket.wait() - finally: - click.echo("--- Goodbye...") + click.echo("--- Waiting for client to exit") + try: + socket.wait() + finally: + click.echo("--- Goodbye...") diff --git a/src/octoprint/cli/config.py b/src/octoprint/cli/config.py index c6f2a4df8..886cae971 100644 --- a/src/octoprint/cli/config.py +++ b/src/octoprint/cli/config.py @@ -1,11 +1,12 @@ # -*- 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import click + click.disable_unicode_literals_warning = True import logging @@ -16,80 +17,88 @@ import yaml import json import pprint + def _to_settings_path(path): - if not isinstance(path, (list, tuple)): - path = list(filter(lambda x: x, map(lambda x: x.strip(), path.split(".")))) - return path + if not isinstance(path, (list, tuple)): + path = list(filter(lambda x: x, map(lambda x: x.strip(), path.split(".")))) + return path + def _set_helper(settings, path, value, data_type=None): - path = _to_settings_path(path) + path = _to_settings_path(path) - method = settings.set - if data_type is not None: - name = None - if data_type == bool: - name = "setBoolean" - elif data_type == float: - name = "setFloat" - elif data_type == int: - name = "setInt" + method = settings.set + if data_type is not None: + name = None + if data_type == bool: + name = "setBoolean" + elif data_type == float: + name = "setFloat" + elif data_type == int: + name = "setInt" - if name is not None: - method = getattr(settings, name) + if name is not None: + method = getattr(settings, name) - method(path, value) - settings.save() + method(path, value) + settings.save() + + +# ~~ "octoprint config" commands -#~~ "octoprint config" commands @click.group() def config_commands(): - pass + pass + @config_commands.group(name="config") @click.pass_context def config(ctx): - """Basic config manipulation.""" - logging.basicConfig(level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN) - try: - ctx.obj.settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None)) - except FatalStartupError as e: - click.echo(e.message, err=True) - click.echo("There was a fatal error initializing the settings manager.", err=True) - ctx.exit(-1) + """Basic config manipulation.""" + logging.basicConfig( + level=logging.DEBUG + if get_ctx_obj_option(ctx, "verbosity", 0) > 0 + else logging.WARN + ) + try: + ctx.obj.settings = init_settings( + get_ctx_obj_option(ctx, "basedir", None), + get_ctx_obj_option(ctx, "configfile", None), + ) + except FatalStartupError as e: + click.echo(e.message, err=True) + click.echo("There was a fatal error initializing the settings manager.", err=True) + ctx.exit(-1) @config.command(name="set") @standard_options(hidden=True) @click.argument("path", type=click.STRING) @click.argument("value", type=click.STRING) -@click.option("--bool", "as_bool", is_flag=True, - help="Interpret value as bool") -@click.option("--float", "as_float", is_flag=True, - help="Interpret value as float") -@click.option("--int", "as_int", is_flag=True, - help="Interpret value as int") -@click.option("--json", "as_json", is_flag=True, - help="Parse value from json") +@click.option("--bool", "as_bool", is_flag=True, help="Interpret value as bool") +@click.option("--float", "as_float", is_flag=True, help="Interpret value as float") +@click.option("--int", "as_int", is_flag=True, help="Interpret value as int") +@click.option("--json", "as_json", is_flag=True, help="Parse value from json") @click.pass_context def set_command(ctx, path, value, as_bool, as_float, as_int, as_json): - """Sets a config path to the provided value.""" - if as_json: - try: - value = json.loads(value) - except Exception as e: - click.echo(e.message, err=True) - ctx.exit(-1) + """Sets a config path to the provided value.""" + if as_json: + try: + value = json.loads(value) + except Exception as e: + click.echo(e.message, err=True) + ctx.exit(-1) - data_type = None - if as_bool: - data_type = bool - elif as_float: - data_type = float - elif as_int: - data_type = int + data_type = None + if as_bool: + data_type = bool + elif as_float: + data_type = float + elif as_int: + data_type = int - _set_helper(ctx.obj.settings, path, value, data_type=data_type) + _set_helper(ctx.obj.settings, path, value, data_type=data_type) @config.command(name="remove") @@ -97,8 +106,8 @@ def set_command(ctx, path, value, as_bool, as_float, as_int, as_json): @click.argument("path", type=click.STRING) @click.pass_context def remove_command(ctx, path): - """Removes a config path.""" - _set_helper(ctx.obj.settings, path, None) + """Removes a config path.""" + _set_helper(ctx.obj.settings, path, None) @config.command(name="append_value") @@ -108,25 +117,25 @@ def remove_command(ctx, path): @click.option("--json", "as_json", is_flag=True) @click.pass_context def append_value_command(ctx, path, value, as_json=False): - """Appends value to list behind config path.""" - path = _to_settings_path(path) + """Appends value to list behind config path.""" + path = _to_settings_path(path) - if as_json: - try: - value = json.loads(value) - except Exception as e: - click.echo(e.message, err=True) - ctx.exit(-1) + if as_json: + try: + value = json.loads(value) + except Exception as e: + click.echo(e.message, err=True) + ctx.exit(-1) - current = ctx.obj.settings.get(path) - if current is None: - current = [] - if not isinstance(current, list): - click.echo("Cannot append to non-list value at given path", err=True) - ctx.exit(-1) + current = ctx.obj.settings.get(path) + if current is None: + current = [] + if not isinstance(current, list): + click.echo("Cannot append to non-list value at given path", err=True) + ctx.exit(-1) - current.append(value) - _set_helper(ctx.obj.settings, path, current) + current.append(value) + _set_helper(ctx.obj.settings, path, current) @config.command(name="insert_value") @@ -137,25 +146,25 @@ def append_value_command(ctx, path, value, as_json=False): @click.option("--json", "as_json", is_flag=True) @click.pass_context def insert_value_command(ctx, path, index, value, as_json=False): - """Inserts value at index of list behind config key.""" - path = _to_settings_path(path) + """Inserts value at index of list behind config key.""" + path = _to_settings_path(path) - if as_json: - try: - value = json.loads(value) - except Exception as e: - click.echo(e.message, err=True) - ctx.exit(-1) + if as_json: + try: + value = json.loads(value) + except Exception as e: + click.echo(e.message, err=True) + ctx.exit(-1) - current = ctx.obj.settings.get(path) - if current is None: - current = [] - if not isinstance(current, list): - click.echo("Cannot insert into non-list value at given path", err=True) - ctx.exit(-1) + current = ctx.obj.settings.get(path) + if current is None: + current = [] + if not isinstance(current, list): + click.echo("Cannot insert into non-list value at given path", err=True) + ctx.exit(-1) - current.insert(index, value) - _set_helper(ctx.obj.settings, path, current) + current.insert(index, value) + _set_helper(ctx.obj.settings, path, current) @config.command(name="remove_value") @@ -165,78 +174,80 @@ def insert_value_command(ctx, path, index, value, as_json=False): @click.option("--json", "as_json", is_flag=True) @click.pass_context def remove_value_command(ctx, path, value, as_json=False): - """Removes value from list at config path.""" - path = _to_settings_path(path) + """Removes value from list at config path.""" + path = _to_settings_path(path) - if as_json: - try: - value = json.loads(value) - except Exception as e: - click.echo(e.message, err=True) - ctx.exit(-1) + if as_json: + try: + value = json.loads(value) + except Exception as e: + click.echo(e.message, err=True) + ctx.exit(-1) - current = ctx.obj.settings.get(path) - if current is None: - current = [] - if not isinstance(current, list): - click.echo("Cannot remove value from non-list value at given path", err=True) - ctx.exit(-1) + current = ctx.obj.settings.get(path) + if current is None: + current = [] + if not isinstance(current, list): + click.echo("Cannot remove value from non-list value at given path", err=True) + ctx.exit(-1) - if not value in current: - click.echo("Value is not contained in list at given path") - ctx.exit() + if not value in current: + click.echo("Value is not contained in list at given path") + ctx.exit() - current.remove(value) - _set_helper(ctx.obj.settings, path, current) + current.remove(value) + _set_helper(ctx.obj.settings, path, current) @config.command(name="get") @click.argument("path", type=click.STRING) -@click.option("--json", "as_json", is_flag=True, - help="Output value formatted as JSON") -@click.option("--yaml", "as_yaml", is_flag=True, - help="Output value formatted as YAML") -@click.option("--raw", "as_raw", is_flag=True, - help="Output value as raw string representation") +@click.option("--json", "as_json", is_flag=True, help="Output value formatted as JSON") +@click.option("--yaml", "as_yaml", is_flag=True, help="Output value formatted as YAML") +@click.option( + "--raw", "as_raw", is_flag=True, help="Output value as raw string representation" +) @standard_options(hidden=True) @click.pass_context def get_command(ctx, path, as_json=False, as_yaml=False, as_raw=False): - """Retrieves value from config path.""" - path = _to_settings_path(path) - value = ctx.obj.settings.get(path, merged=True) + """Retrieves value from config path.""" + path = _to_settings_path(path) + value = ctx.obj.settings.get(path, merged=True) - if as_json: - output = json.dumps(value) - elif as_yaml: - output = yaml.safe_dump(value, default_flow_style=False, indent=4, allow_unicode=True) - elif as_raw: - output = value - else: - output = pprint.pformat(value) + if as_json: + output = json.dumps(value) + elif as_yaml: + output = yaml.safe_dump( + value, default_flow_style=False, indent=4, allow_unicode=True + ) + elif as_raw: + output = value + else: + output = pprint.pformat(value) - click.echo(output) + click.echo(output) @config.command(name="effective") -@click.option("--json", "as_json", is_flag=True, - help="Output value formatted as JSON") -@click.option("--yaml", "as_yaml", is_flag=True, - help="Output value formatted as YAML") -@click.option("--raw", "as_raw", is_flag=True, - help="Output value as raw string representation") +@click.option("--json", "as_json", is_flag=True, help="Output value formatted as JSON") +@click.option("--yaml", "as_yaml", is_flag=True, help="Output value formatted as YAML") +@click.option( + "--raw", "as_raw", is_flag=True, help="Output value as raw string representation" +) @standard_options(hidden=True) @click.pass_context def effective_command(ctx, as_json=False, as_yaml=False, as_raw=False): - """Retrieves the full effective config.""" - value = ctx.obj.settings.effective + """Retrieves the full effective config.""" + value = ctx.obj.settings.effective - if as_json: - output = json.dumps(value) - elif as_yaml: - output = yaml.safe_dump(value, default_flow_style=False, indent=4, allow_unicode=True) - elif as_raw: - output = value - else: - output = pprint.pformat(value) + if as_json: + output = json.dumps(value) + elif as_yaml: + output = yaml.safe_dump( + value, default_flow_style=False, indent=4, allow_unicode=True + ) + elif as_raw: + output = value + else: + output = pprint.pformat(value) - click.echo(output) + click.echo(output) diff --git a/src/octoprint/cli/dev.py b/src/octoprint/cli/dev.py index 755645359..bed9663bd 100644 --- a/src/octoprint/cli/dev.py +++ b/src/octoprint/cli/dev.py @@ -2,236 +2,268 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import click + click.disable_unicode_literals_warning = True from past.builtins import basestring + class OctoPrintDevelCommands(click.MultiCommand): - """ - Custom `click.MultiCommand `_ - implementation that provides commands relevant for (plugin) development - based on availability of development dependencies. - """ + """ + Custom `click.MultiCommand `_ + implementation that provides commands relevant for (plugin) development + based on availability of development dependencies. + """ - sep = ":" - groups = ("plugin",) + sep = ":" + groups = ("plugin",) - def __init__(self, *args, **kwargs): - click.MultiCommand.__init__(self, *args, **kwargs) + def __init__(self, *args, **kwargs): + click.MultiCommand.__init__(self, *args, **kwargs) - from octoprint.util.commandline import CommandlineCaller - from functools import partial + from octoprint.util.commandline import CommandlineCaller + from functools import partial - def log_util(f): - def log(*lines): - for line in lines: - f(line) - return log + def log_util(f): + def log(*lines): + for line in lines: + f(line) - self.command_caller = CommandlineCaller() - self.command_caller.on_log_call = log_util(lambda x: click.echo(">> {}".format(x))) - self.command_caller.on_log_stdout = log_util(click.echo) - self.command_caller.on_log_stderr = log_util(partial(click.echo, err=True)) + return log - def _get_prefix_methods(self, method_prefix): - for name in [x for x in dir(self) if x.startswith(method_prefix)]: - method = getattr(self, name) - yield method + self.command_caller = CommandlineCaller() + self.command_caller.on_log_call = log_util( + lambda x: click.echo(">> {}".format(x)) + ) + self.command_caller.on_log_stdout = log_util(click.echo) + self.command_caller.on_log_stderr = log_util(partial(click.echo, err=True)) - def _get_commands_from_prefix_methods(self, method_prefix): - for method in self._get_prefix_methods(method_prefix): - result = method() - if result is not None and isinstance(result, click.Command): - yield result + def _get_prefix_methods(self, method_prefix): + for name in [x for x in dir(self) if x.startswith(method_prefix)]: + method = getattr(self, name) + yield method - def _get_commands(self): - result = {} - for group in self.groups: - for command in self._get_commands_from_prefix_methods("{}_".format(group)): - result[group + self.sep + command.name] = command - return result + def _get_commands_from_prefix_methods(self, method_prefix): + for method in self._get_prefix_methods(method_prefix): + result = method() + if result is not None and isinstance(result, click.Command): + yield result - def list_commands(self, ctx): - result = [name for name in self._get_commands()] - result.sort() - return result + def _get_commands(self): + result = {} + for group in self.groups: + for command in self._get_commands_from_prefix_methods("{}_".format(group)): + result[group + self.sep + command.name] = command + return result - def get_command(self, ctx, cmd_name): - commands = self._get_commands() - return commands.get(cmd_name, None) + def list_commands(self, ctx): + result = [name for name in self._get_commands()] + result.sort() + return result - def plugin_new(self): - try: - import cookiecutter.main - except ImportError: - return None + def get_command(self, ctx, cmd_name): + commands = self._get_commands() + return commands.get(cmd_name, None) - try: - # we depend on Cookiecutter >= 1.4 - from cookiecutter.prompt import StrictEnvironment - except ImportError: - return None + def plugin_new(self): + try: + import cookiecutter.main + except ImportError: + return None - import contextlib + try: + # we depend on Cookiecutter >= 1.4 + from cookiecutter.prompt import StrictEnvironment + except ImportError: + return None - @contextlib.contextmanager - def custom_cookiecutter_config(config): - """ - Allows overriding cookiecutter's user config with a custom dict - with fallback to the original data. - """ - from octoprint.util import fallback_dict + import contextlib - original_get_user_config = cookiecutter.main.get_user_config - try: - def f(*args, **kwargs): - original_config = original_get_user_config(*args, **kwargs) - return fallback_dict(config, original_config) - cookiecutter.main.get_user_config = f - yield - finally: - cookiecutter.main.get_user_config = original_get_user_config + @contextlib.contextmanager + def custom_cookiecutter_config(config): + """ + Allows overriding cookiecutter's user config with a custom dict + with fallback to the original data. + """ + from octoprint.util import fallback_dict - @contextlib.contextmanager - def custom_cookiecutter_prompt(options): - """ - Custom cookiecutter prompter for the template config. + original_get_user_config = cookiecutter.main.get_user_config + try: - If a setting is available in the provided options (read from the CLI) - that will be used, otherwise the user will be prompted for a value - via click. - """ - original_prompt_for_config = cookiecutter.main.prompt_for_config + def f(*args, **kwargs): + original_config = original_get_user_config(*args, **kwargs) + return fallback_dict(config, original_config) - def custom_prompt_for_config(context, no_input=False): - cookiecutter_dict = {} + cookiecutter.main.get_user_config = f + yield + finally: + cookiecutter.main.get_user_config = original_get_user_config - env = StrictEnvironment() + @contextlib.contextmanager + def custom_cookiecutter_prompt(options): + """ + Custom cookiecutter prompter for the template config. - for key, raw in context['cookiecutter'].items(): - if key in options: - val = options[key] - else: - if not isinstance(raw, basestring): - raw = str(raw) - val = env.from_string(raw).render(cookiecutter=cookiecutter_dict) + If a setting is available in the provided options (read from the CLI) + that will be used, otherwise the user will be prompted for a value + via click. + """ + original_prompt_for_config = cookiecutter.main.prompt_for_config - if not no_input: - val = click.prompt(key, default=val) + def custom_prompt_for_config(context, no_input=False): + cookiecutter_dict = {} - cookiecutter_dict[key] = val - return cookiecutter_dict + env = StrictEnvironment() - try: - cookiecutter.main.prompt_for_config = custom_prompt_for_config - yield - finally: - cookiecutter.main.prompt_for_config = original_prompt_for_config + for key, raw in context["cookiecutter"].items(): + if key in options: + val = options[key] + else: + if not isinstance(raw, basestring): + raw = str(raw) + val = env.from_string(raw).render(cookiecutter=cookiecutter_dict) - @click.command("new") - @click.option("--name", "-n", help="The name of the plugin") - @click.option("--package", "-p", help="The plugin package") - @click.option("--author", "-a", help="The plugin author's name") - @click.option("--email", "-e", help="The plugin author's mail address") - @click.option("--license", "-l", help="The plugin's license") - @click.option("--description", "-d", help="The plugin's description") - @click.option("--homepage", help="The plugin's homepage URL") - @click.option("--source", "-s", help="The URL to the plugin's source") - @click.option("--installurl", "-i", help="The plugin's install URL") - @click.argument("identifier", required=False) - def command(name, package, author, email, description, license, homepage, source, installurl, identifier): - """Creates a new plugin based on the OctoPrint Plugin cookiecutter template.""" - from octoprint.util import tempdir + if not no_input: + val = click.prompt(key, default=val) - # deleting a git checkout folder might run into access errors due - # to write-protected sub folders, so we use a custom onerror handler - # that tries to fix such permissions - def onerror(func, path, exc_info): - """Originally from http://stackoverflow.com/a/2656405/2028598""" - import stat - import os + cookiecutter_dict[key] = val + return cookiecutter_dict - if not os.access(path, os.W_OK): - os.chmod(path, stat.S_IWUSR) - func(path) - else: - raise + try: + cookiecutter.main.prompt_for_config = custom_prompt_for_config + yield + finally: + cookiecutter.main.prompt_for_config = original_prompt_for_config - with tempdir(onerror=onerror) as path: - custom = {"cookiecutters_dir": path} - with custom_cookiecutter_config(custom): - raw_options = {"plugin_identifier": identifier, - "plugin_package": package, - "plugin_name": name, - "full_name": author, - "email": email, - "plugin_description": description, - "plugin_license": license, - "plugin_homepage": homepage, - "plugin_source": source, - "plugin_installurl": installurl} - options = dict((k, v) for k, v in raw_options.items() if v is not None) + @click.command("new") + @click.option("--name", "-n", help="The name of the plugin") + @click.option("--package", "-p", help="The plugin package") + @click.option("--author", "-a", help="The plugin author's name") + @click.option("--email", "-e", help="The plugin author's mail address") + @click.option("--license", "-l", help="The plugin's license") + @click.option("--description", "-d", help="The plugin's description") + @click.option("--homepage", help="The plugin's homepage URL") + @click.option("--source", "-s", help="The URL to the plugin's source") + @click.option("--installurl", "-i", help="The plugin's install URL") + @click.argument("identifier", required=False) + def command( + name, + package, + author, + email, + description, + license, + homepage, + source, + installurl, + identifier, + ): + """Creates a new plugin based on the OctoPrint Plugin cookiecutter template.""" + from octoprint.util import tempdir - with custom_cookiecutter_prompt(options): - cookiecutter.main.cookiecutter("gh:OctoPrint/cookiecutter-octoprint-plugin") + # deleting a git checkout folder might run into access errors due + # to write-protected sub folders, so we use a custom onerror handler + # that tries to fix such permissions + def onerror(func, path, exc_info): + """Originally from http://stackoverflow.com/a/2656405/2028598""" + import stat + import os - return command + if not os.access(path, os.W_OK): + os.chmod(path, stat.S_IWUSR) + func(path) + else: + raise - def plugin_install(self): - @click.command("install") - @click.option("--path", help="Path of the local plugin development folder to install") - def command(path): - """ - Installs the local plugin in development mode. + with tempdir(onerror=onerror) as path: + custom = {"cookiecutters_dir": path} + with custom_cookiecutter_config(custom): + raw_options = { + "plugin_identifier": identifier, + "plugin_package": package, + "plugin_name": name, + "full_name": author, + "email": email, + "plugin_description": description, + "plugin_license": license, + "plugin_homepage": homepage, + "plugin_source": source, + "plugin_installurl": installurl, + } + options = dict( + (k, v) for k, v in raw_options.items() if v is not None + ) - Note: This can NOT be used to install plugins from remote locations - such as the plugin repository! It is strictly for local development - of plugins, to ensure the plugin is installed (editable) into the - same python environment that OctoPrint is installed under. - """ + with custom_cookiecutter_prompt(options): + cookiecutter.main.cookiecutter( + "gh:OctoPrint/cookiecutter-octoprint-plugin" + ) - import os - import sys + return command - if not path: - path = os.getcwd() + def plugin_install(self): + @click.command("install") + @click.option( + "--path", help="Path of the local plugin development folder to install" + ) + def command(path): + """ + Installs the local plugin in development mode. - # check if this really looks like a plugin - if not os.path.isfile(os.path.join(path, "setup.py")): - click.echo("This doesn't look like an OctoPrint plugin folder") - sys.exit(1) + Note: This can NOT be used to install plugins from remote locations + such as the plugin repository! It is strictly for local development + of plugins, to ensure the plugin is installed (editable) into the + same python environment that OctoPrint is installed under. + """ - self.command_caller.call([sys.executable, "-m", "pip", "install", "-e", "."], cwd=path) + import os + import sys - return command + if not path: + path = os.getcwd() - def plugin_uninstall(self): - @click.command("uninstall") - @click.argument("name") - def command(name): - """Uninstalls the plugin with the given name.""" - import sys + # check if this really looks like a plugin + if not os.path.isfile(os.path.join(path, "setup.py")): + click.echo("This doesn't look like an OctoPrint plugin folder") + sys.exit(1) - lower_name = name.lower() - if not lower_name.startswith("octoprint_") and not lower_name.startswith("octoprint-"): - click.echo("This doesn't look like an OctoPrint plugin name") - sys.exit(1) + self.command_caller.call( + [sys.executable, "-m", "pip", "install", "-e", "."], cwd=path + ) - call = [sys.executable, "-m", "pip", "uninstall", "--yes", name] - self.command_caller.call(call) + return command + + def plugin_uninstall(self): + @click.command("uninstall") + @click.argument("name") + def command(name): + """Uninstalls the plugin with the given name.""" + import sys + + lower_name = name.lower() + if not lower_name.startswith("octoprint_") and not lower_name.startswith( + "octoprint-" + ): + click.echo("This doesn't look like an OctoPrint plugin name") + sys.exit(1) + + call = [sys.executable, "-m", "pip", "uninstall", "--yes", name] + self.command_caller.call(call) + + return command - return command @click.group() def dev_commands(): - pass + pass + @dev_commands.group(name="dev", cls=OctoPrintDevelCommands) def dev(): - """Additional commands for development tasks.""" - pass + """Additional commands for development tasks.""" + pass diff --git a/src/octoprint/cli/plugins.py b/src/octoprint/cli/plugins.py index a1e6b2f3f..545874eef 100644 --- a/src/octoprint/cli/plugins.py +++ b/src/octoprint/cli/plugins.py @@ -1,11 +1,12 @@ # -*- 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import click + click.disable_unicode_literals_warning = True import logging import logging.config @@ -14,124 +15,138 @@ from octoprint.cli import pass_octoprint_ctx, OctoPrintContext, get_ctx_obj_opti from octoprint.util import dict_merge LOGGING_CONFIG = { - "version": 1, - "formatters": { - "brief": { - "format": "%(message)s" - } - }, - "handlers": { - "console": { - "class": "logging.StreamHandler", - "formatter": "brief", - "stream": "ext://sys.stdout" - } - }, - "loggers": { - "octoprint.plugin.core": { - "level": logging.ERROR - } - }, - "root": { - "level": logging.WARNING - } + "version": 1, + "formatters": {"brief": {"format": "%(message)s"}}, + "handlers": { + "console": { + "class": "logging.StreamHandler", + "formatter": "brief", + "stream": "ext://sys.stdout", + } + }, + "loggers": {"octoprint.plugin.core": {"level": logging.ERROR}}, + "root": {"level": logging.WARNING}, } -#~~ "octoprint plugin:command" commands +# ~~ "octoprint plugin:command" commands + class OctoPrintPluginCommands(click.MultiCommand): - """ - Custom `click.MultiCommand `_ - implementation that collects commands from the plugin hook - :ref:`octoprint.cli.commands `. + """ + Custom `click.MultiCommand `_ + implementation that collects commands from the plugin hook + :ref:`octoprint.cli.commands `. - .. attribute:: settings + .. attribute:: settings - The global :class:`~octoprint.settings.Settings` instance. + The global :class:`~octoprint.settings.Settings` instance. - .. attribute:: plugin_manager + .. attribute:: plugin_manager - The :class:`~octoprint.plugin.core.PluginManager` instance. - """ + The :class:`~octoprint.plugin.core.PluginManager` instance. + """ - sep = ":" + sep = ":" - def __init__(self, *args, **kwargs): - click.MultiCommand.__init__(self, *args, **kwargs) + def __init__(self, *args, **kwargs): + click.MultiCommand.__init__(self, *args, **kwargs) - self.settings = None - self.plugin_manager = None - self.hooks = {} + self.settings = None + self.plugin_manager = None + self.hooks = {} - self._logger = logging.getLogger(__name__) - self._initialized = False + self._logger = logging.getLogger(__name__) + self._initialized = False - def _initialize(self, ctx): - if self._initialized: - return + def _initialize(self, ctx): + if self._initialized: + return - click.echo("Initializing settings & plugin subsystem...") - if ctx.obj is None: - ctx.obj = OctoPrintContext() + click.echo("Initializing settings & plugin subsystem...") + if ctx.obj is None: + ctx.obj = OctoPrintContext() - logging_config = dict_merge(LOGGING_CONFIG, {"root": {"level": logging.DEBUG if ctx.obj.verbosity > 0 else logging.WARNING}}) - logging.config.dictConfig(logging_config) + logging_config = dict_merge( + LOGGING_CONFIG, + { + "root": { + "level": logging.DEBUG if ctx.obj.verbosity > 0 else logging.WARNING + } + }, + ) + logging.config.dictConfig(logging_config) - # initialize settings and plugin manager based on provided - # context (basedir and configfile) - from octoprint import init_settings, init_pluginsystem, FatalStartupError - try: - self.settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None)) - self.plugin_manager = init_pluginsystem(self.settings, - safe_mode=get_ctx_obj_option(ctx, "safe_mode", False)) - except FatalStartupError as e: - click.echo(e.message, err=True) - click.echo("There was a fatal error initializing the settings or the plugin system.", err=True) - ctx.exit(-1) + # initialize settings and plugin manager based on provided + # context (basedir and configfile) + from octoprint import init_settings, init_pluginsystem, FatalStartupError - # fetch registered hooks - self.hooks = self.plugin_manager.get_hooks("octoprint.cli.commands") + try: + self.settings = init_settings( + get_ctx_obj_option(ctx, "basedir", None), + get_ctx_obj_option(ctx, "configfile", None), + ) + self.plugin_manager = init_pluginsystem( + self.settings, safe_mode=get_ctx_obj_option(ctx, "safe_mode", False) + ) + except FatalStartupError as e: + click.echo(e.message, err=True) + click.echo( + "There was a fatal error initializing the settings or the plugin system.", + err=True, + ) + ctx.exit(-1) - self._initialized = True + # fetch registered hooks + self.hooks = self.plugin_manager.get_hooks("octoprint.cli.commands") - def list_commands(self, ctx): - self._initialize(ctx) - result = [name for name in self._get_commands()] - result.sort() - return result + self._initialized = True - def get_command(self, ctx, cmd_name): - self._initialize(ctx) - commands = self._get_commands() - return commands.get(cmd_name, None) + def list_commands(self, ctx): + self._initialize(ctx) + result = [name for name in self._get_commands()] + result.sort() + return result - def _get_commands(self): - """Fetch all commands from plugins providing any.""" + def get_command(self, ctx, cmd_name): + self._initialize(ctx) + commands = self._get_commands() + return commands.get(cmd_name, None) - import collections - result = collections.OrderedDict() + def _get_commands(self): + """Fetch all commands from plugins providing any.""" - for name, hook in self.hooks.items(): - try: - commands = hook(self, pass_octoprint_ctx) - for command in commands: - if not isinstance(command, click.Command): - self._logger.warning("Plugin {} provided invalid CLI command, ignoring it: {!r}".format(name, command)) - continue - result[name + self.sep + command.name] = command - except Exception: - self._logger.exception("Error while retrieving cli commands for plugin {}".format(name), - extra={"plugin": name}) + import collections + + result = collections.OrderedDict() + + for name, hook in self.hooks.items(): + try: + commands = hook(self, pass_octoprint_ctx) + for command in commands: + if not isinstance(command, click.Command): + self._logger.warning( + "Plugin {} provided invalid CLI command, ignoring it: {!r}".format( + name, command + ) + ) + continue + result[name + self.sep + command.name] = command + except Exception: + self._logger.exception( + "Error while retrieving cli commands for plugin {}".format(name), + extra={"plugin": name}, + ) + + return result - return result @click.group() @pass_octoprint_ctx def plugin_commands(obj): - pass + pass + @plugin_commands.group(name="plugins", cls=OctoPrintPluginCommands) def plugins(): - """Additional commands provided by plugins.""" - pass - + """Additional commands provided by plugins.""" + pass diff --git a/src/octoprint/cli/server.py b/src/octoprint/cli/server.py index 6517b70ce..36b15b711 100644 --- a/src/octoprint/cli/server.py +++ b/src/octoprint/cli/server.py @@ -1,180 +1,276 @@ # -*- 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import click + click.disable_unicode_literals_warning = True import logging import sys -from octoprint.cli import bulk_options, standard_options, set_ctx_obj_option, get_ctx_obj_option +from octoprint.cli import ( + bulk_options, + standard_options, + set_ctx_obj_option, + get_ctx_obj_option, +) -def run_server(basedir, configfile, host, port, v6_only, debug, allow_root, logging_config, verbosity, safe_mode, - ignore_blacklist, octoprint_daemon=None): - """Initializes the environment and starts up the server.""" - from octoprint import init_platform, __display_version__, FatalStartupError +def run_server( + basedir, + configfile, + host, + port, + v6_only, + debug, + allow_root, + logging_config, + verbosity, + safe_mode, + ignore_blacklist, + octoprint_daemon=None, +): + """Initializes the environment and starts up the server.""" - def log_startup(recorder=None, safe_mode=None, **kwargs): - from octoprint.logging import get_divider_line - from octoprint.logging.handlers import PluginTimingsLogHandler + from octoprint import init_platform, __display_version__, FatalStartupError - logger = logging.getLogger("octoprint.startup") - PluginTimingsLogHandler.arm_rollover() + def log_startup(recorder=None, safe_mode=None, **kwargs): + from octoprint.logging import get_divider_line + from octoprint.logging.handlers import PluginTimingsLogHandler - logger.info(get_divider_line("*")) - logger.info("Starting OctoPrint {}".format(__display_version__)) - if safe_mode: - logger.info("Starting in SAFE MODE. Third party plugins will be disabled!") - if safe_mode == "flag": - reason = "command line flag" - elif safe_mode == "settings": - reason = "setting in config.yaml" - elif safe_mode == "incomplete_startup": - reason = "problem during last startup" - else: - reason = "unknown" - logger.info("Reason for safe mode: {}".format(reason)) + logger = logging.getLogger("octoprint.startup") + PluginTimingsLogHandler.arm_rollover() - if recorder and len(recorder): - logger.info(get_divider_line("-", "Logged during platform initialization:")) + logger.info(get_divider_line("*")) + logger.info("Starting OctoPrint {}".format(__display_version__)) + if safe_mode: + logger.info("Starting in SAFE MODE. Third party plugins will be disabled!") + if safe_mode == "flag": + reason = "command line flag" + elif safe_mode == "settings": + reason = "setting in config.yaml" + elif safe_mode == "incomplete_startup": + reason = "problem during last startup" + else: + reason = "unknown" + logger.info("Reason for safe mode: {}".format(reason)) - from octoprint.logging.handlers import CombinedLogHandler - handler = CombinedLogHandler(*logging.getLogger().handlers) - recorder.setTarget(handler) - recorder.flush() + if recorder and len(recorder): + logger.info(get_divider_line("-", "Logged during platform initialization:")) - logger.info(get_divider_line("-")) + from octoprint.logging.handlers import CombinedLogHandler - from octoprint import urllib3_ssl - if not urllib3_ssl: - logging.getLogger("octoprint.server")\ - .warning("requests/urllib3 will run in an insecure SSL environment. " - "You might see corresponding warnings logged later " - "(\"InsecurePlatformWarning\"). It is recommended to either " - "update to a Python version >= 2.7.9 or alternatively " - "install PyOpenSSL plus its dependencies. For details see " - "https://urllib3.readthedocs.org/en/latest/security.html#openssl-pyopenssl") - logger.info(get_divider_line("*")) + handler = CombinedLogHandler(*logging.getLogger().handlers) + recorder.setTarget(handler) + recorder.flush() - def log_register_rollover(safe_mode=None, plugin_manager=None, environment_detector=None, **kwargs): - from octoprint.logging import get_handler, log_to_handler, get_divider_line - from octoprint.logging.handlers import OctoPrintLogHandler + logger.info(get_divider_line("-")) - def rollover_callback(): - handler = get_handler("file") - if handler is None: - return + from octoprint import urllib3_ssl - logger = logging.getLogger("octoprint.server") + if not urllib3_ssl: + logging.getLogger("octoprint.server").warning( + "requests/urllib3 will run in an insecure SSL environment. " + "You might see corresponding warnings logged later " + '("InsecurePlatformWarning"). It is recommended to either ' + "update to a Python version >= 2.7.9 or alternatively " + "install PyOpenSSL plus its dependencies. For details see " + "https://urllib3.readthedocs.org/en/latest/security.html#openssl-pyopenssl" + ) + logger.info(get_divider_line("*")) - def _log(message, level=logging.INFO): - log_to_handler(logger, handler, level, message) + def log_register_rollover( + safe_mode=None, plugin_manager=None, environment_detector=None, **kwargs + ): + from octoprint.logging import get_handler, log_to_handler, get_divider_line + from octoprint.logging.handlers import OctoPrintLogHandler - _log(get_divider_line("-", "Log roll over detected")) - _log("OctoPrint {}".format(__display_version__)) - if safe_mode: - _log("SAFE MODE is active. Third party plugins are disabled!") - plugin_manager.log_all_plugins(only_to_handler=handler) - environment_detector.log_detected_environment(only_to_handler=handler) - _log(get_divider_line("-")) + def rollover_callback(): + handler = get_handler("file") + if handler is None: + return - OctoPrintLogHandler.registerRolloverCallback(rollover_callback) + logger = logging.getLogger("octoprint.server") - try: - components = init_platform(basedir, configfile, - logging_file=logging_config, - debug=debug, - verbosity=verbosity, - uncaught_logger=__name__, - safe_mode=safe_mode, - ignore_blacklist=ignore_blacklist, - after_safe_mode=log_startup, - after_environment_detector=log_register_rollover) - settings, _, safe_mode, event_manager, connectivity_checker, plugin_manager, environment_detector = components + def _log(message, level=logging.INFO): + log_to_handler(logger, handler, level, message) - except FatalStartupError as e: - logger = logging.getLogger("octoprint.startup").fatal - echo = lambda x: click.echo(x, err=True) + _log(get_divider_line("-", "Log roll over detected")) + _log("OctoPrint {}".format(__display_version__)) + if safe_mode: + _log("SAFE MODE is active. Third party plugins are disabled!") + plugin_manager.log_all_plugins(only_to_handler=handler) + environment_detector.log_detected_environment(only_to_handler=handler) + _log(get_divider_line("-")) - for method in logger, echo: - method(str(e)) - method("There was a fatal error starting up OctoPrint.") + OctoPrintLogHandler.registerRolloverCallback(rollover_callback) - else: - from octoprint.server import Server - octoprint_server = Server(settings=settings, - plugin_manager=plugin_manager, - event_manager=event_manager, - connectivity_checker=connectivity_checker, - environment_detector=environment_detector, - host=host, - port=port, - v6_only=v6_only, - debug=debug, - safe_mode=safe_mode, - allow_root=allow_root, - octoprint_daemon=octoprint_daemon) - octoprint_server.run() + try: + components = init_platform( + basedir, + configfile, + logging_file=logging_config, + debug=debug, + verbosity=verbosity, + uncaught_logger=__name__, + safe_mode=safe_mode, + ignore_blacklist=ignore_blacklist, + after_safe_mode=log_startup, + after_environment_detector=log_register_rollover, + ) + ( + settings, + _, + safe_mode, + event_manager, + connectivity_checker, + plugin_manager, + environment_detector, + ) = components -#~~ server options + except FatalStartupError as e: + logger = logging.getLogger("octoprint.startup").fatal + echo = lambda x: click.echo(x, err=True) -server_options = bulk_options([ - click.option("--host", type=click.STRING, callback=set_ctx_obj_option, - help="Specify the host address on which to bind the server."), - click.option("--port", type=click.INT, callback=set_ctx_obj_option, - help="Specify the port on which to bind the server."), - click.option("-4", "--ipv4", "v4", is_flag=True, callback=set_ctx_obj_option, - help="Bind to IPv4 addresses only. Implies '--host 0.0.0.0'. Silently ignored if -6 is present."), - click.option("-6", "--ipv6", "v6", is_flag=True, callback=set_ctx_obj_option, - help="Bind to IPv6 addresses only. Disables dual stack when binding to any v6 addresses. Silently ignored if -4 is present."), - click.option("--logging", type=click.Path(), callback=set_ctx_obj_option, - help="Specify the config file to use for configuring logging."), - click.option("--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option, - help="Allow OctoPrint to run as user root."), - click.option("--debug", is_flag=True, callback=set_ctx_obj_option, - help="Enable debug mode."), - click.option("--ignore-blacklist", "ignore_blacklist", is_flag=True, callback=set_ctx_obj_option, - help="Disable processing of the plugin blacklist.") -]) + for method in logger, echo: + method(str(e)) + method("There was a fatal error starting up OctoPrint.") + + else: + from octoprint.server import Server + + octoprint_server = Server( + settings=settings, + plugin_manager=plugin_manager, + event_manager=event_manager, + connectivity_checker=connectivity_checker, + environment_detector=environment_detector, + host=host, + port=port, + v6_only=v6_only, + debug=debug, + safe_mode=safe_mode, + allow_root=allow_root, + octoprint_daemon=octoprint_daemon, + ) + octoprint_server.run() + + +# ~~ server options + +server_options = bulk_options( + [ + click.option( + "--host", + type=click.STRING, + callback=set_ctx_obj_option, + help="Specify the host address on which to bind the server.", + ), + click.option( + "--port", + type=click.INT, + callback=set_ctx_obj_option, + help="Specify the port on which to bind the server.", + ), + click.option( + "-4", + "--ipv4", + "v4", + is_flag=True, + callback=set_ctx_obj_option, + help="Bind to IPv4 addresses only. Implies '--host 0.0.0.0'. Silently ignored if -6 is present.", + ), + click.option( + "-6", + "--ipv6", + "v6", + is_flag=True, + callback=set_ctx_obj_option, + help="Bind to IPv6 addresses only. Disables dual stack when binding to any v6 addresses. Silently ignored if -4 is present.", + ), + click.option( + "--logging", + type=click.Path(), + callback=set_ctx_obj_option, + help="Specify the config file to use for configuring logging.", + ), + click.option( + "--iknowwhatimdoing", + "allow_root", + is_flag=True, + callback=set_ctx_obj_option, + help="Allow OctoPrint to run as user root.", + ), + click.option( + "--debug", + is_flag=True, + callback=set_ctx_obj_option, + help="Enable debug mode.", + ), + click.option( + "--ignore-blacklist", + "ignore_blacklist", + is_flag=True, + callback=set_ctx_obj_option, + help="Disable processing of the plugin blacklist.", + ), + ] +) """Decorator to add the options shared among the server commands: ``--host``, ``--port``, ``-4``, ``-6`` ``--logging``, ``--iknowwhatimdoing`` and ``--debug``.""" -daemon_options = bulk_options([ - click.option("--pid", type=click.Path(), default="/tmp/octoprint.pid", callback=set_ctx_obj_option, - help="Pidfile to use for daemonizing.") -]) +daemon_options = bulk_options( + [ + click.option( + "--pid", + type=click.Path(), + default="/tmp/octoprint.pid", + callback=set_ctx_obj_option, + help="Pidfile to use for daemonizing.", + ) + ] +) """Decorator to add the options for the daemon subcommand: ``--pid``.""" -#~~ "octoprint serve" and "octoprint daemon" commands +# ~~ "octoprint serve" and "octoprint daemon" commands + @click.group() def server_commands(): - pass + pass @server_commands.command(name="safemode") @standard_options() @click.pass_context def enable_safemode(ctx, **kwargs): - """Sets the safe mode flag for the next start.""" - from octoprint import init_settings, FatalStartupError + """Sets the safe mode flag for the next start.""" + from octoprint import init_settings, FatalStartupError - logging.basicConfig(level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN) - try: - settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None)) - except FatalStartupError as e: - click.echo(e.message, err=True) - click.echo("There was a fatal error initializing the settings manager.", err=True) - ctx.exit(-1) - else: - settings.setBoolean(["server", "startOnceInSafeMode"], True) - settings.save() + logging.basicConfig( + level=logging.DEBUG + if get_ctx_obj_option(ctx, "verbosity", 0) > 0 + else logging.WARN + ) + try: + settings = init_settings( + get_ctx_obj_option(ctx, "basedir", None), + get_ctx_obj_option(ctx, "configfile", None), + ) + except FatalStartupError as e: + click.echo(e.message, err=True) + click.echo("There was a fatal error initializing the settings manager.", err=True) + ctx.exit(-1) + else: + settings.setBoolean(["server", "startOnceInSafeMode"], True) + settings.save() - click.echo("Safe mode flag set, OctoPrint will start in safe mode on next restart.") + click.echo( + "Safe mode flag set, OctoPrint will start in safe mode on next restart." + ) @server_commands.command(name="serve") @@ -182,109 +278,156 @@ def enable_safemode(ctx, **kwargs): @server_options @click.pass_context def serve_command(ctx, **kwargs): - """Starts the OctoPrint server.""" + """Starts the OctoPrint server.""" - def get_value(key): - return get_ctx_obj_option(ctx, key, kwargs.get(key)) + def get_value(key): + return get_ctx_obj_option(ctx, key, kwargs.get(key)) - host = get_value("host") - port = get_value("port") - v4 = get_value("v4") - v6 = get_value("v6") - logging = get_value("logging") - allow_root = get_value("allow_root") - debug = get_value("debug") + host = get_value("host") + port = get_value("port") + v4 = get_value("v4") + v6 = get_value("v6") + logging = get_value("logging") + allow_root = get_value("allow_root") + debug = get_value("debug") - basedir = get_value("basedir") - configfile = get_value("configfile") - verbosity = get_value("verbosity") - safe_mode = "flag" if get_value("safe_mode") else None - ignore_blacklist = get_value("ignore_blacklist") + basedir = get_value("basedir") + configfile = get_value("configfile") + verbosity = get_value("verbosity") + safe_mode = "flag" if get_value("safe_mode") else None + ignore_blacklist = get_value("ignore_blacklist") - if v4 and not host: - host = "0.0.0.0" + if v4 and not host: + host = "0.0.0.0" - run_server(basedir, configfile, host, port, v6, debug, - allow_root, logging, verbosity, safe_mode, - ignore_blacklist) + run_server( + basedir, + configfile, + host, + port, + v6, + debug, + allow_root, + logging, + verbosity, + safe_mode, + ignore_blacklist, + ) if sys.platform != "win32" and sys.platform != "darwin": - # we do not support daemon mode under windows or macosx + # we do not support daemon mode under windows or macosx - @server_commands.command(name="daemon") - @standard_options() - @server_options - @daemon_options - @click.argument("command", type=click.Choice(["start", "stop", "restart", "status"]), - metavar="start|stop|restart|status") - @click.pass_context - def daemon_command(ctx, command, **kwargs): - """ - Starts, stops or restarts in daemon mode. + @server_commands.command(name="daemon") + @standard_options() + @server_options + @daemon_options + @click.argument( + "command", + type=click.Choice(["start", "stop", "restart", "status"]), + metavar="start|stop|restart|status", + ) + @click.pass_context + def daemon_command(ctx, command, **kwargs): + """ + Starts, stops or restarts in daemon mode. - Please note that daemon mode is not supported under Windows and MacOSX right now. - """ + Please note that daemon mode is not supported under Windows and MacOSX right now. + """ - def get_value(key): - return get_ctx_obj_option(ctx, key, kwargs.get(key)) + def get_value(key): + return get_ctx_obj_option(ctx, key, kwargs.get(key)) - host = get_value("host") - port = get_value("port") - v4 = get_value("v4") - v6 = get_value("v6") - logging = get_value("logging") - allow_root = get_value("allow_root") - debug = get_value("debug") - pid = get_value("pid") + host = get_value("host") + port = get_value("port") + v4 = get_value("v4") + v6 = get_value("v6") + logging = get_value("logging") + allow_root = get_value("allow_root") + debug = get_value("debug") + pid = get_value("pid") - basedir = get_value("basedir") - configfile = get_value("configfile") - verbosity = get_value("verbosity") - safe_mode = "flag" if get_value("safe_mode") else None - ignore_blacklist = get_value("ignore_blacklist") + basedir = get_value("basedir") + configfile = get_value("configfile") + verbosity = get_value("verbosity") + safe_mode = "flag" if get_value("safe_mode") else None + ignore_blacklist = get_value("ignore_blacklist") - if v4 and not host: - host = "0.0.0.0" + if v4 and not host: + host = "0.0.0.0" - if pid is None: - click.echo("No path to a pidfile set", - file=sys.stderr) - sys.exit(1) + if pid is None: + click.echo("No path to a pidfile set", file=sys.stderr) + sys.exit(1) - from octoprint.daemon import Daemon - class OctoPrintDaemon(Daemon): - def __init__(self, pidfile, basedir, configfile, host, port, v6_only, debug, allow_root, logging_config, - verbosity, safe_mode, ignore_blacklist): - Daemon.__init__(self, pidfile) + from octoprint.daemon import Daemon - self._basedir = basedir - self._configfile = configfile - self._host = host - self._port = port - self._v6_only = v6_only - self._debug = debug - self._allow_root = allow_root - self._logging_config = logging_config - self._verbosity = verbosity - self._safe_mode = safe_mode - self._ignore_blacklist = ignore_blacklist + class OctoPrintDaemon(Daemon): + def __init__( + self, + pidfile, + basedir, + configfile, + host, + port, + v6_only, + debug, + allow_root, + logging_config, + verbosity, + safe_mode, + ignore_blacklist, + ): + Daemon.__init__(self, pidfile) - def run(self): - run_server(self._basedir, self._configfile, self._host, self._port, self._v6_only, self._debug, - self._allow_root, self._logging_config, self._verbosity, self._safe_mode, - self._ignore_blacklist, octoprint_daemon=self) + self._basedir = basedir + self._configfile = configfile + self._host = host + self._port = port + self._v6_only = v6_only + self._debug = debug + self._allow_root = allow_root + self._logging_config = logging_config + self._verbosity = verbosity + self._safe_mode = safe_mode + self._ignore_blacklist = ignore_blacklist - octoprint_daemon = OctoPrintDaemon(pid, basedir, configfile, host, port, v6, debug, allow_root, logging, - verbosity, safe_mode, ignore_blacklist) - - if command == "start": - octoprint_daemon.start() - elif command == "stop": - octoprint_daemon.stop() - elif command == "restart": - octoprint_daemon.restart() - elif command == "status": - octoprint_daemon.status() + def run(self): + run_server( + self._basedir, + self._configfile, + self._host, + self._port, + self._v6_only, + self._debug, + self._allow_root, + self._logging_config, + self._verbosity, + self._safe_mode, + self._ignore_blacklist, + octoprint_daemon=self, + ) + octoprint_daemon = OctoPrintDaemon( + pid, + basedir, + configfile, + host, + port, + v6, + debug, + allow_root, + logging, + verbosity, + safe_mode, + ignore_blacklist, + ) + if command == "start": + octoprint_daemon.start() + elif command == "stop": + octoprint_daemon.stop() + elif command == "restart": + octoprint_daemon.restart() + elif command == "status": + octoprint_daemon.status() diff --git a/src/octoprint/cli/user.py b/src/octoprint/cli/user.py index 488612a43..44083a987 100644 --- a/src/octoprint/cli/user.py +++ b/src/octoprint/cli/user.py @@ -1,7 +1,7 @@ # 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -16,109 +16,136 @@ from octoprint.util import get_class, sv click.disable_unicode_literals_warning = True -#~~ "octoprint user" commands +# ~~ "octoprint user" commands @click.group() def user_commands(): - pass + pass @user_commands.group(name="user") @click.pass_context def user(ctx): - """ - User management. + """ + User management. - Note that this currently only supports managing user accounts stored in the configured user manager, not any - user managers added through plugins and the "octoprint.users.factory" hook. - """ - try: - logging.basicConfig(level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN) - settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None)) + Note that this currently only supports managing user accounts stored in the configured user manager, not any + user managers added through plugins and the "octoprint.users.factory" hook. + """ + try: + logging.basicConfig( + level=logging.DEBUG + if get_ctx_obj_option(ctx, "verbosity", 0) > 0 + else logging.WARN + ) + settings = init_settings( + get_ctx_obj_option(ctx, "basedir", None), + get_ctx_obj_option(ctx, "configfile", None), + ) - group_manager_name = settings.get(["accessControl", "groupManager"]) - try: - clazz = get_class(group_manager_name) - group_manager = clazz() - except AttributeError: - click.echo("Could not instantiate group manager {}, " - "falling back to FilebasedGroupManager!".format(group_manager_name), err=True) - group_manager = FilebasedGroupManager() + group_manager_name = settings.get(["accessControl", "groupManager"]) + try: + clazz = get_class(group_manager_name) + group_manager = clazz() + except AttributeError: + click.echo( + "Could not instantiate group manager {}, " + "falling back to FilebasedGroupManager!".format(group_manager_name), + err=True, + ) + group_manager = FilebasedGroupManager() - ctx.obj.group_manager = group_manager + ctx.obj.group_manager = group_manager - name = settings.get(["accessControl", "userManager"]) - try: - clazz = get_class(name) - user_manager = clazz(group_manager=group_manager, settings=settings) - except Exception: - click.echo("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(name), err=True) - user_manager = FilebasedUserManager(group_manager, settings=settings) - finally: - user_manager.enabled = settings.getBoolean(["accessControl", "enabled"]) + name = settings.get(["accessControl", "userManager"]) + try: + clazz = get_class(name) + user_manager = clazz(group_manager=group_manager, settings=settings) + except Exception: + click.echo( + "Could not instantiate user manager {}, falling back to FilebasedUserManager!".format( + name + ), + err=True, + ) + user_manager = FilebasedUserManager(group_manager, settings=settings) + finally: + user_manager.enabled = settings.getBoolean(["accessControl", "enabled"]) - ctx.obj.user_manager = user_manager + ctx.obj.user_manager = user_manager - except Exception: - click.echo("Could not instantiate user manager", err=True) - return + except Exception: + click.echo("Could not instantiate user manager", err=True) + return @user.command(name="list") @click.pass_context def list_users_command(ctx): - """Lists user information""" - users = ctx.obj.user_manager.get_all_users() - _print_list(users) + """Lists user information""" + users = ctx.obj.user_manager.get_all_users() + _print_list(users) @user.command(name="add") @click.argument("username", type=click.STRING, required=True) @click.password_option("--password", "password", help="Password for the user") -@click.option("-g", "--group", "groups", multiple=True, - help="Groups to set on the user") -@click.option("-p", "--permission", "permissions", multiple=True, - help="Individual permissions to set on the user") -@click.option("--admin", "is_admin", type=click.BOOL, is_flag=True, default=False, - help="Adds user to admin group") +@click.option("-g", "--group", "groups", multiple=True, help="Groups to set on the user") +@click.option( + "-p", + "--permission", + "permissions", + multiple=True, + help="Individual permissions to set on the user", +) +@click.option( + "--admin", + "is_admin", + type=click.BOOL, + is_flag=True, + default=False, + help="Adds user to admin group", +) @click.pass_context def add_user_command(ctx, username, password, groups, permissions, is_admin): - """Add a new user.""" - if not groups: - groups = [] + """Add a new user.""" + if not groups: + groups = [] - if is_admin: - groups.append(ctx.obj.group_manager.admin_group) + if is_admin: + groups.append(ctx.obj.group_manager.admin_group) - try: - ctx.obj.user_manager.add_user(username, - password, - groups=groups, - permissions=permissions, - active=True) + try: + ctx.obj.user_manager.add_user( + username, password, groups=groups, permissions=permissions, active=True + ) - user = ctx.obj.user_manager.find_user(username) - if user: - click.echo("User created:") - click.echo("\t{}".format(_user_to_line(user.as_dict()))) - except UserAlreadyExists: - click.echo("A user with the name {} does already exist!".format(username), err=True) + user = ctx.obj.user_manager.find_user(username) + if user: + click.echo("User created:") + click.echo("\t{}".format(_user_to_line(user.as_dict()))) + except UserAlreadyExists: + click.echo( + "A user with the name {} does already exist!".format(username), err=True + ) @user.command(name="remove") @click.argument("username", type=click.STRING) @click.pass_context def remove_user_command(ctx, username): - """Remove an existing user.""" - confirm = click.prompt("This is will irreversibly destroy the user account! Enter 'yes' to confirm", - type=click.STRING) + """Remove an existing user.""" + confirm = click.prompt( + "This is will irreversibly destroy the user account! Enter 'yes' to confirm", + type=click.STRING, + ) - if confirm.lower() == "yes": - ctx.obj.user_manager.remove_user(username) - click.echo("User {} removed.".format(username)) - else: - click.echo("User {} not removed.".format(username)) + if confirm.lower() == "yes": + ctx.obj.user_manager.remove_user(username) + click.echo("User {} removed.".format(username)) + else: + click.echo("User {} not removed.".format(username)) @user.command(name="password") @@ -126,59 +153,65 @@ def remove_user_command(ctx, username): @click.password_option("--password", "password", help="New password for user") @click.pass_context def change_password_command(ctx, username, password): - """Change an existing user's password.""" - try: - ctx.obj.user_manager.change_user_password(username, password) - click.echo("Password changed for user {}.".format(username)) - except UnknownUser: - click.echo("User {} does not exist!".format(username), err=True) + """Change an existing user's password.""" + try: + ctx.obj.user_manager.change_user_password(username, password) + click.echo("Password changed for user {}.".format(username)) + except UnknownUser: + click.echo("User {} does not exist!".format(username), err=True) @user.command(name="activate") @click.argument("username", type=click.STRING) @click.pass_context def activate_command(ctx, username): - """Activate a user account.""" - try: - ctx.obj.user_manager.change_user_activation(username, True) - click.echo("User {} activated.".format(username)) + """Activate a user account.""" + try: + ctx.obj.user_manager.change_user_activation(username, True) + click.echo("User {} activated.".format(username)) - user = ctx.obj.user_manager.find_user(username) - if user: - click.echo("User created:") - click.echo("\t{}".format(_user_to_line(user.asDict()))) - except UnknownUser: - click.echo("User {} does not exist!".format(username), err=True) + user = ctx.obj.user_manager.find_user(username) + if user: + click.echo("User created:") + click.echo("\t{}".format(_user_to_line(user.asDict()))) + except UnknownUser: + click.echo("User {} does not exist!".format(username), err=True) @user.command(name="deactivate") @click.argument("username", type=click.STRING) @click.pass_context def deactivate_command(ctx, username): - """Activate a user account.""" - try: - ctx.obj.user_manager.change_user_activation(username, False) - click.echo("User {} activated.".format(username)) + """Activate a user account.""" + try: + ctx.obj.user_manager.change_user_activation(username, False) + click.echo("User {} activated.".format(username)) - user = ctx.obj.user_manager.find_user(username) - if user: - click.echo("User created:") - click.echo("\t{}".format(_user_to_line(user.asDict()))) - except UnknownUser: - click.echo("User {} does not exist!".format(username), err=True) + user = ctx.obj.user_manager.find_user(username) + if user: + click.echo("User created:") + click.echo("\t{}".format(_user_to_line(user.asDict()))) + except UnknownUser: + click.echo("User {} does not exist!".format(username), err=True) def _print_list(users): - click.echo("{} users registered in the system:".format(len(users))) - for user in sorted(map(lambda x: x.as_dict(), users), key=lambda x: sv(x.get("name"))): - click.echo("\t{}".format(_user_to_line(user))) + click.echo("{} users registered in the system:".format(len(users))) + for user in sorted( + map(lambda x: x.as_dict(), users), key=lambda x: sv(x.get("name")) + ): + click.echo("\t{}".format(_user_to_line(user))) def _user_to_line(user): - return "{name}" \ - "\n\t\tactive: {active}" \ - "\n\t\tgroups: {groups}" \ - "\n\t\tpermissions: {permissions}".format(name=user.get("name"), - active=user.get("active", "False"), - groups=", ".join(user.get("groups", [])), - permissions=", ".join(user.get("permissions", []))) + return ( + "{name}" + "\n\t\tactive: {active}" + "\n\t\tgroups: {groups}" + "\n\t\tpermissions: {permissions}".format( + name=user.get("name"), + active=user.get("active", "False"), + groups=", ".join(user.get("groups", [])), + permissions=", ".join(user.get("permissions", [])), + ) + ) diff --git a/src/octoprint/daemon.py b/src/octoprint/daemon.py index dab6751bd..b91361308 100644 --- a/src/octoprint/daemon.py +++ b/src/octoprint/daemon.py @@ -9,168 +9,177 @@ Originally from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon import io, sys, os, time, signal + class Daemon: - """ - A generic daemon class. + """ + A generic daemon class. - Usage: subclass the daemon class and override the run() method. + Usage: subclass the daemon class and override the run() method. - If you want to log the output to someplace different that stdout and stderr, - also override the echo() and error() methods. - """ + If you want to log the output to someplace different that stdout and stderr, + also override the echo() and error() methods. + """ - def __init__(self, pidfile): - self.pidfile = pidfile + def __init__(self, pidfile): + self.pidfile = pidfile - def _daemonize(self): - """Daemonize class. UNIX double fork mechanism.""" + def _daemonize(self): + """Daemonize class. UNIX double fork mechanism.""" - self._double_fork() - self._redirect_io() + self._double_fork() + self._redirect_io() - # write pidfile - pid = str(os.getpid()) - self.set_pid(pid) + # write pidfile + pid = str(os.getpid()) + self.set_pid(pid) - def _double_fork(self): - try: - pid = os.fork() - if pid > 0: - # exit first parent - sys.exit(0) - except OSError as err: - self.error("First fork failed: {}".format(str(err))) - sys.exit(1) + def _double_fork(self): + try: + pid = os.fork() + if pid > 0: + # exit first parent + sys.exit(0) + except OSError as err: + self.error("First fork failed: {}".format(str(err))) + sys.exit(1) - # decouple from parent environment - os.chdir('/') - os.setsid() - os.umask(0o002) + # decouple from parent environment + os.chdir("/") + os.setsid() + os.umask(0o002) - # do second fork - try: - pid = os.fork() - if pid > 0: - # exit from second parent - sys.exit(0) - except OSError as err: - self.error("Second fork failed: {}".format(str(err))) - sys.exit(1) + # do second fork + try: + pid = os.fork() + if pid > 0: + # exit from second parent + sys.exit(0) + except OSError as err: + self.error("Second fork failed: {}".format(str(err))) + sys.exit(1) - def _redirect_io(self): - # redirect standard file descriptors - sys.stdout.flush() - sys.stderr.flush() - si = io.open(os.devnull, 'rt', encoding='utf-8') - so = io.open(os.devnull, 'at+', encoding='utf-8') - se = io.open(os.devnull, 'at+', encoding='utf-8') + def _redirect_io(self): + # redirect standard file descriptors + sys.stdout.flush() + sys.stderr.flush() + si = io.open(os.devnull, "rt", encoding="utf-8") + so = io.open(os.devnull, "at+", encoding="utf-8") + se = io.open(os.devnull, "at+", encoding="utf-8") - os.dup2(si.fileno(), sys.stdin.fileno()) - os.dup2(so.fileno(), sys.stdout.fileno()) - os.dup2(se.fileno(), sys.stderr.fileno()) + os.dup2(si.fileno(), sys.stdin.fileno()) + os.dup2(so.fileno(), sys.stdout.fileno()) + os.dup2(se.fileno(), sys.stderr.fileno()) - def terminated(self): - self.remove_pidfile() + def terminated(self): + self.remove_pidfile() - def start(self): - """Start the daemon.""" + def start(self): + """Start the daemon.""" - # Check for a pidfile to see if the daemon already runs - pid = self.get_pid() - if pid: - self.error("pidfile {} already exist. Is the daemon already running?".format(self.pidfile)) - sys.exit(1) + # Check for a pidfile to see if the daemon already runs + pid = self.get_pid() + if pid: + self.error( + "pidfile {} already exist. Is the daemon already running?".format( + self.pidfile + ) + ) + sys.exit(1) - self.echo("Starting daemon...") + self.echo("Starting daemon...") - # Start the daemon - self._daemonize() - self.run() + # Start the daemon + self._daemonize() + self.run() - def stop(self, check_running=True): - """Stop the daemon.""" - pid = self.get_pid() - if not pid: - if not check_running: - return - self.error("pidfile {} does not exist. Is the daemon really running?".format(self.pidfile)) - sys.exit(1) + def stop(self, check_running=True): + """Stop the daemon.""" + pid = self.get_pid() + if not pid: + if not check_running: + return + self.error( + "pidfile {} does not exist. Is the daemon really running?".format( + self.pidfile + ) + ) + sys.exit(1) - self.echo("Stopping daemon...") + self.echo("Stopping daemon...") - # Try killing the daemon process - try: - while 1: - os.kill(pid, signal.SIGTERM) - time.sleep(0.1) - except OSError as err: - e = str(err.args) - if e.find("No such process") > 0: - self.remove_pidfile() - else: - self.error(e) - sys.exit(1) + # Try killing the daemon process + try: + while 1: + os.kill(pid, signal.SIGTERM) + time.sleep(0.1) + except OSError as err: + e = str(err.args) + if e.find("No such process") > 0: + self.remove_pidfile() + else: + self.error(e) + sys.exit(1) - def restart(self): - """Restart the daemon.""" - self.stop(check_running=False) - self.start() + def restart(self): + """Restart the daemon.""" + self.stop(check_running=False) + self.start() - def status(self): - """Prints the daemon status.""" - if self.is_running(): - self.echo("Daemon is running") - else: - self.echo("Daemon is not running") + def status(self): + """Prints the daemon status.""" + if self.is_running(): + self.echo("Daemon is running") + else: + self.echo("Daemon is not running") - def is_running(self): - """Check if a process is running under the specified pid.""" - pid = self.get_pid() - if pid is None: - return False + def is_running(self): + """Check if a process is running under the specified pid.""" + pid = self.get_pid() + if pid is None: + return False - try: - os.kill(pid, 0) - except OSError: - try: - self.remove_pidfile() - except Exception: - self.error("Daemon found not running, but could not remove stale pidfile") - return False - else: - return True + try: + os.kill(pid, 0) + except OSError: + try: + self.remove_pidfile() + except Exception: + self.error("Daemon found not running, but could not remove stale pidfile") + return False + else: + return True - def get_pid(self): - """Get the pid from the pidfile.""" - try: - with io.open(self.pidfile,'rt', encoding='utf-8') as pf: - pid = int(pf.read().strip()) - except (IOError, ValueError): - pid = None - return pid + def get_pid(self): + """Get the pid from the pidfile.""" + try: + with io.open(self.pidfile, "rt", encoding="utf-8") as pf: + pid = int(pf.read().strip()) + except (IOError, ValueError): + pid = None + return pid - def set_pid(self, pid): - """Write the pid to the pidfile.""" - with io.open(self.pidfile,'wt+', encoding='utf-8') as f: - f.write(str(pid) + '\n') + def set_pid(self, pid): + """Write the pid to the pidfile.""" + with io.open(self.pidfile, "wt+", encoding="utf-8") as f: + f.write(str(pid) + "\n") - def remove_pidfile(self): - """Removes the pidfile.""" - if os.path.isfile(self.pidfile): - os.remove(self.pidfile) + def remove_pidfile(self): + """Removes the pidfile.""" + if os.path.isfile(self.pidfile): + os.remove(self.pidfile) - def run(self): - """You should override this method when you subclass Daemon. + def run(self): + """You should override this method when you subclass Daemon. - It will be called after the process has been daemonized by - start() or restart().""" + It will be called after the process has been daemonized by + start() or restart().""" - raise NotImplementedError() + raise NotImplementedError() - @classmethod - def echo(cls, line): - print(line) + @classmethod + def echo(cls, line): + print(line) - @classmethod - def error(cls, line): - print(line, file=sys.stderr) + @classmethod + def error(cls, line): + print(line, file=sys.stderr) diff --git a/src/octoprint/environment.py b/src/octoprint/environment.py index dd6fbebf2..9be6847d4 100644 --- a/src/octoprint/environment.py +++ b/src/octoprint/environment.py @@ -1,7 +1,7 @@ # -*- 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" import copy @@ -17,157 +17,177 @@ from octoprint.plugin import EnvironmentDetectionPlugin from octoprint.util.platform import get_os from octoprint.util.version import get_python_version_string + class EnvironmentDetector(object): + def __init__(self, plugin_manager): + self._plugin_manager = plugin_manager - def __init__(self, plugin_manager): - self._plugin_manager = plugin_manager + self._cache = None + self._cache_lock = threading.RLock() - self._cache = None - self._cache_lock = threading.RLock() + self._logger = logging.getLogger(__name__) - self._logger = logging.getLogger(__name__) + try: + self._environment_plugins = self._plugin_manager.get_implementations( + EnvironmentDetectionPlugin + ) + except Exception: + # just in case, see #3100... + self._logger.exception( + "There was an error fetching EnvironmentDetectionPlugins from the plugin manager" + ) + self._environment_plugins = [] - try: - self._environment_plugins = self._plugin_manager.get_implementations(EnvironmentDetectionPlugin) - except Exception: - # just in case, see #3100... - self._logger.exception("There was an error fetching EnvironmentDetectionPlugins from the plugin manager") - self._environment_plugins = [] + @property + def environment(self): + with self._cache_lock: + if self._cache is None: + self.run_detection() + return copy.deepcopy(self._cache) - @property - def environment(self): - with self._cache_lock: - if self._cache is None: - self.run_detection() - return copy.deepcopy(self._cache) + def run_detection(self, notify_plugins=True): + try: + environment = {} + environment["os"] = self._detect_os() + environment["python"] = self._detect_python() + environment["hardware"] = self._detect_hardware() - def run_detection(self, notify_plugins=True): - try: - environment = {} - environment["os"] = self._detect_os() - environment["python"] = self._detect_python() - environment["hardware"] = self._detect_hardware() + plugin_result = self._detect_from_plugins() + if plugin_result: + environment["plugins"] = plugin_result - plugin_result = self._detect_from_plugins() - if plugin_result: - environment["plugins"] = plugin_result + with self._cache_lock: + self._cache = environment - with self._cache_lock: - self._cache = environment + if notify_plugins: + self.notify_plugins() - if notify_plugins: - self.notify_plugins() + return environment + except Exception: + self._logger.exception("Unexpected error while detecting environment") + with self._cache_lock: + self._cache = {} + return self._cache - return environment - except Exception: - self._logger.exception("Unexpected error while detecting environment") - with self._cache_lock: - self._cache = {} - return self._cache + def _detect_os(self): + return {"id": get_os(), "platform": sys.platform} - def _detect_os(self): - return {"id": get_os(), - "platform": sys.platform} + def _detect_python(self): + result = {"version": "unknown", "pip": "unknown"} - def _detect_python(self): - result = {"version": "unknown", - "pip": "unknown"} + # determine python version + try: + result["version"] = get_python_version_string() + except Exception: + self._logger.exception("Error detecting python version") - # determine python version - try: - result["version"] = get_python_version_string() - except Exception: - self._logger.exception("Error detecting python version") + # determine if we are running from a virtual environment + try: + if hasattr(sys, "real_prefix") or ( + hasattr(sys, "base_prefix") + and os.path.realpath(sys.prefix) != os.path.realpath(sys.base_prefix) + ): + result["virtualenv"] = sys.prefix + except Exception: + self._logger.exception( + "Error detecting whether we are running in a virtual environment" + ) - # determine if we are running from a virtual environment - try: - if hasattr(sys, "real_prefix") or (hasattr(sys, "base_prefix") and os.path.realpath(sys.prefix) != os.path.realpath(sys.base_prefix)): - result["virtualenv"] = sys.prefix - except Exception: - self._logger.exception("Error detecting whether we are running in a virtual environment") + # try to find pip version + try: + import pkg_resources - # try to find pip version - try: - import pkg_resources - result["pip"] = pkg_resources.get_distribution("pip").version - except Exception: - self._logger.exception("Error detecting pip version") + result["pip"] = pkg_resources.get_distribution("pip").version + except Exception: + self._logger.exception("Error detecting pip version") - return result + return result - def _detect_hardware(self): - result = {"cores": "unknown", - "freq": "unknown", - "ram": "unknown"} + def _detect_hardware(self): + result = {"cores": "unknown", "freq": "unknown", "ram": "unknown"} - try: - cores = psutil.cpu_count() - cpu_freq = psutil.cpu_freq() - ram = psutil.virtual_memory() - if cores: - result["cores"] = cores - if cpu_freq and hasattr(cpu_freq, "max"): - result["freq"] = cpu_freq.max - if ram and hasattr(ram, "total"): - result["ram"] = ram.total - except Exception: - self._logger.exception("Error while detecting hardware environment") + try: + cores = psutil.cpu_count() + cpu_freq = psutil.cpu_freq() + ram = psutil.virtual_memory() + if cores: + result["cores"] = cores + if cpu_freq and hasattr(cpu_freq, "max"): + result["freq"] = cpu_freq.max + if ram and hasattr(ram, "total"): + result["ram"] = ram.total + except Exception: + self._logger.exception("Error while detecting hardware environment") - return result + return result - def _detect_from_plugins(self): - result = {} + def _detect_from_plugins(self): + result = {} - for implementation in self._environment_plugins: - try: - additional = implementation.get_additional_environment() - if additional is not None and isinstance(additional, dict) and len(additional): - result[implementation._identifier] = additional - except Exception: - self._logger.exception("Error while fetching additional " - "environment data from plugin {}".format(implementation._identifier), - extra={"plugin": implementation._identifier}) + for implementation in self._environment_plugins: + try: + additional = implementation.get_additional_environment() + if ( + additional is not None + and isinstance(additional, dict) + and len(additional) + ): + result[implementation._identifier] = additional + except Exception: + self._logger.exception( + "Error while fetching additional " + "environment data from plugin {}".format(implementation._identifier), + extra={"plugin": implementation._identifier}, + ) - return result + return result - def log_detected_environment(self, only_to_handler=None): - def _log(message, level=logging.INFO): - if only_to_handler is not None: - import octoprint.logging - octoprint.logging.log_to_handler(self._logger, only_to_handler, level, message, []) - else: - self._logger.log(level, message) + def log_detected_environment(self, only_to_handler=None): + def _log(message, level=logging.INFO): + if only_to_handler is not None: + import octoprint.logging - try: - _log(self._format()) - except Exception: - self._logger.exception("Error logging detected environment") + octoprint.logging.log_to_handler( + self._logger, only_to_handler, level, message, [] + ) + else: + self._logger.log(level, message) - def _format(self): - with self._cache_lock: - if self._cache is None: - self.run_detection() - environment = copy.deepcopy(self._cache) + try: + _log(self._format()) + except Exception: + self._logger.exception("Error logging detected environment") - dumped_environment = yaml.safe_dump(environment, - default_flow_style=False, - indent=4, - allow_unicode=True).strip() - environment_lines = "\n".join(map(lambda l: "| {}".format(l), dumped_environment.split("\n"))) - return "Detected environment is Python {} under {} ({}). Details:\n{}".format(environment["python"]["version"], - environment["os"]["id"].title(), - environment["os"]["platform"], - environment_lines) + def _format(self): + with self._cache_lock: + if self._cache is None: + self.run_detection() + environment = copy.deepcopy(self._cache) - def notify_plugins(self): - with self._cache_lock: - if self._cache is None: - self.run_detection(notify_plugins=False) - environment = copy.deepcopy(self._cache) + dumped_environment = yaml.safe_dump( + environment, default_flow_style=False, indent=4, allow_unicode=True + ).strip() + environment_lines = "\n".join( + map(lambda l: "| {}".format(l), dumped_environment.split("\n")) + ) + return "Detected environment is Python {} under {} ({}). Details:\n{}".format( + environment["python"]["version"], + environment["os"]["id"].title(), + environment["os"]["platform"], + environment_lines, + ) - for implementation in self._environment_plugins: - try: - implementation.on_environment_detected(environment) - except Exception: - self._logger.exception("Error while sending environment " - "detection result to plugin {}".format(implementation._identifier)) + def notify_plugins(self): + with self._cache_lock: + if self._cache is None: + self.run_detection(notify_plugins=False) + environment = copy.deepcopy(self._cache) + + for implementation in self._environment_plugins: + try: + implementation.on_environment_detected(environment) + except Exception: + self._logger.exception( + "Error while sending environment " + "detection result to plugin {}".format(implementation._identifier) + ) diff --git a/src/octoprint/events.py b/src/octoprint/events.py index 7ac01ea00..254843119 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -2,16 +2,17 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge , Lars Norpchen" -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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 datetime import logging import subprocess + try: - import queue + import queue except ImportError: - import Queue as queue + import Queue as queue import threading import collections import re @@ -24,465 +25,516 @@ _instance = None def all_events(): - return [getattr(Events, name) for name in Events.__dict__ if not name.startswith("_") and not name in ("register_event",)] + return [ + getattr(Events, name) + for name in Events.__dict__ + if not name.startswith("_") and not name in ("register_event",) + ] class Events(object): - # server - STARTUP = "Startup" - SHUTDOWN = "Shutdown" - CONNECTIVITY_CHANGED = "ConnectivityChanged" + # server + STARTUP = "Startup" + SHUTDOWN = "Shutdown" + CONNECTIVITY_CHANGED = "ConnectivityChanged" - # connect/disconnect to printer - CONNECTING = "Connecting" - CONNECTED = "Connected" - DISCONNECTING = "Disconnecting" - DISCONNECTED = "Disconnected" + # connect/disconnect to printer + CONNECTING = "Connecting" + CONNECTED = "Connected" + DISCONNECTING = "Disconnecting" + DISCONNECTED = "Disconnected" - # State changes - PRINTER_STATE_CHANGED = "PrinterStateChanged" - PRINTER_RESET = "PrinterReset" + # State changes + PRINTER_STATE_CHANGED = "PrinterStateChanged" + PRINTER_RESET = "PrinterReset" - # connect/disconnect by client - CLIENT_OPENED = "ClientOpened" - CLIENT_CLOSED = "ClientClosed" - CLIENT_AUTHED = "ClientAuthed" - CLIENT_DEAUTHED = "ClientDeauthed" + # connect/disconnect by client + CLIENT_OPENED = "ClientOpened" + CLIENT_CLOSED = "ClientClosed" + CLIENT_AUTHED = "ClientAuthed" + CLIENT_DEAUTHED = "ClientDeauthed" - # user login/logout - USER_LOGGED_IN = "UserLoggedIn" - USER_LOGGED_OUT = "UserLoggedOut" + # user login/logout + USER_LOGGED_IN = "UserLoggedIn" + USER_LOGGED_OUT = "UserLoggedOut" - # File management - UPLOAD = "Upload" - FILE_SELECTED = "FileSelected" - FILE_DESELECTED = "FileDeselected" - UPDATED_FILES = "UpdatedFiles" - METADATA_ANALYSIS_STARTED = "MetadataAnalysisStarted" - METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished" - METADATA_STATISTICS_UPDATED = "MetadataStatisticsUpdated" + # File management + UPLOAD = "Upload" + FILE_SELECTED = "FileSelected" + FILE_DESELECTED = "FileDeselected" + UPDATED_FILES = "UpdatedFiles" + METADATA_ANALYSIS_STARTED = "MetadataAnalysisStarted" + METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished" + METADATA_STATISTICS_UPDATED = "MetadataStatisticsUpdated" - FILE_ADDED = "FileAdded" - FILE_REMOVED = "FileRemoved" - FOLDER_ADDED = "FolderAdded" - FOLDER_REMOVED = "FolderRemoved" + FILE_ADDED = "FileAdded" + FILE_REMOVED = "FileRemoved" + FOLDER_ADDED = "FolderAdded" + FOLDER_REMOVED = "FolderRemoved" - # SD Upload - TRANSFER_STARTED = "TransferStarted" - TRANSFER_DONE = "TransferDone" - TRANSFER_FAILED = "TransferFailed" + # SD Upload + TRANSFER_STARTED = "TransferStarted" + TRANSFER_DONE = "TransferDone" + TRANSFER_FAILED = "TransferFailed" - # print job - PRINT_STARTED = "PrintStarted" - PRINT_DONE = "PrintDone" - PRINT_FAILED = "PrintFailed" - PRINT_CANCELLING = "PrintCancelling" - PRINT_CANCELLED = "PrintCancelled" - PRINT_PAUSED = "PrintPaused" - PRINT_RESUMED = "PrintResumed" - ERROR = "Error" + # print job + PRINT_STARTED = "PrintStarted" + PRINT_DONE = "PrintDone" + PRINT_FAILED = "PrintFailed" + PRINT_CANCELLING = "PrintCancelling" + PRINT_CANCELLED = "PrintCancelled" + PRINT_PAUSED = "PrintPaused" + PRINT_RESUMED = "PrintResumed" + ERROR = "Error" - # print/gcode events - POWER_ON = "PowerOn" - POWER_OFF = "PowerOff" - HOME = "Home" - Z_CHANGE = "ZChange" - WAITING = "Waiting" - DWELL = "Dwelling" - COOLING = "Cooling" - ALERT = "Alert" - CONVEYOR = "Conveyor" - EJECT = "Eject" - E_STOP = "EStop" - POSITION_UPDATE = "PositionUpdate" - FIRMWARE_DATA = "FirmwareData" - TOOL_CHANGE = "ToolChange" - REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived" + # print/gcode events + POWER_ON = "PowerOn" + POWER_OFF = "PowerOff" + HOME = "Home" + Z_CHANGE = "ZChange" + WAITING = "Waiting" + DWELL = "Dwelling" + COOLING = "Cooling" + ALERT = "Alert" + CONVEYOR = "Conveyor" + EJECT = "Eject" + E_STOP = "EStop" + POSITION_UPDATE = "PositionUpdate" + FIRMWARE_DATA = "FirmwareData" + TOOL_CHANGE = "ToolChange" + REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived" - # Timelapse - CAPTURE_START = "CaptureStart" - CAPTURE_DONE = "CaptureDone" - CAPTURE_FAILED = "CaptureFailed" - POSTROLL_START = "PostRollStart" - POSTROLL_END = "PostRollEnd" - MOVIE_RENDERING = "MovieRendering" - MOVIE_DONE = "MovieDone" - MOVIE_FAILED = "MovieFailed" + # Timelapse + CAPTURE_START = "CaptureStart" + CAPTURE_DONE = "CaptureDone" + CAPTURE_FAILED = "CaptureFailed" + POSTROLL_START = "PostRollStart" + POSTROLL_END = "PostRollEnd" + MOVIE_RENDERING = "MovieRendering" + MOVIE_DONE = "MovieDone" + MOVIE_FAILED = "MovieFailed" - # Slicing - SLICING_STARTED = "SlicingStarted" - SLICING_DONE = "SlicingDone" - SLICING_FAILED = "SlicingFailed" - SLICING_CANCELLED = "SlicingCancelled" - SLICING_PROFILE_ADDED = "SlicingProfileAdded" - SLICING_PROFILE_MODIFIED = "SlicingProfileModified" - SLICING_PROFILE_DELETED = "SlicingProfileDeleted" + # Slicing + SLICING_STARTED = "SlicingStarted" + SLICING_DONE = "SlicingDone" + SLICING_FAILED = "SlicingFailed" + SLICING_CANCELLED = "SlicingCancelled" + SLICING_PROFILE_ADDED = "SlicingProfileAdded" + SLICING_PROFILE_MODIFIED = "SlicingProfileModified" + SLICING_PROFILE_DELETED = "SlicingProfileDeleted" - # Printer Profiles - PRINTER_PROFILE_ADDED = "PrinterProfileAdded" - PRINTER_PROFILE_MODIFIED = "PrinterProfileModified" - PRINTER_PROFILE_DELETED = "PrinterProfileDeleted" + # Printer Profiles + PRINTER_PROFILE_ADDED = "PrinterProfileAdded" + PRINTER_PROFILE_MODIFIED = "PrinterProfileModified" + PRINTER_PROFILE_DELETED = "PrinterProfileDeleted" - # Settings - SETTINGS_UPDATED = "SettingsUpdated" + # Settings + SETTINGS_UPDATED = "SettingsUpdated" - @classmethod - def register_event(cls, event, prefix=None): - name = cls._to_identifier(event) - if prefix: - event = prefix + event - name = cls._to_identifier(prefix) + name - setattr(cls, name, event) - return name, event + @classmethod + def register_event(cls, event, prefix=None): + name = cls._to_identifier(event) + if prefix: + event = prefix + event + name = cls._to_identifier(prefix) + name + setattr(cls, name, event) + return name, event - # based on https://stackoverflow.com/a/1176023 - _first_cap_re = re.compile('(.)([A-Z][a-z]+)') - _all_cap_re = re.compile('([a-z0-9])([A-Z])') + # based on https://stackoverflow.com/a/1176023 + _first_cap_re = re.compile("(.)([A-Z][a-z]+)") + _all_cap_re = re.compile("([a-z0-9])([A-Z])") + + @classmethod + def _to_identifier(cls, name): + s1 = cls._first_cap_re.sub(r"\1_\2", name) + return cls._all_cap_re.sub(r"\1_\2", s1).upper() - @classmethod - def _to_identifier(cls, name): - s1 = cls._first_cap_re.sub(r'\1_\2', name) - return cls._all_cap_re.sub(r'\1_\2', s1).upper() def eventManager(): - global _instance - if _instance is None: - _instance = EventManager() - return _instance + global _instance + if _instance is None: + _instance = EventManager() + return _instance class EventManager(object): - """ - Handles receiving events and dispatching them to subscribers - """ + """ + Handles receiving events and dispatching them to subscribers + """ - def __init__(self): - self._registeredListeners = collections.defaultdict(list) - self._logger = logging.getLogger(__name__) - self._logger_fire = logging.getLogger("{}.fire".format(__name__)) + def __init__(self): + self._registeredListeners = collections.defaultdict(list) + self._logger = logging.getLogger(__name__) + self._logger_fire = logging.getLogger("{}.fire".format(__name__)) - self._startup_signaled = False - self._shutdown_signaled = False + self._startup_signaled = False + self._shutdown_signaled = False - self._queue = queue.Queue() - self._held_back = queue.Queue() + self._queue = queue.Queue() + self._held_back = queue.Queue() - self._worker = threading.Thread(target=self._work) - self._worker.daemon = True - self._worker.start() + self._worker = threading.Thread(target=self._work) + self._worker.daemon = True + self._worker.start() - def _work(self): - try: - while not self._shutdown_signaled: - event, payload = self._queue.get(True) - if event == Events.SHUTDOWN: - # we've got the shutdown event here, stop event loop processing after this has been processed - self._logger.info("Processing shutdown event, this will be our last event") - self._shutdown_signaled = True + def _work(self): + try: + while not self._shutdown_signaled: + event, payload = self._queue.get(True) + if event == Events.SHUTDOWN: + # we've got the shutdown event here, stop event loop processing after this has been processed + self._logger.info( + "Processing shutdown event, this will be our last event" + ) + self._shutdown_signaled = True - eventListeners = self._registeredListeners[event] - self._logger_fire.debug("Firing event: {} (Payload: {!r})".format(event, payload)) + eventListeners = self._registeredListeners[event] + self._logger_fire.debug( + "Firing event: {} (Payload: {!r})".format(event, payload) + ) - for listener in eventListeners: - self._logger.debug("Sending action to {!r}".format(listener)) - try: - listener(event, payload) - except Exception: - self._logger.exception("Got an exception while sending event {} (Payload: {!r}) to {}".format(event, payload, listener)) + for listener in eventListeners: + self._logger.debug("Sending action to {!r}".format(listener)) + try: + listener(event, payload) + except Exception: + self._logger.exception( + "Got an exception while sending event {} (Payload: {!r}) to {}".format( + event, payload, listener + ) + ) - octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin, - "on_event", - args=(event, payload)) - self._logger.info("Event loop shut down") - except Exception: - self._logger.exception("Ooops, the event bus worker loop crashed") + octoprint.plugin.call_plugin( + octoprint.plugin.types.EventHandlerPlugin, + "on_event", + args=(event, payload), + ) + self._logger.info("Event loop shut down") + except Exception: + self._logger.exception("Ooops, the event bus worker loop crashed") - def fire(self, event, payload=None): - """ - Fire an event to anyone subscribed to it + def fire(self, event, payload=None): + """ + Fire an event to anyone subscribed to it - Any object can generate an event and any object can subscribe to the event's name as a string (arbitrary, but - case sensitive) and any extra payload data that may pertain to the event. + Any object can generate an event and any object can subscribe to the event's name as a string (arbitrary, but + case sensitive) and any extra payload data that may pertain to the event. - Callbacks must implement the signature "callback(event, payload)", with "event" being the event's name and - payload being a payload object specific to the event. - """ + Callbacks must implement the signature "callback(event, payload)", with "event" being the event's name and + payload being a payload object specific to the event. + """ - send_held_back = False - if event == Events.STARTUP: - self._logger.info("Processing startup event, this is our first event") - self._startup_signaled = True - send_held_back = True + send_held_back = False + if event == Events.STARTUP: + self._logger.info("Processing startup event, this is our first event") + self._startup_signaled = True + send_held_back = True - self._enqueue(event, payload) + self._enqueue(event, payload) - if send_held_back: - self._logger.info("Adding {} events to queue that " - "were held back before startup event".format(self._held_back.qsize())) - while True: - try: - self._queue.put(self._held_back.get(block=False)) - except queue.Empty: - break + if send_held_back: + self._logger.info( + "Adding {} events to queue that " + "were held back before startup event".format(self._held_back.qsize()) + ) + while True: + try: + self._queue.put(self._held_back.get(block=False)) + except queue.Empty: + break - def _enqueue(self, event, payload): - if self._startup_signaled: - q = self._queue - else: - q = self._held_back + def _enqueue(self, event, payload): + if self._startup_signaled: + q = self._queue + else: + q = self._held_back - q.put((event, payload)) + q.put((event, payload)) - def subscribe(self, event, callback): - """ - Subscribe a listener to an event -- pass in the event name (as a string) and the callback object - """ + def subscribe(self, event, callback): + """ + Subscribe a listener to an event -- pass in the event name (as a string) and the callback object + """ - if callback in self._registeredListeners[event]: - # callback is already subscribed to the event - return + if callback in self._registeredListeners[event]: + # callback is already subscribed to the event + return - self._registeredListeners[event].append(callback) - self._logger.debug("Subscribed listener {!r} for event {}".format(callback, event)) + self._registeredListeners[event].append(callback) + self._logger.debug( + "Subscribed listener {!r} for event {}".format(callback, event) + ) - def unsubscribe (self, event, callback): - """ - Unsubscribe a listener from an event -- pass in the event name (as string) and the callback object - """ + def unsubscribe(self, event, callback): + """ + Unsubscribe a listener from an event -- pass in the event name (as string) and the callback object + """ - try: - self._registeredListeners[event].remove(callback) - except ValueError: - # not registered - pass + try: + self._registeredListeners[event].remove(callback) + except ValueError: + # not registered + pass - def join(self, timeout=None): - self._worker.join(timeout) - return self._worker.is_alive() + def join(self, timeout=None): + self._worker.join(timeout) + return self._worker.is_alive() class GenericEventListener(object): - """ - The GenericEventListener can be subclassed to easily create custom event listeners. - """ + """ + The GenericEventListener can be subclassed to easily create custom event listeners. + """ - def __init__(self): - self._logger = logging.getLogger(__name__) + def __init__(self): + self._logger = logging.getLogger(__name__) - def subscribe(self, events): - """ - Subscribes the eventCallback method for all events in the given list. - """ + def subscribe(self, events): + """ + Subscribes the eventCallback method for all events in the given list. + """ - for event in events: - eventManager().subscribe(event, self.eventCallback) + for event in events: + eventManager().subscribe(event, self.eventCallback) - def unsubscribe(self, events): - """ - Unsubscribes the eventCallback method for all events in the given list - """ + def unsubscribe(self, events): + """ + Unsubscribes the eventCallback method for all events in the given list + """ - for event in events: - eventManager().unsubscribe(event, self.eventCallback) + for event in events: + eventManager().unsubscribe(event, self.eventCallback) - def eventCallback(self, event, payload): - """ - Actual event callback called with name of event and optional payload. Not implemented here, override in - child classes. - """ - pass + def eventCallback(self, event, payload): + """ + Actual event callback called with name of event and optional payload. Not implemented here, override in + child classes. + """ + pass class DebugEventListener(GenericEventListener): - def __init__(self): - GenericEventListener.__init__(self) + def __init__(self): + GenericEventListener.__init__(self) - events = list(filter(lambda x: not x.startswith("__"), dir(Events))) - self.subscribe(events) + events = list(filter(lambda x: not x.startswith("__"), dir(Events))) + self.subscribe(events) - def eventCallback(self, event, payload): - GenericEventListener.eventCallback(self, event, payload) - self._logger.debug("Received event: %s (Payload: %r)" % (event, payload)) + def eventCallback(self, event, payload): + GenericEventListener.eventCallback(self, event, payload) + self._logger.debug("Received event: %s (Payload: %r)" % (event, payload)) class CommandTrigger(GenericEventListener): - def __init__(self, printer): - GenericEventListener.__init__(self) - self._printer = printer - self._subscriptions = {} + def __init__(self, printer): + GenericEventListener.__init__(self) + self._printer = printer + self._subscriptions = {} - self._initSubscriptions() + self._initSubscriptions() - def _initSubscriptions(self): - """ - Subscribes all events as defined in "events > $triggerType > subscriptions" in the settings with their - respective commands. - """ - if not settings().get(["events"]): - return + def _initSubscriptions(self): + """ + Subscribes all events as defined in "events > $triggerType > subscriptions" in the settings with their + respective commands. + """ + if not settings().get(["events"]): + return - if not settings().getBoolean(["events", "enabled"]): - return + if not settings().getBoolean(["events", "enabled"]): + return - eventsToSubscribe = [] - subscriptions = settings().get(["events", "subscriptions"]) - for subscription in subscriptions: - if not isinstance(subscription, dict): - self._logger.info("Invalid subscription definition, not a dictionary: {!r}".format(subscription)) - continue + eventsToSubscribe = [] + subscriptions = settings().get(["events", "subscriptions"]) + for subscription in subscriptions: + if not isinstance(subscription, dict): + self._logger.info( + "Invalid subscription definition, not a dictionary: {!r}".format( + subscription + ) + ) + continue - if not "event" in subscription or not "command" in subscription \ - or not "type" in subscription or not subscription["type"] in ["system", "gcode"]: - self._logger.info("Invalid command trigger, missing either event, type or command or type is invalid: {!r}".format(subscription)) - continue + if ( + not "event" in subscription + or not "command" in subscription + or not "type" in subscription + or not subscription["type"] in ["system", "gcode"] + ): + self._logger.info( + "Invalid command trigger, missing either event, type or command or type is invalid: {!r}".format( + subscription + ) + ) + continue - if "enabled" in subscription and not subscription["enabled"]: - self._logger.info("Disabled command trigger: {!r}".format(subscription)) - continue + if "enabled" in subscription and not subscription["enabled"]: + self._logger.info("Disabled command trigger: {!r}".format(subscription)) + continue - events = subscription["event"] - command = subscription["command"] - commandType = subscription["type"] - debug = subscription["debug"] if "debug" in subscription else False + events = subscription["event"] + command = subscription["command"] + commandType = subscription["type"] + debug = subscription["debug"] if "debug" in subscription else False - # "event" in the configuration can be a string, or - # a list of strings. If it's the former, convert it - # into the latter. - if not isinstance(events, (tuple, list, set)): - events = [events] + # "event" in the configuration can be a string, or + # a list of strings. If it's the former, convert it + # into the latter. + if not isinstance(events, (tuple, list, set)): + events = [events] - for event in events: - if event not in self._subscriptions: - self._subscriptions[event] = [] - self._subscriptions[event].append((command, commandType, debug)) + for event in events: + if event not in self._subscriptions: + self._subscriptions[event] = [] + self._subscriptions[event].append((command, commandType, debug)) - if event not in eventsToSubscribe: - eventsToSubscribe.append(event) + if event not in eventsToSubscribe: + eventsToSubscribe.append(event) - self.subscribe(eventsToSubscribe) + self.subscribe(eventsToSubscribe) - def eventCallback(self, event, payload): - """ - Event callback, iterates over all subscribed commands for the given event, processes the command - string and then executes the command via the abstract executeCommand method. - """ + def eventCallback(self, event, payload): + """ + Event callback, iterates over all subscribed commands for the given event, processes the command + string and then executes the command via the abstract executeCommand method. + """ - GenericEventListener.eventCallback(self, event, payload) + GenericEventListener.eventCallback(self, event, payload) - if not event in self._subscriptions: - return + if not event in self._subscriptions: + return - for command, commandType, debug in self._subscriptions[event]: - try: - if isinstance(command, (tuple, list, set)): - processedCommand = [] - for c in command: - processedCommand.append(self._processCommand(c, event, payload)) - else: - processedCommand = self._processCommand(command, event, payload) - self.executeCommand(processedCommand, commandType, debug=debug) - except KeyError: - self._logger.warning("There was an error processing one or more placeholders in the following command: %s" % command) + for command, commandType, debug in self._subscriptions[event]: + try: + if isinstance(command, (tuple, list, set)): + processedCommand = [] + for c in command: + processedCommand.append(self._processCommand(c, event, payload)) + else: + processedCommand = self._processCommand(command, event, payload) + self.executeCommand(processedCommand, commandType, debug=debug) + except KeyError: + self._logger.warning( + "There was an error processing one or more placeholders in the following command: %s" + % command + ) - def executeCommand(self, command, commandType, debug=False): - if commandType == "system": - self._executeSystemCommand(command, debug=debug) - elif commandType == "gcode": - self._executeGcodeCommand(command, debug=debug) + def executeCommand(self, command, commandType, debug=False): + if commandType == "system": + self._executeSystemCommand(command, debug=debug) + elif commandType == "gcode": + self._executeGcodeCommand(command, debug=debug) - def _executeSystemCommand(self, command, debug=False): - def commandExecutioner(cmd): - if debug: - self._logger.info("Executing system command: {}".format(cmd)) - else: - self._logger.info("Executing a system command") - # we run this with shell=True since we have to trust whatever - # our admin configured as command and since we want to allow - # shell-alike handling here... - subprocess.check_call(cmd, shell=True) + def _executeSystemCommand(self, command, debug=False): + def commandExecutioner(cmd): + if debug: + self._logger.info("Executing system command: {}".format(cmd)) + else: + self._logger.info("Executing a system command") + # we run this with shell=True since we have to trust whatever + # our admin configured as command and since we want to allow + # shell-alike handling here... + subprocess.check_call(cmd, shell=True) - def process(): - try: - if isinstance(command, (list, tuple, set)): - for c in command: - commandExecutioner(c) - else: - commandExecutioner(command) - except subprocess.CalledProcessError as e: - if debug: - self._logger.warning("Command failed with return code {}: {}".format(e.returncode, str(e))) - else: - self._logger.warning("Command failed with return code {}, enable debug logging on target 'octoprint.events' for details".format(e.returncode)) - except Exception: - self._logger.exception("Command failed") + def process(): + try: + if isinstance(command, (list, tuple, set)): + for c in command: + commandExecutioner(c) + else: + commandExecutioner(command) + except subprocess.CalledProcessError as e: + if debug: + self._logger.warning( + "Command failed with return code {}: {}".format( + e.returncode, str(e) + ) + ) + else: + self._logger.warning( + "Command failed with return code {}, enable debug logging on target 'octoprint.events' for details".format( + e.returncode + ) + ) + except Exception: + self._logger.exception("Command failed") - t = threading.Thread(target=process) - t.daemon = True - t.start() + t = threading.Thread(target=process) + t.daemon = True + t.start() - def _executeGcodeCommand(self, command, debug=False): - commands = [command] - if isinstance(command, (list, tuple, set)): - commands = list(command) - if debug: - self._logger.info("Executing GCode commands: %r" % command) - self._printer.commands(commands) + def _executeGcodeCommand(self, command, debug=False): + commands = [command] + if isinstance(command, (list, tuple, set)): + commands = list(command) + if debug: + self._logger.info("Executing GCode commands: %r" % command) + self._printer.commands(commands) - def _processCommand(self, command, event, payload): - """ - Performs string substitutions in the command string based on a few current parameters. + def _processCommand(self, command, event, payload): + """ + Performs string substitutions in the command string based on a few current parameters. - The following substitutions are currently supported: + The following substitutions are currently supported: - - {__currentZ} : current Z position of the print head, or -1 if not available - - {__eventname} : the name of the event hook being triggered - - {__filename} : name of currently selected file, or "NO FILE" if no file is selected - - {__filepath} : path in origin location of currently selected file, or "NO FILE" if no file is selected - - {__fileorigin} : origin of currently selected file, or "NO FILE" if no file is selected - - {__progress} : current print progress in percent, 0 if no print is in progress - - {__data} : the string representation of the event's payload - - {__json} : the json representation of the event's payload, "{}" if there is no payload, "" if there was an error on serialization - - {__now} : ISO 8601 representation of the current date and time + - {__currentZ} : current Z position of the print head, or -1 if not available + - {__eventname} : the name of the event hook being triggered + - {__filename} : name of currently selected file, or "NO FILE" if no file is selected + - {__filepath} : path in origin location of currently selected file, or "NO FILE" if no file is selected + - {__fileorigin} : origin of currently selected file, or "NO FILE" if no file is selected + - {__progress} : current print progress in percent, 0 if no print is in progress + - {__data} : the string representation of the event's payload + - {__json} : the json representation of the event's payload, "{}" if there is no payload, "" if there was an error on serialization + - {__now} : ISO 8601 representation of the current date and time - Additionally, the keys of the event's payload can also be used as placeholder. - """ + Additionally, the keys of the event's payload can also be used as placeholder. + """ - json_string = "{}" - if payload: - import json - try: - json_string = json.dumps(payload) - except Exception: - self._logger.exception("JSON: Cannot dump %r", payload) - json_string = "" + json_string = "{}" + if payload: + import json - params = { - "__currentZ": "-1", - "__eventname": event, - "__filename": "NO FILE", - "__filepath": "NO PATH", - "__progress": "0", - "__data": str(payload), - "__json": json_string, - "__now": datetime.datetime.now().isoformat() - } + try: + json_string = json.dumps(payload) + except Exception: + self._logger.exception("JSON: Cannot dump %r", payload) + json_string = "" - currentData = self._printer.get_current_data() + params = { + "__currentZ": "-1", + "__eventname": event, + "__filename": "NO FILE", + "__filepath": "NO PATH", + "__progress": "0", + "__data": str(payload), + "__json": json_string, + "__now": datetime.datetime.now().isoformat(), + } - if "currentZ" in currentData and currentData["currentZ"] is not None: - params["__currentZ"] = str(currentData["currentZ"]) + currentData = self._printer.get_current_data() - if "job" in currentData and "file" in currentData["job"] and "name" in currentData["job"]["file"] \ - and currentData["job"]["file"]["name"] is not None: - params["__filename"] = currentData["job"]["file"]["name"] - params["__filepath"] = currentData["job"]["file"]["path"] - params["__fileorigin"] = currentData["job"]["file"]["origin"] - if "progress" in currentData and currentData["progress"] is not None \ - and "completion" in currentData["progress"] and currentData["progress"]["completion"] is not None: - params["__progress"] = str(round(currentData["progress"]["completion"])) + if "currentZ" in currentData and currentData["currentZ"] is not None: + params["__currentZ"] = str(currentData["currentZ"]) - # now add the payload keys as well - if isinstance(payload, dict): - params.update(payload) + if ( + "job" in currentData + and "file" in currentData["job"] + and "name" in currentData["job"]["file"] + and currentData["job"]["file"]["name"] is not None + ): + params["__filename"] = currentData["job"]["file"]["name"] + params["__filepath"] = currentData["job"]["file"]["path"] + params["__fileorigin"] = currentData["job"]["file"]["origin"] + if ( + "progress" in currentData + and currentData["progress"] is not None + and "completion" in currentData["progress"] + and currentData["progress"]["completion"] is not None + ): + params["__progress"] = str(round(currentData["progress"]["completion"])) - return command.format(**params) + # now add the payload keys as well + if isinstance(payload, dict): + params.update(payload) + + return command.format(**params) diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py index 9f904a635..2aa9a7b96 100644 --- a/src/octoprint/filemanager/__init__.py +++ b/src/octoprint/filemanager/__init__.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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 logging @@ -29,712 +29,1040 @@ ContentTypeDetector = namedtuple("ContentTypeDetector", "extensions, detector") extensions = {} + def full_extension_tree(): - result = {"machinecode": {"gcode": ContentTypeMapping(["gcode", "gco", "g"], "text/plain")}} + result = { + "machinecode": {"gcode": ContentTypeMapping(["gcode", "gco", "g"], "text/plain")} + } - def leaf_merger(a, b): - supported_leaf_types = (ContentTypeMapping, ContentTypeDetector, list) - if not isinstance(a, supported_leaf_types) or not isinstance(b, supported_leaf_types): - raise ValueError() + def leaf_merger(a, b): + supported_leaf_types = (ContentTypeMapping, ContentTypeDetector, list) + if not isinstance(a, supported_leaf_types) or not isinstance( + b, supported_leaf_types + ): + raise ValueError() - if isinstance(a, ContentTypeDetector) and isinstance(b, ContentTypeMapping): - raise ValueError() + if isinstance(a, ContentTypeDetector) and isinstance(b, ContentTypeMapping): + raise ValueError() - if isinstance(a, ContentTypeMapping) and isinstance(b, ContentTypeDetector): - raise ValueError() + if isinstance(a, ContentTypeMapping) and isinstance(b, ContentTypeDetector): + raise ValueError() - a_list = a if isinstance(a, list) else a.extensions - b_list = b if isinstance(b, list) else b.extensions - merged = a_list + b_list + a_list = a if isinstance(a, list) else a.extensions + b_list = b if isinstance(b, list) else b.extensions + merged = a_list + b_list - content_type = None - if isinstance(b, ContentTypeMapping): - content_type = b.content_type - elif isinstance(a, ContentTypeMapping): - content_type = a.content_type + content_type = None + if isinstance(b, ContentTypeMapping): + content_type = b.content_type + elif isinstance(a, ContentTypeMapping): + content_type = a.content_type - detector = None - if isinstance(b, ContentTypeDetector): - detector = b.detector - elif isinstance(a, ContentTypeDetector): - detector = a.detector + detector = None + if isinstance(b, ContentTypeDetector): + detector = b.detector + elif isinstance(a, ContentTypeDetector): + detector = a.detector - if content_type is not None: - return ContentTypeMapping(merged, content_type) - elif detector is not None: - return ContentTypeDetector(merged, detector) - else: - return merged + if content_type is not None: + return ContentTypeMapping(merged, content_type) + elif detector is not None: + return ContentTypeDetector(merged, detector) + else: + return merged - slicer_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SlicerPlugin) - for plugin in slicer_plugins: - try: - plugin_result = plugin.get_slicer_extension_tree() - if plugin_result is None or not isinstance(plugin_result, dict): - continue - octoprint.util.dict_merge(result, plugin_result, leaf_merger=leaf_merger, in_place=True) - except Exception: - logging.getLogger(__name__).exception("Exception while retrieving additional extension " - "tree entries from SlicerPlugin {name}".format(name=plugin._identifier), - extra={"plugin": plugin._identifier}) + slicer_plugins = octoprint.plugin.plugin_manager().get_implementations( + octoprint.plugin.SlicerPlugin + ) + for plugin in slicer_plugins: + try: + plugin_result = plugin.get_slicer_extension_tree() + if plugin_result is None or not isinstance(plugin_result, dict): + continue + octoprint.util.dict_merge( + result, plugin_result, leaf_merger=leaf_merger, in_place=True + ) + except Exception: + logging.getLogger(__name__).exception( + "Exception while retrieving additional extension " + "tree entries from SlicerPlugin {name}".format(name=plugin._identifier), + extra={"plugin": plugin._identifier}, + ) - extension_tree_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.filemanager.extension_tree") - for name, hook in extension_tree_hooks.items(): - try: - hook_result = hook() - if hook_result is None or not isinstance(hook_result, dict): - continue - result = octoprint.util.dict_merge(result, hook_result, leaf_merger=leaf_merger, in_place=True) - except Exception: - logging.getLogger(__name__).exception("Exception while retrieving additional extension " - "tree entries from hook {name}".format(name=name), - extra={"plugin": name}) + extension_tree_hooks = octoprint.plugin.plugin_manager().get_hooks( + "octoprint.filemanager.extension_tree" + ) + for name, hook in extension_tree_hooks.items(): + try: + hook_result = hook() + if hook_result is None or not isinstance(hook_result, dict): + continue + result = octoprint.util.dict_merge( + result, hook_result, leaf_merger=leaf_merger, in_place=True + ) + except Exception: + logging.getLogger(__name__).exception( + "Exception while retrieving additional extension " + "tree entries from hook {name}".format(name=name), + extra={"plugin": name}, + ) + + return result - return result def get_extensions(type, subtree=None): - if subtree is None: - subtree = full_extension_tree() + if subtree is None: + subtree = full_extension_tree() - for key, value in subtree.items(): - if key == type: - return get_all_extensions(subtree=value) - elif isinstance(value, dict): - sub_extensions = get_extensions(type, subtree=value) - if sub_extensions: - return sub_extensions + for key, value in subtree.items(): + if key == type: + return get_all_extensions(subtree=value) + elif isinstance(value, dict): + sub_extensions = get_extensions(type, subtree=value) + if sub_extensions: + return sub_extensions + + return None - return None def get_all_extensions(subtree=None): - if subtree is None: - subtree = full_extension_tree() + if subtree is None: + subtree = full_extension_tree() + + result = [] + if isinstance(subtree, dict): + for key, value in subtree.items(): + if isinstance(value, dict): + result += get_all_extensions(value) + elif isinstance(value, (ContentTypeMapping, ContentTypeDetector)): + result += value.extensions + elif isinstance(value, (list, tuple)): + result += value + elif isinstance(subtree, (ContentTypeMapping, ContentTypeDetector)): + result = subtree.extensions + elif isinstance(subtree, (list, tuple)): + result = subtree + return result - result = [] - if isinstance(subtree, dict): - for key, value in subtree.items(): - if isinstance(value, dict): - result += get_all_extensions(value) - elif isinstance(value, (ContentTypeMapping, ContentTypeDetector)): - result += value.extensions - elif isinstance(value, (list, tuple)): - result += value - elif isinstance(subtree, (ContentTypeMapping, ContentTypeDetector)): - result = subtree.extensions - elif isinstance(subtree, (list, tuple)): - result = subtree - return result def get_path_for_extension(extension, subtree=None): - if subtree is None: - subtree = full_extension_tree() + if subtree is None: + subtree = full_extension_tree() - for key, value in subtree.items(): - if isinstance(value, (ContentTypeMapping, ContentTypeDetector)) and extension in value.extensions: - return [key] - elif isinstance(value, (list, tuple)) and extension in value: - return [key] - elif isinstance(value, dict): - path = get_path_for_extension(extension, subtree=value) - if path: - return [key] + path + for key, value in subtree.items(): + if ( + isinstance(value, (ContentTypeMapping, ContentTypeDetector)) + and extension in value.extensions + ): + return [key] + elif isinstance(value, (list, tuple)) and extension in value: + return [key] + elif isinstance(value, dict): + path = get_path_for_extension(extension, subtree=value) + if path: + return [key] + path + + return None - return None def get_content_type_mapping_for_extension(extension, subtree=None): - if subtree is None: - subtree = full_extension_tree() + if subtree is None: + subtree = full_extension_tree() - for key, value in subtree.items(): - content_extension_matches = isinstance(value, (ContentTypeMapping, ContentTypeDetector)) and extension in value.extensions - list_extension_matches = isinstance(value, (list, tuple)) and extension in value + for key, value in subtree.items(): + content_extension_matches = ( + isinstance(value, (ContentTypeMapping, ContentTypeDetector)) + and extension in value.extensions + ) + list_extension_matches = isinstance(value, (list, tuple)) and extension in value - if content_extension_matches or list_extension_matches: - return value - elif isinstance(value, dict): - result = get_content_type_mapping_for_extension(extension, subtree=value) - if result is not None: - return result + if content_extension_matches or list_extension_matches: + return value + elif isinstance(value, dict): + result = get_content_type_mapping_for_extension(extension, subtree=value) + if result is not None: + return result + + return None - return None def valid_extension(extension, type=None): - if not type: - return extension in get_all_extensions() - else: - extensions = get_extensions(type) - if extensions: - return extension in extensions + if not type: + return extension in get_all_extensions() + else: + extensions = get_extensions(type) + if extensions: + return extension in extensions + def valid_file_type(filename, type=None): - _, extension = os.path.splitext(filename) - extension = extension[1:].lower() - return valid_extension(extension, type=type) + _, extension = os.path.splitext(filename) + extension = extension[1:].lower() + return valid_extension(extension, type=type) + def get_file_type(filename): - _, extension = os.path.splitext(filename) - extension = extension[1:].lower() - return get_path_for_extension(extension) + _, extension = os.path.splitext(filename) + extension = extension[1:].lower() + return get_path_for_extension(extension) + def get_mime_type(filename): - _, extension = os.path.splitext(filename) - extension = extension[1:].lower() - mapping = get_content_type_mapping_for_extension(extension) - if mapping: - if isinstance(mapping, ContentTypeMapping) and mapping.content_type is not None: - return mapping.content_type - elif isinstance(mapping, ContentTypeDetector) and callable(mapping.detector): - result = mapping.detector(filename) - if result is not None: - return result - return "application/octet-stream" + _, extension = os.path.splitext(filename) + extension = extension[1:].lower() + mapping = get_content_type_mapping_for_extension(extension) + if mapping: + if isinstance(mapping, ContentTypeMapping) and mapping.content_type is not None: + return mapping.content_type + elif isinstance(mapping, ContentTypeDetector) and callable(mapping.detector): + result = mapping.detector(filename) + if result is not None: + return result + return "application/octet-stream" class NoSuchStorage(Exception): - pass + pass class FileManager(object): - def __init__(self, analysis_queue, slicing_manager, printer_profile_manager, initial_storage_managers=None): - self._logger = logging.getLogger(__name__) - self._analysis_queue = analysis_queue - self._analysis_queue.register_finish_callback(self._on_analysis_finished) - - self._storage_managers = {} - if initial_storage_managers: - self._storage_managers.update(initial_storage_managers) - - self._slicing_manager = slicing_manager - self._printer_profile_manager = printer_profile_manager - - import threading - self._slicing_jobs = {} - self._slicing_jobs_mutex = threading.Lock() - - self._slicing_progress_callbacks = [] - self._last_slicing_progress = None - - self._progress_plugins = [] - self._preprocessor_hooks = {} - - import octoprint.settings - self._recovery_file = os.path.join(octoprint.settings.settings().getBaseFolder("data"), "print_recovery_data.yaml") - self._analyzeGcode = octoprint.settings.settings().get(["gcodeAnalysis", "runAt"]) - - def initialize(self, process_backlog=False): - self.reload_plugins() - if process_backlog: - self.process_backlog() - - def process_backlog(self): - # only check for a backlog if gcodeAnalysis is 'idle' or 'always' - if self._analyzeGcode == "never": - return - - def worker(): - self._logger.info("Adding backlog items from all storage types to analysis queue...".format(**locals())) - for storage_type, storage_manager in self._storage_managers.items(): - self._determine_analysis_backlog(storage_type, storage_manager) - - import threading - thread = threading.Thread(target=worker) - thread.daemon = True - thread.start() - - def reload_plugins(self): - self._progress_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.ProgressPlugin) - self._preprocessor_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.filemanager.preprocessor") - - def register_slicingprogress_callback(self, callback): - self._slicing_progress_callbacks.append(callback) - - def unregister_slicingprogress_callback(self, callback): - try: - self._slicing_progress_callbacks.remove(callback) - except ValueError: - # callback was not registered - pass - - def _determine_analysis_backlog(self, storage_type, storage_manager, root=None, high_priority=False): - counter = 0 - - backlog_generator = storage_manager.analysis_backlog - if root is not None: - backlog_generator = storage_manager.analysis_backlog_for_path(path=root) - - for entry, path, printer_profile in backlog_generator: - file_type = get_file_type(path)[-1] - file_name = storage_manager.split_path(path) - - # we'll use the default printer profile for the backlog since we don't know better - queue_entry = QueueEntry(file_name, entry, file_type, storage_type, path, self._printer_profile_manager.get_default(), None) - if self._analysis_queue.enqueue(queue_entry, high_priority=high_priority): - counter += 1 - - if root: - self._logger.info("Added {counter} items from storage type \"{storage_type}\" and root \"{root}\" to analysis queue".format(**locals())) - else: - self._logger.info("Added {counter} items from storage type \"{storage_type}\" to analysis queue".format(**locals())) - - def add_storage(self, storage_type, storage_manager): - self._storage_managers[storage_type] = storage_manager - self._determine_analysis_backlog(storage_type, storage_manager) - - def remove_storage(self, type): - if not type in self._storage_managers: - return - del self._storage_managers[type] - - @property - def registered_storages(self): - return list(self._storage_managers.keys()) - - @property - def slicing_enabled(self): - return self._slicing_manager.slicing_enabled - - @property - def registered_slicers(self): - return self._slicing_manager.registered_slicers - - @property - def default_slicer(self): - return self._slicing_manager.default_slicer - - def analyse(self, destination, path, printer_profile_id=None): - if not self.file_exists(destination, path): - return - - if printer_profile_id is None: - printer_profile = self._printer_profile_manager.get_current_or_default() - else: - printer_profile = self._printer_profile_manager.get(printer_profile_id) - if printer_profile is None: - printer_profile = self._printer_profile_manager.get_current_or_default() - - queue_entry = self._analysis_queue_entry(destination, path) - self._analysis_queue.dequeue(queue_entry) - - queue_entry = self._analysis_queue_entry(destination, path, printer_profile=printer_profile) - if queue_entry: - return self._analysis_queue.enqueue(queue_entry, high_priority=True) - - return False - - def slice(self, slicer_name, source_location, source_path, dest_location, dest_path, - position=None, profile=None, printer_profile_id=None, overrides=None, display=None, - callback=None, callback_args=None): - absolute_source_path = self.path_on_disk(source_location, source_path) - - def stlProcessed(source_location, source_path, tmp_path, dest_location, dest_path, start_time, - printer_profile_id, callback, callback_args, _error=None, _cancelled=False, _analysis=None): - try: - if _error: - eventManager().fire(Events.SLICING_FAILED, {"slicer": slicer_name, - "stl": source_path, - "stl_location": source_location, - "gcode": dest_path, - "gcode_location": dest_location, - "reason": _error}) - elif _cancelled: - eventManager().fire(Events.SLICING_CANCELLED, {"slicer": slicer_name, - "stl": source_path, - "stl_location": source_location, - "gcode": dest_path, - "gcode_location": dest_location}) - else: - source_meta = self.get_metadata(source_location, source_path) - hash = source_meta.get("hash", "n/a") - - import io - links = [("model", {"name": source_path})] - _, stl_name = self.split_path(source_location, source_path) - file_obj = StreamWrapper(os.path.basename(dest_path), - io.BytesIO(";Generated from {stl_name} (hash: {hash})\n".format(**locals()).encode("ascii", "replace")), - io.FileIO(tmp_path, 'rb')) - - printer_profile = self._printer_profile_manager.get(printer_profile_id) - self.add_file(dest_location, dest_path, file_obj, - display=display, links=links, allow_overwrite=True, - printer_profile=printer_profile, analysis=_analysis) - - end_time = octoprint.util.monotonic_time() - eventManager().fire(Events.SLICING_DONE, {"slicer": slicer_name, - "stl": source_path, - "stl_location": source_location, - "gcode": dest_path, - "gcode_location": dest_location, - "time": end_time - start_time}) - - if callback is not None: - if callback_args is None: - callback_args = () - callback(*callback_args) - finally: - os.remove(tmp_path) - - source_job_key = (source_location, source_path) - dest_job_key = (dest_location, dest_path) - - with self._slicing_jobs_mutex: - if source_job_key in self._slicing_jobs: - del self._slicing_jobs[source_job_key] - if dest_job_key in self._slicing_jobs: - del self._slicing_jobs[dest_job_key] - - slicer = self._slicing_manager.get_slicer(slicer_name) - - start_time = octoprint.util.monotonic_time() - eventManager().fire(Events.SLICING_STARTED, {"slicer": slicer_name, - "stl": source_path, - "stl_location": source_location, - "gcode": dest_path, - "gcode_location": dest_location, - "progressAvailable": slicer.get_slicer_properties().get("progress_report", False) if slicer else False}) - - import tempfile - f = tempfile.NamedTemporaryFile(suffix=".gco", delete=False) - temp_path = f.name - f.close() - - with self._slicing_jobs_mutex: - source_job_key = (source_location, source_path) - dest_job_key = (dest_location, dest_path) - if dest_job_key in self._slicing_jobs: - job_slicer_name, job_absolute_source_path, job_temp_path = self._slicing_jobs[dest_job_key] - - self._slicing_manager.cancel_slicing(job_slicer_name, job_absolute_source_path, job_temp_path) - del self._slicing_jobs[dest_job_key] - - self._slicing_jobs[dest_job_key] = self._slicing_jobs[source_job_key] = (slicer_name, absolute_source_path, temp_path) - - args = (source_location, source_path, temp_path, dest_location, dest_path, start_time, printer_profile_id, callback, callback_args) - self._slicing_manager.slice(slicer_name, - absolute_source_path, - temp_path, - profile, - stlProcessed, - position=position, - callback_args=args, - overrides=overrides, - printer_profile_id=printer_profile_id, - on_progress=self.on_slicing_progress, - on_progress_args=(slicer_name, source_location, source_path, dest_location, dest_path)) - - def on_slicing_progress(self, slicer, source_location, source_path, dest_location, dest_path, _progress=None): - if not _progress: - return - - progress_int = int(_progress * 100) - if self._last_slicing_progress != progress_int: - self._last_slicing_progress = progress_int - for callback in self._slicing_progress_callbacks: - try: - callback.sendSlicingProgress(slicer, source_location, source_path, dest_location, dest_path, progress_int) - except Exception: - self._logger.exception("Exception while pushing slicing progress", - extra={"callback": fqcn(callback)}) - - if progress_int: - def call_plugins(slicer, source_location, source_path, dest_location, dest_path, progress): - for plugin in self._progress_plugins: - try: - plugin.on_slicing_progress(slicer, source_location, source_path, dest_location, dest_path, progress) - except Exception: - self._logger.exception("Exception while sending slicing progress to plugin %s" % plugin._identifier, - extra={"plugin": plugin._identifier}) - - import threading - thread = threading.Thread(target=call_plugins, args=(slicer, source_location, source_path, dest_location, dest_path, progress_int)) - thread.daemon = False - thread.start() - - - def get_busy_files(self): - return self._slicing_jobs.keys() - - def file_in_path(self, destination, path, file): - return self._storage(destination).file_in_path(path, file) - - def file_exists(self, destination, path): - return self._storage(destination).file_exists(path) - - def folder_exists(self, destination, path): - return self._storage(destination).folder_exists(path) - - def list_files(self, destinations=None, path=None, filter=None, recursive=None, force_refresh=False): - if not destinations: - destinations = list(self._storage_managers.keys()) - if isinstance(destinations, basestring): - destinations = [destinations] - - result = {} - for dst in destinations: - result[dst] = self._storage_managers[dst].list_files(path=path, filter=filter, recursive=recursive, force_refresh=force_refresh) - return result - - def add_file(self, destination, path, file_object, links=None, allow_overwrite=False, printer_profile=None, analysis=None, display=None): - if printer_profile is None: - printer_profile = self._printer_profile_manager.get_current_or_default() - - for name, hook in self._preprocessor_hooks.items(): - try: - hook_file_object = hook(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite) - except Exception: - self._logger.exception("Error when calling preprocessor hook for plugin {}, ignoring".format(name), extra={"plugin": name}) - continue - - if hook_file_object is not None: - file_object = hook_file_object - - queue_entry = self._analysis_queue_entry(destination, path) - - if queue_entry is not None: - self._analysis_queue.dequeue(queue_entry) - - path_in_storage = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite, display=display) - - queue_entry = self._analysis_queue_entry(destination, path_in_storage, printer_profile=printer_profile, analysis=analysis) - if queue_entry: - self._analysis_queue.enqueue(queue_entry, high_priority=True) - - _, name = self._storage(destination).split_path(path_in_storage) - eventManager().fire(Events.FILE_ADDED, {"storage": destination, - "path": path_in_storage, - "name": name, - "type": get_file_type(name)}) - eventManager().fire(Events.UPDATED_FILES, {"type": "printables"}) - return path_in_storage - - def remove_file(self, destination, path): - queue_entry = self._analysis_queue_entry(destination, path) - self._analysis_queue.dequeue(queue_entry) - self._storage(destination).remove_file(path) - - _, name = self._storage(destination).split_path(path) - eventManager().fire(Events.FILE_REMOVED, {"storage": destination, - "path": path, - "name": name, - "type": get_file_type(name)}) - eventManager().fire(Events.UPDATED_FILES, {"type": "printables"}) - - def copy_file(self, destination, source, dst): - path_in_storage = self._storage(destination).copy_file(source, dst) - if not self.has_analysis(destination, path_in_storage): - queue_entry = self._analysis_queue_entry(destination, path_in_storage) - if queue_entry: - self._analysis_queue.enqueue(queue_entry) - - _, name = self._storage(destination).split_path(path_in_storage) - eventManager().fire(Events.FILE_ADDED, {"storage": destination, - "path": path_in_storage, - "name": name, - "type": get_file_type(name)}) - eventManager().fire(Events.UPDATED_FILES, {"type": "printables"}) - - def move_file(self, destination, source, dst): - queue_entry = self._analysis_queue_entry(destination, source) - self._analysis_queue.dequeue(queue_entry) - path = self._storage(destination).move_file(source, dst) - if not self.has_analysis(destination, path): - queue_entry = self._analysis_queue_entry(destination, path) - if queue_entry: - self._analysis_queue.enqueue(queue_entry) - - source_path_in_storage = self._storage(destination).path_in_storage(source) - _, source_name = self._storage(destination).split_path(source_path_in_storage) - dst_path_in_storage = self._storage(destination).path_in_storage(dst) - _, dst_name = self._storage(destination).split_path(dst_path_in_storage) - - eventManager().fire(Events.FILE_REMOVED, {"storage": destination, - "path": source_path_in_storage, - "name": source_name, - "type": get_file_type(source_name)}) - eventManager().fire(Events.FILE_ADDED, {"storage": destination, - "path": dst_path_in_storage, - "name": dst_name, - "type": get_file_type(dst_name)}) - eventManager().fire(Events.UPDATED_FILES, {"type": "printables"}) - - def add_folder(self, destination, path, ignore_existing=True, display=None): - path_in_storage = self._storage(destination).add_folder(path, ignore_existing=ignore_existing, display=display) - - _, name = self._storage(destination).split_path(path_in_storage) - eventManager().fire(Events.FOLDER_ADDED, {"storage": destination, - "path": path_in_storage, - "name": name}) - eventManager().fire(Events.UPDATED_FILES, {"type": "printables"}) - return path_in_storage - - def remove_folder(self, destination, path, recursive=True): - self._analysis_queue.dequeue_folder(destination, path) - self._analysis_queue.pause() - self._storage(destination).remove_folder(path, recursive=recursive) - self._analysis_queue.resume() - - _, name = self._storage(destination).split_path(path) - eventManager().fire(Events.FOLDER_REMOVED, {"storage": destination, - "path": path, - "name": name}) - eventManager().fire(Events.UPDATED_FILES, {"type": "printables"}) - - def copy_folder(self, destination, source, dst): - path_in_storage = self._storage(destination).copy_folder(source, dst) - self._determine_analysis_backlog(destination, self._storage(destination), root=path_in_storage) - - _, name = self._storage(destination).split_path(path_in_storage) - eventManager().fire(Events.FOLDER_ADDED, {"storage": destination, - "path": path_in_storage, - "name": name}) - eventManager().fire(Events.UPDATED_FILES, {"type": "printables"}) - - def move_folder(self, destination, source, dst): - self._analysis_queue.dequeue_folder(destination, source) - self._analysis_queue.pause() - dst_path_in_storage = self._storage(destination).move_folder(source, dst) - self._determine_analysis_backlog(destination, self._storage(destination), root=dst_path_in_storage) - self._analysis_queue.resume() - - source_path_in_storage = self._storage(destination).path_in_storage(source) - _, source_name = self._storage(destination).split_path(source_path_in_storage) - _, dst_name = self._storage(destination).split_path(dst_path_in_storage) - - eventManager().fire(Events.FOLDER_REMOVED, {"storage": destination, - "path": source_path_in_storage, - "name": source_name}) - eventManager().fire(Events.FOLDER_ADDED, {"storage": destination, - "path": dst_path_in_storage, - "name": dst_name}) - eventManager().fire(Events.UPDATED_FILES, {"type": "printables"}) - - def has_analysis(self, destination, path): - return self._storage(destination).has_analysis(path) - - def get_metadata(self, destination, path): - return self._storage(destination).get_metadata(path) - - def add_link(self, destination, path, rel, data): - self._storage(destination).add_link(path, rel, data) - - def remove_link(self, destination, path, rel, data): - self._storage(destination).remove_link(path, rel, data) - - def log_print(self, destination, path, timestamp, print_time, success, printer_profile): - try: - if success: - self._storage(destination).add_history(path, {"timestamp": timestamp, - "printTime": print_time, - "success": success, - "printerProfile": printer_profile}) - else: - self._storage(destination).add_history(path, {"timestamp": timestamp, - "success": success, - "printerProfile": printer_profile}) - eventManager().fire(Events.METADATA_STATISTICS_UPDATED, {"storage": destination, - "path": path}) - except NoSuchStorage: - # if there's no storage configured where to log the print, we'll just not log it - pass - - def save_recovery_data(self, origin, path, pos): - import time - import yaml - from octoprint.util import atomic_write - - data = {"origin": origin, - "path": self.path_in_storage(origin, path), - "pos": pos, - "date": time.time()} - 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) - except Exception: - self._logger.exception("Could not write recovery data to file {}".format(self._recovery_file)) - - def delete_recovery_data(self): - if not os.path.isfile(self._recovery_file): - return - - try: - os.remove(self._recovery_file) - except Exception: - self._logger.exception("Error deleting recovery data file {}".format(self._recovery_file)) - - def get_recovery_data(self): - if not os.path.isfile(self._recovery_file): - return None - - import yaml - try: - with io.open(self._recovery_file, 'rt', encoding='utf-8') as f: - data = yaml.safe_load(f) - if not isinstance(data, dict) or not all(map(lambda x: x in data, ("origin", "path", "pos", "date"))): - raise ValueError("Invalid recovery data structure") - return data - except Exception: - self._logger.exception("Could not read recovery data from file {}".format(self._recovery_file)) - self.delete_recovery_data() - - def get_additional_metadata(self, destination, path, key): - self._storage(destination).get_additional_metadata(path, key) - - def set_additional_metadata(self, destination, path, key, data, overwrite=False, merge=False): - self._storage(destination).set_additional_metadata(path, key, data, overwrite=overwrite, merge=merge) - - def remove_additional_metadata(self, destination, path, key): - self._storage(destination).remove_additional_metadata(path, key) - - def path_on_disk(self, destination, path): - return self._storage(destination).path_on_disk(path) - - def canonicalize(self, destination, path): - return self._storage(destination).canonicalize(path) - - def sanitize(self, destination, path): - return self._storage(destination).sanitize(path) - - def sanitize_name(self, destination, name): - return self._storage(destination).sanitize_name(name) - - def sanitize_path(self, destination, path): - return self._storage(destination).sanitize_path(path) - - def split_path(self, destination, path): - return self._storage(destination).split_path(path) - - def join_path(self, destination, *path): - return self._storage(destination).join_path(*path) - - def path_in_storage(self, destination, path): - return self._storage(destination).path_in_storage(path) - - def last_modified(self, destination, path=None, recursive=False): - return self._storage(destination).last_modified(path=path, recursive=recursive) - - def _storage(self, destination): - if not destination in self._storage_managers: - raise NoSuchStorage("No storage configured for destination {destination}".format(**locals())) - return self._storage_managers[destination] - - def _add_analysis_result(self, destination, path, result): - if not destination in self._storage_managers: - return - - storage_manager = self._storage_managers[destination] - storage_manager.set_additional_metadata(path, "analysis", result, overwrite=True) - - def _on_analysis_finished(self, entry, result): - self._add_analysis_result(entry.location, entry.path, result) - - def _analysis_queue_entry(self, destination, path, printer_profile=None, analysis=None): - if printer_profile is None: - printer_profile = self._printer_profile_manager.get_current_or_default() - - absolute_path = self._storage(destination).path_on_disk(path) - _, file_name = self._storage(destination).split_path(path) - file_type = get_file_type(absolute_path) - - if file_type: - return QueueEntry(file_name, path, file_type[-1], destination, absolute_path, printer_profile, analysis) - else: - return None + def __init__( + self, + analysis_queue, + slicing_manager, + printer_profile_manager, + initial_storage_managers=None, + ): + self._logger = logging.getLogger(__name__) + self._analysis_queue = analysis_queue + self._analysis_queue.register_finish_callback(self._on_analysis_finished) + + self._storage_managers = {} + if initial_storage_managers: + self._storage_managers.update(initial_storage_managers) + + self._slicing_manager = slicing_manager + self._printer_profile_manager = printer_profile_manager + + import threading + + self._slicing_jobs = {} + self._slicing_jobs_mutex = threading.Lock() + + self._slicing_progress_callbacks = [] + self._last_slicing_progress = None + + self._progress_plugins = [] + self._preprocessor_hooks = {} + + import octoprint.settings + + self._recovery_file = os.path.join( + octoprint.settings.settings().getBaseFolder("data"), + "print_recovery_data.yaml", + ) + self._analyzeGcode = octoprint.settings.settings().get(["gcodeAnalysis", "runAt"]) + + def initialize(self, process_backlog=False): + self.reload_plugins() + if process_backlog: + self.process_backlog() + + def process_backlog(self): + # only check for a backlog if gcodeAnalysis is 'idle' or 'always' + if self._analyzeGcode == "never": + return + + def worker(): + self._logger.info( + "Adding backlog items from all storage types to analysis queue...".format( + **locals() + ) + ) + for storage_type, storage_manager in self._storage_managers.items(): + self._determine_analysis_backlog(storage_type, storage_manager) + + import threading + + thread = threading.Thread(target=worker) + thread.daemon = True + thread.start() + + def reload_plugins(self): + self._progress_plugins = octoprint.plugin.plugin_manager().get_implementations( + octoprint.plugin.ProgressPlugin + ) + self._preprocessor_hooks = octoprint.plugin.plugin_manager().get_hooks( + "octoprint.filemanager.preprocessor" + ) + + def register_slicingprogress_callback(self, callback): + self._slicing_progress_callbacks.append(callback) + + def unregister_slicingprogress_callback(self, callback): + try: + self._slicing_progress_callbacks.remove(callback) + except ValueError: + # callback was not registered + pass + + def _determine_analysis_backlog( + self, storage_type, storage_manager, root=None, high_priority=False + ): + counter = 0 + + backlog_generator = storage_manager.analysis_backlog + if root is not None: + backlog_generator = storage_manager.analysis_backlog_for_path(path=root) + + for entry, path, printer_profile in backlog_generator: + file_type = get_file_type(path)[-1] + file_name = storage_manager.split_path(path) + + # we'll use the default printer profile for the backlog since we don't know better + queue_entry = QueueEntry( + file_name, + entry, + file_type, + storage_type, + path, + self._printer_profile_manager.get_default(), + None, + ) + if self._analysis_queue.enqueue(queue_entry, high_priority=high_priority): + counter += 1 + + if root: + self._logger.info( + 'Added {counter} items from storage type "{storage_type}" and root "{root}" to analysis queue'.format( + **locals() + ) + ) + else: + self._logger.info( + 'Added {counter} items from storage type "{storage_type}" to analysis queue'.format( + **locals() + ) + ) + + def add_storage(self, storage_type, storage_manager): + self._storage_managers[storage_type] = storage_manager + self._determine_analysis_backlog(storage_type, storage_manager) + + def remove_storage(self, type): + if not type in self._storage_managers: + return + del self._storage_managers[type] + + @property + def registered_storages(self): + return list(self._storage_managers.keys()) + + @property + def slicing_enabled(self): + return self._slicing_manager.slicing_enabled + + @property + def registered_slicers(self): + return self._slicing_manager.registered_slicers + + @property + def default_slicer(self): + return self._slicing_manager.default_slicer + + def analyse(self, destination, path, printer_profile_id=None): + if not self.file_exists(destination, path): + return + + if printer_profile_id is None: + printer_profile = self._printer_profile_manager.get_current_or_default() + else: + printer_profile = self._printer_profile_manager.get(printer_profile_id) + if printer_profile is None: + printer_profile = self._printer_profile_manager.get_current_or_default() + + queue_entry = self._analysis_queue_entry(destination, path) + self._analysis_queue.dequeue(queue_entry) + + queue_entry = self._analysis_queue_entry( + destination, path, printer_profile=printer_profile + ) + if queue_entry: + return self._analysis_queue.enqueue(queue_entry, high_priority=True) + + return False + + def slice( + self, + slicer_name, + source_location, + source_path, + dest_location, + dest_path, + position=None, + profile=None, + printer_profile_id=None, + overrides=None, + display=None, + callback=None, + callback_args=None, + ): + absolute_source_path = self.path_on_disk(source_location, source_path) + + def stlProcessed( + source_location, + source_path, + tmp_path, + dest_location, + dest_path, + start_time, + printer_profile_id, + callback, + callback_args, + _error=None, + _cancelled=False, + _analysis=None, + ): + try: + if _error: + eventManager().fire( + Events.SLICING_FAILED, + { + "slicer": slicer_name, + "stl": source_path, + "stl_location": source_location, + "gcode": dest_path, + "gcode_location": dest_location, + "reason": _error, + }, + ) + elif _cancelled: + eventManager().fire( + Events.SLICING_CANCELLED, + { + "slicer": slicer_name, + "stl": source_path, + "stl_location": source_location, + "gcode": dest_path, + "gcode_location": dest_location, + }, + ) + else: + source_meta = self.get_metadata(source_location, source_path) + hash = source_meta.get("hash", "n/a") + + import io + + links = [("model", {"name": source_path})] + _, stl_name = self.split_path(source_location, source_path) + file_obj = StreamWrapper( + os.path.basename(dest_path), + io.BytesIO( + ";Generated from {stl_name} (hash: {hash})\n".format( + **locals() + ).encode("ascii", "replace") + ), + io.FileIO(tmp_path, "rb"), + ) + + printer_profile = self._printer_profile_manager.get( + printer_profile_id + ) + self.add_file( + dest_location, + dest_path, + file_obj, + display=display, + links=links, + allow_overwrite=True, + printer_profile=printer_profile, + analysis=_analysis, + ) + + end_time = octoprint.util.monotonic_time() + eventManager().fire( + Events.SLICING_DONE, + { + "slicer": slicer_name, + "stl": source_path, + "stl_location": source_location, + "gcode": dest_path, + "gcode_location": dest_location, + "time": end_time - start_time, + }, + ) + + if callback is not None: + if callback_args is None: + callback_args = () + callback(*callback_args) + finally: + os.remove(tmp_path) + + source_job_key = (source_location, source_path) + dest_job_key = (dest_location, dest_path) + + with self._slicing_jobs_mutex: + if source_job_key in self._slicing_jobs: + del self._slicing_jobs[source_job_key] + if dest_job_key in self._slicing_jobs: + del self._slicing_jobs[dest_job_key] + + slicer = self._slicing_manager.get_slicer(slicer_name) + + start_time = octoprint.util.monotonic_time() + eventManager().fire( + Events.SLICING_STARTED, + { + "slicer": slicer_name, + "stl": source_path, + "stl_location": source_location, + "gcode": dest_path, + "gcode_location": dest_location, + "progressAvailable": slicer.get_slicer_properties().get( + "progress_report", False + ) + if slicer + else False, + }, + ) + + import tempfile + + f = tempfile.NamedTemporaryFile(suffix=".gco", delete=False) + temp_path = f.name + f.close() + + with self._slicing_jobs_mutex: + source_job_key = (source_location, source_path) + dest_job_key = (dest_location, dest_path) + if dest_job_key in self._slicing_jobs: + ( + job_slicer_name, + job_absolute_source_path, + job_temp_path, + ) = self._slicing_jobs[dest_job_key] + + self._slicing_manager.cancel_slicing( + job_slicer_name, job_absolute_source_path, job_temp_path + ) + del self._slicing_jobs[dest_job_key] + + self._slicing_jobs[dest_job_key] = self._slicing_jobs[source_job_key] = ( + slicer_name, + absolute_source_path, + temp_path, + ) + + args = ( + source_location, + source_path, + temp_path, + dest_location, + dest_path, + start_time, + printer_profile_id, + callback, + callback_args, + ) + self._slicing_manager.slice( + slicer_name, + absolute_source_path, + temp_path, + profile, + stlProcessed, + position=position, + callback_args=args, + overrides=overrides, + printer_profile_id=printer_profile_id, + on_progress=self.on_slicing_progress, + on_progress_args=( + slicer_name, + source_location, + source_path, + dest_location, + dest_path, + ), + ) + + def on_slicing_progress( + self, + slicer, + source_location, + source_path, + dest_location, + dest_path, + _progress=None, + ): + if not _progress: + return + + progress_int = int(_progress * 100) + if self._last_slicing_progress != progress_int: + self._last_slicing_progress = progress_int + for callback in self._slicing_progress_callbacks: + try: + callback.sendSlicingProgress( + slicer, + source_location, + source_path, + dest_location, + dest_path, + progress_int, + ) + except Exception: + self._logger.exception( + "Exception while pushing slicing progress", + extra={"callback": fqcn(callback)}, + ) + + if progress_int: + + def call_plugins( + slicer, + source_location, + source_path, + dest_location, + dest_path, + progress, + ): + for plugin in self._progress_plugins: + try: + plugin.on_slicing_progress( + slicer, + source_location, + source_path, + dest_location, + dest_path, + progress, + ) + except Exception: + self._logger.exception( + "Exception while sending slicing progress to plugin %s" + % plugin._identifier, + extra={"plugin": plugin._identifier}, + ) + + import threading + + thread = threading.Thread( + target=call_plugins, + args=( + slicer, + source_location, + source_path, + dest_location, + dest_path, + progress_int, + ), + ) + thread.daemon = False + thread.start() + + def get_busy_files(self): + return self._slicing_jobs.keys() + + def file_in_path(self, destination, path, file): + return self._storage(destination).file_in_path(path, file) + + def file_exists(self, destination, path): + return self._storage(destination).file_exists(path) + + def folder_exists(self, destination, path): + return self._storage(destination).folder_exists(path) + + def list_files( + self, + destinations=None, + path=None, + filter=None, + recursive=None, + force_refresh=False, + ): + if not destinations: + destinations = list(self._storage_managers.keys()) + if isinstance(destinations, basestring): + destinations = [destinations] + + result = {} + for dst in destinations: + result[dst] = self._storage_managers[dst].list_files( + path=path, filter=filter, recursive=recursive, force_refresh=force_refresh + ) + return result + + def add_file( + self, + destination, + path, + file_object, + links=None, + allow_overwrite=False, + printer_profile=None, + analysis=None, + display=None, + ): + if printer_profile is None: + printer_profile = self._printer_profile_manager.get_current_or_default() + + for name, hook in self._preprocessor_hooks.items(): + try: + hook_file_object = hook( + path, + file_object, + links=links, + printer_profile=printer_profile, + allow_overwrite=allow_overwrite, + ) + except Exception: + self._logger.exception( + "Error when calling preprocessor hook for plugin {}, ignoring".format( + name + ), + extra={"plugin": name}, + ) + continue + + if hook_file_object is not None: + file_object = hook_file_object + + queue_entry = self._analysis_queue_entry(destination, path) + + if queue_entry is not None: + self._analysis_queue.dequeue(queue_entry) + + path_in_storage = self._storage(destination).add_file( + path, + file_object, + links=links, + printer_profile=printer_profile, + allow_overwrite=allow_overwrite, + display=display, + ) + + queue_entry = self._analysis_queue_entry( + destination, + path_in_storage, + printer_profile=printer_profile, + analysis=analysis, + ) + if queue_entry: + self._analysis_queue.enqueue(queue_entry, high_priority=True) + + _, name = self._storage(destination).split_path(path_in_storage) + eventManager().fire( + Events.FILE_ADDED, + { + "storage": destination, + "path": path_in_storage, + "name": name, + "type": get_file_type(name), + }, + ) + eventManager().fire(Events.UPDATED_FILES, {"type": "printables"}) + return path_in_storage + + def remove_file(self, destination, path): + queue_entry = self._analysis_queue_entry(destination, path) + self._analysis_queue.dequeue(queue_entry) + self._storage(destination).remove_file(path) + + _, name = self._storage(destination).split_path(path) + eventManager().fire( + Events.FILE_REMOVED, + { + "storage": destination, + "path": path, + "name": name, + "type": get_file_type(name), + }, + ) + eventManager().fire(Events.UPDATED_FILES, {"type": "printables"}) + + def copy_file(self, destination, source, dst): + path_in_storage = self._storage(destination).copy_file(source, dst) + if not self.has_analysis(destination, path_in_storage): + queue_entry = self._analysis_queue_entry(destination, path_in_storage) + if queue_entry: + self._analysis_queue.enqueue(queue_entry) + + _, name = self._storage(destination).split_path(path_in_storage) + eventManager().fire( + Events.FILE_ADDED, + { + "storage": destination, + "path": path_in_storage, + "name": name, + "type": get_file_type(name), + }, + ) + eventManager().fire(Events.UPDATED_FILES, {"type": "printables"}) + + def move_file(self, destination, source, dst): + queue_entry = self._analysis_queue_entry(destination, source) + self._analysis_queue.dequeue(queue_entry) + path = self._storage(destination).move_file(source, dst) + if not self.has_analysis(destination, path): + queue_entry = self._analysis_queue_entry(destination, path) + if queue_entry: + self._analysis_queue.enqueue(queue_entry) + + source_path_in_storage = self._storage(destination).path_in_storage(source) + _, source_name = self._storage(destination).split_path(source_path_in_storage) + dst_path_in_storage = self._storage(destination).path_in_storage(dst) + _, dst_name = self._storage(destination).split_path(dst_path_in_storage) + + eventManager().fire( + Events.FILE_REMOVED, + { + "storage": destination, + "path": source_path_in_storage, + "name": source_name, + "type": get_file_type(source_name), + }, + ) + eventManager().fire( + Events.FILE_ADDED, + { + "storage": destination, + "path": dst_path_in_storage, + "name": dst_name, + "type": get_file_type(dst_name), + }, + ) + eventManager().fire(Events.UPDATED_FILES, {"type": "printables"}) + + def add_folder(self, destination, path, ignore_existing=True, display=None): + path_in_storage = self._storage(destination).add_folder( + path, ignore_existing=ignore_existing, display=display + ) + + _, name = self._storage(destination).split_path(path_in_storage) + eventManager().fire( + Events.FOLDER_ADDED, + {"storage": destination, "path": path_in_storage, "name": name}, + ) + eventManager().fire(Events.UPDATED_FILES, {"type": "printables"}) + return path_in_storage + + def remove_folder(self, destination, path, recursive=True): + self._analysis_queue.dequeue_folder(destination, path) + self._analysis_queue.pause() + self._storage(destination).remove_folder(path, recursive=recursive) + self._analysis_queue.resume() + + _, name = self._storage(destination).split_path(path) + eventManager().fire( + Events.FOLDER_REMOVED, {"storage": destination, "path": path, "name": name} + ) + eventManager().fire(Events.UPDATED_FILES, {"type": "printables"}) + + def copy_folder(self, destination, source, dst): + path_in_storage = self._storage(destination).copy_folder(source, dst) + self._determine_analysis_backlog( + destination, self._storage(destination), root=path_in_storage + ) + + _, name = self._storage(destination).split_path(path_in_storage) + eventManager().fire( + Events.FOLDER_ADDED, + {"storage": destination, "path": path_in_storage, "name": name}, + ) + eventManager().fire(Events.UPDATED_FILES, {"type": "printables"}) + + def move_folder(self, destination, source, dst): + self._analysis_queue.dequeue_folder(destination, source) + self._analysis_queue.pause() + dst_path_in_storage = self._storage(destination).move_folder(source, dst) + self._determine_analysis_backlog( + destination, self._storage(destination), root=dst_path_in_storage + ) + self._analysis_queue.resume() + + source_path_in_storage = self._storage(destination).path_in_storage(source) + _, source_name = self._storage(destination).split_path(source_path_in_storage) + _, dst_name = self._storage(destination).split_path(dst_path_in_storage) + + eventManager().fire( + Events.FOLDER_REMOVED, + {"storage": destination, "path": source_path_in_storage, "name": source_name}, + ) + eventManager().fire( + Events.FOLDER_ADDED, + {"storage": destination, "path": dst_path_in_storage, "name": dst_name}, + ) + eventManager().fire(Events.UPDATED_FILES, {"type": "printables"}) + + def has_analysis(self, destination, path): + return self._storage(destination).has_analysis(path) + + def get_metadata(self, destination, path): + return self._storage(destination).get_metadata(path) + + def add_link(self, destination, path, rel, data): + self._storage(destination).add_link(path, rel, data) + + def remove_link(self, destination, path, rel, data): + self._storage(destination).remove_link(path, rel, data) + + def log_print( + self, destination, path, timestamp, print_time, success, printer_profile + ): + try: + if success: + self._storage(destination).add_history( + path, + { + "timestamp": timestamp, + "printTime": print_time, + "success": success, + "printerProfile": printer_profile, + }, + ) + else: + self._storage(destination).add_history( + path, + { + "timestamp": timestamp, + "success": success, + "printerProfile": printer_profile, + }, + ) + eventManager().fire( + Events.METADATA_STATISTICS_UPDATED, {"storage": destination, "path": path} + ) + except NoSuchStorage: + # if there's no storage configured where to log the print, we'll just not log it + pass + + def save_recovery_data(self, origin, path, pos): + import time + import yaml + from octoprint.util import atomic_write + + data = { + "origin": origin, + "path": self.path_in_storage(origin, path), + "pos": pos, + "date": time.time(), + } + 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 + ) + except Exception: + self._logger.exception( + "Could not write recovery data to file {}".format(self._recovery_file) + ) + + def delete_recovery_data(self): + if not os.path.isfile(self._recovery_file): + return + + try: + os.remove(self._recovery_file) + except Exception: + self._logger.exception( + "Error deleting recovery data file {}".format(self._recovery_file) + ) + + def get_recovery_data(self): + if not os.path.isfile(self._recovery_file): + return None + + import yaml + + try: + with io.open(self._recovery_file, "rt", encoding="utf-8") as f: + data = yaml.safe_load(f) + if not isinstance(data, dict) or not all( + map(lambda x: x in data, ("origin", "path", "pos", "date")) + ): + raise ValueError("Invalid recovery data structure") + return data + except Exception: + self._logger.exception( + "Could not read recovery data from file {}".format(self._recovery_file) + ) + self.delete_recovery_data() + + def get_additional_metadata(self, destination, path, key): + self._storage(destination).get_additional_metadata(path, key) + + def set_additional_metadata( + self, destination, path, key, data, overwrite=False, merge=False + ): + self._storage(destination).set_additional_metadata( + path, key, data, overwrite=overwrite, merge=merge + ) + + def remove_additional_metadata(self, destination, path, key): + self._storage(destination).remove_additional_metadata(path, key) + + def path_on_disk(self, destination, path): + return self._storage(destination).path_on_disk(path) + + def canonicalize(self, destination, path): + return self._storage(destination).canonicalize(path) + + def sanitize(self, destination, path): + return self._storage(destination).sanitize(path) + + def sanitize_name(self, destination, name): + return self._storage(destination).sanitize_name(name) + + def sanitize_path(self, destination, path): + return self._storage(destination).sanitize_path(path) + + def split_path(self, destination, path): + return self._storage(destination).split_path(path) + + def join_path(self, destination, *path): + return self._storage(destination).join_path(*path) + + def path_in_storage(self, destination, path): + return self._storage(destination).path_in_storage(path) + + def last_modified(self, destination, path=None, recursive=False): + return self._storage(destination).last_modified(path=path, recursive=recursive) + + def _storage(self, destination): + if not destination in self._storage_managers: + raise NoSuchStorage( + "No storage configured for destination {destination}".format(**locals()) + ) + return self._storage_managers[destination] + + def _add_analysis_result(self, destination, path, result): + if not destination in self._storage_managers: + return + + storage_manager = self._storage_managers[destination] + storage_manager.set_additional_metadata(path, "analysis", result, overwrite=True) + + def _on_analysis_finished(self, entry, result): + self._add_analysis_result(entry.location, entry.path, result) + + def _analysis_queue_entry( + self, destination, path, printer_profile=None, analysis=None + ): + if printer_profile is None: + printer_profile = self._printer_profile_manager.get_current_or_default() + + absolute_path = self._storage(destination).path_on_disk(path) + _, file_name = self._storage(destination).split_path(path) + file_type = get_file_type(absolute_path) + + if file_type: + return QueueEntry( + file_name, + path, + file_type[-1], + destination, + absolute_path, + printer_profile, + analysis, + ) + else: + return None diff --git a/src/octoprint/filemanager/analysis.py b/src/octoprint/filemanager/analysis.py index 653d37f73..86bec3477 100644 --- a/src/octoprint/filemanager/analysis.py +++ b/src/octoprint/filemanager/analysis.py @@ -2,15 +2,16 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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 logging + try: - import queue + import queue except ImportError: - import Queue as queue + import Queue as queue import os import threading import collections @@ -23,417 +24,482 @@ from octoprint.util import get_fully_qualified_classname as fqcn, dict_merge from octoprint.util.platform import CLOSE_FDS -class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile, analysis")): - """ - A :class:`QueueEntry` for processing through the :class:`AnalysisQueue`. Wraps the entry's properties necessary - for processing. +class QueueEntry( + collections.namedtuple( + "QueueEntry", + "name, path, type, location, absolute_path, printer_profile, analysis", + ) +): + """ + A :class:`QueueEntry` for processing through the :class:`AnalysisQueue`. Wraps the entry's properties necessary + for processing. - Arguments: - name (str): Name of the file to analyze. - path (str): Storage location specific path to the file to analyze. - type (str): Type of file to analyze, necessary to map to the correct :class:`AbstractAnalysisQueue` sub class. - At the moment, only ``gcode`` is supported here. - location (str): Location the file is located on. - absolute_path (str): Absolute path on disk through which to access the file. - printer_profile (PrinterProfile): :class:`PrinterProfile` which to use for analysis. - analysis (dict): :class:`GcodeAnalysisQueue` results from prior analysis, or ``None`` if there is none. - """ + Arguments: + name (str): Name of the file to analyze. + path (str): Storage location specific path to the file to analyze. + type (str): Type of file to analyze, necessary to map to the correct :class:`AbstractAnalysisQueue` sub class. + At the moment, only ``gcode`` is supported here. + location (str): Location the file is located on. + absolute_path (str): Absolute path on disk through which to access the file. + printer_profile (PrinterProfile): :class:`PrinterProfile` which to use for analysis. + analysis (dict): :class:`GcodeAnalysisQueue` results from prior analysis, or ``None`` if there is none. + """ - def __str__(self): - return "{location}:{path}".format(location=self.location, path=self.path) + def __str__(self): + return "{location}:{path}".format(location=self.location, path=self.path) class AnalysisAborted(Exception): - def __init__(self, reenqueue=True, *args, **kwargs): - Exception.__init__(self, *args, **kwargs) - self.reenqueue = reenqueue + def __init__(self, reenqueue=True, *args, **kwargs): + Exception.__init__(self, *args, **kwargs) + self.reenqueue = reenqueue class AnalysisQueue(object): - """ - OctoPrint's :class:`AnalysisQueue` can manage various :class:`AbstractAnalysisQueue` implementations, mapped - by their machine code type. + """ + OctoPrint's :class:`AnalysisQueue` can manage various :class:`AbstractAnalysisQueue` implementations, mapped + by their machine code type. - By invoking :meth:`register_finish_callback` it is possible to register oneself as a callback to be invoked each - time the analysis of a queue entry finishes. The call parameters will be the finished queue entry as the first - and the analysis result as the second parameter. It is also possible to remove the registration again by invoking - :meth:`unregister_finish_callback`. + By invoking :meth:`register_finish_callback` it is possible to register oneself as a callback to be invoked each + time the analysis of a queue entry finishes. The call parameters will be the finished queue entry as the first + and the analysis result as the second parameter. It is also possible to remove the registration again by invoking + :meth:`unregister_finish_callback`. - :meth:`enqueue` allows enqueuing :class:`QueueEntry` instances to analyze. If the :attr:`QueueEntry.type` is unknown - (no specific child class of :class:`AbstractAnalysisQueue` is registered for it), nothing will happen. Otherwise the - entry will be enqueued with the type specific analysis queue. - """ + :meth:`enqueue` allows enqueuing :class:`QueueEntry` instances to analyze. If the :attr:`QueueEntry.type` is unknown + (no specific child class of :class:`AbstractAnalysisQueue` is registered for it), nothing will happen. Otherwise the + entry will be enqueued with the type specific analysis queue. + """ - def __init__(self, queue_factories): - self._logger = logging.getLogger(__name__) - self._callbacks = [] + def __init__(self, queue_factories): + self._logger = logging.getLogger(__name__) + self._callbacks = [] - self._queues = {} - for key, queue_factory in queue_factories.items(): - self._queues[key] = queue_factory(self._analysis_finished) + self._queues = {} + for key, queue_factory in queue_factories.items(): + self._queues[key] = queue_factory(self._analysis_finished) - def register_finish_callback(self, callback): - self._callbacks.append(callback) + def register_finish_callback(self, callback): + self._callbacks.append(callback) - def unregister_finish_callback(self, callback): - self._callbacks.remove(callback) + def unregister_finish_callback(self, callback): + self._callbacks.remove(callback) - def enqueue(self, entry, high_priority=False): - if entry is None: - return False + def enqueue(self, entry, high_priority=False): + if entry is None: + return False - if not entry.type in self._queues: - return False + if not entry.type in self._queues: + return False - self._queues[entry.type].enqueue(entry, high_priority=high_priority) - return True + self._queues[entry.type].enqueue(entry, high_priority=high_priority) + return True - def dequeue(self, entry): - if entry is None: - return False + def dequeue(self, entry): + if entry is None: + return False - if not entry.type in self._queues: - return False + if not entry.type in self._queues: + return False - self._queues[entry.type].dequeue(entry.location, entry.path) + self._queues[entry.type].dequeue(entry.location, entry.path) - def dequeue_folder(self, destination, path): - for q in self._queues.values(): - q.dequeue_folder(destination, path) + def dequeue_folder(self, destination, path): + for q in self._queues.values(): + q.dequeue_folder(destination, path) - def pause(self): - for q in self._queues.values(): - q.pause() + def pause(self): + for q in self._queues.values(): + q.pause() - def resume(self): - for q in self._queues.values(): - q.resume() + def resume(self): + for q in self._queues.values(): + q.resume() + + def _analysis_finished(self, entry, result): + for callback in self._callbacks: + try: + callback(entry, result) + except: + self._logger.exception( + "Error while pushing analysis data to callback {}".format(callback), + extra={"callback": fqcn(callback)}, + ) + eventManager().fire( + Events.METADATA_ANALYSIS_FINISHED, + { + "name": entry.name, + "path": entry.path, + "origin": entry.location, + "result": result, + }, + ) - def _analysis_finished(self, entry, result): - for callback in self._callbacks: - try: - callback(entry, result) - except: - self._logger.exception(u"Error while pushing analysis data to callback {}".format(callback), - extra={"callback": fqcn(callback)}) - eventManager().fire(Events.METADATA_ANALYSIS_FINISHED, {"name": entry.name, - "path": entry.path, - "origin": entry.location, - "result": result}) class AbstractAnalysisQueue(object): - """ - The :class:`AbstractAnalysisQueue` is the parent class of all specific analysis queues such as the - :class:`GcodeAnalysisQueue`. It offers methods to enqueue new entries to analyze and pausing and resuming analysis - processing. + """ + The :class:`AbstractAnalysisQueue` is the parent class of all specific analysis queues such as the + :class:`GcodeAnalysisQueue`. It offers methods to enqueue new entries to analyze and pausing and resuming analysis + processing. - Arguments: - finished_callback (callable): Callback that will be called upon finishing analysis of an entry in the queue. - The callback will be called with the analyzed entry as the first argument and the analysis result as - returned from the queue implementation as the second parameter. + Arguments: + finished_callback (callable): Callback that will be called upon finishing analysis of an entry in the queue. + The callback will be called with the analyzed entry as the first argument and the analysis result as + returned from the queue implementation as the second parameter. - .. automethod:: _do_analysis + .. automethod:: _do_analysis - .. automethod:: _do_abort - """ + .. automethod:: _do_abort + """ - LOW_PRIO = 100 - LOW_PRIO_ABORTED = 75 - HIGH_PRIO = 50 - HIGH_PRIO_ABORTED = 0 + LOW_PRIO = 100 + LOW_PRIO_ABORTED = 75 + HIGH_PRIO = 50 + HIGH_PRIO_ABORTED = 0 - def __init__(self, finished_callback): - self._logger = logging.getLogger(__name__) + def __init__(self, finished_callback): + self._logger = logging.getLogger(__name__) - self._finished_callback = finished_callback + self._finished_callback = finished_callback - self._active = threading.Event() - self._active.set() + self._active = threading.Event() + self._active.set() - self._done = threading.Event() - self._done.clear() + self._done = threading.Event() + self._done.clear() - self._currentFile = None - self._currentProgress = None + self._currentFile = None + self._currentProgress = None - self._queue = queue.PriorityQueue() - self._current = None - self._current_highprio = False + self._queue = queue.PriorityQueue() + self._current = None + self._current_highprio = False - self._worker = threading.Thread(target=self._work) - self._worker.daemon = True - self._worker.start() + self._worker = threading.Thread(target=self._work) + self._worker.daemon = True + self._worker.start() - def enqueue(self, entry, high_priority=False): - """ - Enqueues an ``entry`` for analysis by the queue. + def enqueue(self, entry, high_priority=False): + """ + Enqueues an ``entry`` for analysis by the queue. - If ``high_priority`` is True (defaults to False), the entry will be prioritized and hence processed before - other entries in the queue with normal priority. + If ``high_priority`` is True (defaults to False), the entry will be prioritized and hence processed before + other entries in the queue with normal priority. - Arguments: - entry (QueueEntry): The :class:`QueueEntry` to analyze. - high_priority (boolean): Whether to process the provided entry with high priority (True) or not - (False, default) - """ + Arguments: + entry (QueueEntry): The :class:`QueueEntry` to analyze. + high_priority (boolean): Whether to process the provided entry with high priority (True) or not + (False, default) + """ - if settings().get(["gcodeAnalysis", "runAt"]) == "never": - self._logger.debug("Ignoring entry {entry} for analysis queue".format(entry=entry)) - return - elif high_priority: - self._logger.debug("Adding entry {entry} to analysis queue with high priority".format(entry=entry)) - prio = self.__class__.HIGH_PRIO - else: - self._logger.debug("Adding entry {entry} to analysis queue with low priority".format(entry=entry)) - prio = self.__class__.LOW_PRIO + if settings().get(["gcodeAnalysis", "runAt"]) == "never": + self._logger.debug( + "Ignoring entry {entry} for analysis queue".format(entry=entry) + ) + return + elif high_priority: + self._logger.debug( + "Adding entry {entry} to analysis queue with high priority".format( + entry=entry + ) + ) + prio = self.__class__.HIGH_PRIO + else: + self._logger.debug( + "Adding entry {entry} to analysis queue with low priority".format( + entry=entry + ) + ) + prio = self.__class__.LOW_PRIO - self._queue.put((prio, entry, high_priority)) - if high_priority and self._current is not None and not self._current_highprio: - self._logger.debug("Aborting current analysis in favor of high priority one") - self._do_abort() + self._queue.put((prio, entry, high_priority)) + if high_priority and self._current is not None and not self._current_highprio: + self._logger.debug("Aborting current analysis in favor of high priority one") + self._do_abort() - def dequeue(self, location, path): - if self._current is not None and self._current.location == location \ - and self._current.path == path: - self._do_abort(reenqueue=False) - self._done.wait() - self._done.clear() + def dequeue(self, location, path): + if ( + self._current is not None + and self._current.location == location + and self._current.path == path + ): + self._do_abort(reenqueue=False) + self._done.wait() + self._done.clear() - def dequeue_folder(self, location, path): - if self._current is not None and self._current.location == location \ - and self._current.path.startswith(path + "/"): - self._do_abort(reenqueue=False) - self._done.wait() - self._done.clear() + def dequeue_folder(self, location, path): + if ( + self._current is not None + and self._current.location == location + and self._current.path.startswith(path + "/") + ): + self._do_abort(reenqueue=False) + self._done.wait() + self._done.clear() - def pause(self): - """ - Pauses processing of the queue, e.g. when a print is active. - """ + def pause(self): + """ + Pauses processing of the queue, e.g. when a print is active. + """ - self._logger.debug("Pausing analysis") - self._active.clear() - if self._current is not None: - self._logger.debug("Aborting running analysis, will restart when analyzer is resumed") - self._do_abort() + self._logger.debug("Pausing analysis") + self._active.clear() + if self._current is not None: + self._logger.debug( + "Aborting running analysis, will restart when analyzer is resumed" + ) + self._do_abort() - def resume(self): - """ - Resumes processing of the queue, e.g. when a print has finished. - """ + def resume(self): + """ + Resumes processing of the queue, e.g. when a print has finished. + """ - self._logger.debug("Resuming analyzer") - self._active.set() + self._logger.debug("Resuming analyzer") + self._active.set() - def _work(self): - while True: - (priority, entry, high_priority) = self._queue.get() - self._logger.debug("Processing entry {} from queue (priority {})".format(entry, priority)) - self._active.wait() + def _work(self): + while True: + (priority, entry, high_priority) = self._queue.get() + self._logger.debug( + "Processing entry {} from queue (priority {})".format(entry, priority) + ) + self._active.wait() - try: - self._analyze(entry, high_priority=high_priority) - self._queue.task_done() - self._done.set() - except AnalysisAborted as ex: - if ex.reenqueue: - self._queue.put((self.__class__.HIGH_PRIO_ABORTED if high_priority else self.__class__.LOW_PRIO_ABORTED, - entry, - high_priority)) - self._logger.debug("Running analysis of entry {} aborted".format(entry)) - self._queue.task_done() - self._done.set() - else: - time.sleep(1.0) + try: + self._analyze(entry, high_priority=high_priority) + self._queue.task_done() + self._done.set() + except AnalysisAborted as ex: + if ex.reenqueue: + self._queue.put( + ( + self.__class__.HIGH_PRIO_ABORTED + if high_priority + else self.__class__.LOW_PRIO_ABORTED, + entry, + high_priority, + ) + ) + self._logger.debug("Running analysis of entry {} aborted".format(entry)) + self._queue.task_done() + self._done.set() + else: + time.sleep(1.0) - def _analyze(self, entry, high_priority=False): - path = entry.absolute_path - if path is None or not os.path.exists(path): - return + def _analyze(self, entry, high_priority=False): + path = entry.absolute_path + if path is None or not os.path.exists(path): + return - self._current = entry - self._current_highprio = high_priority - self._current_progress = 0 + self._current = entry + self._current_highprio = high_priority + self._current_progress = 0 - try: - start_time = monotonic_time() - self._logger.info("Starting analysis of {}".format(entry)) - eventManager().fire(Events.METADATA_ANALYSIS_STARTED, {"name": entry.name, - "path": entry.path, - "origin": entry.location, - "type": entry.type}) - try: - result = self._do_analysis(high_priority=high_priority) - except TypeError: - result = self._do_analysis() - self._logger.info("Analysis of entry {} finished, needed {:.2f}s".format(entry, monotonic_time() - start_time)) - self._finished_callback(self._current, result) - finally: - self._current = None - self._current_progress = None + try: + start_time = monotonic_time() + self._logger.info("Starting analysis of {}".format(entry)) + eventManager().fire( + Events.METADATA_ANALYSIS_STARTED, + { + "name": entry.name, + "path": entry.path, + "origin": entry.location, + "type": entry.type, + }, + ) + try: + result = self._do_analysis(high_priority=high_priority) + except TypeError: + result = self._do_analysis() + self._logger.info( + "Analysis of entry {} finished, needed {:.2f}s".format( + entry, monotonic_time() - start_time + ) + ) + self._finished_callback(self._current, result) + finally: + self._current = None + self._current_progress = None - def _do_analysis(self, high_priority=False): - """ - Performs the actual analysis of the current entry which can be accessed via ``self._current``. Needs to be - overridden by sub classes. + def _do_analysis(self, high_priority=False): + """ + Performs the actual analysis of the current entry which can be accessed via ``self._current``. Needs to be + overridden by sub classes. - Arguments: - high_priority (bool): Whether the current entry has high priority or not. + Arguments: + high_priority (bool): Whether the current entry has high priority or not. - Returns: - object: The result of the analysis which will be forwarded to the ``finished_callback`` provided during - construction. - """ - return None + Returns: + object: The result of the analysis which will be forwarded to the ``finished_callback`` provided during + construction. + """ + return None - def _do_abort(self, reenqueue=True): - """ - Aborts analysis of the current entry. Needs to be overridden by sub classes. - """ - pass + def _do_abort(self, reenqueue=True): + """ + Aborts analysis of the current entry. Needs to be overridden by sub classes. + """ + pass class GcodeAnalysisQueue(AbstractAnalysisQueue): - """ - A queue to analyze GCODE files. Analysis results are :class:`dict` instances structured as follows: + """ + A queue to analyze GCODE files. Analysis results are :class:`dict` instances structured as follows: - .. list-table:: - :widths: 25 70 + .. list-table:: + :widths: 25 70 - - * **Key** - * **Description** - - * ``estimatedPrintTime`` - * Estimated time the file take to print, in seconds - - * ``filament`` - * Substructure describing estimated filament usage. Keys are ``tool0`` for the first extruder, ``tool1`` for - the second and so on. For each tool extruded length and volume (based on diameter) are provided. - - * ``filament.toolX.length`` - * The extruded length in mm - - * ``filament.toolX.volume`` - * The extruded volume in cm³ - - * ``printingArea`` - * Bounding box of the printed object in the print volume (minimum and maximum coordinates) - - * ``printingArea.minX`` - * Minimum X coordinate of the printed object - - * ``printingArea.maxX`` - * Maximum X coordinate of the printed object - - * ``printingArea.minY`` - * Minimum Y coordinate of the printed object - - * ``printingArea.maxY`` - * Maximum Y coordinate of the printed object - - * ``printingArea.minZ`` - * Minimum Z coordinate of the printed object - - * ``printingArea.maxZ`` - * Maximum Z coordinate of the printed object - - * ``dimensions`` - * Dimensions of the printed object in X, Y, Z - - * ``dimensions.width`` - * Width of the printed model along the X axis, in mm - - * ``dimensions.depth`` - * Depth of the printed model along the Y axis, in mm - - * ``dimensions.height`` - * Height of the printed model along the Z axis, in mm - """ + - * **Key** + * **Description** + - * ``estimatedPrintTime`` + * Estimated time the file take to print, in seconds + - * ``filament`` + * Substructure describing estimated filament usage. Keys are ``tool0`` for the first extruder, ``tool1`` for + the second and so on. For each tool extruded length and volume (based on diameter) are provided. + - * ``filament.toolX.length`` + * The extruded length in mm + - * ``filament.toolX.volume`` + * The extruded volume in cm³ + - * ``printingArea`` + * Bounding box of the printed object in the print volume (minimum and maximum coordinates) + - * ``printingArea.minX`` + * Minimum X coordinate of the printed object + - * ``printingArea.maxX`` + * Maximum X coordinate of the printed object + - * ``printingArea.minY`` + * Minimum Y coordinate of the printed object + - * ``printingArea.maxY`` + * Maximum Y coordinate of the printed object + - * ``printingArea.minZ`` + * Minimum Z coordinate of the printed object + - * ``printingArea.maxZ`` + * Maximum Z coordinate of the printed object + - * ``dimensions`` + * Dimensions of the printed object in X, Y, Z + - * ``dimensions.width`` + * Width of the printed model along the X axis, in mm + - * ``dimensions.depth`` + * Depth of the printed model along the Y axis, in mm + - * ``dimensions.height`` + * Height of the printed model along the Z axis, in mm + """ - def __init__(self, finished_callback): - AbstractAnalysisQueue.__init__(self, finished_callback) + def __init__(self, finished_callback): + AbstractAnalysisQueue.__init__(self, finished_callback) - self._aborted = False - self._reenqueue = False + self._aborted = False + self._reenqueue = False - def _do_analysis(self, high_priority=False): - import sarge - import sys - import yaml + def _do_analysis(self, high_priority=False): + import sarge + import sys + import yaml - if self._current.analysis and all(map(lambda x: x in self._current.analysis, ("printingArea", - "dimensions", - "estimatedPrintTime", - "filament"))): - return self._current.analysis + if self._current.analysis and all( + map( + lambda x: x in self._current.analysis, + ("printingArea", "dimensions", "estimatedPrintTime", "filament"), + ) + ): + return self._current.analysis - try: - throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority \ - else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"]) - throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"]) - max_extruders = settings().getInt(["gcodeAnalysis", "maxExtruders"]) - g90_extruder = settings().getBoolean(["feature", "g90InfluencesExtruder"]) - speedx = self._current.printer_profile["axes"]["x"]["speed"] - speedy = self._current.printer_profile["axes"]["y"]["speed"] - offsets = self._current.printer_profile["extruder"]["offsets"] + try: + throttle = ( + settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) + if high_priority + else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"]) + ) + throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"]) + max_extruders = settings().getInt(["gcodeAnalysis", "maxExtruders"]) + g90_extruder = settings().getBoolean(["feature", "g90InfluencesExtruder"]) + speedx = self._current.printer_profile["axes"]["x"]["speed"] + speedy = self._current.printer_profile["axes"]["y"]["speed"] + offsets = self._current.printer_profile["extruder"]["offsets"] - command = [sys.executable, "-m", "octoprint", "analysis", "gcode", - "--speed-x={}".format(speedx), "--speed-y={}".format(speedy), - "--max-t={}".format(max_extruders), "--throttle={}".format(throttle), - "--throttle-lines={}".format(throttle_lines)] - for offset in offsets[1:]: - command += ["--offset", str(offset[0]), str(offset[1])] - if g90_extruder: - command += ["--g90-extruder"] - command.append(self._current.absolute_path) + command = [ + sys.executable, + "-m", + "octoprint", + "analysis", + "gcode", + "--speed-x={}".format(speedx), + "--speed-y={}".format(speedy), + "--max-t={}".format(max_extruders), + "--throttle={}".format(throttle), + "--throttle-lines={}".format(throttle_lines), + ] + for offset in offsets[1:]: + command += ["--offset", str(offset[0]), str(offset[1])] + if g90_extruder: + command += ["--g90-extruder"] + command.append(self._current.absolute_path) - self._logger.info("Invoking analysis command: {}".format(" ".join(command))) + self._logger.info("Invoking analysis command: {}".format(" ".join(command))) - self._aborted = False - p = sarge.run(command, close_fds=CLOSE_FDS, async_=True, stdout=sarge.Capture()) + self._aborted = False + p = sarge.run( + command, close_fds=CLOSE_FDS, async_=True, stdout=sarge.Capture() + ) - while len(p.commands) == 0: - # somewhat ugly... we can't use wait_events because - # the events might not be all set if an exception - # by sarge is triggered within the async process - # thread - time.sleep(0.01) + while len(p.commands) == 0: + # somewhat ugly... we can't use wait_events because + # the events might not be all set if an exception + # by sarge is triggered within the async process + # thread + time.sleep(0.01) - # by now we should have a command, let's wait for its - # process to have been prepared - p.commands[0].process_ready.wait() + # by now we should have a command, let's wait for its + # process to have been prepared + p.commands[0].process_ready.wait() - if not p.commands[0].process: - # the process might have been set to None in case of any exception - raise RuntimeError("Error while trying to run command {}".format(" ".join(command))) + if not p.commands[0].process: + # the process might have been set to None in case of any exception + raise RuntimeError( + "Error while trying to run command {}".format(" ".join(command)) + ) - try: - # let's wait for stuff to finish - while p.returncode is None: - if self._aborted: - # oh, we shall abort, let's do so! - p.commands[0].terminate() - raise AnalysisAborted(reenqueue=self._reenqueue) + try: + # let's wait for stuff to finish + while p.returncode is None: + if self._aborted: + # oh, we shall abort, let's do so! + p.commands[0].terminate() + raise AnalysisAborted(reenqueue=self._reenqueue) - # else continue - p.commands[0].poll() - finally: - p.close() + # else continue + p.commands[0].poll() + finally: + p.close() - output = p.stdout.text - self._logger.debug("Got output: {!r}".format(output)) + output = p.stdout.text + self._logger.debug("Got output: {!r}".format(output)) - if not "RESULTS:" in output: - raise RuntimeError("No analysis result found") + if not "RESULTS:" in output: + raise RuntimeError("No analysis result found") - _, output = output.split("RESULTS:") - analysis = yaml.safe_load(output) + _, output = output.split("RESULTS:") + analysis = yaml.safe_load(output) - result = {} - result["printingArea"] = analysis["printing_area"] - result["dimensions"] = analysis["dimensions"] - if analysis["total_time"]: - result["estimatedPrintTime"] = analysis["total_time"] * 60 - if analysis["extrusion_length"]: - result["filament"] = {} - for i in range(len(analysis["extrusion_length"])): - result["filament"]["tool%d" % i] = { - "length": analysis["extrusion_length"][i], - "volume": analysis["extrusion_volume"][i] - } + result = {} + result["printingArea"] = analysis["printing_area"] + result["dimensions"] = analysis["dimensions"] + if analysis["total_time"]: + result["estimatedPrintTime"] = analysis["total_time"] * 60 + if analysis["extrusion_length"]: + result["filament"] = {} + for i in range(len(analysis["extrusion_length"])): + result["filament"]["tool%d" % i] = { + "length": analysis["extrusion_length"][i], + "volume": analysis["extrusion_volume"][i], + } - if self._current.analysis and isinstance(self._current.analysis, dict): - return dict_merge(result, self._current.analysis) - else: - return result - finally: - self._gcode = None + if self._current.analysis and isinstance(self._current.analysis, dict): + return dict_merge(result, self._current.analysis) + else: + return result + finally: + self._gcode = None - def _do_abort(self, reenqueue=True): - self._aborted = True - self._reenqueue = reenqueue + def _do_abort(self, reenqueue=True): + self._aborted = True + self._reenqueue = reenqueue diff --git a/src/octoprint/filemanager/destinations.py b/src/octoprint/filemanager/destinations.py index 1659a01eb..da0e93cf9 100644 --- a/src/octoprint/filemanager/destinations.py +++ b/src/octoprint/filemanager/destinations.py @@ -1,9 +1,10 @@ # -*- 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" + class FileDestinations(object): - SDCARD = "sdcard" - LOCAL = "local" + SDCARD = "sdcard" + LOCAL = "local" diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index 0e3290d9d..bcb9a38b5 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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 io @@ -14,9 +14,9 @@ import pylru import copy try: - from os import scandir, walk + from os import scandir, walk except ImportError: - from scandir import scandir, walk + from scandir import scandir, walk from octoprint.util import atomic_write, time_this from contextlib import contextmanager @@ -30,1685 +30,1975 @@ import octoprint.filemanager from octoprint.util import is_hidden_path, to_unicode, to_bytes + class StorageInterface(object): - """ - Interface of storage adapters for OctoPrint. - """ - - @property - def analysis_backlog(self): - """ - Get an iterator over all items stored in the storage that need to be analysed by the :class:`~octoprint.filemanager.AnalysisQueue`. - - The yielded elements are expected as storage specific absolute paths to the respective files. Don't forget - to recurse into folders if your storage adapter supports those. - - :return: an iterator yielding all un-analysed files in the storage - """ - # empty generator pattern, yield is intentionally unreachable - return - yield - - def analysis_backlog_for_path(self, path=None): - # empty generator pattern, yield is intentionally unreachable - return - yield - - def last_modified(self, path=None, recursive=False): - """ - Get the last modification date of the specified ``path`` or ``path``'s subtree. - - Args: - path (str or None): Path for which to determine the subtree's last modification date. If left out or - set to None, defatuls to storage root. - recursive (bool): Whether to determine only the date of the specified ``path`` (False, default) or - the whole ``path``'s subtree (True). - - Returns: (float) The last modification date of the indicated subtree - """ - raise NotImplementedError() - - def file_in_path(self, path, filepath): - """ - Returns whether the file indicated by ``file`` is inside ``path`` or not. - :param string path: the path to check - :param string filepath: path to the file - :return: ``True`` if the file is inside the path, ``False`` otherwise - """ - return NotImplementedError() - - def file_exists(self, path): - """ - Returns whether the file indicated by ``path`` exists or not. - :param string path: the path to check for existence - :return: ``True`` if the file exists, ``False`` otherwise - """ - raise NotImplementedError() - - def folder_exists(self, path): - """ - Returns whether the folder indicated by ``path`` exists or not. - :param string path: the path to check for existence - :return: ``True`` if the folder exists, ``False`` otherwise - """ - raise NotImplementedError() - - def list_files(self, path=None, filter=None, recursive=True, force_refresh=False): - """ - List all files in storage starting at ``path``. If ``recursive`` is set to True (the default), also dives into - subfolders. - - An optional filter function can be supplied which will be called with a file name and file data and which has - to return True if the file is to be included in the result or False if not. - - The data structure of the returned result will be a dictionary mapping from file names to entry data. File nodes - will contain their metadata here, folder nodes will contain their contained files and folders. Example:: - - { - "some_folder": { - "name": "some_folder", - "path": "some_folder", - "type": "folder", - "children": { - "some_sub_folder": { - "name": "some_sub_folder", - "path": "some_folder/some_sub_folder", - "type": "folder", - "typePath": ["folder"], - "children": { ... } - }, - "some_file.gcode": { - "name": "some_file.gcode", - "path": "some_folder/some_file.gcode", - "type": "machinecode", - "typePath": ["machinecode", "gcode"], - "hash": "", - "links": [ ... ], - ... - }, - ... - } - "test.gcode": { - "name": "test.gcode", - "path": "test.gcode", - "type": "machinecode", - "typePath": ["machinecode", "gcode"], - "hash": "", - "links": [...], - ... - }, - "test.stl": { - "name": "test.stl", - "path": "test.stl", - "type": "model", - "typePath": ["model", "stl"], - "hash": "", - "links": [...], - ... - }, - ... - } - - :param string path: base path from which to recursively list all files, optional, if not supplied listing will start - from root of base folder - :param function filter: a filter that matches the files that are to be returned, may be left out in which case no - filtering will take place - :param bool recursive: will also step into sub folders for building the complete list if set to True, otherwise will only - do one step down into sub folders to be able to populate the ``children``. - :return: a dictionary mapping entry names to entry data that represents the whole file list - """ - raise NotImplementedError() - - def add_folder(self, path, ignore_existing=True, display=None): - """ - Adds a folder as ``path`` - - The ``path`` will be sanitized. - - :param string path: the path of the new folder - :param bool ignore_existing: if set to True, no error will be raised if the folder to be added already exists - :param unicode display: display name of the folder - :return: the sanitized name of the new folder to be used for future references to the folder - """ - raise NotImplementedError() - - def remove_folder(self, path, recursive=True): - """ - Removes the folder at ``path`` - - :param string path: the path of the folder to remove - :param bool recursive: if set to True, contained folders and files will also be removed, otherwise an error will - be raised if the folder is not empty (apart from any metadata files) when it's to be removed - """ - raise NotImplementedError() - - def copy_folder(self, source, destination): - """ - Copies the folder ``source`` to ``destination`` - - :param string source: path to the source folder - :param string destination: path to destination - - :return: the path in the storage to the copy of the folder - """ - raise NotImplementedError() - - def move_folder(self, source, destination): - """ - Moves the folder ``source`` to ``destination`` - - :param string source: path to the source folder - :param string destination: path to destination - - :return: the new path in the storage to the folder - """ - raise NotImplementedError() - - def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False, display=None): - """ - Adds the file ``file_object`` as ``path`` - - :param string path: the file's new path, will be sanitized - :param object file_object: a file object that provides a ``save`` method which will be called with the destination path - where the object should then store its contents - :param object printer_profile: the printer profile associated with this file (if any) - :param list links: any links to add with the file - :param bool allow_overwrite: if set to True no error will be raised if the file already exists and the existing file - and its metadata will just be silently overwritten - :param unicode display: display name of the file - :return: the sanitized name of the file to be used for future references to it - """ - raise NotImplementedError() - - def remove_file(self, path): - """ - Removes the file at ``path`` - - Will also take care of deleting the corresponding entries - in the metadata and deleting all links pointing to the file. - - :param string path: path of the file to remove - """ - raise NotImplementedError() - - def copy_file(self, source, destination): - """ - Copies the file ``source`` to ``destination`` - - :param string source: path to the source file - :param string destination: path to destination - - :return: the path in the storage to the copy of the file - """ - raise NotImplementedError() - - def move_file(self, source, destination): - """ - Moves the file ``source`` to ``destination`` - - :param string source: path to the source file - :param string destination: path to destination - - :return: the new path in the storage to the file - """ - raise NotImplementedError() - - def has_analysis(self, path): - """ - Returns whether the file at path has been analysed yet - - :param path: virtual path to the file for which to retrieve the metadata - """ - raise NotImplementedError() - - def get_metadata(self, path): - """ - Retrieves the metadata for the file ``path``. - - :param path: virtual path to the file for which to retrieve the metadata - :return: the metadata associated with the file - """ - raise NotImplementedError() - - def add_link(self, path, rel, data): - """ - Adds a link of relation ``rel`` to file ``path`` with the given ``data``. - - The following relation types are currently supported: - - * ``model``: adds a link to a model from which the file was created/sliced, expected additional data is the ``name`` - and optionally the ``hash`` of the file to link to. If the link can be resolved against another file on the - current ``path``, not only will it be added to the links of ``name`` but a reverse link of type ``machinecode`` - referring to ``name`` and its hash will also be added to the linked ``model`` file - * ``machinecode``: adds a link to a file containing machine code created from the current file (model), expected - additional data is the ``name`` and optionally the ``hash`` of the file to link to. If the link can be resolved - against another file on the current ``path``, not only will it be added to the links of ``name`` but a reverse - link of type ``model`` referring to ``name`` and its hash will also be added to the linked ``model`` file. - * ``web``: adds a location on the web associated with this file (e.g. a website where to download a model), - expected additional data is a ``href`` attribute holding the website's URL and optionally a ``retrieved`` - attribute describing when the content was retrieved - - Note that adding ``model`` links to files identifying as models or ``machinecode`` links to files identifying - as machine code will be refused. - - :param path: path of the file for which to add a link - :param rel: type of relation of the link to add (currently ``model``, ``machinecode`` and ``web`` are supported) - :param data: additional data of the link to add - """ - raise NotImplementedError() - - def remove_link(self, path, rel, data): - """ - Removes the link consisting of ``rel`` and ``data`` from file ``name`` on ``path``. - - :param path: path of the file from which to remove the link - :param rel: type of relation of the link to remove (currently ``model``, ``machinecode`` and ``web`` are supported) - :param data: additional data of the link to remove, must match existing link - """ - raise NotImplementedError() - - def get_additional_metadata(self, path, key): - """ - Fetches additional metadata at ``key`` from the metadata of ``path``. - - :param path: the virtual path to the file for which to fetch additional metadata - :param key: key of metadata to fetch - """ - raise NotImplementedError() - - def set_additional_metadata(self, path, key, data, overwrite=False, merge=False): - """ - Adds additional metadata to the metadata of ``path``. Metadata in ``data`` will be saved under ``key``. - - If ``overwrite`` is set and ``key`` already exists in ``name``'s metadata, the current value will be overwritten. - - If ``merge`` is set and ``key`` already exists and both ``data`` and the existing data under ``key`` are dictionaries, - the two dictionaries will be merged recursively. - - :param path: the virtual path to the file for which to add additional metadata - :param key: key of metadata to add - :param data: metadata to add - :param overwrite: if True and ``key`` already exists, it will be overwritten - :param merge: if True and ``key`` already exists and both ``data`` and the existing data are dictionaries, they - will be merged - """ - raise NotImplementedError() - - def remove_additional_metadata(self, path, key): - """ - Removes additional metadata under ``key`` for ``name`` on ``path`` - - :param path: the virtual path to the file for which to remove the metadata under ``key`` - :param key: the key to remove - """ - raise NotImplementedError() - - def canonicalize(self, path): - """ - Canonicalizes the given ``path``. The ``path`` may consist of both folder and file name, the underlying - implementation must separate those if necessary. - - By default, this calls :func:`~octoprint.filemanager.StorageInterface.sanitize`, which also takes care - of stripping any invalid characters. - - Args: - path: the path to canonicalize - - Returns: - a 2-tuple containing the canonicalized path and file name - - """ - return self.sanitize(path) - - def sanitize(self, path): - """ - Sanitizes the given ``path``, stripping it of all invalid characters. The ``path`` may consist of both - folder and file name, the underlying implementation must separate those if necessary and sanitize individually. - - :param string path: the path to sanitize - :return: a 2-tuple containing the sanitized path and file name - """ - raise NotImplementedError() - - def sanitize_path(self, path): - """ - Sanitizes the given folder-only ``path``, stripping it of all invalid characters. - :param string path: the path to sanitize - :return: the sanitized path - """ - raise NotImplementedError() - - def sanitize_name(self, name): - """ - Sanitizes the given file ``name``, stripping it of all invalid characters. - :param string name: the file name to sanitize - :return: the sanitized name - """ - raise NotImplementedError() - - def split_path(self, path): - """ - Split ``path`` into base directory and file name. - :param path: the path to split - :return: a tuple (base directory, file name) - """ - raise NotImplementedError() - - def join_path(self, *path): - """ - Join path elements together - :param path: path elements to join - :return: joined representation of the path to be usable as fully qualified path for further operations - """ - raise NotImplementedError() - - def path_on_disk(self, path): - """ - Retrieves the path on disk for ``path``. - - Note: if the storage is not on disk and there exists no path on disk to refer to it, this method should - raise an :class:`io.UnsupportedOperation` - - Opposite of :func:`path_in_storage`. - - :param string path: the virtual path for which to retrieve the path on disk - :return: the path on disk to ``path`` - """ - raise NotImplementedError() - - def path_in_storage(self, path): - """ - Retrieves the equivalent in the storage adapter for ``path``. - - Opposite of :func:`path_on_disk`. - - :param string path: the path for which to retrieve the storage path - :return: the path in storage to ``path`` - """ - raise NotImplementedError() + """ + Interface of storage adapters for OctoPrint. + """ + + @property + def analysis_backlog(self): + """ + Get an iterator over all items stored in the storage that need to be analysed by the :class:`~octoprint.filemanager.AnalysisQueue`. + + The yielded elements are expected as storage specific absolute paths to the respective files. Don't forget + to recurse into folders if your storage adapter supports those. + + :return: an iterator yielding all un-analysed files in the storage + """ + # empty generator pattern, yield is intentionally unreachable + return + yield + + def analysis_backlog_for_path(self, path=None): + # empty generator pattern, yield is intentionally unreachable + return + yield + + def last_modified(self, path=None, recursive=False): + """ + Get the last modification date of the specified ``path`` or ``path``'s subtree. + + Args: + path (str or None): Path for which to determine the subtree's last modification date. If left out or + set to None, defatuls to storage root. + recursive (bool): Whether to determine only the date of the specified ``path`` (False, default) or + the whole ``path``'s subtree (True). + + Returns: (float) The last modification date of the indicated subtree + """ + raise NotImplementedError() + + def file_in_path(self, path, filepath): + """ + Returns whether the file indicated by ``file`` is inside ``path`` or not. + :param string path: the path to check + :param string filepath: path to the file + :return: ``True`` if the file is inside the path, ``False`` otherwise + """ + return NotImplementedError() + + def file_exists(self, path): + """ + Returns whether the file indicated by ``path`` exists or not. + :param string path: the path to check for existence + :return: ``True`` if the file exists, ``False`` otherwise + """ + raise NotImplementedError() + + def folder_exists(self, path): + """ + Returns whether the folder indicated by ``path`` exists or not. + :param string path: the path to check for existence + :return: ``True`` if the folder exists, ``False`` otherwise + """ + raise NotImplementedError() + + def list_files(self, path=None, filter=None, recursive=True, force_refresh=False): + """ + List all files in storage starting at ``path``. If ``recursive`` is set to True (the default), also dives into + subfolders. + + An optional filter function can be supplied which will be called with a file name and file data and which has + to return True if the file is to be included in the result or False if not. + + The data structure of the returned result will be a dictionary mapping from file names to entry data. File nodes + will contain their metadata here, folder nodes will contain their contained files and folders. Example:: + + { + "some_folder": { + "name": "some_folder", + "path": "some_folder", + "type": "folder", + "children": { + "some_sub_folder": { + "name": "some_sub_folder", + "path": "some_folder/some_sub_folder", + "type": "folder", + "typePath": ["folder"], + "children": { ... } + }, + "some_file.gcode": { + "name": "some_file.gcode", + "path": "some_folder/some_file.gcode", + "type": "machinecode", + "typePath": ["machinecode", "gcode"], + "hash": "", + "links": [ ... ], + ... + }, + ... + } + "test.gcode": { + "name": "test.gcode", + "path": "test.gcode", + "type": "machinecode", + "typePath": ["machinecode", "gcode"], + "hash": "", + "links": [...], + ... + }, + "test.stl": { + "name": "test.stl", + "path": "test.stl", + "type": "model", + "typePath": ["model", "stl"], + "hash": "", + "links": [...], + ... + }, + ... + } + + :param string path: base path from which to recursively list all files, optional, if not supplied listing will start + from root of base folder + :param function filter: a filter that matches the files that are to be returned, may be left out in which case no + filtering will take place + :param bool recursive: will also step into sub folders for building the complete list if set to True, otherwise will only + do one step down into sub folders to be able to populate the ``children``. + :return: a dictionary mapping entry names to entry data that represents the whole file list + """ + raise NotImplementedError() + + def add_folder(self, path, ignore_existing=True, display=None): + """ + Adds a folder as ``path`` + + The ``path`` will be sanitized. + + :param string path: the path of the new folder + :param bool ignore_existing: if set to True, no error will be raised if the folder to be added already exists + :param unicode display: display name of the folder + :return: the sanitized name of the new folder to be used for future references to the folder + """ + raise NotImplementedError() + + def remove_folder(self, path, recursive=True): + """ + Removes the folder at ``path`` + + :param string path: the path of the folder to remove + :param bool recursive: if set to True, contained folders and files will also be removed, otherwise an error will + be raised if the folder is not empty (apart from any metadata files) when it's to be removed + """ + raise NotImplementedError() + + def copy_folder(self, source, destination): + """ + Copies the folder ``source`` to ``destination`` + + :param string source: path to the source folder + :param string destination: path to destination + + :return: the path in the storage to the copy of the folder + """ + raise NotImplementedError() + + def move_folder(self, source, destination): + """ + Moves the folder ``source`` to ``destination`` + + :param string source: path to the source folder + :param string destination: path to destination + + :return: the new path in the storage to the folder + """ + raise NotImplementedError() + + def add_file( + self, + path, + file_object, + printer_profile=None, + links=None, + allow_overwrite=False, + display=None, + ): + """ + Adds the file ``file_object`` as ``path`` + + :param string path: the file's new path, will be sanitized + :param object file_object: a file object that provides a ``save`` method which will be called with the destination path + where the object should then store its contents + :param object printer_profile: the printer profile associated with this file (if any) + :param list links: any links to add with the file + :param bool allow_overwrite: if set to True no error will be raised if the file already exists and the existing file + and its metadata will just be silently overwritten + :param unicode display: display name of the file + :return: the sanitized name of the file to be used for future references to it + """ + raise NotImplementedError() + + def remove_file(self, path): + """ + Removes the file at ``path`` + + Will also take care of deleting the corresponding entries + in the metadata and deleting all links pointing to the file. + + :param string path: path of the file to remove + """ + raise NotImplementedError() + + def copy_file(self, source, destination): + """ + Copies the file ``source`` to ``destination`` + + :param string source: path to the source file + :param string destination: path to destination + + :return: the path in the storage to the copy of the file + """ + raise NotImplementedError() + + def move_file(self, source, destination): + """ + Moves the file ``source`` to ``destination`` + + :param string source: path to the source file + :param string destination: path to destination + + :return: the new path in the storage to the file + """ + raise NotImplementedError() + + def has_analysis(self, path): + """ + Returns whether the file at path has been analysed yet + + :param path: virtual path to the file for which to retrieve the metadata + """ + raise NotImplementedError() + + def get_metadata(self, path): + """ + Retrieves the metadata for the file ``path``. + + :param path: virtual path to the file for which to retrieve the metadata + :return: the metadata associated with the file + """ + raise NotImplementedError() + + def add_link(self, path, rel, data): + """ + Adds a link of relation ``rel`` to file ``path`` with the given ``data``. + + The following relation types are currently supported: + + * ``model``: adds a link to a model from which the file was created/sliced, expected additional data is the ``name`` + and optionally the ``hash`` of the file to link to. If the link can be resolved against another file on the + current ``path``, not only will it be added to the links of ``name`` but a reverse link of type ``machinecode`` + referring to ``name`` and its hash will also be added to the linked ``model`` file + * ``machinecode``: adds a link to a file containing machine code created from the current file (model), expected + additional data is the ``name`` and optionally the ``hash`` of the file to link to. If the link can be resolved + against another file on the current ``path``, not only will it be added to the links of ``name`` but a reverse + link of type ``model`` referring to ``name`` and its hash will also be added to the linked ``model`` file. + * ``web``: adds a location on the web associated with this file (e.g. a website where to download a model), + expected additional data is a ``href`` attribute holding the website's URL and optionally a ``retrieved`` + attribute describing when the content was retrieved + + Note that adding ``model`` links to files identifying as models or ``machinecode`` links to files identifying + as machine code will be refused. + + :param path: path of the file for which to add a link + :param rel: type of relation of the link to add (currently ``model``, ``machinecode`` and ``web`` are supported) + :param data: additional data of the link to add + """ + raise NotImplementedError() + + def remove_link(self, path, rel, data): + """ + Removes the link consisting of ``rel`` and ``data`` from file ``name`` on ``path``. + + :param path: path of the file from which to remove the link + :param rel: type of relation of the link to remove (currently ``model``, ``machinecode`` and ``web`` are supported) + :param data: additional data of the link to remove, must match existing link + """ + raise NotImplementedError() + + def get_additional_metadata(self, path, key): + """ + Fetches additional metadata at ``key`` from the metadata of ``path``. + + :param path: the virtual path to the file for which to fetch additional metadata + :param key: key of metadata to fetch + """ + raise NotImplementedError() + + def set_additional_metadata(self, path, key, data, overwrite=False, merge=False): + """ + Adds additional metadata to the metadata of ``path``. Metadata in ``data`` will be saved under ``key``. + + If ``overwrite`` is set and ``key`` already exists in ``name``'s metadata, the current value will be overwritten. + + If ``merge`` is set and ``key`` already exists and both ``data`` and the existing data under ``key`` are dictionaries, + the two dictionaries will be merged recursively. + + :param path: the virtual path to the file for which to add additional metadata + :param key: key of metadata to add + :param data: metadata to add + :param overwrite: if True and ``key`` already exists, it will be overwritten + :param merge: if True and ``key`` already exists and both ``data`` and the existing data are dictionaries, they + will be merged + """ + raise NotImplementedError() + + def remove_additional_metadata(self, path, key): + """ + Removes additional metadata under ``key`` for ``name`` on ``path`` + + :param path: the virtual path to the file for which to remove the metadata under ``key`` + :param key: the key to remove + """ + raise NotImplementedError() + + def canonicalize(self, path): + """ + Canonicalizes the given ``path``. The ``path`` may consist of both folder and file name, the underlying + implementation must separate those if necessary. + + By default, this calls :func:`~octoprint.filemanager.StorageInterface.sanitize`, which also takes care + of stripping any invalid characters. + + Args: + path: the path to canonicalize + + Returns: + a 2-tuple containing the canonicalized path and file name + + """ + return self.sanitize(path) + + def sanitize(self, path): + """ + Sanitizes the given ``path``, stripping it of all invalid characters. The ``path`` may consist of both + folder and file name, the underlying implementation must separate those if necessary and sanitize individually. + + :param string path: the path to sanitize + :return: a 2-tuple containing the sanitized path and file name + """ + raise NotImplementedError() + + def sanitize_path(self, path): + """ + Sanitizes the given folder-only ``path``, stripping it of all invalid characters. + :param string path: the path to sanitize + :return: the sanitized path + """ + raise NotImplementedError() + + def sanitize_name(self, name): + """ + Sanitizes the given file ``name``, stripping it of all invalid characters. + :param string name: the file name to sanitize + :return: the sanitized name + """ + raise NotImplementedError() + + def split_path(self, path): + """ + Split ``path`` into base directory and file name. + :param path: the path to split + :return: a tuple (base directory, file name) + """ + raise NotImplementedError() + + def join_path(self, *path): + """ + Join path elements together + :param path: path elements to join + :return: joined representation of the path to be usable as fully qualified path for further operations + """ + raise NotImplementedError() + + def path_on_disk(self, path): + """ + Retrieves the path on disk for ``path``. + + Note: if the storage is not on disk and there exists no path on disk to refer to it, this method should + raise an :class:`io.UnsupportedOperation` + + Opposite of :func:`path_in_storage`. + + :param string path: the virtual path for which to retrieve the path on disk + :return: the path on disk to ``path`` + """ + raise NotImplementedError() + + def path_in_storage(self, path): + """ + Retrieves the equivalent in the storage adapter for ``path``. + + Opposite of :func:`path_on_disk`. + + :param string path: the path for which to retrieve the storage path + :return: the path in storage to ``path`` + """ + raise NotImplementedError() class StorageError(Exception): - UNKNOWN = "unknown" - INVALID_DIRECTORY = "invalid_directory" - INVALID_FILE = "invalid_file" - INVALID_SOURCE = "invalid_source" - INVALID_DESTINATION = "invalid_destination" - DOES_NOT_EXIST = "does_not_exist" - ALREADY_EXISTS = "already_exists" - SOURCE_EQUALS_DESTINATION = "source_equals_destination" - NOT_EMPTY = "not_empty" + UNKNOWN = "unknown" + INVALID_DIRECTORY = "invalid_directory" + INVALID_FILE = "invalid_file" + INVALID_SOURCE = "invalid_source" + INVALID_DESTINATION = "invalid_destination" + DOES_NOT_EXIST = "does_not_exist" + ALREADY_EXISTS = "already_exists" + SOURCE_EQUALS_DESTINATION = "source_equals_destination" + NOT_EMPTY = "not_empty" - def __init__(self, message, code=None, cause=None): - BaseException.__init__(self) - self.message = message - self.cause = cause + def __init__(self, message, code=None, cause=None): + BaseException.__init__(self) + self.message = message + self.cause = cause - if code is None: - code = StorageError.UNKNOWN - self.code = code + if code is None: + code = StorageError.UNKNOWN + self.code = code class LocalFileStorage(StorageInterface): - """ - The ``LocalFileStorage`` is a storage implementation which holds all files, folders and metadata on disk. - - Metadata is managed inside ``.metadata.json`` files in the respective folders, indexed by the sanitized filenames - stored within the folder. Metadata access is managed through an LRU cache to minimize access overhead. - - This storage type implements :func:`path_on_disk`. - """ - - _UNICODE_VARIATIONS = re.compile("[\uFE00-\uFE0F]", re.U) - - @classmethod - def _no_unicode_variations(cls, text): - return cls._UNICODE_VARIATIONS.sub("", text) - - _SLUGIFY = Slugify() - _SLUGIFY.safe_chars = "-_.()[] " - - @classmethod - def _slugify(cls, text): - text = to_unicode(text) - text = cls._no_unicode_variations(text) - text = demojize(text, delimiters=("", "")) - return cls._SLUGIFY(text) - - def __init__(self, basefolder, create=False): - """ - Initializes a ``LocalFileStorage`` instance under the given ``basefolder``, creating the necessary folder - if necessary and ``create`` is set to ``True``. - - :param string basefolder: the path to the folder under which to create the storage - :param bool create: ``True`` if the folder should be created if it doesn't exist yet, ``False`` otherwise - """ - self._logger = logging.getLogger(__name__) - - self.basefolder = os.path.realpath(os.path.abspath(to_unicode(basefolder))) - if not os.path.exists(self.basefolder) and create: - os.makedirs(self.basefolder) - if not os.path.exists(self.basefolder) or not os.path.isdir(self.basefolder): - raise StorageError("{basefolder} is not a valid directory".format(**locals()), code=StorageError.INVALID_DIRECTORY) - - import threading - self._metadata_lock_mutex = threading.RLock() - self._metadata_locks = {} - self._persisted_metadata_lock_mutex = threading.RLock() - self._persisted_metadata_locks = {} - - self._metadata_cache = pylru.lrucache(100) - self._filelist_cache = {} - self._filelist_cache_mutex = threading.RLock() - - self._old_metadata = None - self._initialize_metadata() - - def _initialize_metadata(self): - self._logger.info("Initializing the file metadata for {}...".format(self.basefolder)) - - old_metadata_path = os.path.join(self.basefolder, "metadata.yaml") - backup_path = os.path.join(self.basefolder, "metadata.yaml.backup") - - if os.path.exists(old_metadata_path): - # load the old metadata file - try: - with io.open(old_metadata_path, 'rt', encoding='utf-8') as f: - import yaml - self._old_metadata = yaml.safe_load(f) - except Exception: - self._logger.exception("Error while loading old metadata file") - - # make sure the metadata is initialized as far as possible - self._list_folder(self.basefolder) - - # rename the old metadata file - self._old_metadata = None - try: - import shutil - shutil.move(old_metadata_path, backup_path) - except Exception: - self._logger.exception("Could not rename old metadata.yaml file") - - else: - # make sure the metadata is initialized as far as possible - self._list_folder(self.basefolder) - - self._logger.info("... file metadata for {} initialized successfully.".format(self.basefolder)) - - @property - def analysis_backlog(self): - return self.analysis_backlog_for_path() - - def analysis_backlog_for_path(self, path=None): - if path: - path = self.sanitize_path(path) - - for entry in self._analysis_backlog_generator(path): - yield entry - - def _analysis_backlog_generator(self, path=None): - if path is None: - path = self.basefolder - - metadata = self._get_metadata(path) - if not metadata: - metadata = {} - for entry in scandir(path): - if is_hidden_path(entry.name): - continue - - if entry.is_file() and octoprint.filemanager.valid_file_type(entry.name): - if not entry.name in metadata or not isinstance(metadata[entry.name], dict) or not "analysis" in metadata[entry.name]: - printer_profile_rels = self.get_link(entry.path, "printerprofile") - if printer_profile_rels: - printer_profile_id = printer_profile_rels[0]["id"] - else: - printer_profile_id = None - - yield entry.name, entry.path, printer_profile_id - elif os.path.isdir(entry.path): - for sub_entry in self._analysis_backlog_generator(entry.path): - yield self.join_path(entry.name, sub_entry[0]), sub_entry[1], sub_entry[2] - - def last_modified(self, path=None, recursive=False): - if path is None: - path = self.basefolder - else: - path = os.path.join(self.basefolder, path) - - def last_modified_for_path(p): - metadata = os.path.join(p, ".metadata.json") - if os.path.exists(metadata): - return max(os.stat(p).st_mtime, os.stat(metadata).st_mtime) - else: - return os.stat(p).st_mtime - - if recursive: - return max(last_modified_for_path(root) for root, _, _ in walk(path)) - else: - return last_modified_for_path(path) - - def file_in_path(self, path, filepath): - filepath = self.sanitize_path(filepath) - path = self.sanitize_path(path) - - return filepath == path or filepath.startswith(path + os.sep) - - def file_exists(self, path): - path, name = self.sanitize(path) - file_path = os.path.join(path, name) - return os.path.exists(file_path) and os.path.isfile(file_path) - - def folder_exists(self, path): - path, name = self.sanitize(path) - folder_path = os.path.join(path, name) - return os.path.exists(folder_path) and os.path.isdir(folder_path) - - def list_files(self, path=None, filter=None, recursive=True, force_refresh=False): - if path: - path = self.sanitize_path(to_unicode(path)) - base = self.path_in_storage(path) - if base: - base += "/" - else: - path = self.basefolder - base = "" - - def strip_children(nodes): - result = {} - for key, node in nodes.items(): - if node["type"] == "folder": - node = copy.copy(node) - node["children"] = [] - result[key] = node - return result - - def apply_filter(nodes, filter_func): - result = {} - for key, node in nodes.items(): - if filter_func(node) or node["type"] == "folder": - if node["type"] == "folder": - node = copy.copy(node) - node["children"] = apply_filter(node.get("children", []), filter_func) - result[key] = node - return result - - result = self._list_folder(path, base=base, force_refresh=force_refresh) - if not recursive: - result = strip_children(result) - if callable(filter): - result = apply_filter(result, filter) - return result - - def add_folder(self, path, ignore_existing=True, display=None): - display_path, display_name = self.canonicalize(path) - path = self.sanitize_path(display_path) - name = self.sanitize_name(display_name) - - if display is not None: - display_name = display - - folder_path = os.path.join(path, name) - if os.path.exists(folder_path): - if not ignore_existing: - raise StorageError("{name} does already exist in {path}".format(**locals()), code=StorageError.ALREADY_EXISTS) - else: - os.mkdir(folder_path) - - if display_name != name: - metadata = self._get_metadata_entry(path, name, default={}) - metadata["display"] = display_name - self._update_metadata_entry(path, name, metadata) - - return self.path_in_storage((path, name)) - - def remove_folder(self, path, recursive=True): - path, name = self.sanitize(path) - - folder_path = os.path.join(path, name) - if not os.path.exists(folder_path): - return - - empty = True - for entry in scandir(folder_path): - if entry.name == ".metadata.json" or entry.name == ".metadata.yaml": - continue - empty = False - break - - if not empty and not recursive: - raise StorageError("{name} in {path} is not empty".format(**locals()), code=StorageError.NOT_EMPTY) - - import shutil - shutil.rmtree(folder_path) - - self._remove_metadata_entry(path, name) - - def _get_source_destination_data(self, source, destination, must_not_equal=False): - """Prepares data dicts about source and destination for copy/move.""" - source_path, source_name = self.sanitize(source) - - destination_canon_path, destination_canon_name = self.canonicalize(destination) - destination_path = self.sanitize_path(destination_canon_path) - destination_name = self.sanitize_name(destination_canon_name) - - source_fullpath = os.path.join(source_path, source_name) - destination_fullpath = os.path.join(destination_path, destination_name) - - if not os.path.exists(source_fullpath): - raise StorageError("{} in {} does not exist".format(source_name, source_path), code=StorageError.INVALID_SOURCE) - - if not os.path.isdir(destination_path): - raise StorageError("Destination path {} does not exist or is not a folder".format(destination_path), code=StorageError.INVALID_DESTINATION) - if os.path.exists(destination_fullpath) and source_fullpath != destination_fullpath: - raise StorageError("{} does already exist in {}".format(destination_name, destination_path), code=StorageError.INVALID_DESTINATION) - - source_meta = self._get_metadata_entry(source_path, source_name) - if source_meta: - source_display = source_meta.get("display", source_name) - else: - source_display = source_name - - if (must_not_equal or source_display == destination_canon_name) and source_fullpath == destination_fullpath: - raise StorageError("Source {} and destination {} are the same folder".format(source_path, destination_path), code=StorageError.SOURCE_EQUALS_DESTINATION) - - source_data = {"path": source_path, - "name": source_name, - "display": source_display, - "fullpath": source_fullpath} - destination_data = {"path": destination_path, - "name": destination_name, - "display": destination_canon_name, - "fullpath": destination_fullpath} - return source_data, destination_data - - def _set_display_metadata(self, destination_data, source_data=None): - if source_data and destination_data["name"] == source_data["name"] and source_data["name"] != source_data["display"]: - display = source_data["display"] - elif destination_data["name"] != destination_data["display"]: - display = destination_data["display"] - else: - display = None - - destination_meta = self._get_metadata_entry(destination_data["path"], destination_data["name"], - default={}) - if display: - destination_meta["display"] = display - self._update_metadata_entry(destination_data["path"], destination_data["name"], destination_meta) - elif "display" in destination_meta: - del destination_meta["display"] - self._update_metadata_entry(destination_data["path"], destination_data["name"], destination_meta) - - def copy_folder(self, source, destination): - source_data, destination_data = self._get_source_destination_data(source, destination, must_not_equal=True) - - try: - shutil.copytree(source_data["fullpath"], destination_data["fullpath"]) - except Exception as e: - raise StorageError("Could not copy %s in %s to %s in %s" % (source_data["name"], source_data["path"], destination_data["name"], destination_data["path"]), cause=e) - - self._set_display_metadata(destination_data, source_data=source_data) - - return self.path_in_storage(destination_data["fullpath"]) - - def move_folder(self, source, destination): - source_data, destination_data = self._get_source_destination_data(source, destination) - - # only a display rename? Update that and bail early - if source_data["fullpath"] == destination_data["fullpath"]: - self._set_display_metadata(destination_data) - return self.path_in_storage(destination_data["fullpath"]) - - try: - shutil.move(source_data["fullpath"], destination_data["fullpath"]) - except Exception as e: - raise StorageError("Could not move %s in %s to %s in %s" % (source_data["name"], source_data["path"], destination_data["name"], destination_data["path"]), cause=e) - - self._set_display_metadata(destination_data, source_data=source_data) - self._remove_metadata_entry(source_data["path"], source_data["name"]) - self._delete_metadata(source_data["fullpath"]) - - return self.path_in_storage(destination_data["fullpath"]) - - def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False, display=None): - display_path, display_name = self.canonicalize(path) - path = self.sanitize_path(display_path) - name = self.sanitize_name(display_name) - - if display: - display_name = display - - if not octoprint.filemanager.valid_file_type(name): - raise StorageError("{name} is an unrecognized file type".format(**locals()), code=StorageError.INVALID_FILE) - - file_path = os.path.join(path, name) - if os.path.exists(file_path) and not os.path.isfile(file_path): - raise StorageError("{name} does already exist in {path} and is not a file".format(**locals()), code=StorageError.ALREADY_EXISTS) - if os.path.exists(file_path) and not allow_overwrite: - raise StorageError("{name} does already exist in {path} and overwriting is prohibited".format(**locals()), code=StorageError.ALREADY_EXISTS) - - # make sure folders exist - if not os.path.exists(path): - # TODO persist display names of path segments! - os.makedirs(path) - - # save the file - file_object.save(file_path) - - # save the file's hash to the metadata of the folder - file_hash = self._create_hash(file_path) - metadata = self._get_metadata_entry(path, name, default={}) - metadata_dirty = False - if not "hash" in metadata or metadata["hash"] != file_hash: - # hash changed -> throw away old metadata - metadata = {"hash": file_hash} - metadata_dirty = True - - if not "display" in metadata and display_name != name: - # display name is not the same as file name -> store in metadata - metadata["display"] = display_name - metadata_dirty = True - - if metadata_dirty: - self._update_metadata_entry(path, name, metadata) - - # process any links that were also provided for adding to the file - if not links: - links = [] - - if printer_profile is not None: - links.append(("printerprofile", - {"id": printer_profile["id"], - "name": printer_profile["name"]})) + """ + The ``LocalFileStorage`` is a storage implementation which holds all files, folders and metadata on disk. + + Metadata is managed inside ``.metadata.json`` files in the respective folders, indexed by the sanitized filenames + stored within the folder. Metadata access is managed through an LRU cache to minimize access overhead. + + This storage type implements :func:`path_on_disk`. + """ + + _UNICODE_VARIATIONS = re.compile("[\uFE00-\uFE0F]", re.U) - self._add_links(name, path, links) - - # touch the file to set last access and modification time to now - os.utime(file_path, None) - - return self.path_in_storage((path, name)) - - def remove_file(self, path): - path, name = self.sanitize(path) - - file_path = os.path.join(path, name) - if not os.path.exists(file_path): - return - if not os.path.isfile(file_path): - raise StorageError("{name} in {path} is not a file".format(**locals()), code=StorageError.INVALID_FILE) - - try: - os.remove(file_path) - except Exception as e: - raise StorageError("Could not delete {name} in {path}".format(**locals()), cause=e) - - self._remove_metadata_entry(path, name) - - def copy_file(self, source, destination): - source_data, destination_data = self._get_source_destination_data(source, destination, must_not_equal=True) - - try: - shutil.copy2(source_data["fullpath"], destination_data["fullpath"]) - except Exception as e: - raise StorageError("Could not copy %s in %s to %s in %s" % (source_data["name"], source_data["path"], destination_data["name"], destination_data["path"]), cause=e) - - self._copy_metadata_entry(source_data["path"], source_data["name"], - destination_data["path"], destination_data["name"]) - self._set_display_metadata(destination_data, source_data=source_data) - - return self.path_in_storage(destination_data["fullpath"]) - - def move_file(self, source, destination, allow_overwrite=False): - source_data, destination_data = self._get_source_destination_data(source, destination) - - # only a display rename? Update that and bail early - if source_data["fullpath"] == destination_data["fullpath"]: - self._set_display_metadata(destination_data) - return self.path_in_storage(destination_data["fullpath"]) - - try: - shutil.move(source_data["fullpath"], destination_data["fullpath"]) - except Exception as e: - raise StorageError("Could not move %s in %s to %s in %s" % (source_data["name"], source_data["path"], destination_data["name"], destination_data["path"]), cause=e) - - self._copy_metadata_entry(source_data["path"], source_data["name"], - destination_data["path"], destination_data["name"], - delete_source=True) - self._set_display_metadata(destination_data, source_data=source_data) - - return self.path_in_storage(destination_data["fullpath"]) - - def has_analysis(self, path): - metadata = self.get_metadata(path) - return "analysis" in metadata - - def get_metadata(self, path): - path, name = self.sanitize(path) - return self._get_metadata_entry(path, name) - - def get_link(self, path, rel): - path, name = self.sanitize(path) - return self._get_links(name, path, rel) - - def add_link(self, path, rel, data): - path, name = self.sanitize(path) - self._add_links(name, path, [(rel, data)]) - - def remove_link(self, path, rel, data): - path, name = self.sanitize(path) - self._remove_links(name, path, [(rel, data)]) - - def add_history(self, path, data): - path, name = self.sanitize(path) - self._add_history(name, path, data) - - def update_history(self, path, index, data): - path, name = self.sanitize(path) - self._update_history(name, path, index, data) - - def remove_history(self, path, index): - path, name = self.sanitize(path) - self._delete_history(name, path, index) - - def get_additional_metadata(self, path, key): - path, name = self.sanitize(path) - metadata = self._get_metadata(path) - - if not name in metadata: - return - - return metadata[name].get(key) - - def set_additional_metadata(self, path, key, data, overwrite=False, merge=False): - path, name = self.sanitize(path) - metadata = self._get_metadata(path) - metadata_dirty = False - - if not name in metadata: - return - - metadata = self._copied_metadata(metadata, name) - - if not key in metadata[name] or overwrite: - metadata[name][key] = data - metadata_dirty = True - elif key in metadata[name] and isinstance(metadata[name][key], dict) and isinstance(data, dict) and merge: - import octoprint.util - metadata[name][key] = octoprint.util.dict_merge(metadata[name][key], data, in_place=True) - metadata_dirty = True - - if metadata_dirty: - self._save_metadata(path, metadata) - - def remove_additional_metadata(self, path, key): - path, name = self.sanitize(path) - metadata = self._get_metadata(path) - - if not name in metadata: - return - - if not key in metadata[name]: - return - - metadata = self._copied_metadata(metadata, name) - del metadata[name][key] - self._save_metadata(path, metadata) - - def split_path(self, path): - path = to_unicode(path) - split = path.split("/") - if len(split) == 1: - return "", split[0] - else: - return self.join_path(*split[:-1]), split[-1] - - def join_path(self, *path): - return "/".join(map(to_unicode, path)) - - def sanitize(self, path): - """ - Returns a ``(path, name)`` tuple derived from the provided ``path``. - - ``path`` may be: - * a storage path - * an absolute file system path - * a tuple or list containing all individual path elements - * a string representation of the path - * with or without a file name - - Note that for a ``path`` without a trailing slash the last part will be considered a file name and - hence be returned at second position. If you only need to convert a folder path, be sure to - include a trailing slash for a string ``path`` or an empty last element for a list ``path``. - """ - - path, name = self.canonicalize(path) - name = self.sanitize_name(name) - path = self.sanitize_path(path) - return path, name - - def canonicalize(self, path): - name = None - if isinstance(path, basestring): - path = to_unicode(path) - if path.startswith(self.basefolder): - path = path[len(self.basefolder):] - path = path.replace(os.path.sep, "/") - path = path.split("/") - if isinstance(path, (list, tuple)): - if len(path) == 1: - name = to_unicode(path[0]) - path = "" - else: - name = to_unicode(path[-1]) - path = self.join_path(*map(to_unicode, path[:-1])) - if not path: - path = "" - - return path, name - - def sanitize_name(self, name): - """ - Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\\``. Otherwise - slugifies the given ``name`` by converting it to ASCII, leaving ``-``, ``_``, ``.``, - ``(``, and ``)`` as is. - """ - name = to_unicode(name) - - if name is None: - return None - - if "/" in name or "\\" in name: - raise ValueError("name must not contain / or \\") - - result = self._slugify(name).replace(" ", "_") - if result and result != "." and result != ".." and result[0] == ".": - # hidden files under *nix - result = result[1:] - return result - - def sanitize_path(self, path): - """ - Ensures that the on disk representation of ``path`` is located under the configured basefolder. Resolves all - relative path elements (e.g. ``..``) and sanitizes folder names using :func:`sanitize_name`. Final path is the - absolute path including leading ``basefolder`` path. - """ - path = to_unicode(path) - - if len(path): - if path[0] == "/": - path = path[1:] - elif path[0] == "." and path[1] == "/": - path = path[2:] - - path_elements = path.split("/") - joined_path = self.basefolder - for path_element in path_elements: - joined_path = os.path.join(joined_path, self.sanitize_name(path_element)) - path = os.path.realpath(joined_path) - if not path.startswith(self.basefolder): - raise ValueError("path not contained in base folder: {path}".format(**locals())) - return path - - def _sanitize_entry(self, entry, path, entry_path): - entry = to_unicode(entry) - sanitized = self.sanitize_name(entry) - if sanitized != entry: - # entry is not sanitized yet, let's take care of that - sanitized_path = os.path.join(path, sanitized) - sanitized_name, sanitized_ext = os.path.splitext(sanitized) - - counter = 1 - while os.path.exists(sanitized_path): - counter += 1 - sanitized = self.sanitize_name("{}_({}){}".format(sanitized_name, counter, sanitized_ext)) - sanitized_path = os.path.join(path, sanitized) - - try: - shutil.move(entry_path, sanitized_path) - - self._logger.info("Sanitized \"{}\" to \"{}\"".format(entry_path, sanitized_path)) - return sanitized, sanitized_path - except Exception: - self._logger.exception("Error while trying to rename \"{}\" to \"{}\", ignoring file".format(entry_path, sanitized_path)) - raise - - return entry, entry_path - - def path_in_storage(self, path): - if isinstance(path, (tuple, list)): - path = self.join_path(*path) - if isinstance(path, basestring): - path = to_unicode(path) - if path.startswith(self.basefolder): - path = path[len(self.basefolder):] - path = path.replace(os.path.sep, "/") - if path.startswith("/"): - path = path[1:] - - return path - - def path_on_disk(self, path): - path, name = self.sanitize(path) - return os.path.join(path, name) - - ##~~ internals - - def _add_history(self, name, path, data): - metadata = self._copied_metadata(self._get_metadata(path), name) - - if not "hash" in metadata[name]: - metadata[name]["hash"] = self._create_hash(os.path.join(path, name)) - - if not "history" in metadata[name]: - metadata[name]["history"] = [] - - metadata[name]["history"].append(data) - self._calculate_stats_from_history(name, path, metadata=metadata, save=False) - self._save_metadata(path, metadata) - - def _update_history(self, name, path, index, data): - metadata = self._get_metadata(path) - - if not name in metadata or not "history" in metadata[name]: - return - - metadata = self._copied_metadata(metadata, name) - - try: - metadata[name]["history"][index].update(data) - self._calculate_stats_from_history(name, path, metadata=metadata, save=False) - self._save_metadata(path, metadata) - except IndexError: - pass - - def _delete_history(self, name, path, index): - metadata = self._get_metadata(path) - - if not name in metadata or not "history" in metadata[name]: - return - - metadata = self._copied_metadata(metadata, name) - - try: - del metadata[name]["history"][index] - self._calculate_stats_from_history(name, path, metadata=metadata, save=False) - self._save_metadata(path, metadata) - except IndexError: - pass - - def _calculate_stats_from_history(self, name, path, metadata=None, save=True): - if metadata is None: - metadata = self._copied_metadata(self._get_metadata(path), name) - - if not "history" in metadata[name]: - return - - # collect data from history - former_print_times = {} - last_print = {} - - - for history_entry in metadata[name]["history"]: - if not "printTime" in history_entry or not "success" in history_entry or not history_entry["success"] or not "printerProfile" in history_entry: - continue - - printer_profile = history_entry["printerProfile"] - if not printer_profile: - continue - - print_time = history_entry["printTime"] - try: - print_time = float(print_time) - except Exception: - self._logger.warning("Invalid print time value found in print history for {} in {}/.metadata.json: {!r}".format(name, path, print_time)) - continue - - if not printer_profile in former_print_times: - former_print_times[printer_profile] = [] - former_print_times[printer_profile].append(print_time) - - if not printer_profile in last_print or last_print[printer_profile] is None or ("timestamp" in history_entry and history_entry["timestamp"] > last_print[printer_profile]["timestamp"]): - last_print[printer_profile] = history_entry - - # calculate stats - statistics = {"averagePrintTime": {}, "lastPrintTime": {}} - - for printer_profile in former_print_times: - if not former_print_times[printer_profile]: - continue - statistics["averagePrintTime"][printer_profile] = sum(former_print_times[printer_profile]) / float(len(former_print_times[printer_profile])) - - for printer_profile in last_print: - if not last_print[printer_profile]: - continue - statistics["lastPrintTime"][printer_profile] = last_print[printer_profile]["printTime"] - - metadata[name]["statistics"] = statistics - - if save: - self._save_metadata(path, metadata) - - def _get_links(self, name, path, searched_rel): - metadata = self._get_metadata(path) - result = [] - - if not name in metadata: - return result - - if not "links" in metadata[name]: - return result - - for data in metadata[name]["links"]: - if not "rel" in data or not data["rel"] == searched_rel: - continue - result.append(data) - return result - - def _add_links(self, name, path, links): - file_type = octoprint.filemanager.get_file_type(name) - if file_type: - file_type = file_type[0] - - metadata = self._copied_metadata(self._get_metadata(path), name) - metadata_dirty = False - - if not "hash" in metadata[name]: - metadata[name]["hash"] = self._create_hash(os.path.join(path, name)) - - if not "links" in metadata[name]: - metadata[name]["links"] = [] - - for rel, data in links: - if (rel == "model" or rel == "machinecode") and "name" in data: - if file_type == "model" and rel == "model": - # adding a model link to a model doesn't make sense - return - elif file_type == "machinecode" and rel == "machinecode": - # adding a machinecode link to a machinecode doesn't make sense - return - - ref_path = os.path.join(path, data["name"]) - if not os.path.exists(ref_path): - # file doesn't exist, we won't create the link - continue - - # fetch hash of target file - if data["name"] in metadata and "hash" in metadata[data["name"]]: - hash = metadata[data["name"]]["hash"] - else: - hash = self._create_hash(ref_path) - if not data["name"] in metadata: - metadata[data["name"]] = {"hash": hash, - "links": []} - else: - metadata[data["name"]]["hash"] = hash - - if "hash" in data and not data["hash"] == hash: - # file doesn't have the correct hash, we won't create the link - continue - - if not "links" in metadata[data["name"]]: - metadata[data["name"]]["links"] = [] - - # add reverse link to link target file - metadata[data["name"]]["links"].append({"rel": "machinecode" if rel == "model" else "model", - "name": name, - "hash": metadata[name]["hash"]}) - metadata_dirty = True - - link_dict = {"rel": rel, - "name": data["name"], - "hash": hash} - - elif rel == "web" and "href" in data: - link_dict = {"rel": rel, - "href": data["href"]} - if "retrieved" in data: - link_dict["retrieved"] = data["retrieved"] - - else: - continue - - if link_dict: - metadata[name]["links"].append(link_dict) - metadata_dirty = True - - if metadata_dirty: - self._save_metadata(path, metadata) - - def _remove_links(self, name, path, links): - metadata = self._copied_metadata(self._get_metadata(path), name) - metadata_dirty = False - - hash = metadata[name].get("hash", self._create_hash(os.path.join(path, name))) - - for rel, data in links: - if (rel == "model" or rel == "machinecode") and "name" in data: - if data["name"] in metadata and "links" in metadata[data["name"]]: - ref_rel = "model" if rel == "machinecode" else "machinecode" - for link in metadata[data["name"]]["links"]: - if link["rel"] == ref_rel and "name" in link and link["name"] == name and "hash" in link and link["hash"] == hash: - metadata[data["name"]] = copy.deepcopy(metadata[data["name"]]) - metadata[data["name"]]["links"].remove(link) - metadata_dirty = True - - if "links" in metadata[name]: - for link in metadata[name]["links"]: - if not link["rel"] == rel: - continue - - matches = True - for k, v in data.items(): - if not k in link or not link[k] == v: - matches = False - break - - if not matches: - continue - - metadata[name]["links"].remove(link) - metadata_dirty = True - - if metadata_dirty: - self._save_metadata(path, metadata) - - @time_this(logtarget=__name__ + ".timings", message="{func}({func_args},{func_kwargs}) took {timing:.2f}ms", incl_func_args=True) - def _list_folder(self, path, base="", force_refresh=False, **kwargs): - def get_size(nodes): - total_size = 0 - for node in nodes.values(): - if "size" in node: - total_size += node["size"] - return total_size - - def enrich_folders(nodes): - nodes = copy.copy(nodes) - for key, value in nodes.items(): - if value["type"] == "folder": - value = copy.copy(value) - value["children"] = self._list_folder(os.path.join(path, key), - base=value["path"] + "/", - force_refresh=force_refresh) - value["size"] = get_size(value["children"]) - nodes[key] = value - return nodes - - metadata_dirty = False - try: - with self._filelist_cache_mutex: - cache = self._filelist_cache.get(path) - if not force_refresh and cache and cache[0] >= self.last_modified(path, recursive=True): - return enrich_folders(cache[1]) - - metadata = self._get_metadata(path) - if not metadata: - metadata = {} - - result = {} - - for entry in scandir(path): - if is_hidden_path(entry.name): - # no hidden files and folders - continue - - try: - entry_name = entry_display = entry.name - entry_path = entry.path - entry_is_file = entry.is_file() - entry_is_dir = entry.is_dir() - entry_stat = entry.stat() - except Exception: - # error while trying to fetch file metadata, that might be thanks to file already having - # been moved or deleted - ignore it and continue - continue - - try: - new_entry_name, new_entry_path = self._sanitize_entry(entry_name, path, entry_path) - if entry_name != new_entry_name or entry_path != new_entry_path: - entry_display = to_unicode(entry_name) - entry_name = new_entry_name - entry_path = new_entry_path - entry_stat = os.stat(entry_path) - except Exception: - # error while trying to rename the file, we'll continue here and ignore it - continue - - path_in_location = entry_name if not base else base + entry_name - - try: - # file handling - if entry_is_file: - type_path = octoprint.filemanager.get_file_type(entry_name) - if not type_path: - # only supported extensions - continue - else: - file_type = type_path[0] - - if entry_name in metadata and isinstance(metadata[entry_name], dict): - entry_metadata = metadata[entry_name] - if not "display" in entry_metadata and entry_display != entry_name: - if not metadata_dirty: - metadata = self._copied_metadata(metadata, entry_name) - metadata[entry_name]["display"] = entry_display - entry_metadata["display"] = entry_display - metadata_dirty = True - else: - if not metadata_dirty: - metadata = self._copied_metadata(metadata, entry_name) - entry_metadata = self._add_basic_metadata(path, entry_name, - display_name=entry_display, - save=False, - metadata=metadata) - metadata_dirty = True - - extended_entry_data = {} - extended_entry_data.update(entry_metadata) - extended_entry_data["name"] = entry_name - extended_entry_data["display"] = entry_metadata.get("display", entry_name) - extended_entry_data["path"] = path_in_location - extended_entry_data["type"] = file_type - extended_entry_data["typePath"] = type_path - stat = entry_stat - if stat: - extended_entry_data["size"] = stat.st_size - extended_entry_data["date"] = int(stat.st_mtime) - - result[entry_name] = extended_entry_data - - # folder recursion - elif entry_is_dir: - if entry_name in metadata and isinstance(metadata[entry_name], dict): - entry_metadata = metadata[entry_name] - if not "display" in entry_metadata and entry_display != entry_name: - if not metadata_dirty: - metadata = self._copied_metadata(metadata, entry_name) - metadata[entry_name]["display"] = entry_display - entry_metadata["display"] = entry_display - metadata_dirty = True - elif entry_name != entry_display: - if not metadata_dirty: - metadata = self._copied_metadata(metadata, entry_name) - entry_metadata = self._add_basic_metadata(path, entry_name, - display_name=entry_display, - save=False, - metadata=metadata) - metadata_dirty = True - else: - entry_metadata = {} - - entry_data = {"name": entry_name, - "display": entry_metadata.get("display", entry_name), - "path": path_in_location, - "type": "folder", - "typePath": ["folder"]} - - result[entry_name] = entry_data - except Exception: - # So something went wrong somewhere while processing this file entry - log that and continue - self._logger.exception("Error while processing entry {}".format(entry_path)) - continue - - self._filelist_cache[path] = (self.last_modified(path, recursive=True), - result) - return enrich_folders(result) - finally: - # save metadata - if metadata_dirty: - self._save_metadata(path, metadata) - - def _add_basic_metadata(self, path, entry, display_name=None, additional_metadata=None, save=True, metadata=None): - if additional_metadata is None: - additional_metadata = {} - - if metadata is None: - metadata = self._get_metadata(path) - - entry_path = os.path.join(path, entry) - - if os.path.isfile(entry_path): - entry_data = {"hash": self._create_hash(os.path.join(path, entry)), - "links": [], - "notes": []} - if path == self.basefolder and self._old_metadata is not None and entry in self._old_metadata and "gcodeAnalysis" in self._old_metadata[entry]: - # if there is still old metadata available and that contains an analysis for this file, use it! - entry_data["analysis"] = self._old_metadata[entry]["gcodeAnalysis"] - - elif os.path.isdir(entry_path): - entry_data = {} - - else: - return - - if display_name is not None and not display_name == entry: - entry_data["display"] = display_name - - entry_data.update(additional_metadata) - - metadata = copy.copy(metadata) - metadata[entry] = entry_data - - if save: - self._save_metadata(path, metadata) - - return entry_data - - def _create_hash(self, path): - import hashlib - - blocksize = 65536 - hash = hashlib.sha1() - with io.open(path, 'rb') as f: - buffer = f.read(blocksize) - while len(buffer) > 0: - hash.update(buffer) - buffer = f.read(blocksize) - - return hash.hexdigest() - - def _get_metadata_entry(self, path, name, default=None): - with self._get_metadata_lock(path): - metadata = self._get_metadata(path) - return metadata.get(name, default) - - def _remove_metadata_entry(self, path, name): - with self._get_metadata_lock(path): - metadata = self._get_metadata(path) - if not name in metadata: - return - - metadata = copy.copy(metadata) - - if "hash" in metadata[name]: - hash = metadata[name]["hash"] - for m in metadata.values(): - if not "links" in m: - continue - links_hash = lambda link: "hash" in link and link["hash"] == hash and "rel" in link and (link["rel"] == "model" or link["rel"] == "machinecode") - m["links"] = [link for link in m["links"] if not links_hash(link)] - - del metadata[name] - self._save_metadata(path, metadata) - - def _update_metadata_entry(self, path, name, data): - with self._get_metadata_lock(path): - metadata = copy.copy(self._get_metadata(path)) - metadata[name] = data - self._save_metadata(path, metadata) - - def _copy_metadata_entry(self, source_path, source_name, destination_path, destination_name, delete_source=False, updates=None): - with self._get_metadata_lock(source_path): - source_data = self._get_metadata_entry(source_path, source_name, default={}) - if not source_data: - return - - if delete_source: - self._remove_metadata_entry(source_path, source_name) - - if updates is not None: - source_data.update(updates) - - with self._get_metadata_lock(destination_path): - self._update_metadata_entry(destination_path, destination_name, source_data) - - def _get_metadata(self, path, force=False): - import json - - if not force: - metadata = self._metadata_cache.get(path) - if metadata: - return metadata - - self._migrate_metadata(path) - - metadata_path = os.path.join(path, ".metadata.json") - - metadata = None - with self._get_persisted_metadata_lock(path): - if os.path.exists(metadata_path): - with io.open(metadata_path, 'rt', encoding='utf-8') as f: - try: - metadata = json.load(f) - except Exception: - self._logger.exception("Error while reading .metadata.json from {path}".format(**locals())) - - def valid_json(value): - try: - json.dumps(value, allow_nan=False) - return True - except: - return False - - if isinstance(metadata, dict): - old_size = len(metadata) - metadata = { k: v for k, v in metadata.items() if valid_json(v) } - metadata = { k: v for k, v in metadata.items() if os.path.exists(os.path.join(path, k)) } - new_size = len(metadata) - if new_size != old_size: - self._logger.info("Deleted {} stale or invalid entries from metadata for path {}".format(old_size - new_size, - path)) - self._save_metadata(path, metadata) - else: - with self._get_metadata_lock(path): - self._metadata_cache[path] = metadata - return metadata - else: - return {} - - def _save_metadata(self, path, metadata): - import json - - with self._get_metadata_lock(path): - self._metadata_cache[path] = metadata - - with self._get_persisted_metadata_lock(path): - metadata_path = os.path.join(path, ".metadata.json") - try: - with atomic_write(metadata_path, mode='wb') as f: - f.write(to_bytes(json.dumps(metadata, indent=4, separators=(",", ": ")))) - except Exception: - self._logger.exception("Error while writing .metadata.json to {path}".format(**locals())) - - def _delete_metadata(self, path): - with self._get_metadata_lock(path): - if path in self._metadata_cache: - del self._metadata_cache[path] - - with self._get_persisted_metadata_lock(path): - metadata_files = (".metadata.json", ".metadata.yaml") - for metadata_file in metadata_files: - metadata_path = os.path.join(path, metadata_file) - if os.path.exists(metadata_path): - try: - os.remove(metadata_path) - except Exception: - self._logger.exception("Error while deleting {metadata_file} from {path}".format(**locals())) - - @staticmethod - def _copied_metadata(metadata, name): - metadata = copy.copy(metadata) - metadata[name] = copy.deepcopy(metadata.get(name, {})) - return metadata - - def _migrate_metadata(self, path): - # we switched to json in 1.3.9 - if we still have yaml here, migrate it now - import yaml - import json - - 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") - - if not os.path.exists(metadata_path_yaml): - # nothing to migrate - return - - if os.path.exists(metadata_path_json): - # already migrated - try: - os.remove(metadata_path_yaml) - except Exception: - self._logger.exception("Error while removing .metadata.yaml from {path}".format(**locals())) - return - - with io.open(metadata_path_yaml, 'rt', 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 - - if not isinstance(metadata, dict): - # looks invalid, ignore it - return - - with atomic_write(metadata_path_json, mode='wb') as f: - f.write(to_bytes(json.dumps(metadata, indent=4, separators=(",", ": ")))) - - try: - os.remove(metadata_path_yaml) - except Exception: - self._logger.exception("Error while removing .metadata.yaml from {path}".format(**locals())) - - @contextmanager - def _get_metadata_lock(self, path): - with self._metadata_lock_mutex: - if path not in self._metadata_locks: - import threading - self._metadata_locks[path] = (0, threading.RLock()) - - counter, lock = self._metadata_locks[path] - counter += 1 - self._metadata_locks[path] = (counter, lock) - - yield lock - - with self._metadata_lock_mutex: - counter = self._metadata_locks[path][0] - counter -= 1 - if counter <= 0: - del self._metadata_locks[path] - else: - self._metadata_locks[path] = (counter, lock) - - @contextmanager - def _get_persisted_metadata_lock(self, path): - with self._persisted_metadata_lock_mutex: - if path not in self._persisted_metadata_locks: - import threading - self._persisted_metadata_locks[path] = (0, threading.RLock()) - - counter, lock = self._persisted_metadata_locks[path] - counter += 1 - self._persisted_metadata_locks[path] = (counter, lock) - - yield lock - - with self._persisted_metadata_lock_mutex: - counter = self._persisted_metadata_locks[path][0] - counter -= 1 - if counter <= 0: - del self._persisted_metadata_locks[path] - else: - self._persisted_metadata_locks[path] = (counter, lock) + @classmethod + def _no_unicode_variations(cls, text): + return cls._UNICODE_VARIATIONS.sub("", text) + + _SLUGIFY = Slugify() + _SLUGIFY.safe_chars = "-_.()[] " + + @classmethod + def _slugify(cls, text): + text = to_unicode(text) + text = cls._no_unicode_variations(text) + text = demojize(text, delimiters=("", "")) + return cls._SLUGIFY(text) + + def __init__(self, basefolder, create=False): + """ + Initializes a ``LocalFileStorage`` instance under the given ``basefolder``, creating the necessary folder + if necessary and ``create`` is set to ``True``. + + :param string basefolder: the path to the folder under which to create the storage + :param bool create: ``True`` if the folder should be created if it doesn't exist yet, ``False`` otherwise + """ + self._logger = logging.getLogger(__name__) + + self.basefolder = os.path.realpath(os.path.abspath(to_unicode(basefolder))) + if not os.path.exists(self.basefolder) and create: + os.makedirs(self.basefolder) + if not os.path.exists(self.basefolder) or not os.path.isdir(self.basefolder): + raise StorageError( + "{basefolder} is not a valid directory".format(**locals()), + code=StorageError.INVALID_DIRECTORY, + ) + + import threading + + self._metadata_lock_mutex = threading.RLock() + self._metadata_locks = {} + self._persisted_metadata_lock_mutex = threading.RLock() + self._persisted_metadata_locks = {} + + self._metadata_cache = pylru.lrucache(100) + self._filelist_cache = {} + self._filelist_cache_mutex = threading.RLock() + + self._old_metadata = None + self._initialize_metadata() + + def _initialize_metadata(self): + self._logger.info( + "Initializing the file metadata for {}...".format(self.basefolder) + ) + + old_metadata_path = os.path.join(self.basefolder, "metadata.yaml") + backup_path = os.path.join(self.basefolder, "metadata.yaml.backup") + + if os.path.exists(old_metadata_path): + # load the old metadata file + try: + with io.open(old_metadata_path, "rt", encoding="utf-8") as f: + import yaml + + self._old_metadata = yaml.safe_load(f) + except Exception: + self._logger.exception("Error while loading old metadata file") + + # make sure the metadata is initialized as far as possible + self._list_folder(self.basefolder) + + # rename the old metadata file + self._old_metadata = None + try: + import shutil + + shutil.move(old_metadata_path, backup_path) + except Exception: + self._logger.exception("Could not rename old metadata.yaml file") + + else: + # make sure the metadata is initialized as far as possible + self._list_folder(self.basefolder) + + self._logger.info( + "... file metadata for {} initialized successfully.".format(self.basefolder) + ) + + @property + def analysis_backlog(self): + return self.analysis_backlog_for_path() + + def analysis_backlog_for_path(self, path=None): + if path: + path = self.sanitize_path(path) + + for entry in self._analysis_backlog_generator(path): + yield entry + + def _analysis_backlog_generator(self, path=None): + if path is None: + path = self.basefolder + + metadata = self._get_metadata(path) + if not metadata: + metadata = {} + for entry in scandir(path): + if is_hidden_path(entry.name): + continue + + if entry.is_file() and octoprint.filemanager.valid_file_type(entry.name): + if ( + not entry.name in metadata + or not isinstance(metadata[entry.name], dict) + or not "analysis" in metadata[entry.name] + ): + printer_profile_rels = self.get_link(entry.path, "printerprofile") + if printer_profile_rels: + printer_profile_id = printer_profile_rels[0]["id"] + else: + printer_profile_id = None + + yield entry.name, entry.path, printer_profile_id + elif os.path.isdir(entry.path): + for sub_entry in self._analysis_backlog_generator(entry.path): + yield self.join_path(entry.name, sub_entry[0]), sub_entry[ + 1 + ], sub_entry[2] + + def last_modified(self, path=None, recursive=False): + if path is None: + path = self.basefolder + else: + path = os.path.join(self.basefolder, path) + + def last_modified_for_path(p): + metadata = os.path.join(p, ".metadata.json") + if os.path.exists(metadata): + return max(os.stat(p).st_mtime, os.stat(metadata).st_mtime) + else: + return os.stat(p).st_mtime + + if recursive: + return max(last_modified_for_path(root) for root, _, _ in walk(path)) + else: + return last_modified_for_path(path) + + def file_in_path(self, path, filepath): + filepath = self.sanitize_path(filepath) + path = self.sanitize_path(path) + + return filepath == path or filepath.startswith(path + os.sep) + + def file_exists(self, path): + path, name = self.sanitize(path) + file_path = os.path.join(path, name) + return os.path.exists(file_path) and os.path.isfile(file_path) + + def folder_exists(self, path): + path, name = self.sanitize(path) + folder_path = os.path.join(path, name) + return os.path.exists(folder_path) and os.path.isdir(folder_path) + + def list_files(self, path=None, filter=None, recursive=True, force_refresh=False): + if path: + path = self.sanitize_path(to_unicode(path)) + base = self.path_in_storage(path) + if base: + base += "/" + else: + path = self.basefolder + base = "" + + def strip_children(nodes): + result = {} + for key, node in nodes.items(): + if node["type"] == "folder": + node = copy.copy(node) + node["children"] = [] + result[key] = node + return result + + def apply_filter(nodes, filter_func): + result = {} + for key, node in nodes.items(): + if filter_func(node) or node["type"] == "folder": + if node["type"] == "folder": + node = copy.copy(node) + node["children"] = apply_filter( + node.get("children", []), filter_func + ) + result[key] = node + return result + + result = self._list_folder(path, base=base, force_refresh=force_refresh) + if not recursive: + result = strip_children(result) + if callable(filter): + result = apply_filter(result, filter) + return result + + def add_folder(self, path, ignore_existing=True, display=None): + display_path, display_name = self.canonicalize(path) + path = self.sanitize_path(display_path) + name = self.sanitize_name(display_name) + + if display is not None: + display_name = display + + folder_path = os.path.join(path, name) + if os.path.exists(folder_path): + if not ignore_existing: + raise StorageError( + "{name} does already exist in {path}".format(**locals()), + code=StorageError.ALREADY_EXISTS, + ) + else: + os.mkdir(folder_path) + + if display_name != name: + metadata = self._get_metadata_entry(path, name, default={}) + metadata["display"] = display_name + self._update_metadata_entry(path, name, metadata) + + return self.path_in_storage((path, name)) + + def remove_folder(self, path, recursive=True): + path, name = self.sanitize(path) + + folder_path = os.path.join(path, name) + if not os.path.exists(folder_path): + return + + empty = True + for entry in scandir(folder_path): + if entry.name == ".metadata.json" or entry.name == ".metadata.yaml": + continue + empty = False + break + + if not empty and not recursive: + raise StorageError( + "{name} in {path} is not empty".format(**locals()), + code=StorageError.NOT_EMPTY, + ) + + import shutil + + shutil.rmtree(folder_path) + + self._remove_metadata_entry(path, name) + + def _get_source_destination_data(self, source, destination, must_not_equal=False): + """Prepares data dicts about source and destination for copy/move.""" + source_path, source_name = self.sanitize(source) + + destination_canon_path, destination_canon_name = self.canonicalize(destination) + destination_path = self.sanitize_path(destination_canon_path) + destination_name = self.sanitize_name(destination_canon_name) + + source_fullpath = os.path.join(source_path, source_name) + destination_fullpath = os.path.join(destination_path, destination_name) + + if not os.path.exists(source_fullpath): + raise StorageError( + "{} in {} does not exist".format(source_name, source_path), + code=StorageError.INVALID_SOURCE, + ) + + if not os.path.isdir(destination_path): + raise StorageError( + "Destination path {} does not exist or is not a folder".format( + destination_path + ), + code=StorageError.INVALID_DESTINATION, + ) + if ( + os.path.exists(destination_fullpath) + and source_fullpath != destination_fullpath + ): + raise StorageError( + "{} does already exist in {}".format(destination_name, destination_path), + code=StorageError.INVALID_DESTINATION, + ) + + source_meta = self._get_metadata_entry(source_path, source_name) + if source_meta: + source_display = source_meta.get("display", source_name) + else: + source_display = source_name + + if ( + must_not_equal or source_display == destination_canon_name + ) and source_fullpath == destination_fullpath: + raise StorageError( + "Source {} and destination {} are the same folder".format( + source_path, destination_path + ), + code=StorageError.SOURCE_EQUALS_DESTINATION, + ) + + source_data = { + "path": source_path, + "name": source_name, + "display": source_display, + "fullpath": source_fullpath, + } + destination_data = { + "path": destination_path, + "name": destination_name, + "display": destination_canon_name, + "fullpath": destination_fullpath, + } + return source_data, destination_data + + def _set_display_metadata(self, destination_data, source_data=None): + if ( + source_data + and destination_data["name"] == source_data["name"] + and source_data["name"] != source_data["display"] + ): + display = source_data["display"] + elif destination_data["name"] != destination_data["display"]: + display = destination_data["display"] + else: + display = None + + destination_meta = self._get_metadata_entry( + destination_data["path"], destination_data["name"], default={} + ) + if display: + destination_meta["display"] = display + self._update_metadata_entry( + destination_data["path"], destination_data["name"], destination_meta + ) + elif "display" in destination_meta: + del destination_meta["display"] + self._update_metadata_entry( + destination_data["path"], destination_data["name"], destination_meta + ) + + def copy_folder(self, source, destination): + source_data, destination_data = self._get_source_destination_data( + source, destination, must_not_equal=True + ) + + try: + shutil.copytree(source_data["fullpath"], destination_data["fullpath"]) + except Exception as e: + raise StorageError( + "Could not copy %s in %s to %s in %s" + % ( + source_data["name"], + source_data["path"], + destination_data["name"], + destination_data["path"], + ), + cause=e, + ) + + self._set_display_metadata(destination_data, source_data=source_data) + + return self.path_in_storage(destination_data["fullpath"]) + + def move_folder(self, source, destination): + source_data, destination_data = self._get_source_destination_data( + source, destination + ) + + # only a display rename? Update that and bail early + if source_data["fullpath"] == destination_data["fullpath"]: + self._set_display_metadata(destination_data) + return self.path_in_storage(destination_data["fullpath"]) + + try: + shutil.move(source_data["fullpath"], destination_data["fullpath"]) + except Exception as e: + raise StorageError( + "Could not move %s in %s to %s in %s" + % ( + source_data["name"], + source_data["path"], + destination_data["name"], + destination_data["path"], + ), + cause=e, + ) + + self._set_display_metadata(destination_data, source_data=source_data) + self._remove_metadata_entry(source_data["path"], source_data["name"]) + self._delete_metadata(source_data["fullpath"]) + + return self.path_in_storage(destination_data["fullpath"]) + + def add_file( + self, + path, + file_object, + printer_profile=None, + links=None, + allow_overwrite=False, + display=None, + ): + display_path, display_name = self.canonicalize(path) + path = self.sanitize_path(display_path) + name = self.sanitize_name(display_name) + + if display: + display_name = display + + if not octoprint.filemanager.valid_file_type(name): + raise StorageError( + "{name} is an unrecognized file type".format(**locals()), + code=StorageError.INVALID_FILE, + ) + + file_path = os.path.join(path, name) + if os.path.exists(file_path) and not os.path.isfile(file_path): + raise StorageError( + "{name} does already exist in {path} and is not a file".format( + **locals() + ), + code=StorageError.ALREADY_EXISTS, + ) + if os.path.exists(file_path) and not allow_overwrite: + raise StorageError( + "{name} does already exist in {path} and overwriting is prohibited".format( + **locals() + ), + code=StorageError.ALREADY_EXISTS, + ) + + # make sure folders exist + if not os.path.exists(path): + # TODO persist display names of path segments! + os.makedirs(path) + + # save the file + file_object.save(file_path) + + # save the file's hash to the metadata of the folder + file_hash = self._create_hash(file_path) + metadata = self._get_metadata_entry(path, name, default={}) + metadata_dirty = False + if not "hash" in metadata or metadata["hash"] != file_hash: + # hash changed -> throw away old metadata + metadata = {"hash": file_hash} + metadata_dirty = True + + if not "display" in metadata and display_name != name: + # display name is not the same as file name -> store in metadata + metadata["display"] = display_name + metadata_dirty = True + + if metadata_dirty: + self._update_metadata_entry(path, name, metadata) + + # process any links that were also provided for adding to the file + if not links: + links = [] + + if printer_profile is not None: + links.append( + ( + "printerprofile", + {"id": printer_profile["id"], "name": printer_profile["name"]}, + ) + ) + + self._add_links(name, path, links) + + # touch the file to set last access and modification time to now + os.utime(file_path, None) + + return self.path_in_storage((path, name)) + + def remove_file(self, path): + path, name = self.sanitize(path) + + file_path = os.path.join(path, name) + if not os.path.exists(file_path): + return + if not os.path.isfile(file_path): + raise StorageError( + "{name} in {path} is not a file".format(**locals()), + code=StorageError.INVALID_FILE, + ) + + try: + os.remove(file_path) + except Exception as e: + raise StorageError( + "Could not delete {name} in {path}".format(**locals()), cause=e + ) + + self._remove_metadata_entry(path, name) + + def copy_file(self, source, destination): + source_data, destination_data = self._get_source_destination_data( + source, destination, must_not_equal=True + ) + + try: + shutil.copy2(source_data["fullpath"], destination_data["fullpath"]) + except Exception as e: + raise StorageError( + "Could not copy %s in %s to %s in %s" + % ( + source_data["name"], + source_data["path"], + destination_data["name"], + destination_data["path"], + ), + cause=e, + ) + + self._copy_metadata_entry( + source_data["path"], + source_data["name"], + destination_data["path"], + destination_data["name"], + ) + self._set_display_metadata(destination_data, source_data=source_data) + + return self.path_in_storage(destination_data["fullpath"]) + + def move_file(self, source, destination, allow_overwrite=False): + source_data, destination_data = self._get_source_destination_data( + source, destination + ) + + # only a display rename? Update that and bail early + if source_data["fullpath"] == destination_data["fullpath"]: + self._set_display_metadata(destination_data) + return self.path_in_storage(destination_data["fullpath"]) + + try: + shutil.move(source_data["fullpath"], destination_data["fullpath"]) + except Exception as e: + raise StorageError( + "Could not move %s in %s to %s in %s" + % ( + source_data["name"], + source_data["path"], + destination_data["name"], + destination_data["path"], + ), + cause=e, + ) + + self._copy_metadata_entry( + source_data["path"], + source_data["name"], + destination_data["path"], + destination_data["name"], + delete_source=True, + ) + self._set_display_metadata(destination_data, source_data=source_data) + + return self.path_in_storage(destination_data["fullpath"]) + + def has_analysis(self, path): + metadata = self.get_metadata(path) + return "analysis" in metadata + + def get_metadata(self, path): + path, name = self.sanitize(path) + return self._get_metadata_entry(path, name) + + def get_link(self, path, rel): + path, name = self.sanitize(path) + return self._get_links(name, path, rel) + + def add_link(self, path, rel, data): + path, name = self.sanitize(path) + self._add_links(name, path, [(rel, data)]) + + def remove_link(self, path, rel, data): + path, name = self.sanitize(path) + self._remove_links(name, path, [(rel, data)]) + + def add_history(self, path, data): + path, name = self.sanitize(path) + self._add_history(name, path, data) + + def update_history(self, path, index, data): + path, name = self.sanitize(path) + self._update_history(name, path, index, data) + + def remove_history(self, path, index): + path, name = self.sanitize(path) + self._delete_history(name, path, index) + + def get_additional_metadata(self, path, key): + path, name = self.sanitize(path) + metadata = self._get_metadata(path) + + if not name in metadata: + return + + return metadata[name].get(key) + + def set_additional_metadata(self, path, key, data, overwrite=False, merge=False): + path, name = self.sanitize(path) + metadata = self._get_metadata(path) + metadata_dirty = False + + if not name in metadata: + return + + metadata = self._copied_metadata(metadata, name) + + if not key in metadata[name] or overwrite: + metadata[name][key] = data + metadata_dirty = True + elif ( + key in metadata[name] + and isinstance(metadata[name][key], dict) + and isinstance(data, dict) + and merge + ): + import octoprint.util + + metadata[name][key] = octoprint.util.dict_merge( + metadata[name][key], data, in_place=True + ) + metadata_dirty = True + + if metadata_dirty: + self._save_metadata(path, metadata) + + def remove_additional_metadata(self, path, key): + path, name = self.sanitize(path) + metadata = self._get_metadata(path) + + if not name in metadata: + return + + if not key in metadata[name]: + return + + metadata = self._copied_metadata(metadata, name) + del metadata[name][key] + self._save_metadata(path, metadata) + + def split_path(self, path): + path = to_unicode(path) + split = path.split("/") + if len(split) == 1: + return "", split[0] + else: + return self.join_path(*split[:-1]), split[-1] + + def join_path(self, *path): + return "/".join(map(to_unicode, path)) + + def sanitize(self, path): + """ + Returns a ``(path, name)`` tuple derived from the provided ``path``. + + ``path`` may be: + * a storage path + * an absolute file system path + * a tuple or list containing all individual path elements + * a string representation of the path + * with or without a file name + + Note that for a ``path`` without a trailing slash the last part will be considered a file name and + hence be returned at second position. If you only need to convert a folder path, be sure to + include a trailing slash for a string ``path`` or an empty last element for a list ``path``. + """ + + path, name = self.canonicalize(path) + name = self.sanitize_name(name) + path = self.sanitize_path(path) + return path, name + + def canonicalize(self, path): + name = None + if isinstance(path, basestring): + path = to_unicode(path) + if path.startswith(self.basefolder): + path = path[len(self.basefolder) :] + path = path.replace(os.path.sep, "/") + path = path.split("/") + if isinstance(path, (list, tuple)): + if len(path) == 1: + name = to_unicode(path[0]) + path = "" + else: + name = to_unicode(path[-1]) + path = self.join_path(*map(to_unicode, path[:-1])) + if not path: + path = "" + + return path, name + + def sanitize_name(self, name): + """ + Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\\``. Otherwise + slugifies the given ``name`` by converting it to ASCII, leaving ``-``, ``_``, ``.``, + ``(``, and ``)`` as is. + """ + name = to_unicode(name) + + if name is None: + return None + + if "/" in name or "\\" in name: + raise ValueError("name must not contain / or \\") + + result = self._slugify(name).replace(" ", "_") + if result and result != "." and result != ".." and result[0] == ".": + # hidden files under *nix + result = result[1:] + return result + + def sanitize_path(self, path): + """ + Ensures that the on disk representation of ``path`` is located under the configured basefolder. Resolves all + relative path elements (e.g. ``..``) and sanitizes folder names using :func:`sanitize_name`. Final path is the + absolute path including leading ``basefolder`` path. + """ + path = to_unicode(path) + + if len(path): + if path[0] == "/": + path = path[1:] + elif path[0] == "." and path[1] == "/": + path = path[2:] + + path_elements = path.split("/") + joined_path = self.basefolder + for path_element in path_elements: + joined_path = os.path.join(joined_path, self.sanitize_name(path_element)) + path = os.path.realpath(joined_path) + if not path.startswith(self.basefolder): + raise ValueError( + "path not contained in base folder: {path}".format(**locals()) + ) + return path + + def _sanitize_entry(self, entry, path, entry_path): + entry = to_unicode(entry) + sanitized = self.sanitize_name(entry) + if sanitized != entry: + # entry is not sanitized yet, let's take care of that + sanitized_path = os.path.join(path, sanitized) + sanitized_name, sanitized_ext = os.path.splitext(sanitized) + + counter = 1 + while os.path.exists(sanitized_path): + counter += 1 + sanitized = self.sanitize_name( + "{}_({}){}".format(sanitized_name, counter, sanitized_ext) + ) + sanitized_path = os.path.join(path, sanitized) + + try: + shutil.move(entry_path, sanitized_path) + + self._logger.info( + 'Sanitized "{}" to "{}"'.format(entry_path, sanitized_path) + ) + return sanitized, sanitized_path + except Exception: + self._logger.exception( + 'Error while trying to rename "{}" to "{}", ignoring file'.format( + entry_path, sanitized_path + ) + ) + raise + + return entry, entry_path + + def path_in_storage(self, path): + if isinstance(path, (tuple, list)): + path = self.join_path(*path) + if isinstance(path, basestring): + path = to_unicode(path) + if path.startswith(self.basefolder): + path = path[len(self.basefolder) :] + path = path.replace(os.path.sep, "/") + if path.startswith("/"): + path = path[1:] + + return path + + def path_on_disk(self, path): + path, name = self.sanitize(path) + return os.path.join(path, name) + + ##~~ internals + + def _add_history(self, name, path, data): + metadata = self._copied_metadata(self._get_metadata(path), name) + + if not "hash" in metadata[name]: + metadata[name]["hash"] = self._create_hash(os.path.join(path, name)) + + if not "history" in metadata[name]: + metadata[name]["history"] = [] + + metadata[name]["history"].append(data) + self._calculate_stats_from_history(name, path, metadata=metadata, save=False) + self._save_metadata(path, metadata) + + def _update_history(self, name, path, index, data): + metadata = self._get_metadata(path) + + if not name in metadata or not "history" in metadata[name]: + return + + metadata = self._copied_metadata(metadata, name) + + try: + metadata[name]["history"][index].update(data) + self._calculate_stats_from_history(name, path, metadata=metadata, save=False) + self._save_metadata(path, metadata) + except IndexError: + pass + + def _delete_history(self, name, path, index): + metadata = self._get_metadata(path) + + if not name in metadata or not "history" in metadata[name]: + return + + metadata = self._copied_metadata(metadata, name) + + try: + del metadata[name]["history"][index] + self._calculate_stats_from_history(name, path, metadata=metadata, save=False) + self._save_metadata(path, metadata) + except IndexError: + pass + + def _calculate_stats_from_history(self, name, path, metadata=None, save=True): + if metadata is None: + metadata = self._copied_metadata(self._get_metadata(path), name) + + if not "history" in metadata[name]: + return + + # collect data from history + former_print_times = {} + last_print = {} + + for history_entry in metadata[name]["history"]: + if ( + not "printTime" in history_entry + or not "success" in history_entry + or not history_entry["success"] + or not "printerProfile" in history_entry + ): + continue + + printer_profile = history_entry["printerProfile"] + if not printer_profile: + continue + + print_time = history_entry["printTime"] + try: + print_time = float(print_time) + except Exception: + self._logger.warning( + "Invalid print time value found in print history for {} in {}/.metadata.json: {!r}".format( + name, path, print_time + ) + ) + continue + + if not printer_profile in former_print_times: + former_print_times[printer_profile] = [] + former_print_times[printer_profile].append(print_time) + + if ( + not printer_profile in last_print + or last_print[printer_profile] is None + or ( + "timestamp" in history_entry + and history_entry["timestamp"] + > last_print[printer_profile]["timestamp"] + ) + ): + last_print[printer_profile] = history_entry + + # calculate stats + statistics = {"averagePrintTime": {}, "lastPrintTime": {}} + + for printer_profile in former_print_times: + if not former_print_times[printer_profile]: + continue + statistics["averagePrintTime"][printer_profile] = sum( + former_print_times[printer_profile] + ) / float(len(former_print_times[printer_profile])) + + for printer_profile in last_print: + if not last_print[printer_profile]: + continue + statistics["lastPrintTime"][printer_profile] = last_print[printer_profile][ + "printTime" + ] + + metadata[name]["statistics"] = statistics + + if save: + self._save_metadata(path, metadata) + + def _get_links(self, name, path, searched_rel): + metadata = self._get_metadata(path) + result = [] + + if not name in metadata: + return result + + if not "links" in metadata[name]: + return result + + for data in metadata[name]["links"]: + if not "rel" in data or not data["rel"] == searched_rel: + continue + result.append(data) + return result + + def _add_links(self, name, path, links): + file_type = octoprint.filemanager.get_file_type(name) + if file_type: + file_type = file_type[0] + + metadata = self._copied_metadata(self._get_metadata(path), name) + metadata_dirty = False + + if not "hash" in metadata[name]: + metadata[name]["hash"] = self._create_hash(os.path.join(path, name)) + + if not "links" in metadata[name]: + metadata[name]["links"] = [] + + for rel, data in links: + if (rel == "model" or rel == "machinecode") and "name" in data: + if file_type == "model" and rel == "model": + # adding a model link to a model doesn't make sense + return + elif file_type == "machinecode" and rel == "machinecode": + # adding a machinecode link to a machinecode doesn't make sense + return + + ref_path = os.path.join(path, data["name"]) + if not os.path.exists(ref_path): + # file doesn't exist, we won't create the link + continue + + # fetch hash of target file + if data["name"] in metadata and "hash" in metadata[data["name"]]: + hash = metadata[data["name"]]["hash"] + else: + hash = self._create_hash(ref_path) + if not data["name"] in metadata: + metadata[data["name"]] = {"hash": hash, "links": []} + else: + metadata[data["name"]]["hash"] = hash + + if "hash" in data and not data["hash"] == hash: + # file doesn't have the correct hash, we won't create the link + continue + + if not "links" in metadata[data["name"]]: + metadata[data["name"]]["links"] = [] + + # add reverse link to link target file + metadata[data["name"]]["links"].append( + { + "rel": "machinecode" if rel == "model" else "model", + "name": name, + "hash": metadata[name]["hash"], + } + ) + metadata_dirty = True + + link_dict = {"rel": rel, "name": data["name"], "hash": hash} + + elif rel == "web" and "href" in data: + link_dict = {"rel": rel, "href": data["href"]} + if "retrieved" in data: + link_dict["retrieved"] = data["retrieved"] + + else: + continue + + if link_dict: + metadata[name]["links"].append(link_dict) + metadata_dirty = True + + if metadata_dirty: + self._save_metadata(path, metadata) + + def _remove_links(self, name, path, links): + metadata = self._copied_metadata(self._get_metadata(path), name) + metadata_dirty = False + + hash = metadata[name].get("hash", self._create_hash(os.path.join(path, name))) + + for rel, data in links: + if (rel == "model" or rel == "machinecode") and "name" in data: + if data["name"] in metadata and "links" in metadata[data["name"]]: + ref_rel = "model" if rel == "machinecode" else "machinecode" + for link in metadata[data["name"]]["links"]: + if ( + link["rel"] == ref_rel + and "name" in link + and link["name"] == name + and "hash" in link + and link["hash"] == hash + ): + metadata[data["name"]] = copy.deepcopy(metadata[data["name"]]) + metadata[data["name"]]["links"].remove(link) + metadata_dirty = True + + if "links" in metadata[name]: + for link in metadata[name]["links"]: + if not link["rel"] == rel: + continue + + matches = True + for k, v in data.items(): + if not k in link or not link[k] == v: + matches = False + break + + if not matches: + continue + + metadata[name]["links"].remove(link) + metadata_dirty = True + + if metadata_dirty: + self._save_metadata(path, metadata) + + @time_this( + logtarget=__name__ + ".timings", + message="{func}({func_args},{func_kwargs}) took {timing:.2f}ms", + incl_func_args=True, + ) + def _list_folder(self, path, base="", force_refresh=False, **kwargs): + def get_size(nodes): + total_size = 0 + for node in nodes.values(): + if "size" in node: + total_size += node["size"] + return total_size + + def enrich_folders(nodes): + nodes = copy.copy(nodes) + for key, value in nodes.items(): + if value["type"] == "folder": + value = copy.copy(value) + value["children"] = self._list_folder( + os.path.join(path, key), + base=value["path"] + "/", + force_refresh=force_refresh, + ) + value["size"] = get_size(value["children"]) + nodes[key] = value + return nodes + + metadata_dirty = False + try: + with self._filelist_cache_mutex: + cache = self._filelist_cache.get(path) + if ( + not force_refresh + and cache + and cache[0] >= self.last_modified(path, recursive=True) + ): + return enrich_folders(cache[1]) + + metadata = self._get_metadata(path) + if not metadata: + metadata = {} + + result = {} + + for entry in scandir(path): + if is_hidden_path(entry.name): + # no hidden files and folders + continue + + try: + entry_name = entry_display = entry.name + entry_path = entry.path + entry_is_file = entry.is_file() + entry_is_dir = entry.is_dir() + entry_stat = entry.stat() + except Exception: + # error while trying to fetch file metadata, that might be thanks to file already having + # been moved or deleted - ignore it and continue + continue + + try: + new_entry_name, new_entry_path = self._sanitize_entry( + entry_name, path, entry_path + ) + if entry_name != new_entry_name or entry_path != new_entry_path: + entry_display = to_unicode(entry_name) + entry_name = new_entry_name + entry_path = new_entry_path + entry_stat = os.stat(entry_path) + except Exception: + # error while trying to rename the file, we'll continue here and ignore it + continue + + path_in_location = entry_name if not base else base + entry_name + + try: + # file handling + if entry_is_file: + type_path = octoprint.filemanager.get_file_type(entry_name) + if not type_path: + # only supported extensions + continue + else: + file_type = type_path[0] + + if entry_name in metadata and isinstance( + metadata[entry_name], dict + ): + entry_metadata = metadata[entry_name] + if ( + not "display" in entry_metadata + and entry_display != entry_name + ): + if not metadata_dirty: + metadata = self._copied_metadata( + metadata, entry_name + ) + metadata[entry_name]["display"] = entry_display + entry_metadata["display"] = entry_display + metadata_dirty = True + else: + if not metadata_dirty: + metadata = self._copied_metadata(metadata, entry_name) + entry_metadata = self._add_basic_metadata( + path, + entry_name, + display_name=entry_display, + save=False, + metadata=metadata, + ) + metadata_dirty = True + + extended_entry_data = {} + extended_entry_data.update(entry_metadata) + extended_entry_data["name"] = entry_name + extended_entry_data["display"] = entry_metadata.get( + "display", entry_name + ) + extended_entry_data["path"] = path_in_location + extended_entry_data["type"] = file_type + extended_entry_data["typePath"] = type_path + stat = entry_stat + if stat: + extended_entry_data["size"] = stat.st_size + extended_entry_data["date"] = int(stat.st_mtime) + + result[entry_name] = extended_entry_data + + # folder recursion + elif entry_is_dir: + if entry_name in metadata and isinstance( + metadata[entry_name], dict + ): + entry_metadata = metadata[entry_name] + if ( + not "display" in entry_metadata + and entry_display != entry_name + ): + if not metadata_dirty: + metadata = self._copied_metadata( + metadata, entry_name + ) + metadata[entry_name]["display"] = entry_display + entry_metadata["display"] = entry_display + metadata_dirty = True + elif entry_name != entry_display: + if not metadata_dirty: + metadata = self._copied_metadata(metadata, entry_name) + entry_metadata = self._add_basic_metadata( + path, + entry_name, + display_name=entry_display, + save=False, + metadata=metadata, + ) + metadata_dirty = True + else: + entry_metadata = {} + + entry_data = { + "name": entry_name, + "display": entry_metadata.get("display", entry_name), + "path": path_in_location, + "type": "folder", + "typePath": ["folder"], + } + + result[entry_name] = entry_data + except Exception: + # So something went wrong somewhere while processing this file entry - log that and continue + self._logger.exception( + "Error while processing entry {}".format(entry_path) + ) + continue + + self._filelist_cache[path] = ( + self.last_modified(path, recursive=True), + result, + ) + return enrich_folders(result) + finally: + # save metadata + if metadata_dirty: + self._save_metadata(path, metadata) + + def _add_basic_metadata( + self, + path, + entry, + display_name=None, + additional_metadata=None, + save=True, + metadata=None, + ): + if additional_metadata is None: + additional_metadata = {} + + if metadata is None: + metadata = self._get_metadata(path) + + entry_path = os.path.join(path, entry) + + if os.path.isfile(entry_path): + entry_data = { + "hash": self._create_hash(os.path.join(path, entry)), + "links": [], + "notes": [], + } + if ( + path == self.basefolder + and self._old_metadata is not None + and entry in self._old_metadata + and "gcodeAnalysis" in self._old_metadata[entry] + ): + # if there is still old metadata available and that contains an analysis for this file, use it! + entry_data["analysis"] = self._old_metadata[entry]["gcodeAnalysis"] + + elif os.path.isdir(entry_path): + entry_data = {} + + else: + return + + if display_name is not None and not display_name == entry: + entry_data["display"] = display_name + + entry_data.update(additional_metadata) + + metadata = copy.copy(metadata) + metadata[entry] = entry_data + + if save: + self._save_metadata(path, metadata) + + return entry_data + + def _create_hash(self, path): + import hashlib + + blocksize = 65536 + hash = hashlib.sha1() + with io.open(path, "rb") as f: + buffer = f.read(blocksize) + while len(buffer) > 0: + hash.update(buffer) + buffer = f.read(blocksize) + + return hash.hexdigest() + + def _get_metadata_entry(self, path, name, default=None): + with self._get_metadata_lock(path): + metadata = self._get_metadata(path) + return metadata.get(name, default) + + def _remove_metadata_entry(self, path, name): + with self._get_metadata_lock(path): + metadata = self._get_metadata(path) + if not name in metadata: + return + + metadata = copy.copy(metadata) + + if "hash" in metadata[name]: + hash = metadata[name]["hash"] + for m in metadata.values(): + if not "links" in m: + continue + links_hash = ( + lambda link: "hash" in link + and link["hash"] == hash + and "rel" in link + and (link["rel"] == "model" or link["rel"] == "machinecode") + ) + m["links"] = [link for link in m["links"] if not links_hash(link)] + + del metadata[name] + self._save_metadata(path, metadata) + + def _update_metadata_entry(self, path, name, data): + with self._get_metadata_lock(path): + metadata = copy.copy(self._get_metadata(path)) + metadata[name] = data + self._save_metadata(path, metadata) + + def _copy_metadata_entry( + self, + source_path, + source_name, + destination_path, + destination_name, + delete_source=False, + updates=None, + ): + with self._get_metadata_lock(source_path): + source_data = self._get_metadata_entry(source_path, source_name, default={}) + if not source_data: + return + + if delete_source: + self._remove_metadata_entry(source_path, source_name) + + if updates is not None: + source_data.update(updates) + + with self._get_metadata_lock(destination_path): + self._update_metadata_entry(destination_path, destination_name, source_data) + + def _get_metadata(self, path, force=False): + import json + + if not force: + metadata = self._metadata_cache.get(path) + if metadata: + return metadata + + self._migrate_metadata(path) + + metadata_path = os.path.join(path, ".metadata.json") + + metadata = None + with self._get_persisted_metadata_lock(path): + if os.path.exists(metadata_path): + with io.open(metadata_path, "rt", encoding="utf-8") as f: + try: + metadata = json.load(f) + except Exception: + self._logger.exception( + "Error while reading .metadata.json from {path}".format( + **locals() + ) + ) + + def valid_json(value): + try: + json.dumps(value, allow_nan=False) + return True + except: + return False + + if isinstance(metadata, dict): + old_size = len(metadata) + metadata = {k: v for k, v in metadata.items() if valid_json(v)} + metadata = { + k: v for k, v in metadata.items() if os.path.exists(os.path.join(path, k)) + } + new_size = len(metadata) + if new_size != old_size: + self._logger.info( + "Deleted {} stale or invalid entries from metadata for path {}".format( + old_size - new_size, path + ) + ) + self._save_metadata(path, metadata) + else: + with self._get_metadata_lock(path): + self._metadata_cache[path] = metadata + return metadata + else: + return {} + + def _save_metadata(self, path, metadata): + import json + + with self._get_metadata_lock(path): + self._metadata_cache[path] = metadata + + with self._get_persisted_metadata_lock(path): + metadata_path = os.path.join(path, ".metadata.json") + try: + with atomic_write(metadata_path, mode="wb") as f: + f.write( + to_bytes(json.dumps(metadata, indent=4, separators=(",", ": "))) + ) + except Exception: + self._logger.exception( + "Error while writing .metadata.json to {path}".format(**locals()) + ) + + def _delete_metadata(self, path): + with self._get_metadata_lock(path): + if path in self._metadata_cache: + del self._metadata_cache[path] + + with self._get_persisted_metadata_lock(path): + metadata_files = (".metadata.json", ".metadata.yaml") + for metadata_file in metadata_files: + metadata_path = os.path.join(path, metadata_file) + if os.path.exists(metadata_path): + try: + os.remove(metadata_path) + except Exception: + self._logger.exception( + "Error while deleting {metadata_file} from {path}".format( + **locals() + ) + ) + + @staticmethod + def _copied_metadata(metadata, name): + metadata = copy.copy(metadata) + metadata[name] = copy.deepcopy(metadata.get(name, {})) + return metadata + + def _migrate_metadata(self, path): + # we switched to json in 1.3.9 - if we still have yaml here, migrate it now + import yaml + import json + + 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") + + if not os.path.exists(metadata_path_yaml): + # nothing to migrate + return + + if os.path.exists(metadata_path_json): + # already migrated + try: + os.remove(metadata_path_yaml) + except Exception: + self._logger.exception( + "Error while removing .metadata.yaml from {path}".format( + **locals() + ) + ) + return + + with io.open(metadata_path_yaml, "rt", 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 + + if not isinstance(metadata, dict): + # looks invalid, ignore it + return + + with atomic_write(metadata_path_json, mode="wb") as f: + f.write(to_bytes(json.dumps(metadata, indent=4, separators=(",", ": ")))) + + try: + os.remove(metadata_path_yaml) + except Exception: + self._logger.exception( + "Error while removing .metadata.yaml from {path}".format(**locals()) + ) + + @contextmanager + def _get_metadata_lock(self, path): + with self._metadata_lock_mutex: + if path not in self._metadata_locks: + import threading + + self._metadata_locks[path] = (0, threading.RLock()) + + counter, lock = self._metadata_locks[path] + counter += 1 + self._metadata_locks[path] = (counter, lock) + + yield lock + + with self._metadata_lock_mutex: + counter = self._metadata_locks[path][0] + counter -= 1 + if counter <= 0: + del self._metadata_locks[path] + else: + self._metadata_locks[path] = (counter, lock) + + @contextmanager + def _get_persisted_metadata_lock(self, path): + with self._persisted_metadata_lock_mutex: + if path not in self._persisted_metadata_locks: + import threading + + self._persisted_metadata_locks[path] = (0, threading.RLock()) + + counter, lock = self._persisted_metadata_locks[path] + counter += 1 + self._persisted_metadata_locks[path] = (counter, lock) + + yield lock + + with self._persisted_metadata_lock_mutex: + counter = self._persisted_metadata_locks[path][0] + counter -= 1 + if counter <= 0: + del self._persisted_metadata_locks[path] + else: + self._persisted_metadata_locks[path] = (counter, lock) diff --git a/src/octoprint/filemanager/util.py b/src/octoprint/filemanager/util.py index 682d18e53..1ab1222ed 100644 --- a/src/octoprint/filemanager/util.py +++ b/src/octoprint/filemanager/util.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import io @@ -11,247 +11,254 @@ import os from octoprint import UMASK from octoprint.util import atomic_write + class AbstractFileWrapper(object): - """ - Wrapper for file representations to save to storages. + """ + Wrapper for file representations to save to storages. - Arguments: - filename (str): The file's name - """ + Arguments: + filename (str): The file's name + """ - DEFAULT_PERMISSIONS = 0o664 + DEFAULT_PERMISSIONS = 0o664 - def __init__(self, filename): - self.filename = filename + def __init__(self, filename): + self.filename = filename - def save(self, path, permissions=None): - """ - Saves the file's content to the given absolute path. + def save(self, path, permissions=None): + """ + Saves the file's content to the given absolute path. - Arguments: - path (str): The absolute path to where to save the file - permissions (int): The permissions to set on the file - """ - raise NotImplementedError() + Arguments: + path (str): The absolute path to where to save the file + permissions (int): The permissions to set on the file + """ + raise NotImplementedError() - def stream(self): - """ - Returns a Python stream object (subclass of io.IOBase) representing the file's contents. + def stream(self): + """ + Returns a Python stream object (subclass of io.IOBase) representing the file's contents. + + Returns: + io.IOBase: The file's contents as a stream. + """ + raise NotImplementedError() - Returns: - io.IOBase: The file's contents as a stream. - """ - raise NotImplementedError() class DiskFileWrapper(AbstractFileWrapper): - """ - An implementation of :class:`.AbstractFileWrapper` that wraps an actual file on disk. The `save` implementations - will either copy the file to the new path (preserving file attributes) or -- if `move` is `True` (the default) -- - move the file. + """ + An implementation of :class:`.AbstractFileWrapper` that wraps an actual file on disk. The `save` implementations + will either copy the file to the new path (preserving file attributes) or -- if `move` is `True` (the default) -- + move the file. - Arguments: - filename (str): The file's name - path (str): The file's absolute path - move (boolean): Whether to move the file upon saving (True, default) or copying. - """ + Arguments: + filename (str): The file's name + path (str): The file's absolute path + move (boolean): Whether to move the file upon saving (True, default) or copying. + """ - def __init__(self, filename, path, move=True): - AbstractFileWrapper.__init__(self, filename) - self.path = path - self.move = move + def __init__(self, filename, path, move=True): + AbstractFileWrapper.__init__(self, filename) + self.path = path + self.move = move - def save(self, path, permissions=None): - import shutil + def save(self, path, permissions=None): + import shutil - if self.move: - shutil.move(self.path, path) - else: - shutil.copy2(self.path, path) + if self.move: + shutil.move(self.path, path) + else: + shutil.copy2(self.path, path) - if permissions is None: - permissions = self.DEFAULT_PERMISSIONS & ~UMASK - os.chmod(path, permissions) + if permissions is None: + permissions = self.DEFAULT_PERMISSIONS & ~UMASK + os.chmod(path, permissions) + + def stream(self): + return io.open(self.path, "rb") - def stream(self): - return io.open(self.path, 'rb') class StreamWrapper(AbstractFileWrapper): - """ - A wrapper allowing processing of one or more consecutive streams. + """ + A wrapper allowing processing of one or more consecutive streams. - Arguments: - *streams: One or more :py:`io.IOBase` streams to process one after another to save to storage. - """ - def __init__(self, filename, *streams): - if not len(streams) > 0: - raise ValueError("Need at least one stream to wrap") + Arguments: + *streams: One or more :py:`io.IOBase` streams to process one after another to save to storage. + """ - AbstractFileWrapper.__init__(self, filename) - self.streams = streams + def __init__(self, filename, *streams): + if not len(streams) > 0: + raise ValueError("Need at least one stream to wrap") - def save(self, path, permissions=None): - """ - Will dump the contents of all streams provided during construction into the target file, in the order they were - provided. - """ - import shutil + AbstractFileWrapper.__init__(self, filename) + self.streams = streams - with atomic_write(path, mode='wb') as dest: - for source in self.streams: - shutil.copyfileobj(source, dest) - if permissions is None: - permissions = self.DEFAULT_PERMISSIONS & ~UMASK - os.chmod(path, permissions) + def save(self, path, permissions=None): + """ + Will dump the contents of all streams provided during construction into the target file, in the order they were + provided. + """ + import shutil + + with atomic_write(path, mode="wb") as dest: + for source in self.streams: + shutil.copyfileobj(source, dest) + if permissions is None: + permissions = self.DEFAULT_PERMISSIONS & ~UMASK + os.chmod(path, permissions) + + def stream(self): + """ + If more than one stream was provided to the constructor, will return a :class:`.MultiStream` wrapping all + provided streams in the order they were provided, else the first and only stream is returned directly. + """ + if len(self.streams) > 1: + return MultiStream(*self.streams) + else: + return self.streams[0] - def stream(self): - """ - If more than one stream was provided to the constructor, will return a :class:`.MultiStream` wrapping all - provided streams in the order they were provided, else the first and only stream is returned directly. - """ - if len(self.streams) > 1: - return MultiStream(*self.streams) - else: - return self.streams[0] class MultiStream(io.RawIOBase): - """ - A stream implementation which when read reads from multiple streams, one after the other, basically concatenating - their contents in the order they are provided to the constructor. + """ + A stream implementation which when read reads from multiple streams, one after the other, basically concatenating + their contents in the order they are provided to the constructor. - Arguments: - *streams: One or more :py:`io.IOBase` streams to concatenate. - """ - def __init__(self, *streams): - io.RawIOBase.__init__(self) - self.streams = streams - self.current_stream = 0 + Arguments: + *streams: One or more :py:`io.IOBase` streams to concatenate. + """ - def read(self, n=-1): - if n == 0: - return b'' + def __init__(self, *streams): + io.RawIOBase.__init__(self) + self.streams = streams + self.current_stream = 0 - if len(self.streams) == 0: - return b'' + def read(self, n=-1): + if n == 0: + return b"" - while self.current_stream < len(self.streams): - stream = self.streams[self.current_stream] + if len(self.streams) == 0: + return b"" - result = stream.read(n) - if result is None or len(result) != 0: - return result - else: - self.current_stream += 1 + while self.current_stream < len(self.streams): + stream = self.streams[self.current_stream] - return b'' + result = stream.read(n) + if result is None or len(result) != 0: + return result + else: + self.current_stream += 1 - def readinto(self, b): - n = len(b) - read = self.read(n) - b[:len(read)] = read - return len(read) + return b"" - def close(self): - for stream in self.streams: - try: - stream.close() - except Exception: - pass + def readinto(self, b): + n = len(b) + read = self.read(n) + b[: len(read)] = read + return len(read) - def readable(self, *args, **kwargs): - return True + def close(self): + for stream in self.streams: + try: + stream.close() + except Exception: + pass - def seekable(self, *args, **kwargs): - return False + def readable(self, *args, **kwargs): + return True + + def seekable(self, *args, **kwargs): + return False + + def writable(self, *args, **kwargs): + return False - def writable(self, *args, **kwargs): - return False class LineProcessorStream(io.RawIOBase): - """ - While reading from this stream the provided `input_stream` is read line by line, calling the (overridable) method - :meth:`.process_line` for each read line. + """ + While reading from this stream the provided `input_stream` is read line by line, calling the (overridable) method + :meth:`.process_line` for each read line. - Sub classes can thus modify the contents of the `input_stream` in line, while it is being read. Keep in mind that - ``process_line`` will receive the line as a byte stream - if underlying code needs to operate on unicode you'll need - to do the decoding yourself. + Sub classes can thus modify the contents of the `input_stream` in line, while it is being read. Keep in mind that + ``process_line`` will receive the line as a byte stream - if underlying code needs to operate on unicode you'll need + to do the decoding yourself. - Arguments: - input_stream (io.RawIOBase): The stream to process on the fly. - """ + Arguments: + input_stream (io.RawIOBase): The stream to process on the fly. + """ - def __init__(self, input_stream): - io.RawIOBase.__init__(self) - self.input_stream = io.BufferedReader(input_stream) - self.leftover = bytearray() + def __init__(self, input_stream): + io.RawIOBase.__init__(self) + self.input_stream = io.BufferedReader(input_stream) + self.leftover = bytearray() - def read(self, n=-1): - if n == 0: - return b'' + def read(self, n=-1): + if n == 0: + return b"" - result = bytearray() - while len(result) < n or n == -1: - # add left over from previous loop - bytes_left = (n - len(result)) if n != -1 else -1 - if bytes_left != -1 and bytes_left < len(self.leftover): - # only s - result += self.leftover[:bytes_left] - self.leftover = self.leftover[bytes_left:] - break - else: - result += self.leftover - self.leftover = bytearray() + result = bytearray() + while len(result) < n or n == -1: + # add left over from previous loop + bytes_left = (n - len(result)) if n != -1 else -1 + if bytes_left != -1 and bytes_left < len(self.leftover): + # only s + result += self.leftover[:bytes_left] + self.leftover = self.leftover[bytes_left:] + break + else: + result += self.leftover + self.leftover = bytearray() - # read one line from the underlying stream - processed_line = None - while processed_line is None: - line = self.input_stream.readline() - if not line: - break - processed_line = self.process_line(line) - if processed_line is None: - break + # read one line from the underlying stream + processed_line = None + while processed_line is None: + line = self.input_stream.readline() + if not line: + break + processed_line = self.process_line(line) + if processed_line is None: + break - bytes_left = (n - len(result)) if n != -1 else -1 - if bytes_left != -1 and bytes_left < len(processed_line): - result += processed_line[:bytes_left] - self.leftover = processed_line[bytes_left:] - break - else: - result += processed_line + bytes_left = (n - len(result)) if n != -1 else -1 + if bytes_left != -1 and bytes_left < len(processed_line): + result += processed_line[:bytes_left] + self.leftover = processed_line[bytes_left:] + break + else: + result += processed_line - return bytes(result) + return bytes(result) - def readinto(self, b): - n = len(b) - read = self.read(n) - b[:len(read)] = read - return len(read) + def readinto(self, b): + n = len(b) + read = self.read(n) + b[: len(read)] = read + return len(read) - def process_line(self, line): - """ - Called from the `read` Method of this stream with each line read from `self.input_stream`. + def process_line(self, line): + """ + Called from the `read` Method of this stream with each line read from `self.input_stream`. - By returning ``None`` the line will not be returned from the read stream, effectively being stripped from the - wrapper `input_stream`. + By returning ``None`` the line will not be returned from the read stream, effectively being stripped from the + wrapper `input_stream`. - Arguments: - line (bytes): The line as read from `self.input_stream` in byte representation (str under Python 2 and - bytes under Python 3) + Arguments: + line (bytes): The line as read from `self.input_stream` in byte representation (str under Python 2 and + bytes under Python 3) - Returns: - bytes or None: The processed version of the line (might also be multiple lines), or None if the line is to be - stripped from the processed stream. - """ - return line + Returns: + bytes or None: The processed version of the line (might also be multiple lines), or None if the line is to be + stripped from the processed stream. + """ + return line - def close(self): - self.input_stream.close() + def close(self): + self.input_stream.close() - def readable(self, *args, **kwargs): - return True + def readable(self, *args, **kwargs): + return True - def seekable(self, *args, **kwargs): - return False + def seekable(self, *args, **kwargs): + return False - def writable(self, *args, **kwargs): - return False + def writable(self, *args, **kwargs): + return False diff --git a/src/octoprint/logging/__init__.py b/src/octoprint/logging/__init__.py index d884c948f..4c7d1fad1 100644 --- a/src/octoprint/logging/__init__.py +++ b/src/octoprint/logging/__init__.py @@ -7,153 +7,160 @@ from octoprint.logging import handlers from typing import Union + def log_to_handler(logger, handler, level, msg, exc_info=None, extra=None, *args): - """ - Logs to the provided handler only. + """ + Logs to the provided handler only. - Arguments: - logger: logger to log to - handler: handler to restrict logging to - level: level to log at - msg: message to log - exc_info: optional exception info - extra: optional extra data - *args: log args - """ - import sys - try: - from logging import _srcfile - except ImportError: - _srcfile = None + Arguments: + logger: logger to log to + handler: handler to restrict logging to + level: level to log at + msg: message to log + exc_info: optional exception info + extra: optional extra data + *args: log args + """ + import sys - # this is just the same as logging.Logger._log + try: + from logging import _srcfile + except ImportError: + _srcfile = None - if _srcfile: - # IronPython doesn't track Python frames, so findCaller raises an - # exception on some versions of IronPython. We trap it here so that - # IronPython can use logging. - try: - fn, lno, func = logger.findCaller() - except ValueError: - fn, lno, func = "(unknown file)", 0, "(unknown function)" - else: - fn, lno, func = "(unknown file)", 0, "(unknown function)" - if exc_info: - if not isinstance(exc_info, tuple): - exc_info = sys.exc_info() + # this is just the same as logging.Logger._log - record = logger.makeRecord(logger.name, level, fn, lno, msg, args, exc_info, func, extra) + if _srcfile: + # IronPython doesn't track Python frames, so findCaller raises an + # exception on some versions of IronPython. We trap it here so that + # IronPython can use logging. + try: + fn, lno, func = logger.findCaller() + except ValueError: + fn, lno, func = "(unknown file)", 0, "(unknown function)" + else: + fn, lno, func = "(unknown file)", 0, "(unknown function)" + if exc_info: + if not isinstance(exc_info, tuple): + exc_info = sys.exc_info() - # and this is a mixture of logging.Logger.handle and logging.Logger.callHandlers + record = logger.makeRecord( + logger.name, level, fn, lno, msg, args, exc_info, func, extra + ) - if (not logger.disabled) and logger.filter(record): - if record.levelno >= handler.level: - handler.handle(record) + # and this is a mixture of logging.Logger.handle and logging.Logger.callHandlers + + if (not logger.disabled) and logger.filter(record): + if record.levelno >= handler.level: + handler.handle(record) def get_handler(name, logger=None): - """ - Retrieves the handler named ``name``. + """ + Retrieves the handler named ``name``. - If optional ``logger`` is provided, search will be - limited to that logger, otherwise the root logger will be - searched. + If optional ``logger`` is provided, search will be + limited to that logger, otherwise the root logger will be + searched. - Arguments: - name: the name of the handler to look for - logger: (optional) the logger to search in, root logger if not provided + Arguments: + name: the name of the handler to look for + logger: (optional) the logger to search in, root logger if not provided - Returns: - the handler if it could be found, None otherwise - """ - import logging + Returns: + the handler if it could be found, None otherwise + """ + import logging - if logger is None: - logger = logging.getLogger() + if logger is None: + logger = logging.getLogger() - for handler in logger.handlers: - if handler.get_name() == name: - return handler + for handler in logger.handlers: + if handler.get_name() == name: + return handler - return None + return None def get_divider_line(c, message=None, length=78, indent=3): - """ - Generate a divider line for logging, optionally with included message. + """ + Generate a divider line for logging, optionally with included message. - Examples: + Examples: - >>> get_divider_line("-") # doctest: +ALLOW_UNICODE - '------------------------------------------------------------------------------' - >>> get_divider_line("=", length=10) # doctest: +ALLOW_UNICODE - '==========' - >>> get_divider_line("-", message="Hi", length=10) # doctest: +ALLOW_UNICODE - '--- Hi ---' - >>> get_divider_line("-", message="A slightly longer text") # doctest: +ALLOW_UNICODE - '--- A slightly longer text ---------------------------------------------------' - >>> get_divider_line("-", message="A slightly longer text", indent=5) # doctest: +ALLOW_UNICODE - '----- A slightly longer text -------------------------------------------------' - >>> get_divider_line("-", message="Hello World!", length=10) # doctest: +ALLOW_UNICODE - '--- Hello World!' - >>> get_divider_line(None) - Traceback (most recent call last): - ... - AssertionError: c is not text - >>> get_divider_line("´`") - Traceback (most recent call last): - ... - AssertionError: c is not a single character - >>> get_divider_line("-", message=3) - Traceback (most recent call last): - ... - AssertionError: message is not text - >>> get_divider_line("-", length="hello") - Traceback (most recent call last): - ... - AssertionError: length is not an int - >>> get_divider_line("-", indent="hi") - Traceback (most recent call last): - ... - AssertionError: indent is not an int + >>> get_divider_line("-") # doctest: +ALLOW_UNICODE + '------------------------------------------------------------------------------' + >>> get_divider_line("=", length=10) # doctest: +ALLOW_UNICODE + '==========' + >>> get_divider_line("-", message="Hi", length=10) # doctest: +ALLOW_UNICODE + '--- Hi ---' + >>> get_divider_line("-", message="A slightly longer text") # doctest: +ALLOW_UNICODE + '--- A slightly longer text ---------------------------------------------------' + >>> get_divider_line("-", message="A slightly longer text", indent=5) # doctest: +ALLOW_UNICODE + '----- A slightly longer text -------------------------------------------------' + >>> get_divider_line("-", message="Hello World!", length=10) # doctest: +ALLOW_UNICODE + '--- Hello World!' + >>> get_divider_line(None) + Traceback (most recent call last): + ... + AssertionError: c is not text + >>> get_divider_line("´`") + Traceback (most recent call last): + ... + AssertionError: c is not a single character + >>> get_divider_line("-", message=3) + Traceback (most recent call last): + ... + AssertionError: message is not text + >>> get_divider_line("-", length="hello") + Traceback (most recent call last): + ... + AssertionError: length is not an int + >>> get_divider_line("-", indent="hi") + Traceback (most recent call last): + ... + AssertionError: indent is not an int - Arguments: - c: character to use for the line - message: message to print in the line - length: length of the line - indent: indentation of message in line + Arguments: + c: character to use for the line + message: message to print in the line + length: length of the line + indent: indentation of message in line - Returns: - formatted divider line - """ + Returns: + formatted divider line + """ - assert isinstance(c, basestring), "c is not text" - assert len(c) == 1, "c is not a single character" - assert isinstance(length, int), "length is not an int" - assert isinstance(indent, int), "indent is not an int" + assert isinstance(c, basestring), "c is not text" + assert len(c) == 1, "c is not a single character" + assert isinstance(length, int), "length is not an int" + assert isinstance(indent, int), "indent is not an int" - if message is None: - return c * length + if message is None: + return c * length - assert isinstance(message, basestring), "message is not text" + assert isinstance(message, basestring), "message is not text" - space = length - 2 * (indent + 1) - if space >= len(message): - return c * indent + " " + message + " " + c * (length - indent - 2 - len(message)) - else: - return c * indent + " " + message + space = length - 2 * (indent + 1) + if space >= len(message): + return c * indent + " " + message + " " + c * (length - indent - 2 - len(message)) + else: + return c * indent + " " + message -def prefix_multilines(text, prefix=u": "): - # type: (Union[unicode, bytes], unicode) -> unicode - from octoprint.util import to_unicode +def prefix_multilines(text, prefix=": "): + # type: (Union[unicode, bytes], unicode) -> unicode + from octoprint.util import to_unicode - lines = text.splitlines() - if not lines: - return u"" + lines = text.splitlines() + if not lines: + return "" - if len(lines) == 1: - return to_unicode(lines[0]) + if len(lines) == 1: + return to_unicode(lines[0]) - return to_unicode(lines[0]) + u"\n" + u"\n".join(map(lambda line: prefix + to_unicode(line), - lines[1:])) + return ( + to_unicode(lines[0]) + + "\n" + + "\n".join(map(lambda line: prefix + to_unicode(line), lines[1:])) + ) diff --git a/src/octoprint/logging/handlers.py b/src/octoprint/logging/handlers.py index 30a9e8e6e..9e8e2fc26 100644 --- a/src/octoprint/logging/handlers.py +++ b/src/octoprint/logging/handlers.py @@ -11,186 +11,187 @@ import concurrent.futures class AsyncLogHandlerMixin(logging.Handler): - def __init__(self, *args, **kwargs): - self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1) - super(AsyncLogHandlerMixin, self).__init__(*args, **kwargs) + def __init__(self, *args, **kwargs): + self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1) + super(AsyncLogHandlerMixin, self).__init__(*args, **kwargs) - def emit(self, record): - if getattr(self._executor, "_shutdown", False): - return + def emit(self, record): + if getattr(self._executor, "_shutdown", False): + return - try: - self._executor.submit(self._emit, record) - except Exception: - self.handleError(record) + try: + self._executor.submit(self._emit, record) + except Exception: + self.handleError(record) - def _emit(self, record): - # noinspection PyUnresolvedReferences - super(AsyncLogHandlerMixin, self).emit(record) + def _emit(self, record): + # noinspection PyUnresolvedReferences + super(AsyncLogHandlerMixin, self).emit(record) - def close(self): - self._executor.shutdown(wait=True) - super(AsyncLogHandlerMixin, self).close() + def close(self): + self._executor.shutdown(wait=True) + super(AsyncLogHandlerMixin, self).close() class CleaningTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler): + def __init__(self, *args, **kwargs): + kwargs["encoding"] = kwargs.get("encoding", "utf-8") - def __init__(self, *args, **kwargs): - kwargs["encoding"] = kwargs.get("encoding", "utf-8") + super(CleaningTimedRotatingFileHandler, self).__init__(*args, **kwargs) - super(CleaningTimedRotatingFileHandler, self).__init__(*args, **kwargs) - - # clean up old files on handler start - if self.backupCount > 0: - for s in self.getFilesToDelete(): - os.remove(s) + # clean up old files on handler start + if self.backupCount > 0: + for s in self.getFilesToDelete(): + os.remove(s) class OctoPrintLogHandler(AsyncLogHandlerMixin, CleaningTimedRotatingFileHandler): - rollover_callbacks = [] + rollover_callbacks = [] - def __init__(self, *args, **kwargs): - kwargs["encoding"] = kwargs.get("encoding", "utf-8") - super(OctoPrintLogHandler, self).__init__(*args, **kwargs) + def __init__(self, *args, **kwargs): + kwargs["encoding"] = kwargs.get("encoding", "utf-8") + super(OctoPrintLogHandler, self).__init__(*args, **kwargs) - @classmethod - def registerRolloverCallback(cls, callback, *args, **kwargs): - cls.rollover_callbacks.append((callback, args, kwargs)) + @classmethod + def registerRolloverCallback(cls, callback, *args, **kwargs): + cls.rollover_callbacks.append((callback, args, kwargs)) - def doRollover(self): - super(OctoPrintLogHandler, self).doRollover() + def doRollover(self): + super(OctoPrintLogHandler, self).doRollover() - for rcb in self.rollover_callbacks: - callback, args, kwargs = rcb - callback(*args, **kwargs) + for rcb in self.rollover_callbacks: + callback, args, kwargs = rcb + callback(*args, **kwargs) class OctoPrintStreamHandler(AsyncLogHandlerMixin, logging.StreamHandler): - pass + pass -class TriggeredRolloverLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFileHandler): +class TriggeredRolloverLogHandler( + AsyncLogHandlerMixin, logging.handlers.RotatingFileHandler +): - do_rollover = False - suffix_template = "%Y-%m-%d_%H-%M-%S" - file_pattern = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$") + do_rollover = False + suffix_template = "%Y-%m-%d_%H-%M-%S" + file_pattern = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$") - @classmethod - def arm_rollover(cls): - cls.do_rollover = True + @classmethod + def arm_rollover(cls): + cls.do_rollover = True - def __init__(self, *args, **kwargs): - kwargs["encoding"] = kwargs.get("encoding", "utf-8") - super(TriggeredRolloverLogHandler, self).__init__(*args, **kwargs) - self.cleanupFiles() + def __init__(self, *args, **kwargs): + kwargs["encoding"] = kwargs.get("encoding", "utf-8") + super(TriggeredRolloverLogHandler, self).__init__(*args, **kwargs) + self.cleanupFiles() - def shouldRollover(self, record): - return self.do_rollover + def shouldRollover(self, record): + return self.do_rollover - def getFilesToDelete(self): - """ - Determine the files to delete when rolling over. - """ - dirName, baseName = os.path.split(self.baseFilename) - fileNames = os.listdir(dirName) - result = [] - prefix = baseName + "." - plen = len(prefix) - for fileName in fileNames: - if fileName[:plen] == prefix: - suffix = fileName[plen:] - if type(self).file_pattern.match(suffix): - result.append(os.path.join(dirName, fileName)) - result.sort() - if len(result) < self.backupCount: - result = [] - else: - result = result[:len(result) - self.backupCount] - return result + def getFilesToDelete(self): + """ + Determine the files to delete when rolling over. + """ + dirName, baseName = os.path.split(self.baseFilename) + fileNames = os.listdir(dirName) + result = [] + prefix = baseName + "." + plen = len(prefix) + for fileName in fileNames: + if fileName[:plen] == prefix: + suffix = fileName[plen:] + if type(self).file_pattern.match(suffix): + result.append(os.path.join(dirName, fileName)) + result.sort() + if len(result) < self.backupCount: + result = [] + else: + result = result[: len(result) - self.backupCount] + return result - def cleanupFiles(self): - if self.backupCount > 0: - for path in self.getFilesToDelete(): - os.remove(path) + def cleanupFiles(self): + if self.backupCount > 0: + for path in self.getFilesToDelete(): + os.remove(path) - def doRollover(self): - self.do_rollover = False + def doRollover(self): + self.do_rollover = False - if self.stream: - self.stream.close() - self.stream = None + if self.stream: + self.stream.close() + self.stream = None - if os.path.exists(self.baseFilename): - # figure out creation date/time to use for file suffix - t = time.localtime(os.stat(self.baseFilename).st_mtime) - dfn = self.baseFilename + "." + time.strftime(type(self).suffix_template, t) - if os.path.exists(dfn): - os.remove(dfn) - os.rename(self.baseFilename, dfn) + if os.path.exists(self.baseFilename): + # figure out creation date/time to use for file suffix + t = time.localtime(os.stat(self.baseFilename).st_mtime) + dfn = self.baseFilename + "." + time.strftime(type(self).suffix_template, t) + if os.path.exists(dfn): + os.remove(dfn) + os.rename(self.baseFilename, dfn) - self.cleanupFiles() - if not self.delay: - self.stream = self._open() + self.cleanupFiles() + if not self.delay: + self.stream = self._open() class SerialLogHandler(TriggeredRolloverLogHandler): - pass + pass class PluginTimingsLogHandler(TriggeredRolloverLogHandler): - pass + pass class RecordingLogHandler(logging.Handler): - def __init__(self, target=None, *args, **kwargs): - super(RecordingLogHandler, self).__init__(*args, **kwargs) - self._buffer = [] - self._target = target + def __init__(self, target=None, *args, **kwargs): + super(RecordingLogHandler, self).__init__(*args, **kwargs) + self._buffer = [] + self._target = target - def emit(self, record): - self._buffer.append(record) + def emit(self, record): + self._buffer.append(record) - def setTarget(self, target): - self._target = target + def setTarget(self, target): + self._target = target - def flush(self): - if not self._target: - return + def flush(self): + if not self._target: + return - self.acquire() - try: - for record in self._buffer: - self._target.handle(record) - self._buffer = [] - finally: - self.release() + self.acquire() + try: + for record in self._buffer: + self._target.handle(record) + self._buffer = [] + finally: + self.release() - def close(self): - self.flush() - self.acquire() - try: - self._buffer = [] - finally: - self.release() + def close(self): + self.flush() + self.acquire() + try: + self._buffer = [] + finally: + self.release() - def __len__(self): - return len(self._buffer) + def __len__(self): + return len(self._buffer) # noinspection PyAbstractClass class CombinedLogHandler(logging.Handler): - def __init__(self, *handlers): - logging.Handler.__init__(self) - self._handlers = handlers + def __init__(self, *handlers): + logging.Handler.__init__(self) + self._handlers = handlers - def setHandlers(self, *handlers): - self._handlers = handlers + def setHandlers(self, *handlers): + self._handlers = handlers - def handle(self, record): - self.acquire() - try: - if self._handlers: - for handler in self._handlers: - handler.handle(record) - finally: - self.release() + def handle(self, record): + self.acquire() + try: + if self._handlers: + for handler in self._handlers: + handler.handle(record) + finally: + self.release() diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index 1637fa34e..1dbdf6d43 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -16,7 +16,7 @@ registered plugin types. """ __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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 os @@ -24,7 +24,7 @@ import logging import threading from octoprint.settings import settings as s -from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin) +from octoprint.plugin.core import PluginInfo, PluginManager, Plugin from octoprint.plugin.types import OctoPrintPlugin, SettingsPlugin from octoprint.plugin.types import * # noqa: F403 ## used by multiple other modules @@ -33,528 +33,598 @@ from octoprint.util import deprecated, to_native_str # singleton _instance = None + def _validate_plugin(phase, plugin_info): - return True - -def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_entry_points=None, plugin_disabled_list=None, - plugin_blacklist=None, plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, - plugin_considered_bundled=None, plugin_validators=None, compatibility_ignored_list=None): - """ - Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager` - singleton. - - Arguments: - init (boolean): A flag indicating whether this is the initial call to construct the singleton (True) or not - (False, default). If this is set to True and the plugin manager has already been initialized, a :class:`ValueError` - will be raised. The same will happen if the plugin manager has not yet been initialized and this is set to - False. - plugin_folders (list): A list of folders (as strings containing the absolute path to them) in which to look for - potential plugin modules. If not provided this defaults to the configured ``plugins`` base folder and - ``src/plugins`` within OctoPrint's code base. - plugin_bases (list): A list of recognized plugin base classes for which to look for provided implementations. If not - provided this defaults to :class:`~octoprint.plugin.OctoPrintPlugin`. - plugin_entry_points (list): A list of entry points pointing to modules which to load as plugins. If not provided - this defaults to the entry point ``octoprint.plugin``. - plugin_disabled_list (list): A list of plugin identifiers that are currently disabled. If not provided this - defaults to all plugins for which ``enabled`` is set to ``False`` in the settings. - plugin_blacklist (list): A list of plugin identifiers/identifier-version tuples that are currently blacklisted. - plugin_restart_needing_hooks (list): A list of hook namespaces which cause a plugin to need a restart in order - be enabled/disabled. Does not have to contain full hook identifiers, will be matched with startswith similar - to logging handlers - plugin_obsolete_hooks (list): A list of hooks that have been declared obsolete. Plugins implementing them will - not be enabled since they might depend on functionality that is no longer available. - plugin_considered_bundled (list): A list of plugin identifiers that are considered bundled plugins even if - installed separately. - plugin_validators (list): A list of additional plugin validators through which to process each plugin. - compatibility_ignored_list (list): A list of plugin keys for which it will be ignored if they are flagged as - incompatible. This is for development purposes only and should not be used in production. - - Returns: - PluginManager: A fully initialized :class:`~octoprint.plugin.core.PluginManager` instance to be used for plugin - management tasks. - - Raises: - ValueError: ``init`` was True although the plugin manager was already initialized, or it was False although - the plugin manager was not yet initialized. - """ - - global _instance - if _instance is not None: - if init: - raise ValueError("Plugin Manager already initialized") - - else: - if init: - if plugin_bases is None: - plugin_bases = [OctoPrintPlugin] - - if plugin_restart_needing_hooks is None: - plugin_restart_needing_hooks = ["octoprint.server.http.*", - "octoprint.printer.factory", - "octoprint.access.permissions", - "octoprint.timelapse.extensions"] - - if plugin_obsolete_hooks is None: - plugin_obsolete_hooks = ["octoprint.comm.protocol.gcode"] - - if plugin_considered_bundled is None: - plugin_considered_bundled = ["firmware_check", "file_check"] - - if plugin_validators is None: - plugin_validators = [_validate_plugin] - else: - plugin_validators.append(_validate_plugin) - - _instance = PluginManager(plugin_folders, - plugin_bases, - plugin_entry_points, - logging_prefix="octoprint.plugins.", - plugin_disabled_list=plugin_disabled_list, - plugin_blacklist=plugin_blacklist, - plugin_restart_needing_hooks=plugin_restart_needing_hooks, - plugin_obsolete_hooks=plugin_obsolete_hooks, - plugin_considered_bundled=plugin_considered_bundled, - plugin_validators=plugin_validators, - compatibility_ignored_list=compatibility_ignored_list) - else: - raise ValueError("Plugin Manager not initialized yet") - return _instance + return True -def plugin_settings(plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None, settings=None): - """ - Factory method for creating a :class:`PluginSettings` instance. +def plugin_manager( + init=False, + plugin_folders=None, + plugin_bases=None, + plugin_entry_points=None, + plugin_disabled_list=None, + plugin_blacklist=None, + plugin_restart_needing_hooks=None, + plugin_obsolete_hooks=None, + plugin_considered_bundled=None, + plugin_validators=None, + compatibility_ignored_list=None, +): + """ + Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager` + singleton. - Arguments: - plugin_key (string): The plugin identifier for which to create the settings instance. - defaults (dict): The default settings for the plugin, if different from get_settings_defaults. - get_preprocessors (dict): The getter preprocessors for the plugin. - set_preprocessors (dict): The setter preprocessors for the plugin. - settings (octoprint.settings.Settings): The settings instance to use. + Arguments: + init (boolean): A flag indicating whether this is the initial call to construct the singleton (True) or not + (False, default). If this is set to True and the plugin manager has already been initialized, a :class:`ValueError` + will be raised. The same will happen if the plugin manager has not yet been initialized and this is set to + False. + plugin_folders (list): A list of folders (as strings containing the absolute path to them) in which to look for + potential plugin modules. If not provided this defaults to the configured ``plugins`` base folder and + ``src/plugins`` within OctoPrint's code base. + plugin_bases (list): A list of recognized plugin base classes for which to look for provided implementations. If not + provided this defaults to :class:`~octoprint.plugin.OctoPrintPlugin`. + plugin_entry_points (list): A list of entry points pointing to modules which to load as plugins. If not provided + this defaults to the entry point ``octoprint.plugin``. + plugin_disabled_list (list): A list of plugin identifiers that are currently disabled. If not provided this + defaults to all plugins for which ``enabled`` is set to ``False`` in the settings. + plugin_blacklist (list): A list of plugin identifiers/identifier-version tuples that are currently blacklisted. + plugin_restart_needing_hooks (list): A list of hook namespaces which cause a plugin to need a restart in order + be enabled/disabled. Does not have to contain full hook identifiers, will be matched with startswith similar + to logging handlers + plugin_obsolete_hooks (list): A list of hooks that have been declared obsolete. Plugins implementing them will + not be enabled since they might depend on functionality that is no longer available. + plugin_considered_bundled (list): A list of plugin identifiers that are considered bundled plugins even if + installed separately. + plugin_validators (list): A list of additional plugin validators through which to process each plugin. + compatibility_ignored_list (list): A list of plugin keys for which it will be ignored if they are flagged as + incompatible. This is for development purposes only and should not be used in production. - Returns: - PluginSettings: A fully initialized :class:`PluginSettings` instance to be used to access the plugin's - settings - """ - if settings is None: - settings = s() - return PluginSettings(settings, plugin_key, defaults=defaults, - get_preprocessors=get_preprocessors, - set_preprocessors=set_preprocessors) + Returns: + PluginManager: A fully initialized :class:`~octoprint.plugin.core.PluginManager` instance to be used for plugin + management tasks. + + Raises: + ValueError: ``init`` was True although the plugin manager was already initialized, or it was False although + the plugin manager was not yet initialized. + """ + + global _instance + if _instance is not None: + if init: + raise ValueError("Plugin Manager already initialized") + + else: + if init: + if plugin_bases is None: + plugin_bases = [OctoPrintPlugin] + + if plugin_restart_needing_hooks is None: + plugin_restart_needing_hooks = [ + "octoprint.server.http.*", + "octoprint.printer.factory", + "octoprint.access.permissions", + "octoprint.timelapse.extensions", + ] + + if plugin_obsolete_hooks is None: + plugin_obsolete_hooks = ["octoprint.comm.protocol.gcode"] + + if plugin_considered_bundled is None: + plugin_considered_bundled = ["firmware_check", "file_check"] + + if plugin_validators is None: + plugin_validators = [_validate_plugin] + else: + plugin_validators.append(_validate_plugin) + + _instance = PluginManager( + plugin_folders, + plugin_bases, + plugin_entry_points, + logging_prefix="octoprint.plugins.", + plugin_disabled_list=plugin_disabled_list, + plugin_blacklist=plugin_blacklist, + plugin_restart_needing_hooks=plugin_restart_needing_hooks, + plugin_obsolete_hooks=plugin_obsolete_hooks, + plugin_considered_bundled=plugin_considered_bundled, + plugin_validators=plugin_validators, + compatibility_ignored_list=compatibility_ignored_list, + ) + else: + raise ValueError("Plugin Manager not initialized yet") + return _instance + + +def plugin_settings( + plugin_key, + defaults=None, + get_preprocessors=None, + set_preprocessors=None, + settings=None, +): + """ + Factory method for creating a :class:`PluginSettings` instance. + + Arguments: + plugin_key (string): The plugin identifier for which to create the settings instance. + defaults (dict): The default settings for the plugin, if different from get_settings_defaults. + get_preprocessors (dict): The getter preprocessors for the plugin. + set_preprocessors (dict): The setter preprocessors for the plugin. + settings (octoprint.settings.Settings): The settings instance to use. + + Returns: + PluginSettings: A fully initialized :class:`PluginSettings` instance to be used to access the plugin's + settings + """ + if settings is None: + settings = s() + return PluginSettings( + settings, + plugin_key, + defaults=defaults, + get_preprocessors=get_preprocessors, + set_preprocessors=set_preprocessors, + ) def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None): - """ - Factory method for creating a :class:`PluginSettings` instance for a given :class:`SettingsPlugin` instance. + """ + Factory method for creating a :class:`PluginSettings` instance for a given :class:`SettingsPlugin` instance. - Will return `None` if the provided `instance` is not a :class:`SettingsPlugin` instance. + Will return `None` if the provided `instance` is not a :class:`SettingsPlugin` instance. - Arguments: - plugin_key (string): The plugin identifier for which to create the settings instance. - implementation (octoprint.plugin.SettingsPlugin): The :class:`SettingsPlugin` instance. - settings (octoprint.settings.Settings): The settings instance to use. Defaults to the global OctoPrint settings. + Arguments: + plugin_key (string): The plugin identifier for which to create the settings instance. + implementation (octoprint.plugin.SettingsPlugin): The :class:`SettingsPlugin` instance. + settings (octoprint.settings.Settings): The settings instance to use. Defaults to the global OctoPrint settings. - Returns: - PluginSettings or None: A fully initialized :class:`PluginSettings` instance to be used to access the plugin's - settings, or `None` if the provided `instance` was not a class:`SettingsPlugin` - """ - if not isinstance(instance, SettingsPlugin): - return None + Returns: + PluginSettings or None: A fully initialized :class:`PluginSettings` instance to be used to access the plugin's + settings, or `None` if the provided `instance` was not a class:`SettingsPlugin` + """ + if not isinstance(instance, SettingsPlugin): + return None - try: - get_preprocessors, set_preprocessors = instance.get_settings_preprocessors() - except Exception: - logging.getLogger(__name__).exception("Error while retrieving preprocessors for plugin {}".format(plugin_key)) - return None + try: + get_preprocessors, set_preprocessors = instance.get_settings_preprocessors() + except Exception: + logging.getLogger(__name__).exception( + "Error while retrieving preprocessors for plugin {}".format(plugin_key) + ) + return None - return plugin_settings(plugin_key, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings) + return plugin_settings( + plugin_key, + get_preprocessors=get_preprocessors, + set_preprocessors=set_preprocessors, + settings=settings, + ) -def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None, - initialized=True): - """ - Helper method to invoke the indicated ``method`` on all registered plugin implementations implementing the - indicated ``types``. Allows providing method arguments and registering callbacks to call in case of success - and/or failure of each call which can be used to return individual results to the calling code. +def call_plugin( + types, + method, + args=None, + kwargs=None, + callback=None, + error_callback=None, + sorting_context=None, + initialized=True, +): + """ + Helper method to invoke the indicated ``method`` on all registered plugin implementations implementing the + indicated ``types``. Allows providing method arguments and registering callbacks to call in case of success + and/or failure of each call which can be used to return individual results to the calling code. - Example: + Example: - .. sourcecode:: python + .. sourcecode:: python - def my_success_callback(name, plugin, result): - print("{name} was called successfully and returned {result!r}".format(**locals())) + def my_success_callback(name, plugin, result): + print("{name} was called successfully and returned {result!r}".format(**locals())) - def my_error_callback(name, plugin, exc): - print("{name} raised an exception: {exc!s}".format(**locals())) + def my_error_callback(name, plugin, exc): + print("{name} raised an exception: {exc!s}".format(**locals())) - octoprint.plugin.call_plugin( - [octoprint.plugin.StartupPlugin], - "on_startup", - args=(my_host, my_port), - callback=my_success_callback, - error_callback=my_error_callback - ) + octoprint.plugin.call_plugin( + [octoprint.plugin.StartupPlugin], + "on_startup", + args=(my_host, my_port), + callback=my_success_callback, + error_callback=my_error_callback + ) - Arguments: - types (list): A list of plugin implementation types to match against. - method (string): Name of the method to call on all matching implementations. - args (tuple): A tuple containing the arguments to supply to the called ``method``. Optional. - kwargs (dict): A dictionary containing the keyword arguments to supply to the called ``method``. Optional. - callback (function): A callback to invoke after an implementation has been called successfully. Will be called - with the three arguments ``name``, ``plugin`` and ``result``. ``name`` will be the plugin identifier, - ``plugin`` the plugin implementation instance itself and ``result`` the result returned from the - ``method`` invocation. - error_callback (function): A callback to invoke after the call of an implementation resulted in an exception. - Will be called with the three arguments ``name``, ``plugin`` and ``exc``. ``name`` will be the plugin - identifier, ``plugin`` the plugin implementation instance itself and ``exc`` the caught exception. - initialized (boolean): Ignored. - """ + Arguments: + types (list): A list of plugin implementation types to match against. + method (string): Name of the method to call on all matching implementations. + args (tuple): A tuple containing the arguments to supply to the called ``method``. Optional. + kwargs (dict): A dictionary containing the keyword arguments to supply to the called ``method``. Optional. + callback (function): A callback to invoke after an implementation has been called successfully. Will be called + with the three arguments ``name``, ``plugin`` and ``result``. ``name`` will be the plugin identifier, + ``plugin`` the plugin implementation instance itself and ``result`` the result returned from the + ``method`` invocation. + error_callback (function): A callback to invoke after the call of an implementation resulted in an exception. + Will be called with the three arguments ``name``, ``plugin`` and ``exc``. ``name`` will be the plugin + identifier, ``plugin`` the plugin implementation instance itself and ``exc`` the caught exception. + initialized (boolean): Ignored. + """ - if not isinstance(types, (list, tuple)): - types = [types] - if args is None: - args = [] - if kwargs is None: - kwargs = {} + if not isinstance(types, (list, tuple)): + types = [types] + if args is None: + args = [] + if kwargs is None: + kwargs = {} - logger = logging.getLogger(__name__) + logger = logging.getLogger(__name__) - plugins = plugin_manager().get_implementations(*types, sorting_context=sorting_context) - for plugin in plugins: - if not hasattr(plugin, "_identifier"): - continue + plugins = plugin_manager().get_implementations( + *types, sorting_context=sorting_context + ) + for plugin in plugins: + if not hasattr(plugin, "_identifier"): + continue - if hasattr(plugin, method): - logger.debug("Calling {} on {}".format(method, plugin._identifier)) - try: - result = getattr(plugin, method)(*args, **kwargs) - if callback: - callback(plugin._identifier, plugin, result) - except Exception as exc: - logger.exception("Error while calling plugin %s" % plugin._identifier, - extra={"plugin": plugin._identifier}) - if error_callback: - error_callback(plugin._identifier, plugin, exc) + if hasattr(plugin, method): + logger.debug("Calling {} on {}".format(method, plugin._identifier)) + try: + result = getattr(plugin, method)(*args, **kwargs) + if callback: + callback(plugin._identifier, plugin, result) + except Exception as exc: + logger.exception( + "Error while calling plugin %s" % plugin._identifier, + extra={"plugin": plugin._identifier}, + ) + if error_callback: + error_callback(plugin._identifier, plugin, exc) class PluginSettings(object): - """ - The :class:`PluginSettings` class is the interface for plugins to their own or globally defined settings. + """ + The :class:`PluginSettings` class is the interface for plugins to their own or globally defined settings. - It provides some convenience methods for directly accessing plugin settings via the regular - :class:`octoprint.settings.Settings` interfaces as well as means to access plugin specific folder locations. + It provides some convenience methods for directly accessing plugin settings via the regular + :class:`octoprint.settings.Settings` interfaces as well as means to access plugin specific folder locations. - All getter and setter methods will ensure that plugin settings are stored in their correct location within the - settings structure by modifying the supplied paths accordingly. + All getter and setter methods will ensure that plugin settings are stored in their correct location within the + settings structure by modifying the supplied paths accordingly. - Arguments: - settings (Settings): The :class:`~octoprint.settings.Settings` instance on which to operate. - plugin_key (str): The plugin identifier of the plugin for which to create this instance. - defaults (dict): The plugin's defaults settings, will be used to determine valid paths within the plugin's - settings structure + Arguments: + settings (Settings): The :class:`~octoprint.settings.Settings` instance on which to operate. + plugin_key (str): The plugin identifier of the plugin for which to create this instance. + defaults (dict): The plugin's defaults settings, will be used to determine valid paths within the plugin's + settings structure - .. method:: get(path, merged=False, asdict=False) + .. method:: get(path, merged=False, asdict=False) - Retrieves a raw value from the settings for ``path``, optionally merging the raw value with the default settings - if ``merged`` is set to True. + Retrieves a raw value from the settings for ``path``, optionally merging the raw value with the default settings + if ``merged`` is set to True. - :param path: The path for which to retrieve the value. - :type path: list, tuple - :param boolean merged: Whether to merge the returned result with the default settings (True) or not (False, - default). - :returns: The retrieved settings value. - :rtype: object + :param path: The path for which to retrieve the value. + :type path: list, tuple + :param boolean merged: Whether to merge the returned result with the default settings (True) or not (False, + default). + :returns: The retrieved settings value. + :rtype: object - .. method:: get_int(path, min=None, max=None) + .. method:: get_int(path, min=None, max=None) - Like :func:`get` but tries to convert the retrieved value to ``int``. If ``min`` is provided and the retrieved - value is less than it, it will be returned instead of the value. Likewise for ``max`` - it will be returned if - the value is greater than it. + Like :func:`get` but tries to convert the retrieved value to ``int``. If ``min`` is provided and the retrieved + value is less than it, it will be returned instead of the value. Likewise for ``max`` - it will be returned if + the value is greater than it. - .. method:: get_float(path, min=None, max=None) + .. method:: get_float(path, min=None, max=None) - Like :func:`get` but tries to convert the retrieved value to ``float``. If ``min`` is provided and the retrieved - value is less than it, it will be returned instead of the value. Likewise for ``max`` - it will be returned if - the value is greater than it. + Like :func:`get` but tries to convert the retrieved value to ``float``. If ``min`` is provided and the retrieved + value is less than it, it will be returned instead of the value. Likewise for ``max`` - it will be returned if + the value is greater than it. - .. method:: get_boolean(path) + .. method:: get_boolean(path) - Like :func:`get` but tries to convert the retrieved value to ``boolean``. + Like :func:`get` but tries to convert the retrieved value to ``boolean``. - .. method:: set(path, value, force=False) + .. method:: set(path, value, force=False) - Sets the raw value on the settings for ``path``. + Sets the raw value on the settings for ``path``. - :param path: The path for which to retrieve the value. - :type path: list, tuple - :param object value: The value to set. - :param boolean force: If set to True, the modified configuration will even be written back to disk if - the value didn't change. - - .. method:: set_int(path, value, force=False, min=None, max=None) - - Like :func:`set` but ensures the value is an ``int`` through attempted conversion before setting it. - If ``min`` and/or ``max`` are provided, it will also be ensured that the value is greater than or equal - to ``min`` and less than or equal to ``max``. If that is not the case, the limit value (``min`` if less than - that, ``max`` if greater than that) will be set instead. - - .. method:: set_float(path, value, force=False, min=None, max=None) - - Like :func:`set` but ensures the value is an ``float`` through attempted conversion before setting it. - If ``min`` and/or ``max`` are provided, it will also be ensured that the value is greater than or equal - to ``min`` and less than or equal to ``max``. If that is not the case, the limit value (``min`` if less than - that, ``max`` if greater than that) will be set instead. - - .. method:: set_boolean(path, value, force=False) - - Like :func:`set` but ensures the value is an ``boolean`` through attempted conversion before setting it. - - .. method:: save(force=False, trigger_event=False) - - Saves the settings to ``config.yaml`` if there are active changes. If ``force`` is set to ``True`` the settings - will be saved even if there are no changes. Settings ``trigger_event`` to ``True`` will cause a ``SettingsUpdated`` - :ref:`event ` to get triggered. - - :param force: Force saving to ``config.yaml`` even if there are no changes. - :type force: boolean - :param trigger_event: Trigger the ``SettingsUpdated`` :ref:`event ` on save. - :type trigger_event: boolean - - .. method:: add_overlay(overlay, at_end=False, key=None) - - Adds a new config overlay for the plugin's settings. Will return the overlay's key in the map. - - :param overlay: Overlay dict to add - :type overlay: dict - :param at_end: Whether to add overlay at end or start (default) of config hierarchy - :type at_end: boolean - :param key: Key to use to identify overlay. If not set one will be built based on the overlay's hash - :type key: str - :rtype: str - - .. method:: remove_overlay(key) - - Removes an overlay from the settings based on its key. Return ``True`` if the overlay could be found and was - removed, ``False`` otherwise. - - :param key: The key of the overlay to remove - :type key: str - :rtype: boolean - """ - - def __init__(self, settings, plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None): - self.settings = settings - self.plugin_key = plugin_key - - if defaults is not None: - self.defaults = {"plugins": {}} - self.defaults["plugins"][plugin_key] = defaults - self.defaults["plugins"][plugin_key]["_config_version"] = None - else: - self.defaults = None - - if get_preprocessors is None: - get_preprocessors = {} - self.get_preprocessors = {"plugins": {}} - self.get_preprocessors["plugins"][plugin_key] = get_preprocessors - - if set_preprocessors is None: - set_preprocessors = {} - self.set_preprocessors = {"plugins": {}} - self.set_preprocessors["plugins"][plugin_key] = set_preprocessors - - def prefix_path_in_args(args, index=0): - result = [] - if index == 0: - result.append(self._prefix_path(args[0])) - result.extend(args[1:]) - else: - args_before = args[:index - 1] - args_after = args[index + 1:] - result.extend(args_before) - result.append(self._prefix_path(args[index])) - result.extend(args_after) - return result - - def add_getter_kwargs(kwargs): - if not "defaults" in kwargs and self.defaults is not None: - kwargs.update(defaults=self.defaults) - if not "preprocessors" in kwargs: - kwargs.update(preprocessors=self.get_preprocessors) - return kwargs - - def add_setter_kwargs(kwargs): - if not "defaults" in kwargs and self.defaults is not None: - kwargs.update(defaults=self.defaults) - if not "preprocessors" in kwargs: - kwargs.update(preprocessors=self.set_preprocessors) - return kwargs - - def wrap_overlay(args): - result = list(args) - overlay = result[0] - result[0] = {"plugins": {plugin_key: overlay}} - return result - - self.access_methods = {"has": ("has", prefix_path_in_args, add_getter_kwargs), - "get": ("get", prefix_path_in_args, add_getter_kwargs), - "get_int": ("getInt", prefix_path_in_args, add_getter_kwargs), - "get_float": ("getFloat", prefix_path_in_args, add_getter_kwargs), - "get_boolean": ("getBoolean", prefix_path_in_args, add_getter_kwargs), - "set": ("set", prefix_path_in_args, add_setter_kwargs), - "set_int": ("setInt", prefix_path_in_args, add_setter_kwargs), - "set_float": ("setFloat", prefix_path_in_args, add_setter_kwargs), - "set_boolean": ("setBoolean", prefix_path_in_args, add_setter_kwargs), - "remove": ("remove", prefix_path_in_args, lambda x: x), - "add_overlay": ("add_overlay", wrap_overlay, lambda x: x), - "remove_overlay": ("remove_overlay", lambda x: x, lambda x: x)} - self.deprecated_access_methods = {"getInt": "get_int", - "getFloat": "get_float", - "getBoolean": "get_boolean", - "setInt": "set_int", - "setFloat": "set_float", - "setBoolean": "set_boolean"} - - def _prefix_path(self, path=None): - if path is None: - path = list() - return ['plugins', self.plugin_key] + path - - def global_has(self, path, **kwargs): - return self.settings.has(path, **kwargs) - - def global_remove(self, path, **kwargs): - return self.settings.remove(path, **kwargs) - - def global_get(self, path, **kwargs): - """ - Getter for retrieving settings not managed by the plugin itself from the core settings structure. Use this - to access global settings outside of your plugin. - - Directly forwards to :func:`octoprint.settings.Settings.get`. - """ - return self.settings.get(path, **kwargs) - - def global_get_int(self, path, **kwargs): - """ - Like :func:`global_get` but directly forwards to :func:`octoprint.settings.Settings.getInt`. - """ - return self.settings.getInt(path, **kwargs) - - def global_get_float(self, path, **kwargs): - """ - Like :func:`global_get` but directly forwards to :func:`octoprint.settings.Settings.getFloat`. - """ - return self.settings.getFloat(path, **kwargs) - - def global_get_boolean(self, path, **kwargs): - """ - Like :func:`global_get` but directly orwards to :func:`octoprint.settings.Settings.getBoolean`. - """ - return self.settings.getBoolean(path, **kwargs) - - def global_set(self, path, value, **kwargs): - """ - Setter for modifying settings not managed by the plugin itself on the core settings structure. Use this - to modify global settings outside of your plugin. - - Directly forwards to :func:`octoprint.settings.Settings.set`. - """ - self.settings.set(path, value, **kwargs) - - def global_set_int(self, path, value, **kwargs): - """ - Like :func:`global_set` but directly forwards to :func:`octoprint.settings.Settings.setInt`. - """ - self.settings.setInt(path, value, **kwargs) - - def global_set_float(self, path, value, **kwargs): - """ - Like :func:`global_set` but directly forwards to :func:`octoprint.settings.Settings.setFloat`. - """ - self.settings.setFloat(path, value, **kwargs) - - def global_set_boolean(self, path, value, **kwargs): - """ - Like :func:`global_set` but directly forwards to :func:`octoprint.settings.Settings.setBoolean`. - """ - self.settings.setBoolean(path, value, **kwargs) - - def global_get_basefolder(self, folder_type, **kwargs): - """ - Retrieves a globally defined basefolder of the given ``folder_type``. Directly forwards to - :func:`octoprint.settings.Settings.getBaseFolder`. - """ - return self.settings.getBaseFolder(folder_type, **kwargs) - - def get_plugin_logfile_path(self, postfix=None): - """ - Retrieves the path to a logfile specifically for the plugin. If ``postfix`` is not supplied, the logfile - will be named ``plugin_.log`` and located within the configured ``logs`` folder. If a - postfix is supplied, the name will be ``plugin__.log`` at the same location. - - Plugins may use this for specific logging tasks. For example, a :class:`~octoprint.plugin.SlicingPlugin` might - want to create a log file for logging the output of the slicing engine itself if some debug flag is set. - - Arguments: - postfix (str): Postfix of the logfile for which to create the path. If set, the file name of the log file - will be ``plugin__.log``, if not it will be - ``plugin_.log``. - - Returns: - str: Absolute path to the log file, directly usable by the plugin. - """ - filename = "plugin_" + self.plugin_key - if postfix is not None: - filename += "_" + postfix - filename += ".log" - return os.path.join(self.settings.getBaseFolder("logs"), filename) - - @deprecated("PluginSettings.get_plugin_data_folder has been replaced by OctoPrintPlugin.get_plugin_data_folder", - includedoc="Replaced by :func:`~octoprint.plugin.types.OctoPrintPlugin.get_plugin_data_folder`", - since="1.2.0") - def get_plugin_data_folder(self): - path = os.path.join(self.settings.getBaseFolder("data"), self.plugin_key) - if not os.path.isdir(path): - os.makedirs(path) - return path - - def get_all_data(self, **kwargs): - merged = kwargs.get("merged", True) - asdict = kwargs.get("asdict", True) - defaults = kwargs.get("defaults", self.defaults) - preprocessors = kwargs.get("preprocessors", self.get_preprocessors) - - kwargs.update({"merged": merged, - "asdict": asdict, - "defaults": defaults, - "preprocessors": preprocessors}) - - return self.settings.get(self._prefix_path(), **kwargs) - - def clean_all_data(self): - self.settings.remove(self._prefix_path()) - - def __getattr__(self, item): - all_access_methods = list(self.access_methods.keys()) + list(self.deprecated_access_methods.keys()) - if item in all_access_methods: - decorator = None - if item in self.deprecated_access_methods: - new = self.deprecated_access_methods[item] - decorator = deprecated("{old} has been renamed to {new}".format(old=item, new=new), stacklevel=2) - item = new - - settings_name, args_mapper, kwargs_mapper = self.access_methods[item] - if hasattr(self.settings, settings_name) and callable(getattr(self.settings, settings_name)): - orig_func = getattr(self.settings, settings_name) - if decorator is not None: - orig_func = decorator(orig_func) - - def _func(*args, **kwargs): - return orig_func(*args_mapper(args), **kwargs_mapper(kwargs)) - _func.__name__ = to_native_str(item) - _func.__doc__ = orig_func.__doc__ if "__doc__" in dir(orig_func) else None - - return _func - - return getattr(self.settings, item) + :param path: The path for which to retrieve the value. + :type path: list, tuple + :param object value: The value to set. + :param boolean force: If set to True, the modified configuration will even be written back to disk if + the value didn't change. + + .. method:: set_int(path, value, force=False, min=None, max=None) + + Like :func:`set` but ensures the value is an ``int`` through attempted conversion before setting it. + If ``min`` and/or ``max`` are provided, it will also be ensured that the value is greater than or equal + to ``min`` and less than or equal to ``max``. If that is not the case, the limit value (``min`` if less than + that, ``max`` if greater than that) will be set instead. + + .. method:: set_float(path, value, force=False, min=None, max=None) + + Like :func:`set` but ensures the value is an ``float`` through attempted conversion before setting it. + If ``min`` and/or ``max`` are provided, it will also be ensured that the value is greater than or equal + to ``min`` and less than or equal to ``max``. If that is not the case, the limit value (``min`` if less than + that, ``max`` if greater than that) will be set instead. + + .. method:: set_boolean(path, value, force=False) + + Like :func:`set` but ensures the value is an ``boolean`` through attempted conversion before setting it. + + .. method:: save(force=False, trigger_event=False) + + Saves the settings to ``config.yaml`` if there are active changes. If ``force`` is set to ``True`` the settings + will be saved even if there are no changes. Settings ``trigger_event`` to ``True`` will cause a ``SettingsUpdated`` + :ref:`event ` to get triggered. + + :param force: Force saving to ``config.yaml`` even if there are no changes. + :type force: boolean + :param trigger_event: Trigger the ``SettingsUpdated`` :ref:`event ` on save. + :type trigger_event: boolean + + .. method:: add_overlay(overlay, at_end=False, key=None) + + Adds a new config overlay for the plugin's settings. Will return the overlay's key in the map. + + :param overlay: Overlay dict to add + :type overlay: dict + :param at_end: Whether to add overlay at end or start (default) of config hierarchy + :type at_end: boolean + :param key: Key to use to identify overlay. If not set one will be built based on the overlay's hash + :type key: str + :rtype: str + + .. method:: remove_overlay(key) + + Removes an overlay from the settings based on its key. Return ``True`` if the overlay could be found and was + removed, ``False`` otherwise. + + :param key: The key of the overlay to remove + :type key: str + :rtype: boolean + """ + + def __init__( + self, + settings, + plugin_key, + defaults=None, + get_preprocessors=None, + set_preprocessors=None, + ): + self.settings = settings + self.plugin_key = plugin_key + + if defaults is not None: + self.defaults = {"plugins": {}} + self.defaults["plugins"][plugin_key] = defaults + self.defaults["plugins"][plugin_key]["_config_version"] = None + else: + self.defaults = None + + if get_preprocessors is None: + get_preprocessors = {} + self.get_preprocessors = {"plugins": {}} + self.get_preprocessors["plugins"][plugin_key] = get_preprocessors + + if set_preprocessors is None: + set_preprocessors = {} + self.set_preprocessors = {"plugins": {}} + self.set_preprocessors["plugins"][plugin_key] = set_preprocessors + + def prefix_path_in_args(args, index=0): + result = [] + if index == 0: + result.append(self._prefix_path(args[0])) + result.extend(args[1:]) + else: + args_before = args[: index - 1] + args_after = args[index + 1 :] + result.extend(args_before) + result.append(self._prefix_path(args[index])) + result.extend(args_after) + return result + + def add_getter_kwargs(kwargs): + if not "defaults" in kwargs and self.defaults is not None: + kwargs.update(defaults=self.defaults) + if not "preprocessors" in kwargs: + kwargs.update(preprocessors=self.get_preprocessors) + return kwargs + + def add_setter_kwargs(kwargs): + if not "defaults" in kwargs and self.defaults is not None: + kwargs.update(defaults=self.defaults) + if not "preprocessors" in kwargs: + kwargs.update(preprocessors=self.set_preprocessors) + return kwargs + + def wrap_overlay(args): + result = list(args) + overlay = result[0] + result[0] = {"plugins": {plugin_key: overlay}} + return result + + self.access_methods = { + "has": ("has", prefix_path_in_args, add_getter_kwargs), + "get": ("get", prefix_path_in_args, add_getter_kwargs), + "get_int": ("getInt", prefix_path_in_args, add_getter_kwargs), + "get_float": ("getFloat", prefix_path_in_args, add_getter_kwargs), + "get_boolean": ("getBoolean", prefix_path_in_args, add_getter_kwargs), + "set": ("set", prefix_path_in_args, add_setter_kwargs), + "set_int": ("setInt", prefix_path_in_args, add_setter_kwargs), + "set_float": ("setFloat", prefix_path_in_args, add_setter_kwargs), + "set_boolean": ("setBoolean", prefix_path_in_args, add_setter_kwargs), + "remove": ("remove", prefix_path_in_args, lambda x: x), + "add_overlay": ("add_overlay", wrap_overlay, lambda x: x), + "remove_overlay": ("remove_overlay", lambda x: x, lambda x: x), + } + self.deprecated_access_methods = { + "getInt": "get_int", + "getFloat": "get_float", + "getBoolean": "get_boolean", + "setInt": "set_int", + "setFloat": "set_float", + "setBoolean": "set_boolean", + } + + def _prefix_path(self, path=None): + if path is None: + path = list() + return ["plugins", self.plugin_key] + path + + def global_has(self, path, **kwargs): + return self.settings.has(path, **kwargs) + + def global_remove(self, path, **kwargs): + return self.settings.remove(path, **kwargs) + + def global_get(self, path, **kwargs): + """ + Getter for retrieving settings not managed by the plugin itself from the core settings structure. Use this + to access global settings outside of your plugin. + + Directly forwards to :func:`octoprint.settings.Settings.get`. + """ + return self.settings.get(path, **kwargs) + + def global_get_int(self, path, **kwargs): + """ + Like :func:`global_get` but directly forwards to :func:`octoprint.settings.Settings.getInt`. + """ + return self.settings.getInt(path, **kwargs) + + def global_get_float(self, path, **kwargs): + """ + Like :func:`global_get` but directly forwards to :func:`octoprint.settings.Settings.getFloat`. + """ + return self.settings.getFloat(path, **kwargs) + + def global_get_boolean(self, path, **kwargs): + """ + Like :func:`global_get` but directly orwards to :func:`octoprint.settings.Settings.getBoolean`. + """ + return self.settings.getBoolean(path, **kwargs) + + def global_set(self, path, value, **kwargs): + """ + Setter for modifying settings not managed by the plugin itself on the core settings structure. Use this + to modify global settings outside of your plugin. + + Directly forwards to :func:`octoprint.settings.Settings.set`. + """ + self.settings.set(path, value, **kwargs) + + def global_set_int(self, path, value, **kwargs): + """ + Like :func:`global_set` but directly forwards to :func:`octoprint.settings.Settings.setInt`. + """ + self.settings.setInt(path, value, **kwargs) + + def global_set_float(self, path, value, **kwargs): + """ + Like :func:`global_set` but directly forwards to :func:`octoprint.settings.Settings.setFloat`. + """ + self.settings.setFloat(path, value, **kwargs) + + def global_set_boolean(self, path, value, **kwargs): + """ + Like :func:`global_set` but directly forwards to :func:`octoprint.settings.Settings.setBoolean`. + """ + self.settings.setBoolean(path, value, **kwargs) + + def global_get_basefolder(self, folder_type, **kwargs): + """ + Retrieves a globally defined basefolder of the given ``folder_type``. Directly forwards to + :func:`octoprint.settings.Settings.getBaseFolder`. + """ + return self.settings.getBaseFolder(folder_type, **kwargs) + + def get_plugin_logfile_path(self, postfix=None): + """ + Retrieves the path to a logfile specifically for the plugin. If ``postfix`` is not supplied, the logfile + will be named ``plugin_.log`` and located within the configured ``logs`` folder. If a + postfix is supplied, the name will be ``plugin__.log`` at the same location. + + Plugins may use this for specific logging tasks. For example, a :class:`~octoprint.plugin.SlicingPlugin` might + want to create a log file for logging the output of the slicing engine itself if some debug flag is set. + + Arguments: + postfix (str): Postfix of the logfile for which to create the path. If set, the file name of the log file + will be ``plugin__.log``, if not it will be + ``plugin_.log``. + + Returns: + str: Absolute path to the log file, directly usable by the plugin. + """ + filename = "plugin_" + self.plugin_key + if postfix is not None: + filename += "_" + postfix + filename += ".log" + return os.path.join(self.settings.getBaseFolder("logs"), filename) + + @deprecated( + "PluginSettings.get_plugin_data_folder has been replaced by OctoPrintPlugin.get_plugin_data_folder", + includedoc="Replaced by :func:`~octoprint.plugin.types.OctoPrintPlugin.get_plugin_data_folder`", + since="1.2.0", + ) + def get_plugin_data_folder(self): + path = os.path.join(self.settings.getBaseFolder("data"), self.plugin_key) + if not os.path.isdir(path): + os.makedirs(path) + return path + + def get_all_data(self, **kwargs): + merged = kwargs.get("merged", True) + asdict = kwargs.get("asdict", True) + defaults = kwargs.get("defaults", self.defaults) + preprocessors = kwargs.get("preprocessors", self.get_preprocessors) + + kwargs.update( + { + "merged": merged, + "asdict": asdict, + "defaults": defaults, + "preprocessors": preprocessors, + } + ) + + return self.settings.get(self._prefix_path(), **kwargs) + + def clean_all_data(self): + self.settings.remove(self._prefix_path()) + + def __getattr__(self, item): + all_access_methods = list(self.access_methods.keys()) + list( + self.deprecated_access_methods.keys() + ) + if item in all_access_methods: + decorator = None + if item in self.deprecated_access_methods: + new = self.deprecated_access_methods[item] + decorator = deprecated( + "{old} has been renamed to {new}".format(old=item, new=new), + stacklevel=2, + ) + item = new + + settings_name, args_mapper, kwargs_mapper = self.access_methods[item] + if hasattr(self.settings, settings_name) and callable( + getattr(self.settings, settings_name) + ): + orig_func = getattr(self.settings, settings_name) + if decorator is not None: + orig_func = decorator(orig_func) + + def _func(*args, **kwargs): + return orig_func(*args_mapper(args), **kwargs_mapper(kwargs)) + + _func.__name__ = to_native_str(item) + _func.__doc__ = orig_func.__doc__ if "__doc__" in dir(orig_func) else None + + return _func + + return getattr(self.settings, item) diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index e1856c09c..a1c9fe37b 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -21,7 +21,7 @@ In this module resides the core data structures and logic of the plugin system. """ -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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" @@ -42,137 +42,148 @@ from octoprint.util import to_unicode, sv, time_this from octoprint.util.version import is_python_compatible, get_python_version_string try: - from os import scandir + from os import scandir except ImportError: - from scandir import scandir + from scandir import scandir if sys.version_info[0] == 2: - # noinspection PyDeprecation - import imp + # noinspection PyDeprecation + import imp else: - # deprecated in Python 3.4+ and hence vendored for now - import octoprint.vendor.imp as imp + # deprecated in Python 3.4+ and hence vendored for now + import octoprint.vendor.imp as imp # noinspection PyDeprecation def _find_module(name, path=None): - if path is not None: - spec = imp.find_module(name, [path]) - else: - spec = imp.find_module(name) - return spec[1], spec + if path is not None: + spec = imp.find_module(name, [path]) + else: + spec = imp.find_module(name) + return spec[1], spec # noinspection PyDeprecation def _load_module(name, spec): - f, filename, details = spec - return imp.load_module(name, f, filename, details) + f, filename, details = spec + return imp.load_module(name, f, filename, details) + + +_EntryPointOrigin = namedtuple( + "EntryPointOrigin", "type, entry_point, module_name, package_name, package_version" +) -_EntryPointOrigin = namedtuple("EntryPointOrigin", "type, entry_point, module_name, package_name, package_version") class EntryPointOrigin(_EntryPointOrigin): - """ - Origin of a plugin registered via an entry point. + """ + Origin of a plugin registered via an entry point. - .. attribute:: type + .. attribute:: type - Always ``entry_point``. + Always ``entry_point``. - .. attribute:: entry_point + .. attribute:: entry_point - Name of the entry point, usually ``octoprint.plugin``. + Name of the entry point, usually ``octoprint.plugin``. - .. attribute:: module_name + .. attribute:: module_name - Module registered to the entry point. + Module registered to the entry point. - .. attribute:: package_name + .. attribute:: package_name - Python package containing the entry point. + Python package containing the entry point. - .. attribute:: package_version + .. attribute:: package_version + + Version of the python package containing the entry point. + """ - Version of the python package containing the entry point. - """ _FolderOrigin = namedtuple("FolderOrigin", "type, folder") + + class FolderOrigin(_FolderOrigin): - """ - Origin of a (single file) plugin loaded from a plugin folder. + """ + Origin of a (single file) plugin loaded from a plugin folder. - .. attribute:: type + .. attribute:: type - Always `folder`. + Always `folder`. - .. attribute:: folder + .. attribute:: folder + + Folder path from which the plugin was loaded. + """ - Folder path from which the plugin was loaded. - """ _ModuleOrigin = namedtuple("ModuleOrigin", "type, module_name, folder") + + class ModuleOrigin(_ModuleOrigin): - """ - Origin of a (single file) plugin loaded from a plugin folder. + """ + Origin of a (single file) plugin loaded from a plugin folder. - .. attribute:: type + .. attribute:: type - Always `module`. + Always `module`. - .. attribute:: module_name + .. attribute:: module_name - Name of the module from which the plugin was loaded. + Name of the module from which the plugin was loaded. - .. attribute:: folder + .. attribute:: folder + + Folder path from which the plugin was loaded. + """ - Folder path from which the plugin was loaded. - """ class PluginInfo(object): - """ - The :class:`PluginInfo` class wraps all available information about a registered plugin. + """ + The :class:`PluginInfo` class wraps all available information about a registered plugin. - This includes its meta data (like name, description, version, etc) as well as the actual plugin extensions like - implementations, hooks and helpers. + This includes its meta data (like name, description, version, etc) as well as the actual plugin extensions like + implementations, hooks and helpers. - It works on Python module objects and extracts the relevant data from those via accessing the - :ref:`control properties `. + It works on Python module objects and extracts the relevant data from those via accessing the + :ref:`control properties `. - Arguments: - key (str): Identifier of the plugin - location (str): Installation folder of the plugin - instance (module): Plugin module instance - this may be ``None`` if the plugin has been blacklisted! - name (str): Human readable name of the plugin - version (str): Version of the plugin - description (str): Description of the plugin - author (str): Author of the plugin - url (str): URL of the website of the plugin - license (str): License of the plugin - """ + Arguments: + key (str): Identifier of the plugin + location (str): Installation folder of the plugin + instance (module): Plugin module instance - this may be ``None`` if the plugin has been blacklisted! + name (str): Human readable name of the plugin + version (str): Version of the plugin + description (str): Description of the plugin + author (str): Author of the plugin + url (str): URL of the website of the plugin + license (str): License of the plugin + """ - attr_name = '__plugin_name__' - """ Module attribute from which to retrieve the plugin's human readable name. """ + attr_name = "__plugin_name__" + """ Module attribute from which to retrieve the plugin's human readable name. """ - attr_description = '__plugin_description__' - """ Module attribute from which to retrieve the plugin's description. """ + attr_description = "__plugin_description__" + """ Module attribute from which to retrieve the plugin's description. """ - attr_disabling_discouraged = '__plugin_disabling_discouraged__' - """ Module attribute from which to retrieve the reason why disabling the plugin is discouraged. Only effective if ``self.bundled`` is True. """ + attr_disabling_discouraged = "__plugin_disabling_discouraged__" + """ Module attribute from which to retrieve the reason why disabling the plugin is discouraged. Only effective if ``self.bundled`` is True. """ - attr_version = '__plugin_version__' - """ Module attribute from which to retrieve the plugin's version. """ + attr_version = "__plugin_version__" + """ Module attribute from which to retrieve the plugin's version. """ - attr_author = '__plugin_author__' - """ Module attribute from which to retrieve the plugin's author. """ + attr_author = "__plugin_author__" + """ Module attribute from which to retrieve the plugin's author. """ - attr_url = '__plugin_url__' - """ Module attribute from which to retrieve the plugin's website URL. """ + attr_url = "__plugin_url__" + """ Module attribute from which to retrieve the plugin's website URL. """ - attr_license = '__plugin_license__' - """ Module attribute from which to retrieve the plugin's license. """ + attr_license = "__plugin_license__" + """ Module attribute from which to retrieve the plugin's license. """ - attr_pythoncompat = '__plugin_pythoncompat__' - """ + attr_pythoncompat = "__plugin_pythoncompat__" + """ Module attribute from which to retrieve the plugin's python compatibility string. If unset a default of ``>=2.7,<3`` will be assumed, meaning that the plugin will be considered compatible to @@ -183,22 +194,22 @@ class PluginInfo(object): Bundled plugins will automatically be assumed to be compatible. """ - attr_hidden = '__plugin_hidden__' - """ + attr_hidden = "__plugin_hidden__" + """ Module attribute from which to determine if the plugin's hidden or not. Only evaluated for bundled plugins, in order to hide them from the Plugin Manager and similar places. """ - attr_hooks = '__plugin_hooks__' - """ Module attribute from which to retrieve the plugin's provided hooks. """ + attr_hooks = "__plugin_hooks__" + """ Module attribute from which to retrieve the plugin's provided hooks. """ - attr_implementation = '__plugin_implementation__' - """ Module attribute from which to retrieve the plugin's provided mixin implementation. """ + attr_implementation = "__plugin_implementation__" + """ Module attribute from which to retrieve the plugin's provided mixin implementation. """ - attr_implementations = '__plugin_implementations__' - """ + attr_implementations = "__plugin_implementations__" + """ Module attribute from which to retrieve the plugin's provided implementations. This deprecated attribute will only be used if a plugin does not yet offer :attr:`attr_implementation`. Only the @@ -209,14 +220,14 @@ class PluginInfo(object): Use :attr:`attr_implementation` instead. """ - attr_helpers = '__plugin_helpers__' - """ Module attribute from which to retrieve the plugin's provided helpers. """ + attr_helpers = "__plugin_helpers__" + """ Module attribute from which to retrieve the plugin's provided helpers. """ - attr_check = '__plugin_check__' - """ Module attribute which to call to determine if the plugin can be loaded. """ + attr_check = "__plugin_check__" + """ Module attribute which to call to determine if the plugin can be loaded. """ - attr_init = '__plugin_init__' - """ + attr_init = "__plugin_init__" + """ Module attribute which to call when loading the plugin. This deprecated attribute will only be used if a plugin does not yet offer :attr:`attr_load`. @@ -226,1809 +237,2256 @@ class PluginInfo(object): Use :attr:`attr_load` instead. """ - attr_load = '__plugin_load__' - """ Module attribute which to call when loading the plugin. """ + attr_load = "__plugin_load__" + """ Module attribute which to call when loading the plugin. """ - attr_unload = '__plugin_unload__' - """ Module attribute which to call when unloading the plugin. """ + attr_unload = "__plugin_unload__" + """ Module attribute which to call when unloading the plugin. """ - attr_enable = '__plugin_enable__' - """ Module attribute which to call when enabling the plugin. """ + attr_enable = "__plugin_enable__" + """ Module attribute which to call when enabling the plugin. """ - attr_disable = '__plugin_disable__' - """ Module attribute which to call when disabling the plugin. """ + attr_disable = "__plugin_disable__" + """ Module attribute which to call when disabling the plugin. """ - def __init__(self, key, location, instance, name=None, version=None, description=None, author=None, url=None, license=None, parsed_metadata=None): - self.key = key - self.location = location - self.instance = instance + def __init__( + self, + key, + location, + instance, + name=None, + version=None, + description=None, + author=None, + url=None, + license=None, + parsed_metadata=None, + ): + self.key = key + self.location = location + self.instance = instance - self.origin = None - """ + self.origin = None + """ The origin from which this plugin was loaded, either a :class:`EntryPointOrigin`, :class:`FolderOrigin` or :class:`ModuleOrigin` instance. Set during loading, initially ``None``. """ - self.enabled = True - """Whether the plugin is enabled.""" - - self.blacklisted = False - """Whether the plugin is blacklisted.""" - - self.forced_disabled = False - """Whether the plugin has been force disabled by the system, e.g. due to safe mode blacklisting.""" - - self.incompatible = False - """Whether this plugin has been detected as incompatible.""" - - self.bundled = False - """Whether this plugin is bundled with OctoPrint.""" - - self.loaded = False - """Whether this plugin has been loaded.""" - - self.managable = True - """Whether this plugin can be managed by OctoPrint.""" - - self.needs_restart = False - """Whether this plugin needs a restart of OctoPrint after enabling/disabling.""" - - self.invalid_syntax = False - """Whether invalid syntax was encountered while trying to load this plugin.""" - - self._name = name - self._version = version - self._description = description - self._author = author - self._url = url - self._license = license - - self._logger = logging.getLogger(__name__) - - self._cached_parsed_metadata = parsed_metadata - if self._cached_parsed_metadata is None: - self._cached_parsed_metadata = self._parse_metadata() - - def validate(self, phase, additional_validators=None): - """ - Validates the plugin for various validation phases. - - ``phase`` can be one of ``before_import``, ``before_load``, ``after_load``. - - Used by :class:`PluginManager`, should not be used elsewhere. - """ - result = True - - if phase == "before_import": - result = not self.forced_disabled and not self.blacklisted and not self.incompatible and not self.invalid_syntax and result - - elif phase == "before_load": - # if the plugin still uses __plugin_init__, log a deprecation warning and move it to __plugin_load__ - if hasattr(self.instance, self.__class__.attr_init): - if not hasattr(self.instance, self.__class__.attr_load): - # deprecation warning - import warnings - warnings.warn("{name} uses deprecated control property __plugin_init__, use __plugin_load__ instead".format(name=self.key), DeprecationWarning) - - # move it - init = getattr(self.instance, self.__class__.attr_init) - setattr(self.instance, self.__class__.attr_load, init) - - # delete __plugin_init__ - delattr(self.instance, self.__class__.attr_init) - - elif phase == "after_load": - # if the plugin still uses __plugin_implementations__, log a deprecation warning and put the first - # item into __plugin_implementation__ - if hasattr(self.instance, self.__class__.attr_implementations): - if not hasattr(self.instance, self.__class__.attr_implementation): - # deprecation warning - import warnings - warnings.warn("{name} uses deprecated control property __plugin_implementations__, use __plugin_implementation__ instead - only the first implementation of {name} will be recognized".format(name=self.key), DeprecationWarning) - - # put first item into __plugin_implementation__ - implementations = getattr(self.instance, self.__class__.attr_implementations) - if len(implementations) > 0: - setattr(self.instance, self.__class__.attr_implementation, implementations[0]) - - # delete __plugin_implementations__ - delattr(self.instance, self.__class__.attr_implementations) - - if additional_validators is not None: - for validator in additional_validators: - result = validator(phase, self) and result - - return result - - def __str__(self): - if self.version: - return "{name} ({version})".format(name=self.name, version=self.version) - else: - return to_unicode(self.name) - - def long_str(self, show_bundled=False, bundled_strs=(" [B]", ""), - show_location=False, location_str=" - {location}", - show_enabled=False, enabled_strs=("* ", " ", "X ", "C ")): - """ - Long string representation of the plugin's information. Will return a string of the format ````. - - ``enabled``, ``bundled`` and ``location`` will only be displayed if the corresponding flags are set to ``True``. - The will be filled from ``enabled_str``, ``bundled_str`` and ``location_str`` as follows: - - ``enabled_str`` - a 4-tuple, the first entry being the string to insert when the plugin is enabled, the second - entry the string to insert when it is not, the third entry the string when it is blacklisted - and the fourth when it is incompatible. - ``bundled_str`` - a 2-tuple, the first entry being the string to insert when the plugin is bundled, the second - entry the string to insert when it is not. - ``location_str`` - a format string (to be parsed with ``str.format``), the ``{location}`` placeholder will be - replaced with the plugin's installation folder on disk. - - Arguments: - show_enabled (boolean): whether to show the ``enabled`` part - enabled_strs (tuple): the 2-tuple containing the two possible strings to use for displaying the enabled state - show_bundled (boolean): whether to show the ``bundled`` part - bundled_strs(tuple): the 2-tuple containing the two possible strings to use for displaying the bundled state - show_location (boolean): whether to show the ``location`` part - location_str (str): the format string to use for displaying the plugin's installation location - - Returns: - str: The long string representation of the plugin as described above - """ - if show_enabled: - if self.incompatible: - ret = to_unicode(enabled_strs[3]) - elif self.blacklisted: - ret = to_unicode(enabled_strs[2]) - elif not self.enabled: - ret = to_unicode(enabled_strs[1]) - else: - ret = to_unicode(enabled_strs[0]) - else: - ret = "" - - ret += unicode(self) - - if show_bundled: - ret += to_unicode(bundled_strs[0]) if self.bundled else to_unicode(bundled_strs[1]) - - if show_location and self.location: - ret += to_unicode(location_str).format(location=self.location) - - return ret - - def get_hook(self, hook): - """ - Arguments: - hook (str): Hook to return. - - Returns: - callable or None: Handler for the requested ``hook`` or None if no handler is registered. - """ - - if not hook in self.hooks: - return None - return self.hooks[hook] - - def get_implementation(self, *types): - """ - Arguments: - types (list): List of :class:`Plugin` sub classes the implementation needs to implement. - - Returns: - object: The plugin's implementation if it matches all of the requested ``types``, None otherwise. - """ - - if self.implementation and all(map(lambda t: isinstance(self.implementation, t), types)): - return self.implementation - else: - return None - - @property - def name(self): - """ - Human readable name of the plugin. Will be taken from name attribute of the plugin module if available, - otherwise from the ``name`` supplied during construction with a fallback to ``key``. - - Returns: - str: Name of the plugin, fallback is the plugin's identifier. - """ - return self._get_instance_attribute(self.__class__.attr_name, - defaults=(self._name, self.key), - incl_metadata=True) - - @property - def description(self): - """ - Description of the plugin. Will be taken from the description attribute of the plugin module as defined in - :attr:`attr_description` if available, otherwise from the ``description`` supplied during construction. - May be None. - - Returns: - str or None: Description of the plugin. - """ - return self._get_instance_attribute(self.__class__.attr_description, - default=self._description, - incl_metadata=True) - - @property - def disabling_discouraged(self): - """ - Reason why disabling of this plugin is discouraged. Only evaluated for bundled plugins! Will be taken from - the disabling_discouraged attribute of the plugin module as defined in :attr:`attr_disabling_discouraged` if - available. False if unset or plugin not bundled. - - Returns: - str or None: Reason why disabling this plugin is discouraged (only for bundled plugins) - """ - return self._get_instance_attribute(self.__class__.attr_disabling_discouraged, default=False) if self.bundled \ - else False - - @property - def version(self): - """ - Version of the plugin. Will be taken from the version attribute of the plugin module as defined in - :attr:`attr_version` if available, otherwise from the ``version`` supplied during construction. May be None. - - Returns: - str or None: Version of the plugin. - """ - return self._version if self._version is not None else self._get_instance_attribute(self.__class__.attr_version, - default=self._version, - incl_metadata=True) - - @property - def author(self): - """ - Author of the plugin. Will be taken from the author attribute of the plugin module as defined in - :attr:`attr_author` if available, otherwise from the ``author`` supplied during construction. May be None. - - Returns: - str or None: Author of the plugin. - """ - return self._get_instance_attribute(self.__class__.attr_author, - default=self._author, - incl_metadata=True) - - @property - def url(self): - """ - Website URL for the plugin. Will be taken from the url attribute of the plugin module as defined in - :attr:`attr_url` if available, otherwise from the ``url`` supplied during construction. May be None. - - Returns: - str or None: Website URL for the plugin. - """ - return self._get_instance_attribute(self.__class__.attr_url, - default=self._url, - incl_metadata=True) - - @property - def license(self): - """ - License of the plugin. Will be taken from the license attribute of the plugin module as defined in - :attr:`attr_license` if available, otherwise from the ``license`` supplied during construction. May be None. - - Returns: - str or None: License of the plugin. - """ - return self._get_instance_attribute(self.__class__.attr_license, - default=self._license, - incl_metadata=True) - - @property - def pythoncompat(self): - """ - Python compatibility string of the plugin module as defined in :attr:`attr_pythoncompat` if available, otherwise - defaults to ``>=2.7,<3``. - - Returns: - str: Python compatibility string of the plugin - """ - return self._get_instance_attribute(self.__class__.attr_pythoncompat, - default=">=2.7,<3", - incl_metadata=True) - - @property - def hidden(self): - """ - Hidden flag. - - Returns: - bool: Whether the plugin should be flagged as hidden or not - """ - return self._get_instance_attribute(self.__class__.attr_hidden, - default=False, - incl_metadata=True) - - @property - def hooks(self): - """ - Hooks provided by the plugin. Will be taken from the hooks attribute of the plugin module as defined in - :attr:`attr_hooks` if available, otherwise an empty dictionary is returned. - - Returns: - dict: Hooks provided by the plugin. - """ - return self._get_instance_attribute(self.__class__.attr_hooks, default={}) - - @property - def implementation(self): - """ - Implementation provided by the plugin. Will be taken from the implementation attribute of the plugin module - as defined in :attr:`attr_implementation` if available, otherwise None is returned. - - Returns: - object: Implementation provided by the plugin. - """ - return self._get_instance_attribute(self.__class__.attr_implementation, default=None) - - @property - def helpers(self): - """ - Helpers provided by the plugin. Will be taken from the helpers attribute of the plugin module as defined in - :attr:`attr_helpers` if available, otherwise an empty list is returned. - - Returns: - dict: Helpers provided by the plugin. - """ - return self._get_instance_attribute(self.__class__.attr_helpers, default={}) - - @property - def check(self): - """ - Method for pre-load check of plugin. Will be taken from the check attribute of the plugin module as defined in - :attr:`attr_check` if available, otherwise a lambda always returning True is returned. - - Returns: - callable: Check method for the plugin module which should return True if the plugin can be loaded, False - otherwise. - """ - return self._get_instance_attribute(self.__class__.attr_check, default=lambda: True) - - @property - def load(self): - """ - Method for loading the plugin module. Will be taken from the load attribute of the plugin module as defined - in :attr:`attr_load` if available, otherwise a no-operation lambda will be returned. - - Returns: - callable: Load method for the plugin module. - """ - return self._get_instance_attribute(self.__class__.attr_load, default=lambda: True) - - @property - def unload(self): - """ - Method for unloading the plugin module. Will be taken from the unload attribute of the plugin module as defined - in :attr:`attr_unload` if available, otherwise a no-operation lambda will be returned. - - Returns: - callable: Unload method for the plugin module. - """ - return self._get_instance_attribute(self.__class__.attr_unload, default=lambda: True) - - @property - def enable(self): - """ - Method for enabling the plugin module. Will be taken from the enable attribute of the plugin module as defined - in :attr:`attr_enable` if available, otherwise a no-operation lambda will be returned. - - Returns: - callable: Enable method for the plugin module. - """ - return self._get_instance_attribute(self.__class__.attr_enable, default=lambda: True) - - @property - def disable(self): - """ - Method for disabling the plugin module. Will be taken from the disable attribute of the plugin module as defined - in :attr:`attr_disable` if available, otherwise a no-operation lambda will be returned. - - Returns: - callable: Disable method for the plugin module. - """ - return self._get_instance_attribute(self.__class__.attr_disable, default=lambda: True) - - def _get_instance_attribute(self, attr, default=None, defaults=None, incl_metadata=False): - if self.instance is None or not hasattr(self.instance, attr): - if incl_metadata and attr in self.parsed_metadata: - return self.parsed_metadata[attr] - - elif defaults is not None: - for value in defaults: - if callable(value): - value = value() - if value is not None: - return value - - return default - - return getattr(self.instance, attr) - - @property - def parsed_metadata(self): - """The plugin metadata parsed from the plugin ``__init__.py``'s AST.""" - return self._cached_parsed_metadata - - def _parse_metadata(self): - result = {} - - path = self.location - if not path: - return result - - if os.path.isdir(path): - path = os.path.join(self.location, "__init__.py") - - if not os.path.isfile(path): - return result - - if not path.endswith(".py"): - # we only support parsing plain text source files - return result - - self._logger.debug("Parsing plugin metadata for {} from AST of {}".format(self.key, path)) - - try: - import ast - - with io.open(path, 'rb') as f: - root = ast.parse(f.read(), filename=path) - - assignments = list(filter(lambda x: isinstance(x, ast.Assign) and x.targets, - root.body)) - - def extract_target_ids(node): - return list(map(lambda x: x.id, - filter(lambda x: isinstance(x, ast.Name), node.targets))) - - for key in (self.__class__.attr_name, self.__class__.attr_version, self.__class__.attr_author, - self.__class__.attr_description, self.__class__.attr_url, self.__class__.attr_license, - self.__class__.attr_pythoncompat): - for a in reversed(assignments): - targets = extract_target_ids(a) - if key in targets: - if isinstance(a.value, ast.Str): - result[key] = a.value.s - - elif isinstance(a.value, ast.Call) and hasattr(a.value, "func") \ - and a.value.func.id == "gettext" and a.value.args \ - and isinstance(a.value.args[0], ast.Str): - result[key] = a.value.args[0].s - - break - - for key in (self.__class__.attr_hidden,): - for a in reversed(assignments): - targets = extract_target_ids(a) - if key in targets: - if isinstance(a.value, ast.Name) and a.value.id in ("True", "False"): - result[key] = bool(a.value.id) - - break - - except SyntaxError: - self._logger.exception("Invalid syntax in {} for plugin {}".format(path, self.key)) - self.invalid_syntax = True - except Exception: - self._logger.exception("Error while parsing AST from {} for plugin {}".format(path, self.key)) - - return result + self.enabled = True + """Whether the plugin is enabled.""" + + self.blacklisted = False + """Whether the plugin is blacklisted.""" + + self.forced_disabled = False + """Whether the plugin has been force disabled by the system, e.g. due to safe mode blacklisting.""" + + self.incompatible = False + """Whether this plugin has been detected as incompatible.""" + + self.bundled = False + """Whether this plugin is bundled with OctoPrint.""" + + self.loaded = False + """Whether this plugin has been loaded.""" + + self.managable = True + """Whether this plugin can be managed by OctoPrint.""" + + self.needs_restart = False + """Whether this plugin needs a restart of OctoPrint after enabling/disabling.""" + + self.invalid_syntax = False + """Whether invalid syntax was encountered while trying to load this plugin.""" + + self._name = name + self._version = version + self._description = description + self._author = author + self._url = url + self._license = license + + self._logger = logging.getLogger(__name__) + + self._cached_parsed_metadata = parsed_metadata + if self._cached_parsed_metadata is None: + self._cached_parsed_metadata = self._parse_metadata() + + def validate(self, phase, additional_validators=None): + """ + Validates the plugin for various validation phases. + + ``phase`` can be one of ``before_import``, ``before_load``, ``after_load``. + + Used by :class:`PluginManager`, should not be used elsewhere. + """ + result = True + + if phase == "before_import": + result = ( + not self.forced_disabled + and not self.blacklisted + and not self.incompatible + and not self.invalid_syntax + and result + ) + + elif phase == "before_load": + # if the plugin still uses __plugin_init__, log a deprecation warning and move it to __plugin_load__ + if hasattr(self.instance, self.__class__.attr_init): + if not hasattr(self.instance, self.__class__.attr_load): + # deprecation warning + import warnings + + warnings.warn( + "{name} uses deprecated control property __plugin_init__, use __plugin_load__ instead".format( + name=self.key + ), + DeprecationWarning, + ) + + # move it + init = getattr(self.instance, self.__class__.attr_init) + setattr(self.instance, self.__class__.attr_load, init) + + # delete __plugin_init__ + delattr(self.instance, self.__class__.attr_init) + + elif phase == "after_load": + # if the plugin still uses __plugin_implementations__, log a deprecation warning and put the first + # item into __plugin_implementation__ + if hasattr(self.instance, self.__class__.attr_implementations): + if not hasattr(self.instance, self.__class__.attr_implementation): + # deprecation warning + import warnings + + warnings.warn( + "{name} uses deprecated control property __plugin_implementations__, use __plugin_implementation__ instead - only the first implementation of {name} will be recognized".format( + name=self.key + ), + DeprecationWarning, + ) + + # put first item into __plugin_implementation__ + implementations = getattr( + self.instance, self.__class__.attr_implementations + ) + if len(implementations) > 0: + setattr( + self.instance, + self.__class__.attr_implementation, + implementations[0], + ) + + # delete __plugin_implementations__ + delattr(self.instance, self.__class__.attr_implementations) + + if additional_validators is not None: + for validator in additional_validators: + result = validator(phase, self) and result + + return result + + def __str__(self): + if self.version: + return "{name} ({version})".format(name=self.name, version=self.version) + else: + return to_unicode(self.name) + + def long_str( + self, + show_bundled=False, + bundled_strs=(" [B]", ""), + show_location=False, + location_str=" - {location}", + show_enabled=False, + enabled_strs=("* ", " ", "X ", "C "), + ): + """ + Long string representation of the plugin's information. Will return a string of the format ````. + + ``enabled``, ``bundled`` and ``location`` will only be displayed if the corresponding flags are set to ``True``. + The will be filled from ``enabled_str``, ``bundled_str`` and ``location_str`` as follows: + + ``enabled_str`` + a 4-tuple, the first entry being the string to insert when the plugin is enabled, the second + entry the string to insert when it is not, the third entry the string when it is blacklisted + and the fourth when it is incompatible. + ``bundled_str`` + a 2-tuple, the first entry being the string to insert when the plugin is bundled, the second + entry the string to insert when it is not. + ``location_str`` + a format string (to be parsed with ``str.format``), the ``{location}`` placeholder will be + replaced with the plugin's installation folder on disk. + + Arguments: + show_enabled (boolean): whether to show the ``enabled`` part + enabled_strs (tuple): the 2-tuple containing the two possible strings to use for displaying the enabled state + show_bundled (boolean): whether to show the ``bundled`` part + bundled_strs(tuple): the 2-tuple containing the two possible strings to use for displaying the bundled state + show_location (boolean): whether to show the ``location`` part + location_str (str): the format string to use for displaying the plugin's installation location + + Returns: + str: The long string representation of the plugin as described above + """ + if show_enabled: + if self.incompatible: + ret = to_unicode(enabled_strs[3]) + elif self.blacklisted: + ret = to_unicode(enabled_strs[2]) + elif not self.enabled: + ret = to_unicode(enabled_strs[1]) + else: + ret = to_unicode(enabled_strs[0]) + else: + ret = "" + + ret += unicode(self) + + if show_bundled: + ret += ( + to_unicode(bundled_strs[0]) + if self.bundled + else to_unicode(bundled_strs[1]) + ) + + if show_location and self.location: + ret += to_unicode(location_str).format(location=self.location) + + return ret + + def get_hook(self, hook): + """ + Arguments: + hook (str): Hook to return. + + Returns: + callable or None: Handler for the requested ``hook`` or None if no handler is registered. + """ + + if not hook in self.hooks: + return None + return self.hooks[hook] + + def get_implementation(self, *types): + """ + Arguments: + types (list): List of :class:`Plugin` sub classes the implementation needs to implement. + + Returns: + object: The plugin's implementation if it matches all of the requested ``types``, None otherwise. + """ + + if self.implementation and all( + map(lambda t: isinstance(self.implementation, t), types) + ): + return self.implementation + else: + return None + + @property + def name(self): + """ + Human readable name of the plugin. Will be taken from name attribute of the plugin module if available, + otherwise from the ``name`` supplied during construction with a fallback to ``key``. + + Returns: + str: Name of the plugin, fallback is the plugin's identifier. + """ + return self._get_instance_attribute( + self.__class__.attr_name, defaults=(self._name, self.key), incl_metadata=True + ) + + @property + def description(self): + """ + Description of the plugin. Will be taken from the description attribute of the plugin module as defined in + :attr:`attr_description` if available, otherwise from the ``description`` supplied during construction. + May be None. + + Returns: + str or None: Description of the plugin. + """ + return self._get_instance_attribute( + self.__class__.attr_description, default=self._description, incl_metadata=True + ) + + @property + def disabling_discouraged(self): + """ + Reason why disabling of this plugin is discouraged. Only evaluated for bundled plugins! Will be taken from + the disabling_discouraged attribute of the plugin module as defined in :attr:`attr_disabling_discouraged` if + available. False if unset or plugin not bundled. + + Returns: + str or None: Reason why disabling this plugin is discouraged (only for bundled plugins) + """ + return ( + self._get_instance_attribute( + self.__class__.attr_disabling_discouraged, default=False + ) + if self.bundled + else False + ) + + @property + def version(self): + """ + Version of the plugin. Will be taken from the version attribute of the plugin module as defined in + :attr:`attr_version` if available, otherwise from the ``version`` supplied during construction. May be None. + + Returns: + str or None: Version of the plugin. + """ + return ( + self._version + if self._version is not None + else self._get_instance_attribute( + self.__class__.attr_version, default=self._version, incl_metadata=True + ) + ) + + @property + def author(self): + """ + Author of the plugin. Will be taken from the author attribute of the plugin module as defined in + :attr:`attr_author` if available, otherwise from the ``author`` supplied during construction. May be None. + + Returns: + str or None: Author of the plugin. + """ + return self._get_instance_attribute( + self.__class__.attr_author, default=self._author, incl_metadata=True + ) + + @property + def url(self): + """ + Website URL for the plugin. Will be taken from the url attribute of the plugin module as defined in + :attr:`attr_url` if available, otherwise from the ``url`` supplied during construction. May be None. + + Returns: + str or None: Website URL for the plugin. + """ + return self._get_instance_attribute( + self.__class__.attr_url, default=self._url, incl_metadata=True + ) + + @property + def license(self): + """ + License of the plugin. Will be taken from the license attribute of the plugin module as defined in + :attr:`attr_license` if available, otherwise from the ``license`` supplied during construction. May be None. + + Returns: + str or None: License of the plugin. + """ + return self._get_instance_attribute( + self.__class__.attr_license, default=self._license, incl_metadata=True + ) + + @property + def pythoncompat(self): + """ + Python compatibility string of the plugin module as defined in :attr:`attr_pythoncompat` if available, otherwise + defaults to ``>=2.7,<3``. + + Returns: + str: Python compatibility string of the plugin + """ + return self._get_instance_attribute( + self.__class__.attr_pythoncompat, default=">=2.7,<3", incl_metadata=True + ) + + @property + def hidden(self): + """ + Hidden flag. + + Returns: + bool: Whether the plugin should be flagged as hidden or not + """ + return self._get_instance_attribute( + self.__class__.attr_hidden, default=False, incl_metadata=True + ) + + @property + def hooks(self): + """ + Hooks provided by the plugin. Will be taken from the hooks attribute of the plugin module as defined in + :attr:`attr_hooks` if available, otherwise an empty dictionary is returned. + + Returns: + dict: Hooks provided by the plugin. + """ + return self._get_instance_attribute(self.__class__.attr_hooks, default={}) + + @property + def implementation(self): + """ + Implementation provided by the plugin. Will be taken from the implementation attribute of the plugin module + as defined in :attr:`attr_implementation` if available, otherwise None is returned. + + Returns: + object: Implementation provided by the plugin. + """ + return self._get_instance_attribute( + self.__class__.attr_implementation, default=None + ) + + @property + def helpers(self): + """ + Helpers provided by the plugin. Will be taken from the helpers attribute of the plugin module as defined in + :attr:`attr_helpers` if available, otherwise an empty list is returned. + + Returns: + dict: Helpers provided by the plugin. + """ + return self._get_instance_attribute(self.__class__.attr_helpers, default={}) + + @property + def check(self): + """ + Method for pre-load check of plugin. Will be taken from the check attribute of the plugin module as defined in + :attr:`attr_check` if available, otherwise a lambda always returning True is returned. + + Returns: + callable: Check method for the plugin module which should return True if the plugin can be loaded, False + otherwise. + """ + return self._get_instance_attribute( + self.__class__.attr_check, default=lambda: True + ) + + @property + def load(self): + """ + Method for loading the plugin module. Will be taken from the load attribute of the plugin module as defined + in :attr:`attr_load` if available, otherwise a no-operation lambda will be returned. + + Returns: + callable: Load method for the plugin module. + """ + return self._get_instance_attribute( + self.__class__.attr_load, default=lambda: True + ) + + @property + def unload(self): + """ + Method for unloading the plugin module. Will be taken from the unload attribute of the plugin module as defined + in :attr:`attr_unload` if available, otherwise a no-operation lambda will be returned. + + Returns: + callable: Unload method for the plugin module. + """ + return self._get_instance_attribute( + self.__class__.attr_unload, default=lambda: True + ) + + @property + def enable(self): + """ + Method for enabling the plugin module. Will be taken from the enable attribute of the plugin module as defined + in :attr:`attr_enable` if available, otherwise a no-operation lambda will be returned. + + Returns: + callable: Enable method for the plugin module. + """ + return self._get_instance_attribute( + self.__class__.attr_enable, default=lambda: True + ) + + @property + def disable(self): + """ + Method for disabling the plugin module. Will be taken from the disable attribute of the plugin module as defined + in :attr:`attr_disable` if available, otherwise a no-operation lambda will be returned. + + Returns: + callable: Disable method for the plugin module. + """ + return self._get_instance_attribute( + self.__class__.attr_disable, default=lambda: True + ) + + def _get_instance_attribute( + self, attr, default=None, defaults=None, incl_metadata=False + ): + if self.instance is None or not hasattr(self.instance, attr): + if incl_metadata and attr in self.parsed_metadata: + return self.parsed_metadata[attr] + + elif defaults is not None: + for value in defaults: + if callable(value): + value = value() + if value is not None: + return value + + return default + + return getattr(self.instance, attr) + + @property + def parsed_metadata(self): + """The plugin metadata parsed from the plugin ``__init__.py``'s AST.""" + return self._cached_parsed_metadata + + def _parse_metadata(self): + result = {} + + path = self.location + if not path: + return result + + if os.path.isdir(path): + path = os.path.join(self.location, "__init__.py") + + if not os.path.isfile(path): + return result + + if not path.endswith(".py"): + # we only support parsing plain text source files + return result + + self._logger.debug( + "Parsing plugin metadata for {} from AST of {}".format(self.key, path) + ) + + try: + import ast + + with io.open(path, "rb") as f: + root = ast.parse(f.read(), filename=path) + + assignments = list( + filter(lambda x: isinstance(x, ast.Assign) and x.targets, root.body) + ) + + def extract_target_ids(node): + return list( + map( + lambda x: x.id, + filter(lambda x: isinstance(x, ast.Name), node.targets), + ) + ) + + for key in ( + self.__class__.attr_name, + self.__class__.attr_version, + self.__class__.attr_author, + self.__class__.attr_description, + self.__class__.attr_url, + self.__class__.attr_license, + self.__class__.attr_pythoncompat, + ): + for a in reversed(assignments): + targets = extract_target_ids(a) + if key in targets: + if isinstance(a.value, ast.Str): + result[key] = a.value.s + + elif ( + isinstance(a.value, ast.Call) + and hasattr(a.value, "func") + and a.value.func.id == "gettext" + and a.value.args + and isinstance(a.value.args[0], ast.Str) + ): + result[key] = a.value.args[0].s + + break + + for key in (self.__class__.attr_hidden,): + for a in reversed(assignments): + targets = extract_target_ids(a) + if key in targets: + if isinstance(a.value, ast.Name) and a.value.id in ( + "True", + "False", + ): + result[key] = bool(a.value.id) + + break + + except SyntaxError: + self._logger.exception( + "Invalid syntax in {} for plugin {}".format(path, self.key) + ) + self.invalid_syntax = True + except Exception: + self._logger.exception( + "Error while parsing AST from {} for plugin {}".format(path, self.key) + ) + + return result class PluginManager(object): - """ - The :class:`PluginManager` is the central component for finding, loading and accessing plugins provided to the - system. - - It is able to discover plugins both through possible file system locations as well as customizable entry points. - """ - - plugin_timings_logtarget = "PLUGIN_TIMINGS" - plugin_timings_message = "{func} - {timing:05.2f}ms" - - def __init__(self, plugin_folders, plugin_bases, plugin_entry_points, logging_prefix=None, - plugin_disabled_list=None, plugin_blacklist=None, plugin_restart_needing_hooks=None, - plugin_obsolete_hooks=None, plugin_considered_bundled=None, plugin_validators=None, - compatibility_ignored_list=None): - self.logger = logging.getLogger(__name__) - - if logging_prefix is None: - logging_prefix = "" - if plugin_folders is None: - plugin_folders = [] - if plugin_bases is None: - plugin_bases = [] - if plugin_entry_points is None: - plugin_entry_points = [] - if plugin_disabled_list is None: - plugin_disabled_list = [] - if plugin_blacklist is None: - plugin_blacklist = [] - if compatibility_ignored_list is None: - compatibility_ignored_list = [] - if plugin_considered_bundled is None: - plugin_considered_bundled = [] - - self.plugin_folders = plugin_folders - self.plugin_bases = plugin_bases - self.plugin_entry_points = plugin_entry_points - self.plugin_disabled_list = plugin_disabled_list - self.plugin_blacklist = plugin_blacklist - self.plugin_restart_needing_hooks = plugin_restart_needing_hooks - self.plugin_obsolete_hooks = plugin_obsolete_hooks - self.plugin_validators = plugin_validators - self.logging_prefix = logging_prefix - self.compatibility_ignored_list = compatibility_ignored_list - self.plugin_considered_bundled = plugin_considered_bundled - - self.enabled_plugins = {} - self.disabled_plugins = {} - self.plugin_implementations = {} - self.plugin_implementations_by_type = defaultdict(list) - - self._plugin_hooks = defaultdict(list) - - self.implementation_injects = {} - self.implementation_inject_factories = [] - self.implementation_pre_inits = [] - self.implementation_post_inits = [] - - self.on_plugin_loaded = lambda *args, **kwargs: None - self.on_plugin_unloaded = lambda *args, **kwargs: None - self.on_plugin_enabled = lambda *args, **kwargs: None - self.on_plugin_disabled = lambda *args, **kwargs: None - self.on_plugin_implementations_initialized = lambda *args, **kwargs: None - - self.on_plugins_loaded = lambda *args, **kwargs: None - self.on_plugins_enabled = lambda *args, **kwargs: None - - self.registered_clients = [] - - self.marked_plugins = defaultdict(list) - - self._python_install_dir = None - self._python_virtual_env = False - self._detect_python_environment() - - def _detect_python_environment(self): - from distutils.command.install import install as cmd_install - from distutils.dist import Distribution - import sys - - cmd = cmd_install(Distribution()) - cmd.finalize_options() - - self._python_install_dir = cmd.install_lib - self._python_prefix = os.path.realpath(sys.prefix) - self._python_virtual_env = hasattr(sys, "real_prefix") \ - or (hasattr(sys, "base_prefix") and os.path.realpath(sys.prefix) != os.path.realpath(sys.base_prefix)) - - @property - def plugins(self): - """ - Returns: - (list) list of enabled and disabled registered plugins - """ - plugins = dict(self.enabled_plugins) - plugins.update(self.disabled_plugins) - return plugins - - @property - def plugin_hooks(self): - """ - Returns: - (dict) dictionary of registered hooks and their handlers - """ - return {key: list(map(lambda v: (v[1], v[2]), value)) for key, value in self._plugin_hooks.items()} - - def find_plugins(self, existing=None, ignore_uninstalled=True, incl_all_found=False): - added, found = self._find_plugins(existing=existing, ignore_uninstalled=ignore_uninstalled) - if incl_all_found: - return added, found - else: - return added - - def _find_plugins(self, existing=None, ignore_uninstalled=True): - if existing is None: - existing = dict(self.plugins) - - result_added = OrderedDict() - result_found = [] - - if self.plugin_folders: - try: - added, found = self._find_plugins_from_folders(self.plugin_folders, - existing, - ignored_uninstalled=ignore_uninstalled) - result_added.update(added) - result_found += found - except Exception: - self.logger.exception("Error fetching plugins from folders") - - if self.plugin_entry_points: - existing.update(result_added) - try: - added, found = self._find_plugins_from_entry_points(self.plugin_entry_points, - existing, - ignore_uninstalled=ignore_uninstalled) - result_added.update(added) - result_found += found - except Exception: - self.logger.exception("Error fetching plugins from entry points") - - return result_added, result_found - - def _find_plugins_from_folders(self, folders, existing, ignored_uninstalled=True): - added = OrderedDict() - found = [] - - for folder in folders: - try: - flagged_readonly = False - package = None - if isinstance(folder, (list, tuple)): - if len(folder) == 2: - folder, flagged_readonly = folder - elif len(folder) == 3: - folder, package, flagged_readonly = folder - else: - continue - actual_readonly = not os.access(folder, os.W_OK) - - if not os.path.exists(folder): - self.logger.warning("Plugin folder {folder} could not be found, skipping it".format(folder=folder)) - continue - - for entry in scandir(folder): - try: - if entry.is_dir(): - init_py = os.path.join(entry.path, "__init__.py") - init_pyc = os.path.join(entry.path, "__init__.pyc") - - if not os.path.isfile(init_py) and not os.path.isfile(init_pyc): - # neither does exist, we ignore this - continue - - key = entry.name - - elif entry.is_file(): - key, ext = os.path.splitext(entry.name) - if ext not in (".py", ".pyc") or key.startswith("__"): - # neither py nor pyc, or starts with __ (like __init__), we ignore this - continue - - else: - # whatever this is, we ignore it - continue - - found.append(key) - if key in existing or key in added or (ignored_uninstalled and key in self.marked_plugins["uninstalled"]): - # plugin is already defined, ignore it - continue - - bundled = flagged_readonly - - module_name = None - if package: - module_name = "{}.{}".format(package, key) - - plugin = self._import_plugin_from_module(key, module_name=module_name, folder=folder, bundled=bundled) - if plugin: - if module_name: - plugin.origin = ModuleOrigin("module", module_name, folder) - else: - plugin.origin = FolderOrigin("folder", folder) - plugin.managable = not flagged_readonly and not actual_readonly - plugin.enabled = False - added[key] = plugin - except Exception: - self.logger.exception("Error processing folder entry {!r} from folder {}".format(entry, folder)) - except Exception: - self.logger.exception("Error processing folder {}".format(folder)) - - return added, found - - def _find_plugins_from_entry_points(self, groups, existing, ignore_uninstalled=True): - added = OrderedDict() - found = [] - - # let's make sure we have a current working set ... - working_set = pkg_resources.WorkingSet() - - # ... including the user's site packages - import site - import sys - if site.ENABLE_USER_SITE: - if not site.USER_SITE in working_set.entries: - working_set.add_entry(site.USER_SITE) - if not site.USER_SITE in sys.path: - site.addsitedir(site.USER_SITE) - - if not isinstance(groups, (list, tuple)): - groups = [groups] - - def wrapped(gen): - # to protect against some issues in installed packages that make iteration over entry points - # fall on its face - e.g. https://groups.google.com/forum/#!msg/octoprint/DyXdqhR0U7c/kKMUsMmIBgAJ - for entry in gen: - try: - yield entry - except Exception: - self.logger.exception("Something went wrong while processing the entry points of a package in the " - "Python environment - broken entry_points.txt in some package?") - - for group in groups: - for entry_point in wrapped(working_set.iter_entry_points(group=group, name=None)): - try: - key = entry_point.name - module_name = entry_point.module_name - version = entry_point.dist.version - - found.append(key) - if key in existing or key in added or (ignore_uninstalled and key in self.marked_plugins["uninstalled"]): - # plugin is already defined or marked as uninstalled, ignore it - continue - - bundled = key in self.plugin_considered_bundled - kwargs = {"module_name": module_name, - "version": version, - "bundled": bundled} - package_name = entry_point.dist.project_name - try: - entry_point_metadata = EntryPointMetadata(entry_point) - except Exception: - self.logger.exception("Something went wrong while retrieving metadata for module {}".format(module_name)) - else: - kwargs.update({"name": entry_point_metadata.name, - "summary": entry_point_metadata.summary, - "author": entry_point_metadata.author, - "url": entry_point_metadata.home_page, - "license": entry_point_metadata.license}) - - plugin = self._import_plugin_from_module(key, **kwargs) - if plugin: - plugin.origin = EntryPointOrigin("entry_point", group, module_name, package_name, version) - plugin.enabled = False - - # plugin is manageable if its location is writable and OctoPrint - # is either not running from a virtual env or the plugin is - # installed in that virtual env - the virtual env's pip will not - # allow us to uninstall stuff that is installed outside - # of the virtual env, so this check is necessary - plugin.managable = os.access(plugin.location, os.W_OK) \ - and (not self._python_virtual_env - or is_sub_path_of(plugin.location, self._python_prefix) - or is_editable_install(self._python_install_dir, - package_name, - module_name, - plugin.location)) - - added[key] = plugin - except Exception: - self.logger.exception("Error processing entry point {!r} for group {}".format(entry_point, group)) - - return added, found - - def _import_plugin_from_module(self, key, folder=None, module_name=None, name=None, version=None, summary=None, - author=None, url=None, license=None, bundled=False): - # TODO error handling - try: - if folder: - location, spec = _find_module(key, path=folder) - elif module_name: - location, spec = _find_module(module_name) - else: - return None - except Exception: - self.logger.exception("Could not locate plugin {key}".format(key=key)) - return None - - # Create a simple dummy entry first ... - plugin = PluginInfo(key, location, None, name=name, version=version, description=summary, author=author, - url=url, license=license) - plugin.bundled = bundled - - if self._is_plugin_disabled(key): - self.logger.info("Plugin {} is disabled.".format(plugin)) - plugin.forced_disabled = True - - if self._is_plugin_blacklisted(key) or (plugin.version is not None and self._is_plugin_version_blacklisted(key, plugin.version)): - self.logger.warning("Plugin {} is blacklisted.".format(plugin)) - plugin.blacklisted = True - - python_version = get_python_version_string() - if self._is_plugin_incompatible(key, plugin): - if plugin.invalid_syntax: - self.logger.warning("Plugin {} can't be compiled under Python {} due to invalid syntax".format(plugin, python_version)) - else: - self.logger.warning("Plugin {} is not compatible to Python {} (compatibility string: {}).".format(plugin, python_version, plugin.pythoncompat)) - plugin.incompatible = True - - if not plugin.validate("before_import", additional_validators=self.plugin_validators): - return plugin - - # ... then create and return the real one - return self._import_plugin(key, spec, - module_name=module_name, name=name, location=plugin.location, version=version, - summary=summary, author=author, url=url, license=license, bundled=bundled, - parsed_metadata=plugin.parsed_metadata) - - def _import_plugin(self, key, spec, module_name=None, name=None, location=None, version=None, summary=None, author=None, url=None, license=None, bundled=False, parsed_metadata=None): - try: - if module_name: - module = _load_module(module_name, spec) - else: - module = _load_module(key, spec) - - plugin = PluginInfo(key, location, module, - name=name, - version=version, - description=summary, - author=author, - url=url, - license=license, - parsed_metadata=parsed_metadata) - - plugin.bundled = bundled - except Exception: - self.logger.exception("Error loading plugin {key}".format(key=key)) - return None - - if plugin.check(): - return plugin - else: - self.logger.info("Plugin {plugin} did not pass check, not loading.".format(plugin=str(plugin))) - return None - - def _is_plugin_disabled(self, key): - return key in self.plugin_disabled_list or key.endswith('disabled') - - def _is_plugin_blacklisted(self, key): - return key in self.plugin_blacklist - - def _is_plugin_incompatible(self, key, plugin): - return not plugin.bundled \ - and not is_python_compatible(plugin.pythoncompat) \ - and key not in self.compatibility_ignored_list - - def _is_plugin_version_blacklisted(self, key, version): - def matches_plugin(entry): - if isinstance(entry, (tuple, list)) and len(entry) == 2: - entry_key, entry_version = entry - return entry_key == key and entry_version == version - return False - - return any(map(lambda entry: matches_plugin(entry), - self.plugin_blacklist)) - - def reload_plugins(self, startup=False, initialize_implementations=True, force_reload=None): - """ - Reloads plugins, detecting newly added ones in the process. - - Args: - startup (boolean): whether this is called during startup of the platform - initialize_implementations (boolean): whether plugin implementations should be initialized - force_reload (list): list of plugin identifiers which should be force reloaded - """ - self.logger.info("Loading plugins from {folders} and installed plugin packages...".format( - folders=", ".join(map(lambda x: x[0] if isinstance(x, tuple) else str(x), self.plugin_folders)) - )) - - if force_reload is None: - force_reload = [] - - added, found = self.find_plugins(existing=dict((k, v) for k, v in self.plugins.items() if not k in force_reload), - incl_all_found=True) - - # let's clean everything we DIDN'T find first - removed = [key for key in list(self.enabled_plugins.keys()) + list(self.disabled_plugins.keys()) if key not in found] - for key in removed: - try: - del self.enabled_plugins[key] - except KeyError: - pass - - try: - del self.disabled_plugins[key] - except KeyError: - pass - - self.disabled_plugins.update(added) - - # 1st pass: loading the plugins - for name, plugin in added.items(): - try: - if not plugin.blacklisted and not plugin.forced_disabled and not plugin.incompatible: - self.load_plugin(name, plugin, startup=startup, initialize_implementation=initialize_implementations) - except PluginNeedsRestart: - pass - except PluginLifecycleException as e: - self.logger.info(str(e)) - - self.on_plugins_loaded(startup=startup, - initialize_implementations=initialize_implementations, - force_reload=force_reload) - - # 2nd pass: enabling those plugins that need enabling - for name, plugin in added.items(): - try: - if plugin.loaded and not plugin.forced_disabled and not plugin.incompatible: - if plugin.blacklisted: - self.logger.warning("Plugin {} is blacklisted. Not enabling it.".format(plugin)) - continue - self.enable_plugin(name, plugin=plugin, initialize_implementation=initialize_implementations, startup=startup) - except PluginNeedsRestart: - pass - except PluginLifecycleException as e: - self.logger.info(str(e)) - - self.on_plugins_enabled(startup=startup, - initialize_implementations=initialize_implementations, - force_reload=force_reload) - - if len(self.enabled_plugins) <= 0: - self.logger.info("No plugins found") - else: - self.logger.info("Found {count} plugin(s) providing {implementations} mixin implementations, {hooks} hook handlers".format( - count=len(self.enabled_plugins) + len(self.disabled_plugins), - implementations=len(self.plugin_implementations), - hooks=sum(map(lambda x: len(x), self.plugin_hooks.values())) - )) - - def mark_plugin(self, name, **flags): - """ - Mark plugin ``name`` with an arbitrary number of flags. - - Args: - name (str): plugin identifier - **flags (dict): dictionary of flag names and values - """ - if not name in self.plugins: - self.logger.debug("Trying to mark an unknown plugin {name}".format(**locals())) - - for key, value in flags.items(): - if value is None: - continue - - if value and not name in self.marked_plugins[key]: - self.marked_plugins[key].append(name) - elif not value and name in self.marked_plugins[key]: - self.marked_plugins[key].remove(name) - - def is_plugin_marked(self, name, flag): - """ - Checks whether a plugin has been marked with a certain flag. - - Args: - name (str): the plugin's identifier - flag (str): the flag to check - - Returns: - (boolean): True if the plugin has been flagged, False otherwise - """ - if not name in self.plugins: - return False - - return name in self.marked_plugins[flag] - - def load_plugin(self, name, plugin=None, startup=False, initialize_implementation=True): - if not name in self.plugins: - self.logger.warning("Trying to load an unknown plugin {name}".format(**locals())) - return - - if plugin is None: - plugin = self.plugins[name] - - try: - if not plugin.validate("before_load", additional_validators=self.plugin_validators): - return - - plugin.load() - plugin.validate("after_load", additional_validators=self.plugin_validators) - self.on_plugin_loaded(name, plugin) - plugin.loaded = True - - self.logger.debug("Loaded plugin {name}: {plugin}".format(**locals())) - except PluginLifecycleException as e: - raise e - except Exception: - self.logger.exception("There was an error loading plugin %s" % name) - - def unload_plugin(self, name): - if not name in self.plugins: - self.logger.warning("Trying to unload unknown plugin {name}".format(**locals())) - return - - plugin = self.plugins[name] - - try: - if plugin.enabled: - self.disable_plugin(name, plugin=plugin) - - plugin.unload() - self.on_plugin_unloaded(name, plugin) - - if name in self.enabled_plugins: - del self.enabled_plugins[name] - - if name in self.disabled_plugins: - del self.disabled_plugins[name] - - plugin.loaded = False - - self.logger.debug("Unloaded plugin {name}: {plugin}".format(**locals())) - except PluginLifecycleException as e: - raise e - except Exception: - self.logger.exception("There was an error unloading plugin {name}".format(**locals())) - - # make sure the plugin is NOT in the list of enabled plugins but in the list of disabled plugins - if name in self.enabled_plugins: - del self.enabled_plugins[name] - if not name in self.disabled_plugins: - self.disabled_plugins[name] = plugin - - def enable_plugin(self, name, plugin=None, initialize_implementation=True, startup=False): - """Enables a plugin""" - if not name in self.disabled_plugins: - self.logger.warning("Tried to enable plugin {name}, however it is not disabled".format(**locals())) - return - - if plugin is None: - plugin = self.disabled_plugins[name] - - if not startup and self.is_restart_needing_plugin(plugin): - raise PluginNeedsRestart(name) - - if self.has_obsolete_hooks(plugin): - raise PluginCantEnable(name, "Dependency on obsolete hooks detected, full functionality cannot be guaranteed") - - try: - if not plugin.validate("before_enable", additional_validators=self.plugin_validators): - return False - - plugin.enable() - self._activate_plugin(name, plugin) - except PluginLifecycleException as e: - raise e - except Exception: - self.logger.exception("There was an error while enabling plugin {name}".format(**locals())) - return False - else: - if name in self.disabled_plugins: - del self.disabled_plugins[name] - self.enabled_plugins[name] = plugin - plugin.enabled = True - - if plugin.implementation: - if initialize_implementation: - if not self.initialize_implementation_of_plugin(name, plugin): - return False - plugin.implementation.on_plugin_enabled() - self.on_plugin_enabled(name, plugin) - - self.logger.debug("Enabled plugin {name}: {plugin}".format(**locals())) - - return True - - def disable_plugin(self, name, plugin=None): - """Disables a plugin""" - if not name in self.enabled_plugins: - self.logger.warning("Tried to disable plugin {name}, however it is not enabled".format(**locals())) - return - - if plugin is None: - plugin = self.enabled_plugins[name] - - if self.is_restart_needing_plugin(plugin): - raise PluginNeedsRestart(name) - - try: - plugin.disable() - self._deactivate_plugin(name, plugin) - except PluginLifecycleException as e: - raise e - except Exception: - self.logger.exception("There was an error while disabling plugin {name}".format(**locals())) - return False - else: - if name in self.enabled_plugins: - del self.enabled_plugins[name] - self.disabled_plugins[name] = plugin - plugin.enabled = False - - if plugin.implementation: - plugin.implementation.on_plugin_disabled() - self.on_plugin_disabled(name, plugin) - - self.logger.debug("Disabled plugin {name}: {plugin}".format(**locals())) - - return True - - def _activate_plugin(self, name, plugin): - plugin.hotchangeable = self.is_restart_needing_plugin(plugin) - - # evaluate registered hooks - for hook, definition in plugin.hooks.items(): - try: - callback, order = self._get_callback_and_order(definition) - except ValueError as e: - self.logger.warning("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e))) - continue - - self._plugin_hooks[hook].append((order, name, callback)) - self._sort_hooks(hook) - - # evaluate registered implementation - if plugin.implementation: - mixins = self.mixins_matching_bases(plugin.implementation.__class__, *self.plugin_bases) - for mixin in mixins: - self.plugin_implementations_by_type[mixin].append((name, plugin.implementation)) - if not getattr(plugin.implementation, "__timing_wrapped", False): - for method in filter(lambda a: not a.startswith("_") and callable(getattr(mixin, a)), dir(mixin)): - # wrap method with time_this - setattr(plugin.implementation, - method, - time_this(logtarget=self.plugin_timings_logtarget, - expand_logtarget=True, - message=self.plugin_timings_message)(getattr(plugin.implementation, method))) - - self.plugin_implementations[name] = plugin.implementation - setattr(plugin.implementation, "__timing_wrapped", True) - - def _deactivate_plugin(self, name, plugin): - for hook, definition in plugin.hooks.items(): - try: - callback, order = self._get_callback_and_order(definition) - except ValueError as e: - self.logger.warning("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e))) - continue - - try: - self._plugin_hooks[hook].remove((order, name, callback)) - self._sort_hooks(hook) - except ValueError: - # that's ok, the plugin was just not registered for the hook - pass - - if plugin.implementation is not None: - if name in self.plugin_implementations: - del self.plugin_implementations[name] - - mixins = self.mixins_matching_bases(plugin.implementation.__class__, *self.plugin_bases) - for mixin in mixins: - try: - self.plugin_implementations_by_type[mixin].remove((name, plugin.implementation)) - except ValueError: - # that's ok, the plugin was just not registered for the type - pass - - def is_restart_needing_plugin(self, plugin): - """Checks whether the plugin needs a restart on changes""" - return plugin.needs_restart or self.has_restart_needing_implementation(plugin) or self.has_restart_needing_hooks(plugin) - - def has_restart_needing_implementation(self, plugin): - """Checks whether the plugin's implementation needs a restart on changes""" - return self.has_any_of_mixins(plugin, RestartNeedingPlugin) - - def has_restart_needing_hooks(self, plugin): - """Checks whether the plugin has any hooks that need a restart on changes""" - return self.has_any_of_hooks(plugin, self.plugin_restart_needing_hooks) - - def has_obsolete_hooks(self, plugin): - """Checks whether the plugin uses any obsolete hooks""" - return self.has_any_of_hooks(plugin, self.plugin_obsolete_hooks) - - def is_restart_needing_hook(self, hook): - """Checks whether a hook needs a restart on changes""" - return self.hook_matches_hooks(hook, self.plugin_restart_needing_hooks) - - def is_obsolete_hook(self, hook): - """Checks whether a hook is obsolete""" - return self.hook_matches_hooks(hook, self.plugin_obsolete_hooks) - - @staticmethod - def has_any_of_hooks(plugin, *hooks): - """ - Tests if the ``plugin`` contains any of the provided ``hooks``. - - Uses :func:`octoprint.plugin.core.PluginManager.hook_matches_hooks`. - - Args: - plugin: plugin to test hooks for - *hooks: hooks to test against - - Returns: - (bool): True if any of the plugin's hooks match the provided hooks, - False otherwise. - """ - - if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)): - hooks = hooks[0] - - hooks = list(filter(lambda hook: hook is not None, hooks)) - if not hooks: - return False - if not plugin or not plugin.hooks: - return False - - plugin_hooks = plugin.hooks.keys() - - return any(map(lambda hook: PluginManager.hook_matches_hooks(hook, *hooks), - plugin_hooks)) - - @staticmethod - def hook_matches_hooks(hook, *hooks): - """ - Tests if ``hook`` matches any of the provided ``hooks`` to test for. - - ``hook`` is expected to be an exact hook name. - - ``hooks`` is expected to be a list containing one or more hook names or - patterns. That can be either an exact hook name or an - :func:`fnmatch.fnmatch` pattern. - - Args: - hook: the hook to test - hooks: the hook name patterns to test against - - Returns: - (bool): True if the ``hook`` matches any of the ``hooks``, False otherwise. - - """ - - if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)): - hooks = hooks[0] - - hooks = list(filter(lambda hook: hook is not None, hooks)) - if not hooks: - return False - if not hook: - return False - - return any(map(lambda h: fnmatch.fnmatch(hook, h), - hooks)) - - @staticmethod - def mixins_matching_bases(klass, *bases): - result = set() - for c in inspect.getmro(klass): - if c == klass or c in bases: - # ignore the exact class and our bases - continue - if issubclass(c, bases): - result.add(c) - return result - - @staticmethod - def has_any_of_mixins(plugin, *mixins): - """ - Tests if the ``plugin`` has an implementation implementing any - of the provided ``mixins``. - - Args: - plugin: plugin for which to check the implementation - *mixins: mixins to test against - - Returns: - (bool): True if the plugin's implementation implements any of the - provided mixins, False otherwise. - """ - - if mixins and len(mixins) == 1 and isinstance(mixins[0], (list, tuple)): - mixins = mixins[0] - - mixins = list(filter(lambda mixin: mixin is not None, mixins)) - if not mixins: - return False - if not plugin or not plugin.implementation: - return False - - return isinstance(plugin.implementation, tuple(mixins)) - - def initialize_implementations(self, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None): - for name, plugin in self.enabled_plugins.items(): - self.initialize_implementation_of_plugin(name, plugin, - additional_injects=additional_injects, - additional_inject_factories=additional_inject_factories, - additional_pre_inits=additional_pre_inits, - additional_post_inits=additional_post_inits) - - self.logger.info("Initialized {count} plugin implementation(s)".format(count=len(self.plugin_implementations))) - - def initialize_implementation_of_plugin(self, name, plugin, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None): - if plugin.implementation is None: - return - - return self.initialize_implementation(name, plugin, plugin.implementation, - additional_injects=additional_injects, - additional_inject_factories=additional_inject_factories, - additional_pre_inits=additional_pre_inits, - additional_post_inits=additional_post_inits) - - def initialize_implementation(self, name, plugin, implementation, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None): - if additional_injects is None: - additional_injects = {} - if additional_inject_factories is None: - additional_inject_factories = [] - if additional_pre_inits is None: - additional_pre_inits = [] - if additional_post_inits is None: - additional_post_inits = [] - - injects = self.implementation_injects - injects.update(additional_injects) - - inject_factories = self.implementation_inject_factories - inject_factories += additional_inject_factories - - pre_inits = self.implementation_pre_inits - pre_inits += additional_pre_inits - - post_inits = self.implementation_post_inits - post_inits += additional_post_inits - - try: - kwargs = dict(injects) - - kwargs.update({"identifier": name, - "plugin_name": plugin.name, - "plugin_version": plugin.version, - "plugin_info": plugin, - "basefolder": os.path.realpath(plugin.location), - "logger": logging.getLogger(self.logging_prefix + name)}) - - # inject the additional_injects - for arg, value in kwargs.items(): - setattr(implementation, "_" + arg, value) - - # inject any injects produced in the additional_inject_factories - for factory in inject_factories: - try: - return_value = factory(name, implementation) - except Exception: - self.logger.exception("Exception while executing injection factory %r" % factory) - else: - if return_value is not None: - if isinstance(return_value, dict): - for arg, value in return_value.items(): - setattr(implementation, "_" + arg, value) - - # execute any additional pre init methods - for pre_init in pre_inits: - pre_init(name, implementation) - - implementation.initialize() - - # execute any additional post init methods - for post_init in post_inits: - post_init(name, implementation) - - except Exception as e: - self._deactivate_plugin(name, plugin) - plugin.enabled = False - - if isinstance(e, PluginLifecycleException): - raise e - else: - self.logger.exception("Exception while initializing plugin {name}, disabling it".format(**locals())) - return False - else: - self.on_plugin_implementations_initialized(name, plugin) - - self.logger.debug("Initialized plugin mixin implementation for plugin {name}".format(**locals())) - return True - - - def log_all_plugins(self, show_bundled=True, bundled_str=(" (bundled)", ""), show_location=True, - location_str=" = {location}", show_enabled=True, enabled_str=(" ", "!", "#", "*"), - only_to_handler=None): - all_plugins = list(self.enabled_plugins.values()) + list(self.disabled_plugins.values()) - - def _log(message, level=logging.INFO): - if only_to_handler is not None: - import octoprint.logging - octoprint.logging.log_to_handler(self.logger, only_to_handler, level, message, []) - else: - self.logger.log(level, message) - - if len(all_plugins) <= 0: - _log("No plugins available") - else: - formatted_plugins = "\n".join(map(lambda x: "| " + x.long_str(show_bundled=show_bundled, - bundled_strs=bundled_str, - show_location=show_location, - location_str=location_str, - show_enabled=show_enabled, - enabled_strs=enabled_str), - sorted(self.plugins.values(), key=lambda x: unicode(x).lower()))) - legend = "Prefix legend: {1} = disabled, {2} = blacklisted, {3} = incompatible".format(*enabled_str) - _log("{count} plugin(s) registered with the system:\n{plugins}\n{legend}".format(count=len(all_plugins), - plugins=formatted_plugins, - legend=legend)) - - def get_plugin(self, identifier, require_enabled=True): - """ - Retrieves the module of the plugin identified by ``identifier``. If the plugin is not registered or disabled and - ``required_enabled`` is True (the default) None will be returned. - - Arguments: - identifier (str): The identifier of the plugin to retrieve. - require_enabled (boolean): Whether to only return the plugin if is enabled (True, default) or also if it's - disabled. - - Returns: - module: The requested plugin module or None - """ - - plugin_info = self.get_plugin_info(identifier, require_enabled=require_enabled) - if plugin_info is not None: - return plugin_info.instance - return None - - def get_plugin_info(self, identifier, require_enabled=True): - """ - Retrieves the :class:`PluginInfo` instance identified by ``identifier``. If the plugin is not registered or - disabled and ``required_enabled`` is True (the default) None will be returned. - - Arguments: - identifier (str): The identifier of the plugin to retrieve. - require_enabled (boolean): Whether to only return the plugin if is enabled (True, default) or also if it's - disabled. - - Returns: - ~.PluginInfo: The requested :class:`PluginInfo` or None - """ - - if identifier in self.enabled_plugins: - return self.enabled_plugins[identifier] - elif not require_enabled and identifier in self.disabled_plugins: - return self.disabled_plugins[identifier] - - return None - - def get_hooks(self, hook): - """ - Retrieves all registered handlers for the specified hook. - - Arguments: - hook (str): The hook for which to retrieve the handlers. - - Returns: - dict: A dict containing all registered handlers mapped by their plugin's identifier. - """ - - if not hook in self.plugin_hooks: - return {} - - result = OrderedDict() - for h in self.plugin_hooks[hook]: - result[h[0]] = time_this(logtarget=self.plugin_timings_logtarget, - expand_logtarget=True, - message=self.plugin_timings_message)(h[1]) - return result - - def get_implementations(self, *types, **kwargs): - """ - Get all mixin implementations that implement *all* of the provided ``types``. - - Arguments: - types (one or more type): The types a mixin implementation needs to implement in order to be returned. - - Returns: - list: A list of all found implementations - """ - - sorting_context = kwargs.get("sorting_context", None) - - result = None - - for t in types: - implementations = self.plugin_implementations_by_type[t] - if result is None: - result = set(implementations) - else: - result = result.intersection(implementations) - - if result is None: - return [] - - def sort_func(impl): - sorting_value = None - if sorting_context is not None and isinstance(impl[1], SortablePlugin): - try: - sorting_value = impl[1].get_sorting_key(sorting_context) - except Exception: - self.logger.exception("Error while trying to retrieve sorting order for plugin {}".format(impl[0])) - - if sorting_value is not None: - try: - sorting_value = int(sorting_value) - except ValueError: - self.logger.warning("The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format(impl[0], sorting_context)) - sorting_value = None - - plugin_info = self.get_plugin_info(impl[0], require_enabled=False) - return sorting_value is None, sv(sorting_value), not plugin_info.bundled if plugin_info else True, sv(impl[0]) - - return [impl[1] for impl in sorted(result, key=sort_func)] - - def get_filtered_implementations(self, f, *types, **kwargs): - """ - Get all mixin implementations that implement *all* of the provided ``types`` and match the provided filter `f`. - - Arguments: - f (callable): A filter function returning True for implementations to return and False for those to exclude. - types (one or more type): The types a mixin implementation needs to implement in order to be returned. - - Returns: - list: A list of all found and matching implementations. - """ - - assert callable(f) - implementations = self.get_implementations(*types, sorting_context=kwargs.get("sorting_context", None)) - return list(filter(f, implementations)) - - def get_helpers(self, name, *helpers): - """ - Retrieves the named ``helpers`` for the plugin with identifier ``name``. - - If the plugin is not available, returns None. Otherwise returns a :class:`dict` with the requested plugin - helper names mapped to the method - if a helper could not be resolved, it will be missing from the dict. - - Arguments: - name (str): Identifier of the plugin for which to look up the ``helpers``. - helpers (one or more str): Identifiers of the helpers of plugin ``name`` to return. - - Returns: - dict: A dictionary of all resolved helpers, mapped by their identifiers, or None if the plugin was not - registered with the system. - """ - - if not name in self.enabled_plugins: - return None - plugin = self.enabled_plugins[name] - - all_helpers = plugin.helpers - if len(helpers): - return dict((k, v) for (k, v) in all_helpers.items() if k in helpers) - else: - return all_helpers - - def register_message_receiver(self, client): - """ - Registers a ``client`` for receiving plugin messages. The ``client`` needs to be a callable accepting two - input arguments, ``plugin`` (the sending plugin's identifier) and ``data`` (the message itself), and one - optional keyword argument, ``permissions`` (an optional list of permissions to test against). - """ - - if client is None: - return - self.registered_clients.append(client) - - def unregister_message_receiver(self, client): - """ - Unregisters a ``client`` for receiving plugin messages. - """ - - try: - self.registered_clients.remove(client) - except ValueError: - # not registered - pass - - def send_plugin_message(self, plugin, data, permissions=None): - """ - Sends ``data`` in the name of ``plugin`` to all currently registered message receivers by invoking them - with the three arguments. - - Arguments: - plugin (str): The sending plugin's identifier. - data (object): The message. - permissions (list): A list of permissions to test against in the client. - """ - - for client in self.registered_clients: - try: - client(plugin, data, permissions=permissions) - except Exception: - self.logger.exception("Exception while sending plugin data to client") - - def _sort_hooks(self, hook): - self._plugin_hooks[hook] = sorted(self._plugin_hooks[hook], - key=lambda x: (x[0] is None, sv(x[0]), sv(x[1]), sv(x[2]))) - - def _get_callback_and_order(self, hook): - if callable(hook): - return hook, None - - elif isinstance(hook, tuple) and len(hook) == 2: - callback, order = hook - - # test that callback is a callable - if not callable(callback): - raise ValueError("Hook callback is not a callable") - - # test that number is an int - try: - int(order) - except ValueError: - raise ValueError("Hook order is not a number") - - return callback, order - - else: - raise ValueError("Invalid hook definition, neither a callable nor a 2-tuple (callback, order): {!r}".format(hook)) + """ + The :class:`PluginManager` is the central component for finding, loading and accessing plugins provided to the + system. + + It is able to discover plugins both through possible file system locations as well as customizable entry points. + """ + + plugin_timings_logtarget = "PLUGIN_TIMINGS" + plugin_timings_message = "{func} - {timing:05.2f}ms" + + def __init__( + self, + plugin_folders, + plugin_bases, + plugin_entry_points, + logging_prefix=None, + plugin_disabled_list=None, + plugin_blacklist=None, + plugin_restart_needing_hooks=None, + plugin_obsolete_hooks=None, + plugin_considered_bundled=None, + plugin_validators=None, + compatibility_ignored_list=None, + ): + self.logger = logging.getLogger(__name__) + + if logging_prefix is None: + logging_prefix = "" + if plugin_folders is None: + plugin_folders = [] + if plugin_bases is None: + plugin_bases = [] + if plugin_entry_points is None: + plugin_entry_points = [] + if plugin_disabled_list is None: + plugin_disabled_list = [] + if plugin_blacklist is None: + plugin_blacklist = [] + if compatibility_ignored_list is None: + compatibility_ignored_list = [] + if plugin_considered_bundled is None: + plugin_considered_bundled = [] + + self.plugin_folders = plugin_folders + self.plugin_bases = plugin_bases + self.plugin_entry_points = plugin_entry_points + self.plugin_disabled_list = plugin_disabled_list + self.plugin_blacklist = plugin_blacklist + self.plugin_restart_needing_hooks = plugin_restart_needing_hooks + self.plugin_obsolete_hooks = plugin_obsolete_hooks + self.plugin_validators = plugin_validators + self.logging_prefix = logging_prefix + self.compatibility_ignored_list = compatibility_ignored_list + self.plugin_considered_bundled = plugin_considered_bundled + + self.enabled_plugins = {} + self.disabled_plugins = {} + self.plugin_implementations = {} + self.plugin_implementations_by_type = defaultdict(list) + + self._plugin_hooks = defaultdict(list) + + self.implementation_injects = {} + self.implementation_inject_factories = [] + self.implementation_pre_inits = [] + self.implementation_post_inits = [] + + self.on_plugin_loaded = lambda *args, **kwargs: None + self.on_plugin_unloaded = lambda *args, **kwargs: None + self.on_plugin_enabled = lambda *args, **kwargs: None + self.on_plugin_disabled = lambda *args, **kwargs: None + self.on_plugin_implementations_initialized = lambda *args, **kwargs: None + + self.on_plugins_loaded = lambda *args, **kwargs: None + self.on_plugins_enabled = lambda *args, **kwargs: None + + self.registered_clients = [] + + self.marked_plugins = defaultdict(list) + + self._python_install_dir = None + self._python_virtual_env = False + self._detect_python_environment() + + def _detect_python_environment(self): + from distutils.command.install import install as cmd_install + from distutils.dist import Distribution + import sys + + cmd = cmd_install(Distribution()) + cmd.finalize_options() + + self._python_install_dir = cmd.install_lib + self._python_prefix = os.path.realpath(sys.prefix) + self._python_virtual_env = hasattr(sys, "real_prefix") or ( + hasattr(sys, "base_prefix") + and os.path.realpath(sys.prefix) != os.path.realpath(sys.base_prefix) + ) + + @property + def plugins(self): + """ + Returns: + (list) list of enabled and disabled registered plugins + """ + plugins = dict(self.enabled_plugins) + plugins.update(self.disabled_plugins) + return plugins + + @property + def plugin_hooks(self): + """ + Returns: + (dict) dictionary of registered hooks and their handlers + """ + return { + key: list(map(lambda v: (v[1], v[2]), value)) + for key, value in self._plugin_hooks.items() + } + + def find_plugins(self, existing=None, ignore_uninstalled=True, incl_all_found=False): + added, found = self._find_plugins( + existing=existing, ignore_uninstalled=ignore_uninstalled + ) + if incl_all_found: + return added, found + else: + return added + + def _find_plugins(self, existing=None, ignore_uninstalled=True): + if existing is None: + existing = dict(self.plugins) + + result_added = OrderedDict() + result_found = [] + + if self.plugin_folders: + try: + added, found = self._find_plugins_from_folders( + self.plugin_folders, existing, ignored_uninstalled=ignore_uninstalled + ) + result_added.update(added) + result_found += found + except Exception: + self.logger.exception("Error fetching plugins from folders") + + if self.plugin_entry_points: + existing.update(result_added) + try: + added, found = self._find_plugins_from_entry_points( + self.plugin_entry_points, + existing, + ignore_uninstalled=ignore_uninstalled, + ) + result_added.update(added) + result_found += found + except Exception: + self.logger.exception("Error fetching plugins from entry points") + + return result_added, result_found + + def _find_plugins_from_folders(self, folders, existing, ignored_uninstalled=True): + added = OrderedDict() + found = [] + + for folder in folders: + try: + flagged_readonly = False + package = None + if isinstance(folder, (list, tuple)): + if len(folder) == 2: + folder, flagged_readonly = folder + elif len(folder) == 3: + folder, package, flagged_readonly = folder + else: + continue + actual_readonly = not os.access(folder, os.W_OK) + + if not os.path.exists(folder): + self.logger.warning( + "Plugin folder {folder} could not be found, skipping it".format( + folder=folder + ) + ) + continue + + for entry in scandir(folder): + try: + if entry.is_dir(): + init_py = os.path.join(entry.path, "__init__.py") + init_pyc = os.path.join(entry.path, "__init__.pyc") + + if not os.path.isfile(init_py) and not os.path.isfile( + init_pyc + ): + # neither does exist, we ignore this + continue + + key = entry.name + + elif entry.is_file(): + key, ext = os.path.splitext(entry.name) + if ext not in (".py", ".pyc") or key.startswith("__"): + # neither py nor pyc, or starts with __ (like __init__), we ignore this + continue + + else: + # whatever this is, we ignore it + continue + + found.append(key) + if ( + key in existing + or key in added + or ( + ignored_uninstalled + and key in self.marked_plugins["uninstalled"] + ) + ): + # plugin is already defined, ignore it + continue + + bundled = flagged_readonly + + module_name = None + if package: + module_name = "{}.{}".format(package, key) + + plugin = self._import_plugin_from_module( + key, module_name=module_name, folder=folder, bundled=bundled + ) + if plugin: + if module_name: + plugin.origin = ModuleOrigin( + "module", module_name, folder + ) + else: + plugin.origin = FolderOrigin("folder", folder) + plugin.managable = ( + not flagged_readonly and not actual_readonly + ) + plugin.enabled = False + added[key] = plugin + except Exception: + self.logger.exception( + "Error processing folder entry {!r} from folder {}".format( + entry, folder + ) + ) + except Exception: + self.logger.exception("Error processing folder {}".format(folder)) + + return added, found + + def _find_plugins_from_entry_points(self, groups, existing, ignore_uninstalled=True): + added = OrderedDict() + found = [] + + # let's make sure we have a current working set ... + working_set = pkg_resources.WorkingSet() + + # ... including the user's site packages + import site + import sys + + if site.ENABLE_USER_SITE: + if not site.USER_SITE in working_set.entries: + working_set.add_entry(site.USER_SITE) + if not site.USER_SITE in sys.path: + site.addsitedir(site.USER_SITE) + + if not isinstance(groups, (list, tuple)): + groups = [groups] + + def wrapped(gen): + # to protect against some issues in installed packages that make iteration over entry points + # fall on its face - e.g. https://groups.google.com/forum/#!msg/octoprint/DyXdqhR0U7c/kKMUsMmIBgAJ + for entry in gen: + try: + yield entry + except Exception: + self.logger.exception( + "Something went wrong while processing the entry points of a package in the " + "Python environment - broken entry_points.txt in some package?" + ) + + for group in groups: + for entry_point in wrapped( + working_set.iter_entry_points(group=group, name=None) + ): + try: + key = entry_point.name + module_name = entry_point.module_name + version = entry_point.dist.version + + found.append(key) + if ( + key in existing + or key in added + or ( + ignore_uninstalled + and key in self.marked_plugins["uninstalled"] + ) + ): + # plugin is already defined or marked as uninstalled, ignore it + continue + + bundled = key in self.plugin_considered_bundled + kwargs = { + "module_name": module_name, + "version": version, + "bundled": bundled, + } + package_name = entry_point.dist.project_name + try: + entry_point_metadata = EntryPointMetadata(entry_point) + except Exception: + self.logger.exception( + "Something went wrong while retrieving metadata for module {}".format( + module_name + ) + ) + else: + kwargs.update( + { + "name": entry_point_metadata.name, + "summary": entry_point_metadata.summary, + "author": entry_point_metadata.author, + "url": entry_point_metadata.home_page, + "license": entry_point_metadata.license, + } + ) + + plugin = self._import_plugin_from_module(key, **kwargs) + if plugin: + plugin.origin = EntryPointOrigin( + "entry_point", group, module_name, package_name, version + ) + plugin.enabled = False + + # plugin is manageable if its location is writable and OctoPrint + # is either not running from a virtual env or the plugin is + # installed in that virtual env - the virtual env's pip will not + # allow us to uninstall stuff that is installed outside + # of the virtual env, so this check is necessary + plugin.managable = os.access(plugin.location, os.W_OK) and ( + not self._python_virtual_env + or is_sub_path_of(plugin.location, self._python_prefix) + or is_editable_install( + self._python_install_dir, + package_name, + module_name, + plugin.location, + ) + ) + + added[key] = plugin + except Exception: + self.logger.exception( + "Error processing entry point {!r} for group {}".format( + entry_point, group + ) + ) + + return added, found + + def _import_plugin_from_module( + self, + key, + folder=None, + module_name=None, + name=None, + version=None, + summary=None, + author=None, + url=None, + license=None, + bundled=False, + ): + # TODO error handling + try: + if folder: + location, spec = _find_module(key, path=folder) + elif module_name: + location, spec = _find_module(module_name) + else: + return None + except Exception: + self.logger.exception("Could not locate plugin {key}".format(key=key)) + return None + + # Create a simple dummy entry first ... + plugin = PluginInfo( + key, + location, + None, + name=name, + version=version, + description=summary, + author=author, + url=url, + license=license, + ) + plugin.bundled = bundled + + if self._is_plugin_disabled(key): + self.logger.info("Plugin {} is disabled.".format(plugin)) + plugin.forced_disabled = True + + if self._is_plugin_blacklisted(key) or ( + plugin.version is not None + and self._is_plugin_version_blacklisted(key, plugin.version) + ): + self.logger.warning("Plugin {} is blacklisted.".format(plugin)) + plugin.blacklisted = True + + python_version = get_python_version_string() + if self._is_plugin_incompatible(key, plugin): + if plugin.invalid_syntax: + self.logger.warning( + "Plugin {} can't be compiled under Python {} due to invalid syntax".format( + plugin, python_version + ) + ) + else: + self.logger.warning( + "Plugin {} is not compatible to Python {} (compatibility string: {}).".format( + plugin, python_version, plugin.pythoncompat + ) + ) + plugin.incompatible = True + + if not plugin.validate( + "before_import", additional_validators=self.plugin_validators + ): + return plugin + + # ... then create and return the real one + return self._import_plugin( + key, + spec, + module_name=module_name, + name=name, + location=plugin.location, + version=version, + summary=summary, + author=author, + url=url, + license=license, + bundled=bundled, + parsed_metadata=plugin.parsed_metadata, + ) + + def _import_plugin( + self, + key, + spec, + module_name=None, + name=None, + location=None, + version=None, + summary=None, + author=None, + url=None, + license=None, + bundled=False, + parsed_metadata=None, + ): + try: + if module_name: + module = _load_module(module_name, spec) + else: + module = _load_module(key, spec) + + plugin = PluginInfo( + key, + location, + module, + name=name, + version=version, + description=summary, + author=author, + url=url, + license=license, + parsed_metadata=parsed_metadata, + ) + + plugin.bundled = bundled + except Exception: + self.logger.exception("Error loading plugin {key}".format(key=key)) + return None + + if plugin.check(): + return plugin + else: + self.logger.info( + "Plugin {plugin} did not pass check, not loading.".format( + plugin=str(plugin) + ) + ) + return None + + def _is_plugin_disabled(self, key): + return key in self.plugin_disabled_list or key.endswith("disabled") + + def _is_plugin_blacklisted(self, key): + return key in self.plugin_blacklist + + def _is_plugin_incompatible(self, key, plugin): + return ( + not plugin.bundled + and not is_python_compatible(plugin.pythoncompat) + and key not in self.compatibility_ignored_list + ) + + def _is_plugin_version_blacklisted(self, key, version): + def matches_plugin(entry): + if isinstance(entry, (tuple, list)) and len(entry) == 2: + entry_key, entry_version = entry + return entry_key == key and entry_version == version + return False + + return any(map(lambda entry: matches_plugin(entry), self.plugin_blacklist)) + + def reload_plugins( + self, startup=False, initialize_implementations=True, force_reload=None + ): + """ + Reloads plugins, detecting newly added ones in the process. + + Args: + startup (boolean): whether this is called during startup of the platform + initialize_implementations (boolean): whether plugin implementations should be initialized + force_reload (list): list of plugin identifiers which should be force reloaded + """ + self.logger.info( + "Loading plugins from {folders} and installed plugin packages...".format( + folders=", ".join( + map( + lambda x: x[0] if isinstance(x, tuple) else str(x), + self.plugin_folders, + ) + ) + ) + ) + + if force_reload is None: + force_reload = [] + + added, found = self.find_plugins( + existing=dict( + (k, v) for k, v in self.plugins.items() if not k in force_reload + ), + incl_all_found=True, + ) + + # let's clean everything we DIDN'T find first + removed = [ + key + for key in list(self.enabled_plugins.keys()) + + list(self.disabled_plugins.keys()) + if key not in found + ] + for key in removed: + try: + del self.enabled_plugins[key] + except KeyError: + pass + + try: + del self.disabled_plugins[key] + except KeyError: + pass + + self.disabled_plugins.update(added) + + # 1st pass: loading the plugins + for name, plugin in added.items(): + try: + if ( + not plugin.blacklisted + and not plugin.forced_disabled + and not plugin.incompatible + ): + self.load_plugin( + name, + plugin, + startup=startup, + initialize_implementation=initialize_implementations, + ) + except PluginNeedsRestart: + pass + except PluginLifecycleException as e: + self.logger.info(str(e)) + + self.on_plugins_loaded( + startup=startup, + initialize_implementations=initialize_implementations, + force_reload=force_reload, + ) + + # 2nd pass: enabling those plugins that need enabling + for name, plugin in added.items(): + try: + if ( + plugin.loaded + and not plugin.forced_disabled + and not plugin.incompatible + ): + if plugin.blacklisted: + self.logger.warning( + "Plugin {} is blacklisted. Not enabling it.".format(plugin) + ) + continue + self.enable_plugin( + name, + plugin=plugin, + initialize_implementation=initialize_implementations, + startup=startup, + ) + except PluginNeedsRestart: + pass + except PluginLifecycleException as e: + self.logger.info(str(e)) + + self.on_plugins_enabled( + startup=startup, + initialize_implementations=initialize_implementations, + force_reload=force_reload, + ) + + if len(self.enabled_plugins) <= 0: + self.logger.info("No plugins found") + else: + self.logger.info( + "Found {count} plugin(s) providing {implementations} mixin implementations, {hooks} hook handlers".format( + count=len(self.enabled_plugins) + len(self.disabled_plugins), + implementations=len(self.plugin_implementations), + hooks=sum(map(lambda x: len(x), self.plugin_hooks.values())), + ) + ) + + def mark_plugin(self, name, **flags): + """ + Mark plugin ``name`` with an arbitrary number of flags. + + Args: + name (str): plugin identifier + **flags (dict): dictionary of flag names and values + """ + if not name in self.plugins: + self.logger.debug( + "Trying to mark an unknown plugin {name}".format(**locals()) + ) + + for key, value in flags.items(): + if value is None: + continue + + if value and not name in self.marked_plugins[key]: + self.marked_plugins[key].append(name) + elif not value and name in self.marked_plugins[key]: + self.marked_plugins[key].remove(name) + + def is_plugin_marked(self, name, flag): + """ + Checks whether a plugin has been marked with a certain flag. + + Args: + name (str): the plugin's identifier + flag (str): the flag to check + + Returns: + (boolean): True if the plugin has been flagged, False otherwise + """ + if not name in self.plugins: + return False + + return name in self.marked_plugins[flag] + + def load_plugin( + self, name, plugin=None, startup=False, initialize_implementation=True + ): + if not name in self.plugins: + self.logger.warning( + "Trying to load an unknown plugin {name}".format(**locals()) + ) + return + + if plugin is None: + plugin = self.plugins[name] + + try: + if not plugin.validate( + "before_load", additional_validators=self.plugin_validators + ): + return + + plugin.load() + plugin.validate("after_load", additional_validators=self.plugin_validators) + self.on_plugin_loaded(name, plugin) + plugin.loaded = True + + self.logger.debug("Loaded plugin {name}: {plugin}".format(**locals())) + except PluginLifecycleException as e: + raise e + except Exception: + self.logger.exception("There was an error loading plugin %s" % name) + + def unload_plugin(self, name): + if not name in self.plugins: + self.logger.warning( + "Trying to unload unknown plugin {name}".format(**locals()) + ) + return + + plugin = self.plugins[name] + + try: + if plugin.enabled: + self.disable_plugin(name, plugin=plugin) + + plugin.unload() + self.on_plugin_unloaded(name, plugin) + + if name in self.enabled_plugins: + del self.enabled_plugins[name] + + if name in self.disabled_plugins: + del self.disabled_plugins[name] + + plugin.loaded = False + + self.logger.debug("Unloaded plugin {name}: {plugin}".format(**locals())) + except PluginLifecycleException as e: + raise e + except Exception: + self.logger.exception( + "There was an error unloading plugin {name}".format(**locals()) + ) + + # make sure the plugin is NOT in the list of enabled plugins but in the list of disabled plugins + if name in self.enabled_plugins: + del self.enabled_plugins[name] + if not name in self.disabled_plugins: + self.disabled_plugins[name] = plugin + + def enable_plugin( + self, name, plugin=None, initialize_implementation=True, startup=False + ): + """Enables a plugin""" + if not name in self.disabled_plugins: + self.logger.warning( + "Tried to enable plugin {name}, however it is not disabled".format( + **locals() + ) + ) + return + + if plugin is None: + plugin = self.disabled_plugins[name] + + if not startup and self.is_restart_needing_plugin(plugin): + raise PluginNeedsRestart(name) + + if self.has_obsolete_hooks(plugin): + raise PluginCantEnable( + name, + "Dependency on obsolete hooks detected, full functionality cannot be guaranteed", + ) + + try: + if not plugin.validate( + "before_enable", additional_validators=self.plugin_validators + ): + return False + + plugin.enable() + self._activate_plugin(name, plugin) + except PluginLifecycleException as e: + raise e + except Exception: + self.logger.exception( + "There was an error while enabling plugin {name}".format(**locals()) + ) + return False + else: + if name in self.disabled_plugins: + del self.disabled_plugins[name] + self.enabled_plugins[name] = plugin + plugin.enabled = True + + if plugin.implementation: + if initialize_implementation: + if not self.initialize_implementation_of_plugin(name, plugin): + return False + plugin.implementation.on_plugin_enabled() + self.on_plugin_enabled(name, plugin) + + self.logger.debug("Enabled plugin {name}: {plugin}".format(**locals())) + + return True + + def disable_plugin(self, name, plugin=None): + """Disables a plugin""" + if not name in self.enabled_plugins: + self.logger.warning( + "Tried to disable plugin {name}, however it is not enabled".format( + **locals() + ) + ) + return + + if plugin is None: + plugin = self.enabled_plugins[name] + + if self.is_restart_needing_plugin(plugin): + raise PluginNeedsRestart(name) + + try: + plugin.disable() + self._deactivate_plugin(name, plugin) + except PluginLifecycleException as e: + raise e + except Exception: + self.logger.exception( + "There was an error while disabling plugin {name}".format(**locals()) + ) + return False + else: + if name in self.enabled_plugins: + del self.enabled_plugins[name] + self.disabled_plugins[name] = plugin + plugin.enabled = False + + if plugin.implementation: + plugin.implementation.on_plugin_disabled() + self.on_plugin_disabled(name, plugin) + + self.logger.debug("Disabled plugin {name}: {plugin}".format(**locals())) + + return True + + def _activate_plugin(self, name, plugin): + plugin.hotchangeable = self.is_restart_needing_plugin(plugin) + + # evaluate registered hooks + for hook, definition in plugin.hooks.items(): + try: + callback, order = self._get_callback_and_order(definition) + except ValueError as e: + self.logger.warning( + "There is something wrong with the hook definition {} for plugin {}: {}".format( + definition, name, str(e) + ) + ) + continue + + self._plugin_hooks[hook].append((order, name, callback)) + self._sort_hooks(hook) + + # evaluate registered implementation + if plugin.implementation: + mixins = self.mixins_matching_bases( + plugin.implementation.__class__, *self.plugin_bases + ) + for mixin in mixins: + self.plugin_implementations_by_type[mixin].append( + (name, plugin.implementation) + ) + if not getattr(plugin.implementation, "__timing_wrapped", False): + for method in filter( + lambda a: not a.startswith("_") and callable(getattr(mixin, a)), + dir(mixin), + ): + # wrap method with time_this + setattr( + plugin.implementation, + method, + time_this( + logtarget=self.plugin_timings_logtarget, + expand_logtarget=True, + message=self.plugin_timings_message, + )(getattr(plugin.implementation, method)), + ) + + self.plugin_implementations[name] = plugin.implementation + setattr(plugin.implementation, "__timing_wrapped", True) + + def _deactivate_plugin(self, name, plugin): + for hook, definition in plugin.hooks.items(): + try: + callback, order = self._get_callback_and_order(definition) + except ValueError as e: + self.logger.warning( + "There is something wrong with the hook definition {} for plugin {}: {}".format( + definition, name, str(e) + ) + ) + continue + + try: + self._plugin_hooks[hook].remove((order, name, callback)) + self._sort_hooks(hook) + except ValueError: + # that's ok, the plugin was just not registered for the hook + pass + + if plugin.implementation is not None: + if name in self.plugin_implementations: + del self.plugin_implementations[name] + + mixins = self.mixins_matching_bases( + plugin.implementation.__class__, *self.plugin_bases + ) + for mixin in mixins: + try: + self.plugin_implementations_by_type[mixin].remove( + (name, plugin.implementation) + ) + except ValueError: + # that's ok, the plugin was just not registered for the type + pass + + def is_restart_needing_plugin(self, plugin): + """Checks whether the plugin needs a restart on changes""" + return ( + plugin.needs_restart + or self.has_restart_needing_implementation(plugin) + or self.has_restart_needing_hooks(plugin) + ) + + def has_restart_needing_implementation(self, plugin): + """Checks whether the plugin's implementation needs a restart on changes""" + return self.has_any_of_mixins(plugin, RestartNeedingPlugin) + + def has_restart_needing_hooks(self, plugin): + """Checks whether the plugin has any hooks that need a restart on changes""" + return self.has_any_of_hooks(plugin, self.plugin_restart_needing_hooks) + + def has_obsolete_hooks(self, plugin): + """Checks whether the plugin uses any obsolete hooks""" + return self.has_any_of_hooks(plugin, self.plugin_obsolete_hooks) + + def is_restart_needing_hook(self, hook): + """Checks whether a hook needs a restart on changes""" + return self.hook_matches_hooks(hook, self.plugin_restart_needing_hooks) + + def is_obsolete_hook(self, hook): + """Checks whether a hook is obsolete""" + return self.hook_matches_hooks(hook, self.plugin_obsolete_hooks) + + @staticmethod + def has_any_of_hooks(plugin, *hooks): + """ + Tests if the ``plugin`` contains any of the provided ``hooks``. + + Uses :func:`octoprint.plugin.core.PluginManager.hook_matches_hooks`. + + Args: + plugin: plugin to test hooks for + *hooks: hooks to test against + + Returns: + (bool): True if any of the plugin's hooks match the provided hooks, + False otherwise. + """ + + if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)): + hooks = hooks[0] + + hooks = list(filter(lambda hook: hook is not None, hooks)) + if not hooks: + return False + if not plugin or not plugin.hooks: + return False + + plugin_hooks = plugin.hooks.keys() + + return any( + map(lambda hook: PluginManager.hook_matches_hooks(hook, *hooks), plugin_hooks) + ) + + @staticmethod + def hook_matches_hooks(hook, *hooks): + """ + Tests if ``hook`` matches any of the provided ``hooks`` to test for. + + ``hook`` is expected to be an exact hook name. + + ``hooks`` is expected to be a list containing one or more hook names or + patterns. That can be either an exact hook name or an + :func:`fnmatch.fnmatch` pattern. + + Args: + hook: the hook to test + hooks: the hook name patterns to test against + + Returns: + (bool): True if the ``hook`` matches any of the ``hooks``, False otherwise. + + """ + + if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)): + hooks = hooks[0] + + hooks = list(filter(lambda hook: hook is not None, hooks)) + if not hooks: + return False + if not hook: + return False + + return any(map(lambda h: fnmatch.fnmatch(hook, h), hooks)) + + @staticmethod + def mixins_matching_bases(klass, *bases): + result = set() + for c in inspect.getmro(klass): + if c == klass or c in bases: + # ignore the exact class and our bases + continue + if issubclass(c, bases): + result.add(c) + return result + + @staticmethod + def has_any_of_mixins(plugin, *mixins): + """ + Tests if the ``plugin`` has an implementation implementing any + of the provided ``mixins``. + + Args: + plugin: plugin for which to check the implementation + *mixins: mixins to test against + + Returns: + (bool): True if the plugin's implementation implements any of the + provided mixins, False otherwise. + """ + + if mixins and len(mixins) == 1 and isinstance(mixins[0], (list, tuple)): + mixins = mixins[0] + + mixins = list(filter(lambda mixin: mixin is not None, mixins)) + if not mixins: + return False + if not plugin or not plugin.implementation: + return False + + return isinstance(plugin.implementation, tuple(mixins)) + + def initialize_implementations( + self, + additional_injects=None, + additional_inject_factories=None, + additional_pre_inits=None, + additional_post_inits=None, + ): + for name, plugin in self.enabled_plugins.items(): + self.initialize_implementation_of_plugin( + name, + plugin, + additional_injects=additional_injects, + additional_inject_factories=additional_inject_factories, + additional_pre_inits=additional_pre_inits, + additional_post_inits=additional_post_inits, + ) + + self.logger.info( + "Initialized {count} plugin implementation(s)".format( + count=len(self.plugin_implementations) + ) + ) + + def initialize_implementation_of_plugin( + self, + name, + plugin, + additional_injects=None, + additional_inject_factories=None, + additional_pre_inits=None, + additional_post_inits=None, + ): + if plugin.implementation is None: + return + + return self.initialize_implementation( + name, + plugin, + plugin.implementation, + additional_injects=additional_injects, + additional_inject_factories=additional_inject_factories, + additional_pre_inits=additional_pre_inits, + additional_post_inits=additional_post_inits, + ) + + def initialize_implementation( + self, + name, + plugin, + implementation, + additional_injects=None, + additional_inject_factories=None, + additional_pre_inits=None, + additional_post_inits=None, + ): + if additional_injects is None: + additional_injects = {} + if additional_inject_factories is None: + additional_inject_factories = [] + if additional_pre_inits is None: + additional_pre_inits = [] + if additional_post_inits is None: + additional_post_inits = [] + + injects = self.implementation_injects + injects.update(additional_injects) + + inject_factories = self.implementation_inject_factories + inject_factories += additional_inject_factories + + pre_inits = self.implementation_pre_inits + pre_inits += additional_pre_inits + + post_inits = self.implementation_post_inits + post_inits += additional_post_inits + + try: + kwargs = dict(injects) + + kwargs.update( + { + "identifier": name, + "plugin_name": plugin.name, + "plugin_version": plugin.version, + "plugin_info": plugin, + "basefolder": os.path.realpath(plugin.location), + "logger": logging.getLogger(self.logging_prefix + name), + } + ) + + # inject the additional_injects + for arg, value in kwargs.items(): + setattr(implementation, "_" + arg, value) + + # inject any injects produced in the additional_inject_factories + for factory in inject_factories: + try: + return_value = factory(name, implementation) + except Exception: + self.logger.exception( + "Exception while executing injection factory %r" % factory + ) + else: + if return_value is not None: + if isinstance(return_value, dict): + for arg, value in return_value.items(): + setattr(implementation, "_" + arg, value) + + # execute any additional pre init methods + for pre_init in pre_inits: + pre_init(name, implementation) + + implementation.initialize() + + # execute any additional post init methods + for post_init in post_inits: + post_init(name, implementation) + + except Exception as e: + self._deactivate_plugin(name, plugin) + plugin.enabled = False + + if isinstance(e, PluginLifecycleException): + raise e + else: + self.logger.exception( + "Exception while initializing plugin {name}, disabling it".format( + **locals() + ) + ) + return False + else: + self.on_plugin_implementations_initialized(name, plugin) + + self.logger.debug( + "Initialized plugin mixin implementation for plugin {name}".format(**locals()) + ) + return True + + def log_all_plugins( + self, + show_bundled=True, + bundled_str=(" (bundled)", ""), + show_location=True, + location_str=" = {location}", + show_enabled=True, + enabled_str=(" ", "!", "#", "*"), + only_to_handler=None, + ): + all_plugins = list(self.enabled_plugins.values()) + list( + self.disabled_plugins.values() + ) + + def _log(message, level=logging.INFO): + if only_to_handler is not None: + import octoprint.logging + + octoprint.logging.log_to_handler( + self.logger, only_to_handler, level, message, [] + ) + else: + self.logger.log(level, message) + + if len(all_plugins) <= 0: + _log("No plugins available") + else: + formatted_plugins = "\n".join( + map( + lambda x: "| " + + x.long_str( + show_bundled=show_bundled, + bundled_strs=bundled_str, + show_location=show_location, + location_str=location_str, + show_enabled=show_enabled, + enabled_strs=enabled_str, + ), + sorted(self.plugins.values(), key=lambda x: unicode(x).lower()), + ) + ) + legend = "Prefix legend: {1} = disabled, {2} = blacklisted, {3} = incompatible".format( + *enabled_str + ) + _log( + "{count} plugin(s) registered with the system:\n{plugins}\n{legend}".format( + count=len(all_plugins), plugins=formatted_plugins, legend=legend + ) + ) + + def get_plugin(self, identifier, require_enabled=True): + """ + Retrieves the module of the plugin identified by ``identifier``. If the plugin is not registered or disabled and + ``required_enabled`` is True (the default) None will be returned. + + Arguments: + identifier (str): The identifier of the plugin to retrieve. + require_enabled (boolean): Whether to only return the plugin if is enabled (True, default) or also if it's + disabled. + + Returns: + module: The requested plugin module or None + """ + + plugin_info = self.get_plugin_info(identifier, require_enabled=require_enabled) + if plugin_info is not None: + return plugin_info.instance + return None + + def get_plugin_info(self, identifier, require_enabled=True): + """ + Retrieves the :class:`PluginInfo` instance identified by ``identifier``. If the plugin is not registered or + disabled and ``required_enabled`` is True (the default) None will be returned. + + Arguments: + identifier (str): The identifier of the plugin to retrieve. + require_enabled (boolean): Whether to only return the plugin if is enabled (True, default) or also if it's + disabled. + + Returns: + ~.PluginInfo: The requested :class:`PluginInfo` or None + """ + + if identifier in self.enabled_plugins: + return self.enabled_plugins[identifier] + elif not require_enabled and identifier in self.disabled_plugins: + return self.disabled_plugins[identifier] + + return None + + def get_hooks(self, hook): + """ + Retrieves all registered handlers for the specified hook. + + Arguments: + hook (str): The hook for which to retrieve the handlers. + + Returns: + dict: A dict containing all registered handlers mapped by their plugin's identifier. + """ + + if not hook in self.plugin_hooks: + return {} + + result = OrderedDict() + for h in self.plugin_hooks[hook]: + result[h[0]] = time_this( + logtarget=self.plugin_timings_logtarget, + expand_logtarget=True, + message=self.plugin_timings_message, + )(h[1]) + return result + + def get_implementations(self, *types, **kwargs): + """ + Get all mixin implementations that implement *all* of the provided ``types``. + + Arguments: + types (one or more type): The types a mixin implementation needs to implement in order to be returned. + + Returns: + list: A list of all found implementations + """ + + sorting_context = kwargs.get("sorting_context", None) + + result = None + + for t in types: + implementations = self.plugin_implementations_by_type[t] + if result is None: + result = set(implementations) + else: + result = result.intersection(implementations) + + if result is None: + return [] + + def sort_func(impl): + sorting_value = None + if sorting_context is not None and isinstance(impl[1], SortablePlugin): + try: + sorting_value = impl[1].get_sorting_key(sorting_context) + except Exception: + self.logger.exception( + "Error while trying to retrieve sorting order for plugin {}".format( + impl[0] + ) + ) + + if sorting_value is not None: + try: + sorting_value = int(sorting_value) + except ValueError: + self.logger.warning( + "The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format( + impl[0], sorting_context + ) + ) + sorting_value = None + + plugin_info = self.get_plugin_info(impl[0], require_enabled=False) + return ( + sorting_value is None, + sv(sorting_value), + not plugin_info.bundled if plugin_info else True, + sv(impl[0]), + ) + + return [impl[1] for impl in sorted(result, key=sort_func)] + + def get_filtered_implementations(self, f, *types, **kwargs): + """ + Get all mixin implementations that implement *all* of the provided ``types`` and match the provided filter `f`. + + Arguments: + f (callable): A filter function returning True for implementations to return and False for those to exclude. + types (one or more type): The types a mixin implementation needs to implement in order to be returned. + + Returns: + list: A list of all found and matching implementations. + """ + + assert callable(f) + implementations = self.get_implementations( + *types, sorting_context=kwargs.get("sorting_context", None) + ) + return list(filter(f, implementations)) + + def get_helpers(self, name, *helpers): + """ + Retrieves the named ``helpers`` for the plugin with identifier ``name``. + + If the plugin is not available, returns None. Otherwise returns a :class:`dict` with the requested plugin + helper names mapped to the method - if a helper could not be resolved, it will be missing from the dict. + + Arguments: + name (str): Identifier of the plugin for which to look up the ``helpers``. + helpers (one or more str): Identifiers of the helpers of plugin ``name`` to return. + + Returns: + dict: A dictionary of all resolved helpers, mapped by their identifiers, or None if the plugin was not + registered with the system. + """ + + if not name in self.enabled_plugins: + return None + plugin = self.enabled_plugins[name] + + all_helpers = plugin.helpers + if len(helpers): + return dict((k, v) for (k, v) in all_helpers.items() if k in helpers) + else: + return all_helpers + + def register_message_receiver(self, client): + """ + Registers a ``client`` for receiving plugin messages. The ``client`` needs to be a callable accepting two + input arguments, ``plugin`` (the sending plugin's identifier) and ``data`` (the message itself), and one + optional keyword argument, ``permissions`` (an optional list of permissions to test against). + """ + + if client is None: + return + self.registered_clients.append(client) + + def unregister_message_receiver(self, client): + """ + Unregisters a ``client`` for receiving plugin messages. + """ + + try: + self.registered_clients.remove(client) + except ValueError: + # not registered + pass + + def send_plugin_message(self, plugin, data, permissions=None): + """ + Sends ``data`` in the name of ``plugin`` to all currently registered message receivers by invoking them + with the three arguments. + + Arguments: + plugin (str): The sending plugin's identifier. + data (object): The message. + permissions (list): A list of permissions to test against in the client. + """ + + for client in self.registered_clients: + try: + client(plugin, data, permissions=permissions) + except Exception: + self.logger.exception("Exception while sending plugin data to client") + + def _sort_hooks(self, hook): + self._plugin_hooks[hook] = sorted( + self._plugin_hooks[hook], + key=lambda x: (x[0] is None, sv(x[0]), sv(x[1]), sv(x[2])), + ) + + def _get_callback_and_order(self, hook): + if callable(hook): + return hook, None + + elif isinstance(hook, tuple) and len(hook) == 2: + callback, order = hook + + # test that callback is a callable + if not callable(callback): + raise ValueError("Hook callback is not a callable") + + # test that number is an int + try: + int(order) + except ValueError: + raise ValueError("Hook order is not a number") + + return callback, order + + else: + raise ValueError( + "Invalid hook definition, neither a callable nor a 2-tuple (callback, order): {!r}".format( + hook + ) + ) def is_sub_path_of(path, parent): - """ - Tests if `path` is a sub path (or identical) to `path`. + """ + Tests if `path` is a sub path (or identical) to `path`. - >>> is_sub_path_of("/a/b/c", "/a/b") - True - >>> is_sub_path_of("/a/b/c", "/a/b2") - False - >>> is_sub_path_of("/a/b/c", "/b/c") - False - >>> is_sub_path_of("/foo/bar/../../a/b/c", "/a/b") - True - >>> is_sub_path_of("/a/b", "/a/b") - True - """ - rel_path = os.path.relpath(os.path.realpath(path), - os.path.realpath(parent)) - return not (rel_path == os.pardir or - rel_path.startswith(os.pardir + os.sep)) + >>> is_sub_path_of("/a/b/c", "/a/b") + True + >>> is_sub_path_of("/a/b/c", "/a/b2") + False + >>> is_sub_path_of("/a/b/c", "/b/c") + False + >>> is_sub_path_of("/foo/bar/../../a/b/c", "/a/b") + True + >>> is_sub_path_of("/a/b", "/a/b") + True + """ + rel_path = os.path.relpath(os.path.realpath(path), os.path.realpath(parent)) + return not (rel_path == os.pardir or rel_path.startswith(os.pardir + os.sep)) def is_editable_install(install_dir, package, module, location): - package_link = os.path.join(install_dir, "{}.egg-link".format(package)) - if os.path.isfile(package_link): - expected_target = os.path.normcase(os.path.realpath(location)) - try: - with io.open(package_link, 'rt', encoding='utf-8') as f: - contents = f.readlines() - for line in contents: - target = os.path.normcase(os.path.realpath(os.path.join(line.strip(), module))) - if target == expected_target: - return True - except Exception: - raise # TODO really ignore this? - pass - return False + package_link = os.path.join(install_dir, "{}.egg-link".format(package)) + if os.path.isfile(package_link): + expected_target = os.path.normcase(os.path.realpath(location)) + try: + with io.open(package_link, "rt", encoding="utf-8") as f: + contents = f.readlines() + for line in contents: + target = os.path.normcase( + os.path.realpath(os.path.join(line.strip(), module)) + ) + if target == expected_target: + return True + except Exception: + raise # TODO really ignore this? + pass + return False class EntryPointMetadata(pkginfo.Distribution): - def __init__(self, entry_point): - self.entry_point = entry_point - self.extractMetadata() + def __init__(self, entry_point): + self.entry_point = entry_point + self.extractMetadata() - def read(self): - import warnings + def read(self): + import warnings - metadata_files = ("METADATA", # wheel - "PKG-INFO") # egg + metadata_files = ("METADATA", "PKG-INFO") # wheel # egg - if self.entry_point and self.entry_point.dist: - for metadata_file in metadata_files: - try: - return self.entry_point.dist.get_metadata(metadata_file) - except (IOError, OSError): - # file not found, metadata file might be missing, ignore - # IOError: file not found in Py2 - # OSError (specifically FileNotFoundError): file not found in Py3 - pass + if self.entry_point and self.entry_point.dist: + for metadata_file in metadata_files: + try: + return self.entry_point.dist.get_metadata(metadata_file) + except (IOError, OSError): + # file not found, metadata file might be missing, ignore + # IOError: file not found in Py2 + # OSError (specifically FileNotFoundError): file not found in Py3 + pass - warnings.warn('No package metadata found for package {}'.format(self.entry_point.module_name)) + warnings.warn( + "No package metadata found for package {}".format( + self.entry_point.module_name + ) + ) class Plugin(object): - """ - The parent class of all plugin implementations. + """ + The parent class of all plugin implementations. - .. attribute:: _identifier + .. attribute:: _identifier - The identifier of the plugin. Injected by the plugin core system upon initialization of the implementation. + The identifier of the plugin. Injected by the plugin core system upon initialization of the implementation. - .. attribute:: _plugin_name + .. attribute:: _plugin_name - The name of the plugin. Injected by the plugin core system upon initialization of the implementation. + The name of the plugin. Injected by the plugin core system upon initialization of the implementation. - .. attribute:: _plugin_version + .. attribute:: _plugin_version - The version of the plugin. Injected by the plugin core system upon initialization of the implementation. + The version of the plugin. Injected by the plugin core system upon initialization of the implementation. - .. attribute:: _basefolder + .. attribute:: _basefolder - The base folder of the plugin. Injected by the plugin core system upon initialization of the implementation. + The base folder of the plugin. Injected by the plugin core system upon initialization of the implementation. - .. attribute:: _logger + .. attribute:: _logger - The logger instance to use, with the logging name set to the :attr:`PluginManager.logging_prefix` of the - :class:`PluginManager` concatenated with :attr:`_identifier`. Injected by the plugin core system upon - initialization of the implementation. - """ + The logger instance to use, with the logging name set to the :attr:`PluginManager.logging_prefix` of the + :class:`PluginManager` concatenated with :attr:`_identifier`. Injected by the plugin core system upon + initialization of the implementation. + """ - def __init__(self): - self._identifier = None - self._plugin_name = None - self._plugin_version = None - self._basefolder = None - self._logger = None + def __init__(self): + self._identifier = None + self._plugin_name = None + self._plugin_version = None + self._basefolder = None + self._logger = None - def initialize(self): - """ - Called by the plugin core after performing all injections. Override this to initialize your implementation. - """ - pass + def initialize(self): + """ + Called by the plugin core after performing all injections. Override this to initialize your implementation. + """ + pass - def on_plugin_enabled(self): - pass + def on_plugin_enabled(self): + pass + + def on_plugin_disabled(self): + pass - def on_plugin_disabled(self): - pass class RestartNeedingPlugin(Plugin): - """ - Mixin for plugin types that need a restart after enabling/disabling them. - """ + """ + Mixin for plugin types that need a restart after enabling/disabling them. + """ + class SortablePlugin(Plugin): - """ - Mixin for plugin types that are sortable. - """ + """ + Mixin for plugin types that are sortable. + """ - def get_sorting_key(self, context=None): - """ - Returns the sorting key to use for the implementation in the specified ``context``. + def get_sorting_key(self, context=None): + """ + Returns the sorting key to use for the implementation in the specified ``context``. - May return ``None`` if order is irrelevant. + May return ``None`` if order is irrelevant. - Implementations returning None will be ordered by plugin identifier - after all implementations which did return a sorting key value that was - not None sorted by that. + Implementations returning None will be ordered by plugin identifier + after all implementations which did return a sorting key value that was + not None sorted by that. - Arguments: - context (str): The sorting context for which to provide the - sorting key value. + Arguments: + context (str): The sorting context for which to provide the + sorting key value. + + Returns: + int or None: An integer signifying the sorting key value of the plugin + (sorting will be done ascending), or None if the implementation + doesn't care about calling order. + """ + return None - Returns: - int or None: An integer signifying the sorting key value of the plugin - (sorting will be done ascending), or None if the implementation - doesn't care about calling order. - """ - return None class PluginNeedsRestart(Exception): - def __init__(self, name): - Exception.__init__(self) - self.name = name - self.message = "Plugin {name} cannot be enabled or disabled after system startup".format(**locals()) + def __init__(self, name): + Exception.__init__(self) + self.name = name + self.message = ( + "Plugin {name} cannot be enabled or disabled after system startup".format( + **locals() + ) + ) + class PluginLifecycleException(Exception): - def __init__(self, name, reason, message): - Exception.__init__(self) - self.name = name - self.reason = reason + def __init__(self, name, reason, message): + Exception.__init__(self) + self.name = name + self.reason = reason - self.message = message.format(**locals()) + self.message = message.format(**locals()) + + def __str__(self): + return self.message - def __str__(self): - return self.message class PluginCantInitialize(PluginLifecycleException): - def __init__(self, name, reason): - PluginLifecycleException.__init__(self, name, reason, "Plugin {name} cannot be initialized: {reason}") + def __init__(self, name, reason): + PluginLifecycleException.__init__( + self, name, reason, "Plugin {name} cannot be initialized: {reason}" + ) + class PluginCantEnable(PluginLifecycleException): - def __init__(self, name, reason): - PluginLifecycleException.__init__(self, name, reason, "Plugin {name} cannot be enabled: {reason}") + def __init__(self, name, reason): + PluginLifecycleException.__init__( + self, name, reason, "Plugin {name} cannot be enabled: {reason}" + ) + class PluginCantDisable(PluginLifecycleException): - def __init__(self, name, reason): - PluginLifecycleException.__init__(self, name, reason, "Plugin {name} cannot be disabled: {reason}") + def __init__(self, name, reason): + PluginLifecycleException.__init__( + self, name, reason, "Plugin {name} cannot be disabled: {reason}" + ) diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index 80fffb22e..d866a9759 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -19,2103 +19,2166 @@ Please note that the plugin implementation types are documented in the section """ __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" -from .core import (Plugin, RestartNeedingPlugin, SortablePlugin) +from .core import Plugin, RestartNeedingPlugin, SortablePlugin + class OctoPrintPlugin(Plugin): - """ - The parent class of all OctoPrint plugin mixins. + """ + The parent class of all OctoPrint plugin mixins. - .. attribute:: _plugin_manager + .. attribute:: _plugin_manager - The :class:`~octoprint.plugin.core.PluginManager` instance. Injected by the plugin core system upon - initialization of the implementation. + The :class:`~octoprint.plugin.core.PluginManager` instance. Injected by the plugin core system upon + initialization of the implementation. - .. attribute:: _printer_profile_manager + .. attribute:: _printer_profile_manager - The :class:`~octoprint.printer.profile.PrinterProfileManager` instance. Injected by the plugin core system upon - initialization of the implementation. + The :class:`~octoprint.printer.profile.PrinterProfileManager` instance. Injected by the plugin core system upon + initialization of the implementation. - .. attribute:: _event_bus + .. attribute:: _event_bus - The :class:`~octoprint.events.EventManager` instance. Injected by the plugin core system upon initialization of - the implementation. + The :class:`~octoprint.events.EventManager` instance. Injected by the plugin core system upon initialization of + the implementation. - .. attribute:: _analysis_queue + .. attribute:: _analysis_queue - The :class:`~octoprint.filemanager.analysis.AnalysisQueue` instance. Injected by the plugin core system upon - initialization of the implementation. + The :class:`~octoprint.filemanager.analysis.AnalysisQueue` instance. Injected by the plugin core system upon + initialization of the implementation. - .. attribute:: _slicing_manager + .. attribute:: _slicing_manager - The :class:`~octoprint.slicing.SlicingManager` instance. Injected by the plugin core system upon initialization - of the implementation. + The :class:`~octoprint.slicing.SlicingManager` instance. Injected by the plugin core system upon initialization + of the implementation. - .. attribute:: _file_manager + .. attribute:: _file_manager - The :class:`~octoprint.filemanager.FileManager` instance. Injected by the plugin core system upon initialization - of the implementation. + The :class:`~octoprint.filemanager.FileManager` instance. Injected by the plugin core system upon initialization + of the implementation. - .. attribute:: _printer + .. attribute:: _printer - The :class:`~octoprint.printer.PrinterInterface` instance. Injected by the plugin core system upon initialization - of the implementation. + The :class:`~octoprint.printer.PrinterInterface` instance. Injected by the plugin core system upon initialization + of the implementation. - .. attribute:: _app_session_manager + .. attribute:: _app_session_manager - The :class:`~octoprint.access.users.SessionManager` instance. Injected by the plugin core system upon initialization of - the implementation. + The :class:`~octoprint.access.users.SessionManager` instance. Injected by the plugin core system upon initialization of + the implementation. - .. attribute:: _plugin_lifecycle_manager + .. attribute:: _plugin_lifecycle_manager - The :class:`~octoprint.server.LifecycleManager` instance. Injected by the plugin core system upon initialization - of the implementation. + The :class:`~octoprint.server.LifecycleManager` instance. Injected by the plugin core system upon initialization + of the implementation. - .. attribute:: _user_manager + .. attribute:: _user_manager - The :class:`~octoprint.access.users.UserManager` instance. Injected by the plugin core system upon initialization - of the implementation. + The :class:`~octoprint.access.users.UserManager` instance. Injected by the plugin core system upon initialization + of the implementation. - .. attribute:: _connectivity_checker + .. attribute:: _connectivity_checker - The :class:`~octoprint.util.ConnectivityChecker` instance. Injected by the plugin core system upon initialization - of the implementation. + The :class:`~octoprint.util.ConnectivityChecker` instance. Injected by the plugin core system upon initialization + of the implementation. - .. attribute:: _data_folder + .. attribute:: _data_folder - Path to the data folder for the plugin to use for any data it might have to persist. Should always be accessed - through :meth:`get_plugin_data_folder` since that function will also ensure that the data folder actually exists - and if not creating it before returning it. Injected by the plugin core system upon initialization of the - implementation. - """ + Path to the data folder for the plugin to use for any data it might have to persist. Should always be accessed + through :meth:`get_plugin_data_folder` since that function will also ensure that the data folder actually exists + and if not creating it before returning it. Injected by the plugin core system upon initialization of the + implementation. + """ - # noinspection PyMissingConstructor - def __init__(self): - self._plugin_manager = None - self._printer_profile_manager = None - self._event_bus = None - self._analysis_queue = None - self._slicing_manager = None - self._file_manager = None - self._printer = None - self._app_session_manager = None - self._plugin_lifecycle_manager = None - self._user_manager = None - self._connectivity_checker = None - self._data_folder = None + # noinspection PyMissingConstructor + def __init__(self): + self._plugin_manager = None + self._printer_profile_manager = None + self._event_bus = None + self._analysis_queue = None + self._slicing_manager = None + self._file_manager = None + self._printer = None + self._app_session_manager = None + self._plugin_lifecycle_manager = None + self._user_manager = None + self._connectivity_checker = None + self._data_folder = None - def get_plugin_data_folder(self): - """ - Retrieves the path to a data folder specifically for the plugin, ensuring it exists and if not creating it - before returning it. + def get_plugin_data_folder(self): + """ + Retrieves the path to a data folder specifically for the plugin, ensuring it exists and if not creating it + before returning it. - Plugins may use this folder for storing additional data they need for their operation. - """ - if self._data_folder is None: - raise RuntimeError("self._plugin_data_folder is None, has the plugin been initialized yet?") + Plugins may use this folder for storing additional data they need for their operation. + """ + if self._data_folder is None: + raise RuntimeError( + "self._plugin_data_folder is None, has the plugin been initialized yet?" + ) - import os - if not os.path.isdir(self._data_folder): - os.makedirs(self._data_folder) - return self._data_folder + import os + + if not os.path.isdir(self._data_folder): + os.makedirs(self._data_folder) + return self._data_folder class ReloadNeedingPlugin(Plugin): - """ - Mixin for plugin types that need a reload of the UI after enabling/disabling them. - """ + """ + Mixin for plugin types that need a reload of the UI after enabling/disabling them. + """ class EnvironmentDetectionPlugin(OctoPrintPlugin, RestartNeedingPlugin): - """ - .. versionadded:: 1.3.6 - """ + """ + .. versionadded:: 1.3.6 + """ - def get_additional_environment(self): - pass + def get_additional_environment(self): + pass - def on_environment_detected(self, environment, *args, **kwargs): - pass + def on_environment_detected(self, environment, *args, **kwargs): + pass class StartupPlugin(OctoPrintPlugin, SortablePlugin): - """ - The ``StartupPlugin`` allows hooking into the startup of OctoPrint. It can be used to start up additional services - on or just after the startup of the server. + """ + The ``StartupPlugin`` allows hooking into the startup of OctoPrint. It can be used to start up additional services + on or just after the startup of the server. - ``StartupPlugin`` is a :class:`~octoprint.plugin.core.SortablePlugin` and provides - sorting contexts for :meth:`~octoprint.plugin.StartupPlugin.on_startup` as well as - :meth:`~octoprint.plugin.StartupPlugin.on_after_startup`. - """ + ``StartupPlugin`` is a :class:`~octoprint.plugin.core.SortablePlugin` and provides + sorting contexts for :meth:`~octoprint.plugin.StartupPlugin.on_startup` as well as + :meth:`~octoprint.plugin.StartupPlugin.on_after_startup`. + """ - def on_startup(self, host, port): - """ - Called just before the server is actually launched. Plugins get supplied with the ``host`` and ``port`` the server - will listen on. Note that the ``host`` may be ``0.0.0.0`` if it will listen on all interfaces, so you can't just - blindly use this for constructing publicly reachable URLs. Also note that when this method is called, the server - is not actually up yet and none of your plugin's APIs or blueprints will be reachable yet. If you need to be - externally reachable, use :func:`on_after_startup` instead or additionally. + def on_startup(self, host, port): + """ + Called just before the server is actually launched. Plugins get supplied with the ``host`` and ``port`` the server + will listen on. Note that the ``host`` may be ``0.0.0.0`` if it will listen on all interfaces, so you can't just + blindly use this for constructing publicly reachable URLs. Also note that when this method is called, the server + is not actually up yet and none of your plugin's APIs or blueprints will be reachable yet. If you need to be + externally reachable, use :func:`on_after_startup` instead or additionally. - .. warning:: + .. warning:: - Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server. + Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server. - The relevant sorting context is ``StartupPlugin.on_startup``. + The relevant sorting context is ``StartupPlugin.on_startup``. - :param string host: the host the server will listen on, may be ``0.0.0.0`` - :param int port: the port the server will listen on - """ + :param string host: the host the server will listen on, may be ``0.0.0.0`` + :param int port: the port the server will listen on + """ - pass + pass - def on_after_startup(self): - """ - Called just after launch of the server, so when the listen loop is actually running already. + def on_after_startup(self): + """ + Called just after launch of the server, so when the listen loop is actually running already. - .. warning:: + .. warning:: - Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server. + Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server. - The relevant sorting context is ``StartupPlugin.on_after_startup``. - """ + The relevant sorting context is ``StartupPlugin.on_after_startup``. + """ - pass + pass class ShutdownPlugin(OctoPrintPlugin, SortablePlugin): - """ - The ``ShutdownPlugin`` allows hooking into the shutdown of OctoPrint. It's usually used in conjunction with the - :class:`StartupPlugin` mixin, to cleanly shut down additional services again that where started by the :class:`StartupPlugin` - part of the plugin. + """ + The ``ShutdownPlugin`` allows hooking into the shutdown of OctoPrint. It's usually used in conjunction with the + :class:`StartupPlugin` mixin, to cleanly shut down additional services again that where started by the :class:`StartupPlugin` + part of the plugin. - ``ShutdownPlugin`` is a :class:`~octoprint.plugin.core.SortablePlugin` and provides a sorting context for - :meth:`~octoprint.plugin.ShutdownPlugin.on_shutdown`. - """ + ``ShutdownPlugin`` is a :class:`~octoprint.plugin.core.SortablePlugin` and provides a sorting context for + :meth:`~octoprint.plugin.ShutdownPlugin.on_shutdown`. + """ - def on_shutdown(self): - """ - Called upon the imminent shutdown of OctoPrint. + def on_shutdown(self): + """ + Called upon the imminent shutdown of OctoPrint. - .. warning:: + .. warning:: - Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server. + Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server. - The relevant sorting context is ``ShutdownPlugin.on_shutdown``. - """ - pass + The relevant sorting context is ``ShutdownPlugin.on_shutdown``. + """ + pass class AssetPlugin(OctoPrintPlugin, RestartNeedingPlugin): - """ - The ``AssetPlugin`` mixin allows plugins to define additional static assets such as JavaScript or CSS files to - be automatically embedded into the pages delivered by the server to be used within the client sided part of - the plugin. + """ + The ``AssetPlugin`` mixin allows plugins to define additional static assets such as JavaScript or CSS files to + be automatically embedded into the pages delivered by the server to be used within the client sided part of + the plugin. - A typical usage of the ``AssetPlugin`` functionality is to embed a custom view model to be used by templates injected - through a :class:`TemplatePlugin`. + A typical usage of the ``AssetPlugin`` functionality is to embed a custom view model to be used by templates injected + through a :class:`TemplatePlugin`. - ``AssetPlugin`` is a :class:`~octoprint.plugins.core.RestartNeedingPlugin`. - """ + ``AssetPlugin`` is a :class:`~octoprint.plugins.core.RestartNeedingPlugin`. + """ - def get_asset_folder(self): - """ - Defines the folder where the plugin stores its static assets as defined in :func:`get_assets`. Override this if - your plugin stores its assets at some other place than the ``static`` sub folder in the plugin base directory. + def get_asset_folder(self): + """ + Defines the folder where the plugin stores its static assets as defined in :func:`get_assets`. Override this if + your plugin stores its assets at some other place than the ``static`` sub folder in the plugin base directory. - :return string: the absolute path to the folder where the plugin stores its static assets - """ - import os - return os.path.join(self._basefolder, "static") + :return string: the absolute path to the folder where the plugin stores its static assets + """ + import os - def get_assets(self): - """ - Defines the static assets the plugin offers. The following asset types are recognized and automatically - imported at the appropriate places to be available: + return os.path.join(self._basefolder, "static") - js - JavaScript files, such as additional view models - jsclient - JavaScript files containing additional parts for the JS Client Library (since 1.3.10) - css - CSS files with additional styles, will be embedded into delivered pages when not running in LESS mode. - less - LESS files with additional styles, will be embedded into delivered pages when running in LESS mode. + def get_assets(self): + """ + Defines the static assets the plugin offers. The following asset types are recognized and automatically + imported at the appropriate places to be available: - The expected format to be returned is a dictionary mapping one or more of these keys to a list of files of that - type, the files being represented as relative paths from the asset folder as defined via :func:`get_asset_folder`. - Example: + js + JavaScript files, such as additional view models + jsclient + JavaScript files containing additional parts for the JS Client Library (since 1.3.10) + css + CSS files with additional styles, will be embedded into delivered pages when not running in LESS mode. + less + LESS files with additional styles, will be embedded into delivered pages when running in LESS mode. - .. code-block:: python + The expected format to be returned is a dictionary mapping one or more of these keys to a list of files of that + type, the files being represented as relative paths from the asset folder as defined via :func:`get_asset_folder`. + Example: - def get_assets(self): - return dict( - js=['js/my_file.js', 'js/my_other_file.js'], - clientjs=['clientjs/my_file.js'], - css=['css/my_styles.css'], - less=['less/my_styles.less'] - ) + .. code-block:: python - The assets will be made available by OctoPrint under the URL ``/plugin//static/``, with - ``plugin identifier`` being the plugin's identifier and ``path`` being the path as defined in the asset dictionary. + def get_assets(self): + return dict( + js=['js/my_file.js', 'js/my_other_file.js'], + clientjs=['clientjs/my_file.js'], + css=['css/my_styles.css'], + less=['less/my_styles.less'] + ) - Assets of the types ``js``, ``css`` and ``less`` will be automatically bundled by OctoPrint using - `Flask-Assets `_. + The assets will be made available by OctoPrint under the URL ``/plugin//static/``, with + ``plugin identifier`` being the plugin's identifier and ``path`` being the path as defined in the asset dictionary. - :return dict: a dictionary describing the static assets to publish for the plugin - """ - return {} + Assets of the types ``js``, ``css`` and ``less`` will be automatically bundled by OctoPrint using + `Flask-Assets `_. + + :return dict: a dictionary describing the static assets to publish for the plugin + """ + return {} class TemplatePlugin(OctoPrintPlugin, ReloadNeedingPlugin): - """ - Using the ``TemplatePlugin`` mixin plugins may inject their own components into the OctoPrint web interface. + """ + Using the ``TemplatePlugin`` mixin plugins may inject their own components into the OctoPrint web interface. - Currently OctoPrint supports the following types of injections out of the box: + Currently OctoPrint supports the following types of injections out of the box: - Navbar - The right part of the navigation bar located at the top of the UI can be enriched with additional links. Note that - with the current implementation, plugins will always be located *to the left* of the existing links. + Navbar + The right part of the navigation bar located at the top of the UI can be enriched with additional links. Note that + with the current implementation, plugins will always be located *to the left* of the existing links. - The included template must be called ``_navbar.jinja2`` (e.g. ``myplugin_navbar.jinja2``) unless - overridden by the configuration supplied through :func:`get_template_configs`. + The included template must be called ``_navbar.jinja2`` (e.g. ``myplugin_navbar.jinja2``) unless + overridden by the configuration supplied through :func:`get_template_configs`. - The template will be already wrapped into the necessary structure, plugins just need to supply the pure content. The - wrapper structure will have all additional classes and styles applied as specified via the configuration supplied - through :func:`get_template_configs`. + The template will be already wrapped into the necessary structure, plugins just need to supply the pure content. The + wrapper structure will have all additional classes and styles applied as specified via the configuration supplied + through :func:`get_template_configs`. - Sidebar - The left side bar containing Connection, State and Files sections can be enriched with additional sections. Note - that with the current implementations, plugins will always be located *beneath* the existing sections. + Sidebar + The left side bar containing Connection, State and Files sections can be enriched with additional sections. Note + that with the current implementations, plugins will always be located *beneath* the existing sections. - The included template must be called ``_sidebar.jinja2`` (e.g. ``myplugin_sidebar.jinja2``) unless - overridden by the configuration supplied through :func:`get_template_configs`. + The included template must be called ``_sidebar.jinja2`` (e.g. ``myplugin_sidebar.jinja2``) unless + overridden by the configuration supplied through :func:`get_template_configs`. - The template will be already wrapped into the necessary structure, plugins just need to supply the pure content. The - wrapper divs for both the whole box as well as the content pane will have all additional classes and styles applied - as specified via the configuration supplied through :func:`get_template_configs`. + The template will be already wrapped into the necessary structure, plugins just need to supply the pure content. The + wrapper divs for both the whole box as well as the content pane will have all additional classes and styles applied + as specified via the configuration supplied through :func:`get_template_configs`. - Tabs - The available tabs of the main part of the interface may be extended with additional tabs originating from within - plugins. Note that with the current implementation, plugins will always be located *to the right* of the existing - tabs. + Tabs + The available tabs of the main part of the interface may be extended with additional tabs originating from within + plugins. Note that with the current implementation, plugins will always be located *to the right* of the existing + tabs. - The included template must be called ``_tab.jinja2`` (e.g. ``myplugin_tab.jinja2``) unless - overridden by the configuration supplied through :func:`get_template_configs`. + The included template must be called ``_tab.jinja2`` (e.g. ``myplugin_tab.jinja2``) unless + overridden by the configuration supplied through :func:`get_template_configs`. - The template will be already wrapped into the necessary structure, plugins just need to supply the pure content. The - wrapper div and the link in the navigation will have the additional classes and styles applied as specified via the - configuration supplied through :func:`get_template_configs`. + The template will be already wrapped into the necessary structure, plugins just need to supply the pure content. The + wrapper div and the link in the navigation will have the additional classes and styles applied as specified via the + configuration supplied through :func:`get_template_configs`. - Settings - Plugins may inject a dialog into the existing settings view. Note that with the current implementation, plugins - will always be listed beneath the "Plugins" header in the settings link list, ordered alphabetically after - their displayed name. + Settings + Plugins may inject a dialog into the existing settings view. Note that with the current implementation, plugins + will always be listed beneath the "Plugins" header in the settings link list, ordered alphabetically after + their displayed name. - The included template must be called ``_settings.jinja2`` (e.g. ``myplugin_settings.jinja2``) unless - overridden by the configuration supplied through :func:`get_template_configs`. + The included template must be called ``_settings.jinja2`` (e.g. ``myplugin_settings.jinja2``) unless + overridden by the configuration supplied through :func:`get_template_configs`. - The template will be already wrapped into the necessary structure, plugins just need to supply the pure content. The - wrapper div and the link in the navigation will have the additional classes and styles applied as defined via the - configuration through :func:`get_template_configs`. + The template will be already wrapped into the necessary structure, plugins just need to supply the pure content. The + wrapper div and the link in the navigation will have the additional classes and styles applied as defined via the + configuration through :func:`get_template_configs`. - Wizards - Plugins may define wizard dialogs to display to the user if necessary (e.g. in case of missing information that - needs to be queried from the user to make the plugin work). Note that with the current implementation, all - wizard dialogs will be will always be sorted by their ``mandatory`` attribute (which defaults to ``False``) and then - alphabetically by their ``name``. Hence, mandatory wizard steps will come first, sorted alphabetically, then the - optional steps will follow, also alphabetically. A wizard dialog provided through a plugin will only be displayed - if the plugin reports the wizard as being required through :meth:`~octoprint.plugin.WizardPlugin.is_wizard_required`. - Please also refer to the :class:`~octoprint.plugin.WizardPlugin` mixin for further details on this. + Wizards + Plugins may define wizard dialogs to display to the user if necessary (e.g. in case of missing information that + needs to be queried from the user to make the plugin work). Note that with the current implementation, all + wizard dialogs will be will always be sorted by their ``mandatory`` attribute (which defaults to ``False``) and then + alphabetically by their ``name``. Hence, mandatory wizard steps will come first, sorted alphabetically, then the + optional steps will follow, also alphabetically. A wizard dialog provided through a plugin will only be displayed + if the plugin reports the wizard as being required through :meth:`~octoprint.plugin.WizardPlugin.is_wizard_required`. + Please also refer to the :class:`~octoprint.plugin.WizardPlugin` mixin for further details on this. - The included template must be called ``_wizard.jinja2`` (e.g. ``myplugin_wizard.jinja2``) unless - overridden by the configuration supplied through :func:`get_template_configs`. + The included template must be called ``_wizard.jinja2`` (e.g. ``myplugin_wizard.jinja2``) unless + overridden by the configuration supplied through :func:`get_template_configs`. - The template will be already wrapped into the necessary structure, plugins just need to supply the pure content. - The wrapper div and the link in the wizard navigation will have the additional classes and styles applied as defined - via the configuration supplied through :func:`get_template_configs`. + The template will be already wrapped into the necessary structure, plugins just need to supply the pure content. + The wrapper div and the link in the wizard navigation will have the additional classes and styles applied as defined + via the configuration supplied through :func:`get_template_configs`. - .. note:: + .. note:: - A note about ``mandatory`` wizard steps: In the current implementation, marking a wizard step as - mandatory will *only* make it styled accordingly. It is the task of the :ref:`view model ` - to actually prevent the user from skipping the dialog by implementing the ``onWizardTabChange`` - callback and returning ``false`` there if it is detected that the user hasn't yet filled in the - wizard step. + A note about ``mandatory`` wizard steps: In the current implementation, marking a wizard step as + mandatory will *only* make it styled accordingly. It is the task of the :ref:`view model ` + to actually prevent the user from skipping the dialog by implementing the ``onWizardTabChange`` + callback and returning ``false`` there if it is detected that the user hasn't yet filled in the + wizard step. - .. versionadded:: 1.3.0 + .. versionadded:: 1.3.0 - About - Plugins may define additional panels into OctoPrint's "About" dialog. Note that with the current implementation - further about dialog panels will be sorted alphabetically by their name and sorted after the predefined ones. + About + Plugins may define additional panels into OctoPrint's "About" dialog. Note that with the current implementation + further about dialog panels will be sorted alphabetically by their name and sorted after the predefined ones. - The included template must be called ``_about.jinja2`` (e.g. ``myplugin_about.jinja2``) unless - overridden by the configuration supplied through :func:`get_template_configs`. + The included template must be called ``_about.jinja2`` (e.g. ``myplugin_about.jinja2``) unless + overridden by the configuration supplied through :func:`get_template_configs`. - The template will be already wrapped into the necessary structure, plugins just need to supply the pure content. The - wrapped div and the link in the navigation will have the additional classes and styles applied as defined via - the configuration supplied through :func:`get_template_configs`. + The template will be already wrapped into the necessary structure, plugins just need to supply the pure content. The + wrapped div and the link in the navigation will have the additional classes and styles applied as defined via + the configuration supplied through :func:`get_template_configs`. - .. versionadded:: 1.3.0 + .. versionadded:: 1.3.0 - Generic - Plugins may also inject arbitrary templates into the page of the web interface itself, e.g. in order to - add overlays or dialogs to be called from within the plugin's JavaScript code. + Generic + Plugins may also inject arbitrary templates into the page of the web interface itself, e.g. in order to + add overlays or dialogs to be called from within the plugin's JavaScript code. - .. figure:: ../images/template-plugin-types-main.png - :align: center - :alt: Template injection types in the main part of the interface - - Template injection types in the main part of the interface - - .. figure:: ../images/template-plugin-types-settings.png - :align: center - :alt: Template injection types in the settings - - Template injection types in the settings - - You can find an example for a simple plugin which injects navbar, tab and settings content into the interface in - the "helloworld" plugin in OctoPrint's :ref:`Plugin Tutorial `. - - Plugins may replace existing components, see the ``replaces`` keyword in the template configurations returned by - :meth:`.get_template_configs` below. Note that if a plugin replaces a core component, it is the plugin's - responsibility to ensure that all core functionality is still maintained. - - Plugins can also add additional template types by implementing the :ref:`octoprint.ui.web.templatetypes ` hook. - - ``TemplatePlugin`` is a :class:`~octoprint.plugin.core.ReloadNeedingPlugin`. - """ - - def get_template_configs(self): - """ - Allows configuration of injected navbar, sidebar, tab and settings templates (and also additional templates of - types specified by plugins through the :ref:`octoprint.ui.web.templatetypes ` hook). - Should be a list containing one configuration object per template to inject. Each configuration object is - represented by a dictionary which may contain the following keys: - - .. list-table:: - :widths: 5 95 - - * - type - - The template type the configuration is targeting. Possible values here are ``navbar``, ``sidebar``, - ``tab``, ``settings`` and ``generic``. Mandatory. - * - name - - The name of the component, if not set the name of the plugin will be used. The name will be visible at - a location depending on the ``type``: - - * ``navbar``: unused - * ``sidebar``: sidebar heading - * ``tab``: tab heading - * ``settings``: settings link - * ``wizard``: wizard link - * ``about``: about link - * ``generic``: unused - - * - template - - Name of the template to inject, default value depends on the ``type``: - - * ``navbar``: ``_navbar.jinja2`` - * ``sidebar``: ``_sidebar.jinja2`` - * ``tab``: ``_tab.jinja2`` - * ``settings``: ``_settings.jinja2`` - * ``wizard``: ``_wizard.jinja2`` - * ``about``: ``_about.jinja2`` - * ``generic``: ``.jinja2`` - - * - suffix - - Suffix to attach to the component identifier and the div identifier of the injected template. Will be - ``_`` if not provided and not the first template of the type, with ``index`` counting from 1 and - increasing for each template of the same type. - - Example: If your plugin with identifier ``myplugin`` defines two tab components like this: - - .. code-block:: python - - return [ - dict(type="tab", template="myplugin_first_tab.jinja2"), - dict(type="tab", template="myplugin_second_tab.jinja2") - ] - - then the first tab will have the component identifier ``plugin_myplugin`` and the second one will have - the component identifier ``plugin_myplugin_2`` (the generated divs will be ``tab_plugin_myplugin`` and - ``tab_plugin_myplugin_2`` accordingly). Notice that the first tab is *not* called ``plugin_myplugin_1`` -- - as stated above while the ``index`` used as default suffix starts counting at 1, it will not be applied - for the first component of a given type. - - If on the other hand your plugin's definition looks like this: - - .. code-block:: python - - return [ - dict(type="tab", template="myplugin_first_tab_jinja2", suffix="_1st"), - dict(type="tab", template="myplugin_second_tab_jinja2", suffix="_2nd") - ] - - then the generated component identifier will be ``plugin_myplugin_1st`` and ``plugin_myplugin_2nd`` - (and the divs will be ``tab_plugin_myplugin_1st`` and ``tab_plugin_myplugin_2nd``). - - * - div - - Id for the div containing the component. If not provided, defaults to ``_plugin_`` plus - the ``suffix`` if provided or required. - * - replaces - - Id of the component this one replaces, might be either one of the core components or a component - provided by another plugin. A list of the core component identifiers can be found - :ref:`in the configuration documentation `. The identifiers of - other plugin components always follow the format described above. - * - custom_bindings - - A boolean value indicating whether the default view model should be bound to the component (``false``) - or if a custom binding will be used by the plugin (``true``, default). - * - data_bind - - Additional knockout data bindings to apply to the component, can be used to add further behaviour to - the container based on internal state if necessary. - * - classes - - Additional classes to apply to the component, as a list of individual classes - (e.g. ``classes=["myclass", "myotherclass"]``) which will be joined into the correct format by the template engine. - * - styles - - Additional CSS styles to apply to the component, as a list of individual declarations - (e.g. ``styles=["color: red", "display: block"]``) which will be joined into the correct format by the template - engine. - - Further keys to be included in the dictionary depend on the type: - - ``sidebar`` type - - .. list-table:: - :widths: 5 95 - - * - icon - - Icon to use for the sidebar header, should be the name of a Font Awesome icon without the leading ``icon-`` part. - * - template_header - - Additional template to include in the head section of the sidebar item. For an example of this, see the additional - options included in the "Files" section. - * - classes_wrapper - - Like ``classes`` but only applied to the whole wrapper around the sidebar box. - * - classes_content - - Like ``classes`` but only applied to the content pane itself. - * - styles_wrapper - - Like ``styles`` but only applied to the whole wrapper around the sidebar box. - * - styles_content - - Like ``styles`` but only applied to the content pane itself - - ``tab`` type and ``settings`` type - - .. list-table:: - :widths: 5 95 - - * - classes_link - - Like ``classes`` but only applied to the link in the navigation. - * - classes_content - - Like ``classes`` but only applied to the content pane itself. - * - styles_link - - Like ``styles`` but only applied to the link in the navigation. - * - styles_content - - Like ``styles`` but only applied to the content pane itself. - - ``wizard`` type - - .. list-table:: - :widths: 5 95 - - * - mandatory - - Whether the wizard step is mandatory (True) or not (False). Optional, - defaults to False. If set to True, OctoPrint will sort visually mark - the step as mandatory in the UI (bold in the navigation and a little - alert) and also sort it into the first half. - - .. note:: - - As already outlined above, each template type has a default template name (i.e. the default navbar template - of a plugin is called ``_navbar.jinja2``), which may be overridden using the template configuration. - If a plugin needs to include more than one template of a given type, it needs to provide an entry for each of - those, since the implicit default template will only be included automatically if no other templates of that - type are defined. - - Example: If you have a plugin that injects two tab components, one defined in the template file - ``myplugin_tab.jinja2`` (the default template) and one in the template ``myplugin_othertab.jinja2``, you - might be tempted to just return the following configuration since one your templates is named by the default - template name: - - .. code-block:: python - - return [ - dict(type="tab", template="myplugin_othertab.jinja2") - ] - - This will only include the tab defined in ``myplugin_othertab.jinja2`` though, ``myplugin_tab.jinja2`` will - not be included automatically since the presence of a definition for the ``tab`` type overrides the automatic - injection of the default template. You'll have to include it explicitly: - - .. code-block:: python - - return [ - dict(type="tab", template="myplugin_tab.jinja2"), - dict(type="tab", template="myplugin_othertab.jinja2") - ] - - :return list: a list containing the configuration options for the plugin's injected templates - """ - return [] - - def get_template_vars(self): - """ - Defines additional template variables to include into the template renderer. Variable names will be prefixed - with ``plugin__``. - - :return dict: a dictionary containing any additional template variables to include in the renderer - """ - return {} - - def get_template_folder(self): - """ - Defines the folder where the plugin stores its templates. Override this if your plugin stores its templates at - some other place than the ``templates`` sub folder in the plugin base directory. - - :return string: the absolute path to the folder where the plugin stores its jinja2 templates - """ - import os - return os.path.join(self._basefolder, "templates") + .. figure:: ../images/template-plugin-types-main.png + :align: center + :alt: Template injection types in the main part of the interface + + Template injection types in the main part of the interface + + .. figure:: ../images/template-plugin-types-settings.png + :align: center + :alt: Template injection types in the settings + + Template injection types in the settings + + You can find an example for a simple plugin which injects navbar, tab and settings content into the interface in + the "helloworld" plugin in OctoPrint's :ref:`Plugin Tutorial `. + + Plugins may replace existing components, see the ``replaces`` keyword in the template configurations returned by + :meth:`.get_template_configs` below. Note that if a plugin replaces a core component, it is the plugin's + responsibility to ensure that all core functionality is still maintained. + + Plugins can also add additional template types by implementing the :ref:`octoprint.ui.web.templatetypes ` hook. + + ``TemplatePlugin`` is a :class:`~octoprint.plugin.core.ReloadNeedingPlugin`. + """ + + def get_template_configs(self): + """ + Allows configuration of injected navbar, sidebar, tab and settings templates (and also additional templates of + types specified by plugins through the :ref:`octoprint.ui.web.templatetypes ` hook). + Should be a list containing one configuration object per template to inject. Each configuration object is + represented by a dictionary which may contain the following keys: + + .. list-table:: + :widths: 5 95 + + * - type + - The template type the configuration is targeting. Possible values here are ``navbar``, ``sidebar``, + ``tab``, ``settings`` and ``generic``. Mandatory. + * - name + - The name of the component, if not set the name of the plugin will be used. The name will be visible at + a location depending on the ``type``: + + * ``navbar``: unused + * ``sidebar``: sidebar heading + * ``tab``: tab heading + * ``settings``: settings link + * ``wizard``: wizard link + * ``about``: about link + * ``generic``: unused + + * - template + - Name of the template to inject, default value depends on the ``type``: + + * ``navbar``: ``_navbar.jinja2`` + * ``sidebar``: ``_sidebar.jinja2`` + * ``tab``: ``_tab.jinja2`` + * ``settings``: ``_settings.jinja2`` + * ``wizard``: ``_wizard.jinja2`` + * ``about``: ``_about.jinja2`` + * ``generic``: ``.jinja2`` + + * - suffix + - Suffix to attach to the component identifier and the div identifier of the injected template. Will be + ``_`` if not provided and not the first template of the type, with ``index`` counting from 1 and + increasing for each template of the same type. + + Example: If your plugin with identifier ``myplugin`` defines two tab components like this: + + .. code-block:: python + + return [ + dict(type="tab", template="myplugin_first_tab.jinja2"), + dict(type="tab", template="myplugin_second_tab.jinja2") + ] + + then the first tab will have the component identifier ``plugin_myplugin`` and the second one will have + the component identifier ``plugin_myplugin_2`` (the generated divs will be ``tab_plugin_myplugin`` and + ``tab_plugin_myplugin_2`` accordingly). Notice that the first tab is *not* called ``plugin_myplugin_1`` -- + as stated above while the ``index`` used as default suffix starts counting at 1, it will not be applied + for the first component of a given type. + + If on the other hand your plugin's definition looks like this: + + .. code-block:: python + + return [ + dict(type="tab", template="myplugin_first_tab_jinja2", suffix="_1st"), + dict(type="tab", template="myplugin_second_tab_jinja2", suffix="_2nd") + ] + + then the generated component identifier will be ``plugin_myplugin_1st`` and ``plugin_myplugin_2nd`` + (and the divs will be ``tab_plugin_myplugin_1st`` and ``tab_plugin_myplugin_2nd``). + + * - div + - Id for the div containing the component. If not provided, defaults to ``_plugin_`` plus + the ``suffix`` if provided or required. + * - replaces + - Id of the component this one replaces, might be either one of the core components or a component + provided by another plugin. A list of the core component identifiers can be found + :ref:`in the configuration documentation `. The identifiers of + other plugin components always follow the format described above. + * - custom_bindings + - A boolean value indicating whether the default view model should be bound to the component (``false``) + or if a custom binding will be used by the plugin (``true``, default). + * - data_bind + - Additional knockout data bindings to apply to the component, can be used to add further behaviour to + the container based on internal state if necessary. + * - classes + - Additional classes to apply to the component, as a list of individual classes + (e.g. ``classes=["myclass", "myotherclass"]``) which will be joined into the correct format by the template engine. + * - styles + - Additional CSS styles to apply to the component, as a list of individual declarations + (e.g. ``styles=["color: red", "display: block"]``) which will be joined into the correct format by the template + engine. + + Further keys to be included in the dictionary depend on the type: + + ``sidebar`` type + + .. list-table:: + :widths: 5 95 + + * - icon + - Icon to use for the sidebar header, should be the name of a Font Awesome icon without the leading ``icon-`` part. + * - template_header + - Additional template to include in the head section of the sidebar item. For an example of this, see the additional + options included in the "Files" section. + * - classes_wrapper + - Like ``classes`` but only applied to the whole wrapper around the sidebar box. + * - classes_content + - Like ``classes`` but only applied to the content pane itself. + * - styles_wrapper + - Like ``styles`` but only applied to the whole wrapper around the sidebar box. + * - styles_content + - Like ``styles`` but only applied to the content pane itself + + ``tab`` type and ``settings`` type + + .. list-table:: + :widths: 5 95 + + * - classes_link + - Like ``classes`` but only applied to the link in the navigation. + * - classes_content + - Like ``classes`` but only applied to the content pane itself. + * - styles_link + - Like ``styles`` but only applied to the link in the navigation. + * - styles_content + - Like ``styles`` but only applied to the content pane itself. + + ``wizard`` type + + .. list-table:: + :widths: 5 95 + + * - mandatory + - Whether the wizard step is mandatory (True) or not (False). Optional, + defaults to False. If set to True, OctoPrint will sort visually mark + the step as mandatory in the UI (bold in the navigation and a little + alert) and also sort it into the first half. + + .. note:: + + As already outlined above, each template type has a default template name (i.e. the default navbar template + of a plugin is called ``_navbar.jinja2``), which may be overridden using the template configuration. + If a plugin needs to include more than one template of a given type, it needs to provide an entry for each of + those, since the implicit default template will only be included automatically if no other templates of that + type are defined. + + Example: If you have a plugin that injects two tab components, one defined in the template file + ``myplugin_tab.jinja2`` (the default template) and one in the template ``myplugin_othertab.jinja2``, you + might be tempted to just return the following configuration since one your templates is named by the default + template name: + + .. code-block:: python + + return [ + dict(type="tab", template="myplugin_othertab.jinja2") + ] + + This will only include the tab defined in ``myplugin_othertab.jinja2`` though, ``myplugin_tab.jinja2`` will + not be included automatically since the presence of a definition for the ``tab`` type overrides the automatic + injection of the default template. You'll have to include it explicitly: + + .. code-block:: python + + return [ + dict(type="tab", template="myplugin_tab.jinja2"), + dict(type="tab", template="myplugin_othertab.jinja2") + ] + + :return list: a list containing the configuration options for the plugin's injected templates + """ + return [] + + def get_template_vars(self): + """ + Defines additional template variables to include into the template renderer. Variable names will be prefixed + with ``plugin__``. + + :return dict: a dictionary containing any additional template variables to include in the renderer + """ + return {} + + def get_template_folder(self): + """ + Defines the folder where the plugin stores its templates. Override this if your plugin stores its templates at + some other place than the ``templates`` sub folder in the plugin base directory. + + :return string: the absolute path to the folder where the plugin stores its jinja2 templates + """ + import os + + return os.path.join(self._basefolder, "templates") class UiPlugin(OctoPrintPlugin, SortablePlugin): - """ - The ``UiPlugin`` mixin allows plugins to completely replace the UI served - by OctoPrint when requesting the main page hosted at `/`. - - OctoPrint will query whether your mixin implementation will handle a - provided request by calling :meth:`~octoprint.plugin.UiPlugin.will_handle_ui` with the Flask - `Request `_ object as - parameter. If you plugin returns `True` here, OctoPrint will next call - :meth:`~octoprint.plugin.UiPlugin.on_ui_render` with a few parameters like - - again - the Flask Request object and the render keyword arguments as - used by the default OctoPrint web interface. For more information see below. - - There are two methods used in order to allow for caching of the actual - response sent to the client. Whatever a plugin implementation returns - from the call to its :meth:`~octoprint.plugin.UiPlugin.on_ui_render` method - will be cached server side. The cache will be emptied in case of explicit - no-cache headers sent by the client, or if the ``_refresh`` query parameter - on the request exists and is set to ``true``. To prevent caching of the - response altogether, a plugin may set no-cache headers on the returned - response as well. - - ``UiPlugin`` is a :class:`~octoprint.plugin.core.SortablePlugin` with a sorting context - for :meth:`~octoprint.plugin.UiPlugin.will_handle_ui`. The first plugin to return ``True`` - for :meth:`~octoprint.plugin.UiPlugin.will_handle_ui` will be the one whose ui will be used, - no further calls to :meth:`~octoprint.plugin.UiPlugin.on_ui_render` will be performed. - - If implementations want to serve custom templates in the :meth:`~octoprint.plugin.UiPlugin.on_ui_render` - method it is recommended to also implement the :class:`~octoprint.plugin.TemplatePlugin` - mixin. - - **Example** - - What follows is a very simple example that renders a different (non functional and - only exemplary) UI if the requesting client has a UserAgent string hinting - at it being a mobile device: - - .. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/dummy_mobile_ui/__init__.py - :linenos: - :tab-width: 4 - :caption: `dummy_mobile_ui/__init__.py `_ - - .. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/dummy_mobile_ui/templates/dummy_mobile_ui_index.jinja2 - :linenos: - :tab-width: 4 - :caption: `dummy_mobile_ui/templates/dummy_mobile_ui_index.jinja2 `_ - - Try installing the above plugin ``dummy_mobile_ui`` (also available in the - `plugin examples repository `_) - into your OctoPrint instance. If you access it from a regular desktop browser, - you should still see the default UI. However if you access it from a mobile - device (make sure to not have that request the desktop version of pages!) - you should see the very simple dummy page defined above. - - **Preemptive and Runtime Caching** - - OctoPrint will also cache your custom UI for you in its server side UI cache, making sure - it only gets re-rendered if the request demands that (by having no-cache headers set) or if - the cache gets invalidated otherwise. - - In order to be able to do that, the ``UiPlugin`` offers overriding some cache specific - methods used for figuring out the source files whose modification time to use for cache invalidation - as well as override possibilities for ETag and LastModified calculation. Additionally there are - methods to allow persisting call parameters to allow for preemptively caching your UI during - server startup (basically eager caching instead of lazily waiting for the first request). - - See below for details on this. - - .. versionadded:: 1.3.0 - """ - - # noinspection PyMethodMayBeStatic,PyUnusedLocal - def will_handle_ui(self, request): - """ - Called by OctoPrint to determine if the mixin implementation will be - able to handle the ``request`` provided as a parameter. - - Return ``True`` here to signal that your implementation will handle - the request and that the result of its :meth:`~octoprint.plugin.UiPlugin.on_ui_render` method - is what should be served to the user. - - The execution order of calls to this method can be influenced via the sorting context - ``UiPlugin.will_handle_ui``. - - Arguments: - request (flask.Request): A Flask `Request `_ - object. - - Returns: - bool: ``True`` if the the implementation will serve the request, - ``False`` otherwise. - """ - return False - - # noinspection PyMethodMayBeStatic,PyUnusedLocal - def on_ui_render(self, now, request, render_kwargs): - """ - Called by OctoPrint to retrieve the response to send to the client - for the ``request`` to ``/``. Only called if :meth:`~octoprint.plugin.UiPlugin.will_handle_ui` - returned ``True``. - - ``render_kwargs`` will be a dictionary (whose contents are cached) which - will contain the following key and value pairs (note that not all - key value pairs contained in the dictionary are listed here, only - those you should depend on as a plugin developer at the current time): - - .. list-table:: - :widths: 5 95 - - * - debug - - ``True`` if debug mode is enabled, ``False`` otherwise. - * - firstRun - - ``True`` if the server is being run for the first time (not - configured yet), ``False`` otherwise. - * - version - - OctoPrint's version information. This is a ``dict`` with the - following keys: - - .. list-table:: - :widths: 5 95 - - * - number - - The version number (e.g. ``x.y.z``) - * - branch - - The GIT branch from which the OctoPrint instance was built - (e.g. ``master``) - * - display - - The full human readable version string, including the - branch information (e.g. ``x.y.z (master branch)`` - - * - uiApiKey - - The UI API key to use for unauthorized API requests. This is - freshly generated on every server restart. - * - templates - - Template data to render in the UI. Will be a ``dict`` containing entries - for all known template types. - - The sub structure for each key will be as follows: - - .. list-table:: - :widths: 5 95 - - * - order - - A list of template names in the order they should appear - in the final rendered page - * - entries - - The template entry definitions to render. Depending on the - template type those are either 2-tuples of a name and a ``dict`` - or directly ``dicts`` with information regarding the - template to render. - - For the possible contents of the data ``dicts`` see the - :class:`~octoprint.plugin.TemplatePlugin` mixin. - - * - pluginNames - - A list of names of :class:`~octoprint.plugin.TemplatePlugin` - implementation that were enabled when creating the ``templates`` - value. - * - locales - - The locales for which there are translations available. - * - supportedExtensions - - The file extensions supported for uploads. - - On top of that all additional template variables as provided by :meth:`~octoprint.plugin.TemplatePlugin.get_template_vars` - will be contained in the dictionary as well. - - Arguments: - now (datetime.datetime): The datetime instance representing "now" - for this request, in case your plugin implementation needs this - information. - request (flask.Request): A Flask `Request `_ object. - render_kwargs (dict): The (cached) render keyword arguments that - would usually be provided to the core UI render function. - - Returns: - flask.Response: Should return a Flask `Response `_ - object that can be served to the requesting client directly. May be - created with ``flask.make_response`` combined with something like - ``flask.render_template``. - """ - - return None - - # noinspection PyMethodMayBeStatic - def get_ui_additional_key_data_for_cache(self): - """ - Allows to return additional data to use in the cache key. - - Returns: - list, tuple: A list or tuple of strings to use in the cache key. Will be joined by OctoPrint - using ``:`` as separator and appended to the existing ``ui:::`` - cache key. Ignored if ``None`` is returned. - - .. versionadded:: 1.3.0 - """ - return None - - # noinspection PyMethodMayBeStatic - def get_ui_additional_tracked_files(self): - """ - Allows to return additional files to track for validating existing caches. By default OctoPrint - will track all declared templates, assets and translation files in the system. Additional - files can be added by a plugin through this callback. - - Returns: - list: A list of paths to additional files whose modification to track for (in)validating - the cache. Ignored if ``None`` is returned. - - ..versionadded:: 1.3.0 - """ - return None - - # noinspection PyMethodMayBeStatic - def get_ui_custom_tracked_files(self): - """ - Allows to define a complete separate set of files to track for (in)validating the cache. If this - method returns something, the templates, assets and translation files won't be tracked, only the - files specified in the returned list. - - Returns: - list: A list of paths representing the only files whose modification to track for (in)validating - the cache. Ignored if ``None`` is returned. - - ..versionadded:: 1.3.0 - """ - return None - - # noinspection PyMethodMayBeStatic - def get_ui_custom_etag(self): - """ - Allows to use a custom way to calculate the ETag, instead of the default method (hashing - OctoPrint's version, tracked file paths and ``LastModified`` value). - - Returns: - str: An alternatively calculated ETag value. Ignored if ``None`` is returned (default). - - ..versionadded:: 1.3.0 - """ - return None - - # noinspection PyMethodMayBeStatic - def get_ui_additional_etag(self, default_additional): - """ - Allows to provide a list of additional fields to use for ETag generation. - - By default the same list will be returned that is also used in the stock UI (and injected - via the parameter ``default_additional``). - - Arguments: - default_additional (list): The list of default fields added to the ETag of the default UI - - Returns: - (list): A list of additional fields for the ETag generation, or None - - ..versionadded:: 1.3.0 - """ - return default_additional - - # noinspection PyMethodMayBeStatic - def get_ui_custom_lastmodified(self): - """ - Allows to calculate the LastModified differently than using the most recent modification - date of all tracked files. - - Returns: - int: An alternatively calculated LastModified value. Ignored if ``None`` is returned (default). - - ..versionadded:: 1.3.0 - """ - return None - - # noinspection PyMethodMayBeStatic - def get_ui_preemptive_caching_enabled(self): - """ - Allows to control whether the view provided by the plugin should be preemptively - cached on server startup (default) or not. - - Have this return False if you do not want your plugin's UI to ever be preemptively cached. - - Returns: - bool: Whether to enable preemptive caching (True, default) or not (False) - """ - return True - - # noinspection PyMethodMayBeStatic - def get_ui_data_for_preemptive_caching(self): - """ - Allows defining additional data to be persisted in the preemptive cache configuration, on - top of the request path, base URL and used locale. - - Returns: - dict: Additional data to persist in the preemptive cache configuration. - - ..versionadded:: 1.3.0 - """ - return None - - # noinspection PyMethodMayBeStatic - def get_ui_additional_request_data_for_preemptive_caching(self): - """ - Allows defining additional request data to persist in the preemptive cache configuration and - to use for the fake request used for populating the preemptive cache. - - Keys and values are used as keyword arguments for creating the - `Werkzeug EnvironBuilder `_ - used for creating the fake request. - - Returns: - dict: Additional request data to persist in the preemptive cache configuration and to - use for request environment construction. - - ..versionadded:: 1.3.0 - """ - return None - - # noinspection PyMethodMayBeStatic - def get_ui_preemptive_caching_additional_unless(self): - """ - Allows defining additional reasons for temporarily not adding a preemptive cache record for - your plugin's UI. - - OctoPrint will call this method when processing a UI request, to determine whether to record the - access or not. If you return ``True`` here, no record will be created. - - Returns: - bool: Whether to suppress a record (True) or not (False, default) + """ + The ``UiPlugin`` mixin allows plugins to completely replace the UI served + by OctoPrint when requesting the main page hosted at `/`. + + OctoPrint will query whether your mixin implementation will handle a + provided request by calling :meth:`~octoprint.plugin.UiPlugin.will_handle_ui` with the Flask + `Request `_ object as + parameter. If you plugin returns `True` here, OctoPrint will next call + :meth:`~octoprint.plugin.UiPlugin.on_ui_render` with a few parameters like + - again - the Flask Request object and the render keyword arguments as + used by the default OctoPrint web interface. For more information see below. + + There are two methods used in order to allow for caching of the actual + response sent to the client. Whatever a plugin implementation returns + from the call to its :meth:`~octoprint.plugin.UiPlugin.on_ui_render` method + will be cached server side. The cache will be emptied in case of explicit + no-cache headers sent by the client, or if the ``_refresh`` query parameter + on the request exists and is set to ``true``. To prevent caching of the + response altogether, a plugin may set no-cache headers on the returned + response as well. + + ``UiPlugin`` is a :class:`~octoprint.plugin.core.SortablePlugin` with a sorting context + for :meth:`~octoprint.plugin.UiPlugin.will_handle_ui`. The first plugin to return ``True`` + for :meth:`~octoprint.plugin.UiPlugin.will_handle_ui` will be the one whose ui will be used, + no further calls to :meth:`~octoprint.plugin.UiPlugin.on_ui_render` will be performed. + + If implementations want to serve custom templates in the :meth:`~octoprint.plugin.UiPlugin.on_ui_render` + method it is recommended to also implement the :class:`~octoprint.plugin.TemplatePlugin` + mixin. + + **Example** + + What follows is a very simple example that renders a different (non functional and + only exemplary) UI if the requesting client has a UserAgent string hinting + at it being a mobile device: + + .. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/dummy_mobile_ui/__init__.py + :linenos: + :tab-width: 4 + :caption: `dummy_mobile_ui/__init__.py `_ + + .. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/dummy_mobile_ui/templates/dummy_mobile_ui_index.jinja2 + :linenos: + :tab-width: 4 + :caption: `dummy_mobile_ui/templates/dummy_mobile_ui_index.jinja2 `_ + + Try installing the above plugin ``dummy_mobile_ui`` (also available in the + `plugin examples repository `_) + into your OctoPrint instance. If you access it from a regular desktop browser, + you should still see the default UI. However if you access it from a mobile + device (make sure to not have that request the desktop version of pages!) + you should see the very simple dummy page defined above. + + **Preemptive and Runtime Caching** + + OctoPrint will also cache your custom UI for you in its server side UI cache, making sure + it only gets re-rendered if the request demands that (by having no-cache headers set) or if + the cache gets invalidated otherwise. + + In order to be able to do that, the ``UiPlugin`` offers overriding some cache specific + methods used for figuring out the source files whose modification time to use for cache invalidation + as well as override possibilities for ETag and LastModified calculation. Additionally there are + methods to allow persisting call parameters to allow for preemptively caching your UI during + server startup (basically eager caching instead of lazily waiting for the first request). + + See below for details on this. + + .. versionadded:: 1.3.0 + """ + + # noinspection PyMethodMayBeStatic,PyUnusedLocal + def will_handle_ui(self, request): + """ + Called by OctoPrint to determine if the mixin implementation will be + able to handle the ``request`` provided as a parameter. + + Return ``True`` here to signal that your implementation will handle + the request and that the result of its :meth:`~octoprint.plugin.UiPlugin.on_ui_render` method + is what should be served to the user. + + The execution order of calls to this method can be influenced via the sorting context + ``UiPlugin.will_handle_ui``. + + Arguments: + request (flask.Request): A Flask `Request `_ + object. + + Returns: + bool: ``True`` if the the implementation will serve the request, + ``False`` otherwise. + """ + return False + + # noinspection PyMethodMayBeStatic,PyUnusedLocal + def on_ui_render(self, now, request, render_kwargs): + """ + Called by OctoPrint to retrieve the response to send to the client + for the ``request`` to ``/``. Only called if :meth:`~octoprint.plugin.UiPlugin.will_handle_ui` + returned ``True``. + + ``render_kwargs`` will be a dictionary (whose contents are cached) which + will contain the following key and value pairs (note that not all + key value pairs contained in the dictionary are listed here, only + those you should depend on as a plugin developer at the current time): + + .. list-table:: + :widths: 5 95 + + * - debug + - ``True`` if debug mode is enabled, ``False`` otherwise. + * - firstRun + - ``True`` if the server is being run for the first time (not + configured yet), ``False`` otherwise. + * - version + - OctoPrint's version information. This is a ``dict`` with the + following keys: + + .. list-table:: + :widths: 5 95 + + * - number + - The version number (e.g. ``x.y.z``) + * - branch + - The GIT branch from which the OctoPrint instance was built + (e.g. ``master``) + * - display + - The full human readable version string, including the + branch information (e.g. ``x.y.z (master branch)`` + + * - uiApiKey + - The UI API key to use for unauthorized API requests. This is + freshly generated on every server restart. + * - templates + - Template data to render in the UI. Will be a ``dict`` containing entries + for all known template types. + + The sub structure for each key will be as follows: + + .. list-table:: + :widths: 5 95 + + * - order + - A list of template names in the order they should appear + in the final rendered page + * - entries + - The template entry definitions to render. Depending on the + template type those are either 2-tuples of a name and a ``dict`` + or directly ``dicts`` with information regarding the + template to render. + + For the possible contents of the data ``dicts`` see the + :class:`~octoprint.plugin.TemplatePlugin` mixin. + + * - pluginNames + - A list of names of :class:`~octoprint.plugin.TemplatePlugin` + implementation that were enabled when creating the ``templates`` + value. + * - locales + - The locales for which there are translations available. + * - supportedExtensions + - The file extensions supported for uploads. + + On top of that all additional template variables as provided by :meth:`~octoprint.plugin.TemplatePlugin.get_template_vars` + will be contained in the dictionary as well. + + Arguments: + now (datetime.datetime): The datetime instance representing "now" + for this request, in case your plugin implementation needs this + information. + request (flask.Request): A Flask `Request `_ object. + render_kwargs (dict): The (cached) render keyword arguments that + would usually be provided to the core UI render function. + + Returns: + flask.Response: Should return a Flask `Response `_ + object that can be served to the requesting client directly. May be + created with ``flask.make_response`` combined with something like + ``flask.render_template``. + """ + + return None + + # noinspection PyMethodMayBeStatic + def get_ui_additional_key_data_for_cache(self): + """ + Allows to return additional data to use in the cache key. + + Returns: + list, tuple: A list or tuple of strings to use in the cache key. Will be joined by OctoPrint + using ``:`` as separator and appended to the existing ``ui:::`` + cache key. Ignored if ``None`` is returned. + + .. versionadded:: 1.3.0 + """ + return None + + # noinspection PyMethodMayBeStatic + def get_ui_additional_tracked_files(self): + """ + Allows to return additional files to track for validating existing caches. By default OctoPrint + will track all declared templates, assets and translation files in the system. Additional + files can be added by a plugin through this callback. + + Returns: + list: A list of paths to additional files whose modification to track for (in)validating + the cache. Ignored if ``None`` is returned. + + ..versionadded:: 1.3.0 + """ + return None + + # noinspection PyMethodMayBeStatic + def get_ui_custom_tracked_files(self): + """ + Allows to define a complete separate set of files to track for (in)validating the cache. If this + method returns something, the templates, assets and translation files won't be tracked, only the + files specified in the returned list. + + Returns: + list: A list of paths representing the only files whose modification to track for (in)validating + the cache. Ignored if ``None`` is returned. + + ..versionadded:: 1.3.0 + """ + return None + + # noinspection PyMethodMayBeStatic + def get_ui_custom_etag(self): + """ + Allows to use a custom way to calculate the ETag, instead of the default method (hashing + OctoPrint's version, tracked file paths and ``LastModified`` value). + + Returns: + str: An alternatively calculated ETag value. Ignored if ``None`` is returned (default). + + ..versionadded:: 1.3.0 + """ + return None + + # noinspection PyMethodMayBeStatic + def get_ui_additional_etag(self, default_additional): + """ + Allows to provide a list of additional fields to use for ETag generation. + + By default the same list will be returned that is also used in the stock UI (and injected + via the parameter ``default_additional``). + + Arguments: + default_additional (list): The list of default fields added to the ETag of the default UI + + Returns: + (list): A list of additional fields for the ETag generation, or None + + ..versionadded:: 1.3.0 + """ + return default_additional + + # noinspection PyMethodMayBeStatic + def get_ui_custom_lastmodified(self): + """ + Allows to calculate the LastModified differently than using the most recent modification + date of all tracked files. + + Returns: + int: An alternatively calculated LastModified value. Ignored if ``None`` is returned (default). + + ..versionadded:: 1.3.0 + """ + return None + + # noinspection PyMethodMayBeStatic + def get_ui_preemptive_caching_enabled(self): + """ + Allows to control whether the view provided by the plugin should be preemptively + cached on server startup (default) or not. + + Have this return False if you do not want your plugin's UI to ever be preemptively cached. + + Returns: + bool: Whether to enable preemptive caching (True, default) or not (False) + """ + return True + + # noinspection PyMethodMayBeStatic + def get_ui_data_for_preemptive_caching(self): + """ + Allows defining additional data to be persisted in the preemptive cache configuration, on + top of the request path, base URL and used locale. + + Returns: + dict: Additional data to persist in the preemptive cache configuration. + + ..versionadded:: 1.3.0 + """ + return None + + # noinspection PyMethodMayBeStatic + def get_ui_additional_request_data_for_preemptive_caching(self): + """ + Allows defining additional request data to persist in the preemptive cache configuration and + to use for the fake request used for populating the preemptive cache. - ..versionadded:: 1.3.0 - """ - return False + Keys and values are used as keyword arguments for creating the + `Werkzeug EnvironBuilder `_ + used for creating the fake request. - # noinspection PyMethodMayBeStatic - def get_ui_custom_template_filter(self, default_template_filter): - """ - Allows to specify a custom template filter to use for filtering the template contained in the - ``render_kwargs`` provided to the templating sub system. - - Only relevant for UiPlugins that actually utilize the stock templates of OctoPrint. + Returns: + dict: Additional request data to persist in the preemptive cache configuration and to + use for request environment construction. - By default simply returns the provided ``default_template_filter``. - - Arguments: - default_template_filter (callable): The default template filter used by the default UI + ..versionadded:: 1.3.0 + """ + return None + + # noinspection PyMethodMayBeStatic + def get_ui_preemptive_caching_additional_unless(self): + """ + Allows defining additional reasons for temporarily not adding a preemptive cache record for + your plugin's UI. + + OctoPrint will call this method when processing a UI request, to determine whether to record the + access or not. If you return ``True`` here, no record will be created. + + Returns: + bool: Whether to suppress a record (True) or not (False, default) + + ..versionadded:: 1.3.0 + """ + return False + + # noinspection PyMethodMayBeStatic + def get_ui_custom_template_filter(self, default_template_filter): + """ + Allows to specify a custom template filter to use for filtering the template contained in the + ``render_kwargs`` provided to the templating sub system. + + Only relevant for UiPlugins that actually utilize the stock templates of OctoPrint. + + By default simply returns the provided ``default_template_filter``. + + Arguments: + default_template_filter (callable): The default template filter used by the default UI + + Returns: + (callable) A filter function accepting the ``template_type`` and ``template_key`` of a template + and returning ``True`` to keep it and ``False`` to filter it out. If ``None`` is returned, no + filtering will take place. + + ..versionadded:: 1.3.0 + """ + return default_template_filter - Returns: - (callable) A filter function accepting the ``template_type`` and ``template_key`` of a template - and returning ``True`` to keep it and ``False`` to filter it out. If ``None`` is returned, no - filtering will take place. - - ..versionadded:: 1.3.0 - """ - return default_template_filter class WizardPlugin(OctoPrintPlugin, ReloadNeedingPlugin): - """ - The ``WizardPlugin`` mixin allows plugins to report to OctoPrint whether - the ``wizard`` templates they define via the :class:`~octoprint.plugin.TemplatePlugin` - should be displayed to the user, what details to provide to their respective - wizard frontend components and what to do when the wizard is finished - by the user. + """ + The ``WizardPlugin`` mixin allows plugins to report to OctoPrint whether + the ``wizard`` templates they define via the :class:`~octoprint.plugin.TemplatePlugin` + should be displayed to the user, what details to provide to their respective + wizard frontend components and what to do when the wizard is finished + by the user. - OctoPrint will only display such wizard dialogs to the user which belong - to plugins that + OctoPrint will only display such wizard dialogs to the user which belong + to plugins that - * report ``True`` in their :func:`is_wizard_required` method and - * have not yet been shown to the user in the version currently being reported - by the :meth:`~octoprint.plugin.WizardPlugin.get_wizard_version` method + * report ``True`` in their :func:`is_wizard_required` method and + * have not yet been shown to the user in the version currently being reported + by the :meth:`~octoprint.plugin.WizardPlugin.get_wizard_version` method - Example: If a plugin with the identifier ``myplugin`` has a specific - setting ``some_key`` it needs to have filled by the user in order to be - able to work at all, it would probably test for that setting's value in - the :meth:`~octoprint.plugin.WizardPlugin.is_wizard_required` method and - return ``True`` if the value is unset: + Example: If a plugin with the identifier ``myplugin`` has a specific + setting ``some_key`` it needs to have filled by the user in order to be + able to work at all, it would probably test for that setting's value in + the :meth:`~octoprint.plugin.WizardPlugin.is_wizard_required` method and + return ``True`` if the value is unset: - .. code-block:: python + .. code-block:: python - class MyPlugin(octoprint.plugin.SettingsPlugin, - octoprint.plugin.TemplatePlugin, - octoprint.plugin.WizardPlugin): + class MyPlugin(octoprint.plugin.SettingsPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.WizardPlugin): - def get_default_settings(self): - return dict(some_key=None) + def get_default_settings(self): + return dict(some_key=None) - def is_wizard_required(self): - return self._settings.get(["some_key"]) is None + def is_wizard_required(self): + return self._settings.get(["some_key"]) is None - OctoPrint will then display the wizard dialog provided by the plugin through - the :class:`TemplatePlugin` mixin. Once the user finishes the wizard on the - frontend, OctoPrint will store that it already showed the wizard of ``myplugin`` - in the version reported by :meth:`~octoprint.plugin.WizardPlugin.get_wizard_version` - - here ``None`` since that is the default value returned by that function - and the plugin did not override it. + OctoPrint will then display the wizard dialog provided by the plugin through + the :class:`TemplatePlugin` mixin. Once the user finishes the wizard on the + frontend, OctoPrint will store that it already showed the wizard of ``myplugin`` + in the version reported by :meth:`~octoprint.plugin.WizardPlugin.get_wizard_version` + - here ``None`` since that is the default value returned by that function + and the plugin did not override it. - If the plugin in a later version needs another setting from the user in order - to function, it will also need to change the reported version in order to - have OctoPrint reshow the dialog. E.g. + If the plugin in a later version needs another setting from the user in order + to function, it will also need to change the reported version in order to + have OctoPrint reshow the dialog. E.g. - .. code-block:: python + .. code-block:: python - class MyPlugin(octoprint.plugin.SettingsPlugin, - octoprint.plugin.TemplatePlugin, - octoprint.plugin.WizardPlugin): + class MyPlugin(octoprint.plugin.SettingsPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.WizardPlugin): - def get_default_settings(self): - return dict(some_key=None, some_other_key=None) + def get_default_settings(self): + return dict(some_key=None, some_other_key=None) - def is_wizard_required(self): - some_key_unset = self._settings.get(["some_key"]) is None - some_other_key_unset = self._settings.get(["some_other_key"]) is None + def is_wizard_required(self): + some_key_unset = self._settings.get(["some_key"]) is None + some_other_key_unset = self._settings.get(["some_other_key"]) is None - return some_key_unset or some_other_key_unset + return some_key_unset or some_other_key_unset - def get_wizard_version(self): - return 1 + def get_wizard_version(self): + return 1 - ``WizardPlugin`` is a :class:`~octoprint.plugin.core.ReloadNeedingPlugin`. - """ + ``WizardPlugin`` is a :class:`~octoprint.plugin.core.ReloadNeedingPlugin`. + """ - # noinspection PyMethodMayBeStatic - def is_wizard_required(self): - """ - Allows the plugin to report whether it needs to display a wizard to the - user or not. + # noinspection PyMethodMayBeStatic + def is_wizard_required(self): + """ + Allows the plugin to report whether it needs to display a wizard to the + user or not. - Defaults to ``False``. + Defaults to ``False``. - OctoPrint will only include those wizards from plugins which are reporting - their wizards as being required through this method returning ``True``. - Still, if OctoPrint already displayed that wizard in the same version - to the user once it won't be displayed again regardless whether this - method returns ``True`` or not. - """ - return False + OctoPrint will only include those wizards from plugins which are reporting + their wizards as being required through this method returning ``True``. + Still, if OctoPrint already displayed that wizard in the same version + to the user once it won't be displayed again regardless whether this + method returns ``True`` or not. + """ + return False - # noinspection PyMethodMayBeStatic - def get_wizard_version(self): - """ - The version of this plugin's wizard. OctoPrint will only display a wizard - of the same plugin and wizard version once to the user. After they - finish the wizard, OctoPrint will remember that it already showed this - wizard in this particular version and not reshow it. + # noinspection PyMethodMayBeStatic + def get_wizard_version(self): + """ + The version of this plugin's wizard. OctoPrint will only display a wizard + of the same plugin and wizard version once to the user. After they + finish the wizard, OctoPrint will remember that it already showed this + wizard in this particular version and not reshow it. - If a plugin needs to show its wizard to the user again (e.g. because - of changes in the required settings), increasing this value is the - way to notify OctoPrint of these changes. + If a plugin needs to show its wizard to the user again (e.g. because + of changes in the required settings), increasing this value is the + way to notify OctoPrint of these changes. - Returns: - int or None: an int signifying the current wizard version, should be incremented by plugins whenever there - are changes to the plugin that might necessitate reshowing the wizard if it is required. ``None`` - will also be accepted and lead to the wizard always be ignored unless it has never been finished - so far - """ - return None + Returns: + int or None: an int signifying the current wizard version, should be incremented by plugins whenever there + are changes to the plugin that might necessitate reshowing the wizard if it is required. ``None`` + will also be accepted and lead to the wizard always be ignored unless it has never been finished + so far + """ + return None - # noinspection PyMethodMayBeStatic - def get_wizard_details(self): - """ - Called by OctoPrint when the wizard wrapper dialog is shown. Allows the plugin to return data - that will then be made available to the view models via the view model callback ``onWizardDetails``. + # noinspection PyMethodMayBeStatic + def get_wizard_details(self): + """ + Called by OctoPrint when the wizard wrapper dialog is shown. Allows the plugin to return data + that will then be made available to the view models via the view model callback ``onWizardDetails``. - Use this if your plugin's view model that handles your wizard dialog needs additional - data to perform its task. + Use this if your plugin's view model that handles your wizard dialog needs additional + data to perform its task. - Returns: - dict: a dictionary containing additional data to provide to the frontend. Whatever the plugin - returns here will be made available on the wizard API under the plugin's identifier - """ - return {} + Returns: + dict: a dictionary containing additional data to provide to the frontend. Whatever the plugin + returns here will be made available on the wizard API under the plugin's identifier + """ + return {} - # noinspection PyMethodMayBeStatic,PyUnusedLocal - def on_wizard_finish(self, handled): - """ - Called by OctoPrint whenever the user finishes a wizard session. + # noinspection PyMethodMayBeStatic,PyUnusedLocal + def on_wizard_finish(self, handled): + """ + Called by OctoPrint whenever the user finishes a wizard session. - The ``handled`` parameter will indicate whether that plugin's wizard was - included in the wizard dialog presented to the user (so the plugin providing - it was reporting that the wizard was required and the wizard plus version was not - ignored/had already been seen). + The ``handled`` parameter will indicate whether that plugin's wizard was + included in the wizard dialog presented to the user (so the plugin providing + it was reporting that the wizard was required and the wizard plus version was not + ignored/had already been seen). - Use this to do any clean up tasks necessary after wizard completion. + Use this to do any clean up tasks necessary after wizard completion. - Arguments: - handled (bool): True if the plugin's wizard was previously reported as - required, not ignored and thus presented to the user, - False otherwise - """ - pass + Arguments: + handled (bool): True if the plugin's wizard was previously reported as + required, not ignored and thus presented to the user, + False otherwise + """ + pass - # noinspection PyProtectedMember - @classmethod - def is_wizard_ignored(cls, seen_wizards, implementation): - """ - Determines whether the provided implementation is ignored based on the - provided information about already seen wizards and their versions or not. + # noinspection PyProtectedMember + @classmethod + def is_wizard_ignored(cls, seen_wizards, implementation): + """ + Determines whether the provided implementation is ignored based on the + provided information about already seen wizards and their versions or not. - A wizard is ignored if + A wizard is ignored if - * the current and seen versions are identical - * the current version is None and the seen version is not - * the current version is less or equal than the seen one + * the current and seen versions are identical + * the current version is None and the seen version is not + * the current version is less or equal than the seen one - .. code-block:: none + .. code-block:: none - | current | - | N | 1 | 2 | N = None - ----+---+---+---+ X = ignored - s N | X | | | - e --+---+---+---+ - e 1 | X | X | | - n --+---+---+---+ - 2 | X | X | X | - ----+---+---+---+ + | current | + | N | 1 | 2 | N = None + ----+---+---+---+ X = ignored + s N | X | | | + e --+---+---+---+ + e 1 | X | X | | + n --+---+---+---+ + 2 | X | X | X | + ----+---+---+---+ - Arguments: - seen_wizards (dict): A dictionary with information about already seen - wizards and their versions. Mappings from the identifiers of - the plugin providing the wizard to the reported wizard - version (int or None) that was already seen by the user. - implementation (object): The plugin implementation to check. + Arguments: + seen_wizards (dict): A dictionary with information about already seen + wizards and their versions. Mappings from the identifiers of + the plugin providing the wizard to the reported wizard + version (int or None) that was already seen by the user. + implementation (object): The plugin implementation to check. - Returns: - bool: False if the provided ``implementation`` is either not a :class:`WizardPlugin` - or has not yet been seen (in this version), True otherwise - """ + Returns: + bool: False if the provided ``implementation`` is either not a :class:`WizardPlugin` + or has not yet been seen (in this version), True otherwise + """ - if not isinstance(implementation, cls): - return False + if not isinstance(implementation, cls): + return False - name = implementation._identifier - if not name in seen_wizards: - return False + name = implementation._identifier + if not name in seen_wizards: + return False - seen = seen_wizards[name] - wizard_version = implementation.get_wizard_version() + seen = seen_wizards[name] + wizard_version = implementation.get_wizard_version() - current = None - if wizard_version is not None: - try: - current = int(wizard_version) - except ValueError as e: - import logging - logging.getLogger(__name__).log("WizardPlugin {} returned invalid value {} for wizard version: {}".format(name, wizard_version, str(e))) + current = None + if wizard_version is not None: + try: + current = int(wizard_version) + except ValueError as e: + import logging - return (current == seen) \ - or (current is None and seen is not None) \ - or (current <= seen) + logging.getLogger(__name__).log( + "WizardPlugin {} returned invalid value {} for wizard version: {}".format( + name, wizard_version, str(e) + ) + ) + + return ( + (current == seen) + or (current is None and seen is not None) + or (current <= seen) + ) class SimpleApiPlugin(OctoPrintPlugin): - """ - Utilizing the ``SimpleApiPlugin`` mixin plugins may implement a simple API based around one GET resource and one - resource accepting JSON commands POSTed to it. This is the easy alternative for plugin's which don't need the - full power of a `Flask Blueprint `_ that the :class:`BlueprintPlugin` - mixin offers. + """ + Utilizing the ``SimpleApiPlugin`` mixin plugins may implement a simple API based around one GET resource and one + resource accepting JSON commands POSTed to it. This is the easy alternative for plugin's which don't need the + full power of a `Flask Blueprint `_ that the :class:`BlueprintPlugin` + mixin offers. - Use this mixin if all you need to do is return some kind of dynamic data to your plugin from the backend - and/or want to react to simple commands which boil down to a type of command and a few flat parameters - supplied with it. + Use this mixin if all you need to do is return some kind of dynamic data to your plugin from the backend + and/or want to react to simple commands which boil down to a type of command and a few flat parameters + supplied with it. - The simple API constructed by OctoPrint for you will be made available under ``/api/plugin//``. - OctoPrint will do some preliminary request validation for your defined commands, making sure the request body is in - the correct format (content type must be JSON) and contains all obligatory parameters for your command. + The simple API constructed by OctoPrint for you will be made available under ``/api/plugin//``. + OctoPrint will do some preliminary request validation for your defined commands, making sure the request body is in + the correct format (content type must be JSON) and contains all obligatory parameters for your command. - Let's take a look at a small example for such a simple API and how you would go about calling it. + Let's take a look at a small example for such a simple API and how you would go about calling it. - Take this example of a plugin registered under plugin identifier ``mysimpleapiplugin``: + Take this example of a plugin registered under plugin identifier ``mysimpleapiplugin``: - .. code-block:: python - :linenos: + .. code-block:: python + :linenos: - import octoprint.plugin + import octoprint.plugin - import flask + import flask - class MySimpleApiPlugin(octoprint.plugin.SimpleApiPlugin): - def get_api_commands(self): - return dict( - command1=[], - command2=["some_parameter"] - ) + class MySimpleApiPlugin(octoprint.plugin.SimpleApiPlugin): + def get_api_commands(self): + return dict( + command1=[], + command2=["some_parameter"] + ) - def on_api_command(self, command, data): - import flask - if command == "command1": - parameter = "unset" - if "parameter" in data: - parameter = "set" - self._logger.info("command1 called, parameter is {parameter}".format(**locals())) - elif command == "command2": - self._logger.info("command2 called, some_parameter is {some_parameter}".format(**data)) + def on_api_command(self, command, data): + import flask + if command == "command1": + parameter = "unset" + if "parameter" in data: + parameter = "set" + self._logger.info("command1 called, parameter is {parameter}".format(**locals())) + elif command == "command2": + self._logger.info("command2 called, some_parameter is {some_parameter}".format(**data)) - def on_api_get(self, request): - return flask.jsonify(foo="bar") + def on_api_get(self, request): + return flask.jsonify(foo="bar") - __plugin_implementation__ = MySimpleApiPlugin() + __plugin_implementation__ = MySimpleApiPlugin() - Our plugin defines two commands, ``command1`` with no mandatory parameters and ``command2`` with one - mandatory parameter ``some_parameter``. + Our plugin defines two commands, ``command1`` with no mandatory parameters and ``command2`` with one + mandatory parameter ``some_parameter``. - ``command1`` can also accept an optional parameter ``parameter``, and will log whether - that parameter was set or unset. ``command2`` will log the content of the mandatory ``some_parameter`` parameter. + ``command1`` can also accept an optional parameter ``parameter``, and will log whether + that parameter was set or unset. ``command2`` will log the content of the mandatory ``some_parameter`` parameter. - A valid POST request for ``command2`` sent to ``/api/plugin/mysimpleapiplugin`` would look like this: + A valid POST request for ``command2`` sent to ``/api/plugin/mysimpleapiplugin`` would look like this: - .. sourcecode:: http + .. sourcecode:: http - POST /api/plugin/mysimpleapiplugin HTTP/1.1 - Host: example.com - Content-Type: application/json - X-Api-Key: abcdef... + POST /api/plugin/mysimpleapiplugin HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... - { - "command": "command2", - "some_parameter": "some_value", - "some_optional_parameter": 2342 - } + { + "command": "command2", + "some_parameter": "some_value", + "some_optional_parameter": 2342 + } - which would produce a response like this: + which would produce a response like this: - .. sourcecode:: http + .. sourcecode:: http - HTTP/1.1 204 No Content + HTTP/1.1 204 No Content - and print something like this line to ``octoprint.log``:: + and print something like this line to ``octoprint.log``:: - 2015-02-12 17:40:21,140 - octoprint.plugins.mysimpleapiplugin - INFO - command2 called, some_parameter is some_value + 2015-02-12 17:40:21,140 - octoprint.plugins.mysimpleapiplugin - INFO - command2 called, some_parameter is some_value - A GET request on our plugin's simple API resource will only return a JSON document like this: + A GET request on our plugin's simple API resource will only return a JSON document like this: - .. sourcecode:: http + .. sourcecode:: http - HTTP/1.1 200 Ok - Content-Type: application/json + HTTP/1.1 200 Ok + Content-Type: application/json - { - "foo": "bar" - } - """ + { + "foo": "bar" + } + """ - # noinspection PyMethodMayBeStatic - def get_api_commands(self): - """ - Return a dictionary here with the keys representing the accepted commands and the values being lists of - mandatory parameter names. - """ - return None + # noinspection PyMethodMayBeStatic + def get_api_commands(self): + """ + Return a dictionary here with the keys representing the accepted commands and the values being lists of + mandatory parameter names. + """ + return None - # noinspection PyMethodMayBeStatic - def is_api_adminonly(self): - """ - Return True if the API is only available to users having the admin role. - """ - return False + # noinspection PyMethodMayBeStatic + def is_api_adminonly(self): + """ + Return True if the API is only available to users having the admin role. + """ + return False - # noinspection PyMethodMayBeStatic - def on_api_command(self, command, data): - """ - Called by OctoPrint upon a POST request to ``/api/plugin/``. ``command`` will contain one of - the commands as specified via :func:`get_api_commands`, ``data`` will contain the full request body parsed - from JSON into a Python dictionary. Note that this will also contain the ``command`` attribute itself. For the - example given above, for the ``command2`` request the ``data`` received by the plugin would be equal to - ``dict(command="command2", some_parameter="some_value")``. + # noinspection PyMethodMayBeStatic + def on_api_command(self, command, data): + """ + Called by OctoPrint upon a POST request to ``/api/plugin/``. ``command`` will contain one of + the commands as specified via :func:`get_api_commands`, ``data`` will contain the full request body parsed + from JSON into a Python dictionary. Note that this will also contain the ``command`` attribute itself. For the + example given above, for the ``command2`` request the ``data`` received by the plugin would be equal to + ``dict(command="command2", some_parameter="some_value")``. - If your plugin returns nothing here, OctoPrint will return an empty response with return code ``204 No content`` - for you. You may also return regular responses as you would return from any Flask view here though, e.g. - ``return flask.jsonify(result="some json result")`` or ``return flask.make_response("Not found", 404)``. + If your plugin returns nothing here, OctoPrint will return an empty response with return code ``204 No content`` + for you. You may also return regular responses as you would return from any Flask view here though, e.g. + ``return flask.jsonify(result="some json result")`` or ``return flask.make_response("Not found", 404)``. - :param string command: the command with which the resource was called - :param dict data: the full request body of the POST request parsed from JSON into a Python dictionary - :return: ``None`` in which case OctoPrint will generate a ``204 No content`` response with empty body, or optionally - a proper Flask response. - """ - return None + :param string command: the command with which the resource was called + :param dict data: the full request body of the POST request parsed from JSON into a Python dictionary + :return: ``None`` in which case OctoPrint will generate a ``204 No content`` response with empty body, or optionally + a proper Flask response. + """ + return None - # noinspection PyMethodMayBeStatic - def on_api_get(self, request): - """ - Called by OctoPrint upon a GET request to ``/api/plugin/``. ``request`` will contain the - received `Flask request object `_ which you may evaluate - for additional arguments supplied with the request. + # noinspection PyMethodMayBeStatic + def on_api_get(self, request): + """ + Called by OctoPrint upon a GET request to ``/api/plugin/``. ``request`` will contain the + received `Flask request object `_ which you may evaluate + for additional arguments supplied with the request. - If your plugin returns nothing here, OctoPrint will return an empty response with return code ``204 No content`` - for you. You may also return regular responses as you would return from any Flask view here though, e.g. - ``return flask.jsonify(result="some json result")`` or ``return flask.make_response("Not found", 404)``. + If your plugin returns nothing here, OctoPrint will return an empty response with return code ``204 No content`` + for you. You may also return regular responses as you would return from any Flask view here though, e.g. + ``return flask.jsonify(result="some json result")`` or ``return flask.make_response("Not found", 404)``. - :param request: the Flask request object - :return: ``None`` in which case OctoPrint will generate a ``204 No content`` response with empty body, or optionally - a proper Flask response. - """ - return None + :param request: the Flask request object + :return: ``None`` in which case OctoPrint will generate a ``204 No content`` response with empty body, or optionally + a proper Flask response. + """ + return None class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin): - """ - The ``BlueprintPlugin`` mixin allows plugins to define their own full fledged endpoints for whatever purpose, - be it a more sophisticated API than what is possible via the :class:`SimpleApiPlugin` or a custom web frontend. + """ + The ``BlueprintPlugin`` mixin allows plugins to define their own full fledged endpoints for whatever purpose, + be it a more sophisticated API than what is possible via the :class:`SimpleApiPlugin` or a custom web frontend. - The mechanism at work here is `Flask's `_ own `Blueprint mechanism `_. + The mechanism at work here is `Flask's `_ own `Blueprint mechanism `_. - The mixin automatically creates a blueprint for you that will be registered under ``/plugin//``. - All you need to do is decorate all of your view functions with the :func:`route` decorator, - which behaves exactly the same like Flask's regular ``route`` decorators. Example: + The mixin automatically creates a blueprint for you that will be registered under ``/plugin//``. + All you need to do is decorate all of your view functions with the :func:`route` decorator, + which behaves exactly the same like Flask's regular ``route`` decorators. Example: - .. code-block:: python - :linenos: + .. code-block:: python + :linenos: - import octoprint.plugin - import flask + import octoprint.plugin + import flask - class MyBlueprintPlugin(octoprint.plugin.BlueprintPlugin): - @octoprint.plugin.BlueprintPlugin.route("/echo", methods=["GET"]) - def myEcho(self): - if not "text" in flask.request.values: - return flask.make_response("Expected a text to echo back.", 400) - return flask.request.values["text"] + class MyBlueprintPlugin(octoprint.plugin.BlueprintPlugin): + @octoprint.plugin.BlueprintPlugin.route("/echo", methods=["GET"]) + def myEcho(self): + if not "text" in flask.request.values: + return flask.make_response("Expected a text to echo back.", 400) + return flask.request.values["text"] - __plugin_implementation__ = MyBlueprintPlugin() + __plugin_implementation__ = MyBlueprintPlugin() - Your blueprint will be published by OctoPrint under the base URL ``/plugin//``, so the above - example of a plugin with the identifier "myblueprintplugin" would be reachable under - ``/plugin/myblueprintplugin/echo``. + Your blueprint will be published by OctoPrint under the base URL ``/plugin//``, so the above + example of a plugin with the identifier "myblueprintplugin" would be reachable under + ``/plugin/myblueprintplugin/echo``. - Just like with regular blueprints you'll be able to create URLs via ``url_for``, just use the prefix - ``plugin..``, e.g.: + Just like with regular blueprints you'll be able to create URLs via ``url_for``, just use the prefix + ``plugin..``, e.g.: - .. code-block:: python + .. code-block:: python - flask.url_for("plugin.myblueprintplugin.myEcho") # will return "/plugin/myblueprintplugin/echo" + flask.url_for("plugin.myblueprintplugin.myEcho") # will return "/plugin/myblueprintplugin/echo" - ``BlueprintPlugin`` implements :class:`~octoprint.plugins.core.RestartNeedingPlugin`. - """ + ``BlueprintPlugin`` implements :class:`~octoprint.plugins.core.RestartNeedingPlugin`. + """ - @staticmethod - def route(rule, **options): - """ - A decorator to mark view methods in your BlueprintPlugin subclass. Works just the same as Flask's - own ``route`` decorator available on blueprints. + @staticmethod + def route(rule, **options): + """ + A decorator to mark view methods in your BlueprintPlugin subclass. Works just the same as Flask's + own ``route`` decorator available on blueprints. - See `the documentation for flask.Blueprint.route `_ - and `the documentation for flask.Flask.route `_ for more - information. - """ + See `the documentation for flask.Blueprint.route `_ + and `the documentation for flask.Flask.route `_ for more + information. + """ - from collections import defaultdict - def decorator(f): - # We attach the decorator parameters directly to the function object, because that's the only place - # we can access right now. - # This neat little trick was adapter from the Flask-Classy project: https://pythonhosted.org/Flask-Classy/ - if not hasattr(f, "_blueprint_rules") or f._blueprint_rules is None: - f._blueprint_rules = defaultdict(list) - f._blueprint_rules[f.__name__].append((rule, options)) - return f - return decorator + from collections import defaultdict - @staticmethod - def errorhandler(code_or_exception): - """ - A decorator to mark errorhandlings methods in your BlueprintPlugin subclass. Works just the same as Flask's - own ``errorhandler`` decorator available on blueprints. + def decorator(f): + # We attach the decorator parameters directly to the function object, because that's the only place + # we can access right now. + # This neat little trick was adapter from the Flask-Classy project: https://pythonhosted.org/Flask-Classy/ + if not hasattr(f, "_blueprint_rules") or f._blueprint_rules is None: + f._blueprint_rules = defaultdict(list) + f._blueprint_rules[f.__name__].append((rule, options)) + return f - See `the documentation for flask.Blueprint.errorhandler `_ - and `the documentation for flask.Flask.errorhandler `_ for more - information. + return decorator - ..versionadded:: 1.3.0 - """ - from collections import defaultdict - def decorator(f): - if not hasattr(f, "_blueprint_error_handler") or f._blueprint_error_handler is None: - f._blueprint_error_handler = defaultdict(list) - f._blueprint_error_handler[f.__name__].append(code_or_exception) - return f - return decorator + @staticmethod + def errorhandler(code_or_exception): + """ + A decorator to mark errorhandlings methods in your BlueprintPlugin subclass. Works just the same as Flask's + own ``errorhandler`` decorator available on blueprints. - # noinspection PyProtectedMember - def get_blueprint(self): - """ - Creates and returns the blueprint for your plugin. Override this if you want to define and handle your blueprint yourself. + See `the documentation for flask.Blueprint.errorhandler `_ + and `the documentation for flask.Flask.errorhandler `_ for more + information. - This method will only be called once during server initialization. + ..versionadded:: 1.3.0 + """ + from collections import defaultdict - :return: the blueprint ready to be registered with Flask - """ + def decorator(f): + if ( + not hasattr(f, "_blueprint_error_handler") + or f._blueprint_error_handler is None + ): + f._blueprint_error_handler = defaultdict(list) + f._blueprint_error_handler[f.__name__].append(code_or_exception) + return f - if hasattr(self, "_blueprint"): - # if we already constructed the blueprint and hence have it cached, - # return that instance - we don't want to instance it multiple times - return self._blueprint + return decorator - import flask - kwargs = self.get_blueprint_kwargs() - blueprint = flask.Blueprint("plugin." + self._identifier, self._identifier, **kwargs) + # noinspection PyProtectedMember + def get_blueprint(self): + """ + Creates and returns the blueprint for your plugin. Override this if you want to define and handle your blueprint yourself. - # we now iterate over all members of ourselves and look if we find an attribute - # that has data originating from one of our decorators - we ignore anything - # starting with a _ to only handle public stuff - for member in [member for member in dir(self) if not member.startswith("_")]: - f = getattr(self, member) + This method will only be called once during server initialization. - if hasattr(f, "_blueprint_rules") and member in f._blueprint_rules: - # this attribute was annotated with our @route decorator - for blueprint_rule in f._blueprint_rules[member]: - rule, options = blueprint_rule - blueprint.add_url_rule(rule, options.pop("endpoint", f.__name__), view_func=f, **options) + :return: the blueprint ready to be registered with Flask + """ - if hasattr(f, "_blueprint_error_handler") and member in f._blueprint_error_handler: - # this attribute was annotated with our @error_handler decorator - for code_or_exception in f._blueprint_error_handler[member]: - blueprint.errorhandler(code_or_exception)(f) + if hasattr(self, "_blueprint"): + # if we already constructed the blueprint and hence have it cached, + # return that instance - we don't want to instance it multiple times + return self._blueprint - # cache and return the blueprint object - self._blueprint = blueprint - return blueprint + import flask - def get_blueprint_kwargs(self): - """ - Override this if you want your blueprint constructed with additional options such as ``static_folder``, - ``template_folder``, etc. + kwargs = self.get_blueprint_kwargs() + blueprint = flask.Blueprint( + "plugin." + self._identifier, self._identifier, **kwargs + ) - Defaults to the blueprint's ``static_folder`` and ``template_folder`` to be set to the plugin's basefolder - plus ``/static`` or respectively ``/templates``, or -- if the plugin also implements :class:`AssetPlugin` and/or - :class:`TemplatePlugin` -- the paths provided by ``get_asset_folder`` and ``get_template_folder`` respectively. - """ - import os + # we now iterate over all members of ourselves and look if we find an attribute + # that has data originating from one of our decorators - we ignore anything + # starting with a _ to only handle public stuff + for member in [member for member in dir(self) if not member.startswith("_")]: + f = getattr(self, member) - if isinstance(self, AssetPlugin): - static_folder = self.get_asset_folder() - else: - static_folder = os.path.join(self._basefolder, "static") + if hasattr(f, "_blueprint_rules") and member in f._blueprint_rules: + # this attribute was annotated with our @route decorator + for blueprint_rule in f._blueprint_rules[member]: + rule, options = blueprint_rule + blueprint.add_url_rule( + rule, options.pop("endpoint", f.__name__), view_func=f, **options + ) - if isinstance(self, TemplatePlugin): - template_folder = self.get_template_folder() - else: - template_folder = os.path.join(self._basefolder, "templates") + if ( + hasattr(f, "_blueprint_error_handler") + and member in f._blueprint_error_handler + ): + # this attribute was annotated with our @error_handler decorator + for code_or_exception in f._blueprint_error_handler[member]: + blueprint.errorhandler(code_or_exception)(f) - return {"static_folder": static_folder, - "template_folder": template_folder} + # cache and return the blueprint object + self._blueprint = blueprint + return blueprint - # noinspection PyMethodMayBeStatic - def is_blueprint_protected(self): - """ - Whether a login session by a registered user is needed to access the blueprint's endpoints. Requiring - a session is the default. Note that this only restricts access to the blueprint's dynamic methods, static files - are always accessible. + def get_blueprint_kwargs(self): + """ + Override this if you want your blueprint constructed with additional options such as ``static_folder``, + ``template_folder``, etc. - If you want your blueprint's endpoints to have specific permissions, return ``False`` for this and do your - permissions checks explicitly. - """ + Defaults to the blueprint's ``static_folder`` and ``template_folder`` to be set to the plugin's basefolder + plus ``/static`` or respectively ``/templates``, or -- if the plugin also implements :class:`AssetPlugin` and/or + :class:`TemplatePlugin` -- the paths provided by ``get_asset_folder`` and ``get_template_folder`` respectively. + """ + import os - return True + if isinstance(self, AssetPlugin): + static_folder = self.get_asset_folder() + else: + static_folder = os.path.join(self._basefolder, "static") + + if isinstance(self, TemplatePlugin): + template_folder = self.get_template_folder() + else: + template_folder = os.path.join(self._basefolder, "templates") + + return {"static_folder": static_folder, "template_folder": template_folder} + + # noinspection PyMethodMayBeStatic + def is_blueprint_protected(self): + """ + Whether a login session by a registered user is needed to access the blueprint's endpoints. Requiring + a session is the default. Note that this only restricts access to the blueprint's dynamic methods, static files + are always accessible. + + If you want your blueprint's endpoints to have specific permissions, return ``False`` for this and do your + permissions checks explicitly. + """ + + return True class SettingsPlugin(OctoPrintPlugin): - """ - Including the ``SettingsPlugin`` mixin allows plugins to store and retrieve their own settings within OctoPrint's - configuration. + """ + Including the ``SettingsPlugin`` mixin allows plugins to store and retrieve their own settings within OctoPrint's + configuration. - Plugins including the mixing will get injected an additional property ``self._settings`` which is an instance of - :class:`PluginSettingsManager` already properly initialized for use by the plugin. In order for the manager to - know about the available settings structure and default values upon initialization, implementing plugins will need - to provide a dictionary with the plugin's default settings through overriding the method :func:`get_settings_defaults`. - The defined structure will then be available to access through the settings manager available as ``self._settings``. + Plugins including the mixing will get injected an additional property ``self._settings`` which is an instance of + :class:`PluginSettingsManager` already properly initialized for use by the plugin. In order for the manager to + know about the available settings structure and default values upon initialization, implementing plugins will need + to provide a dictionary with the plugin's default settings through overriding the method :func:`get_settings_defaults`. + The defined structure will then be available to access through the settings manager available as ``self._settings``. - If your plugin needs to react to the change of specific configuration values on the fly, e.g. to adjust the log level - of a logger when the user changes a corresponding flag via the settings dialog, you can override the - :func:`on_settings_save` method and wrap the call to the implementation from the parent class with retrieval of the - old and the new value and react accordingly. + If your plugin needs to react to the change of specific configuration values on the fly, e.g. to adjust the log level + of a logger when the user changes a corresponding flag via the settings dialog, you can override the + :func:`on_settings_save` method and wrap the call to the implementation from the parent class with retrieval of the + old and the new value and react accordingly. - Example: + Example: - .. code-block:: python + .. code-block:: python - import octoprint.plugin + import octoprint.plugin - class MySettingsPlugin(octoprint.plugin.SettingsPlugin, octoprint.plugin.StartupPlugin): - def get_settings_defaults(self): - return dict( - some_setting="foo", - some_value=23, - sub=dict( - some_flag=True - ) - ) + class MySettingsPlugin(octoprint.plugin.SettingsPlugin, octoprint.plugin.StartupPlugin): + def get_settings_defaults(self): + return dict( + some_setting="foo", + some_value=23, + sub=dict( + some_flag=True + ) + ) - def on_settings_save(self, data): - old_flag = self._settings.get_boolean(["sub", "some_flag"]) + def on_settings_save(self, data): + old_flag = self._settings.get_boolean(["sub", "some_flag"]) - octoprint.plugin.SettingsPlugin.on_settings_save(self, data) + octoprint.plugin.SettingsPlugin.on_settings_save(self, data) - new_flag = self._settings.get_boolean(["sub", "some_flag"]) - if old_flag != new_flag: - self._logger.info("sub.some_flag changed from {old_flag} to {new_flag}".format(**locals())) + new_flag = self._settings.get_boolean(["sub", "some_flag"]) + if old_flag != new_flag: + self._logger.info("sub.some_flag changed from {old_flag} to {new_flag}".format(**locals())) - def on_after_startup(self): - some_setting = self._settings.get(["some_setting"]) - some_value = self._settings.get_int(["some_value"]) - some_flag = self._settings.get_boolean(["sub", "some_flag"]) - self._logger.info("some_setting = {some_setting}, some_value = {some_value}, sub.some_flag = {some_flag}".format(**locals()) + def on_after_startup(self): + some_setting = self._settings.get(["some_setting"]) + some_value = self._settings.get_int(["some_value"]) + some_flag = self._settings.get_boolean(["sub", "some_flag"]) + self._logger.info("some_setting = {some_setting}, some_value = {some_value}, sub.some_flag = {some_flag}".format(**locals()) - __plugin_implementation__ = MySettingsPlugin() + __plugin_implementation__ = MySettingsPlugin() - Of course, you are always free to completely override both :func:`on_settings_load` and :func:`on_settings_save` if the - default implementations do not fit your requirements. + Of course, you are always free to completely override both :func:`on_settings_load` and :func:`on_settings_save` if the + default implementations do not fit your requirements. - .. warning:: + .. warning:: - Make sure to protect sensitive information stored by your plugin that only logged in administrators (or users) - should have access to via :meth:`~octoprint.plugin.SettingsPlugin.get_settings_restricted_paths`. OctoPrint will - return its settings on the REST API even to anonymous clients, but will filter out fields it knows are restricted, - therefore you **must** make sure that you specify sensitive information accordingly to limit access as required! - """ + Make sure to protect sensitive information stored by your plugin that only logged in administrators (or users) + should have access to via :meth:`~octoprint.plugin.SettingsPlugin.get_settings_restricted_paths`. OctoPrint will + return its settings on the REST API even to anonymous clients, but will filter out fields it knows are restricted, + therefore you **must** make sure that you specify sensitive information accordingly to limit access as required! + """ - config_version_key = "_config_version" - """Key of the field in the settings that holds the configuration format version.""" + config_version_key = "_config_version" + """Key of the field in the settings that holds the configuration format version.""" - # noinspection PyMissingConstructor - def __init__(self): - self._settings = None - """ + # noinspection PyMissingConstructor + def __init__(self): + self._settings = None + """ The :class:`~octoprint.plugin.PluginSettings` instance to use for accessing the plugin's settings. Injected by the plugin core system upon initialization of the implementation. """ - def on_settings_load(self): - """ - Loads the settings for the plugin, called by the Settings API view in order to retrieve all settings from - all plugins. Override this if you want to inject additional settings properties that are not stored within - OctoPrint's configuration. - - .. note:: - - The default implementation will return your plugin's settings as is, so just in the structure and in the types - that are currently stored in OctoPrint's configuration. - - If you need more granular control here, e.g. over the used data types, you'll need to override this method - and iterate yourself over all your settings, using the proper retriever methods on the settings manager - to retrieve the data in the correct format. - - The default implementation will also replace any paths that have been restricted by your plugin through - :func:`~octoprint.plugin.SettingsPlugin.get_settings_restricted_paths` with either the provided - default value (if one was provided), an empty dictionary (as fallback for restricted dictionaries), an - empty list (as fallback for restricted lists) or ``None`` values where necessary. - Make sure to do your own restriction if you decide to fully overload this method. - - :return: the current settings of the plugin, as a dictionary - """ - from flask_login import current_user - import copy - - from octoprint.access.permissions import Permissions - - data = copy.deepcopy(self._settings.get_all_data(merged=True)) - if self.config_version_key in data: - del data[self.config_version_key] - - restricted_paths = self.get_settings_restricted_paths() - - # noinspection PyShadowingNames - def restrict_path_unless(data, path, condition): - if not path: - return - - if condition(): - return - - node = data - - if len(path) > 1: - for entry in path[:-1]: - if not entry in node: - return - node = node[entry] - - key = path[-1] - default_value_available = False - default_value = None - if isinstance(key, (list, tuple)): - # key, default_value tuple - key, default_value = key - default_value_available = True - - if key in node: - if default_value_available: - if callable(default_value): - default_value = default_value() - node[key] = default_value - else: - if isinstance(node[key], dict): - node[key] = {} - elif isinstance(node[key], (list, tuple)): - node[key] = [] - else: - node[key] = None - - conditions = {"user": lambda: current_user is not None and not current_user.is_anonymous, - "admin": lambda: current_user is not None and current_user.has_permission(Permissions.SETTINGS), - "never": lambda: False} - - for level, condition in conditions.items(): - paths_for_level = restricted_paths.get(level, []) - for path in paths_for_level: - restrict_path_unless(data, path, condition) - - return data - - def on_settings_save(self, data): - """ - Saves the settings for the plugin, called by the Settings API view in order to persist all settings - from all plugins. Override this if you need to directly react to settings changes or want to extract - additional settings properties that are not stored within OctoPrint's configuration. - - .. note:: - - The default implementation will persist your plugin's settings as is, so just in the structure and in the - types that were received by the Settings API view. Values identical to the default settings values - will *not* be persisted. - - If you need more granular control here, e.g. over the used data types, you'll need to override this method - and iterate yourself over all your settings, retrieving them (if set) from the supplied received ``data`` - and using the proper setter methods on the settings manager to persist the data in the correct format. - - Arguments: - data (dict): The settings dictionary to be saved for the plugin - - Returns: - dict: The settings that differed from the defaults and were actually saved. - """ - import octoprint.util - - # get the current data - current = self._settings.get_all_data() - if current is None: - current = {} - - # merge our new data on top of it - new_current = octoprint.util.dict_merge(current, data) - if self.config_version_key in new_current: - del new_current[self.config_version_key] - - # determine diff dict that contains minimal set of changes against the - # default settings - we only want to persist that, not everything - diff = octoprint.util.dict_minimal_mergediff(self.get_settings_defaults(), new_current) - - version = self.get_settings_version() - - to_persist = dict(diff) - if version: - to_persist[self.config_version_key] = version - - if to_persist: - self._settings.set([], to_persist) - else: - self._settings.clean_all_data() - - return diff - - # noinspection PyMethodMayBeStatic - def get_settings_defaults(self): - """ - Retrieves the plugin's default settings with which the plugin's settings manager will be initialized. - - Override this in your plugin's implementation and return a dictionary defining your settings data structure - with included default values. - """ - return {} - - # noinspection PyMethodMayBeStatic - def get_settings_restricted_paths(self): - """ - Retrieves the list of paths in the plugin's settings which be restricted on the REST API. - - Override this in your plugin's implementation to restrict whether a path should only be returned to users with - the SETTINGS permission, any logged in users, or never on the REST API. - - Return a ``dict`` with the keys ``admin``, ``user``, ``never`` mapping to a list of paths (as tuples or lists of - the path elements) for which to restrict access via the REST API accordingly. Paths returned for the ``admin`` - key will only be available on the REST API when access with admin rights, ``user`` will only be available when accessed - as a logged in user. ``never`` will never be returned on the API. - - Example: - - .. code-block:: python - - def get_settings_defaults(self): - return dict(some=dict(admin_only=dict(path="path", foo="foo"), - user_only=dict(path="path", bar="bar")), - another=dict(admin_only=dict(path="path"), - field="field"), - path=dict(to=dict(never=dict(return="return")))) - - def get_settings_restricted_paths(self): - return dict(admin=[["some", "admin_only", "path"], ["another", "admin_only", "path"],], - user=[["some", "user_only", "path"],], - never=[["path", "to", "never", "return"],]) - - # this will make the plugin return settings on the REST API like this for an anonymous user - # - # dict(some=dict(admin_only=dict(path=None, foo="foo"), - # user_only=dict(path=None, bar="bar")), - # another=dict(admin_only=dict(path=None), - # field="field"), - # path=dict(to=dict(never=dict(return=None)))) - # - # like this for a logged in user - # - # dict(some=dict(admin_only=dict(path=None, foo="foo"), - # user_only=dict(path="path", bar="bar")), - # another=dict(admin_only=dict(path=None), - # field="field"), - # path=dict(to=dict(never=dict(return=None)))) - # - # and like this for an admin user - # - # dict(some=dict(admin_only=dict(path="path", foo="foo"), - # user_only=dict(path="path", bar="bar")), - # another=dict(admin_only=dict(path="path"), - # field="field"), - # path=dict(to=dict(never=dict(return=None)))) - - ..versionadded:: 1.2.17 - """ - return {} - - # noinspection PyMethodMayBeStatic - def get_settings_preprocessors(self): - """ - Retrieves the plugin's preprocessors to use for preprocessing returned or set values prior to returning/setting - them. - - The preprocessors should be provided as a dictionary mapping the path of the values to preprocess - (hierarchically) to a transform function which will get the value to transform as only input and should return - the transformed value. - - Example: - - .. code-block:: python - - def get_settings_defaults(self): - return dict(some_key="Some_Value", some_other_key="Some_Value") - - def get_settings_preprocessors(self): - return dict(some_key=lambda x: x.upper()), # getter preprocessors - dict(some_other_key=lambda x: x.lower()) # setter preprocessors - - def some_method(self): - # getting the value for "some_key" should turn it to upper case - assert self._settings.get(["some_key"]) == "SOME_VALUE" - - # the value for "some_other_key" should be left alone - assert self._settings.get(["some_other_key"] = "Some_Value" - - # setting a value for "some_other_key" should cause the value to first be turned to lower case - self._settings.set(["some_other_key"], "SOME_OTHER_VALUE") - assert self._settings.get(["some_other_key"]) == "some_other_value" - - Returns: - (dict, dict): A tuple consisting of two dictionaries, the first being the plugin's preprocessors for - getters, the second the preprocessors for setters - """ - return {}, {} - - # noinspection PyMethodMayBeStatic - def get_settings_version(self): - """ - Retrieves the settings format version of the plugin. - - Use this to have OctoPrint trigger your migration function if it detects an outdated settings version in - config.yaml. - - Returns: - int or None: an int signifying the current settings format, should be incremented by plugins whenever there - are backwards incompatible changes. Returning None here disables the version tracking for the - plugin's configuration. - """ - return None - - # noinspection PyMethodMayBeStatic - def on_settings_migrate(self, target, current): - """ - Called by OctoPrint if it detects that the installed version of the plugin necessitates a higher settings version - than the one currently stored in _config.yaml. Will also be called if the settings data stored in config.yaml - doesn't have version information, in which case the ``current`` parameter will be None. - - Your plugin's implementation should take care of migrating any data by utilizing self._settings. OctoPrint - will take care of saving any changes to disk by calling `self._settings.save()` after returning from this method. - - This method will be called before your plugin's :func:`on_settings_initialized` method, with all injections already - having taken place. You can therefore depend on the configuration having been migrated by the time - :func:`on_settings_initialized` is called. - - Arguments: - target (int): The settings format version the plugin requires, this should always be the same value as - returned by :func:`get_settings_version`. - current (int or None): The settings format version as currently stored in config.yaml. May be None if - no version information can be found. - """ - pass - - def on_settings_cleanup(self): - """ - Called after migration and initialization but before call to :func:`on_settings_initialized`. - - Plugins may overwrite this method to perform additional clean up tasks. - - The default implementation just minimizes the data persisted on disk to only contain - the differences to the defaults (in case the current data was persisted with an older - version of OctoPrint that still duplicated default data). - - ..versionadded:: 1.3.0 - """ - import octoprint.util - from octoprint.settings import NoSuchSettingsPath - - try: - # let's fetch the current persisted config (so only the data on disk, - # without the defaults) - config = self._settings.get_all_data(merged=False, incl_defaults=False, error_on_path=True) - except NoSuchSettingsPath: - # no config persisted, nothing to do => get out of here - return - - if config is None: - # config is set to None, that doesn't make sense, kill it and leave - self._settings.clean_all_data() - return - - if self.config_version_key in config and config[self.config_version_key] is None: - # delete None entries for config version - it's the default, no need - del config[self.config_version_key] - - # calculate a minimal diff between the settings and the current config - - # anything already in the settings will be removed from the persisted - # config, no need to duplicate it - defaults = self.get_settings_defaults() - diff = octoprint.util.dict_minimal_mergediff(defaults, config) - - if not diff: - # no diff to defaults, no need to have anything persisted - self._settings.clean_all_data() - else: - # diff => persist only that - self._settings.set([], diff) - - def on_settings_initialized(self): - """ - Called after the settings have been initialized and - if necessary - also been migrated through a call to - func:`on_settings_migrate`. - - This method will always be called after the `initialize` method. - """ - pass + def on_settings_load(self): + """ + Loads the settings for the plugin, called by the Settings API view in order to retrieve all settings from + all plugins. Override this if you want to inject additional settings properties that are not stored within + OctoPrint's configuration. + + .. note:: + + The default implementation will return your plugin's settings as is, so just in the structure and in the types + that are currently stored in OctoPrint's configuration. + + If you need more granular control here, e.g. over the used data types, you'll need to override this method + and iterate yourself over all your settings, using the proper retriever methods on the settings manager + to retrieve the data in the correct format. + + The default implementation will also replace any paths that have been restricted by your plugin through + :func:`~octoprint.plugin.SettingsPlugin.get_settings_restricted_paths` with either the provided + default value (if one was provided), an empty dictionary (as fallback for restricted dictionaries), an + empty list (as fallback for restricted lists) or ``None`` values where necessary. + Make sure to do your own restriction if you decide to fully overload this method. + + :return: the current settings of the plugin, as a dictionary + """ + from flask_login import current_user + import copy + + from octoprint.access.permissions import Permissions + + data = copy.deepcopy(self._settings.get_all_data(merged=True)) + if self.config_version_key in data: + del data[self.config_version_key] + + restricted_paths = self.get_settings_restricted_paths() + + # noinspection PyShadowingNames + def restrict_path_unless(data, path, condition): + if not path: + return + + if condition(): + return + + node = data + + if len(path) > 1: + for entry in path[:-1]: + if not entry in node: + return + node = node[entry] + + key = path[-1] + default_value_available = False + default_value = None + if isinstance(key, (list, tuple)): + # key, default_value tuple + key, default_value = key + default_value_available = True + + if key in node: + if default_value_available: + if callable(default_value): + default_value = default_value() + node[key] = default_value + else: + if isinstance(node[key], dict): + node[key] = {} + elif isinstance(node[key], (list, tuple)): + node[key] = [] + else: + node[key] = None + + conditions = { + "user": lambda: current_user is not None and not current_user.is_anonymous, + "admin": lambda: current_user is not None + and current_user.has_permission(Permissions.SETTINGS), + "never": lambda: False, + } + + for level, condition in conditions.items(): + paths_for_level = restricted_paths.get(level, []) + for path in paths_for_level: + restrict_path_unless(data, path, condition) + + return data + + def on_settings_save(self, data): + """ + Saves the settings for the plugin, called by the Settings API view in order to persist all settings + from all plugins. Override this if you need to directly react to settings changes or want to extract + additional settings properties that are not stored within OctoPrint's configuration. + + .. note:: + + The default implementation will persist your plugin's settings as is, so just in the structure and in the + types that were received by the Settings API view. Values identical to the default settings values + will *not* be persisted. + + If you need more granular control here, e.g. over the used data types, you'll need to override this method + and iterate yourself over all your settings, retrieving them (if set) from the supplied received ``data`` + and using the proper setter methods on the settings manager to persist the data in the correct format. + + Arguments: + data (dict): The settings dictionary to be saved for the plugin + + Returns: + dict: The settings that differed from the defaults and were actually saved. + """ + import octoprint.util + + # get the current data + current = self._settings.get_all_data() + if current is None: + current = {} + + # merge our new data on top of it + new_current = octoprint.util.dict_merge(current, data) + if self.config_version_key in new_current: + del new_current[self.config_version_key] + + # determine diff dict that contains minimal set of changes against the + # default settings - we only want to persist that, not everything + diff = octoprint.util.dict_minimal_mergediff( + self.get_settings_defaults(), new_current + ) + + version = self.get_settings_version() + + to_persist = dict(diff) + if version: + to_persist[self.config_version_key] = version + + if to_persist: + self._settings.set([], to_persist) + else: + self._settings.clean_all_data() + + return diff + + # noinspection PyMethodMayBeStatic + def get_settings_defaults(self): + """ + Retrieves the plugin's default settings with which the plugin's settings manager will be initialized. + + Override this in your plugin's implementation and return a dictionary defining your settings data structure + with included default values. + """ + return {} + + # noinspection PyMethodMayBeStatic + def get_settings_restricted_paths(self): + """ + Retrieves the list of paths in the plugin's settings which be restricted on the REST API. + + Override this in your plugin's implementation to restrict whether a path should only be returned to users with + the SETTINGS permission, any logged in users, or never on the REST API. + + Return a ``dict`` with the keys ``admin``, ``user``, ``never`` mapping to a list of paths (as tuples or lists of + the path elements) for which to restrict access via the REST API accordingly. Paths returned for the ``admin`` + key will only be available on the REST API when access with admin rights, ``user`` will only be available when accessed + as a logged in user. ``never`` will never be returned on the API. + + Example: + + .. code-block:: python + + def get_settings_defaults(self): + return dict(some=dict(admin_only=dict(path="path", foo="foo"), + user_only=dict(path="path", bar="bar")), + another=dict(admin_only=dict(path="path"), + field="field"), + path=dict(to=dict(never=dict(return="return")))) + + def get_settings_restricted_paths(self): + return dict(admin=[["some", "admin_only", "path"], ["another", "admin_only", "path"],], + user=[["some", "user_only", "path"],], + never=[["path", "to", "never", "return"],]) + + # this will make the plugin return settings on the REST API like this for an anonymous user + # + # dict(some=dict(admin_only=dict(path=None, foo="foo"), + # user_only=dict(path=None, bar="bar")), + # another=dict(admin_only=dict(path=None), + # field="field"), + # path=dict(to=dict(never=dict(return=None)))) + # + # like this for a logged in user + # + # dict(some=dict(admin_only=dict(path=None, foo="foo"), + # user_only=dict(path="path", bar="bar")), + # another=dict(admin_only=dict(path=None), + # field="field"), + # path=dict(to=dict(never=dict(return=None)))) + # + # and like this for an admin user + # + # dict(some=dict(admin_only=dict(path="path", foo="foo"), + # user_only=dict(path="path", bar="bar")), + # another=dict(admin_only=dict(path="path"), + # field="field"), + # path=dict(to=dict(never=dict(return=None)))) + + ..versionadded:: 1.2.17 + """ + return {} + + # noinspection PyMethodMayBeStatic + def get_settings_preprocessors(self): + """ + Retrieves the plugin's preprocessors to use for preprocessing returned or set values prior to returning/setting + them. + + The preprocessors should be provided as a dictionary mapping the path of the values to preprocess + (hierarchically) to a transform function which will get the value to transform as only input and should return + the transformed value. + + Example: + + .. code-block:: python + + def get_settings_defaults(self): + return dict(some_key="Some_Value", some_other_key="Some_Value") + + def get_settings_preprocessors(self): + return dict(some_key=lambda x: x.upper()), # getter preprocessors + dict(some_other_key=lambda x: x.lower()) # setter preprocessors + + def some_method(self): + # getting the value for "some_key" should turn it to upper case + assert self._settings.get(["some_key"]) == "SOME_VALUE" + + # the value for "some_other_key" should be left alone + assert self._settings.get(["some_other_key"] = "Some_Value" + + # setting a value for "some_other_key" should cause the value to first be turned to lower case + self._settings.set(["some_other_key"], "SOME_OTHER_VALUE") + assert self._settings.get(["some_other_key"]) == "some_other_value" + + Returns: + (dict, dict): A tuple consisting of two dictionaries, the first being the plugin's preprocessors for + getters, the second the preprocessors for setters + """ + return {}, {} + + # noinspection PyMethodMayBeStatic + def get_settings_version(self): + """ + Retrieves the settings format version of the plugin. + + Use this to have OctoPrint trigger your migration function if it detects an outdated settings version in + config.yaml. + + Returns: + int or None: an int signifying the current settings format, should be incremented by plugins whenever there + are backwards incompatible changes. Returning None here disables the version tracking for the + plugin's configuration. + """ + return None + + # noinspection PyMethodMayBeStatic + def on_settings_migrate(self, target, current): + """ + Called by OctoPrint if it detects that the installed version of the plugin necessitates a higher settings version + than the one currently stored in _config.yaml. Will also be called if the settings data stored in config.yaml + doesn't have version information, in which case the ``current`` parameter will be None. + + Your plugin's implementation should take care of migrating any data by utilizing self._settings. OctoPrint + will take care of saving any changes to disk by calling `self._settings.save()` after returning from this method. + + This method will be called before your plugin's :func:`on_settings_initialized` method, with all injections already + having taken place. You can therefore depend on the configuration having been migrated by the time + :func:`on_settings_initialized` is called. + + Arguments: + target (int): The settings format version the plugin requires, this should always be the same value as + returned by :func:`get_settings_version`. + current (int or None): The settings format version as currently stored in config.yaml. May be None if + no version information can be found. + """ + pass + + def on_settings_cleanup(self): + """ + Called after migration and initialization but before call to :func:`on_settings_initialized`. + + Plugins may overwrite this method to perform additional clean up tasks. + + The default implementation just minimizes the data persisted on disk to only contain + the differences to the defaults (in case the current data was persisted with an older + version of OctoPrint that still duplicated default data). + + ..versionadded:: 1.3.0 + """ + import octoprint.util + from octoprint.settings import NoSuchSettingsPath + + try: + # let's fetch the current persisted config (so only the data on disk, + # without the defaults) + config = self._settings.get_all_data( + merged=False, incl_defaults=False, error_on_path=True + ) + except NoSuchSettingsPath: + # no config persisted, nothing to do => get out of here + return + + if config is None: + # config is set to None, that doesn't make sense, kill it and leave + self._settings.clean_all_data() + return + + if self.config_version_key in config and config[self.config_version_key] is None: + # delete None entries for config version - it's the default, no need + del config[self.config_version_key] + + # calculate a minimal diff between the settings and the current config - + # anything already in the settings will be removed from the persisted + # config, no need to duplicate it + defaults = self.get_settings_defaults() + diff = octoprint.util.dict_minimal_mergediff(defaults, config) + + if not diff: + # no diff to defaults, no need to have anything persisted + self._settings.clean_all_data() + else: + # diff => persist only that + self._settings.set([], diff) + + def on_settings_initialized(self): + """ + Called after the settings have been initialized and - if necessary - also been migrated through a call to + func:`on_settings_migrate`. + + This method will always be called after the `initialize` method. + """ + pass class EventHandlerPlugin(OctoPrintPlugin): - """ - The ``EventHandlerPlugin`` mixin allows OctoPrint plugins to react to any of :ref:`OctoPrint's events `. - OctoPrint will call the :func:`on_event` method for any event fired on its internal event bus, supplying the - event type and the associated payload. Please note that until your plugin returns from that method, further event - processing within OctoPrint will block - the event queue itself is run asynchronously from the rest of OctoPrint, - but the processing of the events within the queue itself happens consecutively. + """ + The ``EventHandlerPlugin`` mixin allows OctoPrint plugins to react to any of :ref:`OctoPrint's events `. + OctoPrint will call the :func:`on_event` method for any event fired on its internal event bus, supplying the + event type and the associated payload. Please note that until your plugin returns from that method, further event + processing within OctoPrint will block - the event queue itself is run asynchronously from the rest of OctoPrint, + but the processing of the events within the queue itself happens consecutively. - This mixin is especially interesting for plugins which want to react on things like print jobs finishing, timelapse - videos rendering etc. - """ + This mixin is especially interesting for plugins which want to react on things like print jobs finishing, timelapse + videos rendering etc. + """ - # noinspection PyMethodMayBeStatic - def on_event(self, event, payload): - """ - Called by OctoPrint upon processing of a fired event on the platform. + # noinspection PyMethodMayBeStatic + def on_event(self, event, payload): + """ + Called by OctoPrint upon processing of a fired event on the platform. - .. warning:: + .. warning:: - Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server. + Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server. - Arguments: - event (str): The type of event that got fired, see :ref:`the list of events ` - for possible values - payload (dict): The payload as provided with the event - """ - pass + Arguments: + event (str): The type of event that got fired, see :ref:`the list of events ` + for possible values + payload (dict): The payload as provided with the event + """ + pass class SlicerPlugin(OctoPrintPlugin): - """ - Via the ``SlicerPlugin`` mixin plugins can add support for slicing engines to be used by OctoPrint. + """ + Via the ``SlicerPlugin`` mixin plugins can add support for slicing engines to be used by OctoPrint. - """ + """ - # noinspection PyMethodMayBeStatic - def is_slicer_configured(self): - """ - Unless the return value of this method is ``True``, OctoPrint will not register the slicer within the slicing - sub system upon startup. Plugins may use this to do some start up checks to verify that e.g. the path to - a slicing binary as set and the binary is executable, or credentials of a cloud slicing platform are properly - entered etc. - """ - return False + # noinspection PyMethodMayBeStatic + def is_slicer_configured(self): + """ + Unless the return value of this method is ``True``, OctoPrint will not register the slicer within the slicing + sub system upon startup. Plugins may use this to do some start up checks to verify that e.g. the path to + a slicing binary as set and the binary is executable, or credentials of a cloud slicing platform are properly + entered etc. + """ + return False - # noinspection PyMethodMayBeStatic - def get_slicer_properties(self): - """ - Plugins should override this method to return a ``dict`` containing a bunch of meta data about the implemented slicer. + # noinspection PyMethodMayBeStatic + def get_slicer_properties(self): + """ + Plugins should override this method to return a ``dict`` containing a bunch of meta data about the implemented slicer. - The expected keys in the returned ``dict`` have the following meaning: + The expected keys in the returned ``dict`` have the following meaning: - type - The type identifier to use for the slicer. This should be a short unique lower case string which will be - used to store slicer profiles under or refer to the slicer programmatically or from the API. - name - The human readable name of the slicer. This will be displayed to the user during slicer selection. - same_device - True if the slicer runs on the same device as OctoPrint, False otherwise. Slicers running on the same - device will not be allowed to slice on systems with less than two CPU cores (or an unknown number) while a - print is running due to performance reasons. Slice requests against slicers running on the same device and - less than two cores will result in an error. - progress_report - ``True`` if the slicer can report back slicing progress to OctoPrint ``False`` otherwise. - source_file_types - A list of file types this slicer supports as valid origin file types. These are file types as found in the - paths within the extension tree. Plugins may add additional file types through the :ref:`sec-plugins-hook-filemanager-extensiontree` hook. - The system will test source files contains in incoming slicing requests via :meth:`octoprint.filemanager.valid_file_type` against the - targeted slicer's ``source_file_types``. - destination_extension - The possible extensions of slicing result files. + type + The type identifier to use for the slicer. This should be a short unique lower case string which will be + used to store slicer profiles under or refer to the slicer programmatically or from the API. + name + The human readable name of the slicer. This will be displayed to the user during slicer selection. + same_device + True if the slicer runs on the same device as OctoPrint, False otherwise. Slicers running on the same + device will not be allowed to slice on systems with less than two CPU cores (or an unknown number) while a + print is running due to performance reasons. Slice requests against slicers running on the same device and + less than two cores will result in an error. + progress_report + ``True`` if the slicer can report back slicing progress to OctoPrint ``False`` otherwise. + source_file_types + A list of file types this slicer supports as valid origin file types. These are file types as found in the + paths within the extension tree. Plugins may add additional file types through the :ref:`sec-plugins-hook-filemanager-extensiontree` hook. + The system will test source files contains in incoming slicing requests via :meth:`octoprint.filemanager.valid_file_type` against the + targeted slicer's ``source_file_types``. + destination_extension + The possible extensions of slicing result files. - Returns: - dict: A dict describing the slicer as outlined above. - """ - return {"type": None, - "name": None, - "same_device": True, - "progress_report": False, - "source_file_types": ["model"], - "destination_extensions": ["gco", "gcode", "g"]} + Returns: + dict: A dict describing the slicer as outlined above. + """ + return { + "type": None, + "name": None, + "same_device": True, + "progress_report": False, + "source_file_types": ["model"], + "destination_extensions": ["gco", "gcode", "g"], + } - # noinspection PyMethodMayBeStatic - def get_slicer_extension_tree(self): - """ - Fetch additional entries to put into the extension tree for accepted files + # noinspection PyMethodMayBeStatic + def get_slicer_extension_tree(self): + """ + Fetch additional entries to put into the extension tree for accepted files - By default, a subtree for ``model`` files with ``stl`` extension is returned. Slicers who want to support - additional/other file types will want to override this. + By default, a subtree for ``model`` files with ``stl`` extension is returned. Slicers who want to support + additional/other file types will want to override this. - For the extension tree format, take a look at the docs of the :ref:`octoprint.filemanager.extension_tree hook `. + For the extension tree format, take a look at the docs of the :ref:`octoprint.filemanager.extension_tree hook `. - Returns: (dict) a dictionary containing a valid extension subtree. + Returns: (dict) a dictionary containing a valid extension subtree. - ..versionadded:: 1.3.11 - """ - from octoprint.filemanager import ContentTypeMapping - return {"model": {"stl": ContentTypeMapping(["stl"], "application/sla")}} + ..versionadded:: 1.3.11 + """ + from octoprint.filemanager import ContentTypeMapping - def get_slicer_profiles(self, profile_path): - """ - Fetch all :class:`~octoprint.slicing.SlicingProfile` stored for this slicer. + return {"model": {"stl": ContentTypeMapping(["stl"], "application/sla")}} - For compatibility reasons with existing slicing plugins this method defaults to returning profiles parsed from - .profile files in the plugin's ``profile_path``, utilizing the :func:`SlicingPlugin.get_slicer_profile` method - of the plugin implementation. + def get_slicer_profiles(self, profile_path): + """ + Fetch all :class:`~octoprint.slicing.SlicingProfile` stored for this slicer. - Arguments: - profile_path (str): The base folder where OctoPrint stores this slicer plugin's profiles + For compatibility reasons with existing slicing plugins this method defaults to returning profiles parsed from + .profile files in the plugin's ``profile_path``, utilizing the :func:`SlicingPlugin.get_slicer_profile` method + of the plugin implementation. - ..versionadded:: 1.3.7 - """ + Arguments: + profile_path (str): The base folder where OctoPrint stores this slicer plugin's profiles - try: - from os import scandir - except ImportError: - from scandir import scandir + ..versionadded:: 1.3.7 + """ - import octoprint.util + try: + from os import scandir + except ImportError: + from scandir import scandir - profiles = {} - for entry in scandir(profile_path): - if not entry.name.endswith(".profile") or octoprint.util.is_hidden_path(entry.name): - # we are only interested in profiles and no hidden files - continue + import octoprint.util - profile_name = entry.name[:-len(".profile")] - profiles[profile_name] = self.get_slicer_profile(entry.path) - return profiles + profiles = {} + for entry in scandir(profile_path): + if not entry.name.endswith(".profile") or octoprint.util.is_hidden_path( + entry.name + ): + # we are only interested in profiles and no hidden files + continue - # noinspection PyMethodMayBeStatic - def get_slicer_profiles_lastmodified(self, profile_path): - """ - ..versionadded:: 1.3.0 - """ - import os - try: - from os import scandir - except ImportError: - from scandir import scandir + profile_name = entry.name[: -len(".profile")] + profiles[profile_name] = self.get_slicer_profile(entry.path) + return profiles - lms = [os.stat(profile_path).st_mtime] - lms += [os.stat(entry.path).st_mtime for entry in scandir(profile_path) if entry.name.endswith(".profile")] - return max(lms) + # noinspection PyMethodMayBeStatic + def get_slicer_profiles_lastmodified(self, profile_path): + """ + ..versionadded:: 1.3.0 + """ + import os - # noinspection PyMethodMayBeStatic - def get_slicer_default_profile(self): - """ - Should return a :class:`~octoprint.slicing.SlicingProfile` containing the default slicing profile to use with - this slicer if no other profile has been selected. + try: + from os import scandir + except ImportError: + from scandir import scandir - Returns: - SlicingProfile: The :class:`~octoprint.slicing.SlicingProfile` containing the default slicing profile for - this slicer. - """ - return None + lms = [os.stat(profile_path).st_mtime] + lms += [ + os.stat(entry.path).st_mtime + for entry in scandir(profile_path) + if entry.name.endswith(".profile") + ] + return max(lms) - # noinspection PyMethodMayBeStatic - def get_slicer_profile(self, path): - """ - Should return a :class:`~octoprint.slicing.SlicingProfile` parsed from the slicing profile stored at the - indicated ``path``. + # noinspection PyMethodMayBeStatic + def get_slicer_default_profile(self): + """ + Should return a :class:`~octoprint.slicing.SlicingProfile` containing the default slicing profile to use with + this slicer if no other profile has been selected. - Arguments: - path (str): The absolute path from which to read the slicing profile. + Returns: + SlicingProfile: The :class:`~octoprint.slicing.SlicingProfile` containing the default slicing profile for + this slicer. + """ + return None - Returns: - SlicingProfile: The specified slicing profile. - """ - return None + # noinspection PyMethodMayBeStatic + def get_slicer_profile(self, path): + """ + Should return a :class:`~octoprint.slicing.SlicingProfile` parsed from the slicing profile stored at the + indicated ``path``. - # noinspection PyMethodMayBeStatic - def save_slicer_profile(self, path, profile, allow_overwrite=True, overrides=None): - """ - Should save the provided :class:`~octoprint.slicing.SlicingProfile` to the indicated ``path``, after applying - any supplied ``overrides``. If a profile is already saved under the indicated path and ``allow_overwrite`` is - set to False (defaults to True), an :class:`IOError` should be raised. + Arguments: + path (str): The absolute path from which to read the slicing profile. - Arguments: - path (str): The absolute path to which to save the profile. - profile (SlicingProfile): The profile to save. - allow_overwrite (boolean): Whether to allow to overwrite an existing profile at the indicated path (True, - default) or not (False). If a profile already exists on the path and this is False an - :class:`IOError` should be raised. - overrides (dict): Profile overrides to apply to the ``profile`` before saving it - """ - pass + Returns: + SlicingProfile: The specified slicing profile. + """ + return None - # noinspection PyMethodMayBeStatic - def do_slice(self, model_path, printer_profile, machinecode_path=None, profile_path=None, position=None, on_progress=None, on_progress_args=None, on_progress_kwargs=None): - """ - Called by OctoPrint to slice ``model_path`` for the indicated ``printer_profile``. If the ``machinecode_path`` is ``None``, - slicer implementations should generate it from the provided ``model_path``. + # noinspection PyMethodMayBeStatic + def save_slicer_profile(self, path, profile, allow_overwrite=True, overrides=None): + """ + Should save the provided :class:`~octoprint.slicing.SlicingProfile` to the indicated ``path``, after applying + any supplied ``overrides``. If a profile is already saved under the indicated path and ``allow_overwrite`` is + set to False (defaults to True), an :class:`IOError` should be raised. - If provided, the ``profile_path`` is guaranteed by OctoPrint to be a serialized slicing profile created through the slicing - plugin's own :func:`save_slicer_profile` method. + Arguments: + path (str): The absolute path to which to save the profile. + profile (SlicingProfile): The profile to save. + allow_overwrite (boolean): Whether to allow to overwrite an existing profile at the indicated path (True, + default) or not (False). If a profile already exists on the path and this is False an + :class:`IOError` should be raised. + overrides (dict): Profile overrides to apply to the ``profile`` before saving it + """ + pass - If provided, ``position`` will be a ``dict`` containing and ``x`` and a ``y`` key, indicating the position - the center of the model on the print bed should have in the final sliced machine code. If not provided, slicer - implementations should place the model in the center of the print bed. + # noinspection PyMethodMayBeStatic + def do_slice( + self, + model_path, + printer_profile, + machinecode_path=None, + profile_path=None, + position=None, + on_progress=None, + on_progress_args=None, + on_progress_kwargs=None, + ): + """ + Called by OctoPrint to slice ``model_path`` for the indicated ``printer_profile``. If the ``machinecode_path`` is ``None``, + slicer implementations should generate it from the provided ``model_path``. - ``on_progress`` will be a callback which expects an additional keyword argument ``_progress`` with the current - slicing progress which - if progress reporting is supported - the slicing plugin should call like the following: + If provided, the ``profile_path`` is guaranteed by OctoPrint to be a serialized slicing profile created through the slicing + plugin's own :func:`save_slicer_profile` method. - .. code-block:: python + If provided, ``position`` will be a ``dict`` containing and ``x`` and a ``y`` key, indicating the position + the center of the model on the print bed should have in the final sliced machine code. If not provided, slicer + implementations should place the model in the center of the print bed. - if on_progress is not None: - if on_progress_args is None: - on_progress_args = () - if on_progress_kwargs is None: - on_progress_kwargs = dict() + ``on_progress`` will be a callback which expects an additional keyword argument ``_progress`` with the current + slicing progress which - if progress reporting is supported - the slicing plugin should call like the following: - on_progress_kwargs["_progress"] = your_plugins_slicing_progress - on_progress(*on_progress_args, **on_progress_kwargs) + .. code-block:: python - Please note that both ``on_progress_args`` and ``on_progress_kwargs`` as supplied by OctoPrint might be ``None``, - so always make sure to initialize those values to sane defaults like depicted above before invoking the callback. + if on_progress is not None: + if on_progress_args is None: + on_progress_args = () + if on_progress_kwargs is None: + on_progress_kwargs = dict() - In order to support external cancellation of an ongoing slicing job via :func:`cancel_slicing`, implementations - should make sure to track the started jobs via the ``machinecode_path``, if provided. + on_progress_kwargs["_progress"] = your_plugins_slicing_progress + on_progress(*on_progress_args, **on_progress_kwargs) - The method should return a 2-tuple consisting of a boolean ``flag`` indicating whether the slicing job was - finished successfully (True) or not (False) and a ``result`` depending on the success of the slicing job. + Please note that both ``on_progress_args`` and ``on_progress_kwargs`` as supplied by OctoPrint might be ``None``, + so always make sure to initialize those values to sane defaults like depicted above before invoking the callback. - For jobs that finished successfully, ``result`` should be a :class:`dict` containing additional information - about the slicing job under the following keys: + In order to support external cancellation of an ongoing slicing job via :func:`cancel_slicing`, implementations + should make sure to track the started jobs via the ``machinecode_path``, if provided. - analysis - Analysis result of the generated machine code as returned by the slicer itself. This should match the - data structure described for the analysis queue of the matching machine code format, e.g. - :class:`~octoprint.filemanager.analysis.GcodeAnalysisQueue` for GCODE files. + The method should return a 2-tuple consisting of a boolean ``flag`` indicating whether the slicing job was + finished successfully (True) or not (False) and a ``result`` depending on the success of the slicing job. - For jobs that did not finish successfully (but not due to being cancelled!), ``result`` should be a :class:`str` - containing a human readable reason for the error. + For jobs that finished successfully, ``result`` should be a :class:`dict` containing additional information + about the slicing job under the following keys: - If the job gets cancelled, a :class:`~octoprint.slicing.SlicingCancelled` exception should be raised. + analysis + Analysis result of the generated machine code as returned by the slicer itself. This should match the + data structure described for the analysis queue of the matching machine code format, e.g. + :class:`~octoprint.filemanager.analysis.GcodeAnalysisQueue` for GCODE files. - Returns: - tuple: A 2-tuple (boolean, object) as outlined above. + For jobs that did not finish successfully (but not due to being cancelled!), ``result`` should be a :class:`str` + containing a human readable reason for the error. - Raises: - SlicingCancelled: The slicing job was cancelled (via :meth:`cancel_slicing`). - """ - pass + If the job gets cancelled, a :class:`~octoprint.slicing.SlicingCancelled` exception should be raised. - # noinspection PyMethodMayBeStatic - def cancel_slicing(self, machinecode_path): - """ - Cancels the slicing to the indicated file. + Returns: + tuple: A 2-tuple (boolean, object) as outlined above. - Arguments: - machinecode_path (str): The absolute path to the machine code file to which to stop slicing to. - """ - pass + Raises: + SlicingCancelled: The slicing job was cancelled (via :meth:`cancel_slicing`). + """ + pass + + # noinspection PyMethodMayBeStatic + def cancel_slicing(self, machinecode_path): + """ + Cancels the slicing to the indicated file. + + Arguments: + machinecode_path (str): The absolute path to the machine code file to which to stop slicing to. + """ + pass class ProgressPlugin(OctoPrintPlugin): - """ - Via the ``ProgressPlugin`` mixing plugins can let themselves be called upon progress in print jobs or slicing jobs, - limited to minimally 1% steps. - """ + """ + Via the ``ProgressPlugin`` mixing plugins can let themselves be called upon progress in print jobs or slicing jobs, + limited to minimally 1% steps. + """ - # noinspection PyMethodMayBeStatic - def on_print_progress(self, storage, path, progress): - """ - Called by OctoPrint on minimally 1% increments during a running print job. + # noinspection PyMethodMayBeStatic + def on_print_progress(self, storage, path, progress): + """ + Called by OctoPrint on minimally 1% increments during a running print job. - :param string storage: Location of the file - :param string path: Path of the file - :param int progress: Current progress as a value between 0 and 100 - """ - pass + :param string storage: Location of the file + :param string path: Path of the file + :param int progress: Current progress as a value between 0 and 100 + """ + pass - # noinspection PyMethodMayBeStatic - def on_slicing_progress(self, slicer, source_location, source_path, destination_location, destination_path, progress): - """ - Called by OctoPrint on minimally 1% increments during a running slicing job. + # noinspection PyMethodMayBeStatic + def on_slicing_progress( + self, + slicer, + source_location, + source_path, + destination_location, + destination_path, + progress, + ): + """ + Called by OctoPrint on minimally 1% increments during a running slicing job. - :param string slicer: Key of the slicer reporting the progress - :param string source_location: Location of the source file - :param string source_path: Path of the source file - :param string destination_location: Location the destination file - :param string destination_path: Path of the destination file - :param int progress: Current progress as a value between 0 and 100 - """ - pass + :param string slicer: Key of the slicer reporting the progress + :param string source_location: Location of the source file + :param string source_path: Path of the source file + :param string destination_location: Location the destination file + :param string destination_path: Path of the destination file + :param int progress: Current progress as a value between 0 and 100 + """ + pass diff --git a/src/octoprint/plugins/action_command_notification/__init__.py b/src/octoprint/plugins/action_command_notification/__init__.py index 5170c5f14..8571ebb5d 100644 --- a/src/octoprint/plugins/action_command_notification/__init__.py +++ b/src/octoprint/plugins/action_command_notification/__init__.py @@ -1,7 +1,7 @@ # -*- 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License" import octoprint.plugin @@ -15,118 +15,138 @@ from flask_babel import gettext import time -class ActionCommandNotificationPlugin(octoprint.plugin.AssetPlugin, - octoprint.plugin.SettingsPlugin, - octoprint.plugin.SimpleApiPlugin, - octoprint.plugin.TemplatePlugin, - octoprint.plugin.EventHandlerPlugin): - def __init__(self): - self._notifications = [] +class ActionCommandNotificationPlugin( + octoprint.plugin.AssetPlugin, + octoprint.plugin.SettingsPlugin, + octoprint.plugin.SimpleApiPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.EventHandlerPlugin, +): + def __init__(self): + self._notifications = [] - # Additional permissions hook + # Additional permissions hook - def get_additional_permissions(self): - return [ - {"key": "SHOW", - "name": "Show printer notifications", - "description": gettext("Allows to see printer notifications"), - "default_groups": [USER_GROUP], - "roles": ["show"]}, - {"key": "CLEAR", - "name": "Clear printer notifications", - "description": gettext("Allows to clear printer notifications"), - "default_groups": [USER_GROUP], - "roles": ["clear"]} - ] + def get_additional_permissions(self): + return [ + { + "key": "SHOW", + "name": "Show printer notifications", + "description": gettext("Allows to see printer notifications"), + "default_groups": [USER_GROUP], + "roles": ["show"], + }, + { + "key": "CLEAR", + "name": "Clear printer notifications", + "description": gettext("Allows to clear printer notifications"), + "default_groups": [USER_GROUP], + "roles": ["clear"], + }, + ] - #~ AssetPlugin + # ~ AssetPlugin - def get_assets(self): - return {"js": ["js/action_command_notification.js"], - "clientjs": ["clientjs/action_command_notification.js"], - "css": ["css/action_command_notification.css"]} + def get_assets(self): + return { + "js": ["js/action_command_notification.js"], + "clientjs": ["clientjs/action_command_notification.js"], + "css": ["css/action_command_notification.css"], + } - #~ EventHandlerPlugin + # ~ EventHandlerPlugin - def on_event(self, event, payload): - if event == Events.DISCONNECTED: - self._clear_notifications() + def on_event(self, event, payload): + if event == Events.DISCONNECTED: + self._clear_notifications() - #~ SettingsPlugin + # ~ SettingsPlugin - def get_settings_defaults(self): - return {"enable": True, - "enable_popups": False} + def get_settings_defaults(self): + return {"enable": True, "enable_popups": False} - #~ SimpleApiPlugin + # ~ SimpleApiPlugin - def on_api_get(self, request): - if not Permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW.can(): - return flask.abort(403, "Insufficient permissions") - return flask.jsonify(notifications=[{"timestamp": notification[0], - "message": notification[1]} for notification in self._notifications]) + def on_api_get(self, request): + if not Permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW.can(): + return flask.abort(403, "Insufficient permissions") + return flask.jsonify( + notifications=[ + {"timestamp": notification[0], "message": notification[1]} + for notification in self._notifications + ] + ) - def get_api_commands(self): - return {"clear": []} + def get_api_commands(self): + return {"clear": []} - def on_api_command(self, command, data): - if command == "clear": - if not Permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_CLEAR.can(): - return flask.abort(403, "Insufficient permissions") - self._clear_notifications() + def on_api_command(self, command, data): + if command == "clear": + if not Permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_CLEAR.can(): + return flask.abort(403, "Insufficient permissions") + self._clear_notifications() - #~ TemplatePlugin + # ~ TemplatePlugin - def get_template_configs(self): - return [ - {"type": "settings", - "name": gettext("Printer Notifications"), - "custom_bindings": False}, - {"type": "sidebar", - "name": gettext("Printer Notifications"), - "icon": "bell-o", - "styles_wrapper": ["display: none"], - "data_bind": "visible: loginState.hasPermissionKo(access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW)" - " && settings.settings.plugins.action_command_notification.enable()"} - ] + def get_template_configs(self): + return [ + { + "type": "settings", + "name": gettext("Printer Notifications"), + "custom_bindings": False, + }, + { + "type": "sidebar", + "name": gettext("Printer Notifications"), + "icon": "bell-o", + "styles_wrapper": ["display: none"], + "data_bind": "visible: loginState.hasPermissionKo(access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW)" + " && settings.settings.plugins.action_command_notification.enable()", + }, + ] - #~ action command handler + # ~ action command handler - def action_command_handler(self, comm, line, action, *args, **kwargs): - if not self._settings.get_boolean(["enable"]): - return + def action_command_handler(self, comm, line, action, *args, **kwargs): + if not self._settings.get_boolean(["enable"]): + return - parts = action.split(None, 1) - if len(parts) == 1: - action = parts[0] - parameter = "" - else: - action, parameter = parts + parts = action.split(None, 1) + if len(parts) == 1: + action = parts[0] + parameter = "" + else: + action, parameter = parts - if action != "notification": - return + if action != "notification": + return - message = parameter.strip() - self._notifications.append((time.time(), message)) - self._plugin_manager.send_plugin_message(self._identifier, {"message": message}) + message = parameter.strip() + self._notifications.append((time.time(), message)) + self._plugin_manager.send_plugin_message(self._identifier, {"message": message}) - self._logger.info("Got a notification: {}".format(message)) + self._logger.info("Got a notification: {}".format(message)) + + def _clear_notifications(self): + self._notifications = [] + self._plugin_manager.send_plugin_message(self._identifier, {}) + self._logger.info("Notifications cleared") - def _clear_notifications(self): - self._notifications = [] - self._plugin_manager.send_plugin_message(self._identifier, {}) - self._logger.info("Notifications cleared") __plugin_name__ = "Action Command Notification Support" -__plugin_description__ = "Allows your printer to trigger notifications via action commands on the connection" +__plugin_description__ = ( + "Allows your printer to trigger notifications via action commands on the connection" +) __plugin_author__ = "Gina Häußge" -__plugin_disabling_discouraged__ = gettext("Without this plugin your printer will no longer be able to trigger" - " notifications in OctoPrint") +__plugin_disabling_discouraged__ = gettext( + "Without this plugin your printer will no longer be able to trigger" + " notifications in OctoPrint" +) __plugin_license__ = "AGPLv3" __plugin_pythoncompat__ = ">=2.7,<4" __plugin_implementation__ = ActionCommandNotificationPlugin() __plugin_hooks__ = { - "octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler, - "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions + "octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler, + "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions, } diff --git a/src/octoprint/plugins/action_command_prompt/__init__.py b/src/octoprint/plugins/action_command_prompt/__init__.py index 64f1f8afb..84a94e7b6 100644 --- a/src/octoprint/plugins/action_command_prompt/__init__.py +++ b/src/octoprint/plugins/action_command_prompt/__init__.py @@ -1,7 +1,7 @@ # -*- 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" import octoprint.plugin @@ -14,232 +14,294 @@ from octoprint.events import Events import flask from flask_babel import gettext + class Prompt(object): + def __init__(self, text): + self.text = text + self.choices = [] - def __init__(self, text): - self.text = text - self.choices = [] + self._active = False - self._active = False + @property + def active(self): + return self._active - @property - def active(self): - return self._active + def add_choice(self, text): + self.choices.append(text) - def add_choice(self, text): - self.choices.append(text) + def activate(self): + self._active = True - def activate(self): - self._active = True - - def validate_choice(self, choice): - return 0 <= choice < len(self.choices) + def validate_choice(self, choice): + return 0 <= choice < len(self.choices) -class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, - octoprint.plugin.EventHandlerPlugin, - octoprint.plugin.SettingsPlugin, - octoprint.plugin.SimpleApiPlugin, - octoprint.plugin.TemplatePlugin): +class ActionCommandPromptPlugin( + octoprint.plugin.AssetPlugin, + octoprint.plugin.EventHandlerPlugin, + octoprint.plugin.SettingsPlugin, + octoprint.plugin.SimpleApiPlugin, + octoprint.plugin.TemplatePlugin, +): - COMMAND = "M876" - CAP_PROMPT_SUPPORT = "PROMPT_SUPPORT" + COMMAND = "M876" + CAP_PROMPT_SUPPORT = "PROMPT_SUPPORT" - # noinspection PyMissingConstructor - def __init__(self): - self._prompt = None - self._enable = "detected" - self._command = None - self._enable_emergency_sending = True - self._enable_signal_support = True - self._cap_prompt_support = False + # noinspection PyMissingConstructor + def __init__(self): + self._prompt = None + self._enable = "detected" + self._command = None + self._enable_emergency_sending = True + self._enable_signal_support = True + self._cap_prompt_support = False - def initialize(self): - self._enable = self._settings.get(["enable"]) - self._command = self._settings.get(["command"]) - self._enable_emergency_sending = self._settings.get_boolean(["enable_emergency_sending"]) - self._enable_signal_support = self._settings.get_boolean(["enable_signal_support"]) + def initialize(self): + self._enable = self._settings.get(["enable"]) + self._command = self._settings.get(["command"]) + self._enable_emergency_sending = self._settings.get_boolean( + ["enable_emergency_sending"] + ) + self._enable_signal_support = self._settings.get_boolean( + ["enable_signal_support"] + ) - # Additional permissions hook + # Additional permissions hook - def get_additional_permissions(self): - return [ - {"key": "INTERACT", - "name": "Interact with printer prompts", - "description": gettext("Allows to see and interact with printer prompts"), - "default_groups": [USER_GROUP], - "roles": ["interact"]} - ] + def get_additional_permissions(self): + return [ + { + "key": "INTERACT", + "name": "Interact with printer prompts", + "description": gettext("Allows to see and interact with printer prompts"), + "default_groups": [USER_GROUP], + "roles": ["interact"], + } + ] - #~ AssetPlugin + # ~ AssetPlugin - def get_assets(self): - return {"js": ["js/action_command_prompt.js"], - "clientjs": ["clientjs/action_command_prompt.js"]} + def get_assets(self): + return { + "js": ["js/action_command_prompt.js"], + "clientjs": ["clientjs/action_command_prompt.js"], + } - #~ EventHandlerPlugin + # ~ EventHandlerPlugin - def on_event(self, event, payload): - if event == Events.CONNECTED and self._enable == "always" and self._enable_signal_support: - self._printer.commands(["{command} P1".format(command=self._command)]) - elif event == Events.DISCONNECTED: - self._close_prompt() + def on_event(self, event, payload): + if ( + event == Events.CONNECTED + and self._enable == "always" + and self._enable_signal_support + ): + self._printer.commands(["{command} P1".format(command=self._command)]) + elif event == Events.DISCONNECTED: + self._close_prompt() - #~ SettingsPlugin + # ~ SettingsPlugin - def get_settings_defaults(self): - return {"enable": "detected", - "command": self.COMMAND, - "enable_emergency_sending": True, - "enable_signal_support": True} + def get_settings_defaults(self): + return { + "enable": "detected", + "command": self.COMMAND, + "enable_emergency_sending": True, + "enable_signal_support": True, + } - def on_settings_save(self, data): - octoprint.plugin.SettingsPlugin.on_settings_save(self, data) - self._enable = self._settings.get(["enable"]) - self._command = self._settings.get(["command"]) - self._enable_emergency_sending = self._settings.get_boolean(["enable_emergency_sending"]) - self._enable_signal_support = self._settings.get_boolean(["enable_signal_support"]) + def on_settings_save(self, data): + octoprint.plugin.SettingsPlugin.on_settings_save(self, data) + self._enable = self._settings.get(["enable"]) + self._command = self._settings.get(["command"]) + self._enable_emergency_sending = self._settings.get_boolean( + ["enable_emergency_sending"] + ) + self._enable_signal_support = self._settings.get_boolean( + ["enable_signal_support"] + ) - #~ SimpleApiPlugin + # ~ SimpleApiPlugin - def get_api_commands(self): - return {"select": ["choice"]} + def get_api_commands(self): + return {"select": ["choice"]} - def on_api_command(self, command, data): - if command == "select": - if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can(): - return flask.abort(403, "Insufficient permissions") + def on_api_command(self, command, data): + if command == "select": + if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can(): + return flask.abort(403, "Insufficient permissions") - if self._prompt is None: - return flask.abort(409, "No active prompt") + if self._prompt is None: + return flask.abort(409, "No active prompt") - choice = data["choice"] - if not isinstance(choice, int) or not self._prompt.validate_choice(choice): - return flask.abort(400, "{!r} is not a valid value for choice".format(choice)) + choice = data["choice"] + if not isinstance(choice, int) or not self._prompt.validate_choice(choice): + return flask.abort( + 400, "{!r} is not a valid value for choice".format(choice) + ) - self._answer_prompt(choice) + self._answer_prompt(choice) - def on_api_get(self, request): - if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can(): - return flask.abort(403, "Insufficient permissions") - if self._prompt is None: - return flask.jsonify() - else: - return flask.jsonify(text=self._prompt.text, choices=self._prompt.choices) + def on_api_get(self, request): + if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can(): + return flask.abort(403, "Insufficient permissions") + if self._prompt is None: + return flask.jsonify() + else: + return flask.jsonify(text=self._prompt.text, choices=self._prompt.choices) - #~ TemplatePlugin + # ~ TemplatePlugin - def get_template_configs(self): - return [{"type": "settings", "name": gettext("Printer Dialogs"), "custom_bindings": False}] + def get_template_configs(self): + return [ + { + "type": "settings", + "name": gettext("Printer Dialogs"), + "custom_bindings": False, + } + ] - #~ action command handler + # ~ action command handler - def action_command_handler(self, comm, line, action, *args, **kwargs): - if not action.startswith("prompt_"): - return + def action_command_handler(self, comm, line, action, *args, **kwargs): + if not action.startswith("prompt_"): + return - parts = action.split(None, 1) - if len(parts) == 1: - action = parts[0] - parameter = "" - else: - action, parameter = parts + parts = action.split(None, 1) + if len(parts) == 1: + action = parts[0] + parameter = "" + else: + action, parameter = parts - if action == "prompt_begin": - if self._prompt is not None and self._prompt.active: - self._logger.warning("Prompt is already defined") - return - self._prompt = Prompt(parameter.strip()) + if action == "prompt_begin": + if self._prompt is not None and self._prompt.active: + self._logger.warning("Prompt is already defined") + return + self._prompt = Prompt(parameter.strip()) - elif action == "prompt_choice" or action == "prompt_button": - if self._prompt is None: - return - if self._prompt.active: - self._logger.warning("Prompt is already active") - return - self._prompt.add_choice(parameter.strip()) + elif action == "prompt_choice" or action == "prompt_button": + if self._prompt is None: + return + if self._prompt.active: + self._logger.warning("Prompt is already active") + return + self._prompt.add_choice(parameter.strip()) - elif action == "prompt_show": - if self._prompt is None: - return - if self._prompt.active: - self._logger.warning("Prompt is already active") - return - self._show_prompt() + elif action == "prompt_show": + if self._prompt is None: + return + if self._prompt.active: + self._logger.warning("Prompt is already active") + return + self._show_prompt() - elif action == "prompt_end": - if self._prompt is None: - return - self._close_prompt() - self._prompt = None + elif action == "prompt_end": + if self._prompt is None: + return + self._close_prompt() + self._prompt = None - #~ queuing handling + # ~ queuing handling - def gcode_queuing_handler(self, comm_instance, phase, cmd, cmd_type, gcode, subcode=None, tags=None, *args, **kwargs): - if gcode != self._command: - return + def gcode_queuing_handler( + self, + comm_instance, + phase, + cmd, + cmd_type, + gcode, + subcode=None, + tags=None, + *args, + **kwargs + ): + if gcode != self._command: + return - if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support) or not self._enable_emergency_sending: - return + if ( + self._enable == "never" + or (self._enable == "detected" and not self._cap_prompt_support) + or not self._enable_emergency_sending + ): + return - if not "S" in cmd: - # we only force-send M876 Sx - return + if not "S" in cmd: + # we only force-send M876 Sx + return - # noinspection PyProtectedMember - return comm_instance._emergency_force_send(cmd, "Force-sending {} to the printer".format(self._command), gcode=gcode) + # noinspection PyProtectedMember + return comm_instance._emergency_force_send( + cmd, "Force-sending {} to the printer".format(self._command), gcode=gcode + ) - #~ capability reporting + # ~ capability reporting - def firmware_capability_handler(self, comm_instance, capability, enabled, already_defined, *args, **kwargs): - if capability == self.CAP_PROMPT_SUPPORT and enabled: - self._cap_prompt_support = True - if self._enable == "detected" and self._enable_signal_support: - self._printer.commands(["{command} P1".format(command=self._command)]) + def firmware_capability_handler( + self, comm_instance, capability, enabled, already_defined, *args, **kwargs + ): + if capability == self.CAP_PROMPT_SUPPORT and enabled: + self._cap_prompt_support = True + if self._enable == "detected" and self._enable_signal_support: + self._printer.commands(["{command} P1".format(command=self._command)]) - #~ prompt handling + # ~ prompt handling - def _show_prompt(self): - if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support): - return + def _show_prompt(self): + if self._enable == "never" or ( + self._enable == "detected" and not self._cap_prompt_support + ): + return - self._prompt.activate() - self._plugin_manager.send_plugin_message(self._identifier, {"action": "show", - "text": self._prompt.text, - "choices": self._prompt.choices}) + self._prompt.activate() + self._plugin_manager.send_plugin_message( + self._identifier, + { + "action": "show", + "text": self._prompt.text, + "choices": self._prompt.choices, + }, + ) - def _close_prompt(self): - if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support): - return + def _close_prompt(self): + if self._enable == "never" or ( + self._enable == "detected" and not self._cap_prompt_support + ): + return - self._prompt = None - self._plugin_manager.send_plugin_message(self._identifier, {"action": "close"}) + self._prompt = None + self._plugin_manager.send_plugin_message(self._identifier, {"action": "close"}) - def _answer_prompt(self, choice): - if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support): - return + def _answer_prompt(self, choice): + if self._enable == "never" or ( + self._enable == "detected" and not self._cap_prompt_support + ): + return - self._close_prompt() - if "{choice}" in self._command: - self._printer.commands([self._command.format(choice=choice)], - force=True) - else: - self._printer.commands(["{command} S{choice}".format(command=self._command, - choice=choice)], - force=True) + self._close_prompt() + if "{choice}" in self._command: + self._printer.commands([self._command.format(choice=choice)], force=True) + else: + self._printer.commands( + ["{command} S{choice}".format(command=self._command, choice=choice)], + force=True, + ) __plugin_name__ = "Action Command Prompt Support" -__plugin_description__ = "Allows your printer to trigger prompts via action commands on the connection" +__plugin_description__ = ( + "Allows your printer to trigger prompts via action commands on the connection" +) __plugin_author__ = "Gina Häußge" -__plugin_disabling_discouraged__ = gettext("Without this plugin your printer will no longer be able to trigger" - " confirmation or selection prompts in OctoPrint") +__plugin_disabling_discouraged__ = gettext( + "Without this plugin your printer will no longer be able to trigger" + " confirmation or selection prompts in OctoPrint" +) __plugin_license__ = "AGPLv3" __plugin_pythoncompat__ = ">=2.7,<4" __plugin_implementation__ = ActionCommandPromptPlugin() __plugin_hooks__ = { - "octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler, - "octoprint.comm.protocol.gcode.queuing": __plugin_implementation__.gcode_queuing_handler, - "octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.firmware_capability_handler, - "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions + "octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler, + "octoprint.comm.protocol.gcode.queuing": __plugin_implementation__.gcode_queuing_handler, + "octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.firmware_capability_handler, + "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions, } diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py index 74f4e115e..edd2653dc 100644 --- a/src/octoprint/plugins/announcements/__init__.py +++ b/src/octoprint/plugins/announcements/__init__.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -15,6 +15,7 @@ import re import time import threading import sys + PY2 = sys.version_info[0] < 3 import feedparser @@ -24,525 +25,621 @@ from collections import OrderedDict from octoprint.access import ADMIN_GROUP from octoprint.access.permissions import Permissions -from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking, check_etag +from octoprint.server.util.flask import ( + no_firstrun_access, + with_revalidation_checking, + check_etag, +) from octoprint.util import utmify, count, monotonic_time from flask_babel import gettext from octoprint import __version__ as OCTOPRINT_VERSION -class AnnouncementPlugin(octoprint.plugin.AssetPlugin, - octoprint.plugin.SettingsPlugin, - octoprint.plugin.BlueprintPlugin, - octoprint.plugin.StartupPlugin, - octoprint.plugin.TemplatePlugin, - octoprint.plugin.EventHandlerPlugin): - - # noinspection PyMissingConstructor - def __init__(self): - self._cached_channel_configs = None - self._cached_channel_configs_mutex = threading.RLock() - - from octoprint.vendor.awesome_slugify import Slugify - self._slugify = Slugify() - self._slugify.safe_chars = "-_." - - # Additional permissions hook - - def get_additional_permissions(self): - return [ - {"key": "READ", - "name": "Read announcements", - "description": gettext("Allows to read announcements"), - "default_groups": [ADMIN_GROUP], - "roles": ["read"]}, - {"key": "MANAGE", - "name": "Manage announcement subscriptions", - "description": gettext("Allows to manage announcement subscriptions. Includes \"Read announcements\" " - "permission"), - "default_groups": [ADMIN_GROUP], - "roles": ["manage"], - "permissions": ["PLUGIN_ANNOUNCEMENTS_READ"]} - ] - - # StartupPlugin - - def on_after_startup(self): - # decouple channel fetching from server startup - def fetch_data(): - self._fetch_all_channels() - - thread = threading.Thread(target=fetch_data) - thread.daemon = True - thread.start() - - # SettingsPlugin - - def get_settings_defaults(self): - settings = {"channels": {"_important": {"name": "Important Announcements", - "description": "Important announcements about OctoPrint.", - "priority": 1, - "type": "rss", - "url": "https://octoprint.org/feeds/important.xml"}, - "_releases": {"name": "Release Announcements", - "description": "Announcements of new releases and release candidates of OctoPrint.", - "priority": 2, - "type": "rss", - "url": "https://octoprint.org/feeds/releases.xml"}, - "_blog": {"name": "On the OctoBlog", - "description": "Development news, community spotlights, OctoPrint On Air episodes and more from the official OctoBlog.", - "priority": 2, - "type": "rss", - "url": "https://octoprint.org/feeds/octoblog.xml"}, - "_plugins": {"name": "New Plugins in the Repository", - "description": "Announcements of new plugins released on the official Plugin Repository.", - "priority": 2, - "type": "rss", - "url": "https://plugins.octoprint.org/feed.xml"}, - "_octopi": {"name": "OctoPi News", - "description": "News around OctoPi, the Raspberry Pi image including OctoPrint.", - "priority": 2, - "type": "rss", - "url": "https://octoprint.org/feeds/octopi.xml"}}, - "enabled_channels": [], - "forced_channels": ["_important"], - "channel_order": ["_important", "_releases", "_blog", "_plugins", "_octopi"], - "ttl": 6*60, - "display_limit": 3, - "summary_limit": 300} - settings["enabled_channels"] = list(settings["channels"].keys()) - return settings - - def get_settings_version(self): - return 1 - - def on_settings_migrate(self, target, current): - if current is None: - # first version had different default feeds and only _important enabled by default - channels = self._settings.get(["channels"]) - if "_news" in channels: - del channels["_news"] - if "_spotlight" in channels: - del channels["_spotlight"] - self._settings.set(["channels"], channels) - - enabled = self._settings.get(["enabled_channels"]) - add_blog = False - if "_news" in enabled: - add_blog = True - enabled.remove("_news") - if "_spotlight" in enabled: - add_blog = True - enabled.remove("_spotlight") - if add_blog and not "_blog" in enabled: - enabled.append("_blog") - self._settings.set(["enabled_channels"], enabled) - - # AssetPlugin - - def get_assets(self): - return {"js": ["js/announcements.js"], - "less": ["less/announcements.less"], - "css": ["css/announcements.css"]} - - # Template Plugin - - def get_template_configs(self): - return [{"type": "settings", - "name": gettext("Announcements"), - "template": "announcements_settings.jinja2", - "custom_bindings": True}, - {"type": "navbar", - "template": "announcements_navbar.jinja2", - "styles": ["display: none"], - "data_bind": "visible: loginState.hasPermission(access.permissions.PLUGIN_ANNOUNCEMENTS_READ)"}] - - # Blueprint Plugin - - @octoprint.plugin.BlueprintPlugin.route("/channels", methods=["GET"]) - @no_firstrun_access - @Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403) - def get_channel_data(self): - from octoprint.settings import valid_boolean_trues - - result = [] - - force = flask.request.values.get("force", "false") in valid_boolean_trues - - enabled = self._settings.get(["enabled_channels"]) - forced = self._settings.get(["forced_channels"]) - - channel_configs = self._get_channel_configs(force=force) - - def view(): - channel_data = self._fetch_all_channels(force=force) - - for key, data in channel_configs.items(): - read_until = channel_configs[key].get("read_until", None) - entries = sorted(self._to_internal_feed(channel_data.get(key, []), read_until=read_until), key=lambda e: e["published"], reverse=True) - unread = count(filter(lambda e: not e["read"], entries)) - - if read_until is None and entries: - last = entries[0]["published"] - self._mark_read_until(key, last) - - result.append({"key": key, - "channel": data["name"], - "url": data["url"], - "description": data.get("description", ""), - "priority": data.get("priority", 2), - "enabled": key in enabled or key in forced, - "forced": key in forced, - "data": entries, - "unread": unread}) - - return flask.jsonify(channels=result) - - def etag(): - import hashlib - hash = hashlib.sha1() - def hash_update(value): - hash.update(value.encode("utf-8")) - hash_update(repr(sorted(enabled))) - hash_update(repr(sorted(forced))) - hash_update(OCTOPRINT_VERSION) - - for channel in sorted(channel_configs.keys()): - hash_update(repr(channel_configs[channel])) - channel_data = self._get_channel_data_from_cache(channel, channel_configs[channel]) - hash_update(repr(channel_data)) - - return hash.hexdigest() - - # noinspection PyShadowingNames - def condition(lm, etag): - return check_etag(etag) - - return with_revalidation_checking(etag_factory=lambda *args, **kwargs: etag(), - condition=lambda lm, etag: condition(lm, etag), - unless=lambda: force)(view)() - - @octoprint.plugin.BlueprintPlugin.route("/channels/", methods=["POST"]) - @no_firstrun_access - @Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403) - def channel_command(self, channel): - from octoprint.server.util.flask import get_json_command_from_request - from octoprint.server import NO_CONTENT - - valid_commands = {"read": ["until"], - "toggle": []} - - command, data, response = get_json_command_from_request(flask.request, valid_commands=valid_commands) - if response is not None: - return response - - if command == "read": - until = data["until"] - self._mark_read_until(channel, until) +class AnnouncementPlugin( + octoprint.plugin.AssetPlugin, + octoprint.plugin.SettingsPlugin, + octoprint.plugin.BlueprintPlugin, + octoprint.plugin.StartupPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.EventHandlerPlugin, +): + + # noinspection PyMissingConstructor + def __init__(self): + self._cached_channel_configs = None + self._cached_channel_configs_mutex = threading.RLock() + + from octoprint.vendor.awesome_slugify import Slugify + + self._slugify = Slugify() + self._slugify.safe_chars = "-_." + + # Additional permissions hook + + def get_additional_permissions(self): + return [ + { + "key": "READ", + "name": "Read announcements", + "description": gettext("Allows to read announcements"), + "default_groups": [ADMIN_GROUP], + "roles": ["read"], + }, + { + "key": "MANAGE", + "name": "Manage announcement subscriptions", + "description": gettext( + 'Allows to manage announcement subscriptions. Includes "Read announcements" ' + "permission" + ), + "default_groups": [ADMIN_GROUP], + "roles": ["manage"], + "permissions": ["PLUGIN_ANNOUNCEMENTS_READ"], + }, + ] + + # StartupPlugin + + def on_after_startup(self): + # decouple channel fetching from server startup + def fetch_data(): + self._fetch_all_channels() + + thread = threading.Thread(target=fetch_data) + thread.daemon = True + thread.start() + + # SettingsPlugin + + def get_settings_defaults(self): + settings = { + "channels": { + "_important": { + "name": "Important Announcements", + "description": "Important announcements about OctoPrint.", + "priority": 1, + "type": "rss", + "url": "https://octoprint.org/feeds/important.xml", + }, + "_releases": { + "name": "Release Announcements", + "description": "Announcements of new releases and release candidates of OctoPrint.", + "priority": 2, + "type": "rss", + "url": "https://octoprint.org/feeds/releases.xml", + }, + "_blog": { + "name": "On the OctoBlog", + "description": "Development news, community spotlights, OctoPrint On Air episodes and more from the official OctoBlog.", + "priority": 2, + "type": "rss", + "url": "https://octoprint.org/feeds/octoblog.xml", + }, + "_plugins": { + "name": "New Plugins in the Repository", + "description": "Announcements of new plugins released on the official Plugin Repository.", + "priority": 2, + "type": "rss", + "url": "https://plugins.octoprint.org/feed.xml", + }, + "_octopi": { + "name": "OctoPi News", + "description": "News around OctoPi, the Raspberry Pi image including OctoPrint.", + "priority": 2, + "type": "rss", + "url": "https://octoprint.org/feeds/octopi.xml", + }, + }, + "enabled_channels": [], + "forced_channels": ["_important"], + "channel_order": ["_important", "_releases", "_blog", "_plugins", "_octopi"], + "ttl": 6 * 60, + "display_limit": 3, + "summary_limit": 300, + } + settings["enabled_channels"] = list(settings["channels"].keys()) + return settings + + def get_settings_version(self): + return 1 + + def on_settings_migrate(self, target, current): + if current is None: + # first version had different default feeds and only _important enabled by default + channels = self._settings.get(["channels"]) + if "_news" in channels: + del channels["_news"] + if "_spotlight" in channels: + del channels["_spotlight"] + self._settings.set(["channels"], channels) + + enabled = self._settings.get(["enabled_channels"]) + add_blog = False + if "_news" in enabled: + add_blog = True + enabled.remove("_news") + if "_spotlight" in enabled: + add_blog = True + enabled.remove("_spotlight") + if add_blog and not "_blog" in enabled: + enabled.append("_blog") + self._settings.set(["enabled_channels"], enabled) + + # AssetPlugin + + def get_assets(self): + return { + "js": ["js/announcements.js"], + "less": ["less/announcements.less"], + "css": ["css/announcements.css"], + } + + # Template Plugin + + def get_template_configs(self): + return [ + { + "type": "settings", + "name": gettext("Announcements"), + "template": "announcements_settings.jinja2", + "custom_bindings": True, + }, + { + "type": "navbar", + "template": "announcements_navbar.jinja2", + "styles": ["display: none"], + "data_bind": "visible: loginState.hasPermission(access.permissions.PLUGIN_ANNOUNCEMENTS_READ)", + }, + ] + + # Blueprint Plugin + + @octoprint.plugin.BlueprintPlugin.route("/channels", methods=["GET"]) + @no_firstrun_access + @Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403) + def get_channel_data(self): + from octoprint.settings import valid_boolean_trues + + result = [] + + force = flask.request.values.get("force", "false") in valid_boolean_trues + + enabled = self._settings.get(["enabled_channels"]) + forced = self._settings.get(["forced_channels"]) + + channel_configs = self._get_channel_configs(force=force) + + def view(): + channel_data = self._fetch_all_channels(force=force) + + for key, data in channel_configs.items(): + read_until = channel_configs[key].get("read_until", None) + entries = sorted( + self._to_internal_feed( + channel_data.get(key, []), read_until=read_until + ), + key=lambda e: e["published"], + reverse=True, + ) + unread = count(filter(lambda e: not e["read"], entries)) + + if read_until is None and entries: + last = entries[0]["published"] + self._mark_read_until(key, last) + + result.append( + { + "key": key, + "channel": data["name"], + "url": data["url"], + "description": data.get("description", ""), + "priority": data.get("priority", 2), + "enabled": key in enabled or key in forced, + "forced": key in forced, + "data": entries, + "unread": unread, + } + ) + + return flask.jsonify(channels=result) + + def etag(): + import hashlib + + hash = hashlib.sha1() + + def hash_update(value): + hash.update(value.encode("utf-8")) + + hash_update(repr(sorted(enabled))) + hash_update(repr(sorted(forced))) + hash_update(OCTOPRINT_VERSION) + + for channel in sorted(channel_configs.keys()): + hash_update(repr(channel_configs[channel])) + channel_data = self._get_channel_data_from_cache( + channel, channel_configs[channel] + ) + hash_update(repr(channel_data)) + + return hash.hexdigest() + + # noinspection PyShadowingNames + def condition(lm, etag): + return check_etag(etag) + + return with_revalidation_checking( + etag_factory=lambda *args, **kwargs: etag(), + condition=lambda lm, etag: condition(lm, etag), + unless=lambda: force, + )(view)() + + @octoprint.plugin.BlueprintPlugin.route("/channels/", methods=["POST"]) + @no_firstrun_access + @Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403) + def channel_command(self, channel): + from octoprint.server.util.flask import get_json_command_from_request + from octoprint.server import NO_CONTENT + + valid_commands = {"read": ["until"], "toggle": []} + + command, data, response = get_json_command_from_request( + flask.request, valid_commands=valid_commands + ) + if response is not None: + return response + + if command == "read": + until = data["until"] + self._mark_read_until(channel, until) + + elif command == "toggle": + if not Permissions.PLUGIN_ANNOUNCEMENTS_MANAGE.can(): + return flask.make_response("Insufficient rights", 403) + self._toggle(channel) + + return NO_CONTENT + + def is_blueprint_protected(self): + return False + + ##~~ EventHandlerPlugin + + def on_event(self, event, payload): + from octoprint.events import Events + + if ( + event != Events.CONNECTIVITY_CHANGED + or not payload + or not payload.get("new", False) + ): + return + self._fetch_all_channels_async() + + # Internal Tools + + def _mark_read_until(self, channel, until): + """Set read_until timestamp of a channel.""" + + current_read_until = None + channel_data = self._settings.get(["channels", channel], merged=True) + if channel_data: + current_read_until = channel_data.get("read_until", None) + + defaults = {"plugins": {"announcements": {"channels": {}}}} + defaults["plugins"]["announcements"]["channels"][channel] = { + "read_until": current_read_until + } + + with self._cached_channel_configs_mutex: + self._settings.set( + ["channels", channel, "read_until"], until, defaults=defaults + ) + self._settings.save() + self._cached_channel_configs = None + + def _toggle(self, channel): + """Toggle enable/disabled state of a channel.""" + + enabled_channels = list(self._settings.get(["enabled_channels"])) + + if channel in enabled_channels: + enabled_channels.remove(channel) + else: + enabled_channels.append(channel) + + self._settings.set(["enabled_channels"], enabled_channels) + self._settings.save() + + def _get_channel_configs(self, force=False): + """Retrieve all channel configs with sanitized keys.""" + + with self._cached_channel_configs_mutex: + if self._cached_channel_configs is None or force: + configs = self._settings.get(["channels"], merged=True) + order = self._settings.get(["channel_order"]) + all_keys = order + [ + key for key in sorted(configs.keys()) if not key in order + ] + + result = OrderedDict() + for key in all_keys: + config = configs.get(key) + if config is None or "url" not in config or "name" not in config: + # strip invalid entries + continue + result[self._slugify(key)] = config + self._cached_channel_configs = result + return self._cached_channel_configs + + def _get_channel_config(self, key, force=False): + """Retrieve specific channel config for channel.""" + + safe_key = self._slugify(key) + return self._get_channel_configs(force=force).get(safe_key) + + def _fetch_all_channels_async(self, force=False): + thread = threading.Thread( + target=self._fetch_all_channels, kwargs={"force": force} + ) + thread.daemon = True + thread.start() + + def _fetch_all_channels(self, force=False): + """Fetch all channel feeds from cache or network.""" + + channels = self._get_channel_configs(force=force) + enabled = self._settings.get(["enabled_channels"]) + forced = self._settings.get(["forced_channels"]) + + all_channels = {} + for key, config in channels.items(): + if not key in enabled and not key in forced: + continue + + if not "url" in config: + continue + + data = self._get_channel_data(key, config, force=force) + if data is not None: + all_channels[key] = data + + return all_channels + + def _get_channel_data(self, key, config, force=False): + """Fetch individual channel feed from cache/network.""" + + data = None + + if not force: + # we may use the cache, see if we have something in there + data = self._get_channel_data_from_cache(key, config) + + if data is None: + # cache not allowed or empty, fetch from network + if self._connectivity_checker.online: + data = self._get_channel_data_from_network(key, config) + else: + self._logger.info( + "Looks like we are offline, can't fetch announcements for channel {} from network".format( + key + ) + ) + + return data + + def _get_channel_data_from_cache(self, key, config): + """Fetch channel feed from cache.""" + + channel_path = self._get_channel_cache_path(key) + + if os.path.exists(channel_path): + if "ttl" in config and isinstance(config["ttl"], int): + ttl = config["ttl"] + else: + ttl = self._settings.get_int(["ttl"]) + + ttl *= 60 + now = time.time() + if os.stat(channel_path).st_mtime + ttl > now: + d = feedparser.parse(channel_path) + self._logger.debug( + "Loaded channel {} from cache at {}".format(key, channel_path) + ) + return d + + return None + + def _get_channel_data_from_network(self, key, config): + """Fetch channel feed from network.""" + + import requests + + url = config["url"] + try: + start = monotonic_time() + r = requests.get(url, timeout=30) + r.raise_for_status() + self._logger.info( + "Loaded channel {} from {} in {:.2}s".format( + key, config["url"], monotonic_time() - start + ) + ) + except Exception: + self._logger.exception( + "Could not fetch channel {} from {}".format(key, config["url"]) + ) + return None + + response = r.text + channel_path = self._get_channel_cache_path(key) + with io.open(channel_path, mode="wt", encoding="utf-8") as f: + f.write(response) + return feedparser.parse(response) + + def _to_internal_feed(self, feed, read_until=None): + """Convert feed to internal data structure.""" + + result = [] + if "entries" in feed: + for entry in feed["entries"]: + try: + internal_entry = self._to_internal_entry(entry, read_until=read_until) + if internal_entry: + result.append(internal_entry) + except Exception: + self._logger.exception( + "Error while converting entry from feed, skipping it" + ) + return result + + def _to_internal_entry(self, entry, read_until=None): + """Convert feed entries to internal data structure.""" + + timestamp = entry.get("published_parsed", None) + if timestamp is None: + timestamp = entry.get("updated_parsed", None) + if timestamp is None: + return None + + published = calendar.timegm(timestamp) + + read = True + if read_until is not None: + read = published <= read_until + + return { + "title": entry["title"], + "title_without_tags": _strip_tags(entry["title"]), + "summary": _lazy_images(entry["summary"]), + "summary_without_images": _strip_images(entry["summary"]), + "published": published, + "link": utmify( + entry["link"], + source="octoprint", + medium="announcements", + content=OCTOPRINT_VERSION, + ), + "read": read, + } + + def _get_channel_cache_path(self, key): + """Retrieve cache path for channel key.""" + + safe_key = self._slugify(key) + return os.path.join(self.get_plugin_data_folder(), "{}.cache".format(safe_key)) + + +_image_tag_re = re.compile(r"") - elif command == "toggle": - if not Permissions.PLUGIN_ANNOUNCEMENTS_MANAGE.can(): - return flask.make_response("Insufficient rights", 403) - self._toggle(channel) - return NO_CONTENT - - def is_blueprint_protected(self): - return False - - ##~~ EventHandlerPlugin - - def on_event(self, event, payload): - from octoprint.events import Events - if event != Events.CONNECTIVITY_CHANGED or not payload or not payload.get("new", False): - return - self._fetch_all_channels_async() - - # Internal Tools - - def _mark_read_until(self, channel, until): - """Set read_until timestamp of a channel.""" - - current_read_until = None - channel_data = self._settings.get(["channels", channel], merged=True) - if channel_data: - current_read_until = channel_data.get("read_until", None) - - defaults = {"plugins": {"announcements": {"channels": {}}}} - defaults["plugins"]["announcements"]["channels"][channel] = {"read_until": current_read_until} - - with self._cached_channel_configs_mutex: - self._settings.set(["channels", channel, "read_until"], until, defaults=defaults) - self._settings.save() - self._cached_channel_configs = None - - def _toggle(self, channel): - """Toggle enable/disabled state of a channel.""" - - enabled_channels = list(self._settings.get(["enabled_channels"])) - - if channel in enabled_channels: - enabled_channels.remove(channel) - else: - enabled_channels.append(channel) - - self._settings.set(["enabled_channels"], enabled_channels) - self._settings.save() - - def _get_channel_configs(self, force=False): - """Retrieve all channel configs with sanitized keys.""" - - with self._cached_channel_configs_mutex: - if self._cached_channel_configs is None or force: - configs = self._settings.get(["channels"], merged=True) - order = self._settings.get(["channel_order"]) - all_keys = order + [key for key in sorted(configs.keys()) if not key in order] - - result = OrderedDict() - for key in all_keys: - config = configs.get(key) - if config is None or "url" not in config or "name" not in config: - # strip invalid entries - continue - result[self._slugify(key)] = config - self._cached_channel_configs = result - return self._cached_channel_configs - - def _get_channel_config(self, key, force=False): - """Retrieve specific channel config for channel.""" - - safe_key = self._slugify(key) - return self._get_channel_configs(force=force).get(safe_key) - - def _fetch_all_channels_async(self, force=False): - thread = threading.Thread(target=self._fetch_all_channels, kwargs={"force": force}) - thread.daemon = True - thread.start() - - def _fetch_all_channels(self, force=False): - """Fetch all channel feeds from cache or network.""" - - channels = self._get_channel_configs(force=force) - enabled = self._settings.get(["enabled_channels"]) - forced = self._settings.get(["forced_channels"]) - - all_channels = {} - for key, config in channels.items(): - if not key in enabled and not key in forced: - continue - - if not "url" in config: - continue - - data = self._get_channel_data(key, config, force=force) - if data is not None: - all_channels[key] = data - - return all_channels - - def _get_channel_data(self, key, config, force=False): - """Fetch individual channel feed from cache/network.""" - - data = None - - if not force: - # we may use the cache, see if we have something in there - data = self._get_channel_data_from_cache(key, config) - - if data is None: - # cache not allowed or empty, fetch from network - if self._connectivity_checker.online: - data = self._get_channel_data_from_network(key, config) - else: - self._logger.info("Looks like we are offline, can't fetch announcements for channel {} from network".format(key)) - - return data - - def _get_channel_data_from_cache(self, key, config): - """Fetch channel feed from cache.""" - - channel_path = self._get_channel_cache_path(key) - - if os.path.exists(channel_path): - if "ttl" in config and isinstance(config["ttl"], int): - ttl = config["ttl"] - else: - ttl = self._settings.get_int(["ttl"]) - - ttl *= 60 - now = time.time() - if os.stat(channel_path).st_mtime + ttl > now: - d = feedparser.parse(channel_path) - self._logger.debug("Loaded channel {} from cache at {}".format(key, channel_path)) - return d - - return None - - def _get_channel_data_from_network(self, key, config): - """Fetch channel feed from network.""" - - import requests - - url = config["url"] - try: - start = monotonic_time() - r = requests.get(url, timeout=30) - r.raise_for_status() - self._logger.info("Loaded channel {} from {} in {:.2}s".format(key, config["url"], monotonic_time() - start)) - except Exception: - self._logger.exception( - "Could not fetch channel {} from {}".format(key, config["url"])) - return None - - response = r.text - channel_path = self._get_channel_cache_path(key) - with io.open(channel_path, mode="wt", encoding="utf-8") as f: - f.write(response) - return feedparser.parse(response) - - def _to_internal_feed(self, feed, read_until=None): - """Convert feed to internal data structure.""" - - result = [] - if "entries" in feed: - for entry in feed["entries"]: - try: - internal_entry = self._to_internal_entry(entry, read_until=read_until) - if internal_entry: - result.append(internal_entry) - except Exception: - self._logger.exception("Error while converting entry from feed, skipping it") - return result - - def _to_internal_entry(self, entry, read_until=None): - """Convert feed entries to internal data structure.""" - - timestamp = entry.get("published_parsed", None) - if timestamp is None: - timestamp = entry.get("updated_parsed", None) - if timestamp is None: - return None - - published = calendar.timegm(timestamp) - - read = True - if read_until is not None: - read = published <= read_until - - return {"title": entry["title"], - "title_without_tags": _strip_tags(entry["title"]), - "summary": _lazy_images(entry["summary"]), - "summary_without_images": _strip_images(entry["summary"]), - "published": published, - "link": utmify(entry["link"], source="octoprint", medium="announcements", content=OCTOPRINT_VERSION), - "read": read} - - def _get_channel_cache_path(self, key): - """Retrieve cache path for channel key.""" - - safe_key = self._slugify(key) - return os.path.join(self.get_plugin_data_folder(), "{}.cache".format(safe_key)) - - -_image_tag_re = re.compile(r'') def _strip_images(text): - """ - >>> _strip_images("I'm a link and this is an image: foo") # doctest: +ALLOW_UNICODE - "I'm a link and this is an image: " - >>> _strip_images("One and two and three and four \\"four\\"") # doctest: +ALLOW_UNICODE - 'One and two and three and four ' - >>> _strip_images("No images here") # doctest: +ALLOW_UNICODE - 'No images here' - """ - return _image_tag_re.sub('', text) + """ + >>> _strip_images("I'm a link and this is an image: foo") # doctest: +ALLOW_UNICODE + "I'm a link and this is an image: " + >>> _strip_images("One and two and three and four \\"four\\"") # doctest: +ALLOW_UNICODE + 'One and two and three and four ' + >>> _strip_images("No images here") # doctest: +ALLOW_UNICODE + 'No images here' + """ + return _image_tag_re.sub("", text) + def _replace_images(text, callback): - """ - >>> callback = lambda img: "foobar" - >>> _replace_images("I'm a link and this is an image: foo", callback) # doctest: +ALLOW_UNICODE - "I'm a link and this is an image: foobar" - >>> _replace_images("One and two and three and four \\"four\\"", callback) # doctest: +ALLOW_UNICODE - 'One foobar and two foobar and three foobar and four foobar' - """ - result = text - for match in _image_tag_re.finditer(text): - tag = match.group(0) - replaced = callback(tag) - result = result.replace(tag, replaced) - return result + """ + >>> callback = lambda img: "foobar" + >>> _replace_images("I'm a link and this is an image: foo", callback) # doctest: +ALLOW_UNICODE + "I'm a link and this is an image: foobar" + >>> _replace_images("One and two and three and four \\"four\\"", callback) # doctest: +ALLOW_UNICODE + 'One foobar and two foobar and three foobar and four foobar' + """ + result = text + for match in _image_tag_re.finditer(text): + tag = match.group(0) + replaced = callback(tag) + result = result.replace(tag, replaced) + return result + _image_src_re = re.compile(r'src=(?P[\'"]*)(?P.*?)(?P=quote)(?=\s+|>)') + + def _lazy_images(text, placeholder=None): - """ - >>> _lazy_images("I'm a link and this is an image: foo") # doctest: +ALLOW_UNICODE - 'I\\'m a link and this is an image: \\'foo\\'' - >>> _lazy_images("I'm a link and this is an image: foo", placeholder="ph.png") # doctest: +ALLOW_UNICODE - 'I\\'m a link and this is an image: \\'foo\\'' - >>> _lazy_images("One and two and three and four \\"four\\"", placeholder="ph.png") # doctest: +ALLOW_UNICODE - 'One and two and three and four four' - >>> _lazy_images("No images here") # doctest: +ALLOW_UNICODE - 'No images here' - """ - if placeholder is None: - # 1px transparent gif - placeholder = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" + """ + >>> _lazy_images("I'm a link and this is an image: foo") # doctest: +ALLOW_UNICODE + 'I\\'m a link and this is an image: \\'foo\\'' + >>> _lazy_images("I'm a link and this is an image: foo", placeholder="ph.png") # doctest: +ALLOW_UNICODE + 'I\\'m a link and this is an image: \\'foo\\'' + >>> _lazy_images("One and two and three and four \\"four\\"", placeholder="ph.png") # doctest: +ALLOW_UNICODE + 'One and two and three and four four' + >>> _lazy_images("No images here") # doctest: +ALLOW_UNICODE + 'No images here' + """ + if placeholder is None: + # 1px transparent gif + placeholder = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" - def callback(img_tag): - match = _image_src_re.search(img_tag) - if match is not None: - src = match.group("src") - quote = match.group("quote") - quoted_src = quote + src + quote - img_tag = img_tag.replace(match.group(0), 'src="{}" data-src={}'.format(placeholder, quoted_src)) - return img_tag + def callback(img_tag): + match = _image_src_re.search(img_tag) + if match is not None: + src = match.group("src") + quote = match.group("quote") + quoted_src = quote + src + quote + img_tag = img_tag.replace( + match.group(0), 'src="{}" data-src={}'.format(placeholder, quoted_src) + ) + return img_tag + + return _replace_images(text, callback) - return _replace_images(text, callback) def _strip_tags(text): - """ - >>> _strip_tags("Hello world<img src='foo.jpg'>") # doctest: +ALLOW_UNICODE - "Hello world<img src='foo.jpg'>" - >>> _strip_tags("> > Foo") # doctest: +ALLOW_UNICODE - '> > Foo' - """ - try: - # noinspection PyCompatibility - from html.parser import HTMLParser - except ImportError: - # noinspection PyCompatibility - from HTMLParser import HTMLParser + """ + >>> _strip_tags("Hello world<img src='foo.jpg'>") # doctest: +ALLOW_UNICODE + "Hello world<img src='foo.jpg'>" + >>> _strip_tags("> > Foo") # doctest: +ALLOW_UNICODE + '> > Foo' + """ + try: + # noinspection PyCompatibility + from html.parser import HTMLParser + except ImportError: + # noinspection PyCompatibility + from HTMLParser import HTMLParser - class TagStripper(HTMLParser): + class TagStripper(HTMLParser): + def __init__(self, **kw): + HTMLParser.__init__(self, **kw) + self._fed = [] - def __init__(self, **kw): - HTMLParser.__init__(self, **kw) - self._fed = [] + def handle_data(self, data): + self._fed.append(data) - def handle_data(self, data): - self._fed.append(data) + def handle_entityref(self, ref): + self._fed.append("&{};".format(ref)) - def handle_entityref(self, ref): - self._fed.append("&{};".format(ref)) + def handle_charref(self, ref): + self._fed.append("&#{};".format(ref)) - def handle_charref(self, ref): - self._fed.append("&#{};".format(ref)) + def get_data(self): + return "".join(self._fed) - def get_data(self): - return "".join(self._fed) - - tag_stripper = TagStripper() if PY2 else TagStripper(convert_charrefs=False) - tag_stripper.feed(text) - return tag_stripper.get_data() + tag_stripper = TagStripper() if PY2 else TagStripper(convert_charrefs=False) + tag_stripper.feed(text) + return tag_stripper.get_data() __plugin_name__ = "Announcement Plugin" __plugin_author__ = "Gina Häußge" __plugin_description__ = "Announcements all around OctoPrint" -__plugin_disabling_discouraged__ = gettext("Without this plugin you might miss important announcements " - "regarding security or other critical issues concerning OctoPrint.") +__plugin_disabling_discouraged__ = gettext( + "Without this plugin you might miss important announcements " + "regarding security or other critical issues concerning OctoPrint." +) __plugin_license__ = "AGPLv3" __plugin_pythoncompat__ = ">=2.7,<4" __plugin_implementation__ = AnnouncementPlugin() __plugin_hooks__ = { - 'octoprint.access.permissions': __plugin_implementation__.get_additional_permissions + "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions } diff --git a/src/octoprint/plugins/appkeys/__init__.py b/src/octoprint/plugins/appkeys/__init__.py index 5a393058e..e1009189d 100644 --- a/src/octoprint/plugins/appkeys/__init__.py +++ b/src/octoprint/plugins/appkeys/__init__.py @@ -20,428 +20,482 @@ from octoprint.util import atomic_write, monotonic_time, ResettableTimer, genera from octoprint.access import ADMIN_GROUP from octoprint.access.permissions import Permissions -CUTOFF_TIME = 10 * 60 # 10min -POLL_TIMEOUT = 5 # 5 seconds +CUTOFF_TIME = 10 * 60 # 10min +POLL_TIMEOUT = 5 # 5 seconds + class AppAlreadyExists(Exception): - pass + pass class PendingDecision(object): - def __init__(self, app_id, app_token, user_id, user_token, timeout_callback=None): - self.app_id = app_id - self.app_token = app_token - self.user_id = user_id - self.user_token = user_token - self.created = monotonic_time() + def __init__(self, app_id, app_token, user_id, user_token, timeout_callback=None): + self.app_id = app_id + self.app_token = app_token + self.user_id = user_id + self.user_token = user_token + self.created = monotonic_time() - if callable(timeout_callback): - self.poll_timeout = ResettableTimer(POLL_TIMEOUT, timeout_callback, [user_token]) - self.poll_timeout.start() + if callable(timeout_callback): + self.poll_timeout = ResettableTimer( + POLL_TIMEOUT, timeout_callback, [user_token] + ) + self.poll_timeout.start() - def external(self): - return {"app_id": self.app_id, - "user_id": self.user_id, - "user_token": self.user_token} + def external(self): + return { + "app_id": self.app_id, + "user_id": self.user_id, + "user_token": self.user_token, + } - def __repr__(self): - return u"PendingDecision({!r}, {!r}, {!r}, {!r}, timeout_callback=...)".format(self.app_id, - self.app_token, - self.user_id, - self.user_token) + def __repr__(self): + return "PendingDecision({!r}, {!r}, {!r}, {!r}, timeout_callback=...)".format( + self.app_id, self.app_token, self.user_id, self.user_token + ) class ReadyDecision(object): - def __init__(self, app_id, app_token, user_id): - self.app_id = app_id - self.app_token = app_token - self.user_id = user_id + def __init__(self, app_id, app_token, user_id): + self.app_id = app_id + self.app_token = app_token + self.user_id = user_id - @classmethod - def for_pending(cls, pending, user_id): - return cls(pending.app_id, pending.app_token, user_id) + @classmethod + def for_pending(cls, pending, user_id): + return cls(pending.app_id, pending.app_token, user_id) - def __repr__(self): - return u"ReadyDecision({!r}, {!r}, {!r})".format(self.app_id, - self.app_token, - self.user_id) + def __repr__(self): + return "ReadyDecision({!r}, {!r}, {!r})".format( + self.app_id, self.app_token, self.user_id + ) class ActiveKey(object): - def __init__(self, app_id, api_key, user_id): - self.app_id = app_id - self.api_key = api_key - self.user_id = user_id - - def external(self): - return {"app_id": self.app_id, - "api_key": self.api_key, - "user_id": self.user_id} - - def internal(self): - return {"app_id": self.app_id, - "api_key": self.api_key} - - @classmethod - def for_internal(cls, internal, user_id): - return cls(internal["app_id"], internal["api_key"], user_id) - - def __repr__(self): - return u"ActiveKey({!r}, {!r}, {!r})".format(self.app_id, - self.api_key, - self.user_id) - - -class AppKeysPlugin(octoprint.plugin.AssetPlugin, - octoprint.plugin.BlueprintPlugin, - octoprint.plugin.SimpleApiPlugin, - octoprint.plugin.TemplatePlugin): - - def __init__(self): - self._pending_decisions = [] - self._pending_lock = threading.RLock() - - self._ready_decisions = [] - self._ready_lock = threading.RLock() - - self._keys = defaultdict(list) - self._keys_lock = threading.RLock() - - self._key_path = None - - def initialize(self): - self._key_path = os.path.join(self.get_plugin_data_folder(), "keys.yaml") - self._load_keys() - - # Additional permissions hook - - def get_additional_permissions(self): - return [ - {"key": "ADMIN", - "name": "Admin access", - "description": gettext("Allows administrating all application keys"), - "roles": ["admin"], - "dangerous": True, - "default_groups": [ADMIN_GROUP]} - ] - - ##~~ TemplatePlugin - - def get_template_configs(self): - return [{"type": "usersettings", "name": gettext("Application Keys")}, - {"type": "settings", "name": gettext("Application Keys")}] - - ##~~ AssetPlugin - - def get_assets(self): - return {"js": ["js/appkeys.js"], - "clientjs": ["clientjs/appkeys.js"], - "less": ["less/appkeys.less"], - "css": ["css/appkeys.css"]} - - ##~~ BlueprintPlugin mixin - - @octoprint.plugin.BlueprintPlugin.route("/probe", methods=["GET"]) - @no_firstrun_access - def handle_probe(self): - return NO_CONTENT - - @octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"]) - @no_firstrun_access - def handle_request(self): - data = flask.request.json - if data is None: - return flask.make_response("Missing key request", 400) - - if not "app" in data: - return flask.make_response("No app name provided", 400) - - app_name = data["app"] - user_id = None - if "user" in data and data["user"]: - user_id = data["user"] - - app_token, user_token = self._add_pending_decision(app_name, user_id=user_id) - - self._plugin_manager.send_plugin_message(self._identifier, {"type": "request_access", - "app_name": app_name, - "user_token": user_token, - "user_id": user_id}) - response = flask.jsonify(app_token=app_token) - response.status_code = 201 - response.headers["Location"] = flask.url_for(".handle_decision_poll", app_token=app_token, _external=True) - return response + def __init__(self, app_id, api_key, user_id): + self.app_id = app_id + self.api_key = api_key + self.user_id = user_id + + def external(self): + return {"app_id": self.app_id, "api_key": self.api_key, "user_id": self.user_id} + + def internal(self): + return {"app_id": self.app_id, "api_key": self.api_key} + + @classmethod + def for_internal(cls, internal, user_id): + return cls(internal["app_id"], internal["api_key"], user_id) + + def __repr__(self): + return "ActiveKey({!r}, {!r}, {!r})".format( + self.app_id, self.api_key, self.user_id + ) + + +class AppKeysPlugin( + octoprint.plugin.AssetPlugin, + octoprint.plugin.BlueprintPlugin, + octoprint.plugin.SimpleApiPlugin, + octoprint.plugin.TemplatePlugin, +): + def __init__(self): + self._pending_decisions = [] + self._pending_lock = threading.RLock() + + self._ready_decisions = [] + self._ready_lock = threading.RLock() + + self._keys = defaultdict(list) + self._keys_lock = threading.RLock() + + self._key_path = None + + def initialize(self): + self._key_path = os.path.join(self.get_plugin_data_folder(), "keys.yaml") + self._load_keys() + + # Additional permissions hook + + def get_additional_permissions(self): + return [ + { + "key": "ADMIN", + "name": "Admin access", + "description": gettext("Allows administrating all application keys"), + "roles": ["admin"], + "dangerous": True, + "default_groups": [ADMIN_GROUP], + } + ] + + ##~~ TemplatePlugin + + def get_template_configs(self): + return [ + {"type": "usersettings", "name": gettext("Application Keys")}, + {"type": "settings", "name": gettext("Application Keys")}, + ] + + ##~~ AssetPlugin + + def get_assets(self): + return { + "js": ["js/appkeys.js"], + "clientjs": ["clientjs/appkeys.js"], + "less": ["less/appkeys.less"], + "css": ["css/appkeys.css"], + } + + ##~~ BlueprintPlugin mixin + + @octoprint.plugin.BlueprintPlugin.route("/probe", methods=["GET"]) + @no_firstrun_access + def handle_probe(self): + return NO_CONTENT + + @octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"]) + @no_firstrun_access + def handle_request(self): + data = flask.request.json + if data is None: + return flask.make_response("Missing key request", 400) + + if not "app" in data: + return flask.make_response("No app name provided", 400) + + app_name = data["app"] + user_id = None + if "user" in data and data["user"]: + user_id = data["user"] + + app_token, user_token = self._add_pending_decision(app_name, user_id=user_id) + + self._plugin_manager.send_plugin_message( + self._identifier, + { + "type": "request_access", + "app_name": app_name, + "user_token": user_token, + "user_id": user_id, + }, + ) + response = flask.jsonify(app_token=app_token) + response.status_code = 201 + response.headers["Location"] = flask.url_for( + ".handle_decision_poll", app_token=app_token, _external=True + ) + return response + + @octoprint.plugin.BlueprintPlugin.route("/request/") + @no_firstrun_access + def handle_decision_poll(self, app_token): + result = self._get_pending_by_app_token(app_token) + if result: + for pending_decision in result: + pending_decision.poll_timeout.reset() + + response = flask.jsonify(message="Awaiting decision") + response.status_code = 202 + return response + + result = self._get_decision(app_token) + if result: + return flask.jsonify(api_key=result) + + return flask.abort(404) + + @octoprint.plugin.BlueprintPlugin.route("/decision/", methods=["POST"]) + @restricted_access + def handle_decision(self, user_token): + data = flask.request.json + if not "decision" in data: + return flask.make_response("No decision provided", 400) + decision = data["decision"] in valid_boolean_trues + user_id = current_user.get_name() + + result = self._set_decision(user_token, decision, user_id) + if not result: + return flask.abort(404) + + # Close access_request dialog for this request on all open OctoPrint connections + self._plugin_manager.send_plugin_message( + self._identifier, {"type": "end_request", "user_token": user_token} + ) + + return NO_CONTENT + + def is_blueprint_protected(self): + return False # No API key required to request API access + + ##~~ SimpleApiPlugin mixin + + def get_api_commands(self): + return {"generate": ["app"], "revoke": ["key"]} + + def on_api_get(self, request): + user_id = current_user.get_name() + if not user_id: + return flask.abort(403) + + if ( + request.values.get("all") in valid_boolean_trues + and Permissions.PLUGIN_APPKEYS_ADMIN.can() + ): + keys = self._all_api_keys() + else: + keys = self._api_keys_for_user(user_id) + + return flask.jsonify( + keys=list(map(lambda x: x.external(), keys)), + pending=dict( + (x.user_token, x.external()) + for x in self._get_pending_by_user_id(user_id) + ), + ) + + def on_api_command(self, command, data): + user_id = current_user.get_name() + if not user_id: + return flask.abort(403) + + if command == "revoke": + api_key = data.get("key") + if not api_key: + return flask.abort(400) + + if not admin_permission.can(): + user_for_key = self._user_for_api_key(api_key) + if user_for_key is None or user_for_key.user_id != user_id: + return flask.abort(403) + + self._delete_api_key(api_key) + + elif command == "generate": + # manual generateKey + app_name = data.get("app") + if not app_name: + return flask.abort(400) + + selected_user_id = data.get("user", user_id) + if selected_user_id != user_id and not Permissions.PLUGIN_APPKEYS_ADMIN.can(): + return flask.abort(403) + + key = self._add_api_key(selected_user_id, app_name.strip()) + return flask.jsonify(user_id=selected_user_id, app_id=app_name, api_key=key) + + return NO_CONTENT + + ##~~ key validator hook + + def validate_api_key(self, api_key, *args, **kwargs): + return self._user_for_api_key(api_key) + + ##~~ Helpers + + def _add_pending_decision(self, app_name, user_id=None): + app_token = self._generate_key() + user_token = self._generate_key() + + with self._pending_lock: + self._remove_stale_pending() + self._pending_decisions.append( + PendingDecision( + app_name, + app_token, + user_id, + user_token, + timeout_callback=self._expire_pending, + ) + ) + + return app_token, user_token + + def _get_pending_by_app_token(self, app_token): + result = [] + with self._pending_lock: + self._remove_stale_pending() + for data in self._pending_decisions: + if data.app_token == app_token: + result.append(data) + return result + + def _get_pending_by_user_id(self, user_id): + result = [] + with self._pending_lock: + self._remove_stale_pending() + for data in self._pending_decisions: + if data.user_id == user_id or data.user_id is None: + result.append(data) + return result + + def _expire_pending(self, user_token): + with self._pending_lock: + len_before = len(self._pending_decisions) + self._pending_decisions = list( + filter(lambda x: x.user_token != user_token, self._pending_decisions) + ) + len_after = len(self._pending_decisions) + + if len_after < len_before: + self._plugin_manager.send_plugin_message( + self._identifier, {"type": "end_request", "user_token": user_token} + ) + + def _remove_stale_pending(self): + with self._pending_lock: + cutoff = monotonic_time() - CUTOFF_TIME + len_before = len(self._pending_decisions) + self._pending_decisions = list( + filter(lambda x: x.created >= cutoff, self._pending_decisions) + ) + len_after = len(self._pending_decisions) + if len_after < len_before: + self._logger.info( + "Deleted {} stale pending authorization requests".format( + len_before - len_after + ) + ) + + def _set_decision(self, user_token, decision, user_id): + with self._pending_lock: + self._remove_stale_pending() + for data in self._pending_decisions: + if data.user_token == user_token and ( + data.user_id == user_id or data.user_id is None + ): + pending = data + break + else: + return False # not found + + if decision: + with self._ready_lock: + self._ready_decisions.append(ReadyDecision.for_pending(pending, user_id)) + + with self._pending_lock: + self._pending_decisions = list( + filter(lambda x: x.user_token != user_token, self._pending_decisions) + ) + + return True + + def _get_decision(self, app_token): + self._remove_stale_pending() + + with self._ready_lock: + for data in self._ready_decisions: + if data.app_token == app_token: + decision = data + break + else: + return False # not found + + api_key = self._add_api_key(decision.user_id, decision.app_id) + + with self._ready_lock: + self._ready_decisions = list( + filter(lambda x: x.app_token != app_token, self._ready_decisions) + ) + + return api_key + + def _add_api_key(self, user_id, app_name): + with self._keys_lock: + for key in self._keys[user_id]: + if key.app_id.lower() == app_name.lower(): + return key.api_key + + key = ActiveKey(app_name, self._generate_key(), user_id) + self._keys[user_id].append(key) + self._save_keys() + return key.api_key + + def _delete_api_key(self, api_key): + with self._keys_lock: + for user_id, data in self._keys.items(): + self._keys[user_id] = list(filter(lambda x: x.api_key != api_key, data)) + self._save_keys() + + def _user_for_api_key(self, api_key): + with self._keys_lock: + for user_id, data in self._keys.items(): + if any(filter(lambda x: x.api_key == api_key, data)): + if self._user_manager.enabled: + return self._user_manager.find_user(userid=user_id) + elif user_id == "_admin" or user_id == "dummy": + # dummy = backwards compatible + return self._user_manager.anonymous_user_factory() + return None + + def _api_keys_for_user(self, user_id): + with self._keys_lock: + return self._keys[user_id] + + def _all_api_keys(self): + with self._keys_lock: + result = [] + for user_id, keys in self._keys.items(): + result += keys + return result + + def _generate_key(self): + return generate_api_key() + + def _load_keys(self): + with self._keys_lock: + if not os.path.exists(self._key_path): + return + + try: + with io.open( + self._key_path, "rt", encoding="utf-8", errors="strict" + ) as f: + persisted = yaml.safe_load(f) + except Exception: + self._logger.exception( + "Could not load application keys from {}".format(self._key_path) + ) + return + + if not isinstance(persisted, dict): + return + + keys = defaultdict(list) + for user_id, persisted_keys in persisted.items(): + keys[user_id] = [ + ActiveKey.for_internal(x, user_id) for x in persisted_keys + ] + self._keys = keys + + def _save_keys(self): + with self._keys_lock: + to_persist = {} + for user_id, keys in self._keys.items(): + to_persist[user_id] = [x.internal() for x in keys] + + try: + with atomic_write(self._key_path, mode="wt") as f: + yaml.safe_dump(to_persist, f, allow_unicode=True) + except Exception: + self._logger.exception( + "Could not write application keys to {}".format(self._key_path) + ) - @octoprint.plugin.BlueprintPlugin.route("/request/") - @no_firstrun_access - def handle_decision_poll(self, app_token): - result = self._get_pending_by_app_token(app_token) - if result: - for pending_decision in result: - pending_decision.poll_timeout.reset() - - response = flask.jsonify(message="Awaiting decision") - response.status_code = 202 - return response - - result = self._get_decision(app_token) - if result: - return flask.jsonify(api_key=result) - - return flask.abort(404) - - @octoprint.plugin.BlueprintPlugin.route("/decision/", methods=["POST"]) - @restricted_access - def handle_decision(self, user_token): - data = flask.request.json - if not "decision" in data: - return flask.make_response("No decision provided", 400) - decision = data["decision"] in valid_boolean_trues - user_id = current_user.get_name() - - result = self._set_decision(user_token, decision, user_id) - if not result: - return flask.abort(404) - - # Close access_request dialog for this request on all open OctoPrint connections - self._plugin_manager.send_plugin_message(self._identifier, {"type": "end_request", - "user_token": user_token}) - - return NO_CONTENT - - def is_blueprint_protected(self): - return False # No API key required to request API access - - ##~~ SimpleApiPlugin mixin - - def get_api_commands(self): - return {"generate": ["app"], - "revoke": ["key"]} - - def on_api_get(self, request): - user_id = current_user.get_name() - if not user_id: - return flask.abort(403) - - if request.values.get("all") in valid_boolean_trues and Permissions.PLUGIN_APPKEYS_ADMIN.can(): - keys = self._all_api_keys() - else: - keys = self._api_keys_for_user(user_id) - - return flask.jsonify(keys=list(map(lambda x: x.external(), keys)), - pending=dict((x.user_token, x.external()) for x in self._get_pending_by_user_id(user_id))) - - def on_api_command(self, command, data): - user_id = current_user.get_name() - if not user_id: - return flask.abort(403) - - if command == "revoke": - api_key = data.get("key") - if not api_key: - return flask.abort(400) - - if not admin_permission.can(): - user_for_key = self._user_for_api_key(api_key) - if user_for_key is None or user_for_key.user_id != user_id: - return flask.abort(403) - - self._delete_api_key(api_key) - - elif command == "generate": - # manual generateKey - app_name = data.get("app") - if not app_name: - return flask.abort(400) - - selected_user_id = data.get("user", user_id) - if selected_user_id != user_id and not Permissions.PLUGIN_APPKEYS_ADMIN.can(): - return flask.abort(403) - - key = self._add_api_key(selected_user_id, app_name.strip()) - return flask.jsonify(user_id=selected_user_id, app_id=app_name, api_key=key) - - return NO_CONTENT - - ##~~ key validator hook - - def validate_api_key(self, api_key, *args, **kwargs): - return self._user_for_api_key(api_key) - - ##~~ Helpers - - def _add_pending_decision(self, app_name, user_id=None): - app_token = self._generate_key() - user_token = self._generate_key() - - with self._pending_lock: - self._remove_stale_pending() - self._pending_decisions.append(PendingDecision(app_name, app_token, user_id, user_token, - timeout_callback=self._expire_pending)) - - return app_token, user_token - - def _get_pending_by_app_token(self, app_token): - result = [] - with self._pending_lock: - self._remove_stale_pending() - for data in self._pending_decisions: - if data.app_token == app_token: - result.append(data) - return result - - def _get_pending_by_user_id(self, user_id): - result = [] - with self._pending_lock: - self._remove_stale_pending() - for data in self._pending_decisions: - if data.user_id == user_id or data.user_id is None: - result.append(data) - return result - - def _expire_pending(self, user_token): - with self._pending_lock: - len_before = len(self._pending_decisions) - self._pending_decisions = list(filter(lambda x: x.user_token != user_token, - self._pending_decisions)) - len_after = len(self._pending_decisions) - - if len_after < len_before: - self._plugin_manager.send_plugin_message(self._identifier, {"type": "end_request", - "user_token": user_token}) - - def _remove_stale_pending(self): - with self._pending_lock: - cutoff = monotonic_time() - CUTOFF_TIME - len_before = len(self._pending_decisions) - self._pending_decisions = list(filter(lambda x: x.created >= cutoff, - self._pending_decisions)) - len_after = len(self._pending_decisions) - if len_after < len_before: - self._logger.info("Deleted {} stale pending authorization requests".format(len_before - len_after)) - - def _set_decision(self, user_token, decision, user_id): - with self._pending_lock: - self._remove_stale_pending() - for data in self._pending_decisions: - if data.user_token == user_token and (data.user_id == user_id or data.user_id is None): - pending = data - break - else: - return False # not found - - if decision: - with self._ready_lock: - self._ready_decisions.append(ReadyDecision.for_pending(pending, user_id)) - - with self._pending_lock: - self._pending_decisions = list(filter(lambda x: x.user_token != user_token, - self._pending_decisions)) - - return True - - def _get_decision(self, app_token): - self._remove_stale_pending() - - with self._ready_lock: - for data in self._ready_decisions: - if data.app_token == app_token: - decision = data - break - else: - return False # not found - - api_key = self._add_api_key(decision.user_id, decision.app_id) - - with self._ready_lock: - self._ready_decisions = list(filter(lambda x: x.app_token != app_token, - self._ready_decisions)) - - return api_key - - def _add_api_key(self, user_id, app_name): - with self._keys_lock: - for key in self._keys[user_id]: - if key.app_id.lower() == app_name.lower(): - return key.api_key - - key = ActiveKey(app_name, self._generate_key(), user_id) - self._keys[user_id].append(key) - self._save_keys() - return key.api_key - - def _delete_api_key(self, api_key): - with self._keys_lock: - for user_id, data in self._keys.items(): - self._keys[user_id] = list(filter(lambda x: x.api_key != api_key, data)) - self._save_keys() - - def _user_for_api_key(self, api_key): - with self._keys_lock: - for user_id, data in self._keys.items(): - if any(filter(lambda x: x.api_key == api_key, data)): - if self._user_manager.enabled: - return self._user_manager.find_user(userid=user_id) - elif user_id == "_admin" or user_id == "dummy": - # dummy = backwards compatible - return self._user_manager.anonymous_user_factory() - return None - - def _api_keys_for_user(self, user_id): - with self._keys_lock: - return self._keys[user_id] - - def _all_api_keys(self): - with self._keys_lock: - result = [] - for user_id, keys in self._keys.items(): - result += keys - return result - - def _generate_key(self): - return generate_api_key() - - def _load_keys(self): - with self._keys_lock: - if not os.path.exists(self._key_path): - return - - try: - with io.open(self._key_path, 'rt', encoding="utf-8", errors="strict") as f: - persisted = yaml.safe_load(f) - except Exception: - self._logger.exception("Could not load application keys from {}".format(self._key_path)) - return - - if not isinstance(persisted, dict): - return - - keys = defaultdict(list) - for user_id, persisted_keys in persisted.items(): - keys[user_id] = [ActiveKey.for_internal(x, user_id) for x in persisted_keys] - self._keys = keys - - def _save_keys(self): - with self._keys_lock: - to_persist = {} - for user_id, keys in self._keys.items(): - to_persist[user_id] = [x.internal() for x in keys] - - try: - with atomic_write(self._key_path, mode='wt') as f: - yaml.safe_dump(to_persist, f, allow_unicode=True) - except Exception: - self._logger.exception("Could not write application keys to {}".format(self._key_path)) __plugin_name__ = "Application Keys Plugin" -__plugin_description__ = "Implements a workflow for third party clients to obtain API keys" +__plugin_description__ = ( + "Implements a workflow for third party clients to obtain API keys" +) __plugin_author__ = "Gina Häußge, Aldo Hoeben" -__plugin_disabling_discouraged__ = gettext("Without this plugin third party clients will no longer be able to " - "obtain an API key without you manually copy-pasting it.") +__plugin_disabling_discouraged__ = gettext( + "Without this plugin third party clients will no longer be able to " + "obtain an API key without you manually copy-pasting it." +) __plugin_license__ = "AGPLv3" __plugin_pythoncompat__ = ">=2.7,<4" __plugin_implementation__ = AppKeysPlugin() __plugin_hooks__ = { - "octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key, - "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions + "octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key, + "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions, } diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index 7d3b04c46..199c98828 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -1,7 +1,7 @@ # -*- 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" import octoprint.plugin @@ -12,21 +12,26 @@ from octoprint.server import admin_permission, NO_CONTENT from octoprint.server.util.flask import no_firstrun_access from octoprint.events import Events from octoprint.util import is_hidden_path, to_bytes -from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, get_comparable_version, is_octoprint_compatible +from octoprint.util.version import ( + get_octoprint_version_string, + get_octoprint_version, + get_comparable_version, + is_octoprint_compatible, +) from octoprint.util.platform import is_os_compatible from octoprint.util.pip import LocalPipCaller from octoprint.access import ADMIN_GROUP from octoprint.access.permissions import Permissions try: - from os import scandir + from os import scandir except ImportError: - from scandir import scandir + from scandir import scandir try: - import zlib # check if zlib is available + import zlib # check if zlib is available except ImportError: - zlib = None + zlib = None from flask_babel import gettext @@ -55,1016 +60,1260 @@ BACKUP_FILE_PREFIX = "octoprint-backup" BACKUP_DATE_TIME_FMT = "%Y%m%d-%H%M%S" + def build_backup_filename(): - return "{}-{}.zip".format(BACKUP_FILE_PREFIX, - time.strftime(BACKUP_DATE_TIME_FMT)) - - -class BackupPlugin(octoprint.plugin.SettingsPlugin, - octoprint.plugin.TemplatePlugin, - octoprint.plugin.AssetPlugin, - octoprint.plugin.BlueprintPlugin, - octoprint.plugin.StartupPlugin, - octoprint.plugin.WizardPlugin): - - _pip_caller = None - - # noinspection PyMissingConstructor - def __init__(self): - self._in_progress = [] - self._in_progress_lock = threading.RLock() - - # Additional permissions hook - - def get_additional_permissions(self): - return [ - {"key": "ACCESS", - "name": "Backup access", - "description": gettext("Allows access to backups and restores"), - "roles": ["access"], - "dangerous": True, - "default_groups": [ADMIN_GROUP]} - ] - - # Socket emit hook - - def socket_emit_hook(self, socket, user, message, payload, *args, **kwargs): - if message != "event" or payload["type"] != Events.PLUGIN_BACKUP_BACKUP_CREATED: - return True - - return user and user.has_permission(Permissions.PLUGIN_BACKUP_ACCESS) - - ##~~ StartupPlugin - - def on_after_startup(self): - self._clean_dir_backup(self._settings._basedir, - on_log_progress=self._logger.info) - - ##~~ SettingsPlugin - - def get_settings_defaults(self): - return { - "restore_unsupported": False - } - - ##~~ AssetPlugin - - def get_assets(self): - return {"js": ["js/backup.js"], - "clientjs": ["clientjs/backup.js"], - "css": ["css/backup.css"], - "less": ["less/backup.less"]} - - ##~~ TemplatePlugin - - def get_template_configs(self): - return [{"type": "settings", "name": gettext("Backup & Restore")}, - {"type": "wizard", "name": gettext("Restore Backup?")}] - - ##~~ BlueprintPlugin - - @octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"]) - @no_firstrun_access - @Permissions.PLUGIN_BACKUP_ACCESS.require(403) - def get_state(self): - backups = self._get_backups() - unknown_plugins = self._get_unknown_plugins() - return flask.jsonify(backups=backups, - backup_in_progress=len(self._in_progress) > 0, - unknown_plugins=unknown_plugins, - restore_supported=self._restore_supported(self._settings)) - - @octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["GET"]) - @no_firstrun_access - @Permissions.PLUGIN_BACKUP_ACCESS.require(403) - def get_unknown_plugins(self): - # TODO add caching - unknown_plugins = self._get_unknown_plugins() - return flask.jsonify(unknown_plugins=unknown_plugins) - - @octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["DELETE"]) - @no_firstrun_access - @Permissions.PLUGIN_BACKUP_ACCESS.require(403) - def delete_unknown_plugins(self): - data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE) - try: - os.remove(data_file) - except Exception: - pass - return NO_CONTENT - - @octoprint.plugin.BlueprintPlugin.route("/backup", methods=["GET"]) - @no_firstrun_access - @Permissions.PLUGIN_BACKUP_ACCESS.require(403) - def get_backups(self): - backups = self._get_backups() - return flask.jsonify(backups=backups) - - @octoprint.plugin.BlueprintPlugin.route("/backup", methods=["POST"]) - @no_firstrun_access - @Permissions.PLUGIN_BACKUP_ACCESS.require(403) - def create_backup(self): - backup_file = build_backup_filename() - - data = flask.request.json - exclude = data.get("exclude", []) - - def on_backup_start(name, temporary_path, exclude): - self._logger.info("Creating backup zip at {} (excluded: {})...".format(temporary_path, - ",".join(exclude) if len(exclude) else "-")) - - with self._in_progress_lock: - self._in_progress.append(name) - self._send_client_message("backup_started", payload={"name": name}) - - def on_backup_done(name, final_path, exclude): - with self._in_progress_lock: - self._in_progress.remove(name) - self._send_client_message("backup_done", payload={"name": name}) - - self._logger.info("... done creating backup zip.") - - self._event_bus.fire(Events.PLUGIN_BACKUP_BACKUP_CREATED, - {"name": name, - "path": final_path, - "excludes": exclude}) - - def on_backup_error(name, exc_info): - with self._in_progress_lock: - try: - self._in_progress.remove(name) - except ValueError: - # we'll ignore that - pass - - self._send_client_message("backup_error", payload={"name": name, - "error": "{}".format(exc_info[1])}) - self._logger.error("Error while creating backup zip", exc_info=exc_info) - - thread = threading.Thread(target=self._create_backup, - args=(backup_file,), - kwargs={"exclude": exclude, - "settings": self._settings, - "plugin_manager": self._plugin_manager, - "logger": self._logger, - "datafolder": self.get_plugin_data_folder(), - "on_backup_start": on_backup_start, - "on_backup_done": on_backup_done, - "on_backup_error": on_backup_error}) - thread.daemon = True - thread.start() - - response = flask.jsonify(started=True, - name=backup_file) - response.status_code = 201 - return response - - @octoprint.plugin.BlueprintPlugin.route("/backup/", methods=["DELETE"]) - @no_firstrun_access - @Permissions.PLUGIN_BACKUP_ACCESS.require(403) - def delete_backup(self, filename): - backup_folder = self.get_plugin_data_folder() - full_path = os.path.realpath(os.path.join(backup_folder, filename)) - if full_path.startswith(backup_folder) \ - and os.path.exists(full_path) \ - and not is_hidden_path(full_path): - try: - os.remove(full_path) - except Exception: - self._logger.exception("Could not delete {}".format(filename)) - raise - return NO_CONTENT - - @octoprint.plugin.BlueprintPlugin.route("/restore", methods=["POST"]) - def perform_restore(self): - if not Permissions.PLUGIN_BACKUP_ACCESS.can() and not self._settings.global_get(["server", "firstRun"]): - return flask.abort(403) - - if not self._restore_supported(self._settings): - return flask.make_response("Invalid request, the restores are not supported on the underlying operating system", 400) - - input_name = "file" - input_upload_path = input_name + "." + self._settings.global_get(["server", "uploads", "pathSuffix"]) - - if input_upload_path in flask.request.values: - # file to restore was uploaded - path = flask.request.values[input_upload_path] - - elif flask.request.json and "path" in flask.request.json: - # existing backup is supposed to be restored - backup_folder = self.get_plugin_data_folder() - path = os.path.realpath(os.path.join(backup_folder, flask.request.json["path"])) - if not path.startswith(backup_folder) \ - or not os.path.exists(path) \ - or is_hidden_path(path): - return flask.abort(404) - - else: - return flask.make_response("Invalid request, neither a file nor a path of a file to restore provided", 400) - - def on_install_plugins(plugins): - force_user = self._settings.global_get_boolean(["plugins", "pluginmanager", "pip_force_user"]) - pip_args = self._settings.global_get(["plugins", "pluginmanager", "pip_args"]) - - def on_log(line): - self._logger.info(line) - self._send_client_message("logline", {"line": line, "type": "stdout"}) - - for plugin in plugins: - octoprint_compatible = is_octoprint_compatible(*plugin["compatibility"]["octoprint"]) - os_compatible = is_os_compatible(plugin["compatibility"]["os"]) - compatible = octoprint_compatible and os_compatible - if not compatible: - if not octoprint_compatible and not os_compatible: - self._logger.warning("Cannot install plugin {}, it is incompatible to this version " - "of OctoPrint and the underlying operating system".format(plugin["id"])) - elif not octoprint_compatible: - self._logger.warning("Cannot install plugin {}, it is incompatible to this version " - "of OctoPrint".format(plugin["id"])) - elif not os_compatible: - self._logger.warning("Cannot install plugin {}, it is incompatible to the underlying " - "operating system".format(plugin["id"])) - self._send_client_message("plugin_incompatible", {"plugin": plugin["id"], - "octoprint_compatible": octoprint_compatible, - "os_compatible": os_compatible}) - continue - - self._logger.info("Installing plugin {}".format(plugin["id"])) - self._send_client_message("installing_plugin", {"plugin": plugin["id"]}) - self.__class__._install_plugin(plugin, - force_user=force_user, - pip_args=pip_args, - on_log=on_log) - - def on_report_unknown_plugins(plugins): - self._send_client_message("unknown_plugins", payload={"plugins": plugins}) - - def on_log_progress(line): - self._logger.info(line) - self._send_client_message("logline", payload={"line": line, "stream": "stdout"}) - - def on_log_error(line, exc_info=None): - self._logger.error(line, exc_info=exc_info) - self._send_client_message("logline", payload={"line": line, "stream": "stderr"}) - - if exc_info is not None: - exc_type, exc_value, exc_tb = exc_info - output = traceback.format_exception(exc_type, exc_value, exc_tb) - for line in output: - self._send_client_message("logline", payload={"line": line.rstrip(), "stream": "stderr"}) - - def on_restore_start(path): - self._send_client_message("restore_started") - - def on_restore_done(path): - self._send_client_message("restore_done") - - def on_restore_failed(path): - self._send_client_message("restore_failed") - - def on_invalid_backup(line): - on_log_error(line) - - archive = tempfile.NamedTemporaryFile(delete=False) - archive.close() - shutil.copy(path, archive.name) - path = archive.name - - # noinspection PyTypeChecker - thread = threading.Thread(target=self._restore_backup, - args=(path,), - kwargs={"settings": self._settings, - "plugin_manager": self._plugin_manager, - "datafolder": self.get_plugin_data_folder(), - "on_install_plugins": on_install_plugins, - "on_report_unknown_plugins": on_report_unknown_plugins, - "on_invalid_backup": on_invalid_backup, - "on_log_progress": on_log_progress, - "on_log_error": on_log_error, - "on_restore_start": on_restore_start, - "on_restore_done": on_restore_done, - "on_restore_failed": on_restore_failed}) - thread.daemon = True - thread.start() - - return flask.jsonify(started=True) - - def is_blueprint_protected(self): - return False - - ##~~ WizardPlugin - - def is_wizard_required(self): - return self._settings.global_get(["server", "firstRun"]) and is_os_compatible(["!windows"]) - - def get_wizard_details(self): - return {"required": self.is_wizard_required()} - - ##~~ tornado hook - - def route_hook(self, *args, **kwargs): - from octoprint.server.util.tornado import LargeResponseHandler, path_validation_factory - from octoprint.util import is_hidden_path - from octoprint.server import app - from octoprint.server.util.tornado import access_validation_factory - from octoprint.server.util.flask import admin_validator - - return [ - (r"/download/(.*)", LargeResponseHandler, {"path": self.get_plugin_data_folder(), - "as_attachment": True, - "path_validation": path_validation_factory(lambda path: not is_hidden_path(path), - status_code=404), - "access_validation": access_validation_factory(app, admin_validator)}) - ] - - def bodysize_hook(self, current_max_body_sizes, *args, **kwargs): - # max upload size of 1GB for the restore endpoint - return [("POST", r"/restore", 1024 * 1024 * 1024)] - - ##~~ CLI hook - - def cli_commands_hook(self, cli_group, pass_octoprint_ctx, *args, **kwargs): - import click - - @click.command("backup") - @click.option("--exclude", multiple=True, - help="Identifiers of data folders to exclude, e.g. 'uploads' to exclude uploads or " - "'timelapse' to exclude timelapses.") - @click.option("--path", type=click.Path(), default=None, - help="Specify full path to backup file to be created") - def backup_command(exclude, path): - """ - Creates a new backup. - """ - - settings = octoprint.plugin.plugin_settings_for_settings_plugin("backup", self, settings=cli_group.settings) - - if path is not None: - datafolder, backup_file = os.path.split(os.path.abspath(path)) - else: - backup_file = build_backup_filename() - datafolder = os.path.join(settings.getBaseFolder("data"), "backup") - - if not os.path.isdir(datafolder): - os.makedirs(datafolder) - - click.echo("Creating backup at {}, please wait...".format(backup_file)) - self._create_backup(backup_file, - exclude=exclude, - settings=settings, - logger=self._logger, - plugin_manager=cli_group.plugin_manager, - datafolder=datafolder) - click.echo("Done.") - click.echo("Backup located at {}".format(os.path.join(datafolder, backup_file))) - - @click.command("restore") - @click.argument("path") - def restore_command(path): - """ - Restores an existing backup from the backup zip provided as argument. - - OctoPrint does not need to run for this to proceed. - """ - settings = octoprint.plugin.plugin_settings_for_settings_plugin("backup", self, settings=cli_group.settings) - plugin_manager = cli_group.plugin_manager - - datafolder = os.path.join(settings.getBaseFolder("data"), "backup") - if not os.path.isdir(datafolder): - os.makedirs(datafolder) - - # register plugin manager plugin setting overlays - plugin_info = plugin_manager.get_plugin_info("pluginmanager") - if plugin_info and plugin_info.implementation: - default_settings_overlay = {"plugins": {}} - default_settings_overlay["plugins"]["pluginmanager"] = plugin_info.implementation.get_settings_defaults() - settings.add_overlay(default_settings_overlay, at_end=True) - - if not os.path.isabs(path): - datafolder = os.path.join(settings.getBaseFolder("data"), "backup") - if not os.path.isdir(datafolder): - os.makedirs(datafolder) - path = os.path.join(datafolder, path) - - if not os.path.exists(path): - click.echo("Backup {} does not exist".format(path), err=True) - sys.exit(-1) - - archive = tempfile.NamedTemporaryFile(delete=False) - archive.close() - shutil.copy(path, archive.name) - path = archive.name - - def on_install_plugins(plugins): - if not plugins: - return - - force_user = settings.global_get_boolean(["plugins", "pluginmanager", "pip_force_user"]) - pip_args = settings.global_get(["plugins", "pluginmanager", "pip_args"]) - - def log(line): - click.echo("\t{}".format(line)) - - for plugin in plugins: - octoprint_compatible = is_octoprint_compatible(*plugin["compatibility"]["octoprint"]) - os_compatible = is_os_compatible(plugin["compatibility"]["os"]) - compatible = octoprint_compatible and os_compatible - if not compatible: - if not octoprint_compatible and not os_compatible: - click.echo("Cannot install plugin {}, it is incompatible to this version of " - "OctoPrint and the underlying operating system".format(plugin["id"])) - elif not octoprint_compatible: - click.echo("Cannot install plugin {}, it is incompatible to this version of " - "OctoPrint".format(plugin["id"])) - elif not os_compatible: - click.echo("Cannot install plugin {}, it is incompatible to the underlying " - "operating system".format(plugin["id"])) - continue - - click.echo("Installing plugin {}".format(plugin["id"])) - self.__class__._install_plugin(plugin, - force_user=force_user, - pip_args=pip_args, - on_log=log) - - def on_report_unknown_plugins(plugins): - if not plugins: - return - - click.echo("The following plugins were not found in the plugin repository. You'll need to install them manually.") - for plugin in plugins: - click.echo("\t{} (Homepage: {})".format(plugin["name"], plugin["url"] if plugin["url"] else "?")) - - def on_log_progress(line): - click.echo(line) - - def on_log_error(line, exc_info=None): - click.echo(line, err=True) - - if exc_info is not None: - exc_type, exc_value, exc_tb = exc_info - output = traceback.format_exception(exc_type, exc_value, exc_tb) - for line in output: - click.echo(line.rstrip(), err=True) - - if self._restore_backup(path, - settings=settings, - plugin_manager=plugin_manager, - datafolder=datafolder, - on_install_plugins=on_install_plugins, - on_report_unknown_plugins=on_report_unknown_plugins, - on_log_progress=on_log_progress, - on_log_error=on_log_error, - on_invalid_backup=on_log_error): - click.echo("Restored from {}".format(path)) - else: - click.echo("Restoring from {} failed".format(path), err=True) - - return [backup_command, restore_command] - - ##~~ helpers - - def _get_backups(self): - backups = [] - for entry in scandir(self.get_plugin_data_folder()): - if is_hidden_path(entry.path): - continue - if not entry.is_file(): - continue - if not entry.name.endswith(".zip"): - continue - - backups.append({"name": entry.name, - "date": entry.stat().st_mtime, - "size": entry.stat().st_size, - "url": flask.url_for("index") + "plugin/backup/download/" + entry.name}) - return backups - - def _get_unknown_plugins(self): - data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE) - if os.path.exists(data_file): - try: - with io.open(data_file, mode='rt', encoding="utf-8") as f: - unknown_plugins = json.load(f) - - assert isinstance(unknown_plugins, list) - assert all(map(lambda x: isinstance(x, dict) and "key" in x and "name" in x and "url" in x, unknown_plugins)) - - installed_plugins = self._plugin_manager.plugins - unknown_plugins = list(filter(lambda x: x["key"] not in installed_plugins, unknown_plugins)) - if not unknown_plugins: - # no plugins left uninstalled, delete data file - try: - os.remove(data_file) - except Exception: - self._logger.exception("Error while deleting list of unknown plugins at {}".format(data_file)) - - return unknown_plugins - except Exception: - self._logger.exception("Error while reading list of unknown plugins from {}".format(data_file)) - try: - os.remove(data_file) - except Exception: - self._logger.exception("Error while deleting list of unknown plugins at {}".format(data_file)) - - return [] - - @classmethod - def _clean_dir_backup(cls, basedir, - on_log_progress=None): - basedir_backup = basedir + ".bck" - - if os.path.exists(basedir_backup): - def remove_bck(): - if callable(on_log_progress): - on_log_progress("Found config folder backup from prior restore, deleting it...") - shutil.rmtree(basedir_backup) - if callable(on_log_progress): - on_log_progress("... deleted.") - - thread = threading.Thread(target=remove_bck) - thread.daemon = True - thread.start() - - @classmethod - def _get_disk_size(cls, path, ignored=None): - if ignored is None: - ignored = [] - - if path in ignored: - return 0 - - total = 0 - for entry in scandir(path): - if entry.is_dir(): - total += cls._get_disk_size(entry.path, ignored=ignored) - elif entry.is_file(): - total += entry.stat().st_size - return total - - @classmethod - def _free_space(cls, path, size): - from psutil import disk_usage - return disk_usage(path).free > size - - @classmethod - def _get_plugin_repository_data(cls, url, logger=None): - if logger is None: - logger = logging.getLogger(__name__) - - try: - r = requests.get(url, timeout=30) - r.raise_for_status() - except Exception: - logger.exception("Error while fetching the plugin repository data from {}".format(url)) - return {} - - from octoprint.plugins.pluginmanager import map_repository_entry - return dict((plugin["id"], plugin) for plugin in map(map_repository_entry, r.json())) - - @classmethod - def _install_plugin(cls, plugin, force_user=False, pip_args=None, on_log=None): - if pip_args is None: - pip_args = [] - - if on_log is None: - on_log = logging.getLogger(__name__).info - - # prepare pip caller - def log(prefix, *lines): - for line in lines: - on_log("{} {}".format(prefix, line.rstrip())) - - def log_call(*lines): - log(">", *lines) - - def log_stdout(*lines): - log("<", *lines) - - def log_stderr(*lines): - log("!", *lines) - - if cls._pip_caller is None: - cls._pip_caller = LocalPipCaller(force_user=force_user) - - cls._pip_caller.on_log_call = log_call - cls._pip_caller.on_log_stdout = log_stdout - cls._pip_caller.on_log_stderr = log_stderr - - # install plugin - pip = ["install", sarge.shell_quote(plugin["archive"]), '--no-cache-dir'] - - if plugin.get("follow_dependency_links"): - pip.append("--process-dependency-links") - - if force_user: - pip.append("--user") - - if pip_args: - pip += pip_args - - cls._pip_caller.execute(*pip) - - @classmethod - def _create_backup(cls, name, - exclude=None, - settings=None, - plugin_manager=None, - logger=None, - datafolder=None, - on_backup_start=None, - on_backup_done=None, - on_backup_error=None): - exclude_by_default = ("generated", "logs", "watched",) - - try: - if exclude is None: - exclude = [] - if not isinstance(exclude, list): - exclude = list(exclude) - - if "timelapse" in exclude: - exclude.append("timelapse_tmp") - - current_excludes = list(exclude) - additional_excludes = list() - plugin_data = settings.global_get_basefolder("data") - for plugin, hook in plugin_manager.get_hooks("octoprint.plugin.backup.additional_excludes").items(): - try: - additional = hook(current_excludes) - if isinstance(additional, list): - if "." in additional: - current_excludes.append(os.path.join("data", plugin)) - additional_excludes.append(os.path.join(plugin_data, plugin)) - else: - current_excludes += map(lambda x: os.path.join("data", plugin, x), additional) - additional_excludes += map(lambda x: os.path.join(plugin_data, plugin, x), additional) - except Exception: - logger.exception("Error while retrieving additional excludes " - "from plugin {name}".format(**locals()), - extra={"plugin": plugin}) - - configfile = settings._configfile - basedir = settings._basedir - - temporary_path = os.path.join(datafolder, ".{}".format(name)) - final_path = os.path.join(datafolder, name) - - own_folder = datafolder - defaults = [os.path.join(basedir, "config.yaml"),] + \ - [os.path.join(basedir, folder) for folder in default_settings["folder"].keys()] - - # check how many bytes we are about to backup - size = os.stat(configfile).st_size - for folder in default_settings["folder"].keys(): - if folder in exclude or folder in exclude_by_default: - continue - size += cls._get_disk_size(settings.global_get_basefolder(folder), - ignored=[own_folder,]) - size += cls._get_disk_size(basedir, ignored=defaults + [own_folder,]) - - # since we can't know the compression ratio beforehand, we assume we need the same amount of space - if not cls._free_space(os.path.dirname(temporary_path), size): - raise InsufficientSpace() - - compression = zipfile.ZIP_DEFLATED if zlib else zipfile.ZIP_STORED - - if callable(on_backup_start): - on_backup_start(name, temporary_path, exclude) - - with zipfile.ZipFile(temporary_path, mode="w", compression=compression, allowZip64=True) as zip: - def add_to_zip(source, target, ignored=None): - if ignored is None: - ignored = [] - - if source in ignored: - return - - if os.path.isdir(source): - for entry in scandir(source): - add_to_zip(entry.path, os.path.join(target, entry.name), ignored=ignored) - elif os.path.isfile(source): - zip.write(source, arcname=target) - - # add metadata - metadata = {"version": get_octoprint_version_string(), - "excludes": exclude} - zip.writestr("metadata.json", json.dumps(metadata)) - - # backup current config file - add_to_zip(configfile, "basedir/config.yaml", ignored=[own_folder,]) - - # backup configured folder paths - for folder in default_settings["folder"].keys(): - if folder in exclude or folder in exclude_by_default: - continue - - add_to_zip(settings.global_get_basefolder(folder), - "basedir/" + folder.replace("_", "/"), - ignored=[own_folder,] + additional_excludes) - - # backup anything else that might be lying around in our basedir - add_to_zip(basedir, "basedir", ignored=defaults + [own_folder, ] + additional_excludes) - - # add list of installed plugins - plugins = [] - plugin_folder = settings.global_get_basefolder("plugins") - for key, plugin in plugin_manager.plugins.items(): - if plugin.bundled or (isinstance(plugin.origin, FolderOrigin) and plugin.origin.folder == plugin_folder): - # ignore anything bundled or from the plugins folder we already include in the backup - continue - - plugins.append({"key": plugin.key, - "name": plugin.name, - "url": plugin.url}) - - if len(plugins): - zip.writestr("plugin_list.json", json.dumps(plugins)) - - shutil.move(temporary_path, final_path) - - if callable(on_backup_done): - on_backup_done(name, final_path, exclude) - - except Exception as exc: ## noqa: F841 - # TODO py3: use the exception, not sys.exc_info() - if callable(on_backup_error): - exc_info = sys.exc_info() - try: - on_backup_error(name, exc_info) - finally: - del exc_info - raise - - @classmethod - def _restore_backup(cls, path, - settings=None, - plugin_manager=None, - datafolder=None, - on_install_plugins=None, - on_report_unknown_plugins=None, - on_invalid_backup=None, - on_log_progress=None, - on_log_error=None, - on_restore_start=None, - on_restore_done=None, - on_restore_failed=None): - if not cls._restore_supported(settings): - if callable(on_log_error): - on_log_error("Restore is not supported on this operating system") - if callable(on_restore_failed): - on_restore_failed(path) - return False - - restart_command = settings.global_get(["server", "commands", "serverRestartCommand"]) - - basedir = settings._basedir - cls._clean_dir_backup(basedir, - on_log_progress=on_log_progress) - - plugin_repo = {} - repo_url = settings.global_get(["plugins", "pluginmanager", "repository"]) - if repo_url: - plugin_repo = cls._get_plugin_repository_data(repo_url) - - if callable(on_restore_start): - on_restore_start(path) - - try: - - with zipfile.ZipFile(path, "r") as zip: - # read metadata - try: - metadata_zipinfo = zip.getinfo("metadata.json") - except KeyError: - if callable(on_invalid_backup): - on_invalid_backup("Not an OctoPrint backup, lacks metadata.json") - if callable(on_restore_failed): - on_restore_failed(path) - return False - - metadata_bytes = zip.read(metadata_zipinfo) - metadata = json.loads(metadata_bytes) - - backup_version = get_comparable_version(metadata["version"], base=True) - if backup_version > get_octoprint_version(base=True): - if callable(on_invalid_backup): - on_invalid_backup("Backup is from a newer version of OctoPrint and cannot be applied") - if callable(on_restore_failed): - on_restore_failed(path) - return False - - # unzip to temporary folder - temp = tempfile.mkdtemp() - try: - if callable(on_log_progress): - on_log_progress("Unpacking backup to {}...".format(temp)) - - abstemp = os.path.abspath(temp) - dirs = {} - for member in zip.infolist(): - abspath = os.path.abspath(os.path.join(temp, member.filename)) - if abspath.startswith(abstemp): - date_time = time.mktime(member.date_time + (0, 0, -1)) - - zip.extract(member, temp) - - if os.path.isdir(abspath): - dirs[abspath] = date_time - else: - os.utime(abspath, (date_time, date_time)) - - # set time on folders - for abspath, date_time in dirs.items(): - os.utime(abspath, (date_time, date_time)) - - # sanity check - configfile = os.path.join(temp, "basedir", "config.yaml") - if not os.path.exists(configfile): - if callable(on_invalid_backup): - on_invalid_backup("Backup lacks config.yaml") - if callable(on_restore_failed): - on_restore_failed(path) - return False - - import yaml - - with io.open(configfile, "rt", encoding="utf-8") as f: - configdata = yaml.safe_load(f) - - if configdata.get("accessControl", {}).get("enabled", True): - userfile = os.path.join(temp, "basedir", "users.yaml") - if not os.path.exists(userfile): - if callable(on_invalid_backup): - on_invalid_backup("Backup lacks users.yaml") - if callable(on_restore_failed): - on_restore_failed(path) - return False - - if callable(on_log_progress): - on_log_progress("Unpacked") - - # install available plugins - plugins = [] - plugin_list_file = os.path.join(temp, "plugin_list.json") - if os.path.exists(plugin_list_file): - with io.open(os.path.join(temp, "plugin_list.json"), 'rb') as f: - plugins = json.load(f) - - known_plugins = [] - unknown_plugins = [] - if plugins: - if plugin_repo: - for plugin in plugins: - if plugin["key"] in plugin_manager.plugins: - # already installed - continue - - if plugin["key"] in plugin_repo: - # not installed, can be installed from repository url - known_plugins.append(plugin_repo[plugin["key"]]) - else: - # not installed, not installable - unknown_plugins.append(plugin) - - else: - # no repo, all plugins are not installable - unknown_plugins = plugins - - if callable(on_log_progress): - if known_plugins: - on_log_progress("Known and installable plugins: {}".format(", ".join(map(lambda x: x["id"], known_plugins)))) - if unknown_plugins: - on_log_progress("Unknown plugins: {}".format(", ".join(map(lambda x: x["key"], unknown_plugins)))) - - if callable(on_install_plugins): - on_install_plugins(known_plugins) - - if callable(on_report_unknown_plugins): - on_report_unknown_plugins(unknown_plugins) - - # move config data - basedir_backup = basedir + ".bck" - basedir_extracted = os.path.join(temp, "basedir") - - if callable(on_log_progress): - on_log_progress("Renaming {} to {}...".format(basedir, basedir_backup)) - shutil.move(basedir, basedir_backup) - - try: - if callable(on_log_progress): - on_log_progress("Moving {} to {}...".format(basedir_extracted, basedir)) - shutil.move(basedir_extracted, basedir) - except Exception: - if callable(on_log_error): - on_log_error("Error while restoring config data", exc_info=sys.exc_info()) - on_log_error("Rolling back old config data") - - shutil.move(basedir_backup, basedir) - - if callable(on_restore_failed): - on_restore_failed(path) - return False - - if unknown_plugins: - if callable(on_log_progress): - on_log_progress("Writing info file about unknown plugins") - - if not os.path.isdir(datafolder): - os.makedirs(datafolder) - - unknown_plugins_path = os.path.join(datafolder, UNKNOWN_PLUGINS_FILE) - try: - with io.open(unknown_plugins_path, mode='wb') as f: - f.write(to_bytes(json.dumps(unknown_plugins))) - except Exception: - if callable(on_log_error): - on_log_error("Could not persist list of unknown plugins to {}".format(unknown_plugins_path), - exc_info = sys.exc_info()) - - finally: - if callable(on_log_progress): - on_log_progress("Removing temporary unpacked folder") - shutil.rmtree(temp) - - except Exception: - exc_info = sys.exc_info() - try: - if callable(on_log_error): - on_log_error("Error while running restore", exc_info=exc_info) - if callable(on_restore_failed): - on_restore_failed(path) - finally: - del exc_info - return False - - finally: - # remove zip - if callable(on_log_progress): - on_log_progress("Removing temporary zip") - os.remove(path) - - # restart server - if not restart_command: - restart_command = configdata.get("server", {}).get("commands", {}).get("serverRestartCommand") - - if restart_command: - import sarge - - if callable(on_log_progress): - on_log_progress("Restarting...") - if callable(on_restore_done): - on_restore_done(path) - - try: - sarge.run(restart_command, close_fds=True, async_=True) - except Exception: - if callable(on_log_error): - on_log_error("Error while restarting via command {}".format(restart_command), - exc_info=sys.exc_info()) - on_log_error("Please restart OctoPrint manually") - return False - - else: - if callable(on_restore_done): - on_restore_done(path) - if callable(on_log_error): - on_log_error("No restart command configured. Please restart OctoPrint manually.") - - return True - - @classmethod - def _restore_supported(cls, settings): - return is_os_compatible(["!windows"]) \ - and not settings.get_boolean(["restore_unsupported"]) \ - and not os.environ.get("OCTOPRINT_BACKUP_RESTORE_UNSUPPORTED", False) in valid_boolean_trues - - - def _send_client_message(self, message, payload=None): - if payload is None: - payload = {} - payload["type"] = message - self._plugin_manager.send_plugin_message(self._identifier, payload) + return "{}-{}.zip".format(BACKUP_FILE_PREFIX, time.strftime(BACKUP_DATE_TIME_FMT)) + + +class BackupPlugin( + octoprint.plugin.SettingsPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.AssetPlugin, + octoprint.plugin.BlueprintPlugin, + octoprint.plugin.StartupPlugin, + octoprint.plugin.WizardPlugin, +): + + _pip_caller = None + + # noinspection PyMissingConstructor + def __init__(self): + self._in_progress = [] + self._in_progress_lock = threading.RLock() + + # Additional permissions hook + + def get_additional_permissions(self): + return [ + { + "key": "ACCESS", + "name": "Backup access", + "description": gettext("Allows access to backups and restores"), + "roles": ["access"], + "dangerous": True, + "default_groups": [ADMIN_GROUP], + } + ] + + # Socket emit hook + + def socket_emit_hook(self, socket, user, message, payload, *args, **kwargs): + if message != "event" or payload["type"] != Events.PLUGIN_BACKUP_BACKUP_CREATED: + return True + + return user and user.has_permission(Permissions.PLUGIN_BACKUP_ACCESS) + + ##~~ StartupPlugin + + def on_after_startup(self): + self._clean_dir_backup(self._settings._basedir, on_log_progress=self._logger.info) + + ##~~ SettingsPlugin + + def get_settings_defaults(self): + return {"restore_unsupported": False} + + ##~~ AssetPlugin + + def get_assets(self): + return { + "js": ["js/backup.js"], + "clientjs": ["clientjs/backup.js"], + "css": ["css/backup.css"], + "less": ["less/backup.less"], + } + + ##~~ TemplatePlugin + + def get_template_configs(self): + return [ + {"type": "settings", "name": gettext("Backup & Restore")}, + {"type": "wizard", "name": gettext("Restore Backup?")}, + ] + + ##~~ BlueprintPlugin + + @octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"]) + @no_firstrun_access + @Permissions.PLUGIN_BACKUP_ACCESS.require(403) + def get_state(self): + backups = self._get_backups() + unknown_plugins = self._get_unknown_plugins() + return flask.jsonify( + backups=backups, + backup_in_progress=len(self._in_progress) > 0, + unknown_plugins=unknown_plugins, + restore_supported=self._restore_supported(self._settings), + ) + + @octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["GET"]) + @no_firstrun_access + @Permissions.PLUGIN_BACKUP_ACCESS.require(403) + def get_unknown_plugins(self): + # TODO add caching + unknown_plugins = self._get_unknown_plugins() + return flask.jsonify(unknown_plugins=unknown_plugins) + + @octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["DELETE"]) + @no_firstrun_access + @Permissions.PLUGIN_BACKUP_ACCESS.require(403) + def delete_unknown_plugins(self): + data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE) + try: + os.remove(data_file) + except Exception: + pass + return NO_CONTENT + + @octoprint.plugin.BlueprintPlugin.route("/backup", methods=["GET"]) + @no_firstrun_access + @Permissions.PLUGIN_BACKUP_ACCESS.require(403) + def get_backups(self): + backups = self._get_backups() + return flask.jsonify(backups=backups) + + @octoprint.plugin.BlueprintPlugin.route("/backup", methods=["POST"]) + @no_firstrun_access + @Permissions.PLUGIN_BACKUP_ACCESS.require(403) + def create_backup(self): + backup_file = build_backup_filename() + + data = flask.request.json + exclude = data.get("exclude", []) + + def on_backup_start(name, temporary_path, exclude): + self._logger.info( + "Creating backup zip at {} (excluded: {})...".format( + temporary_path, ",".join(exclude) if len(exclude) else "-" + ) + ) + + with self._in_progress_lock: + self._in_progress.append(name) + self._send_client_message("backup_started", payload={"name": name}) + + def on_backup_done(name, final_path, exclude): + with self._in_progress_lock: + self._in_progress.remove(name) + self._send_client_message("backup_done", payload={"name": name}) + + self._logger.info("... done creating backup zip.") + + self._event_bus.fire( + Events.PLUGIN_BACKUP_BACKUP_CREATED, + {"name": name, "path": final_path, "excludes": exclude}, + ) + + def on_backup_error(name, exc_info): + with self._in_progress_lock: + try: + self._in_progress.remove(name) + except ValueError: + # we'll ignore that + pass + + self._send_client_message( + "backup_error", payload={"name": name, "error": "{}".format(exc_info[1])} + ) + self._logger.error("Error while creating backup zip", exc_info=exc_info) + + thread = threading.Thread( + target=self._create_backup, + args=(backup_file,), + kwargs={ + "exclude": exclude, + "settings": self._settings, + "plugin_manager": self._plugin_manager, + "logger": self._logger, + "datafolder": self.get_plugin_data_folder(), + "on_backup_start": on_backup_start, + "on_backup_done": on_backup_done, + "on_backup_error": on_backup_error, + }, + ) + thread.daemon = True + thread.start() + + response = flask.jsonify(started=True, name=backup_file) + response.status_code = 201 + return response + + @octoprint.plugin.BlueprintPlugin.route("/backup/", methods=["DELETE"]) + @no_firstrun_access + @Permissions.PLUGIN_BACKUP_ACCESS.require(403) + def delete_backup(self, filename): + backup_folder = self.get_plugin_data_folder() + full_path = os.path.realpath(os.path.join(backup_folder, filename)) + if ( + full_path.startswith(backup_folder) + and os.path.exists(full_path) + and not is_hidden_path(full_path) + ): + try: + os.remove(full_path) + except Exception: + self._logger.exception("Could not delete {}".format(filename)) + raise + return NO_CONTENT + + @octoprint.plugin.BlueprintPlugin.route("/restore", methods=["POST"]) + def perform_restore(self): + if not Permissions.PLUGIN_BACKUP_ACCESS.can() and not self._settings.global_get( + ["server", "firstRun"] + ): + return flask.abort(403) + + if not self._restore_supported(self._settings): + return flask.make_response( + "Invalid request, the restores are not supported on the underlying operating system", + 400, + ) + + input_name = "file" + input_upload_path = ( + input_name + + "." + + self._settings.global_get(["server", "uploads", "pathSuffix"]) + ) + + if input_upload_path in flask.request.values: + # file to restore was uploaded + path = flask.request.values[input_upload_path] + + elif flask.request.json and "path" in flask.request.json: + # existing backup is supposed to be restored + backup_folder = self.get_plugin_data_folder() + path = os.path.realpath( + os.path.join(backup_folder, flask.request.json["path"]) + ) + if ( + not path.startswith(backup_folder) + or not os.path.exists(path) + or is_hidden_path(path) + ): + return flask.abort(404) + + else: + return flask.make_response( + "Invalid request, neither a file nor a path of a file to restore provided", + 400, + ) + + def on_install_plugins(plugins): + force_user = self._settings.global_get_boolean( + ["plugins", "pluginmanager", "pip_force_user"] + ) + pip_args = self._settings.global_get(["plugins", "pluginmanager", "pip_args"]) + + def on_log(line): + self._logger.info(line) + self._send_client_message("logline", {"line": line, "type": "stdout"}) + + for plugin in plugins: + octoprint_compatible = is_octoprint_compatible( + *plugin["compatibility"]["octoprint"] + ) + os_compatible = is_os_compatible(plugin["compatibility"]["os"]) + compatible = octoprint_compatible and os_compatible + if not compatible: + if not octoprint_compatible and not os_compatible: + self._logger.warning( + "Cannot install plugin {}, it is incompatible to this version " + "of OctoPrint and the underlying operating system".format( + plugin["id"] + ) + ) + elif not octoprint_compatible: + self._logger.warning( + "Cannot install plugin {}, it is incompatible to this version " + "of OctoPrint".format(plugin["id"]) + ) + elif not os_compatible: + self._logger.warning( + "Cannot install plugin {}, it is incompatible to the underlying " + "operating system".format(plugin["id"]) + ) + self._send_client_message( + "plugin_incompatible", + { + "plugin": plugin["id"], + "octoprint_compatible": octoprint_compatible, + "os_compatible": os_compatible, + }, + ) + continue + + self._logger.info("Installing plugin {}".format(plugin["id"])) + self._send_client_message("installing_plugin", {"plugin": plugin["id"]}) + self.__class__._install_plugin( + plugin, force_user=force_user, pip_args=pip_args, on_log=on_log + ) + + def on_report_unknown_plugins(plugins): + self._send_client_message("unknown_plugins", payload={"plugins": plugins}) + + def on_log_progress(line): + self._logger.info(line) + self._send_client_message( + "logline", payload={"line": line, "stream": "stdout"} + ) + + def on_log_error(line, exc_info=None): + self._logger.error(line, exc_info=exc_info) + self._send_client_message( + "logline", payload={"line": line, "stream": "stderr"} + ) + + if exc_info is not None: + exc_type, exc_value, exc_tb = exc_info + output = traceback.format_exception(exc_type, exc_value, exc_tb) + for line in output: + self._send_client_message( + "logline", payload={"line": line.rstrip(), "stream": "stderr"} + ) + + def on_restore_start(path): + self._send_client_message("restore_started") + + def on_restore_done(path): + self._send_client_message("restore_done") + + def on_restore_failed(path): + self._send_client_message("restore_failed") + + def on_invalid_backup(line): + on_log_error(line) + + archive = tempfile.NamedTemporaryFile(delete=False) + archive.close() + shutil.copy(path, archive.name) + path = archive.name + + # noinspection PyTypeChecker + thread = threading.Thread( + target=self._restore_backup, + args=(path,), + kwargs={ + "settings": self._settings, + "plugin_manager": self._plugin_manager, + "datafolder": self.get_plugin_data_folder(), + "on_install_plugins": on_install_plugins, + "on_report_unknown_plugins": on_report_unknown_plugins, + "on_invalid_backup": on_invalid_backup, + "on_log_progress": on_log_progress, + "on_log_error": on_log_error, + "on_restore_start": on_restore_start, + "on_restore_done": on_restore_done, + "on_restore_failed": on_restore_failed, + }, + ) + thread.daemon = True + thread.start() + + return flask.jsonify(started=True) + + def is_blueprint_protected(self): + return False + + ##~~ WizardPlugin + + def is_wizard_required(self): + return self._settings.global_get(["server", "firstRun"]) and is_os_compatible( + ["!windows"] + ) + + def get_wizard_details(self): + return {"required": self.is_wizard_required()} + + ##~~ tornado hook + + def route_hook(self, *args, **kwargs): + from octoprint.server.util.tornado import ( + LargeResponseHandler, + path_validation_factory, + ) + from octoprint.util import is_hidden_path + from octoprint.server import app + from octoprint.server.util.tornado import access_validation_factory + from octoprint.server.util.flask import admin_validator + + return [ + ( + r"/download/(.*)", + LargeResponseHandler, + { + "path": self.get_plugin_data_folder(), + "as_attachment": True, + "path_validation": path_validation_factory( + lambda path: not is_hidden_path(path), status_code=404 + ), + "access_validation": access_validation_factory(app, admin_validator), + }, + ) + ] + + def bodysize_hook(self, current_max_body_sizes, *args, **kwargs): + # max upload size of 1GB for the restore endpoint + return [("POST", r"/restore", 1024 * 1024 * 1024)] + + ##~~ CLI hook + + def cli_commands_hook(self, cli_group, pass_octoprint_ctx, *args, **kwargs): + import click + + @click.command("backup") + @click.option( + "--exclude", + multiple=True, + help="Identifiers of data folders to exclude, e.g. 'uploads' to exclude uploads or " + "'timelapse' to exclude timelapses.", + ) + @click.option( + "--path", + type=click.Path(), + default=None, + help="Specify full path to backup file to be created", + ) + def backup_command(exclude, path): + """ + Creates a new backup. + """ + + settings = octoprint.plugin.plugin_settings_for_settings_plugin( + "backup", self, settings=cli_group.settings + ) + + if path is not None: + datafolder, backup_file = os.path.split(os.path.abspath(path)) + else: + backup_file = build_backup_filename() + datafolder = os.path.join(settings.getBaseFolder("data"), "backup") + + if not os.path.isdir(datafolder): + os.makedirs(datafolder) + + click.echo("Creating backup at {}, please wait...".format(backup_file)) + self._create_backup( + backup_file, + exclude=exclude, + settings=settings, + logger=self._logger, + plugin_manager=cli_group.plugin_manager, + datafolder=datafolder, + ) + click.echo("Done.") + click.echo( + "Backup located at {}".format(os.path.join(datafolder, backup_file)) + ) + + @click.command("restore") + @click.argument("path") + def restore_command(path): + """ + Restores an existing backup from the backup zip provided as argument. + + OctoPrint does not need to run for this to proceed. + """ + settings = octoprint.plugin.plugin_settings_for_settings_plugin( + "backup", self, settings=cli_group.settings + ) + plugin_manager = cli_group.plugin_manager + + datafolder = os.path.join(settings.getBaseFolder("data"), "backup") + if not os.path.isdir(datafolder): + os.makedirs(datafolder) + + # register plugin manager plugin setting overlays + plugin_info = plugin_manager.get_plugin_info("pluginmanager") + if plugin_info and plugin_info.implementation: + default_settings_overlay = {"plugins": {}} + default_settings_overlay["plugins"][ + "pluginmanager" + ] = plugin_info.implementation.get_settings_defaults() + settings.add_overlay(default_settings_overlay, at_end=True) + + if not os.path.isabs(path): + datafolder = os.path.join(settings.getBaseFolder("data"), "backup") + if not os.path.isdir(datafolder): + os.makedirs(datafolder) + path = os.path.join(datafolder, path) + + if not os.path.exists(path): + click.echo("Backup {} does not exist".format(path), err=True) + sys.exit(-1) + + archive = tempfile.NamedTemporaryFile(delete=False) + archive.close() + shutil.copy(path, archive.name) + path = archive.name + + def on_install_plugins(plugins): + if not plugins: + return + + force_user = settings.global_get_boolean( + ["plugins", "pluginmanager", "pip_force_user"] + ) + pip_args = settings.global_get(["plugins", "pluginmanager", "pip_args"]) + + def log(line): + click.echo("\t{}".format(line)) + + for plugin in plugins: + octoprint_compatible = is_octoprint_compatible( + *plugin["compatibility"]["octoprint"] + ) + os_compatible = is_os_compatible(plugin["compatibility"]["os"]) + compatible = octoprint_compatible and os_compatible + if not compatible: + if not octoprint_compatible and not os_compatible: + click.echo( + "Cannot install plugin {}, it is incompatible to this version of " + "OctoPrint and the underlying operating system".format( + plugin["id"] + ) + ) + elif not octoprint_compatible: + click.echo( + "Cannot install plugin {}, it is incompatible to this version of " + "OctoPrint".format(plugin["id"]) + ) + elif not os_compatible: + click.echo( + "Cannot install plugin {}, it is incompatible to the underlying " + "operating system".format(plugin["id"]) + ) + continue + + click.echo("Installing plugin {}".format(plugin["id"])) + self.__class__._install_plugin( + plugin, force_user=force_user, pip_args=pip_args, on_log=log + ) + + def on_report_unknown_plugins(plugins): + if not plugins: + return + + click.echo( + "The following plugins were not found in the plugin repository. You'll need to install them manually." + ) + for plugin in plugins: + click.echo( + "\t{} (Homepage: {})".format( + plugin["name"], plugin["url"] if plugin["url"] else "?" + ) + ) + + def on_log_progress(line): + click.echo(line) + + def on_log_error(line, exc_info=None): + click.echo(line, err=True) + + if exc_info is not None: + exc_type, exc_value, exc_tb = exc_info + output = traceback.format_exception(exc_type, exc_value, exc_tb) + for line in output: + click.echo(line.rstrip(), err=True) + + if self._restore_backup( + path, + settings=settings, + plugin_manager=plugin_manager, + datafolder=datafolder, + on_install_plugins=on_install_plugins, + on_report_unknown_plugins=on_report_unknown_plugins, + on_log_progress=on_log_progress, + on_log_error=on_log_error, + on_invalid_backup=on_log_error, + ): + click.echo("Restored from {}".format(path)) + else: + click.echo("Restoring from {} failed".format(path), err=True) + + return [backup_command, restore_command] + + ##~~ helpers + + def _get_backups(self): + backups = [] + for entry in scandir(self.get_plugin_data_folder()): + if is_hidden_path(entry.path): + continue + if not entry.is_file(): + continue + if not entry.name.endswith(".zip"): + continue + + backups.append( + { + "name": entry.name, + "date": entry.stat().st_mtime, + "size": entry.stat().st_size, + "url": flask.url_for("index") + + "plugin/backup/download/" + + entry.name, + } + ) + return backups + + def _get_unknown_plugins(self): + data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE) + if os.path.exists(data_file): + try: + with io.open(data_file, mode="rt", encoding="utf-8") as f: + unknown_plugins = json.load(f) + + assert isinstance(unknown_plugins, list) + assert all( + map( + lambda x: isinstance(x, dict) + and "key" in x + and "name" in x + and "url" in x, + unknown_plugins, + ) + ) + + installed_plugins = self._plugin_manager.plugins + unknown_plugins = list( + filter(lambda x: x["key"] not in installed_plugins, unknown_plugins) + ) + if not unknown_plugins: + # no plugins left uninstalled, delete data file + try: + os.remove(data_file) + except Exception: + self._logger.exception( + "Error while deleting list of unknown plugins at {}".format( + data_file + ) + ) + + return unknown_plugins + except Exception: + self._logger.exception( + "Error while reading list of unknown plugins from {}".format( + data_file + ) + ) + try: + os.remove(data_file) + except Exception: + self._logger.exception( + "Error while deleting list of unknown plugins at {}".format( + data_file + ) + ) + + return [] + + @classmethod + def _clean_dir_backup(cls, basedir, on_log_progress=None): + basedir_backup = basedir + ".bck" + + if os.path.exists(basedir_backup): + + def remove_bck(): + if callable(on_log_progress): + on_log_progress( + "Found config folder backup from prior restore, deleting it..." + ) + shutil.rmtree(basedir_backup) + if callable(on_log_progress): + on_log_progress("... deleted.") + + thread = threading.Thread(target=remove_bck) + thread.daemon = True + thread.start() + + @classmethod + def _get_disk_size(cls, path, ignored=None): + if ignored is None: + ignored = [] + + if path in ignored: + return 0 + + total = 0 + for entry in scandir(path): + if entry.is_dir(): + total += cls._get_disk_size(entry.path, ignored=ignored) + elif entry.is_file(): + total += entry.stat().st_size + return total + + @classmethod + def _free_space(cls, path, size): + from psutil import disk_usage + + return disk_usage(path).free > size + + @classmethod + def _get_plugin_repository_data(cls, url, logger=None): + if logger is None: + logger = logging.getLogger(__name__) + + try: + r = requests.get(url, timeout=30) + r.raise_for_status() + except Exception: + logger.exception( + "Error while fetching the plugin repository data from {}".format(url) + ) + return {} + + from octoprint.plugins.pluginmanager import map_repository_entry + + return dict( + (plugin["id"], plugin) for plugin in map(map_repository_entry, r.json()) + ) + + @classmethod + def _install_plugin(cls, plugin, force_user=False, pip_args=None, on_log=None): + if pip_args is None: + pip_args = [] + + if on_log is None: + on_log = logging.getLogger(__name__).info + + # prepare pip caller + def log(prefix, *lines): + for line in lines: + on_log("{} {}".format(prefix, line.rstrip())) + + def log_call(*lines): + log(">", *lines) + + def log_stdout(*lines): + log("<", *lines) + + def log_stderr(*lines): + log("!", *lines) + + if cls._pip_caller is None: + cls._pip_caller = LocalPipCaller(force_user=force_user) + + cls._pip_caller.on_log_call = log_call + cls._pip_caller.on_log_stdout = log_stdout + cls._pip_caller.on_log_stderr = log_stderr + + # install plugin + pip = ["install", sarge.shell_quote(plugin["archive"]), "--no-cache-dir"] + + if plugin.get("follow_dependency_links"): + pip.append("--process-dependency-links") + + if force_user: + pip.append("--user") + + if pip_args: + pip += pip_args + + cls._pip_caller.execute(*pip) + + @classmethod + def _create_backup( + cls, + name, + exclude=None, + settings=None, + plugin_manager=None, + logger=None, + datafolder=None, + on_backup_start=None, + on_backup_done=None, + on_backup_error=None, + ): + exclude_by_default = ( + "generated", + "logs", + "watched", + ) + + try: + if exclude is None: + exclude = [] + if not isinstance(exclude, list): + exclude = list(exclude) + + if "timelapse" in exclude: + exclude.append("timelapse_tmp") + + current_excludes = list(exclude) + additional_excludes = list() + plugin_data = settings.global_get_basefolder("data") + for plugin, hook in plugin_manager.get_hooks( + "octoprint.plugin.backup.additional_excludes" + ).items(): + try: + additional = hook(current_excludes) + if isinstance(additional, list): + if "." in additional: + current_excludes.append(os.path.join("data", plugin)) + additional_excludes.append(os.path.join(plugin_data, plugin)) + else: + current_excludes += map( + lambda x: os.path.join("data", plugin, x), additional + ) + additional_excludes += map( + lambda x: os.path.join(plugin_data, plugin, x), additional + ) + except Exception: + logger.exception( + "Error while retrieving additional excludes " + "from plugin {name}".format(**locals()), + extra={"plugin": plugin}, + ) + + configfile = settings._configfile + basedir = settings._basedir + + temporary_path = os.path.join(datafolder, ".{}".format(name)) + final_path = os.path.join(datafolder, name) + + own_folder = datafolder + defaults = [os.path.join(basedir, "config.yaml"),] + [ + os.path.join(basedir, folder) + for folder in default_settings["folder"].keys() + ] + + # check how many bytes we are about to backup + size = os.stat(configfile).st_size + for folder in default_settings["folder"].keys(): + if folder in exclude or folder in exclude_by_default: + continue + size += cls._get_disk_size( + settings.global_get_basefolder(folder), + ignored=[ + own_folder, + ], + ) + size += cls._get_disk_size( + basedir, + ignored=defaults + + [ + own_folder, + ], + ) + + # since we can't know the compression ratio beforehand, we assume we need the same amount of space + if not cls._free_space(os.path.dirname(temporary_path), size): + raise InsufficientSpace() + + compression = zipfile.ZIP_DEFLATED if zlib else zipfile.ZIP_STORED + + if callable(on_backup_start): + on_backup_start(name, temporary_path, exclude) + + with zipfile.ZipFile( + temporary_path, mode="w", compression=compression, allowZip64=True + ) as zip: + + def add_to_zip(source, target, ignored=None): + if ignored is None: + ignored = [] + + if source in ignored: + return + + if os.path.isdir(source): + for entry in scandir(source): + add_to_zip( + entry.path, + os.path.join(target, entry.name), + ignored=ignored, + ) + elif os.path.isfile(source): + zip.write(source, arcname=target) + + # add metadata + metadata = { + "version": get_octoprint_version_string(), + "excludes": exclude, + } + zip.writestr("metadata.json", json.dumps(metadata)) + + # backup current config file + add_to_zip( + configfile, + "basedir/config.yaml", + ignored=[ + own_folder, + ], + ) + + # backup configured folder paths + for folder in default_settings["folder"].keys(): + if folder in exclude or folder in exclude_by_default: + continue + + add_to_zip( + settings.global_get_basefolder(folder), + "basedir/" + folder.replace("_", "/"), + ignored=[ + own_folder, + ] + + additional_excludes, + ) + + # backup anything else that might be lying around in our basedir + add_to_zip( + basedir, + "basedir", + ignored=defaults + + [ + own_folder, + ] + + additional_excludes, + ) + + # add list of installed plugins + plugins = [] + plugin_folder = settings.global_get_basefolder("plugins") + for key, plugin in plugin_manager.plugins.items(): + if plugin.bundled or ( + isinstance(plugin.origin, FolderOrigin) + and plugin.origin.folder == plugin_folder + ): + # ignore anything bundled or from the plugins folder we already include in the backup + continue + + plugins.append( + {"key": plugin.key, "name": plugin.name, "url": plugin.url} + ) + + if len(plugins): + zip.writestr("plugin_list.json", json.dumps(plugins)) + + shutil.move(temporary_path, final_path) + + if callable(on_backup_done): + on_backup_done(name, final_path, exclude) + + except Exception as exc: ## noqa: F841 + # TODO py3: use the exception, not sys.exc_info() + if callable(on_backup_error): + exc_info = sys.exc_info() + try: + on_backup_error(name, exc_info) + finally: + del exc_info + raise + + @classmethod + def _restore_backup( + cls, + path, + settings=None, + plugin_manager=None, + datafolder=None, + on_install_plugins=None, + on_report_unknown_plugins=None, + on_invalid_backup=None, + on_log_progress=None, + on_log_error=None, + on_restore_start=None, + on_restore_done=None, + on_restore_failed=None, + ): + if not cls._restore_supported(settings): + if callable(on_log_error): + on_log_error("Restore is not supported on this operating system") + if callable(on_restore_failed): + on_restore_failed(path) + return False + + restart_command = settings.global_get( + ["server", "commands", "serverRestartCommand"] + ) + + basedir = settings._basedir + cls._clean_dir_backup(basedir, on_log_progress=on_log_progress) + + plugin_repo = {} + repo_url = settings.global_get(["plugins", "pluginmanager", "repository"]) + if repo_url: + plugin_repo = cls._get_plugin_repository_data(repo_url) + + if callable(on_restore_start): + on_restore_start(path) + + try: + + with zipfile.ZipFile(path, "r") as zip: + # read metadata + try: + metadata_zipinfo = zip.getinfo("metadata.json") + except KeyError: + if callable(on_invalid_backup): + on_invalid_backup("Not an OctoPrint backup, lacks metadata.json") + if callable(on_restore_failed): + on_restore_failed(path) + return False + + metadata_bytes = zip.read(metadata_zipinfo) + metadata = json.loads(metadata_bytes) + + backup_version = get_comparable_version(metadata["version"], base=True) + if backup_version > get_octoprint_version(base=True): + if callable(on_invalid_backup): + on_invalid_backup( + "Backup is from a newer version of OctoPrint and cannot be applied" + ) + if callable(on_restore_failed): + on_restore_failed(path) + return False + + # unzip to temporary folder + temp = tempfile.mkdtemp() + try: + if callable(on_log_progress): + on_log_progress("Unpacking backup to {}...".format(temp)) + + abstemp = os.path.abspath(temp) + dirs = {} + for member in zip.infolist(): + abspath = os.path.abspath(os.path.join(temp, member.filename)) + if abspath.startswith(abstemp): + date_time = time.mktime(member.date_time + (0, 0, -1)) + + zip.extract(member, temp) + + if os.path.isdir(abspath): + dirs[abspath] = date_time + else: + os.utime(abspath, (date_time, date_time)) + + # set time on folders + for abspath, date_time in dirs.items(): + os.utime(abspath, (date_time, date_time)) + + # sanity check + configfile = os.path.join(temp, "basedir", "config.yaml") + if not os.path.exists(configfile): + if callable(on_invalid_backup): + on_invalid_backup("Backup lacks config.yaml") + if callable(on_restore_failed): + on_restore_failed(path) + return False + + import yaml + + with io.open(configfile, "rt", encoding="utf-8") as f: + configdata = yaml.safe_load(f) + + if configdata.get("accessControl", {}).get("enabled", True): + userfile = os.path.join(temp, "basedir", "users.yaml") + if not os.path.exists(userfile): + if callable(on_invalid_backup): + on_invalid_backup("Backup lacks users.yaml") + if callable(on_restore_failed): + on_restore_failed(path) + return False + + if callable(on_log_progress): + on_log_progress("Unpacked") + + # install available plugins + plugins = [] + plugin_list_file = os.path.join(temp, "plugin_list.json") + if os.path.exists(plugin_list_file): + with io.open(os.path.join(temp, "plugin_list.json"), "rb") as f: + plugins = json.load(f) + + known_plugins = [] + unknown_plugins = [] + if plugins: + if plugin_repo: + for plugin in plugins: + if plugin["key"] in plugin_manager.plugins: + # already installed + continue + + if plugin["key"] in plugin_repo: + # not installed, can be installed from repository url + known_plugins.append(plugin_repo[plugin["key"]]) + else: + # not installed, not installable + unknown_plugins.append(plugin) + + else: + # no repo, all plugins are not installable + unknown_plugins = plugins + + if callable(on_log_progress): + if known_plugins: + on_log_progress( + "Known and installable plugins: {}".format( + ", ".join(map(lambda x: x["id"], known_plugins)) + ) + ) + if unknown_plugins: + on_log_progress( + "Unknown plugins: {}".format( + ", ".join( + map(lambda x: x["key"], unknown_plugins) + ) + ) + ) + + if callable(on_install_plugins): + on_install_plugins(known_plugins) + + if callable(on_report_unknown_plugins): + on_report_unknown_plugins(unknown_plugins) + + # move config data + basedir_backup = basedir + ".bck" + basedir_extracted = os.path.join(temp, "basedir") + + if callable(on_log_progress): + on_log_progress( + "Renaming {} to {}...".format(basedir, basedir_backup) + ) + shutil.move(basedir, basedir_backup) + + try: + if callable(on_log_progress): + on_log_progress( + "Moving {} to {}...".format(basedir_extracted, basedir) + ) + shutil.move(basedir_extracted, basedir) + except Exception: + if callable(on_log_error): + on_log_error( + "Error while restoring config data", + exc_info=sys.exc_info(), + ) + on_log_error("Rolling back old config data") + + shutil.move(basedir_backup, basedir) + + if callable(on_restore_failed): + on_restore_failed(path) + return False + + if unknown_plugins: + if callable(on_log_progress): + on_log_progress("Writing info file about unknown plugins") + + if not os.path.isdir(datafolder): + os.makedirs(datafolder) + + unknown_plugins_path = os.path.join( + datafolder, UNKNOWN_PLUGINS_FILE + ) + try: + with io.open(unknown_plugins_path, mode="wb") as f: + f.write(to_bytes(json.dumps(unknown_plugins))) + except Exception: + if callable(on_log_error): + on_log_error( + "Could not persist list of unknown plugins to {}".format( + unknown_plugins_path + ), + exc_info=sys.exc_info(), + ) + + finally: + if callable(on_log_progress): + on_log_progress("Removing temporary unpacked folder") + shutil.rmtree(temp) + + except Exception: + exc_info = sys.exc_info() + try: + if callable(on_log_error): + on_log_error("Error while running restore", exc_info=exc_info) + if callable(on_restore_failed): + on_restore_failed(path) + finally: + del exc_info + return False + + finally: + # remove zip + if callable(on_log_progress): + on_log_progress("Removing temporary zip") + os.remove(path) + + # restart server + if not restart_command: + restart_command = ( + configdata.get("server", {}) + .get("commands", {}) + .get("serverRestartCommand") + ) + + if restart_command: + import sarge + + if callable(on_log_progress): + on_log_progress("Restarting...") + if callable(on_restore_done): + on_restore_done(path) + + try: + sarge.run(restart_command, close_fds=True, async_=True) + except Exception: + if callable(on_log_error): + on_log_error( + "Error while restarting via command {}".format(restart_command), + exc_info=sys.exc_info(), + ) + on_log_error("Please restart OctoPrint manually") + return False + + else: + if callable(on_restore_done): + on_restore_done(path) + if callable(on_log_error): + on_log_error( + "No restart command configured. Please restart OctoPrint manually." + ) + + return True + + @classmethod + def _restore_supported(cls, settings): + return ( + is_os_compatible(["!windows"]) + and not settings.get_boolean(["restore_unsupported"]) + and not os.environ.get("OCTOPRINT_BACKUP_RESTORE_UNSUPPORTED", False) + in valid_boolean_trues + ) + + def _send_client_message(self, message, payload=None): + if payload is None: + payload = {} + payload["type"] = message + self._plugin_manager.send_plugin_message(self._identifier, payload) + class InsufficientSpace(Exception): - pass + pass + def _register_custom_events(*args, **kwargs): - return ["backup_created"] + return ["backup_created"] + __plugin_name__ = "Backup & Restore" __plugin_author__ = "Gina Häußge" __plugin_description__ = "Backup & restore your OctoPrint settings and data" -__plugin_disabling_discouraged__ = gettext("Without this plugin you will no longer be able to backup " - "& restore your OctoPrint settings and data.") +__plugin_disabling_discouraged__ = gettext( + "Without this plugin you will no longer be able to backup " + "& restore your OctoPrint settings and data." +) __plugin_license__ = "AGPLv3" __plugin_pythoncompat__ = ">=2.7,<4" __plugin_implementation__ = BackupPlugin() __plugin_hooks__ = { - "octoprint.server.http.routes": __plugin_implementation__.route_hook, - "octoprint.server.http.bodysize": __plugin_implementation__.bodysize_hook, - "octoprint.cli.commands": __plugin_implementation__.cli_commands_hook, - "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions, - "octoprint.events.register_custom_events": _register_custom_events, - "octoprint.server.sockjs.emit": __plugin_implementation__.socket_emit_hook + "octoprint.server.http.routes": __plugin_implementation__.route_hook, + "octoprint.server.http.bodysize": __plugin_implementation__.bodysize_hook, + "octoprint.cli.commands": __plugin_implementation__.cli_commands_hook, + "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions, + "octoprint.events.register_custom_events": _register_custom_events, + "octoprint.server.sockjs.emit": __plugin_implementation__.socket_emit_hook, } diff --git a/src/octoprint/plugins/corewizard/__init__.py b/src/octoprint/plugins/corewizard/__init__.py index e275b340a..c37a2eb6f 100644 --- a/src/octoprint/plugins/corewizard/__init__.py +++ b/src/octoprint/plugins/corewizard/__init__.py @@ -1,7 +1,7 @@ # -*- 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import octoprint.plugin @@ -10,116 +10,130 @@ from flask_babel import gettext from .subwizards import Subwizards -class CoreWizardPlugin(octoprint.plugin.AssetPlugin, - octoprint.plugin.TemplatePlugin, - octoprint.plugin.WizardPlugin, - octoprint.plugin.SettingsPlugin, - octoprint.plugin.BlueprintPlugin, - Subwizards): +class CoreWizardPlugin( + octoprint.plugin.AssetPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.WizardPlugin, + octoprint.plugin.SettingsPlugin, + octoprint.plugin.BlueprintPlugin, + Subwizards, +): - #~~ TemplatePlugin API + # ~~ TemplatePlugin API - def get_template_configs(self): - required = self._get_subwizard_attrs("_is_", "_wizard_required") - names = self._get_subwizard_attrs("_get_", "_wizard_name") - additional = self._get_subwizard_attrs("_get_", "_additional_wizard_template_data") + def get_template_configs(self): + required = self._get_subwizard_attrs("_is_", "_wizard_required") + names = self._get_subwizard_attrs("_get_", "_wizard_name") + additional = self._get_subwizard_attrs( + "_get_", "_additional_wizard_template_data" + ) - firstrunonly = self._get_subwizard_attrs("_is_", "_wizard_firstrunonly") - firstrun = self._settings.global_get(["server", "firstRun"]) + firstrunonly = self._get_subwizard_attrs("_is_", "_wizard_firstrunonly") + firstrun = self._settings.global_get(["server", "firstRun"]) - if not firstrun: - required = dict((key, value) for key, value in required.items() - if not firstrunonly.get(key, lambda: False)()) + if not firstrun: + required = dict( + (key, value) + for key, value in required.items() + if not firstrunonly.get(key, lambda: False)() + ) - result = list() - for key, method in required.items(): - if not callable(method): - continue + result = list() + for key, method in required.items(): + if not callable(method): + continue - if not method(): - continue + if not method(): + continue - if not key in names: - continue + if not key in names: + continue - name = names[key]() - if not name: - continue + name = names[key]() + if not name: + continue - config = {"type": "wizard", - "name": name, - "template": "corewizard_{}_wizard.jinja2".format(key), - "div": "wizard_plugin_corewizard_{}".format(key), - "suffix": "_{}".format(key)} - if key in additional: - additional_result = additional[key]() - if additional_result: - config.update(additional_result) - result.append(config) + config = { + "type": "wizard", + "name": name, + "template": "corewizard_{}_wizard.jinja2".format(key), + "div": "wizard_plugin_corewizard_{}".format(key), + "suffix": "_{}".format(key), + } + if key in additional: + additional_result = additional[key]() + if additional_result: + config.update(additional_result) + result.append(config) - return result + return result - #~~ AssetPlugin API + # ~~ AssetPlugin API - def get_assets(self): - if self.is_wizard_required(): - return {"js": ["js/corewizard.js"], - "css": ["css/corewizard.css"]} - else: - return {} + def get_assets(self): + if self.is_wizard_required(): + return {"js": ["js/corewizard.js"], "css": ["css/corewizard.css"]} + else: + return {} - #~~ WizardPlugin API + # ~~ WizardPlugin API - def is_wizard_required(self): - required = self._get_subwizard_attrs("_is_", "_wizard_required") - firstrunonly = self._get_subwizard_attrs("_is_", "_wizard_firstrunonly") - firstrun = self._settings.global_get(["server", "firstRun"]) + def is_wizard_required(self): + required = self._get_subwizard_attrs("_is_", "_wizard_required") + firstrunonly = self._get_subwizard_attrs("_is_", "_wizard_firstrunonly") + firstrun = self._settings.global_get(["server", "firstRun"]) - if not firstrun: - required = dict((key, value) for key, value in required.items() - if not firstrunonly.get(key, lambda: False)()) - any_required = any(map(lambda m: m(), required.values())) + if not firstrun: + required = dict( + (key, value) + for key, value in required.items() + if not firstrunonly.get(key, lambda: False)() + ) + any_required = any(map(lambda m: m(), required.values())) - return any_required + return any_required - def get_wizard_details(self): - result = {} + def get_wizard_details(self): + result = {} - def add_result(key, method): - result[key] = method() - self._get_subwizard_attrs("_get_", "_wizard_details", add_result) + def add_result(key, method): + result[key] = method() - return result + self._get_subwizard_attrs("_get_", "_wizard_details", add_result) - def get_wizard_version(self): - return 3 + return result - #~~ helpers + def get_wizard_version(self): + return 3 - def _get_subwizard_attrs(self, start, end, callback=None): - result = {} + # ~~ helpers - for item in dir(self): - if not item.startswith(start) or not item.endswith(end): - continue + def _get_subwizard_attrs(self, start, end, callback=None): + result = {} - key = item[len(start):-len(end)] - if not key: - continue + for item in dir(self): + if not item.startswith(start) or not item.endswith(end): + continue - attr = getattr(self, item) - if callable(callback): - callback(key, attr) - result[key] = attr + key = item[len(start) : -len(end)] + if not key: + continue - return result + attr = getattr(self, item) + if callable(callback): + callback(key, attr) + result[key] = attr + + return result __plugin_name__ = "Core Wizard" __plugin_author__ = "Gina Häußge" __plugin_description__ = "Provides wizard dialogs for core components and functionality" -__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to perform " - "setup steps that might be required after an update.") +__plugin_disabling_discouraged__ = gettext( + "Without this plugin OctoPrint will no longer be able to perform " + "setup steps that might be required after an update." +) __plugin_license__ = "AGPLv3" __plugin_pythoncompat__ = ">=2.7,<4" __plugin_implementation__ = CoreWizardPlugin() diff --git a/src/octoprint/plugins/corewizard/subwizards.py b/src/octoprint/plugins/corewizard/subwizards.py index e695ea9c3..f7061da1d 100644 --- a/src/octoprint/plugins/corewizard/subwizards.py +++ b/src/octoprint/plugins/corewizard/subwizards.py @@ -1,7 +1,7 @@ # -*- 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import octoprint.plugin @@ -14,139 +14,170 @@ from octoprint.util import to_native_str # noinspection PyUnresolvedReferences,PyMethodMayBeStatic class ServerCommandsSubwizard(object): - def _is_servercommands_wizard_firstrunonly(self): - return True + def _is_servercommands_wizard_firstrunonly(self): + return True - def _is_servercommands_wizard_required(self): - system_shutdown_command = self._settings.global_get(["server", "commands", "systemShutdownCommand"]) - system_restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"]) - server_restart_command = self._settings.global_get(["server", "commands", "serverRestartCommand"]) + def _is_servercommands_wizard_required(self): + system_shutdown_command = self._settings.global_get( + ["server", "commands", "systemShutdownCommand"] + ) + system_restart_command = self._settings.global_get( + ["server", "commands", "systemRestartCommand"] + ) + server_restart_command = self._settings.global_get( + ["server", "commands", "serverRestartCommand"] + ) - return not (system_shutdown_command and system_restart_command and server_restart_command) + return not ( + system_shutdown_command and system_restart_command and server_restart_command + ) - def _get_servercommands_wizard_details(self): - return {"required": self._is_servercommands_wizard_required()} + def _get_servercommands_wizard_details(self): + return {"required": self._is_servercommands_wizard_required()} - def _get_servercommands_wizard_name(self): - return gettext("Server Commands") + def _get_servercommands_wizard_name(self): + return gettext("Server Commands") # noinspection PyUnresolvedReferences,PyMethodMayBeStatic class WebcamSubwizard(object): - def _is_webcam_wizard_firstrunonly(self): - return True + def _is_webcam_wizard_firstrunonly(self): + return True - def _is_webcam_wizard_required(self): - webcam_snapshot_url = self._settings.global_get(["webcam", "snapshot"]) - webcam_stream_url = self._settings.global_get(["webcam", "stream"]) - ffmpeg_path = self._settings.global_get(["webcam", "ffmpeg"]) + def _is_webcam_wizard_required(self): + webcam_snapshot_url = self._settings.global_get(["webcam", "snapshot"]) + webcam_stream_url = self._settings.global_get(["webcam", "stream"]) + ffmpeg_path = self._settings.global_get(["webcam", "ffmpeg"]) - return not (webcam_snapshot_url and webcam_stream_url and ffmpeg_path) + return not (webcam_snapshot_url and webcam_stream_url and ffmpeg_path) - def _get_webcam_wizard_details(self): - return {"required": self._is_webcam_wizard_required()} + def _get_webcam_wizard_details(self): + return {"required": self._is_webcam_wizard_required()} - def _get_webcam_wizard_name(self): - return gettext("Webcam & Timelapse") + def _get_webcam_wizard_name(self): + return gettext("Webcam & Timelapse") # noinspection PyUnresolvedReferences,PyMethodMayBeStatic class AclSubwizard(object): - def _is_acl_wizard_firstrunonly(self): - return True + def _is_acl_wizard_firstrunonly(self): + return True - def _is_acl_wizard_required(self): - return self._user_manager.enabled and not self._user_manager.has_been_customized() + def _is_acl_wizard_required(self): + return self._user_manager.enabled and not self._user_manager.has_been_customized() - def _get_acl_wizard_details(self): - return {"required": self._is_acl_wizard_required()} + def _get_acl_wizard_details(self): + return {"required": self._is_acl_wizard_required()} - def _get_acl_wizard_name(self): - return gettext("Access Control") + def _get_acl_wizard_name(self): + return gettext("Access Control") - def _get_acl_additional_wizard_template_data(self): - return {"mandatory": self._is_acl_wizard_required()} + def _get_acl_additional_wizard_template_data(self): + return {"mandatory": self._is_acl_wizard_required()} - @octoprint.plugin.BlueprintPlugin.route("/acl", methods=["POST"]) - def acl_wizard_api(self): - from flask import request, abort - from octoprint.server.api import valid_boolean_trues, NO_CONTENT + @octoprint.plugin.BlueprintPlugin.route("/acl", methods=["POST"]) + def acl_wizard_api(self): + from flask import request, abort + from octoprint.server.api import valid_boolean_trues, NO_CONTENT - if not self._settings.global_get(["server", "firstRun"]) or self._user_manager.has_been_customized(): - abort(404) + if ( + not self._settings.global_get(["server", "firstRun"]) + or self._user_manager.has_been_customized() + ): + abort(404) - data = request.get_json() - if data is None: - data = request.values + data = request.get_json() + if data is None: + data = request.values - if "ac" in data and data["ac"] in valid_boolean_trues and \ - "user" in data and "pass1" in data and \ - "pass2" in data and data["pass1"] == data["pass2"]: - # configure access control - self._settings.global_set_boolean(["accessControl", "enabled"], True) - self._user_manager.enable() + if ( + "ac" in data + and data["ac"] in valid_boolean_trues + and "user" in data + and "pass1" in data + and "pass2" in data + and data["pass1"] == data["pass2"] + ): + # configure access control + self._settings.global_set_boolean(["accessControl", "enabled"], True) + self._user_manager.enable() - self._user_manager.add_user(data["user"], data["pass1"], True, [], [USER_GROUP, ADMIN_GROUP], overwrite=True) - elif "ac" in data and not data["ac"] in valid_boolean_trues: - # disable access control - self._settings.global_set_boolean(["accessControl", "enabled"], False) - self._user_manager.disable() - self._settings.save() - return NO_CONTENT + self._user_manager.add_user( + data["user"], + data["pass1"], + True, + [], + [USER_GROUP, ADMIN_GROUP], + overwrite=True, + ) + elif "ac" in data and not data["ac"] in valid_boolean_trues: + # disable access control + self._settings.global_set_boolean(["accessControl", "enabled"], False) + self._user_manager.disable() + self._settings.save() + return NO_CONTENT # noinspection PyUnresolvedReferences,PyMethodMayBeStatic class OnlineCheckSubwizard(object): - def _is_onlinecheck_wizard_firstrunonly(self): - return False + def _is_onlinecheck_wizard_firstrunonly(self): + return False - def _is_onlinecheck_wizard_required(self): - return self._settings.global_get(["server", "onlineCheck", "enabled"]) is None + def _is_onlinecheck_wizard_required(self): + return self._settings.global_get(["server", "onlineCheck", "enabled"]) is None - def _get_onlinecheck_wizard_details(self): - return {"required": self._is_onlinecheck_wizard_required()} + def _get_onlinecheck_wizard_details(self): + return {"required": self._is_onlinecheck_wizard_required()} - def _get_onlinecheck_wizard_name(self): - return gettext("Online Connectivity Check") + def _get_onlinecheck_wizard_name(self): + return gettext("Online Connectivity Check") - def _get_onlinecheck_additional_wizard_template_data(self): - return {"mandatory": self._is_onlinecheck_wizard_required()} + def _get_onlinecheck_additional_wizard_template_data(self): + return {"mandatory": self._is_onlinecheck_wizard_required()} # noinspection PyUnresolvedReferences,PyMethodMayBeStatic class PluginBlacklistSubwizard(object): - def _is_pluginblacklist_wizard_firstrunonly(self): - return False + def _is_pluginblacklist_wizard_firstrunonly(self): + return False - def _is_pluginblacklist_wizard_required(self): - return self._settings.global_get(["server", "pluginBlacklist", "enabled"]) is None + def _is_pluginblacklist_wizard_required(self): + return self._settings.global_get(["server", "pluginBlacklist", "enabled"]) is None - def _get_pluginblacklist_wizard_details(self): - return {"required": self._is_pluginblacklist_wizard_required()} + def _get_pluginblacklist_wizard_details(self): + return {"required": self._is_pluginblacklist_wizard_required()} - def _get_pluginblacklist_wizard_name(self): - return gettext("Plugin Blacklist") + def _get_pluginblacklist_wizard_name(self): + return gettext("Plugin Blacklist") - def _get_pluginblacklist_additional_wizard_template_data(self): - return {"mandatory": self._is_pluginblacklist_wizard_required()} + def _get_pluginblacklist_additional_wizard_template_data(self): + return {"mandatory": self._is_pluginblacklist_wizard_required()} # noinspection PyUnresolvedReferences,PyMethodMayBeStatic class PrinterProfileSubwizard(object): - def _is_printerprofile_wizard_firstrunonly(self): - return True + def _is_printerprofile_wizard_firstrunonly(self): + return True - def _is_printerprofile_wizard_required(self): - return self._printer_profile_manager.is_default_unmodified() and self._printer_profile_manager.profile_count == 1 + def _is_printerprofile_wizard_required(self): + return ( + self._printer_profile_manager.is_default_unmodified() + and self._printer_profile_manager.profile_count == 1 + ) - def _get_printerprofile_wizard_details(self): - return {"required": self._is_printerprofile_wizard_required()} + def _get_printerprofile_wizard_details(self): + return {"required": self._is_printerprofile_wizard_required()} - def _get_printerprofile_wizard_name(self): - return gettext("Default Printer Profile") + def _get_printerprofile_wizard_name(self): + return gettext("Default Printer Profile") -Subwizards = type(to_native_str("Subwizards"), - tuple(cls for clsname, cls in inspect.getmembers(sys.modules[__name__], inspect.isclass) - if clsname.endswith("Subwizard")), - {}) +Subwizards = type( + to_native_str("Subwizards"), + tuple( + cls + for clsname, cls in inspect.getmembers(sys.modules[__name__], inspect.isclass) + if clsname.endswith("Subwizard") + ), + {}, +) diff --git a/src/octoprint/plugins/discovery/__init__.py b/src/octoprint/plugins/discovery/__init__.py index def966ddd..409570894 100644 --- a/src/octoprint/plugins/discovery/__init__.py +++ b/src/octoprint/plugins/discovery/__init__.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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" """ @@ -21,680 +21,800 @@ import octoprint.plugin import octoprint.util try: - # python 3 - import zeroconf + # python 3 + import zeroconf except ImportError: - # python 2: vendored version with some backported fixes - import octoprint.vendor.zeroconf as zeroconf + # python 2: vendored version with some backported fixes + import octoprint.vendor.zeroconf as zeroconf import time import collections import socket import platform + def __plugin_load__(): - plugin = DiscoveryPlugin() - - global __plugin_implementation__ - __plugin_implementation__ = plugin - - global __plugin_helpers__ - __plugin_helpers__ = {"ssdp_browse": plugin.ssdp_browse, - "zeroconf_browse": plugin.zeroconf_browse, - "zeroconf_register": plugin.zeroconf_register, - "zeroconf_unregister": plugin.zeroconf_unregister} - -class DiscoveryPlugin(octoprint.plugin.StartupPlugin, - octoprint.plugin.ShutdownPlugin, - octoprint.plugin.BlueprintPlugin, - octoprint.plugin.SettingsPlugin): - - ssdp_multicast_addr = "239.255.255.250" # IPv6: ff0X::c - - ssdp_multicast_port = 1900 - - ssdp_server = "{}/{} UPnP/1.0 OctoPrint/{}".format(platform.system(), - platform.version(), - octoprint.__version__) - - # noinspection PyMissingConstructor - def __init__(self): - self.host = None - self.port = None - - # zeroconf - self._zeroconf = zeroconf.Zeroconf() - self._zeroconf_registrations = collections.defaultdict(list) - - # upnp/ssdp - self._ssdp_monitor_active = False - self._ssdp_monitor_thread = None - self._ssdp_notify_timeout = 30 - self._ssdp_last_notify = 0 - - ##~~ SettingsPlugin API - - def get_settings_defaults(self): - return { - "publicHost": None, - "publicPort": None, - "pathPrefix": None, - "httpUsername": None, - "httpPassword": None, - "upnpUuid": None, - "zeroConf": [], - "model": { - "name": None, - "description": None, - "number": None, - "url": None, - "serial": None, - "vendor": None, - "vendorUrl": None - } - } - - ##~~ BlueprintPlugin API -- used for providing the SSDP device descriptor XML - - @octoprint.plugin.BlueprintPlugin.route("/discovery.xml", methods=["GET"]) - def discovery(self): - self._logger.debug("Rendering discovery.xml") - - modelName = self._settings.get(["model", "name"]) - if not modelName: - import octoprint.server - modelName = octoprint.server.DISPLAY_VERSION - - vendor = self._settings.get(["model", "vendor"]) - vendorUrl = self._settings.get(["model", "vendorUrl"]) - if not vendor: - vendor = "The OctoPrint Project" - vendorUrl = "http://www.octoprint.org/" - - response = flask.make_response(flask.render_template("discovery.xml.jinja2", - friendlyName=self.get_instance_name(), - manufacturer=vendor, - manufacturerUrl=vendorUrl, - modelName=modelName, - modelDescription=self._settings.get(["model", "description"]), - modelNumber=self._settings.get(["model", "number"]), - modelUrl=self._settings.get(["model", "url"]), - serialNumber=self._settings.get(["model", "serial"]), - uuid=self.get_uuid(), - presentationUrl=flask.url_for("index", _external=True))) - response.headers['Content-Type'] = 'application/xml' - return response - - def is_blueprint_protected(self): - return False - - ##~~ StartupPlugin API -- used for registering OctoPrint's Zeroconf and SSDP services upon application startup - - def on_startup(self, host, port): - public_host = self._settings.get(["publicHost"]) - if public_host: - host = public_host - public_port = self._settings.get(["publicPort"]) - if public_port: - port = public_port - - self.host = host - self.port = port - - # Zeroconf - instance_name = self.get_instance_name() - self.zeroconf_register("_http._tcp", instance_name, txt_record=self._create_http_txt_record_dict()) - self.zeroconf_register("_octoprint._tcp", instance_name, txt_record=self._create_octoprint_txt_record_dict()) - for zc in self._settings.get(["zeroConf"]): - if "service" in zc: - self.zeroconf_register(zc["service"], - zc.get("name", instance_name), - port=zc.get("port"), - txt_record=zc.get("txtRecord")) - - # SSDP - self._ssdp_register() - - ##~~ ShutdownPlugin API -- used for unregistering OctoPrint's Zeroconf and SSDP service upon application shutdown - - def on_shutdown(self): - registrations = list(self._zeroconf_registrations.keys()) - for key in registrations: - reg_type, port = key - self.zeroconf_unregister(reg_type, port) - - self._ssdp_unregister() - - ##~~ helpers - - # ZeroConf - - def _format_zeroconf_service_type(self, service_type): - service_type = octoprint.util.to_native_str(service_type) - if not service_type.endswith(octoprint.util.to_native_str(".")): - service_type += octoprint.util.to_native_str(".") - if not service_type.endswith(octoprint.util.to_native_str("local.")): - service_type += octoprint.util.to_native_str("local.") - return service_type - - def _format_zeroconf_name(self, name, service_type): - service_type = self._format_zeroconf_service_type(service_type) - return octoprint.util.to_native_str(name) + octoprint.util.to_native_str(".") + service_type - - def _format_zeroconf_txt(self, record): - result = {} - if not record: - return result - - for key, value in record.items(): - result[octoprint.util.to_bytes(key)] = octoprint.util.to_bytes(value) - return result - - def zeroconf_register(self, reg_type, name=None, port=None, txt_record=None): - """ - Registers a new service with Zeroconf/Bonjour/Avahi. - - :param reg_type: type of service to register, e.g. "_gntp._tcp" - :param name: displayable name of the service, if not given defaults to the OctoPrint instance name - :param port: port to register for the service, if not given defaults to OctoPrint's (public) port - :param txt_record: optional txt record to attach to the service, dictionary of key-value-pairs - """ - - if not name: - name = self.get_instance_name() - if not port: - port = self.port - - reg_type = self._format_zeroconf_service_type(reg_type) - name = self._format_zeroconf_name(name, reg_type) - txt_record = self._format_zeroconf_txt(txt_record) - - key = (reg_type, port) - addresses = list(map(lambda x: socket.inet_aton(x), octoprint.util.net.interface_addresses())) - - try: - info = zeroconf.ServiceInfo(reg_type, name, - addresses=addresses, - port=port, - server="{}.local.".format(socket.gethostname()), - properties=txt_record) - self._zeroconf.register_service(info, allow_name_change=True) - self._zeroconf_registrations[key].append(info) - self._logger.info("Registered '{}' for {}".format(name, reg_type)) - except Exception: - self._logger.exception("Could not register {} for {} on port {}".format(name, reg_type, port)) - - def zeroconf_unregister(self, reg_type, port=None): - """ - Unregisters a previously registered Zeroconf/Bonjour/Avahi service identified by service and port. - - :param reg_type: the type of the service to be unregistered - :param port: the port of the service to be unregistered, defaults to OctoPrint's (public) port if not given - :return: - """ - - if not port: - port = self.port - reg_type = self._format_zeroconf_service_type(reg_type) - - key = (reg_type, port) - if not key in self._zeroconf_registrations: - return - - infos = self._zeroconf_registrations.pop(key) - try: - for info in infos: - self._zeroconf.unregister_service(info) - self._logger.debug("Unregistered {} on port {}".format(reg_type, port)) - except: - self._logger.exception("Could not (fully) unregister {} on port {}".format(reg_type, port)) - - def zeroconf_browse(self, service_type, block=True, callback=None, browse_timeout=5, resolve_timeout=5): - """ - Browses for services on the local network providing the specified service type. Can be used either blocking or - non-blocking. - - The non-blocking version (default behaviour) will not return until the lookup has completed and - return all results that were found. - - For non-blocking version, set `block` to `False` and provide a `callback` to be called once the lookup completes. - If no callback is provided in non-blocking mode, a ValueError will be raised. - - The results are provided as a list of discovered services, with each service being described by a dictionary - with the following keys: - - * `name`: display name of the service - * `host`: host name of the service - * `post`: port the service is listening on - * `txt_record`: TXT record of the service as a dictionary, exact contents depend on the service - - Callbacks will be called with that list as the single parameter supplied to them. Thus, the following is an - example for a valid callback: - - def browse_callback(results): - for result in results: - print "Name: {name}, Host: {host}, Port: {port}, TXT: {txt_record!r}".format(**result) - - :param service_type: the service type to browse for - :param block: whether to block, defaults to True - :param callback: callback to call once lookup has completed, must be set when `block` is set to `False` - :param browse_timeout: timeout for browsing operation - :param resolve_timeout: timeout for resolving operations for discovered records - :return: if `block` is `True` a list of the discovered services, an empty list otherwise (results will then be - supplied to the callback instead) - """ - - import threading - - if not block and not callback: - raise ValueError("Non-blocking mode but no callback given") - - service_type = self._format_zeroconf_service_type(service_type) - - result = [] - result_available = threading.Event() - result_available.clear() - - class ZeroconfListener(object): - def __init__(self, logger): - self._logger = logger - - def add_service(self, zeroconf, type, name): - self._logger.debug("Got a browsing result for Zeroconf resolution of {}, resolving...".format(type)) - info = zeroconf.get_service_info(type, name, timeout=resolve_timeout * 1000) - if info: - def to_result(info, address): - n = info.name[:-(len(type) + 1)] - p = info.port - - self._logger.debug("Resolved a result for Zeroconf resolution of {}: {} @ {}:{}".format(type, - n, - address, - p)) - - return {"name": n, - "host": address, - "port": p, - "txt_record": info.properties} - - for address in map(lambda x: socket.inet_ntoa(x), info.addresses): - result.append(to_result(info, address)) - - self._logger.debug("Browsing Zeroconf for {service_type}".format(service_type=service_type)) - - def browse(): - listener = ZeroconfListener(self._logger) - browser = zeroconf.ServiceBrowser(self._zeroconf, service_type, listener) - time.sleep(browse_timeout) - browser.cancel() - - if callback: - callback(result) - result_available.set() - - browse_thread = threading.Thread(target=browse) - browse_thread.daemon = True - browse_thread.start() - - if block: - result_available.wait() - return result - else: - return [] - - # SSDP/UPNP - - def ssdp_browse(self, query, block=True, callback=None, timeout=1, retries=5): - """ - Browses for UPNP services matching the supplied query. Can be used either blocking or - non-blocking. - - The non-blocking version (default behaviour) will not return until the lookup has completed and - return all results that were found. - - For non-blocking version, set `block` to `False` and provide a `callback` to be called once the lookup completes. - If no callback is provided in non-blocking mode, a ValueError will be raised. - - The results are provided as a list of discovered locations of device descriptor files. - - Callbacks will be called with that list as the single parameter supplied to them. Thus, the following is an - example for a valid callback: - - def browse_callback(results): - for result in results: - print("Location: {}".format(result)) - - :param query: the SSDP query to send, e.g. "upnp:rootdevice" to search for all devices - :param block: whether to block, defaults to True - :param callback: callback to call in non-blocking mode when lookup has finished, must be set if block is False - :param timeout: timeout in seconds to wait for replies to the M-SEARCH query per interface, defaults to 1 - :param retries: number of retries to perform the lookup on all interfaces, defaults to 5 - :return: if `block` is `True` a list of the discovered devices, an empty list otherwise (results will then be - supplied to the callback instead) - """ - - import threading - import io - - try: - # noinspection PyCompatibility - from http.client import HTTPResponse # py3 - except ImportError: - # noinspection PyCompatibility - from httplib import HTTPResponse # py2 - - class Response(HTTPResponse): - def __init__(self, response_text): - self.fp = io.BytesIO(response_text) - self.debuglevel = 0 - self.strict = 0 - self.msg = None - self._method = None - self.begin() - - result = [] - result_available = threading.Event() - result_available.clear() - - def browse(): - socket.setdefaulttimeout(timeout) - - search_message = "".join([ - "M-SEARCH * HTTP/1.1\r\n", - "ST: {query}\r\n", - "MX: 3\r\n", - "MAN: \"ssdp:discovery\"\r\n", - "HOST: {mcast_addr}:{mcast_port}\r\n\r\n" - ]) - - for _ in range(retries): - for addr in octoprint.util.interface_addresses(): - try: - sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) - sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2) - sock.bind((addr, 0)) - - message = search_message.format(query=query, - mcast_addr=self.__class__.ssdp_multicast_addr, - mcast_port=self.__class__.ssdp_multicast_port) - for _ in range(2): - sock.sendto(message.encode("utf-8"), (self.__class__.ssdp_multicast_addr, self.__class__.ssdp_multicast_port)) - - try: - data = sock.recv(1024) - except socket.timeout: - pass - else: - response = Response(data) - - result.append(response.getheader("Location")) - except Exception: - pass - - if callback: - callback(result) - result_available.set() - - browse_thread = threading.Thread(target=browse) - browse_thread.daemon = True - browse_thread.start() - - if block: - result_available.wait() - return result - else: - return [] - - ##~~ internals - - # Zeroconf - - def _create_http_txt_record_dict(self): - """ - Creates a TXT record for the _http._tcp Zeroconf service supplied by this OctoPrint instance. - - Defines the keys for _http._tcp as defined in http://www.dns-sd.org/txtrecords.html - - :return: a dictionary containing the defined key-value-pairs, ready to be turned into a TXT record - """ - - # determine path entry - path = "/" - if self._settings.get(["pathPrefix"]): - path = self._settings.get(["pathPrefix"]) - else: - prefix = self._settings.global_get(["server", "reverseProxy", "prefixFallback"]) - if prefix: - path = prefix - - # fetch username and password (if set) - username = self._settings.get(["httpUsername"]) - password = self._settings.get(["httpPassword"]) - - entries = {"path": path} - - if username and password: - entries.update({"u": username, "p": password}) - - return entries - - def _create_octoprint_txt_record_dict(self): - """ - Creates a TXT record for the _octoprint._tcp Zeroconf service supplied by this OctoPrint instance. - - The following keys are defined: - - * `path`: path prefix to actual OctoPrint instance, inherited from _http._tcp - * `u`: username if HTTP Basic Auth is used, optional, inherited from _http._tcp - * `p`: password if HTTP Basic Auth is used, optional, inherited from _http._tcp - * `version`: OctoPrint software version - * `api`: OctoPrint API version - * `model`: Model of the device that is running OctoPrint - * `vendor`: Vendor of the device that is running OctoPrint - - :return: a dictionary containing the defined key-value-pairs, ready to be turned into a TXT record - """ - import octoprint.server - import octoprint.server.api - - entries = self._create_http_txt_record_dict() - entries.update( - version=octoprint.server.VERSION, - api=octoprint.server.api.VERSION, - uuid=self.get_uuid() - ) - - modelName = self._settings.get(["model", "name"]) - if modelName: - entries.update(model=modelName) - vendor = self._settings.get(["model", "vendor"]) - if vendor: - entries.update(vendor=vendor) - - return entries - - # SSDP/UPNP - - def _ssdp_register(self): - """ - Registers the OctoPrint instance as basic service with a presentation URL pointing to the web interface - """ - - import threading - - self._ssdp_monitor_active = True - - self._ssdp_monitor_thread = threading.Thread(target=self._ssdp_monitor, - kwargs={"timeout": self._ssdp_notify_timeout}) - self._ssdp_monitor_thread.daemon = True - self._ssdp_monitor_thread.start() - - def _ssdp_unregister(self): - """ - Unregisters the OctoPrint instance again - """ - - self._ssdp_monitor_active = False - if self.host and self.port: - for _ in range(2): - self._ssdp_notify(alive=False) - - def _ssdp_notify(self, alive=True): - """ - Sends an SSDP notify message across the connected networks. - - :param alive: True to send an "ssdp:alive" message, False to send an "ssdp:byebye" message - """ - - if alive and self._ssdp_last_notify + self._ssdp_notify_timeout > octoprint.util.monotonic_time(): - # we just sent an alive, no need to send another one now - return - - if alive and not self._ssdp_monitor_active: - # the monitor already shut down, alive messages don't make sense anymore as byebye will shortly follow - return - - for addr in octoprint.util.interface_addresses(): - try: - sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) - sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2) - sock.bind((addr, 0)) - - location = "http://{addr}:{port}/plugin/discovery/discovery.xml".format(addr=addr, port=self.port) - - self._logger.debug("Sending NOTIFY {} via {}".format("alive" if alive else "byebye", addr)) - notify_message = "".join([ - "NOTIFY * HTTP/1.1\r\n", - "Server: {server}\r\n", - "Cache-Control: max-age=900\r\n", - "Location: {location}\r\n", - "NTS: {nts}\r\n", - "NT: {nt}\r\n", - "USN: {usn}\r\n", - "HOST: {mcast_addr}:{mcast_port}\r\n\r\n" - ]) - uuid = self.get_uuid() - for nt, usn in (("upnp:rootdevice", "uuid:{uuid}::upnp:rootdevice"), - ("uuid:{}", "uuid:{uuid}"), - ("urn:schemas-upnp-org:device:basic:1", "uuid:{uuid}::url:schemas-upnp-org:device:basic:1")): - message = notify_message.format(uuid=uuid, - location=location, - nts="ssdp:alive" if alive else "ssdp:byebye", - nt=nt.format(uuid=uuid), - usn=usn.format(uuid=uuid), - server=self.ssdp_server, - mcast_addr=self.ssdp_multicast_addr, - mcast_port=self.ssdp_multicast_port) - for _ in range(2): - # send twice, stuff might get lost, it's only UDP - sock.sendto(message.encode("utf-8"), (self.ssdp_multicast_addr, self.ssdp_multicast_port)) - except Exception: - pass - - self._ssdp_last_notify = octoprint.util.monotonic_time() - - def _ssdp_monitor(self, timeout=5): - """ - Monitor thread that listens on the multicast address for M-SEARCH requests and answers them if they are relevant - - :param timeout: timeout after which to stop waiting for M-SEARCHs for a short while in order to put out an - alive message - """ - - try: - # noinspection PyCompatibility - from http.server import BaseHTTPRequestHandler - except ImportError: - # noinspection PyCompatibility - from BaseHTTPServer import BaseHTTPRequestHandler - - from io import BytesIO - - socket.setdefaulttimeout(timeout) - - location_message = "".join([ - "HTTP/1.1 200 OK\r\n", - "ST: upnp:rootdevice\r\n", - "USN: uuid:{uuid}::upnp:rootdevice\r\n", - "Location: {location}\r\n", - "Cache-Control: max-age=60\r\n\r\n" - ]) - - class Request(BaseHTTPRequestHandler): - - # noinspection PyMissingConstructor - def __init__(self, request_text): - self.rfile = BytesIO(request_text) - self.raw_requestline = self.rfile.readline() - self.error_code = self.error_message = None - self.parse_request() - - def send_error(self, code, message=None): - self.error_code = code - self.error_message = message - - sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) - sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2) - sock.bind(('', self.__class__.ssdp_multicast_port)) - - sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(self.__class__.ssdp_multicast_addr) + socket.inet_aton('0.0.0.0')) - - self._logger.info("Registered {} for SSDP".format(self.get_instance_name())) - - self._ssdp_notify(alive=True) - - try: - while self._ssdp_monitor_active: - try: - data, address = sock.recvfrom(4096) - request = Request(data) - if not request.error_code and request.command == "M-SEARCH" and request.path == "*" and (request.headers["ST"] == "upnp:rootdevice" or request.headers["ST"] == "ssdp:all") and request.headers["MAN"] == '"ssdp:discover"': - interface_address = octoprint.util.address_for_client(*address) - if not interface_address: - self._logger.warning("Can't determine address to user for client {}, not sending a M-SEARCH reply".format(address)) - continue - message = location_message.format(uuid=self.get_uuid(), - location="http://{host}:{port}/plugin/discovery/discovery.xml".format(host=interface_address, port=self.port)) - sock.sendto(message.encode("utf-8"), address) - self._logger.debug("Sent M-SEARCH reply for {path} and {st} to {address!r}".format(path=request.path, st=request.headers["ST"], address=address)) - except socket.timeout: - pass - finally: - self._ssdp_notify(alive=True) - finally: - try: - sock.close() - except Exception: - pass - - ##~~ helpers - - def get_uuid(self): - upnpUuid = self._settings.get(["upnpUuid"]) - if upnpUuid is None: - import uuid - upnpUuid = str(uuid.uuid4()) - self._settings.set(["upnpUuid"], upnpUuid) - self._settings.save() - return upnpUuid - - def get_instance_name(self): - name = self._settings.global_get(["appearance", "name"]) - if name: - return "OctoPrint instance \"{}\"".format(name) - else: - return "OctoPrint instance on {}".format(socket.gethostname()) + plugin = DiscoveryPlugin() + + global __plugin_implementation__ + __plugin_implementation__ = plugin + + global __plugin_helpers__ + __plugin_helpers__ = { + "ssdp_browse": plugin.ssdp_browse, + "zeroconf_browse": plugin.zeroconf_browse, + "zeroconf_register": plugin.zeroconf_register, + "zeroconf_unregister": plugin.zeroconf_unregister, + } + + +class DiscoveryPlugin( + octoprint.plugin.StartupPlugin, + octoprint.plugin.ShutdownPlugin, + octoprint.plugin.BlueprintPlugin, + octoprint.plugin.SettingsPlugin, +): + + ssdp_multicast_addr = "239.255.255.250" # IPv6: ff0X::c + + ssdp_multicast_port = 1900 + + ssdp_server = "{}/{} UPnP/1.0 OctoPrint/{}".format( + platform.system(), platform.version(), octoprint.__version__ + ) + + # noinspection PyMissingConstructor + def __init__(self): + self.host = None + self.port = None + + # zeroconf + self._zeroconf = zeroconf.Zeroconf() + self._zeroconf_registrations = collections.defaultdict(list) + + # upnp/ssdp + self._ssdp_monitor_active = False + self._ssdp_monitor_thread = None + self._ssdp_notify_timeout = 30 + self._ssdp_last_notify = 0 + + ##~~ SettingsPlugin API + + def get_settings_defaults(self): + return { + "publicHost": None, + "publicPort": None, + "pathPrefix": None, + "httpUsername": None, + "httpPassword": None, + "upnpUuid": None, + "zeroConf": [], + "model": { + "name": None, + "description": None, + "number": None, + "url": None, + "serial": None, + "vendor": None, + "vendorUrl": None, + }, + } + + ##~~ BlueprintPlugin API -- used for providing the SSDP device descriptor XML + + @octoprint.plugin.BlueprintPlugin.route("/discovery.xml", methods=["GET"]) + def discovery(self): + self._logger.debug("Rendering discovery.xml") + + modelName = self._settings.get(["model", "name"]) + if not modelName: + import octoprint.server + + modelName = octoprint.server.DISPLAY_VERSION + + vendor = self._settings.get(["model", "vendor"]) + vendorUrl = self._settings.get(["model", "vendorUrl"]) + if not vendor: + vendor = "The OctoPrint Project" + vendorUrl = "http://www.octoprint.org/" + + response = flask.make_response( + flask.render_template( + "discovery.xml.jinja2", + friendlyName=self.get_instance_name(), + manufacturer=vendor, + manufacturerUrl=vendorUrl, + modelName=modelName, + modelDescription=self._settings.get(["model", "description"]), + modelNumber=self._settings.get(["model", "number"]), + modelUrl=self._settings.get(["model", "url"]), + serialNumber=self._settings.get(["model", "serial"]), + uuid=self.get_uuid(), + presentationUrl=flask.url_for("index", _external=True), + ) + ) + response.headers["Content-Type"] = "application/xml" + return response + + def is_blueprint_protected(self): + return False + + ##~~ StartupPlugin API -- used for registering OctoPrint's Zeroconf and SSDP services upon application startup + + def on_startup(self, host, port): + public_host = self._settings.get(["publicHost"]) + if public_host: + host = public_host + public_port = self._settings.get(["publicPort"]) + if public_port: + port = public_port + + self.host = host + self.port = port + + # Zeroconf + instance_name = self.get_instance_name() + self.zeroconf_register( + "_http._tcp", instance_name, txt_record=self._create_http_txt_record_dict() + ) + self.zeroconf_register( + "_octoprint._tcp", + instance_name, + txt_record=self._create_octoprint_txt_record_dict(), + ) + for zc in self._settings.get(["zeroConf"]): + if "service" in zc: + self.zeroconf_register( + zc["service"], + zc.get("name", instance_name), + port=zc.get("port"), + txt_record=zc.get("txtRecord"), + ) + + # SSDP + self._ssdp_register() + + ##~~ ShutdownPlugin API -- used for unregistering OctoPrint's Zeroconf and SSDP service upon application shutdown + + def on_shutdown(self): + registrations = list(self._zeroconf_registrations.keys()) + for key in registrations: + reg_type, port = key + self.zeroconf_unregister(reg_type, port) + + self._ssdp_unregister() + + ##~~ helpers + + # ZeroConf + + def _format_zeroconf_service_type(self, service_type): + service_type = octoprint.util.to_native_str(service_type) + if not service_type.endswith(octoprint.util.to_native_str(".")): + service_type += octoprint.util.to_native_str(".") + if not service_type.endswith(octoprint.util.to_native_str("local.")): + service_type += octoprint.util.to_native_str("local.") + return service_type + + def _format_zeroconf_name(self, name, service_type): + service_type = self._format_zeroconf_service_type(service_type) + return ( + octoprint.util.to_native_str(name) + + octoprint.util.to_native_str(".") + + service_type + ) + + def _format_zeroconf_txt(self, record): + result = {} + if not record: + return result + + for key, value in record.items(): + result[octoprint.util.to_bytes(key)] = octoprint.util.to_bytes(value) + return result + + def zeroconf_register(self, reg_type, name=None, port=None, txt_record=None): + """ + Registers a new service with Zeroconf/Bonjour/Avahi. + + :param reg_type: type of service to register, e.g. "_gntp._tcp" + :param name: displayable name of the service, if not given defaults to the OctoPrint instance name + :param port: port to register for the service, if not given defaults to OctoPrint's (public) port + :param txt_record: optional txt record to attach to the service, dictionary of key-value-pairs + """ + + if not name: + name = self.get_instance_name() + if not port: + port = self.port + + reg_type = self._format_zeroconf_service_type(reg_type) + name = self._format_zeroconf_name(name, reg_type) + txt_record = self._format_zeroconf_txt(txt_record) + + key = (reg_type, port) + addresses = list( + map(lambda x: socket.inet_aton(x), octoprint.util.net.interface_addresses()) + ) + + try: + info = zeroconf.ServiceInfo( + reg_type, + name, + addresses=addresses, + port=port, + server="{}.local.".format(socket.gethostname()), + properties=txt_record, + ) + self._zeroconf.register_service(info, allow_name_change=True) + self._zeroconf_registrations[key].append(info) + self._logger.info("Registered '{}' for {}".format(name, reg_type)) + except Exception: + self._logger.exception( + "Could not register {} for {} on port {}".format(name, reg_type, port) + ) + + def zeroconf_unregister(self, reg_type, port=None): + """ + Unregisters a previously registered Zeroconf/Bonjour/Avahi service identified by service and port. + + :param reg_type: the type of the service to be unregistered + :param port: the port of the service to be unregistered, defaults to OctoPrint's (public) port if not given + :return: + """ + + if not port: + port = self.port + reg_type = self._format_zeroconf_service_type(reg_type) + + key = (reg_type, port) + if not key in self._zeroconf_registrations: + return + + infos = self._zeroconf_registrations.pop(key) + try: + for info in infos: + self._zeroconf.unregister_service(info) + self._logger.debug("Unregistered {} on port {}".format(reg_type, port)) + except: + self._logger.exception( + "Could not (fully) unregister {} on port {}".format(reg_type, port) + ) + + def zeroconf_browse( + self, service_type, block=True, callback=None, browse_timeout=5, resolve_timeout=5 + ): + """ + Browses for services on the local network providing the specified service type. Can be used either blocking or + non-blocking. + + The non-blocking version (default behaviour) will not return until the lookup has completed and + return all results that were found. + + For non-blocking version, set `block` to `False` and provide a `callback` to be called once the lookup completes. + If no callback is provided in non-blocking mode, a ValueError will be raised. + + The results are provided as a list of discovered services, with each service being described by a dictionary + with the following keys: + + * `name`: display name of the service + * `host`: host name of the service + * `post`: port the service is listening on + * `txt_record`: TXT record of the service as a dictionary, exact contents depend on the service + + Callbacks will be called with that list as the single parameter supplied to them. Thus, the following is an + example for a valid callback: + + def browse_callback(results): + for result in results: + print "Name: {name}, Host: {host}, Port: {port}, TXT: {txt_record!r}".format(**result) + + :param service_type: the service type to browse for + :param block: whether to block, defaults to True + :param callback: callback to call once lookup has completed, must be set when `block` is set to `False` + :param browse_timeout: timeout for browsing operation + :param resolve_timeout: timeout for resolving operations for discovered records + :return: if `block` is `True` a list of the discovered services, an empty list otherwise (results will then be + supplied to the callback instead) + """ + + import threading + + if not block and not callback: + raise ValueError("Non-blocking mode but no callback given") + + service_type = self._format_zeroconf_service_type(service_type) + + result = [] + result_available = threading.Event() + result_available.clear() + + class ZeroconfListener(object): + def __init__(self, logger): + self._logger = logger + + def add_service(self, zeroconf, type, name): + self._logger.debug( + "Got a browsing result for Zeroconf resolution of {}, resolving...".format( + type + ) + ) + info = zeroconf.get_service_info( + type, name, timeout=resolve_timeout * 1000 + ) + if info: + + def to_result(info, address): + n = info.name[: -(len(type) + 1)] + p = info.port + + self._logger.debug( + "Resolved a result for Zeroconf resolution of {}: {} @ {}:{}".format( + type, n, address, p + ) + ) + + return { + "name": n, + "host": address, + "port": p, + "txt_record": info.properties, + } + + for address in map(lambda x: socket.inet_ntoa(x), info.addresses): + result.append(to_result(info, address)) + + self._logger.debug( + "Browsing Zeroconf for {service_type}".format(service_type=service_type) + ) + + def browse(): + listener = ZeroconfListener(self._logger) + browser = zeroconf.ServiceBrowser(self._zeroconf, service_type, listener) + time.sleep(browse_timeout) + browser.cancel() + + if callback: + callback(result) + result_available.set() + + browse_thread = threading.Thread(target=browse) + browse_thread.daemon = True + browse_thread.start() + + if block: + result_available.wait() + return result + else: + return [] + + # SSDP/UPNP + + def ssdp_browse(self, query, block=True, callback=None, timeout=1, retries=5): + """ + Browses for UPNP services matching the supplied query. Can be used either blocking or + non-blocking. + + The non-blocking version (default behaviour) will not return until the lookup has completed and + return all results that were found. + + For non-blocking version, set `block` to `False` and provide a `callback` to be called once the lookup completes. + If no callback is provided in non-blocking mode, a ValueError will be raised. + + The results are provided as a list of discovered locations of device descriptor files. + + Callbacks will be called with that list as the single parameter supplied to them. Thus, the following is an + example for a valid callback: + + def browse_callback(results): + for result in results: + print("Location: {}".format(result)) + + :param query: the SSDP query to send, e.g. "upnp:rootdevice" to search for all devices + :param block: whether to block, defaults to True + :param callback: callback to call in non-blocking mode when lookup has finished, must be set if block is False + :param timeout: timeout in seconds to wait for replies to the M-SEARCH query per interface, defaults to 1 + :param retries: number of retries to perform the lookup on all interfaces, defaults to 5 + :return: if `block` is `True` a list of the discovered devices, an empty list otherwise (results will then be + supplied to the callback instead) + """ + + import threading + import io + + try: + # noinspection PyCompatibility + from http.client import HTTPResponse # py3 + except ImportError: + # noinspection PyCompatibility + from httplib import HTTPResponse # py2 + + class Response(HTTPResponse): + def __init__(self, response_text): + self.fp = io.BytesIO(response_text) + self.debuglevel = 0 + self.strict = 0 + self.msg = None + self._method = None + self.begin() + + result = [] + result_available = threading.Event() + result_available.clear() + + def browse(): + socket.setdefaulttimeout(timeout) + + search_message = "".join( + [ + "M-SEARCH * HTTP/1.1\r\n", + "ST: {query}\r\n", + "MX: 3\r\n", + 'MAN: "ssdp:discovery"\r\n', + "HOST: {mcast_addr}:{mcast_port}\r\n\r\n", + ] + ) + + for _ in range(retries): + for addr in octoprint.util.interface_addresses(): + try: + sock = socket.socket( + socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP + ) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2) + sock.bind((addr, 0)) + + message = search_message.format( + query=query, + mcast_addr=self.__class__.ssdp_multicast_addr, + mcast_port=self.__class__.ssdp_multicast_port, + ) + for _ in range(2): + sock.sendto( + message.encode("utf-8"), + ( + self.__class__.ssdp_multicast_addr, + self.__class__.ssdp_multicast_port, + ), + ) + + try: + data = sock.recv(1024) + except socket.timeout: + pass + else: + response = Response(data) + + result.append(response.getheader("Location")) + except Exception: + pass + + if callback: + callback(result) + result_available.set() + + browse_thread = threading.Thread(target=browse) + browse_thread.daemon = True + browse_thread.start() + + if block: + result_available.wait() + return result + else: + return [] + + ##~~ internals + + # Zeroconf + + def _create_http_txt_record_dict(self): + """ + Creates a TXT record for the _http._tcp Zeroconf service supplied by this OctoPrint instance. + + Defines the keys for _http._tcp as defined in http://www.dns-sd.org/txtrecords.html + + :return: a dictionary containing the defined key-value-pairs, ready to be turned into a TXT record + """ + + # determine path entry + path = "/" + if self._settings.get(["pathPrefix"]): + path = self._settings.get(["pathPrefix"]) + else: + prefix = self._settings.global_get( + ["server", "reverseProxy", "prefixFallback"] + ) + if prefix: + path = prefix + + # fetch username and password (if set) + username = self._settings.get(["httpUsername"]) + password = self._settings.get(["httpPassword"]) + + entries = {"path": path} + + if username and password: + entries.update({"u": username, "p": password}) + + return entries + + def _create_octoprint_txt_record_dict(self): + """ + Creates a TXT record for the _octoprint._tcp Zeroconf service supplied by this OctoPrint instance. + + The following keys are defined: + + * `path`: path prefix to actual OctoPrint instance, inherited from _http._tcp + * `u`: username if HTTP Basic Auth is used, optional, inherited from _http._tcp + * `p`: password if HTTP Basic Auth is used, optional, inherited from _http._tcp + * `version`: OctoPrint software version + * `api`: OctoPrint API version + * `model`: Model of the device that is running OctoPrint + * `vendor`: Vendor of the device that is running OctoPrint + + :return: a dictionary containing the defined key-value-pairs, ready to be turned into a TXT record + """ + import octoprint.server + import octoprint.server.api + + entries = self._create_http_txt_record_dict() + entries.update( + version=octoprint.server.VERSION, + api=octoprint.server.api.VERSION, + uuid=self.get_uuid(), + ) + + modelName = self._settings.get(["model", "name"]) + if modelName: + entries.update(model=modelName) + vendor = self._settings.get(["model", "vendor"]) + if vendor: + entries.update(vendor=vendor) + + return entries + + # SSDP/UPNP + + def _ssdp_register(self): + """ + Registers the OctoPrint instance as basic service with a presentation URL pointing to the web interface + """ + + import threading + + self._ssdp_monitor_active = True + + self._ssdp_monitor_thread = threading.Thread( + target=self._ssdp_monitor, kwargs={"timeout": self._ssdp_notify_timeout} + ) + self._ssdp_monitor_thread.daemon = True + self._ssdp_monitor_thread.start() + + def _ssdp_unregister(self): + """ + Unregisters the OctoPrint instance again + """ + + self._ssdp_monitor_active = False + if self.host and self.port: + for _ in range(2): + self._ssdp_notify(alive=False) + + def _ssdp_notify(self, alive=True): + """ + Sends an SSDP notify message across the connected networks. + + :param alive: True to send an "ssdp:alive" message, False to send an "ssdp:byebye" message + """ + + if ( + alive + and self._ssdp_last_notify + self._ssdp_notify_timeout + > octoprint.util.monotonic_time() + ): + # we just sent an alive, no need to send another one now + return + + if alive and not self._ssdp_monitor_active: + # the monitor already shut down, alive messages don't make sense anymore as byebye will shortly follow + return + + for addr in octoprint.util.interface_addresses(): + try: + sock = socket.socket( + socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP + ) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2) + sock.bind((addr, 0)) + + location = "http://{addr}:{port}/plugin/discovery/discovery.xml".format( + addr=addr, port=self.port + ) + + self._logger.debug( + "Sending NOTIFY {} via {}".format( + "alive" if alive else "byebye", addr + ) + ) + notify_message = "".join( + [ + "NOTIFY * HTTP/1.1\r\n", + "Server: {server}\r\n", + "Cache-Control: max-age=900\r\n", + "Location: {location}\r\n", + "NTS: {nts}\r\n", + "NT: {nt}\r\n", + "USN: {usn}\r\n", + "HOST: {mcast_addr}:{mcast_port}\r\n\r\n", + ] + ) + uuid = self.get_uuid() + for nt, usn in ( + ("upnp:rootdevice", "uuid:{uuid}::upnp:rootdevice"), + ("uuid:{}", "uuid:{uuid}"), + ( + "urn:schemas-upnp-org:device:basic:1", + "uuid:{uuid}::url:schemas-upnp-org:device:basic:1", + ), + ): + message = notify_message.format( + uuid=uuid, + location=location, + nts="ssdp:alive" if alive else "ssdp:byebye", + nt=nt.format(uuid=uuid), + usn=usn.format(uuid=uuid), + server=self.ssdp_server, + mcast_addr=self.ssdp_multicast_addr, + mcast_port=self.ssdp_multicast_port, + ) + for _ in range(2): + # send twice, stuff might get lost, it's only UDP + sock.sendto( + message.encode("utf-8"), + (self.ssdp_multicast_addr, self.ssdp_multicast_port), + ) + except Exception: + pass + + self._ssdp_last_notify = octoprint.util.monotonic_time() + + def _ssdp_monitor(self, timeout=5): + """ + Monitor thread that listens on the multicast address for M-SEARCH requests and answers them if they are relevant + + :param timeout: timeout after which to stop waiting for M-SEARCHs for a short while in order to put out an + alive message + """ + + try: + # noinspection PyCompatibility + from http.server import BaseHTTPRequestHandler + except ImportError: + # noinspection PyCompatibility + from BaseHTTPServer import BaseHTTPRequestHandler + + from io import BytesIO + + socket.setdefaulttimeout(timeout) + + location_message = "".join( + [ + "HTTP/1.1 200 OK\r\n", + "ST: upnp:rootdevice\r\n", + "USN: uuid:{uuid}::upnp:rootdevice\r\n", + "Location: {location}\r\n", + "Cache-Control: max-age=60\r\n\r\n", + ] + ) + + class Request(BaseHTTPRequestHandler): + + # noinspection PyMissingConstructor + def __init__(self, request_text): + self.rfile = BytesIO(request_text) + self.raw_requestline = self.rfile.readline() + self.error_code = self.error_message = None + self.parse_request() + + def send_error(self, code, message=None): + self.error_code = code + self.error_message = message + + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2) + sock.bind(("", self.__class__.ssdp_multicast_port)) + + sock.setsockopt( + socket.IPPROTO_IP, + socket.IP_ADD_MEMBERSHIP, + socket.inet_aton(self.__class__.ssdp_multicast_addr) + + socket.inet_aton("0.0.0.0"), + ) + + self._logger.info("Registered {} for SSDP".format(self.get_instance_name())) + + self._ssdp_notify(alive=True) + + try: + while self._ssdp_monitor_active: + try: + data, address = sock.recvfrom(4096) + request = Request(data) + if ( + not request.error_code + and request.command == "M-SEARCH" + and request.path == "*" + and ( + request.headers["ST"] == "upnp:rootdevice" + or request.headers["ST"] == "ssdp:all" + ) + and request.headers["MAN"] == '"ssdp:discover"' + ): + interface_address = octoprint.util.address_for_client(*address) + if not interface_address: + self._logger.warning( + "Can't determine address to user for client {}, not sending a M-SEARCH reply".format( + address + ) + ) + continue + message = location_message.format( + uuid=self.get_uuid(), + location="http://{host}:{port}/plugin/discovery/discovery.xml".format( + host=interface_address, port=self.port + ), + ) + sock.sendto(message.encode("utf-8"), address) + self._logger.debug( + "Sent M-SEARCH reply for {path} and {st} to {address!r}".format( + path=request.path, + st=request.headers["ST"], + address=address, + ) + ) + except socket.timeout: + pass + finally: + self._ssdp_notify(alive=True) + finally: + try: + sock.close() + except Exception: + pass + + ##~~ helpers + + def get_uuid(self): + upnpUuid = self._settings.get(["upnpUuid"]) + if upnpUuid is None: + import uuid + + upnpUuid = str(uuid.uuid4()) + self._settings.set(["upnpUuid"], upnpUuid) + self._settings.save() + return upnpUuid + + def get_instance_name(self): + name = self._settings.global_get(["appearance", "name"]) + if name: + return 'OctoPrint instance "{}"'.format(name) + else: + return "OctoPrint instance on {}".format(socket.gethostname()) __plugin_name__ = "Discovery" __plugin_author__ = "Gina Häußge" __plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/discovery.html" -__plugin_description__ = "Makes the OctoPrint instance discoverable via Bonjour/Avahi/Zeroconf and uPnP" -__plugin_disabling_discouraged__ = gettext("Without this plugin your OctoPrint instance will no longer be " - "discoverable on the network via Bonjour and uPnP.") +__plugin_description__ = ( + "Makes the OctoPrint instance discoverable via Bonjour/Avahi/Zeroconf and uPnP" +) +__plugin_disabling_discouraged__ = gettext( + "Without this plugin your OctoPrint instance will no longer be " + "discoverable on the network via Bonjour and uPnP." +) __plugin_license__ = "AGPLv3" __plugin_pythoncompat__ = ">=2.7,<4" diff --git a/src/octoprint/plugins/errortracking/__init__.py b/src/octoprint/plugins/errortracking/__init__.py index 4ee577ad4..15bac94d4 100644 --- a/src/octoprint/plugins/errortracking/__init__.py +++ b/src/octoprint/plugins/errortracking/__init__.py @@ -1,26 +1,35 @@ # 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License" import octoprint.plugin import logging from octoprint.util import get_fully_qualified_classname as fqcn -from octoprint.util.version import get_octoprint_version_string, is_released_octoprint_version +from octoprint.util.version import ( + get_octoprint_version_string, + is_released_octoprint_version, +) from flask import jsonify from flask_babel import gettext -SENTRY_URL_SERVER = "https://d479a74f172d4ac2b959a9a7d0536a82@o118517.ingest.sentry.io/1373987" -SENTRY_URL_COREUI = "https://040577fb88b241ff985e408c11775720@o118517.ingest.sentry.io/1374096" +SENTRY_URL_SERVER = ( + "https://d479a74f172d4ac2b959a9a7d0536a82@o118517.ingest.sentry.io/1373987" +) +SENTRY_URL_COREUI = ( + "https://040577fb88b241ff985e408c11775720@o118517.ingest.sentry.io/1374096" +) -SETTINGS_DEFAULTS = {"enabled": False, - "enabled_unreleased": False, - "unique_id": None, - "url_server": SENTRY_URL_SERVER, - "url_coreui": SENTRY_URL_COREUI} +SETTINGS_DEFAULTS = { + "enabled": False, + "enabled_unreleased": False, + "unique_id": None, + "url_server": SENTRY_URL_SERVER, + "url_coreui": SENTRY_URL_COREUI, +} import serial import requests.exceptions @@ -28,181 +37,217 @@ import errno import tornado.websocket IGNORED_EXCEPTIONS = [ - # serial exceptions in octoprint.util.comm - (serial.SerialException, lambda exc, logger, plugin, cb: logger == "octoprint.util.comm"), - - # KeyboardInterrupts - KeyboardInterrupt, - - # IOErrors of any kind due to a full file system - (IOError, lambda exc, logger, plugin, cb: getattr(exc, "errno") and exc.errno in (getattr(errno, "ENOSPC"),)), - - # RequestExceptions of any kind - requests.exceptions.RequestException, - - # Tornado WebSocketErrors of any kind - tornado.websocket.WebSocketError, - - # Anything triggered by or in third party plugin Astroprint - (Exception, lambda exc, logger, plugin, cb: logger.startswith("octoprint.plugins.astroprint") - or plugin == "astroprint" - or cb.startswith("octoprint_astroprint.")) + # serial exceptions in octoprint.util.comm + ( + serial.SerialException, + lambda exc, logger, plugin, cb: logger == "octoprint.util.comm", + ), + # KeyboardInterrupts + KeyboardInterrupt, + # IOErrors of any kind due to a full file system + ( + IOError, + lambda exc, logger, plugin, cb: getattr(exc, "errno") + and exc.errno in (getattr(errno, "ENOSPC"),), + ), + # RequestExceptions of any kind + requests.exceptions.RequestException, + # Tornado WebSocketErrors of any kind + tornado.websocket.WebSocketError, + # Anything triggered by or in third party plugin Astroprint + ( + Exception, + lambda exc, logger, plugin, cb: logger.startswith("octoprint.plugins.astroprint") + or plugin == "astroprint" + or cb.startswith("octoprint_astroprint."), + ), ] try: - # noinspection PyUnresolvedReferences - from octoprint.plugins.backup import InsufficientSpace + # noinspection PyUnresolvedReferences + from octoprint.plugins.backup import InsufficientSpace - # if the backup plugin is enabled, ignore InsufficientSpace errors from it as well - IGNORED_EXCEPTIONS.append(InsufficientSpace) + # if the backup plugin is enabled, ignore InsufficientSpace errors from it as well + IGNORED_EXCEPTIONS.append(InsufficientSpace) - del InsufficientSpace + del InsufficientSpace except ImportError: - pass + pass -class ErrorTrackingPlugin(octoprint.plugin.SettingsPlugin, - octoprint.plugin.AssetPlugin, - octoprint.plugin.TemplatePlugin, - octoprint.plugin.SimpleApiPlugin): +class ErrorTrackingPlugin( + octoprint.plugin.SettingsPlugin, + octoprint.plugin.AssetPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.SimpleApiPlugin, +): + def get_template_configs(self): + return [ + { + "type": "settings", + "name": gettext("Error Tracking"), + "template": "errortracking_settings.jinja2", + "custom_bindings": False, + }, + {"type": "generic", "template": "errortracking_javascripts.jinja2"}, + ] - def get_template_configs(self): - return [{"type": "settings", - "name": gettext("Error Tracking"), - "template": "errortracking_settings.jinja2", - "custom_bindings": False}, - {"type": "generic", - "template": "errortracking_javascripts.jinja2"}] + def get_template_vars(self): + enabled = self._settings.get_boolean(["enabled"]) + enabled_unreleased = self._settings.get_boolean(["enabled_unreleased"]) - def get_template_vars(self): - enabled = self._settings.get_boolean(["enabled"]) - enabled_unreleased = self._settings.get_boolean(["enabled_unreleased"]) + return { + "enabled": _is_enabled(enabled, enabled_unreleased), + "unique_id": self._settings.get(["unique_id"]), + "url_coreui": self._settings.get(["url_coreui"]), + } - return {"enabled": _is_enabled(enabled, enabled_unreleased), - "unique_id": self._settings.get(["unique_id"]), - "url_coreui": self._settings.get(["url_coreui"])} + def get_assets(self): + return {"js": ["js/sentry.min.js", "js/errortracking.js"]} - def get_assets(self): - return {"js": ["js/sentry.min.js", "js/errortracking.js"]} + def get_settings_defaults(self): + return SETTINGS_DEFAULTS - def get_settings_defaults(self): - return SETTINGS_DEFAULTS + def on_settings_save(self, data): + old_enabled = _is_enabled( + self._settings.get_boolean(["enabled"]), + self._settings.get_boolean(["enabled_unreleased"]), + ) - def on_settings_save(self, data): - old_enabled = _is_enabled(self._settings.get_boolean(["enabled"]), - self._settings.get_boolean(["enabled_unreleased"])) + octoprint.plugin.SettingsPlugin.on_settings_save(self, data) - octoprint.plugin.SettingsPlugin.on_settings_save(self, data) + enabled = _is_enabled( + self._settings.get_boolean(["enabled"]), + self._settings.get_boolean(["enabled_unreleased"]), + ) - enabled = _is_enabled(self._settings.get_boolean(["enabled"]), - self._settings.get_boolean(["enabled_unreleased"])) + if old_enabled != enabled: + _enable_errortracking() - if old_enabled != enabled: - _enable_errortracking() - - def on_api_get(self, request): - return jsonify(**self.get_template_vars()) + def on_api_get(self, request): + return jsonify(**self.get_template_vars()) _enabled = False + + def _enable_errortracking(): - # this is a bit hackish, but we want to enable error tracking as early in the platform lifecycle as possible - # and hence can't wait until our implementation is initialized and injected with settings + # this is a bit hackish, but we want to enable error tracking as early in the platform lifecycle as possible + # and hence can't wait until our implementation is initialized and injected with settings - from octoprint.settings import settings - global _enabled + from octoprint.settings import settings - if _enabled: - return + global _enabled - version = get_octoprint_version_string() + if _enabled: + return - s = settings() - plugin_defaults = {"plugins": {"errortracking": SETTINGS_DEFAULTS}} + version = get_octoprint_version_string() - enabled = s.getBoolean(["plugins", "errortracking", "enabled"], defaults=plugin_defaults) - enabled_unreleased = s.getBoolean(["plugins", "errortracking", "enabled_unreleased"], defaults=plugin_defaults) - url_server = s.get(["plugins", "errortracking", "url_server"], defaults=plugin_defaults) - unique_id = s.get(["plugins", "errortracking", "unique_id"], defaults=plugin_defaults) - if unique_id is None: - import uuid - unique_id = str(uuid.uuid4()) - s.set(["plugins", "errortracking", "unique_id"], unique_id, defaults=plugin_defaults) - s.save() + s = settings() + plugin_defaults = {"plugins": {"errortracking": SETTINGS_DEFAULTS}} - if _is_enabled(enabled, enabled_unreleased): - import sentry_sdk - from octoprint.plugin import plugin_manager + enabled = s.getBoolean( + ["plugins", "errortracking", "enabled"], defaults=plugin_defaults + ) + enabled_unreleased = s.getBoolean( + ["plugins", "errortracking", "enabled_unreleased"], defaults=plugin_defaults + ) + url_server = s.get( + ["plugins", "errortracking", "url_server"], defaults=plugin_defaults + ) + unique_id = s.get(["plugins", "errortracking", "unique_id"], defaults=plugin_defaults) + if unique_id is None: + import uuid - def _before_send(event, hint): - if not "exc_info" in hint: - # we only want exceptions - return None + unique_id = str(uuid.uuid4()) + s.set( + ["plugins", "errortracking", "unique_id"], unique_id, defaults=plugin_defaults + ) + s.save() - handled = True - logger = event.get("logger", "") - plugin = event.get("extra", {}).get("plugin", None) - callback = event.get("extra", {}).get("callback", None) + if _is_enabled(enabled, enabled_unreleased): + import sentry_sdk + from octoprint.plugin import plugin_manager - for ignore in IGNORED_EXCEPTIONS: - if isinstance(ignore, tuple): - ignored_exc, matcher = ignore - else: - ignored_exc = ignore - matcher = lambda *args: True + def _before_send(event, hint): + if not "exc_info" in hint: + # we only want exceptions + return None - exc = hint["exc_info"][1] - if isinstance(exc, ignored_exc) and matcher(exc, logger, plugin, callback): - # exception ignored for logger, plugin and/or callback - return None + handled = True + logger = event.get("logger", "") + plugin = event.get("extra", {}).get("plugin", None) + callback = event.get("extra", {}).get("callback", None) - elif isinstance(ignore, type): - if isinstance(hint["exc_info"][1], ignore): - # exception ignored - return None + for ignore in IGNORED_EXCEPTIONS: + if isinstance(ignore, tuple): + ignored_exc, matcher = ignore + else: + ignored_exc = ignore + matcher = lambda *args: True - if event.get("exception") and event["exception"].get("values"): - handled = not any(map(lambda x: x.get("mechanism") and x["mechanism"].get("handled", True) == False, - event["exception"]["values"])) + exc = hint["exc_info"][1] + if isinstance(exc, ignored_exc) and matcher( + exc, logger, plugin, callback + ): + # exception ignored for logger, plugin and/or callback + return None - if handled: - # error is handled, restrict further based on logger - if logger != "" and not (logger.startswith("octoprint.") or logger.startswith("tornado.")): - # we only want errors logged by loggers octoprint.* or tornado.* - return None + elif isinstance(ignore, type): + if isinstance(hint["exc_info"][1], ignore): + # exception ignored + return None - if logger.startswith("octoprint.plugins."): - plugin_id = logger.split(".")[2] - plugin_info = plugin_manager().get_plugin_info(plugin_id) - if plugin_info is None or not plugin_info.bundled: - # we only want our active bundled plugins - return None + if event.get("exception") and event["exception"].get("values"): + handled = not any( + map( + lambda x: x.get("mechanism") + and x["mechanism"].get("handled", True) == False, + event["exception"]["values"], + ) + ) - if plugin is not None: - plugin_info = plugin_manager().get_plugin_info(plugin) - if plugin_info is None or not plugin_info.bundled: - # we only want our active bundled plugins - return None + if handled: + # error is handled, restrict further based on logger + if logger != "" and not ( + logger.startswith("octoprint.") or logger.startswith("tornado.") + ): + # we only want errors logged by loggers octoprint.* or tornado.* + return None - return event + if logger.startswith("octoprint.plugins."): + plugin_id = logger.split(".")[2] + plugin_info = plugin_manager().get_plugin_info(plugin_id) + if plugin_info is None or not plugin_info.bundled: + # we only want our active bundled plugins + return None - sentry_sdk.init(url_server, - release=version, - before_send=_before_send) + if plugin is not None: + plugin_info = plugin_manager().get_plugin_info(plugin) + if plugin_info is None or not plugin_info.bundled: + # we only want our active bundled plugins + return None - with sentry_sdk.configure_scope() as scope: - scope.user = {"id": unique_id} + return event - logging.getLogger("octoprint.plugins.errortracking").info("Initialized error tracking") - _enabled = True + sentry_sdk.init(url_server, release=version, before_send=_before_send) + + with sentry_sdk.configure_scope() as scope: + scope.user = {"id": unique_id} + + logging.getLogger("octoprint.plugins.errortracking").info( + "Initialized error tracking" + ) + _enabled = True def _is_enabled(enabled, enabled_unreleased): - return enabled and (enabled_unreleased or is_released_octoprint_version()) + return enabled and (enabled_unreleased or is_released_octoprint_version()) def __plugin_enable__(): - _enable_errortracking() + _enable_errortracking() __plugin_name__ = "Error Tracking" diff --git a/src/octoprint/plugins/gcodeviewer/__init__.py b/src/octoprint/plugins/gcodeviewer/__init__.py index b8562b689..a5b6596f4 100644 --- a/src/octoprint/plugins/gcodeviewer/__init__.py +++ b/src/octoprint/plugins/gcodeviewer/__init__.py @@ -1,69 +1,84 @@ # -*- 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License" import octoprint.plugin from flask_babel import gettext -class GcodeviewerPlugin(octoprint.plugin.AssetPlugin, - octoprint.plugin.TemplatePlugin, - octoprint.plugin.SettingsPlugin): - def get_assets(self): - js = ["js/gcodeviewer.js", - "js/viewer/ui.js", - "js/viewer/reader.js", - "js/viewer/renderer.js" - ] +class GcodeviewerPlugin( + octoprint.plugin.AssetPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.SettingsPlugin, +): + def get_assets(self): + js = [ + "js/gcodeviewer.js", + "js/viewer/ui.js", + "js/viewer/reader.js", + "js/viewer/renderer.js", + ] - return {"js": js, - "less": ["less/gcodeviewer.less"], - "css": ["css/gcodeviewer.css"]} + return { + "js": js, + "less": ["less/gcodeviewer.less"], + "css": ["css/gcodeviewer.css"], + } - def get_template_configs(self): - return [ - {"type": "tab", - "template": "gcodeviewer_tab.jinja2", - "div": "gcode", - "styles": ["display: none;"], - "data_bind": "visible: loginState.hasAllPermissionsKo(access.permissions.GCODE_VIEWER, access.permissions.FILES_DOWNLOAD)"}, - {"type": "settings", - "template": "gcodeviewer_settings.jinja2", - "custom_bindings": True}, - {"type": "generic", - "template": "gcodeviewer_initscript.jinja2"} - ] + def get_template_configs(self): + return [ + { + "type": "tab", + "template": "gcodeviewer_tab.jinja2", + "div": "gcode", + "styles": ["display: none;"], + "data_bind": "visible: loginState.hasAllPermissionsKo(access.permissions.GCODE_VIEWER, access.permissions.FILES_DOWNLOAD)", + }, + { + "type": "settings", + "template": "gcodeviewer_settings.jinja2", + "custom_bindings": True, + }, + {"type": "generic", "template": "gcodeviewer_initscript.jinja2"}, + ] - def get_settings_defaults(self): - return {"mobileSizeThreshold": 2 * 1024 * 1024, # 2MB - "sizeThreshold": 20 * 1024 * 1024} # 20MB + def get_settings_defaults(self): + return { + "mobileSizeThreshold": 2 * 1024 * 1024, # 2MB + "sizeThreshold": 20 * 1024 * 1024, + } # 20MB - def get_settings_version(self): - return 1 + def get_settings_version(self): + return 1 - def on_settings_migrate(self, target, current): - if current is None: - config = self._settings.global_get(["gcodeViewer"]) - if config: - self._logger.info("Migrating settings from gcodeViewer to plugins.gcodeviewer...") - if "mobileSizeThreshold" in config: - self._settings.set_int(["mobileSizeThreshold"], config["mobileSizeThreshold"]) - if "sizeThreshold" in config: - self._settings.set_int(["sizeThreshold"], config["sizeThreshold"]) - self._settings.global_remove(["gcodeViewer"]) + def on_settings_migrate(self, target, current): + if current is None: + config = self._settings.global_get(["gcodeViewer"]) + if config: + self._logger.info( + "Migrating settings from gcodeViewer to plugins.gcodeviewer..." + ) + if "mobileSizeThreshold" in config: + self._settings.set_int( + ["mobileSizeThreshold"], config["mobileSizeThreshold"] + ) + if "sizeThreshold" in config: + self._settings.set_int(["sizeThreshold"], config["sizeThreshold"]) + self._settings.global_remove(["gcodeViewer"]) __plugin_name__ = gettext("GCode Viewer") __plugin_author__ = "Gina Häußge" __plugin_description__ = "Provides a GCODE viewer in OctoPrint's UI." -__plugin_disabling_discouraged__ = gettext("Without this plugin the GCode Viewer in OctoPrint will no longer be " - "available.") +__plugin_disabling_discouraged__ = gettext( + "Without this plugin the GCode Viewer in OctoPrint will no longer be " "available." +) __plugin_license__ = "AGPLv3" __plugin_pythoncompat__ = ">=2.7,<4" __plugin_implementation__ = GcodeviewerPlugin() -#__plugin_hooks__ = { -# "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions -#} +# __plugin_hooks__ = { +# "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions +# } diff --git a/src/octoprint/plugins/logging/__init__.py b/src/octoprint/plugins/logging/__init__.py index df8367410..d71413249 100644 --- a/src/octoprint/plugins/logging/__init__.py +++ b/src/octoprint/plugins/logging/__init__.py @@ -1,7 +1,7 @@ # -*- 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" import octoprint.plugin @@ -23,221 +23,264 @@ import io import os try: - from os import scandir + from os import scandir except ImportError: - from scandir import scandir + from scandir import scandir -class LoggingPlugin(octoprint.plugin.AssetPlugin, - octoprint.plugin.SettingsPlugin, - octoprint.plugin.TemplatePlugin, - octoprint.plugin.BlueprintPlugin): - # Additional permissions hook +class LoggingPlugin( + octoprint.plugin.AssetPlugin, + octoprint.plugin.SettingsPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.BlueprintPlugin, +): - def get_additional_permissions(self): - return [ - {"key": "MANAGE", - "name": "Logging management", - "description": gettext("Allows to download and delete log files and list and set log levels."), - "default_groups": [ADMIN_GROUP], - "roles": ["manage"]} - ] + # Additional permissions hook - @octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"]) - @no_firstrun_access - @Permissions.PLUGIN_LOGGING_MANAGE.require(403) - def get_all(self): - files = self._getLogFiles() - free, total = self._get_usage() - loggers = self._get_available_loggers() - levels = self._get_logging_levels() - serial_log_enabled = self._settings.global_get_boolean(["serial", "log"]) - plugintimings_log_enabled = self._settings.global_get_boolean(["devel", "pluginTimings"]) - return jsonify(logs={"files": files, "free": free, "total": total}, - setup={"loggers": loggers, "levels": levels}, - serial_log={"enabled": serial_log_enabled}, - plugintimings_log={"enabled": plugintimings_log_enabled}) + def get_additional_permissions(self): + return [ + { + "key": "MANAGE", + "name": "Logging management", + "description": gettext( + "Allows to download and delete log files and list and set log levels." + ), + "default_groups": [ADMIN_GROUP], + "roles": ["manage"], + } + ] - @octoprint.plugin.BlueprintPlugin.route("/logs", methods=["GET"]) - @no_firstrun_access - @Permissions.PLUGIN_LOGGING_MANAGE.require(403) - def get_log_files(self): - files = self._getLogFiles() - free, total = self._get_usage() - return jsonify(files=files, free=free, total=total) + @octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"]) + @no_firstrun_access + @Permissions.PLUGIN_LOGGING_MANAGE.require(403) + def get_all(self): + files = self._getLogFiles() + free, total = self._get_usage() + loggers = self._get_available_loggers() + levels = self._get_logging_levels() + serial_log_enabled = self._settings.global_get_boolean(["serial", "log"]) + plugintimings_log_enabled = self._settings.global_get_boolean( + ["devel", "pluginTimings"] + ) + return jsonify( + logs={"files": files, "free": free, "total": total}, + setup={"loggers": loggers, "levels": levels}, + serial_log={"enabled": serial_log_enabled}, + plugintimings_log={"enabled": plugintimings_log_enabled}, + ) - @octoprint.plugin.BlueprintPlugin.route("/logs/", methods=["GET"]) - @no_firstrun_access - @Permissions.PLUGIN_LOGGING_MANAGE.require(403) - def download_log(self, filename): - return redirect_to_tornado(request, url_for("index") + "downloads/logs/" + filename) + @octoprint.plugin.BlueprintPlugin.route("/logs", methods=["GET"]) + @no_firstrun_access + @Permissions.PLUGIN_LOGGING_MANAGE.require(403) + def get_log_files(self): + files = self._getLogFiles() + free, total = self._get_usage() + return jsonify(files=files, free=free, total=total) - @octoprint.plugin.BlueprintPlugin.route("/logs/", methods=["DELETE"]) - @no_firstrun_access - @Permissions.PLUGIN_LOGGING_MANAGE.require(403) - def delete_log(self, filename): - secure = os.path.join(settings().getBaseFolder("logs"), secure_filename(filename)) - if not os.path.exists(secure): - return make_response("File not found: %s" % filename, 404) + @octoprint.plugin.BlueprintPlugin.route("/logs/", methods=["GET"]) + @no_firstrun_access + @Permissions.PLUGIN_LOGGING_MANAGE.require(403) + def download_log(self, filename): + return redirect_to_tornado( + request, url_for("index") + "downloads/logs/" + filename + ) - os.remove(secure) + @octoprint.plugin.BlueprintPlugin.route("/logs/", methods=["DELETE"]) + @no_firstrun_access + @Permissions.PLUGIN_LOGGING_MANAGE.require(403) + def delete_log(self, filename): + secure = os.path.join(settings().getBaseFolder("logs"), secure_filename(filename)) + if not os.path.exists(secure): + return make_response("File not found: %s" % filename, 404) - return NO_CONTENT + os.remove(secure) - @octoprint.plugin.BlueprintPlugin.route("/setup", methods=["GET"]) - @no_firstrun_access - @Permissions.PLUGIN_LOGGING_MANAGE.require(403) - def get_logging_setup(self): - loggers = self._get_available_loggers() - levels = self._get_logging_levels() - return jsonify(loggers=loggers, levels=levels) + return NO_CONTENT - @octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["GET"]) - @no_firstrun_access - @Permissions.PLUGIN_LOGGING_MANAGE.require(403) - def get_logging_levels_api(self): - return jsonify(self._get_logging_levels()) + @octoprint.plugin.BlueprintPlugin.route("/setup", methods=["GET"]) + @no_firstrun_access + @Permissions.PLUGIN_LOGGING_MANAGE.require(403) + def get_logging_setup(self): + loggers = self._get_available_loggers() + levels = self._get_logging_levels() + return jsonify(loggers=loggers, levels=levels) - @octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["PUT"]) - @no_firstrun_access - @Permissions.PLUGIN_LOGGING_MANAGE.require(403) - def set_logging_levels_api(self): - if not "application/json" in request.headers["Content-Type"]: - return make_response("Expected content-type JSON", 400) + @octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["GET"]) + @no_firstrun_access + @Permissions.PLUGIN_LOGGING_MANAGE.require(403) + def get_logging_levels_api(self): + return jsonify(self._get_logging_levels()) - try: - json_data = request.json - except BadRequest: - return make_response("Malformed JSON body in request", 400) + @octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["PUT"]) + @no_firstrun_access + @Permissions.PLUGIN_LOGGING_MANAGE.require(403) + def set_logging_levels_api(self): + if not "application/json" in request.headers["Content-Type"]: + return make_response("Expected content-type JSON", 400) - if not isinstance(json_data, dict): - return make_response("Invalid log level configuration", 400) + try: + json_data = request.json + except BadRequest: + return make_response("Malformed JSON body in request", 400) - # TODO validate further + if not isinstance(json_data, dict): + return make_response("Invalid log level configuration", 400) - self._set_logging_levels(json_data) - return self.get_logging_levels_api() + # TODO validate further - def is_blueprint_protected(self): - return False + self._set_logging_levels(json_data) + return self.get_logging_levels_api() - def _get_usage(self): - import psutil - usage = psutil.disk_usage(settings().getBaseFolder("logs", check_writable=False)) - return usage.free, usage.total + def is_blueprint_protected(self): + return False - def _getLogFiles(self): - files = [] - basedir = settings().getBaseFolder("logs", check_writable=False) - for entry in scandir(basedir): - files.append({ - "name": entry.name, - "date": int(entry.stat().st_mtime), - "size": entry.stat().st_size, - "refs": { - "resource": url_for(".download_log", filename=entry.name, _external=True), - "download": url_for("index", _external=True) + "downloads/logs/" + entry.name - } - }) + def _get_usage(self): + import psutil - return files + usage = psutil.disk_usage(settings().getBaseFolder("logs", check_writable=False)) + return usage.free, usage.total - def _get_available_loggers(self): - return list(filter(lambda x: self._is_managed_logger(x), self._logger.manager.loggerDict.keys())) + def _getLogFiles(self): + files = [] + basedir = settings().getBaseFolder("logs", check_writable=False) + for entry in scandir(basedir): + files.append( + { + "name": entry.name, + "date": int(entry.stat().st_mtime), + "size": entry.stat().st_size, + "refs": { + "resource": url_for( + ".download_log", filename=entry.name, _external=True + ), + "download": url_for("index", _external=True) + + "downloads/logs/" + + entry.name, + }, + } + ) - def _get_logging_file(self): - # TODO this might not be the logging config we are actually using here (command line parameter...) - return os.path.join(self._settings.getBaseFolder("base"), "logging.yaml") + return files - def _get_logging_config(self): - logging_file = self._get_logging_file() + def _get_available_loggers(self): + return list( + filter( + lambda x: self._is_managed_logger(x), + self._logger.manager.loggerDict.keys(), + ) + ) - config_from_file = {} - if os.path.exists(logging_file) and os.path.isfile(logging_file): - import yaml - with io.open(logging_file, 'rt', encoding='utf-8') as f: - config_from_file = yaml.safe_load(f) - return config_from_file + def _get_logging_file(self): + # TODO this might not be the logging config we are actually using here (command line parameter...) + return os.path.join(self._settings.getBaseFolder("base"), "logging.yaml") - def _get_logging_levels(self): - config = self._get_logging_config() - if config is None or not isinstance(config, dict): - return {} + def _get_logging_config(self): + logging_file = self._get_logging_file() - return dict((key, value.get("level")) - for key, value in config.get("loggers", {}).items() - if isinstance(value, dict) and "level" in value) + config_from_file = {} + if os.path.exists(logging_file) and os.path.isfile(logging_file): + import yaml - def _set_logging_levels(self, new_levels): - import logging + with io.open(logging_file, "rt", encoding="utf-8") as f: + config_from_file = yaml.safe_load(f) + return config_from_file - config = self._get_logging_config() + def _get_logging_levels(self): + config = self._get_logging_config() + if config is None or not isinstance(config, dict): + return {} - # clear all configured logging levels - if "loggers" in config: - purge = [] - for component, data in config["loggers"].items(): - if not self._is_managed_logger(component): continue - try: - del data["level"] - self._logger.manager.loggerDict[component].setLevel(logging.INFO) - except KeyError: - pass - if len(data) == 0: - purge.append(component) - for component in purge: - del config["loggers"][component] - else: - config["loggers"] = {} + return dict( + (key, value.get("level")) + for key, value in config.get("loggers", {}).items() + if isinstance(value, dict) and "level" in value + ) - # update all logging levels - for logger, level in new_levels.items(): - if logger not in config["loggers"]: - config["loggers"][logger] = {} - config["loggers"][logger]["level"] = level + def _set_logging_levels(self, new_levels): + import logging - # delete empty entries - config["loggers"] = {k: v for k, v in config["loggers"].items() if len(v)} + config = self._get_logging_config() - # save - 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) + # clear all configured logging levels + if "loggers" in config: + purge = [] + for component, data in config["loggers"].items(): + if not self._is_managed_logger(component): + continue + try: + del data["level"] + self._logger.manager.loggerDict[component].setLevel(logging.INFO) + except KeyError: + pass + if len(data) == 0: + purge.append(component) + for component in purge: + del config["loggers"][component] + else: + config["loggers"] = {} - # set runtime logging levels now - for logger, level in new_levels.items(): - level = logging.getLevelName(level) + # update all logging levels + for logger, level in new_levels.items(): + if logger not in config["loggers"]: + config["loggers"][logger] = {} + config["loggers"][logger]["level"] = level - self._logger.info("Setting logger {} level to {}".format(logger, level)) - self._logger.manager.loggerDict[logger].setLevel(level) + # delete empty entries + config["loggers"] = {k: v for k, v in config["loggers"].items() if len(v)} - def _is_managed_logger(self, logger): - return logger and (logger.startswith("octoprint") or logger.startswith("tornado")) + # save + 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 + ) - def get_template_configs(self): - return [{"type": "navbar", - "template": "logging_navbar_seriallog.jinja2", - "suffix": "_seriallog"}, - {"type": "navbar", - "template": "logging_navbar_plugintimingslog.jinja2", - "suffix": "_plugintimingslog"}, - {"type": "settings", - "custom_bindings": True}] + # set runtime logging levels now + for logger, level in new_levels.items(): + level = logging.getLevelName(level) + + self._logger.info("Setting logger {} level to {}".format(logger, level)) + self._logger.manager.loggerDict[logger].setLevel(level) + + def _is_managed_logger(self, logger): + return logger and (logger.startswith("octoprint") or logger.startswith("tornado")) + + def get_template_configs(self): + return [ + { + "type": "navbar", + "template": "logging_navbar_seriallog.jinja2", + "suffix": "_seriallog", + }, + { + "type": "navbar", + "template": "logging_navbar_plugintimingslog.jinja2", + "suffix": "_plugintimingslog", + }, + {"type": "settings", "custom_bindings": True}, + ] + + def get_assets(self): + return { + "js": ["js/logging.js"], + "clientjs": ["clientjs/logging.js"], + "less": ["less/logging.less"], + "css": ["css/logging.css"], + } - def get_assets(self): - return {"js": ["js/logging.js"], - "clientjs": ["clientjs/logging.js"], - "less": ["less/logging.less"], - "css": ["css/logging.css"]} __plugin_name__ = "Logging" __plugin_author__ = "Shawn Bruce, based on work by Gina Häußge and Marc Hannappel" __plugin_description__ = "Provides access to OctoPrint's logs and logging configuration." -__plugin_disabling_discouraged__ = gettext("Without this plugin you will no longer be able to retrieve " - "OctoPrint's logs or modify the current logging levels through " - "the web interface.") +__plugin_disabling_discouraged__ = gettext( + "Without this plugin you will no longer be able to retrieve " + "OctoPrint's logs or modify the current logging levels through " + "the web interface." +) __plugin_license__ = "AGPLv3" __plugin_pythoncompat__ = ">=2.7,<4" __plugin_implementation__ = LoggingPlugin() __plugin_hooks__ = { - "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions + "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions } diff --git a/src/octoprint/plugins/pi_support/__init__.py b/src/octoprint/plugins/pi_support/__init__.py index 1553b4aa4..2847661eb 100644 --- a/src/octoprint/plugins/pi_support/__init__.py +++ b/src/octoprint/plugins/pi_support/__init__.py @@ -1,7 +1,7 @@ # -*- 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" import flask @@ -30,17 +30,35 @@ _CHECK_INTERVAL_THROTTLED = 30 __LOCAL_DEBUG = False if __LOCAL_DEBUG: - ### mocks & settings for local debugging - import sys - base = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "tests", "plugins", "pi_support", "fakes")) - _PROC_DT_MODEL_PATH = os.path.join(base, "fake_model.txt") - _OCTOPI_VERSION_PATH = os.path.join(base, "fake_octopi.txt") - _VCGENCMD_THROTTLE = "{} {}".format(sys.executable, os.path.join(base, "fake_vcgencmd.py")) - import itertools - _VCGENCMD_OUTPUT = itertools.chain(iter(("0x0", "0x0", "0x50005", "0x50000", "0x70007")), itertools.repeat("0x70005")) + ### mocks & settings for local debugging + import sys - _CHECK_INTERVAL_OK = 10 - _CHECK_INTERVAL_THROTTLED = 5 + base = os.path.realpath( + os.path.join( + os.path.dirname(__file__), + "..", + "..", + "..", + "..", + "tests", + "plugins", + "pi_support", + "fakes", + ) + ) + _PROC_DT_MODEL_PATH = os.path.join(base, "fake_model.txt") + _OCTOPI_VERSION_PATH = os.path.join(base, "fake_octopi.txt") + _VCGENCMD_THROTTLE = "{} {}".format( + sys.executable, os.path.join(base, "fake_vcgencmd.py") + ) + import itertools + + _VCGENCMD_OUTPUT = itertools.chain( + iter(("0x0", "0x0", "0x50005", "0x50000", "0x70007")), itertools.repeat("0x70005") + ) + + _CHECK_INTERVAL_OK = 10 + _CHECK_INTERVAL_THROTTLED = 5 # see https://www.raspberrypi.org/forums/viewtopic.php?f=63&t=147781&start=50#p972790 @@ -51,314 +69,375 @@ _FLAG_PAST_UNDERVOLTAGE = 1 << 16 _FLAG_PAST_FREQ_CAPPED = 1 << 17 _FLAG_PAST_THROTTLED = 1 << 18 + class ThrottleState(object): - @classmethod - def from_value(cls, value=0): - if value == 0: - return ThrottleState() + @classmethod + def from_value(cls, value=0): + if value == 0: + return ThrottleState() - kwargs = {"undervoltage": _FLAG_UNDERVOLTAGE & value == _FLAG_UNDERVOLTAGE, - "freq_capped": _FLAG_FREQ_CAPPED & value == _FLAG_FREQ_CAPPED, - "throttled": _FLAG_THROTTLED & value == _FLAG_THROTTLED, - "past_undervoltage": _FLAG_PAST_UNDERVOLTAGE & value == _FLAG_PAST_UNDERVOLTAGE, - "past_freq_capped": _FLAG_PAST_FREQ_CAPPED & value == _FLAG_PAST_FREQ_CAPPED, - "past_throttled": _FLAG_PAST_THROTTLED & value == _FLAG_PAST_THROTTLED, - "raw_value": value} - return ThrottleState(**kwargs) + kwargs = { + "undervoltage": _FLAG_UNDERVOLTAGE & value == _FLAG_UNDERVOLTAGE, + "freq_capped": _FLAG_FREQ_CAPPED & value == _FLAG_FREQ_CAPPED, + "throttled": _FLAG_THROTTLED & value == _FLAG_THROTTLED, + "past_undervoltage": _FLAG_PAST_UNDERVOLTAGE & value + == _FLAG_PAST_UNDERVOLTAGE, + "past_freq_capped": _FLAG_PAST_FREQ_CAPPED & value == _FLAG_PAST_FREQ_CAPPED, + "past_throttled": _FLAG_PAST_THROTTLED & value == _FLAG_PAST_THROTTLED, + "raw_value": value, + } + return ThrottleState(**kwargs) - def __init__(self, **kwargs): - self._raw_value = kwargs.get('raw_value', -1) - self._undervoltage = False - self._freq_capped = False - self._throttled = False - self._past_undervoltage = False - self._past_freq_capped = False - self._past_throttled = False + def __init__(self, **kwargs): + self._raw_value = kwargs.get("raw_value", -1) + self._undervoltage = False + self._freq_capped = False + self._throttled = False + self._past_undervoltage = False + self._past_freq_capped = False + self._past_throttled = False - for key, value in kwargs.items(): - local_key = "_{}".format(key) - if hasattr(self, local_key) and isinstance(value, bool): - setattr(self, local_key, value) + for key, value in kwargs.items(): + local_key = "_{}".format(key) + if hasattr(self, local_key) and isinstance(value, bool): + setattr(self, local_key, value) - @property - def undervoltage(self): - return self.current_undervoltage or self.past_undervoltage + @property + def undervoltage(self): + return self.current_undervoltage or self.past_undervoltage - @property - def current_undervoltage(self): - return self._undervoltage + @property + def current_undervoltage(self): + return self._undervoltage - @property - def past_undervoltage(self): - return self._past_undervoltage + @property + def past_undervoltage(self): + return self._past_undervoltage - @property - def overheat(self): - return self.current_overheat or self.past_overheat + @property + def overheat(self): + return self.current_overheat or self.past_overheat - @property - def current_overheat(self): - return self._freq_capped + @property + def current_overheat(self): + return self._freq_capped - @property - def past_overheat(self): - return self._past_freq_capped + @property + def past_overheat(self): + return self._past_freq_capped - @property - def issue(self): - return self.current_issue or self.past_issue + @property + def issue(self): + return self.current_issue or self.past_issue - @property - def current_issue(self): - return self._undervoltage or self._freq_capped or self._throttled + @property + def current_issue(self): + return self._undervoltage or self._freq_capped or self._throttled - @property - def past_issue(self): - return self._past_undervoltage or self._past_freq_capped or self._past_throttled + @property + def past_issue(self): + return self._past_undervoltage or self._past_freq_capped or self._past_throttled - def __eq__(self, other): - if not isinstance(other, ThrottleState): - return False + def __eq__(self, other): + if not isinstance(other, ThrottleState): + return False - return self._undervoltage == other._undervoltage \ - and self._freq_capped == other._freq_capped \ - and self._throttled == other._throttled \ - and self._past_undervoltage == other._past_undervoltage \ - and self._past_freq_capped == other._past_freq_capped \ - and self._past_throttled == other._past_throttled + return ( + self._undervoltage == other._undervoltage + and self._freq_capped == other._freq_capped + and self._throttled == other._throttled + and self._past_undervoltage == other._past_undervoltage + and self._past_freq_capped == other._past_freq_capped + and self._past_throttled == other._past_throttled + ) - def as_dict(self): - return {"raw_value": self._raw_value, - "current_undervoltage": self.current_undervoltage, - "past_undervoltage": self.past_undervoltage, - "current_overheat": self.current_overheat, - "past_overheat": self.past_overheat, - "current_issue": self.current_issue, - "past_issue": self.past_issue} + def as_dict(self): + return { + "raw_value": self._raw_value, + "current_undervoltage": self.current_undervoltage, + "past_undervoltage": self.past_undervoltage, + "current_overheat": self.current_overheat, + "past_overheat": self.past_overheat, + "current_issue": self.current_issue, + "past_issue": self.past_issue, + } _proc_dt_model = None + + def get_proc_dt_model(): - global _proc_dt_model + global _proc_dt_model - if _proc_dt_model is None: - with io.open(_PROC_DT_MODEL_PATH, 'rt', encoding='utf-8') as f: - _proc_dt_model = f.readline().strip(" \t\r\n\0") + if _proc_dt_model is None: + with io.open(_PROC_DT_MODEL_PATH, "rt", encoding="utf-8") as f: + _proc_dt_model = f.readline().strip(" \t\r\n\0") - return _proc_dt_model + return _proc_dt_model def get_vcgencmd_throttled_state(command): - if __LOCAL_DEBUG: - output = "throttled={}".format(next(_VCGENCMD_OUTPUT)) # mock for local debugging - else: - output = sarge.get_stdout(command, close_fds=CLOSE_FDS) + if __LOCAL_DEBUG: + output = "throttled={}".format(next(_VCGENCMD_OUTPUT)) # mock for local debugging + else: + output = sarge.get_stdout(command, close_fds=CLOSE_FDS) - if not "throttled=0x" in output: - raise ValueError("cannot parse \"{}\" output: {}".format(command, output)) + if not "throttled=0x" in output: + raise ValueError('cannot parse "{}" output: {}'.format(command, output)) - value = output[len("throttled="):].strip(" \t\r\n\0") - value = int(value, 0) - return ThrottleState.from_value(value) + value = output[len("throttled=") :].strip(" \t\r\n\0") + value = int(value, 0) + return ThrottleState.from_value(value) def is_octopi(): - return os.path.exists(_OCTOPI_VERSION_PATH) + return os.path.exists(_OCTOPI_VERSION_PATH) _octopi_version = None + + def get_octopi_version(): - global _octopi_version + global _octopi_version - if _octopi_version is None: - with io.open(_OCTOPI_VERSION_PATH, 'rt', encoding='utf-8') as f: - _octopi_version = f.readline().strip(" \t\r\n\0") + if _octopi_version is None: + with io.open(_OCTOPI_VERSION_PATH, "rt", encoding="utf-8") as f: + _octopi_version = f.readline().strip(" \t\r\n\0") - return _octopi_version + return _octopi_version -class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin, - octoprint.plugin.SimpleApiPlugin, - octoprint.plugin.AssetPlugin, - octoprint.plugin.TemplatePlugin, - octoprint.plugin.StartupPlugin, - octoprint.plugin.SettingsPlugin): +class PiSupportPlugin( + octoprint.plugin.EnvironmentDetectionPlugin, + octoprint.plugin.SimpleApiPlugin, + octoprint.plugin.AssetPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.StartupPlugin, + octoprint.plugin.SettingsPlugin, +): - # noinspection PyMissingConstructor - def __init__(self): - self._throttle_state = ThrottleState() - self._throttle_check = None - self._throttle_undervoltage = False - self._throttle_overheat = False - self._throttle_functional = True + # noinspection PyMissingConstructor + def __init__(self): + self._throttle_state = ThrottleState() + self._throttle_check = None + self._throttle_undervoltage = False + self._throttle_overheat = False + self._throttle_functional = True - # Additional permissions hook + # Additional permissions hook - def get_additional_permissions(self): - return [{"key": "STATUS", - "name": "Status", - "description": gettext("Allows to check for the Pi's throttling status and environment info"), - "roles": ["check"], - "default_groups": [USER_GROUP]}] + def get_additional_permissions(self): + return [ + { + "key": "STATUS", + "name": "Status", + "description": gettext( + "Allows to check for the Pi's throttling status and environment info" + ), + "roles": ["check"], + "default_groups": [USER_GROUP], + } + ] - #~~ EnvironmentDetectionPlugin + # ~~ EnvironmentDetectionPlugin - def get_additional_environment(self): - result = {"model": get_proc_dt_model()} + def get_additional_environment(self): + result = {"model": get_proc_dt_model()} - if is_octopi(): - result.update({"octopi_version": get_octopi_version()}) + if is_octopi(): + result.update({"octopi_version": get_octopi_version()}) - return result + return result - #~~ SimpleApiPlugin + # ~~ SimpleApiPlugin - def on_api_get(self, request): - if not Permissions.PLUGIN_PI_SUPPORT_STATUS.can(): - return flask.abort(403) - result = {"throttle_state": self._throttle_state.as_dict()} - result.update(self.get_additional_environment()) - return flask.jsonify(**result) + def on_api_get(self, request): + if not Permissions.PLUGIN_PI_SUPPORT_STATUS.can(): + return flask.abort(403) + result = {"throttle_state": self._throttle_state.as_dict()} + result.update(self.get_additional_environment()) + return flask.jsonify(**result) - #~~ AssetPlugin + # ~~ AssetPlugin - def get_assets(self): - return {"js": ["js/pi_support.js"], - "clientjs": ["clientjs/pi_support.js"], - "css": ["css/pi_support.css"]} + def get_assets(self): + return { + "js": ["js/pi_support.js"], + "clientjs": ["clientjs/pi_support.js"], + "css": ["css/pi_support.css"], + } - #~~ TemplatePlugin + # ~~ TemplatePlugin - def get_template_configs(self): - configs = [{"type": "settings", - "name": gettext("Pi Support"), - "template": "pi_support_settings.jinja2", - "custom_bindings": False}] + def get_template_configs(self): + configs = [ + { + "type": "settings", + "name": gettext("Pi Support"), + "template": "pi_support_settings.jinja2", + "custom_bindings": False, + } + ] - if is_octopi(): - configs.append({"type": "about", - "name": "About OctoPi", - "template": "pi_support_about_octopi.jinja2"}) + if is_octopi(): + configs.append( + { + "type": "about", + "name": "About OctoPi", + "template": "pi_support_about_octopi.jinja2", + } + ) - return configs + return configs - def get_template_vars(self): - return self.get_additional_environment() + def get_template_vars(self): + return self.get_additional_environment() - #~~ StartupPlugin + # ~~ StartupPlugin - def on_startup(self, *args, **kwargs): - if self._settings.get_boolean(["vcgencmd_throttle_check_enabled"]): - self._check_throttled_state() - self._throttle_check = RepeatedTimer(self._check_throttled_state_interval, - self._check_throttled_state, - condition=self._check_throttled_state_condition) - self._throttle_check.start() + def on_startup(self, *args, **kwargs): + if self._settings.get_boolean(["vcgencmd_throttle_check_enabled"]): + self._check_throttled_state() + self._throttle_check = RepeatedTimer( + self._check_throttled_state_interval, + self._check_throttled_state, + condition=self._check_throttled_state_condition, + ) + self._throttle_check.start() - #~~ SettingsPlugin + # ~~ SettingsPlugin - def get_settings_defaults(self): - return {"vcgencmd_throttle_check_enabled": True, - "vcgencmd_throttle_check_command": _VCGENCMD_THROTTLE} + def get_settings_defaults(self): + return { + "vcgencmd_throttle_check_enabled": True, + "vcgencmd_throttle_check_command": _VCGENCMD_THROTTLE, + } - def get_settings_restricted_paths(self): - return {"admin": [["vcgencmd_throttle_check_enabled"], ["vcgencmd_throttle_check_command"]]} + def get_settings_restricted_paths(self): + return { + "admin": [ + ["vcgencmd_throttle_check_enabled"], + ["vcgencmd_throttle_check_command"], + ] + } - #~~ Helpers + # ~~ Helpers - def _check_throttled_state_interval(self): - if self._throttle_state.current_issue: - return _CHECK_INTERVAL_THROTTLED - else: - return _CHECK_INTERVAL_OK + def _check_throttled_state_interval(self): + if self._throttle_state.current_issue: + return _CHECK_INTERVAL_THROTTLED + else: + return _CHECK_INTERVAL_OK - def _check_throttled_state_condition(self): - return self._throttle_functional + def _check_throttled_state_condition(self): + return self._throttle_functional - def get_throttle_state(self, run_now=False): - """Exposed as public helper.""" - if run_now: - self._check_throttled_state() + def get_throttle_state(self, run_now=False): + """Exposed as public helper.""" + if run_now: + self._check_throttled_state() - if not self._throttle_functional: - return False + if not self._throttle_functional: + return False - return self._throttle_state.as_dict() + return self._throttle_state.as_dict() - def _check_throttled_state(self): - command = self._settings.get(["vcgencmd_throttle_check_command"]) + def _check_throttled_state(self): + command = self._settings.get(["vcgencmd_throttle_check_command"]) - self._logger.debug("Retrieving throttle state via \"{}\"".format(command)) - try: - state = get_vcgencmd_throttled_state(command) - except ValueError: - self._logger.warning("Fetching the current throttle state via \"{}\" doesn't work".format(command)) - self._throttle_functional = False - return + self._logger.debug('Retrieving throttle state via "{}"'.format(command)) + try: + state = get_vcgencmd_throttled_state(command) + except ValueError: + self._logger.warning( + 'Fetching the current throttle state via "{}" doesn\'t work'.format( + command + ) + ) + self._throttle_functional = False + return - if self._throttle_state == state: - # no change - return + if self._throttle_state == state: + # no change + return - self._throttle_state = state + self._throttle_state = state - if (not self._throttle_undervoltage and self._throttle_state.undervoltage) \ - or (not self._throttle_overheat and self._throttle_state.overheat): - message = "This Raspberry Pi is reporting problems that might lead to bad performance or errors caused " \ - "by overheating or insufficient power." + if (not self._throttle_undervoltage and self._throttle_state.undervoltage) or ( + not self._throttle_overheat and self._throttle_state.overheat + ): + message = ( + "This Raspberry Pi is reporting problems that might lead to bad performance or errors caused " + "by overheating or insufficient power." + ) - if self._throttle_state.undervoltage: - self._throttle_undervoltage = True - message += "\n!!! UNDERVOLTAGE REPORTED !!! Make sure that the power supply and power cable are " \ - "capable of supplying enough voltage and current to your Pi." + if self._throttle_state.undervoltage: + self._throttle_undervoltage = True + message += ( + "\n!!! UNDERVOLTAGE REPORTED !!! Make sure that the power supply and power cable are " + "capable of supplying enough voltage and current to your Pi." + ) - if self._throttle_state.overheat: - self._throttle_overheat = True - message += "\n!!! FREQUENCY CAPPING DUE TO OVERHEATING REPORTED !!! Improve cooling on the Pi's " \ - "CPU and GPU." + if self._throttle_state.overheat: + self._throttle_overheat = True + message += ( + "\n!!! FREQUENCY CAPPING DUE TO OVERHEATING REPORTED !!! Improve cooling on the Pi's " + "CPU and GPU." + ) - self._logger.warning(message) + self._logger.warning(message) - self._plugin_manager.send_plugin_message(self._identifier, {"type": "throttle_state", - "state": self._throttle_state.as_dict()}) + self._plugin_manager.send_plugin_message( + self._identifier, + {"type": "throttle_state", "state": self._throttle_state.as_dict()}, + ) - # noinspection PyUnresolvedReferences - self._event_bus.fire(octoprint.events.Events.PLUGIN_PI_SUPPORT_THROTTLE_STATE, self._throttle_state.as_dict()) + # noinspection PyUnresolvedReferences + self._event_bus.fire( + octoprint.events.Events.PLUGIN_PI_SUPPORT_THROTTLE_STATE, + self._throttle_state.as_dict(), + ) def register_custom_events(*args, **kwargs): - return ["throttle_state",] + return [ + "throttle_state", + ] __plugin_name__ = "Pi Support Plugin" __plugin_author__ = "Gina Häußge" __plugin_description__ = "Provides additional information about your Pi in the UI." -__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to " - "provide additional information about your Pi, " - "which will make it more tricky to help you if you need support.") +__plugin_disabling_discouraged__ = gettext( + "Without this plugin OctoPrint will no longer be able to " + "provide additional information about your Pi, " + "which will make it more tricky to help you if you need support." +) __plugin_license__ = "AGPLv3" __plugin_pythoncompat__ = ">=2.7,<4" -def __plugin_check__(): - try: - proc_dt_model = get_proc_dt_model() - if proc_dt_model is None: - return False - except Exception: - return False - return "raspberry pi" in proc_dt_model.lower() +def __plugin_check__(): + try: + proc_dt_model = get_proc_dt_model() + if proc_dt_model is None: + return False + except Exception: + return False + + return "raspberry pi" in proc_dt_model.lower() + def __plugin_load__(): - plugin = PiSupportPlugin() - global __plugin_implementation__ - __plugin_implementation__ = plugin + plugin = PiSupportPlugin() + global __plugin_implementation__ + __plugin_implementation__ = plugin - global __plugin_hooks__ - __plugin_hooks__ = { - "octoprint.events.register_custom_events": register_custom_events, - "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions - } + global __plugin_hooks__ + __plugin_hooks__ = { + "octoprint.events.register_custom_events": register_custom_events, + "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions, + } - global __plugin_helpers__ - __plugin_helpers__ = {"get_throttled": plugin.get_throttle_state} + global __plugin_helpers__ + __plugin_helpers__ = {"get_throttled": plugin.get_throttle_state} diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 2054a854f..5958dcd6e 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" from past.builtins import basestring @@ -11,12 +11,21 @@ import octoprint.plugin import octoprint.plugin.core from octoprint.settings import valid_boolean_trues -from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking, check_etag +from octoprint.server.util.flask import ( + no_firstrun_access, + with_revalidation_checking, + check_etag, +) from octoprint.access import ADMIN_GROUP from octoprint.access.permissions import Permissions from octoprint.util import to_bytes, to_native_str, TemporaryDirectory from octoprint.util.pip import LocalPipCaller -from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, is_octoprint_compatible, is_python_compatible +from octoprint.util.version import ( + get_octoprint_version_string, + get_octoprint_version, + is_octoprint_compatible, + is_python_compatible, +) from octoprint.util.platform import get_os, is_os_compatible from octoprint.util.net import download_file from octoprint.events import Events @@ -42,42 +51,56 @@ import pkg_resources from datetime import datetime try: - from os import scandir + from os import scandir except: - from scandir import scandir + from scandir import scandir _DATA_FORMAT_VERSION = "v3" def map_repository_entry(entry): - if not isinstance(entry, dict): - return None + if not isinstance(entry, dict): + return None - result = copy.deepcopy(entry) + result = copy.deepcopy(entry) - if not "follow_dependency_links" in result: - result["follow_dependency_links"] = False + if not "follow_dependency_links" in result: + result["follow_dependency_links"] = False - result["is_compatible"] = {"octoprint": True, - "os": True, - "python": True} + result["is_compatible"] = {"octoprint": True, "os": True, "python": True} - if "compatibility" in entry: - if "octoprint" in entry["compatibility"] and entry["compatibility"]["octoprint"] is not None and isinstance( - entry["compatibility"]["octoprint"], (list, tuple)) and len(entry["compatibility"]["octoprint"]): - result["is_compatible"]["octoprint"] = is_octoprint_compatible(*entry["compatibility"]["octoprint"]) + if "compatibility" in entry: + if ( + "octoprint" in entry["compatibility"] + and entry["compatibility"]["octoprint"] is not None + and isinstance(entry["compatibility"]["octoprint"], (list, tuple)) + and len(entry["compatibility"]["octoprint"]) + ): + result["is_compatible"]["octoprint"] = is_octoprint_compatible( + *entry["compatibility"]["octoprint"] + ) - if "os" in entry["compatibility"] and entry["compatibility"]["os"] is not None and isinstance( - entry["compatibility"]["os"], (list, tuple)) and len(entry["compatibility"]["os"]): - result["is_compatible"]["os"] = is_os_compatible(entry["compatibility"]["os"]) + if ( + "os" in entry["compatibility"] + and entry["compatibility"]["os"] is not None + and isinstance(entry["compatibility"]["os"], (list, tuple)) + and len(entry["compatibility"]["os"]) + ): + result["is_compatible"]["os"] = is_os_compatible(entry["compatibility"]["os"]) - if "python" in entry["compatibility"] and entry["compatibility"]["python"] is not None and isinstance(entry["compatibility"]["python"], basestring): - result["is_compatible"]["python"] = is_python_compatible(entry["compatibility"]["python"]) - else: - # we default to only assume py2 compatiblity for now - result["is_compatible"]["python"] = is_python_compatible(">=2.7,<3") + if ( + "python" in entry["compatibility"] + and entry["compatibility"]["python"] is not None + and isinstance(entry["compatibility"]["python"], basestring) + ): + result["is_compatible"]["python"] = is_python_compatible( + entry["compatibility"]["python"] + ) + else: + # we default to only assume py2 compatiblity for now + result["is_compatible"]["python"] = is_python_compatible(">=2.7,<3") - return result + return result already_installed_string = "Requirement already satisfied (use --upgrade to upgrade)" @@ -85,1310 +108,1777 @@ success_string = "Successfully installed" failure_string = "Could not install" -class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, - octoprint.plugin.TemplatePlugin, - octoprint.plugin.AssetPlugin, - octoprint.plugin.SettingsPlugin, - octoprint.plugin.StartupPlugin, - octoprint.plugin.BlueprintPlugin, - octoprint.plugin.EventHandlerPlugin): - - ARCHIVE_EXTENSIONS = (".zip", ".tar.gz", ".tgz", ".tar", ".gz") - PYTHON_EXTENSIONS = (".py",) - - # valid pip install URL schemes according to https://pip.pypa.io/en/stable/reference/pip_install/ - URL_SCHEMES = ("http", "https", "git", - "git+http", "git+https", "git+ssh", "git+git", - "hg+http", "hg+https", "hg+static-http", "hg+ssh", - "svn", "svn+svn", "svn+http", "svn+https", "svn+ssh", - "bzr+http", "bzr+https", "bzr+ssh", "bzr+sftp", "bzr+ftp", "bzr+lp") - - OPERATING_SYSTEMS = {"windows": ["win32"], - "linux": lambda x: x.startswith("linux"), - "macos": ["darwin"], - "freebsd": lambda x: x.startswith("freebsd")} - - PIP_INAPPLICABLE_ARGUMENTS = {"uninstall": ["--user"]} - - RECONNECT_HOOKS = ["octoprint.comm.protocol.*",] - - # noinspection PyMissingConstructor - def __init__(self): - self._pending_enable = set() - self._pending_disable = set() - self._pending_install = set() - self._pending_uninstall = set() - - self._pip_caller = None - - self._repository_available = False - self._repository_plugins = [] - self._repository_cache_path = None - self._repository_cache_ttl = 0 - self._repository_mtime = None - - self._notices = {} - self._notices_available = False - self._notices_cache_path = None - self._notices_cache_ttl = 0 - self._notices_mtime = None - - self._orphans = None - - self._console_logger = None - - self._get_throttled = lambda: False - - self._install_task = None - self._install_lock = threading.RLock() - - def initialize(self): - self._console_logger = logging.getLogger("octoprint.plugins.pluginmanager.console") - self._repository_cache_path = os.path.join(self.get_plugin_data_folder(), "plugins.json") - self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60 - self._notices_cache_path = os.path.join(self.get_plugin_data_folder(), "notices.json") - self._notices_cache_ttl = self._settings.get_int(["notices_ttl"]) * 60 - self._confirm_disable = self._settings.global_get_boolean(["confirm_disable"]) - - self._pip_caller = LocalPipCaller(force_user=self._settings.get_boolean(["pip_force_user"])) - self._pip_caller.on_log_call = self._log_call - self._pip_caller.on_log_stdout = self._log_stdout - self._pip_caller.on_log_stderr = self._log_stderr - - ##~~ Body size hook - - def increase_upload_bodysize(self, current_max_body_sizes, *args, **kwargs): - # set a maximum body size of 50 MB for plugin archive uploads - return [("POST", r"/upload_file", 50 * 1024 * 1024)] - - # Additional permissions hook - - def get_additional_permissions(self): - return [{"key": "MANAGE", - "name": "Manage plugins", - "description": gettext("Allows to enable, disable and uninstall installed plugins."), - "default_groups": [ADMIN_GROUP], - "roles": ["manage"]}, - {"key": "INSTALL", - "name": "Install new plugins", - "description": gettext("Allows to install new plugins. Includes the \"Manage plugins\" permission."), - "default_groups": [ADMIN_GROUP], - "roles": ["install"], - "permissions": ["PLUGIN_PLUGINMANAGER_MANAGE"], - "dangerous": True}] - - ##~~ StartupPlugin - - def on_after_startup(self): - from octoprint.logging.handlers import CleaningTimedRotatingFileHandler - console_logging_handler = CleaningTimedRotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="console"), when="D", backupCount=3) - console_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s")) - console_logging_handler.setLevel(logging.DEBUG) - - self._console_logger.addHandler(console_logging_handler) - self._console_logger.setLevel(logging.DEBUG) - self._console_logger.propagate = False - - helpers = self._plugin_manager.get_helpers("pi_support", "get_throttled") - if helpers and "get_throttled" in helpers: - self._get_throttled = helpers["get_throttled"] - if self._settings.get_boolean(["ignore_throttled"]): - self._logger.warning("!!! THROTTLE STATE IGNORED !!! You have configured the Plugin Manager plugin to ignore an active throttle state of the underlying system. You might run into stability issues or outright corrupt your install. Consider fixing the throttling issue instead of suppressing it.") - - # decouple repository fetching from server startup - self._fetch_all_data(do_async=True) - - ##~~ SettingsPlugin - - def get_settings_defaults(self): - return {"repository": "https://plugins.octoprint.org/plugins.json", - "repository_ttl": 24*60, - "notices": "https://plugins.octoprint.org/notices.json", - "notices_ttl": 6*60, - "pip_args": None, - "pip_force_user": False, - "confirm_disable": False, - "dependency_links": False, - "hidden": [], - "ignore_throttled": False} - - def on_settings_save(self, data): - octoprint.plugin.SettingsPlugin.on_settings_save(self, data) - - self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60 - self._notices_cache_ttl = self._settings.get_int(["notices_ttl"]) * 60 - self._pip_caller.force_user = self._settings.get_boolean(["pip_force_user"]) - self._confirm_disable = self._settings.global_get_boolean(["confirm_disable"]) - - ##~~ AssetPlugin - - def get_assets(self): - return {"js": ["js/pluginmanager.js"], - "clientjs": ["clientjs/pluginmanager.js"], - "css": ["css/pluginmanager.css"], - "less": ["less/pluginmanager.less"]} - - ##~~ TemplatePlugin - - def get_template_configs(self): - return [{"type": "settings", - "name": gettext("Plugin Manager"), - "template": "pluginmanager_settings.jinja2", - "custom_bindings": True}, - {"type": "about", - "name": "Plugin Licenses", - "template": "pluginmanager_about.jinja2"}] - - def get_template_vars(self): - plugins = sorted(self._get_plugins(), key=lambda x: x["name"].lower()) - return {"all": plugins, - "thirdparty": list(filter(lambda p: not p["bundled"], plugins)), - "file_extensions": self.ARCHIVE_EXTENSIONS + self.PYTHON_EXTENSIONS} - - def get_template_types(self, template_sorting, template_rules, *args, **kwargs): - return [("about_thirdparty", - {}, - {"template": lambda x: x + "_about_thirdparty.jinja2"})] - - ##~~ BlueprintPlugin - - @octoprint.plugin.BlueprintPlugin.route("/upload_file", methods=["POST"]) - @no_firstrun_access - @Permissions.PLUGIN_PLUGINMANAGER_INSTALL.require(403) - def upload_file(self): - import flask - - input_name = "file" - input_upload_path = input_name + "." + self._settings.global_get(["server", "uploads", "pathSuffix"]) - input_upload_name = input_name + "." + self._settings.global_get(["server", "uploads", "nameSuffix"]) - - if input_upload_path not in flask.request.values or input_upload_name not in flask.request.values: - return flask.make_response("No file included", 400) - upload_path = flask.request.values[input_upload_path] - upload_name = flask.request.values[input_upload_name] - - exts = list(filter(lambda x: upload_name.lower().endswith(x), self.ARCHIVE_EXTENSIONS + self.PYTHON_EXTENSIONS)) - if not len(exts): - return flask.make_response("File doesn't have a valid extension for a plugin archive or a single file plugin", 400) - - ext = exts[0] - - archive = tempfile.NamedTemporaryFile(delete=False, suffix="{ext}".format(**locals())) - try: - archive.close() - shutil.copy(upload_path, archive.name) - return self.command_install(path=archive.name, - name=upload_name, - force="force" in flask.request.values and flask.request.values["force"] in valid_boolean_trues) - finally: - try: - os.remove(archive.name) - except Exception as e: - self._logger.warning("Could not remove temporary file {path} again: {message}".format(path=archive.name, message=str(e))) - - def is_blueprint_protected(self): - return False - - ##~~ EventHandlerPlugin - - def on_event(self, event, payload): - from octoprint.events import Events - if event != Events.CONNECTIVITY_CHANGED or not payload or not payload.get("new", False): - return - self._fetch_all_data(do_async=True) - - ##~~ SimpleApiPlugin - - def get_api_commands(self): - return { - "install": ["url"], - "uninstall": ["plugin"], - "enable": ["plugin"], - "disable": ["plugin"], - "cleanup": ["plugin"], - "cleanup_all": [], - "refresh_repository": [] - } - - def on_api_get(self, request): - if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can(): - return make_response("Insufficient rights", 403) - - from octoprint.server import safe_mode - - refresh_repository = request.values.get("refresh_repository", "false") in valid_boolean_trues - if refresh_repository or not self._is_repository_cache_valid(): - self._repository_available = self._refresh_repository() - - refresh_notices = request.values.get("refresh_notices", "false") in valid_boolean_trues - if refresh_notices or not self._is_notices_cache_valid(): - self._notices_available = self._refresh_notices() - - refresh_orphan = request.values.get("refresh_orphans", "false") in valid_boolean_trues - - def view(): - return jsonify(plugins=self._get_plugins(), - repository={"available": self._repository_available, - "plugins": self._repository_plugins}, - orphan_data=self._get_orphans(refresh=refresh_orphan), - os=get_os(), - octoprint=get_octoprint_version_string(), - pip={"available": self._pip_caller.available, - "version": self._pip_caller.version_string, - "install_dir": self._pip_caller.install_dir, - "use_user": self._pip_caller.use_user, - "virtual_env": self._pip_caller.virtual_env, - "additional_args": self._settings.get(["pip_args"]), - "python": sys.executable}, - safe_mode=safe_mode, - online=self._connectivity_checker.online) - - def etag(): - import hashlib - hash = hashlib.sha1() - def hash_update(value): - value = value.encode('utf-8') - hash.update(value) - - hash_update(repr(self._get_plugins())) - hash_update(str(self._repository_available)) - hash_update(repr(self._repository_plugins)) - hash_update(str(self._notices_available)) - hash_update(repr(self._notices)) - hash_update(repr(self._get_orphans())) - hash_update(repr(safe_mode)) - hash_update(repr(self._connectivity_checker.online)) - hash_update(repr(_DATA_FORMAT_VERSION)) - return hash.hexdigest() - - def condition(): - return check_etag(etag()) - - return with_revalidation_checking(etag_factory=lambda *args, **kwargs: etag(), - condition=lambda *args, **kwargs: condition(), - unless=lambda: refresh_repository or refresh_notices or refresh_orphan)(view)() - - def on_api_command(self, command, data): - if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can(): - return make_response("Insufficient rights", 403) - - if self._printer.is_printing() or self._printer.is_paused(): - # do not update while a print job is running - return make_response("Printer is currently printing or paused", 409) - - if command == "install": - if not Permissions.PLUGIN_PLUGINMANAGER_INSTALL.can(): - return make_response("Insufficient rights", 403) - url = data["url"] - plugin_name = data["plugin"] if "plugin" in data else None - - with self._install_lock: - if self._install_task is not None: - return make_response("There's always a plugin being installed", 409) - - self._install_task = threading.Thread(target=self.command_install, - kwargs={"url": url, - "force": "force" in data and data["force"] in valid_boolean_trues, - "dependency_links": "dependency_links" in data - and data["dependency_links"] in valid_boolean_trues, - "reinstall": plugin_name}) - self._install_task.daemon = True - self._install_task.start() - - return jsonify(in_progress=True) - - elif command == "uninstall": - plugin_name = data["plugin"] - if not plugin_name in self._plugin_manager.plugins: - return make_response("Unknown plugin: %s" % plugin_name, 404) - - plugin = self._plugin_manager.plugins[plugin_name] - return self.command_uninstall(plugin, cleanup=data.get("cleanup", False)) - - elif command == "cleanup": - plugin = data["plugin"] - try: - plugin = self._plugin_manager.plugins[plugin] - except KeyError: - # not installed, we are cleaning up left overs, that's ok - pass - - return self.command_cleanup(plugin, include_disabled=True) - - elif command == "cleanup_all": - return self.command_cleanup_all() - - elif command == "enable" or command == "disable": - plugin_name = data["plugin"] - if not plugin_name in self._plugin_manager.plugins: - return make_response("Unknown plugin: %s" % plugin_name, 404) - - plugin = self._plugin_manager.plugins[plugin_name] - return self.command_toggle(plugin, command) - - # noinspection PyMethodMayBeStatic - def _is_archive(self, path): - _, ext = os.path.splitext(path) - if ext in PluginManagerPlugin.ARCHIVE_EXTENSIONS: - return True - - kind = filetype.guess(to_native_str(path)) - if kind: - return ".{}".format(kind.extension) in PluginManagerPlugin.ARCHIVE_EXTENSIONS - return False - - def _is_pythonfile(self, path): - _, ext = os.path.splitext(path) - if ext in PluginManagerPlugin.PYTHON_EXTENSIONS: - import ast - try: - with io.open(path, 'rb') as f: - ast.parse(f.read(), filename=path) - return True - except Exception as exc: - self._logger.exception("Could not parse {} as python file: {}".format(path, exc)) - - return False - - def command_install(self, url=None, path=None, name=None, force=False, reinstall=None, dependency_links=False): - folder = None - - with self._install_lock: - try: - source = path - source_type = "path" - - if url is not None: - # fetch URL - folder = TemporaryDirectory() - path = download_file(url, folder.name) - source = url - source_type = "url" - - # determine type of path - if self._is_archive(path): - return self._command_install_archive(path, - source=source, - source_type=source_type, - force=force, - reinstall=reinstall, - dependency_links=dependency_links) - - elif self._is_pythonfile(path): - return self._command_install_pythonfile(path, - source=source, - source_type=source_type, - name=name) - - else: - self._logger.error("{} is neither an archive nor a python file, can't install that.".format(source)) - result = {"result": False, - "source": source, - "source_type": source_type, - "reason": "Could not install plugin from {}, was neither " - "a plugin archive nor a single file plugin".format(source)} - self._send_result_notification("install", result) - return result - - finally: - if folder is not None: - folder.cleanup() - self._install_task = None - - # noinspection DuplicatedCode - def _command_install_archive(self, path, source=None, source_type=None, force=False, reinstall=None, dependency_links=False): - throttled = self._get_throttled() - if throttled and isinstance(throttled, dict) and throttled.get("current_issue", False) and not self._settings.get_boolean(["ignore_throttled"]): - # currently throttled, we refuse to run - return make_response("System is currently throttled, refusing to install " - "anything due to possible stability issues", 409) - - try: - # Py3 - from urllib.parse import quote as url_quote - except ImportError: - # Py2 - from urllib import quote as url_quote - - path = os.path.abspath(path) - if os.sep != "/": - # windows gets special handling - drive, loc = os.path.splitdrive(path) - path_url = "file:///" + drive.lower() + url_quote(loc.replace(os.sep, "/").lower()) - shell_quote = lambda x: x # do not shell quote under windows, non posix shell - else: - path_url = "file://" + url_quote(path) - shell_quote = sarge.shell_quote - - already_installed_check = lambda line: path_url in line.lower() # lower case in case of windows - - self._logger.info("Installing plugin from {}".format(source)) - pip_args = ["--disable-pip-version-check", "install", shell_quote(path_url), "--no-cache-dir"] - - if dependency_links or self._settings.get_boolean(["dependency_links"]): - pip_args.append("--process-dependency-links") - - all_plugins_before = self._plugin_manager.find_plugins(existing={}) - - try: - returncode, stdout, stderr = self._call_pip(pip_args) - - # pip's output for a package that is already installed looks something like any of these: - # - # Requirement already satisfied (use --upgrade to upgrade): OctoPrint-Plugin==1.0 from \ - # https://example.com/foobar.zip in - # Requirement already satisfied (use --upgrade to upgrade): OctoPrint-Plugin in - # Requirement already satisfied (use --upgrade to upgrade): OctoPrint-Plugin==1.0 from \ - # file:///tmp/foobar.zip in - # Requirement already satisfied (use --upgrade to upgrade): OctoPrint-Plugin==1.0 from \ - # file:///C:/Temp/foobar.zip in - # - # If we detect any of these matching what we just tried to install, we'll need to trigger a second - # install with reinstall flags. - - if not force and any(map(lambda x: x.strip().startswith(already_installed_string) and already_installed_check(x), - stdout)): - self._logger.info("Plugin to be installed from {} was already installed, forcing a reinstall".format(source)) - self._log_message("Looks like the plugin was already installed. Forcing a reinstall.") - force = True - except Exception: - self._logger.exception("Could not install plugin from %s" % source) - return make_response("Could not install plugin from URL, see the log for more details", 500) - else: - if force: - # We don't use --upgrade here because that will also happily update all our dependencies - we'd rather - # do that in a controlled manner - pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"] - try: - returncode, stdout, stderr = self._call_pip(pip_args) - except Exception: - self._logger.exception("Could not install plugin from {}".format(source)) - return make_response("Could not install plugin from source {}, see the log for more details" - .format(source), 500) - - try: - result_line = list(filter(lambda x: x.startswith(success_string) or x.startswith(failure_string), - stdout))[-1] - except IndexError: - self._logger.error("Installing the plugin from {} failed, could not parse output from pip. " - "See plugin_pluginmanager_console.log for generated output".format(source)) - result = {"result": False, - "source": source, - "source_type": source_type, - "reason": "Could not parse output from pip, see plugin_pluginmanager_console.log " - "for generated output"} - self._send_result_notification("install", result) - return jsonify(result) - - # The final output of a pip install command looks something like this: - # - # Successfully installed OctoPrint-Plugin-1.0 Dependency-One-0.1 Dependency-Two-9.3 - # - # or this: - # - # Successfully installed OctoPrint-Plugin Dependency-One Dependency-Two - # Cleaning up... - # - # So we'll need to fetch the "Successfully installed" line, strip the "Successfully" part, then split - # by whitespace and strip to get all installed packages. - # - # We then need to iterate over all known plugins and see if either the package name or the package name plus - # version number matches one of our installed packages. If it does, that's our installed plugin. - # - # Known issue: This might return the wrong plugin if more than one plugin was installed through this - # command (e.g. due to pulling in another plugin as dependency). It should be safe for now though to - # consider this a rare corner case. Once it becomes a real problem we'll just extend the plugin manager - # so that it can report on more than one installed plugin. - - result_line = result_line.strip() - if not result_line.startswith(success_string): - self._logger.error("Installing the plugin from {} failed, pip did not report successful installation" - .format(source)) - result = {"result": False, - "source": source, - "source_type": source_type, - "reason": "Pip did not report successful installation"} - self._send_result_notification("install", result) - return result - - installed = list(map(lambda x: x.strip(), result_line[len(success_string):].split(" "))) - all_plugins_after = self._plugin_manager.find_plugins(existing={}, ignore_uninstalled=False) - - new_plugin = self._find_installed_plugin(installed, plugins=all_plugins_after) - - if new_plugin is None: - self._logger.warning("The plugin was installed successfully, but couldn't be found afterwards to " - "initialize properly during runtime. Please restart OctoPrint.") - result = {"result": True, - "source": source, - "source_type": source_type, - "needs_restart": True, - "needs_refresh": True, - "needs_reconnect": True, - "was_reinstalled": False, - "plugin": "unknown"} - self._send_result_notification("install", result) - return result - - self._plugin_manager.reload_plugins() - needs_restart = self._plugin_manager.is_restart_needing_plugin(new_plugin) \ - or new_plugin.key in all_plugins_before \ - or reinstall is not None - needs_refresh = new_plugin.implementation \ - and isinstance(new_plugin.implementation, octoprint.plugin.ReloadNeedingPlugin) - needs_reconnect = self._plugin_manager.has_any_of_hooks(new_plugin, self._reconnect_hooks) and self._printer.is_operational() - - is_reinstall = self._plugin_manager.is_plugin_marked(new_plugin.key, "uninstalled") - self._plugin_manager.mark_plugin(new_plugin.key, - uninstalled=False, - installed=not is_reinstall and needs_restart) - - self._plugin_manager.log_all_plugins() - - self._logger.info("The plugin was installed successfully: {}, version {}".format(new_plugin.name, new_plugin.version)) - - # noinspection PyUnresolvedReferences - self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN, {"id": new_plugin.key, - "version": new_plugin.version, - "source": source, - "source_type": source_type}) - - result = {"result": True, - "source": source, - "source_type": source_type, - "needs_restart": needs_restart, - "needs_refresh": needs_refresh, - "needs_reconnect": needs_reconnect, - "was_reinstalled": new_plugin.key in all_plugins_before or reinstall is not None, - "plugin": self._to_external_plugin(new_plugin)} - self._send_result_notification("install", result) - return result - - # noinspection DuplicatedCode - def _command_install_pythonfile(self, path, source=None, source_type=None, name=None): - if name is None: - name = os.path.basename(path) - - self._logger.info("Installing single file plugin {} from {}".format(name, source)) - - all_plugins_before = self._plugin_manager.find_plugins(existing={}) - - destination = os.path.join(self._settings.global_get_basefolder("plugins"), name) - plugin_id, _ = os.path.splitext(name) - - try: - self._log_call("cp {} {}".format(path, destination)) - shutil.copy(path, destination) - except: - self._logger.exception("Installing plugin from {} failed".format(source)) - result = {"result": False, - "source": source, - "source_type": source_type, - "reason": "Plugin could not be copied"} - self._send_result_notification("install", result) - return result - - plugins = self._plugin_manager.find_plugins(existing={}, ignore_uninstalled=False) - new_plugin = plugins.get(plugin_id) - if new_plugin is None: - self._logger.warning("The plugin was installed successfully, but couldn't be found afterwards to " - "initialize properly during runtime. Please restart OctoPrint.") - result = {"result": True, - "source": source, - "source_type": source_type, - "needs_restart": True, - "needs_refresh": True, - "needs_reconnect": True, - "was_reinstalled": False, - "plugin": "unknown"} - self._send_result_notification("install", result) - return result - - self._plugin_manager.reload_plugins() - needs_restart = self._plugin_manager.is_restart_needing_plugin(new_plugin) \ - or new_plugin.key in all_plugins_before - needs_refresh = new_plugin.implementation \ - and isinstance(new_plugin.implementation, octoprint.plugin.ReloadNeedingPlugin) - needs_reconnect = self._plugin_manager.has_any_of_hooks(new_plugin, self._reconnect_hooks) and self._printer.is_operational() - - self._logger.info("The plugin was installed successfully: {}, version {}".format(new_plugin.name, new_plugin.version)) - self._plugin_manager.log_all_plugins() - - # noinspection PyUnresolvedReferences - self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN, {"id": new_plugin.key, - "version": new_plugin.version, - "source": source, - "source_type": source_type}) - - result = {"result": True, - "source": source, - "source_type": source_type, - "needs_restart": needs_restart, - "needs_refresh": needs_refresh, - "needs_reconnect": needs_reconnect, - "was_reinstalled": new_plugin.key in all_plugins_before, - "plugin": self._to_external_plugin(new_plugin)} - self._send_result_notification("install", result) - return result - - def command_uninstall(self, plugin, cleanup=False): - if plugin.key == "pluginmanager": - return make_response("Can't uninstall Plugin Manager", 403) - - if not plugin.managable: - return make_response("Plugin is not managable and hence cannot be uninstalled", 403) - - if plugin.bundled: - return make_response("Bundled plugins cannot be uninstalled", 403) - - if plugin.origin is None: - self._logger.warning("Trying to uninstall plugin {plugin} but origin is unknown".format(**locals())) - return make_response("Could not uninstall plugin, its origin is unknown") - - if plugin.origin.type == "entry_point": - # plugin is installed through entry point, need to use pip to uninstall it - origin = plugin.origin[3] - if origin is None: - origin = plugin.origin[2] - - pip_args = ["--disable-pip-version-check", "uninstall", "--yes", origin] - try: - self._call_pip(pip_args) - except Exception: - self._logger.exception("Could not uninstall plugin via pip") - return make_response("Could not uninstall plugin via pip, see the log for more details", 500) - - elif plugin.origin.type == "folder": - import os - import shutil - full_path = os.path.realpath(plugin.location) - - if os.path.isdir(full_path): - # plugin is installed via a plugin folder, need to use rmtree to get rid of it - self._log_stdout("Deleting plugin from {folder}".format(folder=plugin.location)) - shutil.rmtree(full_path) - elif os.path.isfile(full_path): - self._log_stdout("Deleting plugin from {file}".format(file=plugin.location)) - os.remove(full_path) - - if full_path.endswith(".py"): - pyc_file = "{full_path}c".format(**locals()) - if os.path.isfile(pyc_file): - os.remove(pyc_file) - - else: - self._logger.warning("Trying to uninstall plugin {plugin} but origin is unknown ({plugin.origin.type})".format(**locals())) - return make_response("Could not uninstall plugin, its origin is unknown") - - needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin) or cleanup - needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin) - needs_reconnect = self._plugin_manager.has_any_of_hooks(plugin, self._reconnect_hooks) and self._printer.is_operational() - - was_pending_install = self._plugin_manager.is_plugin_marked(plugin.key, "installed") - self._plugin_manager.mark_plugin(plugin.key, - uninstalled=not was_pending_install and needs_restart, - installed=False) - - if not needs_restart: - try: - if plugin.enabled: - self._plugin_manager.disable_plugin(plugin.key, plugin=plugin) - except octoprint.plugin.core.PluginLifecycleException as e: - self._logger.exception("Problem disabling plugin {name}".format(name=plugin.key)) - result = {"result": False, "uninstalled": True, "disabled": False, "unloaded": False, "reason": e.reason} - self._send_result_notification("uninstall", result) - return jsonify(result) - - try: - if plugin.loaded: - self._plugin_manager.unload_plugin(plugin.key) - except octoprint.plugin.core.PluginLifecycleException as e: - self._logger.exception("Problem unloading plugin {name}".format(name=plugin.key)) - result = {"result": False, "uninstalled": True, "disabled": True, "unloaded": False, "reason": e.reason} - self._send_result_notification("uninstall", result) - return jsonify(result) - - self._plugin_manager.reload_plugins() - - # noinspection PyUnresolvedReferences - self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_UNINSTALL_PLUGIN, {"id": plugin.key, - "version": plugin.version}) - - result = {"result": True, - "needs_restart": needs_restart, - "needs_refresh": needs_refresh, - "needs_reconnect": needs_reconnect, - "plugin": self._to_external_plugin(plugin)} - self._send_result_notification("uninstall", result) - self._logger.info("Plugin {} uninstalled".format(plugin.key)) - - self._cleanup_disabled(plugin.key) - if cleanup: - self.command_cleanup(plugin.key, result_notifications=False) - - return jsonify(result) - - def command_cleanup(self, plugin, include_disabled=False, result_notifications=True, settings_save=True): - if isinstance(plugin, basestring): - key = result_value = plugin - else: - key = plugin.key - result_value = self._to_external_plugin(plugin) - - message = "Cleaning up plugin {}...".format(key) - self._logger.info(message) - self._log_stdout(message) - - # delete plugin settings - self._cleanup_settings(key) - - # delete plugin disabled entry - if include_disabled: - self._cleanup_disabled(key) - - # delete plugin data folder - result_data = True - if not self._cleanup_data(key): - message = "Could not delete data folder of plugin {}".format(key) - self._logger.exception(message) - self._log_stderr(message) - result_data = False - - if settings_save: - self._settings.save() - - result = {"result": result_data, - "needs_restart": True, - "plugin": result_value} - if result_notifications: - self._send_result_notification("cleanup", result) - - # cleaning orphan cache - self._orphans = None - - return jsonify(result) - - def command_cleanup_all(self): - orphans = self._get_orphans() - cleaned_up = set() - - for orphan in sorted(orphans.keys()): - self.command_cleanup(orphan, - include_disabled=True, - result_notifications=False, - settings_save=False) - cleaned_up.add(orphan) - - self._settings.save() - - result = {"result": True, - "needs_restart": len(cleaned_up) > 0, - "cleaned_up": sorted(list(cleaned_up))} - self._send_result_notification("cleanup_all", result) - self._logger.info("Cleaned up all data, {} left overs removed".format(len(cleaned_up))) - - # cleaning orphan cache - self._orphans = None - - return jsonify(result) - - def _cleanup_disabled(self, plugin): - # delete from disabled list - disabled = self._settings.global_get(["plugins", "_disabled"]) - try: - disabled.remove(plugin) - except ValueError: - # not in list, ok - pass - self._settings.global_set(["plugins", "_disabled"], disabled) - - def _cleanup_settings(self, plugin): - # delete plugin settings - self._settings.global_remove(["plugins", plugin]) - self._settings.global_remove(["server", "seenWizards", plugin]) - return True - - def _cleanup_data(self, plugin): - import os - import shutil - - data_folder = os.path.join(self._settings.getBaseFolder("data"), plugin) - if os.path.exists(data_folder): - try: - shutil.rmtree(data_folder) - return True - except Exception: - self._logger.exception("Could not delete plugin data folder at {}".format(data_folder)) - return False - else: - return True - - def command_toggle(self, plugin, command): - if plugin.key == "pluginmanager" or (plugin.hidden and plugin.bundled): - return make_response("Can't enable/disable Plugin Manager", 400) - - pending = ((command == "disable" and plugin.key in self._pending_enable) or (command == "enable" and plugin.key in self._pending_disable)) - safe_mode_victim = getattr(plugin, "safe_mode_victim", False) - - needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin) - needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin) - needs_reconnect = self._plugin_manager.has_any_of_hooks(plugin, self._reconnect_hooks) and self._printer.is_operational() - - needs_restart_api = (needs_restart or safe_mode_victim or plugin.forced_disabled) and not pending - needs_refresh_api = needs_refresh and not pending - needs_reconnect_api = needs_reconnect and not pending - - try: - if command == "disable": - self._mark_plugin_disabled(plugin, needs_restart=needs_restart) - elif command == "enable": - self._mark_plugin_enabled(plugin, needs_restart=needs_restart) - except octoprint.plugin.core.PluginLifecycleException as e: - self._logger.exception("Problem toggling enabled state of {name}: {reason}".format(name=plugin.key, reason=e.reason)) - result = {"result": False, "reason": e.reason} - except octoprint.plugin.core.PluginNeedsRestart: - result = {"result": True, - "needs_restart": True, - "needs_refresh": True, - "needs_reconnect": True, - "plugin": self._to_external_plugin(plugin)} - else: - result = {"result": True, - "needs_restart": needs_restart_api, - "needs_refresh": needs_refresh_api, - "needs_reconnect": needs_reconnect_api, - "plugin": self._to_external_plugin(plugin)} - - self._send_result_notification(command, result) - return jsonify(result) - - def _find_installed_plugin(self, packages, plugins=None): - if plugins is None: - plugins = self._plugin_manager.find_plugins(existing={}, ignore_uninstalled=False) - - for key, plugin in plugins.items(): - if plugin.origin is None or plugin.origin.type != "entry_point": - continue - - package_name = plugin.origin.package_name - package_version = plugin.origin.package_version - versioned_package = "{package_name}-{package_version}".format(**locals()) - - if package_name in packages or versioned_package in packages: - # exact match, we are done here - return plugin - - else: - # it might still be a version that got stripped by python's package resources, e.g. 1.4.5a0 => 1.4.5a - found = False - - for inst in packages: - if inst.startswith(versioned_package): - found = True - break - - if found: - return plugin - - return None - - def _send_result_notification(self, action, result): - notification = {"type": "result", "action": action} - notification.update(result) - self._plugin_manager.send_plugin_message(self._identifier, notification) - - def _call_pip(self, args): - if self._pip_caller is None or not self._pip_caller.available: - raise RuntimeError("No pip available, can't operate".format(**locals())) - - if "--process-dependency-links" in args: - self._log_message("Installation needs to process external dependencies, that might make it take a bit longer than usual depending on the pip version") - - additional_args = self._settings.get(["pip_args"]) - - if additional_args is not None: - - inapplicable_arguments = self.__class__.PIP_INAPPLICABLE_ARGUMENTS.get(args[0], list()) - for inapplicable_argument in inapplicable_arguments: - additional_args = re.sub(r"(^|\s)" + re.escape(inapplicable_argument) + r"\\b", "", additional_args) - - if additional_args: - args.append(additional_args) - - kwargs = {"env": {"PYTHONWARNINGS": "ignore:DEPRECATION::pip._internal.cli.base_command"}} - - return self._pip_caller.execute(*args, **kwargs) - - def _log_message(self, *lines): - self._log(lines, prefix="*", stream="message") - - def _log_call(self, *lines): - self._log(lines, prefix=" ", stream="call") - - def _log_stdout(self, *lines): - self._log(lines, prefix=">", stream="stdout") - - def _log_stderr(self, *lines): - self._log(lines, prefix="!", stream="stderr") - - def _log(self, lines, prefix=None, stream=None, strip=True): - if strip: - lines = list(map(lambda x: x.strip(), lines)) - - self._plugin_manager.send_plugin_message(self._identifier, {"type": "loglines", - "loglines": [{"line": line, "stream": stream} for line in lines]}) - for line in lines: - self._console_logger.debug("{prefix} {line}".format(**locals())) - - def _mark_plugin_enabled(self, plugin, needs_restart=False): - disabled_list = list(self._settings.global_get(["plugins", "_disabled"], - validator=lambda x: isinstance(x, list), - fallback=[])) - if plugin.key in disabled_list: - disabled_list.remove(plugin.key) - self._settings.global_set(["plugins", "_disabled"], disabled_list) - self._settings.save(force=True) - - if not needs_restart and not plugin.forced_disabled and not getattr(plugin, "safe_mode_victim", False): - self._plugin_manager.enable_plugin(plugin.key) - else: - if plugin.key in self._pending_disable: - self._pending_disable.remove(plugin.key) - elif not plugin.enabled and plugin.key not in self._pending_enable: - self._pending_enable.add(plugin.key) - - # noinspection PyUnresolvedReferences - self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_ENABLE_PLUGIN, {"id": plugin.key, - "version": plugin.version}) - - def _mark_plugin_disabled(self, plugin, needs_restart=False): - disabled_list = list(self._settings.global_get(["plugins", "_disabled"], - validator=lambda x: isinstance(x, list), - fallback=[])) - if not plugin.key in disabled_list: - disabled_list.append(plugin.key) - self._settings.global_set(["plugins", "_disabled"], disabled_list) - self._settings.save(force=True) - - if not needs_restart and not plugin.forced_disabled and not getattr(plugin, "safe_mode_victim", False): - self._plugin_manager.disable_plugin(plugin.key) - else: - if plugin.key in self._pending_enable: - self._pending_enable.remove(plugin.key) - elif (plugin.enabled or plugin.forced_disabled or getattr(plugin, "safe_mode_victim", False)) and plugin.key not in self._pending_disable: - self._pending_disable.add(plugin.key) - - # noinspection PyUnresolvedReferences - self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_DISABLE_PLUGIN, {"id": plugin.key, - "version": plugin.version}) - - def _fetch_all_data(self, do_async=False): - def run(): - self._repository_available = self._fetch_repository_from_disk() - self._notices_available = self._fetch_notices_from_disk() - - if do_async: - thread = threading.Thread(target=run) - thread.daemon = True - thread.start() - else: - run() - - def _is_repository_cache_valid(self, mtime=None): - import time - if mtime is None: - mtime = self._repository_mtime - if mtime is None: - return False - return mtime + self._repository_cache_ttl >= time.time() > mtime - - def _fetch_repository_from_disk(self): - repo_data = None - if os.path.isfile(self._repository_cache_path): - import time - mtime = os.path.getmtime(self._repository_cache_path) - if self._is_repository_cache_valid(mtime=mtime): - try: - import json - with io.open(self._repository_cache_path, 'rt', encoding='utf-8') as f: - repo_data = json.load(f) - self._repository_mtime = mtime - self._logger.info("Loaded plugin repository data from disk, was still valid") - except Exception: - self._logger.exception("Error while loading repository data from {}".format(self._repository_cache_path)) - - return self._refresh_repository(repo_data=repo_data) - - def _fetch_repository_from_url(self): - if not self._connectivity_checker.online: - self._logger.info("Looks like we are offline, can't fetch repository from network") - return None - - repository_url = self._settings.get(["repository"]) - try: - r = requests.get(repository_url, timeout=30) - r.raise_for_status() - self._logger.info("Loaded plugin repository data from {}".format(repository_url)) - except Exception as e: - self._logger.exception("Could not fetch plugins from repository at {repository_url}: {message}".format(repository_url=repository_url, message=e)) - return None - - try: - repo_data = r.json() - except Exception as e: - self._logger.exception("Error while reading repository data: {}".format(e)) - return None - - # validation - if not isinstance(repo_data, (list, tuple)): - self._logger.warning("Invalid repository data: expected a list, got {!r}".format(repo_data)) - return None - - try: - import json - with octoprint.util.atomic_write(self._repository_cache_path, mode='wb') as f: - f.write(to_bytes(json.dumps(repo_data))) - self._repository_mtime = os.path.getmtime(self._repository_cache_path) - except Exception as e: - self._logger.exception("Error while saving repository data to {}: {}".format(self._repository_cache_path, e)) - - return repo_data - - def _refresh_repository(self, repo_data=None): - if repo_data is None: - repo_data = self._fetch_repository_from_url() - if repo_data is None: - return False - - self._repository_plugins = list(filter(lambda x: x is not None, - map(map_repository_entry, repo_data))) - return True - - def _is_notices_cache_valid(self, mtime=None): - import time - if mtime is None: - mtime = self._notices_mtime - if mtime is None: - return False - return mtime + self._notices_cache_ttl >= time.time() > mtime - - def _fetch_notices_from_disk(self): - notice_data = None - if os.path.isfile(self._notices_cache_path): - import time - mtime = os.path.getmtime(self._notices_cache_path) - if self._is_notices_cache_valid(mtime=mtime): - try: - import json - with io.open(self._notices_cache_path, 'rt', encoding='utf-8') as f: - notice_data = json.load(f) - self._notices_mtime = mtime - self._logger.info("Loaded notice data from disk, was still valid") - except Exception: - self._logger.exception("Error while loading notices from {}".format(self._notices_cache_path)) - - return self._refresh_notices(notice_data=notice_data) - - def _fetch_notices_from_url(self): - if not self._connectivity_checker.online: - self._logger.info("Looks like we are offline, can't fetch notices from network") - return None - - notices_url = self._settings.get(["notices"]) - try: - r = requests.get(notices_url, timeout=30) - r.raise_for_status() - self._logger.info("Loaded plugin notices data from {}".format(notices_url)) - except Exception as e: - self._logger.exception("Could not fetch notices from {notices_url}: {message}".format(notices_url=notices_url, message=str(e))) - return None - - notice_data = r.json() - - try: - import json - with octoprint.util.atomic_write(self._notices_cache_path, mode="wb") as f: - f.write(to_bytes(json.dumps(notice_data))) - self._notices_mtime = os.path.getmtime(self._notices_cache_path) - except Exception as e: - self._logger.exception("Error while saving notices to {}: {}".format(self._notices_cache_path, str(e))) - return notice_data - - def _refresh_notices(self, notice_data=None): - if notice_data is None: - notice_data = self._fetch_notices_from_url() - if notice_data is None: - return False - - notices = {} - for notice in notice_data: - if not "plugin" in notice or not "text" in notice or not "date" in notice: - continue - - key = notice["plugin"] - - try: - # Jekyll turns "%Y-%m-%d %H:%M:%SZ" into "%Y-%m-%d %H:%M:%S +0000", so be sure to ignore "+0000" - # - # Being able to use dateutil here would make things way easier but sadly that can no longer get - # installed (from source) under OctoPi 0.14 due to its setuptools-scm dependency, so we have to do - # without it for now until we can drop support for OctoPi 0.14. - parsed_date = datetime.strptime(notice["date"], "%Y-%m-%d %H:%M:%S +0000") - notice["timestamp"] = parsed_date.timetuple() - except Exception as e: - self._logger.warning("Error while parsing date {!r} for plugin notice " - "of plugin {}, ignoring notice: {}".format(notice["date"], key, str(e))) - continue - - if not key in notices: - notices[key] = [] - notices[key].append(notice) - - self._notices = notices - return True - - def _get_orphans(self, refresh=False): - from collections import defaultdict - - if self._orphans is not None and not refresh: - return self._orphans - - installed_keys = self._plugin_manager.plugins.keys() - orphans = defaultdict(lambda: {"settings": False, "data": False, "disabled": False}) - - # settings - for key in list(self._settings.global_get(["plugins"]).keys()): - if key.startswith("_"): - # internal key, like _disabled - continue - - if key not in installed_keys: - orphans[key]["settings"] = True - - # data - for entry in scandir(self._settings.getBaseFolder("data")): - if not entry.is_dir(): - continue - - if entry.name not in installed_keys: - orphans[entry.name]["data"] = True - - # disabled - disabled = self._settings.global_get(["plugins", "_disabled"]) - for key in disabled: - if key not in installed_keys: - orphans[key]["disabled"] = True - - self._orphans = dict(**orphans) - return self._orphans - - @property - def _reconnect_hooks(self): - reconnect_hooks = self.__class__.RECONNECT_HOOKS - - reconnect_hook_provider_hooks = self._plugin_manager.get_hooks("octoprint.plugin.pluginmanager.reconnect_hooks") - for name, hook in reconnect_hook_provider_hooks.items(): - try: - result = hook() - if isinstance(result, (list, tuple)): - reconnect_hooks.extend(filter(lambda x: isinstance(x, basestring), result)) - except Exception: - self._logger.exception("Error while retrieving additional hooks for which a " - "reconnect is required from plugin {name}".format(**locals()), - extra={"plugin": name}) - - return reconnect_hooks - - def _get_plugins(self): - plugins = self._plugin_manager.plugins - - hidden = self._settings.get(["hidden"]) - result = [] - for key, plugin in plugins.items(): - if key in hidden or (plugin.bundled and plugin.hidden): - continue - result.append(self._to_external_plugin(plugin)) - - return result - - def _to_external_plugin(self, plugin): - return {"key": plugin.key, - "name": plugin.name, - "description": plugin.description, - "disabling_discouraged": gettext(plugin.disabling_discouraged) if plugin.disabling_discouraged else False, - "author": plugin.author, - "version": plugin.version, - "url": plugin.url, - "license": plugin.license, - "python": plugin.pythoncompat, - "bundled": plugin.bundled, - "managable": plugin.managable, - "enabled": plugin.enabled, - "blacklisted": plugin.blacklisted, - "forced_disabled": plugin.forced_disabled, - "incompatible": plugin.incompatible, - "safe_mode_victim": getattr(plugin, "safe_mode_victim", False), - "pending_enable": (not plugin.enabled and not getattr(plugin, "safe_mode_victim", False) and plugin.key in self._pending_enable), - "pending_disable": ((plugin.enabled or getattr(plugin, "safe_mode_victim", False)) and plugin.key in self._pending_disable), - "pending_install": (self._plugin_manager.is_plugin_marked(plugin.key, "installed")), - "pending_uninstall": (self._plugin_manager.is_plugin_marked(plugin.key, "uninstalled")), - "origin": plugin.origin.type, - "notifications": self._get_notifications(plugin)} - - def _get_notifications(self, plugin): - key = plugin.key - if not plugin.enabled: - return - - if key not in self._notices: - return - - octoprint_version = get_octoprint_version(base=True) - plugin_notifications = self._notices.get(key, []) - - def map_notification(notification): - return self._to_external_notification(key, notification) - - return list(filter(lambda x: x is not None, - map(map_notification, - filter(lambda n: _filter_relevant_notification(n, plugin.version, octoprint_version), - plugin_notifications)))) - - def _to_external_notification(self, key, notification): - return {"key": key, - "date": time.mktime(notification["timestamp"]), - "text": notification["text"], - "link": notification.get("link"), - "versions": notification.get("pluginversions", notification.get("versions", [])), - "important": notification.get("important", False)} +class PluginManagerPlugin( + octoprint.plugin.SimpleApiPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.AssetPlugin, + octoprint.plugin.SettingsPlugin, + octoprint.plugin.StartupPlugin, + octoprint.plugin.BlueprintPlugin, + octoprint.plugin.EventHandlerPlugin, +): + + ARCHIVE_EXTENSIONS = (".zip", ".tar.gz", ".tgz", ".tar", ".gz") + PYTHON_EXTENSIONS = (".py",) + + # valid pip install URL schemes according to https://pip.pypa.io/en/stable/reference/pip_install/ + URL_SCHEMES = ( + "http", + "https", + "git", + "git+http", + "git+https", + "git+ssh", + "git+git", + "hg+http", + "hg+https", + "hg+static-http", + "hg+ssh", + "svn", + "svn+svn", + "svn+http", + "svn+https", + "svn+ssh", + "bzr+http", + "bzr+https", + "bzr+ssh", + "bzr+sftp", + "bzr+ftp", + "bzr+lp", + ) + + OPERATING_SYSTEMS = { + "windows": ["win32"], + "linux": lambda x: x.startswith("linux"), + "macos": ["darwin"], + "freebsd": lambda x: x.startswith("freebsd"), + } + + PIP_INAPPLICABLE_ARGUMENTS = {"uninstall": ["--user"]} + + RECONNECT_HOOKS = [ + "octoprint.comm.protocol.*", + ] + + # noinspection PyMissingConstructor + def __init__(self): + self._pending_enable = set() + self._pending_disable = set() + self._pending_install = set() + self._pending_uninstall = set() + + self._pip_caller = None + + self._repository_available = False + self._repository_plugins = [] + self._repository_cache_path = None + self._repository_cache_ttl = 0 + self._repository_mtime = None + + self._notices = {} + self._notices_available = False + self._notices_cache_path = None + self._notices_cache_ttl = 0 + self._notices_mtime = None + + self._orphans = None + + self._console_logger = None + + self._get_throttled = lambda: False + + self._install_task = None + self._install_lock = threading.RLock() + + def initialize(self): + self._console_logger = logging.getLogger( + "octoprint.plugins.pluginmanager.console" + ) + self._repository_cache_path = os.path.join( + self.get_plugin_data_folder(), "plugins.json" + ) + self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60 + self._notices_cache_path = os.path.join( + self.get_plugin_data_folder(), "notices.json" + ) + self._notices_cache_ttl = self._settings.get_int(["notices_ttl"]) * 60 + self._confirm_disable = self._settings.global_get_boolean(["confirm_disable"]) + + self._pip_caller = LocalPipCaller( + force_user=self._settings.get_boolean(["pip_force_user"]) + ) + self._pip_caller.on_log_call = self._log_call + self._pip_caller.on_log_stdout = self._log_stdout + self._pip_caller.on_log_stderr = self._log_stderr + + ##~~ Body size hook + + def increase_upload_bodysize(self, current_max_body_sizes, *args, **kwargs): + # set a maximum body size of 50 MB for plugin archive uploads + return [("POST", r"/upload_file", 50 * 1024 * 1024)] + + # Additional permissions hook + + def get_additional_permissions(self): + return [ + { + "key": "MANAGE", + "name": "Manage plugins", + "description": gettext( + "Allows to enable, disable and uninstall installed plugins." + ), + "default_groups": [ADMIN_GROUP], + "roles": ["manage"], + }, + { + "key": "INSTALL", + "name": "Install new plugins", + "description": gettext( + 'Allows to install new plugins. Includes the "Manage plugins" permission.' + ), + "default_groups": [ADMIN_GROUP], + "roles": ["install"], + "permissions": ["PLUGIN_PLUGINMANAGER_MANAGE"], + "dangerous": True, + }, + ] + + ##~~ StartupPlugin + + def on_after_startup(self): + from octoprint.logging.handlers import CleaningTimedRotatingFileHandler + + console_logging_handler = CleaningTimedRotatingFileHandler( + self._settings.get_plugin_logfile_path(postfix="console"), + when="D", + backupCount=3, + ) + console_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s")) + console_logging_handler.setLevel(logging.DEBUG) + + self._console_logger.addHandler(console_logging_handler) + self._console_logger.setLevel(logging.DEBUG) + self._console_logger.propagate = False + + helpers = self._plugin_manager.get_helpers("pi_support", "get_throttled") + if helpers and "get_throttled" in helpers: + self._get_throttled = helpers["get_throttled"] + if self._settings.get_boolean(["ignore_throttled"]): + self._logger.warning( + "!!! THROTTLE STATE IGNORED !!! You have configured the Plugin Manager plugin to ignore an active throttle state of the underlying system. You might run into stability issues or outright corrupt your install. Consider fixing the throttling issue instead of suppressing it." + ) + + # decouple repository fetching from server startup + self._fetch_all_data(do_async=True) + + ##~~ SettingsPlugin + + def get_settings_defaults(self): + return { + "repository": "https://plugins.octoprint.org/plugins.json", + "repository_ttl": 24 * 60, + "notices": "https://plugins.octoprint.org/notices.json", + "notices_ttl": 6 * 60, + "pip_args": None, + "pip_force_user": False, + "confirm_disable": False, + "dependency_links": False, + "hidden": [], + "ignore_throttled": False, + } + + def on_settings_save(self, data): + octoprint.plugin.SettingsPlugin.on_settings_save(self, data) + + self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60 + self._notices_cache_ttl = self._settings.get_int(["notices_ttl"]) * 60 + self._pip_caller.force_user = self._settings.get_boolean(["pip_force_user"]) + self._confirm_disable = self._settings.global_get_boolean(["confirm_disable"]) + + ##~~ AssetPlugin + + def get_assets(self): + return { + "js": ["js/pluginmanager.js"], + "clientjs": ["clientjs/pluginmanager.js"], + "css": ["css/pluginmanager.css"], + "less": ["less/pluginmanager.less"], + } + + ##~~ TemplatePlugin + + def get_template_configs(self): + return [ + { + "type": "settings", + "name": gettext("Plugin Manager"), + "template": "pluginmanager_settings.jinja2", + "custom_bindings": True, + }, + { + "type": "about", + "name": "Plugin Licenses", + "template": "pluginmanager_about.jinja2", + }, + ] + + def get_template_vars(self): + plugins = sorted(self._get_plugins(), key=lambda x: x["name"].lower()) + return { + "all": plugins, + "thirdparty": list(filter(lambda p: not p["bundled"], plugins)), + "file_extensions": self.ARCHIVE_EXTENSIONS + self.PYTHON_EXTENSIONS, + } + + def get_template_types(self, template_sorting, template_rules, *args, **kwargs): + return [ + ( + "about_thirdparty", + {}, + {"template": lambda x: x + "_about_thirdparty.jinja2"}, + ) + ] + + ##~~ BlueprintPlugin + + @octoprint.plugin.BlueprintPlugin.route("/upload_file", methods=["POST"]) + @no_firstrun_access + @Permissions.PLUGIN_PLUGINMANAGER_INSTALL.require(403) + def upload_file(self): + import flask + + input_name = "file" + input_upload_path = ( + input_name + + "." + + self._settings.global_get(["server", "uploads", "pathSuffix"]) + ) + input_upload_name = ( + input_name + + "." + + self._settings.global_get(["server", "uploads", "nameSuffix"]) + ) + + if ( + input_upload_path not in flask.request.values + or input_upload_name not in flask.request.values + ): + return flask.make_response("No file included", 400) + upload_path = flask.request.values[input_upload_path] + upload_name = flask.request.values[input_upload_name] + + exts = list( + filter( + lambda x: upload_name.lower().endswith(x), + self.ARCHIVE_EXTENSIONS + self.PYTHON_EXTENSIONS, + ) + ) + if not len(exts): + return flask.make_response( + "File doesn't have a valid extension for a plugin archive or a single file plugin", + 400, + ) + + ext = exts[0] + + archive = tempfile.NamedTemporaryFile( + delete=False, suffix="{ext}".format(**locals()) + ) + try: + archive.close() + shutil.copy(upload_path, archive.name) + return self.command_install( + path=archive.name, + name=upload_name, + force="force" in flask.request.values + and flask.request.values["force"] in valid_boolean_trues, + ) + finally: + try: + os.remove(archive.name) + except Exception as e: + self._logger.warning( + "Could not remove temporary file {path} again: {message}".format( + path=archive.name, message=str(e) + ) + ) + + def is_blueprint_protected(self): + return False + + ##~~ EventHandlerPlugin + + def on_event(self, event, payload): + from octoprint.events import Events + + if ( + event != Events.CONNECTIVITY_CHANGED + or not payload + or not payload.get("new", False) + ): + return + self._fetch_all_data(do_async=True) + + ##~~ SimpleApiPlugin + + def get_api_commands(self): + return { + "install": ["url"], + "uninstall": ["plugin"], + "enable": ["plugin"], + "disable": ["plugin"], + "cleanup": ["plugin"], + "cleanup_all": [], + "refresh_repository": [], + } + + def on_api_get(self, request): + if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can(): + return make_response("Insufficient rights", 403) + + from octoprint.server import safe_mode + + refresh_repository = ( + request.values.get("refresh_repository", "false") in valid_boolean_trues + ) + if refresh_repository or not self._is_repository_cache_valid(): + self._repository_available = self._refresh_repository() + + refresh_notices = ( + request.values.get("refresh_notices", "false") in valid_boolean_trues + ) + if refresh_notices or not self._is_notices_cache_valid(): + self._notices_available = self._refresh_notices() + + refresh_orphan = ( + request.values.get("refresh_orphans", "false") in valid_boolean_trues + ) + + def view(): + return jsonify( + plugins=self._get_plugins(), + repository={ + "available": self._repository_available, + "plugins": self._repository_plugins, + }, + orphan_data=self._get_orphans(refresh=refresh_orphan), + os=get_os(), + octoprint=get_octoprint_version_string(), + pip={ + "available": self._pip_caller.available, + "version": self._pip_caller.version_string, + "install_dir": self._pip_caller.install_dir, + "use_user": self._pip_caller.use_user, + "virtual_env": self._pip_caller.virtual_env, + "additional_args": self._settings.get(["pip_args"]), + "python": sys.executable, + }, + safe_mode=safe_mode, + online=self._connectivity_checker.online, + ) + + def etag(): + import hashlib + + hash = hashlib.sha1() + + def hash_update(value): + value = value.encode("utf-8") + hash.update(value) + + hash_update(repr(self._get_plugins())) + hash_update(str(self._repository_available)) + hash_update(repr(self._repository_plugins)) + hash_update(str(self._notices_available)) + hash_update(repr(self._notices)) + hash_update(repr(self._get_orphans())) + hash_update(repr(safe_mode)) + hash_update(repr(self._connectivity_checker.online)) + hash_update(repr(_DATA_FORMAT_VERSION)) + return hash.hexdigest() + + def condition(): + return check_etag(etag()) + + return with_revalidation_checking( + etag_factory=lambda *args, **kwargs: etag(), + condition=lambda *args, **kwargs: condition(), + unless=lambda: refresh_repository or refresh_notices or refresh_orphan, + )(view)() + + def on_api_command(self, command, data): + if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can(): + return make_response("Insufficient rights", 403) + + if self._printer.is_printing() or self._printer.is_paused(): + # do not update while a print job is running + return make_response("Printer is currently printing or paused", 409) + + if command == "install": + if not Permissions.PLUGIN_PLUGINMANAGER_INSTALL.can(): + return make_response("Insufficient rights", 403) + url = data["url"] + plugin_name = data["plugin"] if "plugin" in data else None + + with self._install_lock: + if self._install_task is not None: + return make_response("There's always a plugin being installed", 409) + + self._install_task = threading.Thread( + target=self.command_install, + kwargs={ + "url": url, + "force": "force" in data and data["force"] in valid_boolean_trues, + "dependency_links": "dependency_links" in data + and data["dependency_links"] in valid_boolean_trues, + "reinstall": plugin_name, + }, + ) + self._install_task.daemon = True + self._install_task.start() + + return jsonify(in_progress=True) + + elif command == "uninstall": + plugin_name = data["plugin"] + if not plugin_name in self._plugin_manager.plugins: + return make_response("Unknown plugin: %s" % plugin_name, 404) + + plugin = self._plugin_manager.plugins[plugin_name] + return self.command_uninstall(plugin, cleanup=data.get("cleanup", False)) + + elif command == "cleanup": + plugin = data["plugin"] + try: + plugin = self._plugin_manager.plugins[plugin] + except KeyError: + # not installed, we are cleaning up left overs, that's ok + pass + + return self.command_cleanup(plugin, include_disabled=True) + + elif command == "cleanup_all": + return self.command_cleanup_all() + + elif command == "enable" or command == "disable": + plugin_name = data["plugin"] + if not plugin_name in self._plugin_manager.plugins: + return make_response("Unknown plugin: %s" % plugin_name, 404) + + plugin = self._plugin_manager.plugins[plugin_name] + return self.command_toggle(plugin, command) + + # noinspection PyMethodMayBeStatic + def _is_archive(self, path): + _, ext = os.path.splitext(path) + if ext in PluginManagerPlugin.ARCHIVE_EXTENSIONS: + return True + + kind = filetype.guess(to_native_str(path)) + if kind: + return ".{}".format(kind.extension) in PluginManagerPlugin.ARCHIVE_EXTENSIONS + return False + + def _is_pythonfile(self, path): + _, ext = os.path.splitext(path) + if ext in PluginManagerPlugin.PYTHON_EXTENSIONS: + import ast + + try: + with io.open(path, "rb") as f: + ast.parse(f.read(), filename=path) + return True + except Exception as exc: + self._logger.exception( + "Could not parse {} as python file: {}".format(path, exc) + ) + + return False + + def command_install( + self, + url=None, + path=None, + name=None, + force=False, + reinstall=None, + dependency_links=False, + ): + folder = None + + with self._install_lock: + try: + source = path + source_type = "path" + + if url is not None: + # fetch URL + folder = TemporaryDirectory() + path = download_file(url, folder.name) + source = url + source_type = "url" + + # determine type of path + if self._is_archive(path): + return self._command_install_archive( + path, + source=source, + source_type=source_type, + force=force, + reinstall=reinstall, + dependency_links=dependency_links, + ) + + elif self._is_pythonfile(path): + return self._command_install_pythonfile( + path, source=source, source_type=source_type, name=name + ) + + else: + self._logger.error( + "{} is neither an archive nor a python file, can't install that.".format( + source + ) + ) + result = { + "result": False, + "source": source, + "source_type": source_type, + "reason": "Could not install plugin from {}, was neither " + "a plugin archive nor a single file plugin".format(source), + } + self._send_result_notification("install", result) + return result + + finally: + if folder is not None: + folder.cleanup() + self._install_task = None + + # noinspection DuplicatedCode + def _command_install_archive( + self, + path, + source=None, + source_type=None, + force=False, + reinstall=None, + dependency_links=False, + ): + throttled = self._get_throttled() + if ( + throttled + and isinstance(throttled, dict) + and throttled.get("current_issue", False) + and not self._settings.get_boolean(["ignore_throttled"]) + ): + # currently throttled, we refuse to run + return make_response( + "System is currently throttled, refusing to install " + "anything due to possible stability issues", + 409, + ) + + try: + # Py3 + from urllib.parse import quote as url_quote + except ImportError: + # Py2 + from urllib import quote as url_quote + + path = os.path.abspath(path) + if os.sep != "/": + # windows gets special handling + drive, loc = os.path.splitdrive(path) + path_url = ( + "file:///" + drive.lower() + url_quote(loc.replace(os.sep, "/").lower()) + ) + shell_quote = lambda x: x # do not shell quote under windows, non posix shell + else: + path_url = "file://" + url_quote(path) + shell_quote = sarge.shell_quote + + already_installed_check = ( + lambda line: path_url in line.lower() + ) # lower case in case of windows + + self._logger.info("Installing plugin from {}".format(source)) + pip_args = [ + "--disable-pip-version-check", + "install", + shell_quote(path_url), + "--no-cache-dir", + ] + + if dependency_links or self._settings.get_boolean(["dependency_links"]): + pip_args.append("--process-dependency-links") + + all_plugins_before = self._plugin_manager.find_plugins(existing={}) + + try: + returncode, stdout, stderr = self._call_pip(pip_args) + + # pip's output for a package that is already installed looks something like any of these: + # + # Requirement already satisfied (use --upgrade to upgrade): OctoPrint-Plugin==1.0 from \ + # https://example.com/foobar.zip in + # Requirement already satisfied (use --upgrade to upgrade): OctoPrint-Plugin in + # Requirement already satisfied (use --upgrade to upgrade): OctoPrint-Plugin==1.0 from \ + # file:///tmp/foobar.zip in + # Requirement already satisfied (use --upgrade to upgrade): OctoPrint-Plugin==1.0 from \ + # file:///C:/Temp/foobar.zip in + # + # If we detect any of these matching what we just tried to install, we'll need to trigger a second + # install with reinstall flags. + + if not force and any( + map( + lambda x: x.strip().startswith(already_installed_string) + and already_installed_check(x), + stdout, + ) + ): + self._logger.info( + "Plugin to be installed from {} was already installed, forcing a reinstall".format( + source + ) + ) + self._log_message( + "Looks like the plugin was already installed. Forcing a reinstall." + ) + force = True + except Exception: + self._logger.exception("Could not install plugin from %s" % source) + return make_response( + "Could not install plugin from URL, see the log for more details", 500 + ) + else: + if force: + # We don't use --upgrade here because that will also happily update all our dependencies - we'd rather + # do that in a controlled manner + pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"] + try: + returncode, stdout, stderr = self._call_pip(pip_args) + except Exception: + self._logger.exception( + "Could not install plugin from {}".format(source) + ) + return make_response( + "Could not install plugin from source {}, see the log for more details".format( + source + ), + 500, + ) + + try: + result_line = list( + filter( + lambda x: x.startswith(success_string) + or x.startswith(failure_string), + stdout, + ) + )[-1] + except IndexError: + self._logger.error( + "Installing the plugin from {} failed, could not parse output from pip. " + "See plugin_pluginmanager_console.log for generated output".format(source) + ) + result = { + "result": False, + "source": source, + "source_type": source_type, + "reason": "Could not parse output from pip, see plugin_pluginmanager_console.log " + "for generated output", + } + self._send_result_notification("install", result) + return jsonify(result) + + # The final output of a pip install command looks something like this: + # + # Successfully installed OctoPrint-Plugin-1.0 Dependency-One-0.1 Dependency-Two-9.3 + # + # or this: + # + # Successfully installed OctoPrint-Plugin Dependency-One Dependency-Two + # Cleaning up... + # + # So we'll need to fetch the "Successfully installed" line, strip the "Successfully" part, then split + # by whitespace and strip to get all installed packages. + # + # We then need to iterate over all known plugins and see if either the package name or the package name plus + # version number matches one of our installed packages. If it does, that's our installed plugin. + # + # Known issue: This might return the wrong plugin if more than one plugin was installed through this + # command (e.g. due to pulling in another plugin as dependency). It should be safe for now though to + # consider this a rare corner case. Once it becomes a real problem we'll just extend the plugin manager + # so that it can report on more than one installed plugin. + + result_line = result_line.strip() + if not result_line.startswith(success_string): + self._logger.error( + "Installing the plugin from {} failed, pip did not report successful installation".format( + source + ) + ) + result = { + "result": False, + "source": source, + "source_type": source_type, + "reason": "Pip did not report successful installation", + } + self._send_result_notification("install", result) + return result + + installed = list( + map(lambda x: x.strip(), result_line[len(success_string) :].split(" ")) + ) + all_plugins_after = self._plugin_manager.find_plugins( + existing={}, ignore_uninstalled=False + ) + + new_plugin = self._find_installed_plugin(installed, plugins=all_plugins_after) + + if new_plugin is None: + self._logger.warning( + "The plugin was installed successfully, but couldn't be found afterwards to " + "initialize properly during runtime. Please restart OctoPrint." + ) + result = { + "result": True, + "source": source, + "source_type": source_type, + "needs_restart": True, + "needs_refresh": True, + "needs_reconnect": True, + "was_reinstalled": False, + "plugin": "unknown", + } + self._send_result_notification("install", result) + return result + + self._plugin_manager.reload_plugins() + needs_restart = ( + self._plugin_manager.is_restart_needing_plugin(new_plugin) + or new_plugin.key in all_plugins_before + or reinstall is not None + ) + needs_refresh = new_plugin.implementation and isinstance( + new_plugin.implementation, octoprint.plugin.ReloadNeedingPlugin + ) + needs_reconnect = ( + self._plugin_manager.has_any_of_hooks(new_plugin, self._reconnect_hooks) + and self._printer.is_operational() + ) + + is_reinstall = self._plugin_manager.is_plugin_marked( + new_plugin.key, "uninstalled" + ) + self._plugin_manager.mark_plugin( + new_plugin.key, + uninstalled=False, + installed=not is_reinstall and needs_restart, + ) + + self._plugin_manager.log_all_plugins() + + self._logger.info( + "The plugin was installed successfully: {}, version {}".format( + new_plugin.name, new_plugin.version + ) + ) + + # noinspection PyUnresolvedReferences + self._event_bus.fire( + Events.PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN, + { + "id": new_plugin.key, + "version": new_plugin.version, + "source": source, + "source_type": source_type, + }, + ) + + result = { + "result": True, + "source": source, + "source_type": source_type, + "needs_restart": needs_restart, + "needs_refresh": needs_refresh, + "needs_reconnect": needs_reconnect, + "was_reinstalled": new_plugin.key in all_plugins_before + or reinstall is not None, + "plugin": self._to_external_plugin(new_plugin), + } + self._send_result_notification("install", result) + return result + + # noinspection DuplicatedCode + def _command_install_pythonfile(self, path, source=None, source_type=None, name=None): + if name is None: + name = os.path.basename(path) + + self._logger.info("Installing single file plugin {} from {}".format(name, source)) + + all_plugins_before = self._plugin_manager.find_plugins(existing={}) + + destination = os.path.join(self._settings.global_get_basefolder("plugins"), name) + plugin_id, _ = os.path.splitext(name) + + try: + self._log_call("cp {} {}".format(path, destination)) + shutil.copy(path, destination) + except: + self._logger.exception("Installing plugin from {} failed".format(source)) + result = { + "result": False, + "source": source, + "source_type": source_type, + "reason": "Plugin could not be copied", + } + self._send_result_notification("install", result) + return result + + plugins = self._plugin_manager.find_plugins(existing={}, ignore_uninstalled=False) + new_plugin = plugins.get(plugin_id) + if new_plugin is None: + self._logger.warning( + "The plugin was installed successfully, but couldn't be found afterwards to " + "initialize properly during runtime. Please restart OctoPrint." + ) + result = { + "result": True, + "source": source, + "source_type": source_type, + "needs_restart": True, + "needs_refresh": True, + "needs_reconnect": True, + "was_reinstalled": False, + "plugin": "unknown", + } + self._send_result_notification("install", result) + return result + + self._plugin_manager.reload_plugins() + needs_restart = ( + self._plugin_manager.is_restart_needing_plugin(new_plugin) + or new_plugin.key in all_plugins_before + ) + needs_refresh = new_plugin.implementation and isinstance( + new_plugin.implementation, octoprint.plugin.ReloadNeedingPlugin + ) + needs_reconnect = ( + self._plugin_manager.has_any_of_hooks(new_plugin, self._reconnect_hooks) + and self._printer.is_operational() + ) + + self._logger.info( + "The plugin was installed successfully: {}, version {}".format( + new_plugin.name, new_plugin.version + ) + ) + self._plugin_manager.log_all_plugins() + + # noinspection PyUnresolvedReferences + self._event_bus.fire( + Events.PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN, + { + "id": new_plugin.key, + "version": new_plugin.version, + "source": source, + "source_type": source_type, + }, + ) + + result = { + "result": True, + "source": source, + "source_type": source_type, + "needs_restart": needs_restart, + "needs_refresh": needs_refresh, + "needs_reconnect": needs_reconnect, + "was_reinstalled": new_plugin.key in all_plugins_before, + "plugin": self._to_external_plugin(new_plugin), + } + self._send_result_notification("install", result) + return result + + def command_uninstall(self, plugin, cleanup=False): + if plugin.key == "pluginmanager": + return make_response("Can't uninstall Plugin Manager", 403) + + if not plugin.managable: + return make_response( + "Plugin is not managable and hence cannot be uninstalled", 403 + ) + + if plugin.bundled: + return make_response("Bundled plugins cannot be uninstalled", 403) + + if plugin.origin is None: + self._logger.warning( + "Trying to uninstall plugin {plugin} but origin is unknown".format( + **locals() + ) + ) + return make_response("Could not uninstall plugin, its origin is unknown") + + if plugin.origin.type == "entry_point": + # plugin is installed through entry point, need to use pip to uninstall it + origin = plugin.origin[3] + if origin is None: + origin = plugin.origin[2] + + pip_args = ["--disable-pip-version-check", "uninstall", "--yes", origin] + try: + self._call_pip(pip_args) + except Exception: + self._logger.exception("Could not uninstall plugin via pip") + return make_response( + "Could not uninstall plugin via pip, see the log for more details", + 500, + ) + + elif plugin.origin.type == "folder": + import os + import shutil + + full_path = os.path.realpath(plugin.location) + + if os.path.isdir(full_path): + # plugin is installed via a plugin folder, need to use rmtree to get rid of it + self._log_stdout( + "Deleting plugin from {folder}".format(folder=plugin.location) + ) + shutil.rmtree(full_path) + elif os.path.isfile(full_path): + self._log_stdout( + "Deleting plugin from {file}".format(file=plugin.location) + ) + os.remove(full_path) + + if full_path.endswith(".py"): + pyc_file = "{full_path}c".format(**locals()) + if os.path.isfile(pyc_file): + os.remove(pyc_file) + + else: + self._logger.warning( + "Trying to uninstall plugin {plugin} but origin is unknown ({plugin.origin.type})".format( + **locals() + ) + ) + return make_response("Could not uninstall plugin, its origin is unknown") + + needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin) or cleanup + needs_refresh = plugin.implementation and isinstance( + plugin.implementation, octoprint.plugin.ReloadNeedingPlugin + ) + needs_reconnect = ( + self._plugin_manager.has_any_of_hooks(plugin, self._reconnect_hooks) + and self._printer.is_operational() + ) + + was_pending_install = self._plugin_manager.is_plugin_marked( + plugin.key, "installed" + ) + self._plugin_manager.mark_plugin( + plugin.key, + uninstalled=not was_pending_install and needs_restart, + installed=False, + ) + + if not needs_restart: + try: + if plugin.enabled: + self._plugin_manager.disable_plugin(plugin.key, plugin=plugin) + except octoprint.plugin.core.PluginLifecycleException as e: + self._logger.exception( + "Problem disabling plugin {name}".format(name=plugin.key) + ) + result = { + "result": False, + "uninstalled": True, + "disabled": False, + "unloaded": False, + "reason": e.reason, + } + self._send_result_notification("uninstall", result) + return jsonify(result) + + try: + if plugin.loaded: + self._plugin_manager.unload_plugin(plugin.key) + except octoprint.plugin.core.PluginLifecycleException as e: + self._logger.exception( + "Problem unloading plugin {name}".format(name=plugin.key) + ) + result = { + "result": False, + "uninstalled": True, + "disabled": True, + "unloaded": False, + "reason": e.reason, + } + self._send_result_notification("uninstall", result) + return jsonify(result) + + self._plugin_manager.reload_plugins() + + # noinspection PyUnresolvedReferences + self._event_bus.fire( + Events.PLUGIN_PLUGINMANAGER_UNINSTALL_PLUGIN, + {"id": plugin.key, "version": plugin.version}, + ) + + result = { + "result": True, + "needs_restart": needs_restart, + "needs_refresh": needs_refresh, + "needs_reconnect": needs_reconnect, + "plugin": self._to_external_plugin(plugin), + } + self._send_result_notification("uninstall", result) + self._logger.info("Plugin {} uninstalled".format(plugin.key)) + + self._cleanup_disabled(plugin.key) + if cleanup: + self.command_cleanup(plugin.key, result_notifications=False) + + return jsonify(result) + + def command_cleanup( + self, + plugin, + include_disabled=False, + result_notifications=True, + settings_save=True, + ): + if isinstance(plugin, basestring): + key = result_value = plugin + else: + key = plugin.key + result_value = self._to_external_plugin(plugin) + + message = "Cleaning up plugin {}...".format(key) + self._logger.info(message) + self._log_stdout(message) + + # delete plugin settings + self._cleanup_settings(key) + + # delete plugin disabled entry + if include_disabled: + self._cleanup_disabled(key) + + # delete plugin data folder + result_data = True + if not self._cleanup_data(key): + message = "Could not delete data folder of plugin {}".format(key) + self._logger.exception(message) + self._log_stderr(message) + result_data = False + + if settings_save: + self._settings.save() + + result = {"result": result_data, "needs_restart": True, "plugin": result_value} + if result_notifications: + self._send_result_notification("cleanup", result) + + # cleaning orphan cache + self._orphans = None + + return jsonify(result) + + def command_cleanup_all(self): + orphans = self._get_orphans() + cleaned_up = set() + + for orphan in sorted(orphans.keys()): + self.command_cleanup( + orphan, + include_disabled=True, + result_notifications=False, + settings_save=False, + ) + cleaned_up.add(orphan) + + self._settings.save() + + result = { + "result": True, + "needs_restart": len(cleaned_up) > 0, + "cleaned_up": sorted(list(cleaned_up)), + } + self._send_result_notification("cleanup_all", result) + self._logger.info( + "Cleaned up all data, {} left overs removed".format(len(cleaned_up)) + ) + + # cleaning orphan cache + self._orphans = None + + return jsonify(result) + + def _cleanup_disabled(self, plugin): + # delete from disabled list + disabled = self._settings.global_get(["plugins", "_disabled"]) + try: + disabled.remove(plugin) + except ValueError: + # not in list, ok + pass + self._settings.global_set(["plugins", "_disabled"], disabled) + + def _cleanup_settings(self, plugin): + # delete plugin settings + self._settings.global_remove(["plugins", plugin]) + self._settings.global_remove(["server", "seenWizards", plugin]) + return True + + def _cleanup_data(self, plugin): + import os + import shutil + + data_folder = os.path.join(self._settings.getBaseFolder("data"), plugin) + if os.path.exists(data_folder): + try: + shutil.rmtree(data_folder) + return True + except Exception: + self._logger.exception( + "Could not delete plugin data folder at {}".format(data_folder) + ) + return False + else: + return True + + def command_toggle(self, plugin, command): + if plugin.key == "pluginmanager" or (plugin.hidden and plugin.bundled): + return make_response("Can't enable/disable Plugin Manager", 400) + + pending = (command == "disable" and plugin.key in self._pending_enable) or ( + command == "enable" and plugin.key in self._pending_disable + ) + safe_mode_victim = getattr(plugin, "safe_mode_victim", False) + + needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin) + needs_refresh = plugin.implementation and isinstance( + plugin.implementation, octoprint.plugin.ReloadNeedingPlugin + ) + needs_reconnect = ( + self._plugin_manager.has_any_of_hooks(plugin, self._reconnect_hooks) + and self._printer.is_operational() + ) + + needs_restart_api = ( + needs_restart or safe_mode_victim or plugin.forced_disabled + ) and not pending + needs_refresh_api = needs_refresh and not pending + needs_reconnect_api = needs_reconnect and not pending + + try: + if command == "disable": + self._mark_plugin_disabled(plugin, needs_restart=needs_restart) + elif command == "enable": + self._mark_plugin_enabled(plugin, needs_restart=needs_restart) + except octoprint.plugin.core.PluginLifecycleException as e: + self._logger.exception( + "Problem toggling enabled state of {name}: {reason}".format( + name=plugin.key, reason=e.reason + ) + ) + result = {"result": False, "reason": e.reason} + except octoprint.plugin.core.PluginNeedsRestart: + result = { + "result": True, + "needs_restart": True, + "needs_refresh": True, + "needs_reconnect": True, + "plugin": self._to_external_plugin(plugin), + } + else: + result = { + "result": True, + "needs_restart": needs_restart_api, + "needs_refresh": needs_refresh_api, + "needs_reconnect": needs_reconnect_api, + "plugin": self._to_external_plugin(plugin), + } + + self._send_result_notification(command, result) + return jsonify(result) + + def _find_installed_plugin(self, packages, plugins=None): + if plugins is None: + plugins = self._plugin_manager.find_plugins( + existing={}, ignore_uninstalled=False + ) + + for key, plugin in plugins.items(): + if plugin.origin is None or plugin.origin.type != "entry_point": + continue + + package_name = plugin.origin.package_name + package_version = plugin.origin.package_version + versioned_package = "{package_name}-{package_version}".format(**locals()) + + if package_name in packages or versioned_package in packages: + # exact match, we are done here + return plugin + + else: + # it might still be a version that got stripped by python's package resources, e.g. 1.4.5a0 => 1.4.5a + found = False + + for inst in packages: + if inst.startswith(versioned_package): + found = True + break + + if found: + return plugin + + return None + + def _send_result_notification(self, action, result): + notification = {"type": "result", "action": action} + notification.update(result) + self._plugin_manager.send_plugin_message(self._identifier, notification) + + def _call_pip(self, args): + if self._pip_caller is None or not self._pip_caller.available: + raise RuntimeError("No pip available, can't operate".format(**locals())) + + if "--process-dependency-links" in args: + self._log_message( + "Installation needs to process external dependencies, that might make it take a bit longer than usual depending on the pip version" + ) + + additional_args = self._settings.get(["pip_args"]) + + if additional_args is not None: + + inapplicable_arguments = self.__class__.PIP_INAPPLICABLE_ARGUMENTS.get( + args[0], list() + ) + for inapplicable_argument in inapplicable_arguments: + additional_args = re.sub( + r"(^|\s)" + re.escape(inapplicable_argument) + r"\\b", + "", + additional_args, + ) + + if additional_args: + args.append(additional_args) + + kwargs = { + "env": { + "PYTHONWARNINGS": "ignore:DEPRECATION::pip._internal.cli.base_command" + } + } + + return self._pip_caller.execute(*args, **kwargs) + + def _log_message(self, *lines): + self._log(lines, prefix="*", stream="message") + + def _log_call(self, *lines): + self._log(lines, prefix=" ", stream="call") + + def _log_stdout(self, *lines): + self._log(lines, prefix=">", stream="stdout") + + def _log_stderr(self, *lines): + self._log(lines, prefix="!", stream="stderr") + + def _log(self, lines, prefix=None, stream=None, strip=True): + if strip: + lines = list(map(lambda x: x.strip(), lines)) + + self._plugin_manager.send_plugin_message( + self._identifier, + { + "type": "loglines", + "loglines": [{"line": line, "stream": stream} for line in lines], + }, + ) + for line in lines: + self._console_logger.debug("{prefix} {line}".format(**locals())) + + def _mark_plugin_enabled(self, plugin, needs_restart=False): + disabled_list = list( + self._settings.global_get( + ["plugins", "_disabled"], + validator=lambda x: isinstance(x, list), + fallback=[], + ) + ) + if plugin.key in disabled_list: + disabled_list.remove(plugin.key) + self._settings.global_set(["plugins", "_disabled"], disabled_list) + self._settings.save(force=True) + + if ( + not needs_restart + and not plugin.forced_disabled + and not getattr(plugin, "safe_mode_victim", False) + ): + self._plugin_manager.enable_plugin(plugin.key) + else: + if plugin.key in self._pending_disable: + self._pending_disable.remove(plugin.key) + elif not plugin.enabled and plugin.key not in self._pending_enable: + self._pending_enable.add(plugin.key) + + # noinspection PyUnresolvedReferences + self._event_bus.fire( + Events.PLUGIN_PLUGINMANAGER_ENABLE_PLUGIN, + {"id": plugin.key, "version": plugin.version}, + ) + + def _mark_plugin_disabled(self, plugin, needs_restart=False): + disabled_list = list( + self._settings.global_get( + ["plugins", "_disabled"], + validator=lambda x: isinstance(x, list), + fallback=[], + ) + ) + if not plugin.key in disabled_list: + disabled_list.append(plugin.key) + self._settings.global_set(["plugins", "_disabled"], disabled_list) + self._settings.save(force=True) + + if ( + not needs_restart + and not plugin.forced_disabled + and not getattr(plugin, "safe_mode_victim", False) + ): + self._plugin_manager.disable_plugin(plugin.key) + else: + if plugin.key in self._pending_enable: + self._pending_enable.remove(plugin.key) + elif ( + plugin.enabled + or plugin.forced_disabled + or getattr(plugin, "safe_mode_victim", False) + ) and plugin.key not in self._pending_disable: + self._pending_disable.add(plugin.key) + + # noinspection PyUnresolvedReferences + self._event_bus.fire( + Events.PLUGIN_PLUGINMANAGER_DISABLE_PLUGIN, + {"id": plugin.key, "version": plugin.version}, + ) + + def _fetch_all_data(self, do_async=False): + def run(): + self._repository_available = self._fetch_repository_from_disk() + self._notices_available = self._fetch_notices_from_disk() + + if do_async: + thread = threading.Thread(target=run) + thread.daemon = True + thread.start() + else: + run() + + def _is_repository_cache_valid(self, mtime=None): + import time + + if mtime is None: + mtime = self._repository_mtime + if mtime is None: + return False + return mtime + self._repository_cache_ttl >= time.time() > mtime + + def _fetch_repository_from_disk(self): + repo_data = None + if os.path.isfile(self._repository_cache_path): + import time + + mtime = os.path.getmtime(self._repository_cache_path) + if self._is_repository_cache_valid(mtime=mtime): + try: + import json + + with io.open( + self._repository_cache_path, "rt", encoding="utf-8" + ) as f: + repo_data = json.load(f) + self._repository_mtime = mtime + self._logger.info( + "Loaded plugin repository data from disk, was still valid" + ) + except Exception: + self._logger.exception( + "Error while loading repository data from {}".format( + self._repository_cache_path + ) + ) + + return self._refresh_repository(repo_data=repo_data) + + def _fetch_repository_from_url(self): + if not self._connectivity_checker.online: + self._logger.info( + "Looks like we are offline, can't fetch repository from network" + ) + return None + + repository_url = self._settings.get(["repository"]) + try: + r = requests.get(repository_url, timeout=30) + r.raise_for_status() + self._logger.info( + "Loaded plugin repository data from {}".format(repository_url) + ) + except Exception as e: + self._logger.exception( + "Could not fetch plugins from repository at {repository_url}: {message}".format( + repository_url=repository_url, message=e + ) + ) + return None + + try: + repo_data = r.json() + except Exception as e: + self._logger.exception("Error while reading repository data: {}".format(e)) + return None + + # validation + if not isinstance(repo_data, (list, tuple)): + self._logger.warning( + "Invalid repository data: expected a list, got {!r}".format(repo_data) + ) + return None + + try: + import json + + with octoprint.util.atomic_write(self._repository_cache_path, mode="wb") as f: + f.write(to_bytes(json.dumps(repo_data))) + self._repository_mtime = os.path.getmtime(self._repository_cache_path) + except Exception as e: + self._logger.exception( + "Error while saving repository data to {}: {}".format( + self._repository_cache_path, e + ) + ) + + return repo_data + + def _refresh_repository(self, repo_data=None): + if repo_data is None: + repo_data = self._fetch_repository_from_url() + if repo_data is None: + return False + + self._repository_plugins = list( + filter(lambda x: x is not None, map(map_repository_entry, repo_data)) + ) + return True + + def _is_notices_cache_valid(self, mtime=None): + import time + + if mtime is None: + mtime = self._notices_mtime + if mtime is None: + return False + return mtime + self._notices_cache_ttl >= time.time() > mtime + + def _fetch_notices_from_disk(self): + notice_data = None + if os.path.isfile(self._notices_cache_path): + import time + + mtime = os.path.getmtime(self._notices_cache_path) + if self._is_notices_cache_valid(mtime=mtime): + try: + import json + + with io.open(self._notices_cache_path, "rt", encoding="utf-8") as f: + notice_data = json.load(f) + self._notices_mtime = mtime + self._logger.info("Loaded notice data from disk, was still valid") + except Exception: + self._logger.exception( + "Error while loading notices from {}".format( + self._notices_cache_path + ) + ) + + return self._refresh_notices(notice_data=notice_data) + + def _fetch_notices_from_url(self): + if not self._connectivity_checker.online: + self._logger.info( + "Looks like we are offline, can't fetch notices from network" + ) + return None + + notices_url = self._settings.get(["notices"]) + try: + r = requests.get(notices_url, timeout=30) + r.raise_for_status() + self._logger.info("Loaded plugin notices data from {}".format(notices_url)) + except Exception as e: + self._logger.exception( + "Could not fetch notices from {notices_url}: {message}".format( + notices_url=notices_url, message=str(e) + ) + ) + return None + + notice_data = r.json() + + try: + import json + + with octoprint.util.atomic_write(self._notices_cache_path, mode="wb") as f: + f.write(to_bytes(json.dumps(notice_data))) + self._notices_mtime = os.path.getmtime(self._notices_cache_path) + except Exception as e: + self._logger.exception( + "Error while saving notices to {}: {}".format( + self._notices_cache_path, str(e) + ) + ) + return notice_data + + def _refresh_notices(self, notice_data=None): + if notice_data is None: + notice_data = self._fetch_notices_from_url() + if notice_data is None: + return False + + notices = {} + for notice in notice_data: + if not "plugin" in notice or not "text" in notice or not "date" in notice: + continue + + key = notice["plugin"] + + try: + # Jekyll turns "%Y-%m-%d %H:%M:%SZ" into "%Y-%m-%d %H:%M:%S +0000", so be sure to ignore "+0000" + # + # Being able to use dateutil here would make things way easier but sadly that can no longer get + # installed (from source) under OctoPi 0.14 due to its setuptools-scm dependency, so we have to do + # without it for now until we can drop support for OctoPi 0.14. + parsed_date = datetime.strptime(notice["date"], "%Y-%m-%d %H:%M:%S +0000") + notice["timestamp"] = parsed_date.timetuple() + except Exception as e: + self._logger.warning( + "Error while parsing date {!r} for plugin notice " + "of plugin {}, ignoring notice: {}".format( + notice["date"], key, str(e) + ) + ) + continue + + if not key in notices: + notices[key] = [] + notices[key].append(notice) + + self._notices = notices + return True + + def _get_orphans(self, refresh=False): + from collections import defaultdict + + if self._orphans is not None and not refresh: + return self._orphans + + installed_keys = self._plugin_manager.plugins.keys() + orphans = defaultdict( + lambda: {"settings": False, "data": False, "disabled": False} + ) + + # settings + for key in list(self._settings.global_get(["plugins"]).keys()): + if key.startswith("_"): + # internal key, like _disabled + continue + + if key not in installed_keys: + orphans[key]["settings"] = True + + # data + for entry in scandir(self._settings.getBaseFolder("data")): + if not entry.is_dir(): + continue + + if entry.name not in installed_keys: + orphans[entry.name]["data"] = True + + # disabled + disabled = self._settings.global_get(["plugins", "_disabled"]) + for key in disabled: + if key not in installed_keys: + orphans[key]["disabled"] = True + + self._orphans = dict(**orphans) + return self._orphans + + @property + def _reconnect_hooks(self): + reconnect_hooks = self.__class__.RECONNECT_HOOKS + + reconnect_hook_provider_hooks = self._plugin_manager.get_hooks( + "octoprint.plugin.pluginmanager.reconnect_hooks" + ) + for name, hook in reconnect_hook_provider_hooks.items(): + try: + result = hook() + if isinstance(result, (list, tuple)): + reconnect_hooks.extend( + filter(lambda x: isinstance(x, basestring), result) + ) + except Exception: + self._logger.exception( + "Error while retrieving additional hooks for which a " + "reconnect is required from plugin {name}".format(**locals()), + extra={"plugin": name}, + ) + + return reconnect_hooks + + def _get_plugins(self): + plugins = self._plugin_manager.plugins + + hidden = self._settings.get(["hidden"]) + result = [] + for key, plugin in plugins.items(): + if key in hidden or (plugin.bundled and plugin.hidden): + continue + result.append(self._to_external_plugin(plugin)) + + return result + + def _to_external_plugin(self, plugin): + return { + "key": plugin.key, + "name": plugin.name, + "description": plugin.description, + "disabling_discouraged": gettext(plugin.disabling_discouraged) + if plugin.disabling_discouraged + else False, + "author": plugin.author, + "version": plugin.version, + "url": plugin.url, + "license": plugin.license, + "python": plugin.pythoncompat, + "bundled": plugin.bundled, + "managable": plugin.managable, + "enabled": plugin.enabled, + "blacklisted": plugin.blacklisted, + "forced_disabled": plugin.forced_disabled, + "incompatible": plugin.incompatible, + "safe_mode_victim": getattr(plugin, "safe_mode_victim", False), + "pending_enable": ( + not plugin.enabled + and not getattr(plugin, "safe_mode_victim", False) + and plugin.key in self._pending_enable + ), + "pending_disable": ( + (plugin.enabled or getattr(plugin, "safe_mode_victim", False)) + and plugin.key in self._pending_disable + ), + "pending_install": ( + self._plugin_manager.is_plugin_marked(plugin.key, "installed") + ), + "pending_uninstall": ( + self._plugin_manager.is_plugin_marked(plugin.key, "uninstalled") + ), + "origin": plugin.origin.type, + "notifications": self._get_notifications(plugin), + } + + def _get_notifications(self, plugin): + key = plugin.key + if not plugin.enabled: + return + + if key not in self._notices: + return + + octoprint_version = get_octoprint_version(base=True) + plugin_notifications = self._notices.get(key, []) + + def map_notification(notification): + return self._to_external_notification(key, notification) + + return list( + filter( + lambda x: x is not None, + map( + map_notification, + filter( + lambda n: _filter_relevant_notification( + n, plugin.version, octoprint_version + ), + plugin_notifications, + ), + ), + ) + ) + + def _to_external_notification(self, key, notification): + return { + "key": key, + "date": time.mktime(notification["timestamp"]), + "text": notification["text"], + "link": notification.get("link"), + "versions": notification.get( + "pluginversions", notification.get("versions", []) + ), + "important": notification.get("important", False), + } def _filter_relevant_notification(notification, plugin_version, octoprint_version): - if "pluginversions" in notification: - pluginversions = notification["pluginversions"] + if "pluginversions" in notification: + pluginversions = notification["pluginversions"] - 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), - filter(is_range, - pluginversions))) - versions = list(filter(lambda x: not is_range(x), - pluginversions)) - elif "versions" in notification: - version_ranges = [] - versions = notification["versions"] - else: - version_ranges = versions = None + 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), + filter(is_range, pluginversions), + ) + ) + versions = list(filter(lambda x: not is_range(x), pluginversions)) + elif "versions" in notification: + version_ranges = [] + versions = notification["versions"] + else: + version_ranges = versions = None - return "text" in notification and "date" in notification and \ - ((version_ranges is None and versions is None) or - (version_ranges and (any(map(lambda v: plugin_version in v, version_ranges)))) or - (versions and plugin_version in versions)) and \ - ("octoversions" not in notification or is_octoprint_compatible(*notification["octoversions"], - octoprint_version=octoprint_version)) + return ( + "text" in notification + and "date" in notification + and ( + (version_ranges is None and versions is None) + or ( + version_ranges + and (any(map(lambda v: plugin_version in v, version_ranges))) + ) + or (versions and plugin_version in versions) + ) + and ( + "octoversions" not in notification + or is_octoprint_compatible( + *notification["octoversions"], octoprint_version=octoprint_version + ) + ) + ) def _register_custom_events(*args, **kwargs): - return ["install_plugin", "uninstall_plugin", "enable_plugin", "disable_plugin"] + return ["install_plugin", "uninstall_plugin", "enable_plugin", "disable_plugin"] __plugin_name__ = "Plugin Manager" @@ -1399,14 +1889,15 @@ __plugin_license__ = "AGPLv3" __plugin_pythoncompat__ = ">=2.7,<4" __plugin_hidden__ = True -def __plugin_load__(): - global __plugin_implementation__ - __plugin_implementation__ = PluginManagerPlugin() - global __plugin_hooks__ - __plugin_hooks__ = { - "octoprint.server.http.bodysize": __plugin_implementation__.increase_upload_bodysize, - "octoprint.ui.web.templatetypes": __plugin_implementation__.get_template_types, - "octoprint.events.register_custom_events": _register_custom_events, - "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions - } +def __plugin_load__(): + global __plugin_implementation__ + __plugin_implementation__ = PluginManagerPlugin() + + global __plugin_hooks__ + __plugin_hooks__ = { + "octoprint.server.http.bodysize": __plugin_implementation__.increase_upload_bodysize, + "octoprint.ui.web.templatetypes": __plugin_implementation__.get_template_types, + "octoprint.events.register_custom_events": _register_custom_events, + "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions, + } diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index 88b3c00d8..e6f42cfca 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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" @@ -26,7 +26,11 @@ from . import version_checks, updaters, exceptions, util, cli from flask_babel import gettext -from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking, check_etag +from octoprint.server.util.flask import ( + no_firstrun_access, + with_revalidation_checking, + check_etag, +) from octoprint.server import VERSION, REVISION, BRANCH, NO_CONTENT from octoprint.access import USER_GROUP, ADMIN_GROUP from octoprint.access.permissions import Permissions @@ -44,1588 +48,2082 @@ MINIMUM_PIP = "9.0.3" ##~~ Plugin -class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, - octoprint.plugin.SettingsPlugin, - octoprint.plugin.AssetPlugin, - octoprint.plugin.TemplatePlugin, - octoprint.plugin.StartupPlugin, - octoprint.plugin.WizardPlugin, - octoprint.plugin.EventHandlerPlugin): - - COMMIT_TRACKING_TYPES = ("github_commit", "bitbucket_commit") - CURRENT_TRACKING_TYPES = COMMIT_TRACKING_TYPES + ("etag", "lastmodified", "jsondata") - - OCTOPRINT_RESTART_TYPES = ("pip", "single_file_plugin") - - DATA_FORMAT_VERSION = "v4" - - CHECK_OVERLAY_KEY = "softwareupdate_check_overlay" - - # noinspection PyMissingConstructor - def __init__(self): - self._update_in_progress = False - self._configured_checks_mutex = threading.Lock() - self._configured_checks = None - self._refresh_configured_checks = False - - self._get_versions_mutex = threading.RLock() - self._get_versions_data = None - self._get_versions_data_ready = threading.Event() - - self._version_cache = {} - self._version_cache_ttl = 0 - self._version_cache_path = None - self._version_cache_dirty = False - self._version_cache_timestamp = None - - self._overlay_cache = {} - self._overlay_cache_ttl = 0 - self._overlay_cache_timestamp = None - - self._environment_supported = True - self._environment_versions = {} - self._environment_ready = threading.Event() - - self._storage_sufficient = True - self.storage_info = {} - - self._console_logger = None - - self._get_throttled = lambda: False - - def initialize(self): - self._console_logger = logging.getLogger("octoprint.plugins.softwareupdate.console") - - self._version_cache_ttl = self._settings.get_int(["cache_ttl"]) * 60 - self._version_cache_path = os.path.join(self.get_plugin_data_folder(), "versioncache.yaml") - self._load_version_cache() - - self._overlay_cache_ttl = self._settings.get_int(["check_overlay_ttl"]) * 60 - - def refresh_checks(name, plugin): - self._refresh_configured_checks = True - self._send_client_message("update_versions") - - self._plugin_lifecycle_manager.add_callback("enabled", refresh_checks) - self._plugin_lifecycle_manager.add_callback("disabled", refresh_checks) - - # Additional permissions hook - - def get_additional_permissions(self): - return [ - {"key": "CHECK", - "name": "Check", - "description": gettext("Allows to check for software updates"), - "roles": ["check"], - "default_groups": [USER_GROUP]}, - {"key": "UPDATE", - "name": "Update", - "description": gettext("Allows to perform software updates"), - "default_groups": [ADMIN_GROUP], - "roles": ["update"], - "dangerous": True}, - {"key": "CONFIGURE", - "name": "Configure", - "description": gettext("Allows to configure software update"), - "default_groups": [ADMIN_GROUP], - "roles": ["configure"], - "dangerous": True} - ] - - def on_startup(self, host, port): - console_logging_handler = logging.handlers.RotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="console"), - maxBytes=2*1024*1024, - encoding="utf-8") - console_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s")) - console_logging_handler.setLevel(logging.DEBUG) - - self._console_logger.addHandler(console_logging_handler) - self._console_logger.setLevel(logging.DEBUG) - self._console_logger.propagate = False - - helpers = self._plugin_manager.get_helpers("pi_support", "get_throttled") - if helpers and "get_throttled" in helpers: - self._get_throttled = helpers["get_throttled"] - if self._settings.get_boolean(["ignore_throttled"]): - self._logger.warning("!!! THROTTLE STATE IGNORED !!! You have configured the Software Update plugin to ignore an active throttle state of the underlying system. You might run into stability issues or outright corrupt your install. Consider fixing the throttling issue instead of suppressing it.") - - def on_after_startup(self): - self._check_environment() - self._check_storage() - self.get_current_versions() - - def _get_configured_checks(self): - with self._configured_checks_mutex: - if self._refresh_configured_checks \ - or self._configured_checks is None \ - or self._check_overlays_stale: - - self._refresh_configured_checks = False - - overlays = self._get_check_overlays() - self._configured_checks = self._settings.get(["checks"], merged=True) - - update_check_hooks = self._plugin_manager.get_hooks("octoprint.plugin.softwareupdate.check_config") - check_providers = {} - - effective_configs = {} - - for name, hook in update_check_hooks.items(): - try: - hook_checks = hook() - except Exception: - self._logger.exception("Error while retrieving update information " - "from plugin {name}".format(**locals()), - extra={"plugin": name}) - else: - for key, default_config in hook_checks.items(): - if key in effective_configs or key == "octoprint": - if key == name: - self._logger.warning("Software update hook {} provides check for itself but that was already registered by {} - overwriting that third party registration now!".format(name, check_providers.get(key, "unknown hook"))) - else: - self._logger.warning("Software update hook {} tried to overwrite config for check {} but that was already configured elsewhere".format(name, key)) - continue - - check_providers[key] = name - - yaml_config = {} - effective_config = default_config - - if key in overlays: - effective_config = dict_merge(default_config, overlays[key]) - - if key in self._configured_checks: - yaml_config = self._configured_checks[key] - effective_config = dict_merge(effective_config, yaml_config, in_place=True) - - # Make sure there's nothing persisted in that check that shouldn't be persisted - # - # This used to be part of the settings migration (version 2) due to a bug - it can't - # stay there though since it interferes with manual entries to the checks not - # originating from within a plugin. Hence we do that step now here. - if "type" not in effective_config or effective_config["type"] not in self.CURRENT_TRACKING_TYPES: - deletables = ["current", "displayVersion"] - else: - deletables = [] - self._clean_settings_check(key, yaml_config, default_config, delete=deletables, save=False) - - if effective_config: - effective_configs[key] = effective_config - else: - self._logger.warning("Update for {} is empty or None, ignoring it".format(key)) - - # finally set all our internal representations to our processed results - for key, config in effective_configs.items(): - self._configured_checks[key] = config - - # we only want to process checks that came from plugins for - # which the plugins are still installed and enabled - config_checks = self._settings.get(["checks"]) - plugin_and_not_enabled = lambda k: k in check_providers and \ - not check_providers[k] in self._plugin_manager.enabled_plugins - obsolete_plugin_checks = list(filter(plugin_and_not_enabled, - config_checks.keys())) - for key in obsolete_plugin_checks: - self._logger.debug("Check for key {} was provided by plugin {} that's no longer available, ignoring it".format(key, check_providers[key])) - del self._configured_checks[key] - - return self._configured_checks - - def _check_environment(self): - import pkg_resources - - local_pip = LocalPipCaller() - - # check python and setuptools version - versions = {"python": get_python_version_string(), - "setuptools": pkg_resources.get_distribution("setuptools").version, - "pip": local_pip.version_string} - supported = get_comparable_version(versions["python"]) >= get_comparable_version(MINIMUM_PYTHON) \ - and get_comparable_version(versions["setuptools"]) >= get_comparable_version(MINIMUM_SETUPTOOLS) \ - and get_comparable_version(versions["pip"]) >= get_comparable_version(MINIMUM_PIP) - - self._environment_supported = supported - self._environment_versions = versions - self._environment_ready.set() - - def _check_storage(self): - import distutils.sysconfig - import tempfile - import psutil - - storage_info = {} - paths = {"python": distutils.sysconfig.get_python_lib(), - "plugins": self._settings.global_get_basefolder("plugins"), - "temp": tempfile.gettempdir()} - - for key, path in paths.items(): - info = {"path": path, - "free": None} - - try: - data = psutil.disk_usage(path) - info["free"] = data.free - except: - self._logger.exception("Error while determining disk usage of {}".format(path)) - continue - - storage_info[key] = info - - if len(storage_info): - free_storage = min(*list(map(lambda x: x["free"], storage_info.values()))) - else: - free_storage = None - - self._storage_sufficient = free_storage is None or free_storage >= self._settings.get_int(["minimum_free_storage"]) * 1024 * 1024 - self._storage_info = storage_info - - self._logger.info("Minimum free storage across all update relevant locations is {}. " - "That is considered {} for updating.".format(get_formatted_size(free_storage) - if free_storage is not None - else "unknown", - "sufficient" - if self._storage_sufficient - else "insufficient")) - - @property - def _check_overlays_stale(self): - return self._overlay_cache is None or self._overlay_cache_timestamp is None \ - or self._overlay_cache_timestamp + self._overlay_cache_ttl < time.time() - - def _get_check_overlays(self, force=False): - if self._check_overlays_stale or force: - if self._connectivity_checker.online: - # reload from URL - url = self._settings.get(["check_overlay_url"]) - self._logger.info("Fetching check overlays from {}".format(url)) - try: - r = requests.get(url, timeout=3.1) - r.raise_for_status() - data = r.json() - except Exception as exc: - self._logger.error("Could not fetch check overlay from {}: {}".format(url, exc)) - self._overlay_cache = {} - else: - self._overlay_cache = data - - else: - self._logger.info("Not fetching check overlays, we are offline") - self._overlay_cache = {} - - self._overlay_cache_timestamp = time.time() - - default_overlay = {} - defaults = self.get_settings_defaults() - for key in defaults["checks"]: - if key in self._overlay_cache: - default_overlay[key] = self._overlay_cache[key] - - self._settings.remove_overlay(self.CHECK_OVERLAY_KEY) - if default_overlay: - self._settings.add_overlay({"checks": default_overlay}, key=self.CHECK_OVERLAY_KEY) - - return self._overlay_cache - - def _load_version_cache(self): - if not os.path.isfile(self._version_cache_path): - return - - import yaml - try: - with io.open(self._version_cache_path, 'rt', encoding='utf-8') as f: - data = yaml.safe_load(f) - timestamp = os.stat(self._version_cache_path).st_mtime - except Exception: - self._logger.exception("Error while loading version cache from disk") - else: - try: - if not isinstance(data, dict): - self._logger.info("Version cache was created in a different format, not using it") - return - - if "__version" in data: - data_version = data["__version"] - else: - self._logger.info("Can't determine version of OctoPrint version cache was created for, not using it") - return - - from octoprint._version import get_versions - octoprint_version = get_versions()["version"] - if data_version != octoprint_version: - self._logger.info("Version cache was created for another version of OctoPrint, not using it") - return - - self._version_cache = data - self._version_cache_dirty = False - self._version_cache_timestamp = timestamp - self._logger.info("Loaded version cache from disk") - except Exception: - self._logger.exception("Error parsing in version cache data") - - def _save_version_cache(self): - import yaml - from octoprint.util import atomic_write - from octoprint._version import get_versions - - octoprint_version = get_versions()["version"] - self._version_cache["__version"] = octoprint_version - - 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) - - self._version_cache_dirty = False - self._version_cache_timestamp = time.time() - self._logger.info("Saved version cache to disk") - - def _invalidate_version_cache(self, target): - self._refresh_configured_checks = True - try: - del self._version_cache[target] - except KeyError: - pass - self._version_cache_dirty = True - - #~~ SettingsPlugin API - - def get_settings_defaults(self): - update_script = os.path.join(self._basefolder, "scripts", "update-octoprint.py") - default_update_script = "{{python}} \"{update_script}\" --branch={{branch}} " \ - "--force={{force}} \"{{folder}}\" {{target}}".format(update_script=update_script) - - return { - "checks": { - "octoprint": { - "type": "github_release", - "user": "foosel", - "repo": "OctoPrint", - "method": "pip", - "pip": "https://github.com/OctoPrint/OctoPrint/archive/{target_version}.zip", - "update_script": default_update_script, - "restart": "octoprint", - "stable_branch": {"branch": "master", "commitish": ["master"], "name": "Stable"}, - "prerelease_branches": [{"branch": "rc/maintenance", - "commitish": ["rc/maintenance"], # maintenance RCs - "name": "Maintenance RCs"}, - {"branch": "rc/devel", - "commitish": ["rc/maintenance", "rc/devel"], # devel & maintenance RCs - "name": "Devel RCs"}] - }, - }, - "pip_command": None, - - "cache_ttl": 24 * 60, - - "notify_users": True, - - "ignore_throttled": False, - - "minimum_free_storage": 150, - - "check_overlay_url": "https://plugins.octoprint.org/update_check_overlay.json", - - "check_overlay_ttl": 6 * 60, - } - - def on_settings_load(self): - # ensure we don't persist check configs we receive on the API - data = dict(octoprint.plugin.SettingsPlugin.on_settings_load(self)) - if "checks" in data: - del data["checks"] - - checks = self._get_configured_checks() - - #~~ octoprint check settings - - if "octoprint" in checks: - data["octoprint_checkout_folder"] = self._get_octoprint_checkout_folder(checks=checks) - data["octoprint_tracked_branch"] = self._get_octoprint_tracked_branch(checks=checks) - data["octoprint_pip_target"] = self._get_octoprint_pip_target(checks=checks) - data["octoprint_type"] = checks["octoprint"].get("type", None) - - try: - data["octoprint_method"] = self._get_update_method("octoprint", checks["octoprint"]) - except exceptions.UnknownUpdateType: - data["octoprint_method"] = "unknown" - - stable_branch = None - prerelease_branches = [] - branch_mappings = [] - if "stable_branch" in checks["octoprint"]: - branch_mappings.append(checks["octoprint"]["stable_branch"]) - stable_branch = checks["octoprint"]["stable_branch"]["branch"] - if "prerelease_branches" in checks["octoprint"]: - for mapping in checks["octoprint"]["prerelease_branches"]: - branch_mappings.append(mapping) - prerelease_branches.append(mapping["branch"]) - data["octoprint_branch_mappings"] = branch_mappings - - data["octoprint_release_channel"] = stable_branch - if checks["octoprint"].get("prerelease", False): - channel = checks["octoprint"].get("prerelease_channel", BRANCH) - if channel in prerelease_branches: - data["octoprint_release_channel"] = channel - - else: - data["octoprint_checkout_folder"] = None - data["octoprint_type"] = None - - #~~ pip check settings - - data["pip_enable_check"] = "pip" in checks - - return data - - def on_settings_save(self, data): - #~~ plugin settings - - for key in self.get_settings_defaults(): - if key in ("checks", "cache_ttl", "check_overlay_ttl", "notify_user", "minimum_free_storage", - "octoprint_checkout_folder", "octoprint_type", "octoprint_release_channel"): - continue - if key in data: - self._settings.set([key], data[key]) - - if "cache_ttl" in data: - self._settings.set_int(["cache_ttl"], data["cache_ttl"]) - self._version_cache_ttl = self._settings.get_int(["cache_ttl"]) * 60 - - if "check_overlay_ttl" in data: - self._settings.set_int(["check_overlay_ttl"], data["check_overlay_ttl"]) - self._overlay_cache_ttl = self._settings.get_int(["check_overlay_ttl"]) * 60 - - if "notify_users" in data: - self._settings.set_boolean(["notify_users"], data["notify_users"]) - - if "minimum_free_storage" in data: - self._settings.set_int(["minimum_free_storage"], data["minimum_free_storage"]) - self._check_storage() - - #~~ octoprint check settings - - updated_octoprint_check_config = False - - if "octoprint_checkout_folder" in data: - if data["octoprint_checkout_folder"]: - # force=True as that path is not part of the default config - self._settings.set(["checks", "octoprint", "checkout_folder"], data["octoprint_checkout_folder"], force=True) - if self._settings.get(["checks", "octoprint", "update_folder"]): - self._settings.remove(["checks", "octoprint", "update_folder"]) - else: - self._settings.remove(["checks", "octoprint", "checkout_folder"]) - updated_octoprint_check_config = True - - if "octoprint_type" in data: - octoprint_type = data["octoprint_type"] - - if octoprint_type == "github_release": - self._settings.set(["checks", "octoprint", "type"], octoprint_type) - self._settings.set(["checks", "octoprint", "method"], "pip") - updated_octoprint_check_config = True - - elif octoprint_type == "github_commit": - self._settings.set(["checks", "octoprint", "type"], octoprint_type) - self._settings.set(["checks", "octoprint", "method"], "pip") - updated_octoprint_check_config = True - - elif octoprint_type == "git_commit": - self._settings.set(["checks", "octoprint", "type"], octoprint_type) - self._settings.set(["checks", "octoprint", "method"], "update_script") - updated_octoprint_check_config = True - - if "octoprint_tracked_branch" in data: - if data["octoprint_tracked_branch"]: - # force=True as that path is not part of the default config - self._settings.set(["checks", "octoprint", "branch"], data["octoprint_tracked_branch"], force=True) - else: - self._settings.remove(["checks", "octoprint", "branch"]) - updated_octoprint_check_config = True - - if "octoprint_pip_target" in data: - self._settings.set(["checks", "octoprint", "pip"], data["octoprint_pip_target"]) - updated_octoprint_check_config = True - - if "octoprint_release_channel" in data: - prerelease_branches = self._settings.get(["checks", "octoprint", "prerelease_branches"]) - if prerelease_branches and data["octoprint_release_channel"] in [x["branch"] for x in prerelease_branches]: - # force=True as those paths are not part of the default config - self._settings.set(["checks", "octoprint", "prerelease"], True, force=True) - self._settings.set(["checks", "octoprint", "prerelease_channel"], data["octoprint_release_channel"], force=True) - else: - self._settings.remove(["checks", "octoprint", "prerelease"]) - self._settings.remove(["checks", "octoprint", "prerelease_channel"]) - updated_octoprint_check_config = True - - if updated_octoprint_check_config: - self._invalidate_version_cache("octoprint") - - #~~ pip check settings - - update_pip_check_config = False - - if "pip_enable_check" in data: - pip_enable_check = data["pip_enable_check"] in octoprint.settings.valid_boolean_trues - pip_check_currently_enabled = "pip" in self._settings.get(["checks"], merged=True) - - if pip_enable_check != pip_check_currently_enabled: - if pip_enable_check: - # force=True as that path is not part of the default config - self._settings.set(["checks", "pip"], - {"type": "pypi_release", - "package": "pip", - "pip": "pip=={target_version}"}, - force=True) - else: - self._settings.remove(["checks", "pip"]) - update_pip_check_config = True - - if update_pip_check_config: - self._invalidate_version_cache("pip") - - def get_settings_version(self): - return 9 - - def on_settings_migrate(self, target, current=None): - - if current is None or current < 6: - # up until & including config version 5 we didn't set the method parameter for the octoprint check - # configuration - - configured_checks = self._settings.get(["checks"], incl_defaults=False) - if configured_checks is not None and "octoprint" in configured_checks: - octoprint_check = dict(configured_checks["octoprint"]) - - if not "method" in octoprint_check and octoprint_check.get("type") == "git_commit": - defaults = {"plugins": {"softwareupdate": {"checks": {"octoprint": {"method": "pip"}}}}} - self._settings.set(["checks", "octoprint", "method"], "update_script", defaults=defaults) - - if current == 4: - # config version 4 didn't correctly remove the old settings for octoprint_restart_command - # and environment_restart_command - - self._settings.set(["environment_restart_command"], None) - self._settings.set(["octoprint_restart_command"], None) - - if current is None or current < 5: - # config version 4 and higher moves octoprint_restart_command and - # environment_restart_command to the core configuration - - # current plugin commands - configured_octoprint_restart_command = self._settings.get(["octoprint_restart_command"]) - configured_environment_restart_command = self._settings.get(["environment_restart_command"]) - - # current global commands - configured_system_restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"]) - configured_server_restart_command = self._settings.global_get(["server", "commands", "serverRestartCommand"]) - - # only set global commands if they are not yet set - if configured_system_restart_command is None and configured_environment_restart_command is not None: - self._settings.global_set(["server", "commands", "systemRestartCommand"], configured_environment_restart_command) - if configured_server_restart_command is None and configured_octoprint_restart_command is not None: - self._settings.global_set(["server", "commands", "serverRestartCommand"], configured_octoprint_restart_command) - - # delete current plugin commands from config - self._settings.set(["environment_restart_command"], None) - self._settings.set(["octoprint_restart_command"], None) - - if current is None or current == 2 or current == 8: - # No config version and config version 2 and 8 need the same fix, stripping - # accidentally persisted data off the checks. - # - # We used to do the same processing for the plugin entries too here, but that interfered - # with manual configuration entries. Stuff got deleted that wasn't supposed to be deleted. - # - # The problem is that we don't know if an entry we are looking at and which didn't come through - # a plugin hook is simply an entry from a now uninstalled/unactive plugin, or if it was something - # manually configured by the user. So instead of just blindly removing anything that doesn't - # come from a plugin here we instead clean up anything that indeed comes from a plugin - # during run time and leave everything else as is in the hopes that will not cause trouble. - # - # We still handle the "octoprint" entry here though. - - configured_checks = self._settings.get(["checks"], incl_defaults=False) - if configured_checks is not None and "octoprint" in configured_checks: - octoprint_check = dict(configured_checks["octoprint"]) - if "type" not in octoprint_check or octoprint_check["type"] not in self.CURRENT_TRACKING_TYPES: - deletables=["current", "displayName", "displayVersion"] - else: - deletables=[] - self._clean_settings_check("octoprint", - octoprint_check, - self.get_settings_defaults()["checks"]["octoprint"], - delete=deletables, - save=False) - - elif current == 1: - # config version 1 had the error that the octoprint check got accidentally - # included in checks["octoprint"], leading to recursion and hence to - # yaml parser errors - - configured_checks = self._settings.get(["checks"], incl_defaults=False) - if configured_checks is None: - return - - if "octoprint" in configured_checks and "octoprint" in configured_checks["octoprint"]: - # that's a circular reference, back to defaults - dummy_defaults = {"plugins": {}} - dummy_defaults["plugins"][self._identifier] = {"checks": {}} - dummy_defaults["plugins"][self._identifier]["checks"]["octoprint"] = None - self._settings.set(["checks", "octoprint"], None, defaults=dummy_defaults) - - if current is None or current < 8: - # remove check_providers again - self._settings.remove(["check_providers"]) - - def _clean_settings_check(self, key, data, defaults, delete=None, save=True): - if not data: - # nothing to do - return data - - if delete is None: - delete = [] - - for k, v in data.items(): - if k in defaults and defaults[k] == data[k]: - delete.append(k) - - for k in delete: - if k in data: - del data[k] - - dummy_defaults = {"plugins": {}} - dummy_defaults["plugins"][self._identifier] = {"checks": {}} - dummy_defaults["plugins"][self._identifier]["checks"][key] = defaults - if len(data): - self._settings.set(["checks", key], data, defaults=dummy_defaults) - else: - self._settings.remove(["checks", key], defaults=dummy_defaults) - - if save: - self._settings.save() - - return data - - #~~ BluePrint API - - @octoprint.plugin.BlueprintPlugin.route("/check", methods=["GET"]) - @no_firstrun_access - @Permissions.PLUGIN_SOFTWAREUPDATE_CHECK.require(403) - def check_for_update(self): - request_data = flask.request.values - - if "targets" in request_data or "check" in request_data: - check_targets = list(map(lambda x: x.strip(), - request_data.get("targets", request_data.get("check", "")).split(","))) - else: - check_targets = None - - force = request_data.get("force", "false") in octoprint.settings.valid_boolean_trues - - def view(): - self._environment_ready.wait(timeout=30.0) - - try: - information, update_available, update_possible = self.get_current_versions(check_targets=check_targets, force=force) - - storage = list() - for key, name in (("python", gettext("Python package installation folder")), - ("plugins", gettext("Plugin folder")), - ("temp", gettext("System temporary files"))): - data = self._storage_info.get(key) - if not data: - continue - - s = {"name": name} - s.update(**data) - storage.append(s) - - status = "current" - if self._update_in_progress: - status = "inProgress" - elif update_available and update_possible and self._environment_supported and self._storage_sufficient: - status = "updatePossible" - elif update_available: - status = "updateAvailable" - - return flask.jsonify({"status": status, - "information": information, - "timestamp": self._version_cache_timestamp, - "environment": {"supported": self._environment_supported, - "versions": [{"name": gettext("Python"), - "current": self._environment_versions.get("python", "unknown"), - "minimum": MINIMUM_PYTHON}, - {"name": gettext("pip"), - "current": self._environment_versions.get("pip", "unknown"), - "minimum": MINIMUM_PIP}, - {"name": gettext("setuptools"), - "current": self._environment_versions.get("setuptools", "unknown"), - "minimum": MINIMUM_SETUPTOOLS}]}, - "storage": {"sufficient": self._storage_sufficient, - "free": storage}}) - except exceptions.ConfigurationInvalid as e: - return flask.make_response("Update not properly configured, can't proceed: {}".format(e), 500) - - def etag(): - checks = self._get_configured_checks() - - targets = check_targets - if targets is None: - targets = checks.keys() - - hash = hashlib.sha1() - def hash_update(value): - value = value.encode('utf-8') - hash.update(value) - - targets = sorted(targets) - for target in targets: - current_hash = self._get_check_hash(checks.get(target, {})) - if target in self._version_cache and not force: - data = self._version_cache[target] - hash_update(current_hash) - hash_update(str(data["timestamp"] + self._version_cache_ttl >= time.time() > data["timestamp"])) - hash_update(repr(data["information"])) - hash_update(str(data["available"])) - hash_update(str(data["possible"])) - hash_update(str(data.get("online", None))) - - hash_update(",".join(targets)) - - hash_update(str(self._environment_supported)) - hash_update(str(self._version_cache_timestamp)) - hash_update(str(self._overlay_cache_timestamp)) - hash_update(str(self._connectivity_checker.online)) - hash_update(str(self._update_in_progress)) - hash_update(self.DATA_FORMAT_VERSION) - return hash.hexdigest() - - def condition(): - return check_etag(etag()) - - return with_revalidation_checking(etag_factory=lambda *args, **kwargs: etag(), - condition=lambda *args, **kwargs: condition(), - unless=lambda: force or self._check_overlays_stale)(view)() - - - @octoprint.plugin.BlueprintPlugin.route("/update", methods=["POST"]) - @no_firstrun_access - @Permissions.PLUGIN_SOFTWAREUPDATE_UPDATE.require(403) - def perform_update(self): - throttled = self._get_throttled() - if throttled and isinstance(throttled, dict) and throttled.get("current_issue", False) and not self._settings.get_boolean(["ignore_throttled"]): - # currently throttled, we refuse to run - return flask.make_response("System is currently throttled, refusing to update " - "anything due to possible stability issues", 409) - - if self._printer.is_printing() or self._printer.is_paused(): - # do not update while a print job is running - return flask.make_response("Printer is currently printing or paused", 409) - - if not self._environment_supported: - return flask.make_response("Direct updates are not supported in this Python environment", 409) - - if not self._storage_sufficient: - return flask.make_response("Not enough free disk space for updating", 409) - - if not "application/json" in flask.request.headers["Content-Type"]: - return flask.make_response("Expected content-type JSON", 400) - - json_data = flask.request.get_json(silent=True) - if json_data is None: - return flask.make_response("Invalid JSON", 400) - - if "targets" in json_data or "checks" in json_data: - targets = list(map(lambda x: x.strip(), json_data.get("targets", json_data.get("check", [])))) - else: - targets = None - - force = json_data.get("force", "false") in octoprint.settings.valid_boolean_trues - - to_be_checked, checks = self.perform_updates(targets=targets, force=force) - return flask.jsonify({"order": to_be_checked, "checks": checks}) - - @octoprint.plugin.BlueprintPlugin.route("/configure", methods=["POST"]) - @no_firstrun_access - @Permissions.PLUGIN_SOFTWAREUPDATE_CONFIGURE.require(403) - def configure_update(self): - json_data = flask.request.get_json(silent=True) - if json_data is None: - return flask.make_response("Invalid JSON", 400) - - checks = self._get_configured_checks() - - settings_dirty = False - for target, data in json_data.items(): - if not target in checks: - continue - - try: - populated_check = self._populated_check(target, checks[target]) - except exceptions.UnknownCheckType: - self._logger.debug("Ignoring unknown check type for target {}".format(target)) - continue - except Exception: - self._logger.exception("Error while populating check prior to configuration for target {}".format(target)) - continue - - patch = {} - - # switched release channel - if "channel" in data: - if populated_check["type"] == "github_release" and "stable_branch" in populated_check and "prerelease_branches" in populated_check: - valid_channel = data["channel"] == populated_check["stable_branch"].get("branch") \ - or any(map(lambda x: data["channel"] == x.get("branch"), populated_check["prerelease_branches"])) - prerelease = data["channel"] != populated_check["stable_branch"].get("branch") - - if valid_channel: - patch["prerelease"] = prerelease - patch["prerelease_channel"] = data["channel"] - - # disable/enable check - if "disabled" in data: - patch["disabled"] = data["disabled"] in octoprint.settings.valid_boolean_trues - - # do we have changes to apply? - if patch: - current = self._settings.get(["checks", target], incl_defaults=False) - updated = dict_merge(current, patch) - self._settings.set(["checks", target], updated, defaults={"plugins": {"softwareupdate": {"checks": {target: {}}}}}) - - settings_dirty = True - self._invalidate_version_cache(target) - - if settings_dirty: - self._settings.save() - - return NO_CONTENT - - def is_blueprint_protected(self): - return False - - #~~ Asset API - - def get_assets(self): - return {"css": ["css/softwareupdate.css"], - "js": ["js/softwareupdate.js"], - "clientjs": ["clientjs/softwareupdate.js"], - "less": ["less/softwareupdate.less"]} - - ##~~ TemplatePlugin API - - def get_template_configs(self): - from flask_babel import gettext - return [ - {"type": "settings", "name": gettext("Software Update")} - ] - - ##~~ WizardPlugin API - - def is_wizard_required(self): - checks = self._get_configured_checks() - check = checks.get("octoprint", None) - checkout_folder = self._get_octoprint_checkout_folder(checks=checks) - return check and "method" in check and check["method"] == "update_script" and not checkout_folder - - ##~~ EventHandlerPlugin API - - def on_event(self, event, payload): - from octoprint.events import Events - if event != Events.CONNECTIVITY_CHANGED or not payload or not payload.get("new", False): - return - - thread = threading.Thread(target=self.get_current_versions) - thread.daemon = True - thread.start() - - #~~ Updater - - def get_current_versions(self, check_targets=None, force=False): - """ - Retrieves the current version information for all defined check_targets. Will retrieve information for all - available targets by default. - - :param check_targets: an iterable defining the targets to check, if not supplied defaults to all targets - """ - - if force: - self._get_check_overlays(force=True) - - checks = self._get_configured_checks() - if check_targets is None: - check_targets = list(checks.keys()) - - update_available = False - update_possible = False - information = {} - - # we don't want to do the same work twice, so let's use a lock - if self._get_versions_mutex.acquire(False): - self._get_versions_data_ready.clear() - try: - futures_to_result = {} - online = self._connectivity_checker.check_immediately() - self._logger.debug("Looks like we are {}".format("online" if online else "offline")) - - with futures.ThreadPoolExecutor(max_workers=5) as executor: - for target, check in checks.items(): - if not target in check_targets: - continue - - if not check: - continue - - try: - populated_check = self._populated_check(target, check) - future = executor.submit(self._get_current_version, target, populated_check, force=force) - futures_to_result[future] = (target, populated_check) - except exceptions.UnknownCheckType: - self._logger.warning("Unknown update check type for target {}: {}".format(target, - check.get("type", - ""))) - continue - except Exception: - self._logger.exception("Could not check {} for updates".format(target)) - continue - - for future in futures.as_completed(futures_to_result): - - target, populated_check = futures_to_result[future] - if future.exception() is not None: - self._logger.error("Could not check {} for updates, error: {!r}".format(target, - future.exception())) - continue - - target_information, target_update_available, target_update_possible, target_online, target_error = future.result() - target_update_possible = target_update_possible and self._environment_supported - - target_information = dict_merge({"local": {"name": "?", "value": "?"}, - "remote": {"name": "?", "value": "?", - "release_notes": None}, - "needs_online": True}, target_information) - - target_disabled = populated_check.get("disabled", False) - update_available = update_available or (target_update_available and not target_disabled) - update_possible = update_possible or (target_update_possible and target_update_available and not target_disabled) - - local_name = target_information["local"]["name"] - local_value = target_information["local"]["value"] - - release_notes = None - if target_information and target_information["remote"] and target_information["remote"][ - "value"]: - if "release_notes" in populated_check and populated_check["release_notes"]: - release_notes = populated_check["release_notes"] - elif "release_notes" in target_information["remote"]: - release_notes = target_information["remote"]["release_notes"] - - if release_notes: - release_notes = release_notes.format(octoprint_version=VERSION, - target_name=target_information["remote"]["name"], - target_version=target_information["remote"]["value"]) - - information[target] = {"updateAvailable": target_update_available, - "updatePossible": target_update_possible, - "information": target_information, - "displayName": populated_check["displayName"], - "displayVersion": populated_check["displayVersion"].format(octoprint_version=VERSION, - local_name=local_name, - local_value=local_value), - "releaseNotes": release_notes, - "online": target_online, - "error": target_error, - "disabled": target_disabled, - "releaseChannels": {}} - - if populated_check["type"] == "github_release" and "stable_branch" in populated_check and "prerelease_branches" in populated_check: - # target supports release channels via github branches and releases - def to_release_channel(branch_info): - return {"name": branch_info["name"], - "channel": branch_info["branch"]} - - stable_channel = populated_check["stable_branch"]["branch"] - current_channel = populated_check.get("prerelease_channel") - release_channels = [to_release_channel(populated_check["stable_branch"]),] + \ - list(map(to_release_channel, - populated_check["prerelease_branches"])) - information[target]["releaseChannels"] = {"available": release_channels, - "current": current_channel if current_channel else stable_channel, - "stable": stable_channel} - - if "released_version" in populated_check: - information[target]["releasedVersion"] = populated_check["released_version"] - - if self._version_cache_dirty: - self._save_version_cache() - - self._get_versions_data = information, update_available, update_possible - self._get_versions_data_ready.set() - finally: - self._get_versions_mutex.release() - - else: # something's already in progress, let's wait for it to complete and use its result - self._get_versions_data_ready.wait() - information, update_available, update_possible = self._get_versions_data - - return information, update_available, update_possible - - def _get_check_hash(self, check): - def dict_to_sorted_repr(d): - lines = [] - for key in sorted(d.keys()): - value = d[key] - if isinstance(value, dict): - lines.append("{!r}: {}".format(key, dict_to_sorted_repr(value))) - else: - lines.append("{!r}: {!r}".format(key, value)) - - return "{" + ", ".join(lines) + "}" - - hash = hashlib.md5() - def hash_update(value): - value = value.encode('utf-8') - hash.update(value) - hash_update(dict_to_sorted_repr(check)) - return hash.hexdigest() - - def _get_current_version(self, target, check, force=False, online=None): - """ - Determines the current version information for one target based on its check configuration. - """ - - current_hash = self._get_check_hash(check) - if online is None: - online = self._connectivity_checker.online - if target in self._version_cache and not force: - data = self._version_cache[target] - if data["hash"] == current_hash \ - and data["timestamp"] + self._version_cache_ttl >= time.time() > data["timestamp"] \ - and data.get("online", None) == online: - # we also check that timestamp < now to not get confused too much by clock changes - return data["information"], data["available"], data["possible"], data["online"], data.get("error", None) - - information = {} - update_available = False - error = None - - try: - version_checker = self._get_version_checker(target, check) - information, is_current = version_checker.get_latest(target, check, online=online) - if information is not None: - if is_current and check["type"] in self.CURRENT_TRACKING_TYPES and check["current"] is None: - self._persist_check_current(target, check, information["remote"]["value"]) - del self._version_cache[target] - self._version_cache_dirty = True - elif not is_current: - update_available = True - except exceptions.CannotCheckOffline: - update_possible = False - information["needs_online"] = True - except exceptions.UnknownCheckType: - self._logger.warning("Unknown check type %s for %s" % (check["type"], target)) - update_possible = False - error = "unknown_check" - except exceptions.NetworkError: - self._logger.warning("Could not check %s for updates due to a network error" % target) - update_possible = False - error = "network" - except Exception: - self._logger.exception("Could not check %s for updates" % target) - update_possible = False - error = "unknown" - else: - try: - updater = self._get_updater(target, check) - update_possible = updater.can_perform_update(target, check, online=online) - except Exception: - self._logger.exception("Error while checking if {} can be updated".format(target)) - update_possible = False - - disabled = check.get("disabled", False) - - self._version_cache[target] = {"timestamp": time.time(), - "hash": current_hash, - "information": information, - "available": update_available, - "possible": update_possible, - "online": online, - "error": error, - "disabled": disabled} - self._version_cache_dirty = True - return information, update_available, update_possible, online, error - - def perform_updates(self, force=False, **kwargs): - """ - Performs the updates for the given check_targets. Will update all possible targets by default. - - :param targets: an iterable defining the targets to update, if not supplied defaults to all targets - """ - - if not self._environment_supported: - self._logger.error("Direct updates are unsupported in this environment") - return [], {} - - if not self._storage_sufficient: - self._logger.error("Not enough free disk space for updating") - return [], {} - - targets = kwargs.get("targets", kwargs.get("check_targets", None)) - - checks = self._get_configured_checks() - populated_checks = {} - for target, check in checks.items(): - try: - populated_checks[target] = self._populated_check(target, check) - except exceptions.UnknownCheckType: - self._logger.debug("Ignoring unknown check type for target {}".format(target)) - except Exception: - self._logger.exception("Error while populating check prior to update for target {}".format(target)) - - if targets is None: - targets = populated_checks.keys() - to_be_updated = sorted(set(targets) & set(populated_checks.keys())) - if "octoprint" in to_be_updated: - to_be_updated.remove("octoprint") - tmp = ["octoprint"] + to_be_updated - to_be_updated = tmp - if "pip" in to_be_updated: - to_be_updated.remove("pip") - tmp = ["pip"] + to_be_updated - to_be_updated = tmp - - updater_thread = threading.Thread(target=self._update_worker, args=(populated_checks, to_be_updated, force)) - updater_thread.daemon = False - updater_thread.start() - - check_data = dict((key, check["displayName"] if "displayName" in check else key) for key, check in populated_checks.items() if key in to_be_updated) - return to_be_updated, check_data - - def _update_worker(self, checks, check_targets, force): - - restart_type = None - - try: - self._update_in_progress = True - - target_results = {} - error = False - - ### iterate over all configured targets - - for target in check_targets: - if not target in checks: - continue - check = checks[target] - - if "enabled" in check and not check["enabled"]: - continue - - if not target in check_targets: - continue - - target_error, target_result = self._perform_update(target, check, force) - error = error or target_error - if target_result is not None: - target_results[target] = target_result - - if "restart" in check: - target_restart_type = check["restart"] - elif "pip" in check or check.get("method") in self.OCTOPRINT_RESTART_TYPES: - target_restart_type = "octoprint" - else: - target_restart_type = None - - # if our update requires a restart we have to determine which type - if restart_type is None or (restart_type == "octoprint" and target_restart_type == "environment"): - restart_type = target_restart_type - - finally: - # we might have needed to update the config, so we'll save that now - self._settings.save() - - # also, we are now longer updating - self._update_in_progress = False - - if error: - # if there was an unignorable error, we just return error - self._send_client_message("error", {"results": target_results}) - - else: - self._save_version_cache() - - # otherwise the update process was a success, but we might still have to restart - if restart_type is not None and restart_type in ("octoprint", "environment"): - # one of our updates requires a restart of either type "octoprint" or "environment". Let's see if - # we can actually perform that - - restart_command = None - if restart_type == "octoprint": - restart_command = self._settings.global_get(["server", "commands", "serverRestartCommand"]) - elif restart_type == "environment": - restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"]) - - if restart_command: - self._send_client_message("restarting", {"restart_type": restart_type, "results": target_results}) - try: - self._perform_restart(restart_command) - except exceptions.RestartFailed: - self._send_client_message("restart_failed", {"restart_type": restart_type, "results": target_results}) - else: - # we don't have this restart type configured, we'll have to display a message that a manual - # restart is needed - self._send_client_message("restart_manually", {"restart_type": restart_type, "results": target_results}) - else: - self._send_client_message("success", {"results": target_results}) - - def _perform_update(self, target, check, force): - online = self._connectivity_checker.online - - information, update_available, update_possible, _, _ = self._get_current_version(target, check, online=online) - - if not update_available and not force: - return False, None - - if not update_possible: - self._logger.warning("Cannot perform update for %s, update type is not fully configured" % target) - return False, None - - # determine the target version to update to - target_version = information["remote"]["value"] - target_error = False - target_result = None - - def trigger_event(success, **additional_payload): - from octoprint.events import Events - - if success: - # noinspection PyUnresolvedReferences - event = Events.PLUGIN_SOFTWAREUPDATE_UPDATE_SUCCEEDED - else: - # noinspection PyUnresolvedReferences - event = Events.PLUGIN_SOFTWAREUPDATE_UPDATE_FAILED - payload = copy.copy(additional_payload) - payload.update({"target": target, - "from_version": information["local"]["value"], - "to_version": target_version}) - - self._event_bus.fire(event, payload=payload) - - ### The actual update procedure starts here... - - populated_check = self._populated_check(target, check) - try: - self._logger.info("Starting update of %s to %s..." % (target, target_version)) - self._send_client_message("updating", {"target": target, "version": target_version, "name": populated_check["displayName"]}) - updater = self._get_updater(target, check) - if updater is None: - raise exceptions.UnknownUpdateType() - - update_result = updater.perform_update(target, populated_check, target_version, log_cb=self._log, online=online) - target_result = ("success", update_result) - self._logger.info("Update of %s to %s successful!" % (target, target_version)) - trigger_event(True) - - except exceptions.UnknownUpdateType: - self._logger.warning("Update of %s can not be performed, unknown update type" % target) - self._send_client_message("update_failed", {"target": target, "version": target_version, "name": populated_check["displayName"], "reason": "Unknown update type"}) - return False, None - - except exceptions.CannotUpdateOffline: - self._logger.warning("Update of %s can not be performed, it's not marked as 'offline' capable but we are apparently offline right now" % target) - self._send_client_message("update_failed", {"target": target, "version": target_version, "name": populated_check["displayName"], "reason": "No internet connection"}) - - except Exception as e: - self._logger.exception("Update of %s can not be performed, please also check plugin_softwareupdate_console.log for possible causes of this" % target) - trigger_event(False) - - if not "ignorable" in populated_check or not populated_check["ignorable"]: - target_error = True - - if isinstance(e, exceptions.UpdateError): - target_result = ("failed", e.data) - self._send_client_message("update_failed", {"target": target, "version": target_version, "name": populated_check["displayName"], "reason": e.data}) - else: - target_result = ("failed", None) - self._send_client_message("update_failed", {"target": target, "version": target_version, "name": populated_check["displayName"], "reason": "unknown"}) - - else: - # make sure that any external changes to config.yaml are loaded into the system - self._settings.load() - - # persist the new version if necessary for check type - self._persist_check_current(target, check, target_version) - - del self._version_cache[target] - self._version_cache_dirty = True - - return target_error, target_result - - def _persist_check_current(self, target, check, current): - if check["type"] not in self.CURRENT_TRACKING_TYPES: - return - - self._settings.load() - - dummy_default = {"plugins": {}} - dummy_default["plugins"][self._identifier] = {"checks": {}} - dummy_default["plugins"][self._identifier]["checks"][target] = {"current": None} - self._settings.set(["checks", target, "current"], current, defaults=dummy_default) - - # we have to save here (even though that makes us save quite often) since otherwise the next - # load will overwrite our changes we just made - self._settings.save() - - check["current"] = current - - def _perform_restart(self, restart_command): - """ - Performs a restart using the supplied restart_command. - """ - - self._logger.info("Restarting...") - try: - util.execute(restart_command, evaluate_returncode=False, do_async=True) - except exceptions.ScriptError as e: - self._logger.exception("Error while restarting via command {}".format(restart_command)) - self._logger.warning("Restart stdout:\n{}".format(e.stdout)) - self._logger.warning("Restart stderr:\n{}".format(e.stderr)) - raise exceptions.RestartFailed() - - def _populated_check(self, target, check): - from flask_babel import gettext - - if not "type" in check: - raise exceptions.UnknownCheckType() - - result = dict(check) - - if target == "octoprint": - - from octoprint.util.version import is_released_octoprint_version, is_stable_octoprint_version - - displayName = check.get("displayName") - if displayName is None: - # displayName missing or set to None - displayName = gettext("OctoPrint") - result["displayName"] = to_unicode(displayName, errors="replace") - - displayVersion = check.get("displayVersion") - if displayVersion is None: - # displayVersion missing or set to None - displayVersion = "{octoprint_version}" - result["displayVersion"] = to_unicode(displayVersion, errors="replace") - - stable_branch = "master" - release_branches = [] - if "stable_branch" in check: - release_branches.append(check["stable_branch"]["branch"]) - stable_branch = check["stable_branch"]["branch"] - if "prerelease_branches" in check: - release_branches += [x["branch"] for x in check["prerelease_branches"]] - result["released_version"] = is_released_octoprint_version() - - if check["type"] in self.COMMIT_TRACKING_TYPES: - result["current"] = REVISION if REVISION else "unknown" - else: - result["current"] = VERSION - - if check["type"] == "github_release" and (check.get("prerelease", None) or not is_stable_octoprint_version()): - # we are tracking github releases and are either also tracking prerelease OR are currently running - # a non stable version => we need to change some parameters - - # we compare versions fully, not just the base so that we see a difference - # between RCs + stable for the same version release - result["force_base"] = False - - if check.get("prerelease", None): - # we are tracking prereleases => we want to be on the correct prerelease channel/branch - channel = check.get("prerelease_channel", None) - if channel: - # if we have a release channel, we also set our update_branch here to our release channel - # in case it's not already set - result["update_branch"] = check.get("update_branch", channel) - - else: - # we are not tracking prereleases, but aren't on the stable branch either => switch back - # to stable branch on update - result["update_branch"] = check.get("update_branch", stable_branch) - - if check.get("update_script", None): - # we force an exact version & python unequality check, to be able to downgrade - result["force_exact_version"] = True - result["release_compare"] = "python_unequal" - elif check.get("pip", None): - # we force python unequality check for pip installs, to be able to downgrade - result["release_compare"] = "python_unequal" - - elif target == "pip": - import pkg_resources - - displayName = check.get("displayName") - if displayName is None: - # displayName missing or set to None - displayName = gettext("pip") - result["displayName"] = to_unicode(displayName, errors="replace") - - displayVersion = check.get("displayVersion") - if displayVersion is None: - # displayVersion missing or set to None - distribution = pkg_resources.get_distribution("pip") - if distribution: - displayVersion = distribution.version - result["displayVersion"] = to_unicode(displayVersion, errors="replace") - - else: - result["displayName"] = to_unicode(check.get("displayName"), errors="replace") - if result["displayName"] is None: - # displayName missing or None - result["displayName"] = to_unicode(target, errors="replace") - - result["displayVersion"] = to_unicode(check.get("displayVersion", check.get("current")), errors="replace") - if result["displayVersion"] is None: - # displayVersion AND current missing or None - result["displayVersion"] = "unknown" - - if check["type"] in self.CURRENT_TRACKING_TYPES: - result["current"] = check.get("current", None) - else: - result["current"] = check.get("current", check.get("displayVersion", None)) - - if "pip" in result: - if not "pip_command" in check and self._settings.get(["pip_command"]) is not None: - result["pip_command"] = self._settings.get(["pip_command"]) - - return result - - def _log(self, lines, prefix=None, stream=None, strip=True): - if strip: - lines = list(map(lambda x: x.strip(), lines)) - - self._send_client_message("loglines", data={"loglines": [{"line": line, "stream": stream} for line in lines]}) - for line in lines: - self._console_logger.debug("{} {}".format(prefix, line)) - - def _send_client_message(self, message_type, data=None): - self._plugin_manager.send_plugin_message(self._identifier, {"type": message_type, "data": data}) - - def _get_version_checker(self, target, check): - """ - Retrieves the version checker to use for given target and check configuration. Will raise an UnknownCheckType - if version checker cannot be determined. - """ - - if not "type" in check: - raise exceptions.ConfigurationInvalid("no check type defined") - - check_type = check["type"] - method = getattr(version_checks, check_type) - if method is None: - raise exceptions.UnknownCheckType() - else: - return method - - def _get_update_method(self, target, check, valid_methods=None): - """ - Determines the update method for the given target and check. - - If ``valid_methods`` is provided, determine method must be contained - therein to be considered valid. - - Raises an ``UnknownUpdateType`` exception if method cannot be determined - or validated. - """ - - method = None - if "method" in check: - method = check["method"] - else: - if "update_script" in check: - method = "update_script" - elif "pip" in check: - method = "pip" - elif "python_updater" in check: - method = "python_updater" - - if method is None or (valid_methods and not method in valid_methods): - raise exceptions.UnknownUpdateType() - - return method - - def _get_updater(self, target, check): - """ - Retrieves the updater for the given target and check configuration. Will raise an UnknownUpdateType if updater - cannot be determined. - """ - - method = self._get_update_method(target, check) - if method is None: - raise exceptions.UnknownUpdateType() - - updater = getattr(updaters, method) - if updater is None: - raise exceptions.UnknownUpdateType() - - return updater - - def _get_octoprint_checkout_folder(self, checks=None): - if checks is None: - checks = self._get_configured_checks() - - if not "octoprint" in checks: - return None +class SoftwareUpdatePlugin( + octoprint.plugin.BlueprintPlugin, + octoprint.plugin.SettingsPlugin, + octoprint.plugin.AssetPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.StartupPlugin, + octoprint.plugin.WizardPlugin, + octoprint.plugin.EventHandlerPlugin, +): + + COMMIT_TRACKING_TYPES = ("github_commit", "bitbucket_commit") + CURRENT_TRACKING_TYPES = COMMIT_TRACKING_TYPES + ("etag", "lastmodified", "jsondata") + + OCTOPRINT_RESTART_TYPES = ("pip", "single_file_plugin") + + DATA_FORMAT_VERSION = "v4" + + CHECK_OVERLAY_KEY = "softwareupdate_check_overlay" + + # noinspection PyMissingConstructor + def __init__(self): + self._update_in_progress = False + self._configured_checks_mutex = threading.Lock() + self._configured_checks = None + self._refresh_configured_checks = False + + self._get_versions_mutex = threading.RLock() + self._get_versions_data = None + self._get_versions_data_ready = threading.Event() + + self._version_cache = {} + self._version_cache_ttl = 0 + self._version_cache_path = None + self._version_cache_dirty = False + self._version_cache_timestamp = None + + self._overlay_cache = {} + self._overlay_cache_ttl = 0 + self._overlay_cache_timestamp = None + + self._environment_supported = True + self._environment_versions = {} + self._environment_ready = threading.Event() + + self._storage_sufficient = True + self.storage_info = {} + + self._console_logger = None + + self._get_throttled = lambda: False + + def initialize(self): + self._console_logger = logging.getLogger( + "octoprint.plugins.softwareupdate.console" + ) + + self._version_cache_ttl = self._settings.get_int(["cache_ttl"]) * 60 + self._version_cache_path = os.path.join( + self.get_plugin_data_folder(), "versioncache.yaml" + ) + self._load_version_cache() + + self._overlay_cache_ttl = self._settings.get_int(["check_overlay_ttl"]) * 60 + + def refresh_checks(name, plugin): + self._refresh_configured_checks = True + self._send_client_message("update_versions") + + self._plugin_lifecycle_manager.add_callback("enabled", refresh_checks) + self._plugin_lifecycle_manager.add_callback("disabled", refresh_checks) + + # Additional permissions hook + + def get_additional_permissions(self): + return [ + { + "key": "CHECK", + "name": "Check", + "description": gettext("Allows to check for software updates"), + "roles": ["check"], + "default_groups": [USER_GROUP], + }, + { + "key": "UPDATE", + "name": "Update", + "description": gettext("Allows to perform software updates"), + "default_groups": [ADMIN_GROUP], + "roles": ["update"], + "dangerous": True, + }, + { + "key": "CONFIGURE", + "name": "Configure", + "description": gettext("Allows to configure software update"), + "default_groups": [ADMIN_GROUP], + "roles": ["configure"], + "dangerous": True, + }, + ] + + def on_startup(self, host, port): + console_logging_handler = logging.handlers.RotatingFileHandler( + self._settings.get_plugin_logfile_path(postfix="console"), + maxBytes=2 * 1024 * 1024, + encoding="utf-8", + ) + console_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s")) + console_logging_handler.setLevel(logging.DEBUG) + + self._console_logger.addHandler(console_logging_handler) + self._console_logger.setLevel(logging.DEBUG) + self._console_logger.propagate = False + + helpers = self._plugin_manager.get_helpers("pi_support", "get_throttled") + if helpers and "get_throttled" in helpers: + self._get_throttled = helpers["get_throttled"] + if self._settings.get_boolean(["ignore_throttled"]): + self._logger.warning( + "!!! THROTTLE STATE IGNORED !!! You have configured the Software Update plugin to ignore an active throttle state of the underlying system. You might run into stability issues or outright corrupt your install. Consider fixing the throttling issue instead of suppressing it." + ) + + def on_after_startup(self): + self._check_environment() + self._check_storage() + self.get_current_versions() + + def _get_configured_checks(self): + with self._configured_checks_mutex: + if ( + self._refresh_configured_checks + or self._configured_checks is None + or self._check_overlays_stale + ): + + self._refresh_configured_checks = False + + overlays = self._get_check_overlays() + self._configured_checks = self._settings.get(["checks"], merged=True) + + update_check_hooks = self._plugin_manager.get_hooks( + "octoprint.plugin.softwareupdate.check_config" + ) + check_providers = {} + + effective_configs = {} + + for name, hook in update_check_hooks.items(): + try: + hook_checks = hook() + except Exception: + self._logger.exception( + "Error while retrieving update information " + "from plugin {name}".format(**locals()), + extra={"plugin": name}, + ) + else: + for key, default_config in hook_checks.items(): + if key in effective_configs or key == "octoprint": + if key == name: + self._logger.warning( + "Software update hook {} provides check for itself but that was already registered by {} - overwriting that third party registration now!".format( + name, check_providers.get(key, "unknown hook") + ) + ) + else: + self._logger.warning( + "Software update hook {} tried to overwrite config for check {} but that was already configured elsewhere".format( + name, key + ) + ) + continue + + check_providers[key] = name + + yaml_config = {} + effective_config = default_config + + if key in overlays: + effective_config = dict_merge( + default_config, overlays[key] + ) + + if key in self._configured_checks: + yaml_config = self._configured_checks[key] + effective_config = dict_merge( + effective_config, yaml_config, in_place=True + ) + + # Make sure there's nothing persisted in that check that shouldn't be persisted + # + # This used to be part of the settings migration (version 2) due to a bug - it can't + # stay there though since it interferes with manual entries to the checks not + # originating from within a plugin. Hence we do that step now here. + if ( + "type" not in effective_config + or effective_config["type"] + not in self.CURRENT_TRACKING_TYPES + ): + deletables = ["current", "displayVersion"] + else: + deletables = [] + self._clean_settings_check( + key, + yaml_config, + default_config, + delete=deletables, + save=False, + ) + + if effective_config: + effective_configs[key] = effective_config + else: + self._logger.warning( + "Update for {} is empty or None, ignoring it".format( + key + ) + ) + + # finally set all our internal representations to our processed results + for key, config in effective_configs.items(): + self._configured_checks[key] = config + + # we only want to process checks that came from plugins for + # which the plugins are still installed and enabled + config_checks = self._settings.get(["checks"]) + plugin_and_not_enabled = ( + lambda k: k in check_providers + and not check_providers[k] in self._plugin_manager.enabled_plugins + ) + obsolete_plugin_checks = list( + filter(plugin_and_not_enabled, config_checks.keys()) + ) + for key in obsolete_plugin_checks: + self._logger.debug( + "Check for key {} was provided by plugin {} that's no longer available, ignoring it".format( + key, check_providers[key] + ) + ) + del self._configured_checks[key] + + return self._configured_checks + + def _check_environment(self): + import pkg_resources + + local_pip = LocalPipCaller() + + # check python and setuptools version + versions = { + "python": get_python_version_string(), + "setuptools": pkg_resources.get_distribution("setuptools").version, + "pip": local_pip.version_string, + } + supported = ( + get_comparable_version(versions["python"]) + >= get_comparable_version(MINIMUM_PYTHON) + and get_comparable_version(versions["setuptools"]) + >= get_comparable_version(MINIMUM_SETUPTOOLS) + and get_comparable_version(versions["pip"]) + >= get_comparable_version(MINIMUM_PIP) + ) + + self._environment_supported = supported + self._environment_versions = versions + self._environment_ready.set() + + def _check_storage(self): + import distutils.sysconfig + import tempfile + import psutil + + storage_info = {} + paths = { + "python": distutils.sysconfig.get_python_lib(), + "plugins": self._settings.global_get_basefolder("plugins"), + "temp": tempfile.gettempdir(), + } + + for key, path in paths.items(): + info = {"path": path, "free": None} + + try: + data = psutil.disk_usage(path) + info["free"] = data.free + except: + self._logger.exception( + "Error while determining disk usage of {}".format(path) + ) + continue + + storage_info[key] = info + + if len(storage_info): + free_storage = min(*list(map(lambda x: x["free"], storage_info.values()))) + else: + free_storage = None + + self._storage_sufficient = ( + free_storage is None + or free_storage + >= self._settings.get_int(["minimum_free_storage"]) * 1024 * 1024 + ) + self._storage_info = storage_info + + self._logger.info( + "Minimum free storage across all update relevant locations is {}. " + "That is considered {} for updating.".format( + get_formatted_size(free_storage) + if free_storage is not None + else "unknown", + "sufficient" if self._storage_sufficient else "insufficient", + ) + ) + + @property + def _check_overlays_stale(self): + return ( + self._overlay_cache is None + or self._overlay_cache_timestamp is None + or self._overlay_cache_timestamp + self._overlay_cache_ttl < time.time() + ) + + def _get_check_overlays(self, force=False): + if self._check_overlays_stale or force: + if self._connectivity_checker.online: + # reload from URL + url = self._settings.get(["check_overlay_url"]) + self._logger.info("Fetching check overlays from {}".format(url)) + try: + r = requests.get(url, timeout=3.1) + r.raise_for_status() + data = r.json() + except Exception as exc: + self._logger.error( + "Could not fetch check overlay from {}: {}".format(url, exc) + ) + self._overlay_cache = {} + else: + self._overlay_cache = data + + else: + self._logger.info("Not fetching check overlays, we are offline") + self._overlay_cache = {} + + self._overlay_cache_timestamp = time.time() + + default_overlay = {} + defaults = self.get_settings_defaults() + for key in defaults["checks"]: + if key in self._overlay_cache: + default_overlay[key] = self._overlay_cache[key] + + self._settings.remove_overlay(self.CHECK_OVERLAY_KEY) + if default_overlay: + self._settings.add_overlay( + {"checks": default_overlay}, key=self.CHECK_OVERLAY_KEY + ) + + return self._overlay_cache + + def _load_version_cache(self): + if not os.path.isfile(self._version_cache_path): + return + + import yaml + + try: + with io.open(self._version_cache_path, "rt", encoding="utf-8") as f: + data = yaml.safe_load(f) + timestamp = os.stat(self._version_cache_path).st_mtime + except Exception: + self._logger.exception("Error while loading version cache from disk") + else: + try: + if not isinstance(data, dict): + self._logger.info( + "Version cache was created in a different format, not using it" + ) + return + + if "__version" in data: + data_version = data["__version"] + else: + self._logger.info( + "Can't determine version of OctoPrint version cache was created for, not using it" + ) + return + + from octoprint._version import get_versions + + octoprint_version = get_versions()["version"] + if data_version != octoprint_version: + self._logger.info( + "Version cache was created for another version of OctoPrint, not using it" + ) + return + + self._version_cache = data + self._version_cache_dirty = False + self._version_cache_timestamp = timestamp + self._logger.info("Loaded version cache from disk") + except Exception: + self._logger.exception("Error parsing in version cache data") + + def _save_version_cache(self): + import yaml + from octoprint.util import atomic_write + from octoprint._version import get_versions + + octoprint_version = get_versions()["version"] + self._version_cache["__version"] = octoprint_version + + 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, + ) + + self._version_cache_dirty = False + self._version_cache_timestamp = time.time() + self._logger.info("Saved version cache to disk") + + def _invalidate_version_cache(self, target): + self._refresh_configured_checks = True + try: + del self._version_cache[target] + except KeyError: + pass + self._version_cache_dirty = True + + # ~~ SettingsPlugin API + + def get_settings_defaults(self): + update_script = os.path.join(self._basefolder, "scripts", "update-octoprint.py") + default_update_script = ( + '{{python}} "{update_script}" --branch={{branch}} ' + '--force={{force}} "{{folder}}" {{target}}'.format( + update_script=update_script + ) + ) + + return { + "checks": { + "octoprint": { + "type": "github_release", + "user": "foosel", + "repo": "OctoPrint", + "method": "pip", + "pip": "https://github.com/OctoPrint/OctoPrint/archive/{target_version}.zip", + "update_script": default_update_script, + "restart": "octoprint", + "stable_branch": { + "branch": "master", + "commitish": ["master"], + "name": "Stable", + }, + "prerelease_branches": [ + { + "branch": "rc/maintenance", + "commitish": ["rc/maintenance"], # maintenance RCs + "name": "Maintenance RCs", + }, + { + "branch": "rc/devel", + "commitish": [ + "rc/maintenance", + "rc/devel", + ], # devel & maintenance RCs + "name": "Devel RCs", + }, + ], + }, + }, + "pip_command": None, + "cache_ttl": 24 * 60, + "notify_users": True, + "ignore_throttled": False, + "minimum_free_storage": 150, + "check_overlay_url": "https://plugins.octoprint.org/update_check_overlay.json", + "check_overlay_ttl": 6 * 60, + } + + def on_settings_load(self): + # ensure we don't persist check configs we receive on the API + data = dict(octoprint.plugin.SettingsPlugin.on_settings_load(self)) + if "checks" in data: + del data["checks"] + + checks = self._get_configured_checks() + + # ~~ octoprint check settings + + if "octoprint" in checks: + data["octoprint_checkout_folder"] = self._get_octoprint_checkout_folder( + checks=checks + ) + data["octoprint_tracked_branch"] = self._get_octoprint_tracked_branch( + checks=checks + ) + data["octoprint_pip_target"] = self._get_octoprint_pip_target(checks=checks) + data["octoprint_type"] = checks["octoprint"].get("type", None) + + try: + data["octoprint_method"] = self._get_update_method( + "octoprint", checks["octoprint"] + ) + except exceptions.UnknownUpdateType: + data["octoprint_method"] = "unknown" + + stable_branch = None + prerelease_branches = [] + branch_mappings = [] + if "stable_branch" in checks["octoprint"]: + branch_mappings.append(checks["octoprint"]["stable_branch"]) + stable_branch = checks["octoprint"]["stable_branch"]["branch"] + if "prerelease_branches" in checks["octoprint"]: + for mapping in checks["octoprint"]["prerelease_branches"]: + branch_mappings.append(mapping) + prerelease_branches.append(mapping["branch"]) + data["octoprint_branch_mappings"] = branch_mappings + + data["octoprint_release_channel"] = stable_branch + if checks["octoprint"].get("prerelease", False): + channel = checks["octoprint"].get("prerelease_channel", BRANCH) + if channel in prerelease_branches: + data["octoprint_release_channel"] = channel + + else: + data["octoprint_checkout_folder"] = None + data["octoprint_type"] = None + + # ~~ pip check settings + + data["pip_enable_check"] = "pip" in checks + + return data + + def on_settings_save(self, data): + # ~~ plugin settings + + for key in self.get_settings_defaults(): + if key in ( + "checks", + "cache_ttl", + "check_overlay_ttl", + "notify_user", + "minimum_free_storage", + "octoprint_checkout_folder", + "octoprint_type", + "octoprint_release_channel", + ): + continue + if key in data: + self._settings.set([key], data[key]) + + if "cache_ttl" in data: + self._settings.set_int(["cache_ttl"], data["cache_ttl"]) + self._version_cache_ttl = self._settings.get_int(["cache_ttl"]) * 60 + + if "check_overlay_ttl" in data: + self._settings.set_int(["check_overlay_ttl"], data["check_overlay_ttl"]) + self._overlay_cache_ttl = self._settings.get_int(["check_overlay_ttl"]) * 60 + + if "notify_users" in data: + self._settings.set_boolean(["notify_users"], data["notify_users"]) + + if "minimum_free_storage" in data: + self._settings.set_int(["minimum_free_storage"], data["minimum_free_storage"]) + self._check_storage() + + # ~~ octoprint check settings + + updated_octoprint_check_config = False + + if "octoprint_checkout_folder" in data: + if data["octoprint_checkout_folder"]: + # force=True as that path is not part of the default config + self._settings.set( + ["checks", "octoprint", "checkout_folder"], + data["octoprint_checkout_folder"], + force=True, + ) + if self._settings.get(["checks", "octoprint", "update_folder"]): + self._settings.remove(["checks", "octoprint", "update_folder"]) + else: + self._settings.remove(["checks", "octoprint", "checkout_folder"]) + updated_octoprint_check_config = True + + if "octoprint_type" in data: + octoprint_type = data["octoprint_type"] + + if octoprint_type == "github_release": + self._settings.set(["checks", "octoprint", "type"], octoprint_type) + self._settings.set(["checks", "octoprint", "method"], "pip") + updated_octoprint_check_config = True + + elif octoprint_type == "github_commit": + self._settings.set(["checks", "octoprint", "type"], octoprint_type) + self._settings.set(["checks", "octoprint", "method"], "pip") + updated_octoprint_check_config = True + + elif octoprint_type == "git_commit": + self._settings.set(["checks", "octoprint", "type"], octoprint_type) + self._settings.set(["checks", "octoprint", "method"], "update_script") + updated_octoprint_check_config = True + + if "octoprint_tracked_branch" in data: + if data["octoprint_tracked_branch"]: + # force=True as that path is not part of the default config + self._settings.set( + ["checks", "octoprint", "branch"], + data["octoprint_tracked_branch"], + force=True, + ) + else: + self._settings.remove(["checks", "octoprint", "branch"]) + updated_octoprint_check_config = True + + if "octoprint_pip_target" in data: + self._settings.set( + ["checks", "octoprint", "pip"], data["octoprint_pip_target"] + ) + updated_octoprint_check_config = True + + if "octoprint_release_channel" in data: + prerelease_branches = self._settings.get( + ["checks", "octoprint", "prerelease_branches"] + ) + if prerelease_branches and data["octoprint_release_channel"] in [ + x["branch"] for x in prerelease_branches + ]: + # force=True as those paths are not part of the default config + self._settings.set( + ["checks", "octoprint", "prerelease"], True, force=True + ) + self._settings.set( + ["checks", "octoprint", "prerelease_channel"], + data["octoprint_release_channel"], + force=True, + ) + else: + self._settings.remove(["checks", "octoprint", "prerelease"]) + self._settings.remove(["checks", "octoprint", "prerelease_channel"]) + updated_octoprint_check_config = True + + if updated_octoprint_check_config: + self._invalidate_version_cache("octoprint") + + # ~~ pip check settings + + update_pip_check_config = False + + if "pip_enable_check" in data: + pip_enable_check = ( + data["pip_enable_check"] in octoprint.settings.valid_boolean_trues + ) + pip_check_currently_enabled = "pip" in self._settings.get( + ["checks"], merged=True + ) + + if pip_enable_check != pip_check_currently_enabled: + if pip_enable_check: + # force=True as that path is not part of the default config + self._settings.set( + ["checks", "pip"], + { + "type": "pypi_release", + "package": "pip", + "pip": "pip=={target_version}", + }, + force=True, + ) + else: + self._settings.remove(["checks", "pip"]) + update_pip_check_config = True + + if update_pip_check_config: + self._invalidate_version_cache("pip") + + def get_settings_version(self): + return 9 + + def on_settings_migrate(self, target, current=None): + + if current is None or current < 6: + # up until & including config version 5 we didn't set the method parameter for the octoprint check + # configuration + + configured_checks = self._settings.get(["checks"], incl_defaults=False) + if configured_checks is not None and "octoprint" in configured_checks: + octoprint_check = dict(configured_checks["octoprint"]) + + if ( + not "method" in octoprint_check + and octoprint_check.get("type") == "git_commit" + ): + defaults = { + "plugins": { + "softwareupdate": {"checks": {"octoprint": {"method": "pip"}}} + } + } + self._settings.set( + ["checks", "octoprint", "method"], + "update_script", + defaults=defaults, + ) + + if current == 4: + # config version 4 didn't correctly remove the old settings for octoprint_restart_command + # and environment_restart_command + + self._settings.set(["environment_restart_command"], None) + self._settings.set(["octoprint_restart_command"], None) + + if current is None or current < 5: + # config version 4 and higher moves octoprint_restart_command and + # environment_restart_command to the core configuration + + # current plugin commands + configured_octoprint_restart_command = self._settings.get( + ["octoprint_restart_command"] + ) + configured_environment_restart_command = self._settings.get( + ["environment_restart_command"] + ) + + # current global commands + configured_system_restart_command = self._settings.global_get( + ["server", "commands", "systemRestartCommand"] + ) + configured_server_restart_command = self._settings.global_get( + ["server", "commands", "serverRestartCommand"] + ) + + # only set global commands if they are not yet set + if ( + configured_system_restart_command is None + and configured_environment_restart_command is not None + ): + self._settings.global_set( + ["server", "commands", "systemRestartCommand"], + configured_environment_restart_command, + ) + if ( + configured_server_restart_command is None + and configured_octoprint_restart_command is not None + ): + self._settings.global_set( + ["server", "commands", "serverRestartCommand"], + configured_octoprint_restart_command, + ) + + # delete current plugin commands from config + self._settings.set(["environment_restart_command"], None) + self._settings.set(["octoprint_restart_command"], None) + + if current is None or current == 2 or current == 8: + # No config version and config version 2 and 8 need the same fix, stripping + # accidentally persisted data off the checks. + # + # We used to do the same processing for the plugin entries too here, but that interfered + # with manual configuration entries. Stuff got deleted that wasn't supposed to be deleted. + # + # The problem is that we don't know if an entry we are looking at and which didn't come through + # a plugin hook is simply an entry from a now uninstalled/unactive plugin, or if it was something + # manually configured by the user. So instead of just blindly removing anything that doesn't + # come from a plugin here we instead clean up anything that indeed comes from a plugin + # during run time and leave everything else as is in the hopes that will not cause trouble. + # + # We still handle the "octoprint" entry here though. + + configured_checks = self._settings.get(["checks"], incl_defaults=False) + if configured_checks is not None and "octoprint" in configured_checks: + octoprint_check = dict(configured_checks["octoprint"]) + if ( + "type" not in octoprint_check + or octoprint_check["type"] not in self.CURRENT_TRACKING_TYPES + ): + deletables = ["current", "displayName", "displayVersion"] + else: + deletables = [] + self._clean_settings_check( + "octoprint", + octoprint_check, + self.get_settings_defaults()["checks"]["octoprint"], + delete=deletables, + save=False, + ) + + elif current == 1: + # config version 1 had the error that the octoprint check got accidentally + # included in checks["octoprint"], leading to recursion and hence to + # yaml parser errors + + configured_checks = self._settings.get(["checks"], incl_defaults=False) + if configured_checks is None: + return + + if ( + "octoprint" in configured_checks + and "octoprint" in configured_checks["octoprint"] + ): + # that's a circular reference, back to defaults + dummy_defaults = {"plugins": {}} + dummy_defaults["plugins"][self._identifier] = {"checks": {}} + dummy_defaults["plugins"][self._identifier]["checks"]["octoprint"] = None + self._settings.set(["checks", "octoprint"], None, defaults=dummy_defaults) + + if current is None or current < 8: + # remove check_providers again + self._settings.remove(["check_providers"]) + + def _clean_settings_check(self, key, data, defaults, delete=None, save=True): + if not data: + # nothing to do + return data + + if delete is None: + delete = [] + + for k, v in data.items(): + if k in defaults and defaults[k] == data[k]: + delete.append(k) + + for k in delete: + if k in data: + del data[k] + + dummy_defaults = {"plugins": {}} + dummy_defaults["plugins"][self._identifier] = {"checks": {}} + dummy_defaults["plugins"][self._identifier]["checks"][key] = defaults + if len(data): + self._settings.set(["checks", key], data, defaults=dummy_defaults) + else: + self._settings.remove(["checks", key], defaults=dummy_defaults) + + if save: + self._settings.save() + + return data + + # ~~ BluePrint API + + @octoprint.plugin.BlueprintPlugin.route("/check", methods=["GET"]) + @no_firstrun_access + @Permissions.PLUGIN_SOFTWAREUPDATE_CHECK.require(403) + def check_for_update(self): + request_data = flask.request.values + + if "targets" in request_data or "check" in request_data: + check_targets = list( + map( + lambda x: x.strip(), + request_data.get("targets", request_data.get("check", "")).split(","), + ) + ) + else: + check_targets = None + + force = ( + request_data.get("force", "false") in octoprint.settings.valid_boolean_trues + ) + + def view(): + self._environment_ready.wait(timeout=30.0) + + try: + ( + information, + update_available, + update_possible, + ) = self.get_current_versions(check_targets=check_targets, force=force) + + storage = list() + for key, name in ( + ("python", gettext("Python package installation folder")), + ("plugins", gettext("Plugin folder")), + ("temp", gettext("System temporary files")), + ): + data = self._storage_info.get(key) + if not data: + continue + + s = {"name": name} + s.update(**data) + storage.append(s) + + status = "current" + if self._update_in_progress: + status = "inProgress" + elif ( + update_available + and update_possible + and self._environment_supported + and self._storage_sufficient + ): + status = "updatePossible" + elif update_available: + status = "updateAvailable" + + return flask.jsonify( + { + "status": status, + "information": information, + "timestamp": self._version_cache_timestamp, + "environment": { + "supported": self._environment_supported, + "versions": [ + { + "name": gettext("Python"), + "current": self._environment_versions.get( + "python", "unknown" + ), + "minimum": MINIMUM_PYTHON, + }, + { + "name": gettext("pip"), + "current": self._environment_versions.get( + "pip", "unknown" + ), + "minimum": MINIMUM_PIP, + }, + { + "name": gettext("setuptools"), + "current": self._environment_versions.get( + "setuptools", "unknown" + ), + "minimum": MINIMUM_SETUPTOOLS, + }, + ], + }, + "storage": { + "sufficient": self._storage_sufficient, + "free": storage, + }, + } + ) + except exceptions.ConfigurationInvalid as e: + return flask.make_response( + "Update not properly configured, can't proceed: {}".format(e), 500 + ) + + def etag(): + checks = self._get_configured_checks() + + targets = check_targets + if targets is None: + targets = checks.keys() + + hash = hashlib.sha1() + + def hash_update(value): + value = value.encode("utf-8") + hash.update(value) + + targets = sorted(targets) + for target in targets: + current_hash = self._get_check_hash(checks.get(target, {})) + if target in self._version_cache and not force: + data = self._version_cache[target] + hash_update(current_hash) + hash_update( + str( + data["timestamp"] + self._version_cache_ttl + >= time.time() + > data["timestamp"] + ) + ) + hash_update(repr(data["information"])) + hash_update(str(data["available"])) + hash_update(str(data["possible"])) + hash_update(str(data.get("online", None))) + + hash_update(",".join(targets)) + + hash_update(str(self._environment_supported)) + hash_update(str(self._version_cache_timestamp)) + hash_update(str(self._overlay_cache_timestamp)) + hash_update(str(self._connectivity_checker.online)) + hash_update(str(self._update_in_progress)) + hash_update(self.DATA_FORMAT_VERSION) + return hash.hexdigest() + + def condition(): + return check_etag(etag()) + + return with_revalidation_checking( + etag_factory=lambda *args, **kwargs: etag(), + condition=lambda *args, **kwargs: condition(), + unless=lambda: force or self._check_overlays_stale, + )(view)() + + @octoprint.plugin.BlueprintPlugin.route("/update", methods=["POST"]) + @no_firstrun_access + @Permissions.PLUGIN_SOFTWAREUPDATE_UPDATE.require(403) + def perform_update(self): + throttled = self._get_throttled() + if ( + throttled + and isinstance(throttled, dict) + and throttled.get("current_issue", False) + and not self._settings.get_boolean(["ignore_throttled"]) + ): + # currently throttled, we refuse to run + return flask.make_response( + "System is currently throttled, refusing to update " + "anything due to possible stability issues", + 409, + ) + + if self._printer.is_printing() or self._printer.is_paused(): + # do not update while a print job is running + return flask.make_response("Printer is currently printing or paused", 409) + + if not self._environment_supported: + return flask.make_response( + "Direct updates are not supported in this Python environment", 409 + ) + + if not self._storage_sufficient: + return flask.make_response("Not enough free disk space for updating", 409) + + if not "application/json" in flask.request.headers["Content-Type"]: + return flask.make_response("Expected content-type JSON", 400) + + json_data = flask.request.get_json(silent=True) + if json_data is None: + return flask.make_response("Invalid JSON", 400) + + if "targets" in json_data or "checks" in json_data: + targets = list( + map( + lambda x: x.strip(), + json_data.get("targets", json_data.get("check", [])), + ) + ) + else: + targets = None + + force = json_data.get("force", "false") in octoprint.settings.valid_boolean_trues + + to_be_checked, checks = self.perform_updates(targets=targets, force=force) + return flask.jsonify({"order": to_be_checked, "checks": checks}) + + @octoprint.plugin.BlueprintPlugin.route("/configure", methods=["POST"]) + @no_firstrun_access + @Permissions.PLUGIN_SOFTWAREUPDATE_CONFIGURE.require(403) + def configure_update(self): + json_data = flask.request.get_json(silent=True) + if json_data is None: + return flask.make_response("Invalid JSON", 400) + + checks = self._get_configured_checks() + + settings_dirty = False + for target, data in json_data.items(): + if not target in checks: + continue + + try: + populated_check = self._populated_check(target, checks[target]) + except exceptions.UnknownCheckType: + self._logger.debug( + "Ignoring unknown check type for target {}".format(target) + ) + continue + except Exception: + self._logger.exception( + "Error while populating check prior to configuration for target {}".format( + target + ) + ) + continue + + patch = {} + + # switched release channel + if "channel" in data: + if ( + populated_check["type"] == "github_release" + and "stable_branch" in populated_check + and "prerelease_branches" in populated_check + ): + valid_channel = data["channel"] == populated_check[ + "stable_branch" + ].get("branch") or any( + map( + lambda x: data["channel"] == x.get("branch"), + populated_check["prerelease_branches"], + ) + ) + prerelease = data["channel"] != populated_check["stable_branch"].get( + "branch" + ) + + if valid_channel: + patch["prerelease"] = prerelease + patch["prerelease_channel"] = data["channel"] + + # disable/enable check + if "disabled" in data: + patch["disabled"] = ( + data["disabled"] in octoprint.settings.valid_boolean_trues + ) + + # do we have changes to apply? + if patch: + current = self._settings.get(["checks", target], incl_defaults=False) + updated = dict_merge(current, patch) + self._settings.set( + ["checks", target], + updated, + defaults={"plugins": {"softwareupdate": {"checks": {target: {}}}}}, + ) + + settings_dirty = True + self._invalidate_version_cache(target) + + if settings_dirty: + self._settings.save() + + return NO_CONTENT + + def is_blueprint_protected(self): + return False + + # ~~ Asset API + + def get_assets(self): + return { + "css": ["css/softwareupdate.css"], + "js": ["js/softwareupdate.js"], + "clientjs": ["clientjs/softwareupdate.js"], + "less": ["less/softwareupdate.less"], + } + + ##~~ TemplatePlugin API + + def get_template_configs(self): + from flask_babel import gettext + + return [{"type": "settings", "name": gettext("Software Update")}] + + ##~~ WizardPlugin API + + def is_wizard_required(self): + checks = self._get_configured_checks() + check = checks.get("octoprint", None) + checkout_folder = self._get_octoprint_checkout_folder(checks=checks) + return ( + check + and "method" in check + and check["method"] == "update_script" + and not checkout_folder + ) + + ##~~ EventHandlerPlugin API + + def on_event(self, event, payload): + from octoprint.events import Events + + if ( + event != Events.CONNECTIVITY_CHANGED + or not payload + or not payload.get("new", False) + ): + return + + thread = threading.Thread(target=self.get_current_versions) + thread.daemon = True + thread.start() + + # ~~ Updater + + def get_current_versions(self, check_targets=None, force=False): + """ + Retrieves the current version information for all defined check_targets. Will retrieve information for all + available targets by default. + + :param check_targets: an iterable defining the targets to check, if not supplied defaults to all targets + """ + + if force: + self._get_check_overlays(force=True) + + checks = self._get_configured_checks() + if check_targets is None: + check_targets = list(checks.keys()) + + update_available = False + update_possible = False + information = {} + + # we don't want to do the same work twice, so let's use a lock + if self._get_versions_mutex.acquire(False): + self._get_versions_data_ready.clear() + try: + futures_to_result = {} + online = self._connectivity_checker.check_immediately() + self._logger.debug( + "Looks like we are {}".format("online" if online else "offline") + ) + + with futures.ThreadPoolExecutor(max_workers=5) as executor: + for target, check in checks.items(): + if not target in check_targets: + continue + + if not check: + continue + + try: + populated_check = self._populated_check(target, check) + future = executor.submit( + self._get_current_version, + target, + populated_check, + force=force, + ) + futures_to_result[future] = (target, populated_check) + except exceptions.UnknownCheckType: + self._logger.warning( + "Unknown update check type for target {}: {}".format( + target, check.get("type", "") + ) + ) + continue + except Exception: + self._logger.exception( + "Could not check {} for updates".format(target) + ) + continue + + for future in futures.as_completed(futures_to_result): + + target, populated_check = futures_to_result[future] + if future.exception() is not None: + self._logger.error( + "Could not check {} for updates, error: {!r}".format( + target, future.exception() + ) + ) + continue + + ( + target_information, + target_update_available, + target_update_possible, + target_online, + target_error, + ) = future.result() + target_update_possible = ( + target_update_possible and self._environment_supported + ) + + target_information = dict_merge( + { + "local": {"name": "?", "value": "?"}, + "remote": { + "name": "?", + "value": "?", + "release_notes": None, + }, + "needs_online": True, + }, + target_information, + ) + + target_disabled = populated_check.get("disabled", False) + update_available = update_available or ( + target_update_available and not target_disabled + ) + update_possible = update_possible or ( + target_update_possible + and target_update_available + and not target_disabled + ) + + local_name = target_information["local"]["name"] + local_value = target_information["local"]["value"] + + release_notes = None + if ( + target_information + and target_information["remote"] + and target_information["remote"]["value"] + ): + if ( + "release_notes" in populated_check + and populated_check["release_notes"] + ): + release_notes = populated_check["release_notes"] + elif "release_notes" in target_information["remote"]: + release_notes = target_information["remote"][ + "release_notes" + ] + + if release_notes: + release_notes = release_notes.format( + octoprint_version=VERSION, + target_name=target_information["remote"]["name"], + target_version=target_information["remote"]["value"], + ) + + information[target] = { + "updateAvailable": target_update_available, + "updatePossible": target_update_possible, + "information": target_information, + "displayName": populated_check["displayName"], + "displayVersion": populated_check["displayVersion"].format( + octoprint_version=VERSION, + local_name=local_name, + local_value=local_value, + ), + "releaseNotes": release_notes, + "online": target_online, + "error": target_error, + "disabled": target_disabled, + "releaseChannels": {}, + } + + if ( + populated_check["type"] == "github_release" + and "stable_branch" in populated_check + and "prerelease_branches" in populated_check + ): + # target supports release channels via github branches and releases + def to_release_channel(branch_info): + return { + "name": branch_info["name"], + "channel": branch_info["branch"], + } + + stable_channel = populated_check["stable_branch"]["branch"] + current_channel = populated_check.get("prerelease_channel") + release_channels = [ + to_release_channel(populated_check["stable_branch"]), + ] + list( + map( + to_release_channel, + populated_check["prerelease_branches"], + ) + ) + information[target]["releaseChannels"] = { + "available": release_channels, + "current": current_channel + if current_channel + else stable_channel, + "stable": stable_channel, + } + + if "released_version" in populated_check: + information[target]["releasedVersion"] = populated_check[ + "released_version" + ] + + if self._version_cache_dirty: + self._save_version_cache() + + self._get_versions_data = information, update_available, update_possible + self._get_versions_data_ready.set() + finally: + self._get_versions_mutex.release() + + else: # something's already in progress, let's wait for it to complete and use its result + self._get_versions_data_ready.wait() + information, update_available, update_possible = self._get_versions_data + + return information, update_available, update_possible + + def _get_check_hash(self, check): + def dict_to_sorted_repr(d): + lines = [] + for key in sorted(d.keys()): + value = d[key] + if isinstance(value, dict): + lines.append("{!r}: {}".format(key, dict_to_sorted_repr(value))) + else: + lines.append("{!r}: {!r}".format(key, value)) + + return "{" + ", ".join(lines) + "}" + + hash = hashlib.md5() + + def hash_update(value): + value = value.encode("utf-8") + hash.update(value) + + hash_update(dict_to_sorted_repr(check)) + return hash.hexdigest() + + def _get_current_version(self, target, check, force=False, online=None): + """ + Determines the current version information for one target based on its check configuration. + """ + + current_hash = self._get_check_hash(check) + if online is None: + online = self._connectivity_checker.online + if target in self._version_cache and not force: + data = self._version_cache[target] + if ( + data["hash"] == current_hash + and data["timestamp"] + self._version_cache_ttl + >= time.time() + > data["timestamp"] + and data.get("online", None) == online + ): + # we also check that timestamp < now to not get confused too much by clock changes + return ( + data["information"], + data["available"], + data["possible"], + data["online"], + data.get("error", None), + ) + + information = {} + update_available = False + error = None + + try: + version_checker = self._get_version_checker(target, check) + information, is_current = version_checker.get_latest( + target, check, online=online + ) + if information is not None: + if ( + is_current + and check["type"] in self.CURRENT_TRACKING_TYPES + and check["current"] is None + ): + self._persist_check_current( + target, check, information["remote"]["value"] + ) + del self._version_cache[target] + self._version_cache_dirty = True + elif not is_current: + update_available = True + except exceptions.CannotCheckOffline: + update_possible = False + information["needs_online"] = True + except exceptions.UnknownCheckType: + self._logger.warning("Unknown check type %s for %s" % (check["type"], target)) + update_possible = False + error = "unknown_check" + except exceptions.NetworkError: + self._logger.warning( + "Could not check %s for updates due to a network error" % target + ) + update_possible = False + error = "network" + except Exception: + self._logger.exception("Could not check %s for updates" % target) + update_possible = False + error = "unknown" + else: + try: + updater = self._get_updater(target, check) + update_possible = updater.can_perform_update(target, check, online=online) + except Exception: + self._logger.exception( + "Error while checking if {} can be updated".format(target) + ) + update_possible = False + + disabled = check.get("disabled", False) + + self._version_cache[target] = { + "timestamp": time.time(), + "hash": current_hash, + "information": information, + "available": update_available, + "possible": update_possible, + "online": online, + "error": error, + "disabled": disabled, + } + self._version_cache_dirty = True + return information, update_available, update_possible, online, error + + def perform_updates(self, force=False, **kwargs): + """ + Performs the updates for the given check_targets. Will update all possible targets by default. + + :param targets: an iterable defining the targets to update, if not supplied defaults to all targets + """ + + if not self._environment_supported: + self._logger.error("Direct updates are unsupported in this environment") + return [], {} + + if not self._storage_sufficient: + self._logger.error("Not enough free disk space for updating") + return [], {} + + targets = kwargs.get("targets", kwargs.get("check_targets", None)) + + checks = self._get_configured_checks() + populated_checks = {} + for target, check in checks.items(): + try: + populated_checks[target] = self._populated_check(target, check) + except exceptions.UnknownCheckType: + self._logger.debug( + "Ignoring unknown check type for target {}".format(target) + ) + except Exception: + self._logger.exception( + "Error while populating check prior to update for target {}".format( + target + ) + ) + + if targets is None: + targets = populated_checks.keys() + to_be_updated = sorted(set(targets) & set(populated_checks.keys())) + if "octoprint" in to_be_updated: + to_be_updated.remove("octoprint") + tmp = ["octoprint"] + to_be_updated + to_be_updated = tmp + if "pip" in to_be_updated: + to_be_updated.remove("pip") + tmp = ["pip"] + to_be_updated + to_be_updated = tmp + + updater_thread = threading.Thread( + target=self._update_worker, args=(populated_checks, to_be_updated, force) + ) + updater_thread.daemon = False + updater_thread.start() + + check_data = dict( + (key, check["displayName"] if "displayName" in check else key) + for key, check in populated_checks.items() + if key in to_be_updated + ) + return to_be_updated, check_data + + def _update_worker(self, checks, check_targets, force): + + restart_type = None + + try: + self._update_in_progress = True + + target_results = {} + error = False + + ### iterate over all configured targets + + for target in check_targets: + if not target in checks: + continue + check = checks[target] + + if "enabled" in check and not check["enabled"]: + continue + + if not target in check_targets: + continue + + target_error, target_result = self._perform_update(target, check, force) + error = error or target_error + if target_result is not None: + target_results[target] = target_result + + if "restart" in check: + target_restart_type = check["restart"] + elif ( + "pip" in check + or check.get("method") in self.OCTOPRINT_RESTART_TYPES + ): + target_restart_type = "octoprint" + else: + target_restart_type = None + + # if our update requires a restart we have to determine which type + if restart_type is None or ( + restart_type == "octoprint" + and target_restart_type == "environment" + ): + restart_type = target_restart_type + + finally: + # we might have needed to update the config, so we'll save that now + self._settings.save() + + # also, we are now longer updating + self._update_in_progress = False + + if error: + # if there was an unignorable error, we just return error + self._send_client_message("error", {"results": target_results}) + + else: + self._save_version_cache() + + # otherwise the update process was a success, but we might still have to restart + if restart_type is not None and restart_type in ("octoprint", "environment"): + # one of our updates requires a restart of either type "octoprint" or "environment". Let's see if + # we can actually perform that + + restart_command = None + if restart_type == "octoprint": + restart_command = self._settings.global_get( + ["server", "commands", "serverRestartCommand"] + ) + elif restart_type == "environment": + restart_command = self._settings.global_get( + ["server", "commands", "systemRestartCommand"] + ) + + if restart_command: + self._send_client_message( + "restarting", + {"restart_type": restart_type, "results": target_results}, + ) + try: + self._perform_restart(restart_command) + except exceptions.RestartFailed: + self._send_client_message( + "restart_failed", + {"restart_type": restart_type, "results": target_results}, + ) + else: + # we don't have this restart type configured, we'll have to display a message that a manual + # restart is needed + self._send_client_message( + "restart_manually", + {"restart_type": restart_type, "results": target_results}, + ) + else: + self._send_client_message("success", {"results": target_results}) + + def _perform_update(self, target, check, force): + online = self._connectivity_checker.online + + information, update_available, update_possible, _, _ = self._get_current_version( + target, check, online=online + ) + + if not update_available and not force: + return False, None + + if not update_possible: + self._logger.warning( + "Cannot perform update for %s, update type is not fully configured" + % target + ) + return False, None + + # determine the target version to update to + target_version = information["remote"]["value"] + target_error = False + target_result = None + + def trigger_event(success, **additional_payload): + from octoprint.events import Events + + if success: + # noinspection PyUnresolvedReferences + event = Events.PLUGIN_SOFTWAREUPDATE_UPDATE_SUCCEEDED + else: + # noinspection PyUnresolvedReferences + event = Events.PLUGIN_SOFTWAREUPDATE_UPDATE_FAILED + + payload = copy.copy(additional_payload) + payload.update( + { + "target": target, + "from_version": information["local"]["value"], + "to_version": target_version, + } + ) + + self._event_bus.fire(event, payload=payload) + + ### The actual update procedure starts here... + + populated_check = self._populated_check(target, check) + try: + self._logger.info("Starting update of %s to %s..." % (target, target_version)) + self._send_client_message( + "updating", + { + "target": target, + "version": target_version, + "name": populated_check["displayName"], + }, + ) + updater = self._get_updater(target, check) + if updater is None: + raise exceptions.UnknownUpdateType() + + update_result = updater.perform_update( + target, populated_check, target_version, log_cb=self._log, online=online + ) + target_result = ("success", update_result) + self._logger.info("Update of %s to %s successful!" % (target, target_version)) + trigger_event(True) + + except exceptions.UnknownUpdateType: + self._logger.warning( + "Update of %s can not be performed, unknown update type" % target + ) + self._send_client_message( + "update_failed", + { + "target": target, + "version": target_version, + "name": populated_check["displayName"], + "reason": "Unknown update type", + }, + ) + return False, None + + except exceptions.CannotUpdateOffline: + self._logger.warning( + "Update of %s can not be performed, it's not marked as 'offline' capable but we are apparently offline right now" + % target + ) + self._send_client_message( + "update_failed", + { + "target": target, + "version": target_version, + "name": populated_check["displayName"], + "reason": "No internet connection", + }, + ) + + except Exception as e: + self._logger.exception( + "Update of %s can not be performed, please also check plugin_softwareupdate_console.log for possible causes of this" + % target + ) + trigger_event(False) + + if not "ignorable" in populated_check or not populated_check["ignorable"]: + target_error = True + + if isinstance(e, exceptions.UpdateError): + target_result = ("failed", e.data) + self._send_client_message( + "update_failed", + { + "target": target, + "version": target_version, + "name": populated_check["displayName"], + "reason": e.data, + }, + ) + else: + target_result = ("failed", None) + self._send_client_message( + "update_failed", + { + "target": target, + "version": target_version, + "name": populated_check["displayName"], + "reason": "unknown", + }, + ) + + else: + # make sure that any external changes to config.yaml are loaded into the system + self._settings.load() + + # persist the new version if necessary for check type + self._persist_check_current(target, check, target_version) + + del self._version_cache[target] + self._version_cache_dirty = True + + return target_error, target_result + + def _persist_check_current(self, target, check, current): + if check["type"] not in self.CURRENT_TRACKING_TYPES: + return + + self._settings.load() + + dummy_default = {"plugins": {}} + dummy_default["plugins"][self._identifier] = {"checks": {}} + dummy_default["plugins"][self._identifier]["checks"][target] = {"current": None} + self._settings.set(["checks", target, "current"], current, defaults=dummy_default) + + # we have to save here (even though that makes us save quite often) since otherwise the next + # load will overwrite our changes we just made + self._settings.save() + + check["current"] = current + + def _perform_restart(self, restart_command): + """ + Performs a restart using the supplied restart_command. + """ + + self._logger.info("Restarting...") + try: + util.execute(restart_command, evaluate_returncode=False, do_async=True) + except exceptions.ScriptError as e: + self._logger.exception( + "Error while restarting via command {}".format(restart_command) + ) + self._logger.warning("Restart stdout:\n{}".format(e.stdout)) + self._logger.warning("Restart stderr:\n{}".format(e.stderr)) + raise exceptions.RestartFailed() + + def _populated_check(self, target, check): + from flask_babel import gettext + + if not "type" in check: + raise exceptions.UnknownCheckType() + + result = dict(check) + + if target == "octoprint": + + from octoprint.util.version import ( + is_released_octoprint_version, + is_stable_octoprint_version, + ) + + displayName = check.get("displayName") + if displayName is None: + # displayName missing or set to None + displayName = gettext("OctoPrint") + result["displayName"] = to_unicode(displayName, errors="replace") + + displayVersion = check.get("displayVersion") + if displayVersion is None: + # displayVersion missing or set to None + displayVersion = "{octoprint_version}" + result["displayVersion"] = to_unicode(displayVersion, errors="replace") + + stable_branch = "master" + release_branches = [] + if "stable_branch" in check: + release_branches.append(check["stable_branch"]["branch"]) + stable_branch = check["stable_branch"]["branch"] + if "prerelease_branches" in check: + release_branches += [x["branch"] for x in check["prerelease_branches"]] + result["released_version"] = is_released_octoprint_version() + + if check["type"] in self.COMMIT_TRACKING_TYPES: + result["current"] = REVISION if REVISION else "unknown" + else: + result["current"] = VERSION + + if check["type"] == "github_release" and ( + check.get("prerelease", None) or not is_stable_octoprint_version() + ): + # we are tracking github releases and are either also tracking prerelease OR are currently running + # a non stable version => we need to change some parameters + + # we compare versions fully, not just the base so that we see a difference + # between RCs + stable for the same version release + result["force_base"] = False + + if check.get("prerelease", None): + # we are tracking prereleases => we want to be on the correct prerelease channel/branch + channel = check.get("prerelease_channel", None) + if channel: + # if we have a release channel, we also set our update_branch here to our release channel + # in case it's not already set + result["update_branch"] = check.get("update_branch", channel) + + else: + # we are not tracking prereleases, but aren't on the stable branch either => switch back + # to stable branch on update + result["update_branch"] = check.get( + "update_branch", stable_branch + ) + + if check.get("update_script", None): + # we force an exact version & python unequality check, to be able to downgrade + result["force_exact_version"] = True + result["release_compare"] = "python_unequal" + elif check.get("pip", None): + # we force python unequality check for pip installs, to be able to downgrade + result["release_compare"] = "python_unequal" + + elif target == "pip": + import pkg_resources + + displayName = check.get("displayName") + if displayName is None: + # displayName missing or set to None + displayName = gettext("pip") + result["displayName"] = to_unicode(displayName, errors="replace") + + displayVersion = check.get("displayVersion") + if displayVersion is None: + # displayVersion missing or set to None + distribution = pkg_resources.get_distribution("pip") + if distribution: + displayVersion = distribution.version + result["displayVersion"] = to_unicode(displayVersion, errors="replace") + + else: + result["displayName"] = to_unicode(check.get("displayName"), errors="replace") + if result["displayName"] is None: + # displayName missing or None + result["displayName"] = to_unicode(target, errors="replace") + + result["displayVersion"] = to_unicode( + check.get("displayVersion", check.get("current")), errors="replace" + ) + if result["displayVersion"] is None: + # displayVersion AND current missing or None + result["displayVersion"] = "unknown" + + if check["type"] in self.CURRENT_TRACKING_TYPES: + result["current"] = check.get("current", None) + else: + result["current"] = check.get( + "current", check.get("displayVersion", None) + ) + + if "pip" in result: + if ( + not "pip_command" in check + and self._settings.get(["pip_command"]) is not None + ): + result["pip_command"] = self._settings.get(["pip_command"]) + + return result + + def _log(self, lines, prefix=None, stream=None, strip=True): + if strip: + lines = list(map(lambda x: x.strip(), lines)) + + self._send_client_message( + "loglines", + data={"loglines": [{"line": line, "stream": stream} for line in lines]}, + ) + for line in lines: + self._console_logger.debug("{} {}".format(prefix, line)) + + def _send_client_message(self, message_type, data=None): + self._plugin_manager.send_plugin_message( + self._identifier, {"type": message_type, "data": data} + ) + + def _get_version_checker(self, target, check): + """ + Retrieves the version checker to use for given target and check configuration. Will raise an UnknownCheckType + if version checker cannot be determined. + """ + + if not "type" in check: + raise exceptions.ConfigurationInvalid("no check type defined") + + check_type = check["type"] + method = getattr(version_checks, check_type) + if method is None: + raise exceptions.UnknownCheckType() + else: + return method + + def _get_update_method(self, target, check, valid_methods=None): + """ + Determines the update method for the given target and check. + + If ``valid_methods`` is provided, determine method must be contained + therein to be considered valid. + + Raises an ``UnknownUpdateType`` exception if method cannot be determined + or validated. + """ + + method = None + if "method" in check: + method = check["method"] + else: + if "update_script" in check: + method = "update_script" + elif "pip" in check: + method = "pip" + elif "python_updater" in check: + method = "python_updater" + + if method is None or (valid_methods and not method in valid_methods): + raise exceptions.UnknownUpdateType() + + return method + + def _get_updater(self, target, check): + """ + Retrieves the updater for the given target and check configuration. Will raise an UnknownUpdateType if updater + cannot be determined. + """ + + method = self._get_update_method(target, check) + if method is None: + raise exceptions.UnknownUpdateType() + + updater = getattr(updaters, method) + if updater is None: + raise exceptions.UnknownUpdateType() + + return updater + + def _get_octoprint_checkout_folder(self, checks=None): + if checks is None: + checks = self._get_configured_checks() + + if not "octoprint" in checks: + return None + + if "checkout_folder" in checks["octoprint"]: + return checks["octoprint"]["checkout_folder"] + elif "update_folder" in checks["octoprint"]: + return checks["octoprint"]["update_folder"] + + return None + + def _get_octoprint_tracked_branch(self, checks=None): + if checks is None: + checks = self._get_configured_checks() + + if not "octoprint" in checks: + return None - if "checkout_folder" in checks["octoprint"]: - return checks["octoprint"]["checkout_folder"] - elif "update_folder" in checks["octoprint"]: - return checks["octoprint"]["update_folder"] + return checks["octoprint"].get("branch") - return None - - def _get_octoprint_tracked_branch(self, checks=None): - if checks is None: - checks = self._get_configured_checks() - - if not "octoprint" in checks: - return None - - return checks["octoprint"].get("branch") - - def _get_octoprint_pip_target(self, checks=None): - if checks is None: - checks = self._get_configured_checks() - - if not "octoprint" in checks: - return None - - return checks["octoprint"].get("pip") + def _get_octoprint_pip_target(self, checks=None): + if checks is None: + checks = self._get_configured_checks() + + if not "octoprint" in checks: + return None + + return checks["octoprint"].get("pip") def _register_custom_events(*args, **kwargs): - return ["update_succeeded", "update_failed"] + return ["update_succeeded", "update_failed"] __plugin_name__ = "Software Update" __plugin_author__ = "Gina Häußge" __plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html" __plugin_description__ = "Allows receiving update notifications and performing updates of OctoPrint and plugins" -__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to " - "update itself or any of your installed plugins which might put " - "your system at risk.") +__plugin_disabling_discouraged__ = gettext( + "Without this plugin OctoPrint will no longer be able to " + "update itself or any of your installed plugins which might put " + "your system at risk." +) __plugin_license__ = "AGPLv3" __plugin_pythoncompat__ = ">=2.7,<4" + def __plugin_load__(): - global __plugin_implementation__ - __plugin_implementation__ = SoftwareUpdatePlugin() + global __plugin_implementation__ + __plugin_implementation__ = SoftwareUpdatePlugin() - global __plugin_helpers__ - __plugin_helpers__ = {"version_checks": version_checks, - "updaters": updaters, - "exceptions": exceptions, - "util": util} + global __plugin_helpers__ + __plugin_helpers__ = { + "version_checks": version_checks, + "updaters": updaters, + "exceptions": exceptions, + "util": util, + } - global __plugin_hooks__ - __plugin_hooks__ = { - "octoprint.cli.commands": cli.commands, - "octoprint.events.register_custom_events": _register_custom_events, - "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions - } + global __plugin_hooks__ + __plugin_hooks__ = { + "octoprint.cli.commands": cli.commands, + "octoprint.events.register_custom_events": _register_custom_events, + "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions, + } diff --git a/src/octoprint/plugins/softwareupdate/cli.py b/src/octoprint/plugins/softwareupdate/cli.py index 2aeff8940..d2dcf9655 100644 --- a/src/octoprint/plugins/softwareupdate/cli.py +++ b/src/octoprint/plugins/softwareupdate/cli.py @@ -1,229 +1,255 @@ # -*- 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" def commands(cli_group, pass_octoprint_ctx, *args, **kwargs): - import click - click.disable_unicode_literals_warning = True - import sys - import requests.exceptions - from octoprint.cli.client import create_client, client_options + import click - @click.command("check") - @click.option("--force", is_flag=True, help="Ignore the cache for the update check") - @click.option("--only-new", is_flag=True, help="Only show entries with updates available") - @client_options - @click.argument("targets", nargs=-1) - def check_command(force, only_new, apikey, host, port, httpuser, httppass, https, prefix, targets): - """ - Check for updates. + click.disable_unicode_literals_warning = True + import sys + import requests.exceptions + from octoprint.cli.client import create_client, client_options - If any TARGETs are provided, only those components will be checked. + @click.command("check") + @click.option("--force", is_flag=True, help="Ignore the cache for the update check") + @click.option( + "--only-new", is_flag=True, help="Only show entries with updates available" + ) + @client_options + @click.argument("targets", nargs=-1) + def check_command( + force, only_new, apikey, host, port, httpuser, httppass, https, prefix, targets + ): + """ + Check for updates. - \b - Examples: - - octoprint plugins softwareupdate:check - This will check all components for available updates, - utilizing cached version information. - - octoprint plugins softwareupdate:check --force - This will check all components for available updates, - ignoring any cached version information even if it's - still valid. - - octoprint plugins softwareupdate:check octoprint - This will only check OctoPrint itself for available - updates. + If any TARGETs are provided, only those components will be checked. - Note that the OctoPrint server needs to be running for this - command to work as it utilizes the server API. - """ - params = {"force": force} - if targets: - params["targets"] = ",".join(targets) + \b + Examples: + - octoprint plugins softwareupdate:check + This will check all components for available updates, + utilizing cached version information. + - octoprint plugins softwareupdate:check --force + This will check all components for available updates, + ignoring any cached version information even if it's + still valid. + - octoprint plugins softwareupdate:check octoprint + This will only check OctoPrint itself for available + updates. - client = create_client(settings=cli_group.settings, - apikey=apikey, - host=host, - port=port, - httpuser=httpuser, - httppass=httppass, - https=https, - prefix=prefix) + Note that the OctoPrint server needs to be running for this + command to work as it utilizes the server API. + """ + params = {"force": force} + if targets: + params["targets"] = ",".join(targets) - r = client.get("plugin/softwareupdate/check", params=params) - try: - r.raise_for_status() - except requests.exceptions.HTTPError as e: - click.echo("Could not get update information from server, got {}".format(e)) - sys.exit(1) + client = create_client( + settings=cli_group.settings, + apikey=apikey, + host=host, + port=port, + httpuser=httpuser, + httppass=httppass, + https=https, + prefix=prefix, + ) - data = r.json() - status = data["status"] - information = data["information"] + r = client.get("plugin/softwareupdate/check", params=params) + try: + r.raise_for_status() + except requests.exceptions.HTTPError as e: + click.echo("Could not get update information from server, got {}".format(e)) + sys.exit(1) - lines = [] - octoprint_line = None - for key, info in information.items(): - status_text = "Up to date" - if info["updateAvailable"]: - if info["updatePossible"]: - status_text = "Update available" - else: - status_text = "Update available (manual)" + data = r.json() + status = data["status"] + information = data["information"] - elif only_new: - continue + lines = [] + octoprint_line = None + for key, info in information.items(): + status_text = "Up to date" + if info["updateAvailable"]: + if info["updatePossible"]: + status_text = "Update available" + else: + status_text = "Update available (manual)" - line = "{} (target: {})\n\tInstalled: {}\n\tAvailable: {}\n\t=> {}".format(info["displayName"], - key, - info["information"]["local"]["name"], - info["information"]["remote"]["name"], - status_text) - if key == "octoprint": - octoprint_line = line - else: - lines.append(line) + elif only_new: + continue - lines.sort() - if octoprint_line: - lines = [octoprint_line] + lines + line = "{} (target: {})\n\tInstalled: {}\n\tAvailable: {}\n\t=> {}".format( + info["displayName"], + key, + info["information"]["local"]["name"], + info["information"]["remote"]["name"], + status_text, + ) + if key == "octoprint": + octoprint_line = line + else: + lines.append(line) - for line in lines: - click.echo(line) + lines.sort() + if octoprint_line: + lines = [octoprint_line] + lines - click.echo() - if status == "current": - click.echo("Everything is up to date") - else: - click.echo("There are updates available!") + for line in lines: + click.echo(line) + click.echo() + if status == "current": + click.echo("Everything is up to date") + else: + click.echo("There are updates available!") - @click.command("update") - @click.option("--force", is_flag=True, help="Update even if already up to date") - @client_options - @click.argument("targets", nargs=-1) - def update_command(force, apikey, host, port, httpuser, httppass, https, prefix, targets): - """ - Apply updates. + @click.command("update") + @click.option("--force", is_flag=True, help="Update even if already up to date") + @client_options + @click.argument("targets", nargs=-1) + def update_command( + force, apikey, host, port, httpuser, httppass, https, prefix, targets + ): + """ + Apply updates. - If any TARGETs are provided, only those components will be updated. + If any TARGETs are provided, only those components will be updated. - \b - Examples: - - octoprint plugins softwareupdate:update - This will update all components with a pending update - that can be updated. - - octoprint plugins softwareupdate:update --force - This will force an update of all registered components - that can be updated, even if they don't have an updated - pending. - - octoprint plugins softwareupdate:update octoprint - This will only update OctoPrint and leave any further - components with pending updates at their current versions. + \b + Examples: + - octoprint plugins softwareupdate:update + This will update all components with a pending update + that can be updated. + - octoprint plugins softwareupdate:update --force + This will force an update of all registered components + that can be updated, even if they don't have an updated + pending. + - octoprint plugins softwareupdate:update octoprint + This will only update OctoPrint and leave any further + components with pending updates at their current versions. - Note that the OctoPrint server needs to be running for this - command to work as it utilizes the server API. - """ + Note that the OctoPrint server needs to be running for this + command to work as it utilizes the server API. + """ - data = {"force": force} - if targets: - data["targets"] = targets + data = {"force": force} + if targets: + data["targets"] = targets - client = create_client(settings=cli_group.settings, - apikey=apikey, - host=host, - port=port, - httpuser=httpuser, - httppass=httppass, - https=https, - prefix=prefix) + client = create_client( + settings=cli_group.settings, + apikey=apikey, + host=host, + port=port, + httpuser=httpuser, + httppass=httppass, + https=https, + prefix=prefix, + ) - flags = {"waiting_for_restart": False, - "seen_close": False} + flags = {"waiting_for_restart": False, "seen_close": False} - def on_message(ws, msg_type, msg): - if msg_type != "plugin" or msg["plugin"] != "softwareupdate": - return + def on_message(ws, msg_type, msg): + if msg_type != "plugin" or msg["plugin"] != "softwareupdate": + return - plugin_message = msg["data"] - if not "type" in plugin_message: - return + plugin_message = msg["data"] + if not "type" in plugin_message: + return - plugin_message_type = plugin_message["type"] - plugin_message_data = plugin_message["data"] + plugin_message_type = plugin_message["type"] + plugin_message_data = plugin_message["data"] - if plugin_message_type == "updating": - click.echo("Updating {} to {}...".format(plugin_message_data.get("name", "unknown"), plugin_message_data.get("version", "n/a"))) + if plugin_message_type == "updating": + click.echo( + "Updating {} to {}...".format( + plugin_message_data.get("name", "unknown"), + plugin_message_data.get("version", "n/a"), + ) + ) - elif plugin_message_type == "update_failed": - click.echo("\t... failed :(") + elif plugin_message_type == "update_failed": + click.echo("\t... failed :(") - elif plugin_message_type == "loglines" and "loglines" in plugin_message_data: - for entry in plugin_message_data["loglines"]: - prefix = ">>> " if entry["stream"] == "call" else "" - error = entry["stream"] == "stderr" - click.echo("\t{}{}".format(prefix, entry["line"].replace("\n", "\n\t")), err=error) + elif plugin_message_type == "loglines" and "loglines" in plugin_message_data: + for entry in plugin_message_data["loglines"]: + prefix = ">>> " if entry["stream"] == "call" else "" + error = entry["stream"] == "stderr" + click.echo( + "\t{}{}".format(prefix, entry["line"].replace("\n", "\n\t")), + err=error, + ) - elif plugin_message_type == "success" or plugin_message_type == "restart_manually": - results = plugin_message_data["results"] if "results" in plugin_message_data else {} - if results: - click.echo("The update finished successfully.") - if plugin_message_type == "restart_manually": - click.echo("Please restart the OctoPrint server.") - else: - click.echo("No update necessary") - ws.close() + elif ( + plugin_message_type == "success" + or plugin_message_type == "restart_manually" + ): + results = ( + plugin_message_data["results"] + if "results" in plugin_message_data + else {} + ) + if results: + click.echo("The update finished successfully.") + if plugin_message_type == "restart_manually": + click.echo("Please restart the OctoPrint server.") + else: + click.echo("No update necessary") + ws.close() - elif plugin_message_type == "restarting": - flags["waiting_for_restart"] = True - click.echo("Restarting to apply changes...") + elif plugin_message_type == "restarting": + flags["waiting_for_restart"] = True + click.echo("Restarting to apply changes...") - elif plugin_message_type == "error": - click.echo("Error") - ws.close() + elif plugin_message_type == "error": + click.echo("Error") + ws.close() - def on_open(ws): - if flags["waiting_for_restart"] and flags["seen_close"]: - click.echo(" Reconnected!") - else: - click.echo("Connected to server...") + def on_open(ws): + if flags["waiting_for_restart"] and flags["seen_close"]: + click.echo(" Reconnected!") + else: + click.echo("Connected to server...") - def on_close(ws): - if flags["waiting_for_restart"] and flags["seen_close"]: - click.echo(".", nl=False) - else: - flags["seen_close"] = True - click.echo("Disconnected from server...") + def on_close(ws): + if flags["waiting_for_restart"] and flags["seen_close"]: + click.echo(".", nl=False) + else: + flags["seen_close"] = True + click.echo("Disconnected from server...") - socket = client.create_socket(on_message=on_message, - on_open=on_open, - on_close=on_close) + socket = client.create_socket( + on_message=on_message, on_open=on_open, on_close=on_close + ) - r = client.post_json("plugin/softwareupdate/update", data=data) - try: - r.raise_for_status() - except requests.exceptions.HTTPError as e: - click.echo("Could not get update information from server, got {}".format(e)) - sys.exit(1) + r = client.post_json("plugin/softwareupdate/update", data=data) + try: + r.raise_for_status() + except requests.exceptions.HTTPError as e: + click.echo("Could not get update information from server, got {}".format(e)) + sys.exit(1) - data = r.json() - to_be_updated = data["order"] - checks = data["checks"] - click.echo("Update in progress, updating:") - for name in to_be_updated: - click.echo("\t{}".format(name if not name in checks else checks[name])) + data = r.json() + to_be_updated = data["order"] + checks = data["checks"] + click.echo("Update in progress, updating:") + for name in to_be_updated: + click.echo("\t{}".format(name if not name in checks else checks[name])) - socket.wait() - - if flags["waiting_for_restart"]: - if socket.reconnect(timeout=60): - click.echo("The update finished successfully.") - else: - click.echo("The update finished successfully but the server apparently didn't restart as expected.") - click.echo("Please restart the OctoPrint server.") - - return [check_command, update_command] + socket.wait() + if flags["waiting_for_restart"]: + if socket.reconnect(timeout=60): + click.echo("The update finished successfully.") + else: + click.echo( + "The update finished successfully but the server apparently didn't restart as expected." + ) + click.echo("Please restart the OctoPrint server.") + return [check_command, update_command] diff --git a/src/octoprint/plugins/softwareupdate/exceptions.py b/src/octoprint/plugins/softwareupdate/exceptions.py index 685317025..08aad6fe7 100644 --- a/src/octoprint/plugins/softwareupdate/exceptions.py +++ b/src/octoprint/plugins/softwareupdate/exceptions.py @@ -2,55 +2,65 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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" class NoUpdateAvailable(Exception): - pass + pass + class UpdateAlreadyInProgress(Exception): - pass + pass + class UnknownUpdateType(Exception): - pass + pass + class UnknownCheckType(Exception): - pass + pass + class NetworkError(Exception): - def __init__(self, message=None, cause=None): - Exception.__init__(self) - self.message = message - self.cause = cause + def __init__(self, message=None, cause=None): + Exception.__init__(self) + self.message = message + self.cause = cause + + def __str__(self): + if self.message is not None: + return self.message + elif self.cause is not None: + return "NetworkError caused by {}".format(self.cause) + else: + return "NetworkError" - def __str__(self): - if self.message is not None: - return self.message - elif self.cause is not None: - return "NetworkError caused by {}".format(self.cause) - else: - return "NetworkError" class UpdateError(Exception): - def __init__(self, message, data): - self.message = message - self.data = data + def __init__(self, message, data): + self.message = message + self.data = data + class ScriptError(Exception): - def __init__(self, returncode, stdout, stderr): - self.returncode = returncode - self.stdout = stdout - self.stderr = stderr + def __init__(self, returncode, stdout, stderr): + self.returncode = returncode + self.stdout = stdout + self.stderr = stderr + class RestartFailed(Exception): - pass + pass + class ConfigurationInvalid(Exception): - pass + pass + class CannotCheckOffline(Exception): - pass + pass + class CannotUpdateOffline(Exception): - pass + pass diff --git a/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py b/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py index 1ce91f4f9..320d2a015 100644 --- a/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py +++ b/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py @@ -3,7 +3,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Haeussge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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" @@ -16,310 +16,416 @@ from past.builtins import unicode # default close_fds settings if sys.platform == "win32" and sys.version_info < (3, 7): - CLOSE_FDS = False + CLOSE_FDS = False else: - CLOSE_FDS = True + CLOSE_FDS = True + def _log_call(*lines): - _log(lines, prefix=">", stream="call") + _log(lines, prefix=">", stream="call") def _log_stdout(*lines): - _log(lines, prefix=" ", stream="stdout") + _log(lines, prefix=" ", stream="stdout") def _log_stderr(*lines): - _log(lines, prefix=" ", stream="stderr") + _log(lines, prefix=" ", stream="stderr") def _log(lines, prefix=None, stream=None): - output_stream = sys.stdout - if stream == "stderr": - output_stream = sys.stderr + output_stream = sys.stdout + if stream == "stderr": + output_stream = sys.stderr - for line in lines: - to_print = _to_bytes("{} {}".format(prefix, _to_unicode(line.rstrip(), errors="replace")), - errors="replace") - print(to_print, file=output_stream) + for line in lines: + to_print = _to_bytes( + "{} {}".format(prefix, _to_unicode(line.rstrip(), errors="replace")), + errors="replace", + ) + print(to_print, file=output_stream) def _to_unicode(s_or_u, encoding="utf-8", errors="strict"): - """Make sure ``s_or_u`` is a unicode string.""" - if isinstance(s_or_u, bytes): - return s_or_u.decode(encoding, errors=errors) - else: - return s_or_u + """Make sure ``s_or_u`` is a unicode string.""" + if isinstance(s_or_u, bytes): + return s_or_u.decode(encoding, errors=errors) + else: + return s_or_u def _to_bytes(s_or_u, encoding="utf-8", errors="strict"): - """Make sure ``s_or_u`` is a str.""" - if isinstance(s_or_u, unicode): - return s_or_u.encode(encoding, errors=errors) - else: - return s_or_u + """Make sure ``s_or_u`` is a str.""" + if isinstance(s_or_u, unicode): + return s_or_u.encode(encoding, errors=errors) + else: + return s_or_u def _execute(command, **kwargs): - import sarge + import sarge - if isinstance(command, (list, tuple)): - joined_command = " ".join(command) - else: - joined_command = command - _log_call(joined_command) + if isinstance(command, (list, tuple)): + joined_command = " ".join(command) + else: + joined_command = command + _log_call(joined_command) - kwargs.update({"close_fds": CLOSE_FDS, - "async_": True, - "stdout": sarge.Capture(), - "stderr": sarge.Capture()}) + kwargs.update( + { + "close_fds": CLOSE_FDS, + "async_": True, + "stdout": sarge.Capture(), + "stderr": sarge.Capture(), + } + ) - try: - p = sarge.run(command, **kwargs) - while len(p.commands) == 0: - # somewhat ugly... we can't use wait_events because - # the events might not be all set if an exception - # by sarge is triggered within the async process - # thread - time.sleep(0.01) + try: + p = sarge.run(command, **kwargs) + while len(p.commands) == 0: + # somewhat ugly... we can't use wait_events because + # the events might not be all set if an exception + # by sarge is triggered within the async process + # thread + time.sleep(0.01) - # by now we should have a command, let's wait for its - # process to have been prepared - p.commands[0].process_ready.wait() + # by now we should have a command, let's wait for its + # process to have been prepared + p.commands[0].process_ready.wait() - if not p.commands[0].process: - # the process might have been set to None in case of any exception - print("Error while trying to run command {}".format(joined_command), file=sys.stderr) - return None, [], [] - except Exception: - print("Error while trying to run command {}".format(joined_command), file=sys.stderr) - traceback.print_exc(file=sys.stderr) - return None, [], [] + if not p.commands[0].process: + # the process might have been set to None in case of any exception + print( + "Error while trying to run command {}".format(joined_command), + file=sys.stderr, + ) + return None, [], [] + except Exception: + print( + "Error while trying to run command {}".format(joined_command), file=sys.stderr + ) + traceback.print_exc(file=sys.stderr) + return None, [], [] - all_stdout = [] - all_stderr = [] - try: - while p.commands[0].poll() is None: - lines = p.stderr.readlines(timeout=0.5) - if lines: - lines = list(map(lambda x: _to_unicode(x, errors="replace"), lines)) - _log_stderr(*lines) - all_stderr += lines + all_stdout = [] + all_stderr = [] + try: + while p.commands[0].poll() is None: + lines = p.stderr.readlines(timeout=0.5) + if lines: + lines = list(map(lambda x: _to_unicode(x, errors="replace"), lines)) + _log_stderr(*lines) + all_stderr += lines - lines = p.stdout.readlines(timeout=0.5) - if lines: - lines = list(map(lambda x: _to_unicode(x, errors="replace"), lines)) - _log_stdout(*lines) - all_stdout += lines + lines = p.stdout.readlines(timeout=0.5) + if lines: + lines = list(map(lambda x: _to_unicode(x, errors="replace"), lines)) + _log_stdout(*lines) + all_stdout += lines - finally: - p.close() + finally: + p.close() - lines = p.stderr.readlines() - if lines: - lines = list(map(lambda x: _to_unicode(x, errors="replace"), lines)) - _log_stderr(*lines) - all_stderr += lines + lines = p.stderr.readlines() + if lines: + lines = list(map(lambda x: _to_unicode(x, errors="replace"), lines)) + _log_stderr(*lines) + all_stderr += lines - lines = p.stdout.readlines() - if lines: - lines = list(map(lambda x: _to_unicode(x, errors="replace"), lines)) - _log_stdout(*lines) - all_stdout += lines + lines = p.stdout.readlines() + if lines: + lines = list(map(lambda x: _to_unicode(x, errors="replace"), lines)) + _log_stdout(*lines) + all_stdout += lines - return p.returncode, all_stdout, all_stderr + return p.returncode, all_stdout, all_stderr def _get_git_executables(): - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - return GITS + GITS = ["git"] + if sys.platform == "win32": + GITS = ["git.cmd", "git.exe"] + return GITS def _git(args, cwd, git_executable=None): - if git_executable is not None: - commands = [git_executable] - else: - commands = _get_git_executables() + if git_executable is not None: + commands = [git_executable] + else: + commands = _get_git_executables() - for c in commands: - command = [c] + args - try: - return _execute(command, cwd=cwd) - except EnvironmentError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue + for c in commands: + command = [c] + args + try: + return _execute(command, cwd=cwd) + except EnvironmentError: + e = sys.exc_info()[1] + if e.errno == errno.ENOENT: + continue - print("Error while trying to run command {}".format(" ".join(command)), file=sys.stderr) - traceback.print_exc(file=sys.stderr) - return None, [], [] - except Exception: - print("Error while trying to run command {}".format(" ".join(command)), file=sys.stderr) - traceback.print_exc(file=sys.stderr) - return None, [], [] - else: - print("Unable to find git command, tried {}".format(", ".join(commands)), file=sys.stderr) - return None, [], [] + print( + "Error while trying to run command {}".format(" ".join(command)), + file=sys.stderr, + ) + traceback.print_exc(file=sys.stderr) + return None, [], [] + except Exception: + print( + "Error while trying to run command {}".format(" ".join(command)), + file=sys.stderr, + ) + traceback.print_exc(file=sys.stderr) + return None, [], [] + else: + print( + "Unable to find git command, tried {}".format(", ".join(commands)), + file=sys.stderr, + ) + return None, [], [] def _python(args, cwd, python_executable, sudo=False): - command = [python_executable] + args - if sudo: - command = ["sudo"] + command - try: - return _execute(command, cwd=cwd) - except Exception: - import traceback - print("Error while trying to run command {}".format(" ".join(command)), file=sys.stderr) - traceback.print_exc(file=sys.stderr) - return None, [], [] + command = [python_executable] + args + if sudo: + command = ["sudo"] + command + try: + return _execute(command, cwd=cwd) + except Exception: + import traceback + + print( + "Error while trying to run command {}".format(" ".join(command)), + file=sys.stderr, + ) + traceback.print_exc(file=sys.stderr) + return None, [], [] def _to_error(*lines): - if len(lines) == 1: - if isinstance(lines[0], (list, tuple)): - lines = lines[0] - elif not isinstance(lines[0], (str, unicode)): - lines = [repr(lines[0]),] - return "\n".join(map(lambda x: _to_unicode(x, errors="replace"), lines)) + if len(lines) == 1: + if isinstance(lines[0], (list, tuple)): + lines = lines[0] + elif not isinstance(lines[0], (str, unicode)): + lines = [ + repr(lines[0]), + ] + return "\n".join(map(lambda x: _to_unicode(x, errors="replace"), lines)) def _rescue_changes(git_executable, folder): - print(">>> Running: git diff --shortstat") - returncode, stdout, stderr = _git(["diff", "--shortstat"], folder, git_executable=git_executable) - if returncode is None or returncode != 0: - raise RuntimeError("Could not update, \"git diff\" failed with returncode {}".format(returncode)) - if stdout and "".join(stdout).strip(): - # we got changes in the working tree, maybe from the user, so we'll now rescue those into a patch - import time - import os - timestamp = time.strftime("%Y%m%d%H%M") - patch = os.path.join(folder, "{}-preupdate.patch".format(timestamp)) + print(">>> Running: git diff --shortstat") + returncode, stdout, stderr = _git( + ["diff", "--shortstat"], folder, git_executable=git_executable + ) + if returncode is None or returncode != 0: + raise RuntimeError( + 'Could not update, "git diff" failed with returncode {}'.format(returncode) + ) + if stdout and "".join(stdout).strip(): + # we got changes in the working tree, maybe from the user, so we'll now rescue those into a patch + import time + import os - print(">>> Running: git diff and saving output to {}".format(patch)) - returncode, stdout, stderr = _git(["diff"], folder, git_executable=git_executable) - if returncode is None or returncode != 0: - raise RuntimeError("Could not update, installation directory was dirty and state could not be persisted as a patch to {}".format(patch)) + timestamp = time.strftime("%Y%m%d%H%M") + patch = os.path.join(folder, "{}-preupdate.patch".format(timestamp)) - import io - with io.open(patch, "wt", encoding="utf-8", errors="replace") as f: - for line in stdout: - f.write(line) + print(">>> Running: git diff and saving output to {}".format(patch)) + returncode, stdout, stderr = _git(["diff"], folder, git_executable=git_executable) + if returncode is None or returncode != 0: + raise RuntimeError( + "Could not update, installation directory was dirty and state could not be persisted as a patch to {}".format( + patch + ) + ) - return True + import io - return False + with io.open(patch, "wt", encoding="utf-8", errors="replace") as f: + for line in stdout: + f.write(line) + + return True + + return False def update_source(git_executable, folder, target, force=False, branch=None): - if _rescue_changes(git_executable, folder): - print(">>> Running: git reset --hard") - returncode, stdout, stderr = _git(["reset", "--hard"], folder, git_executable=git_executable) - if returncode is None or returncode != 0: - raise RuntimeError("Could not update, \"git reset --hard\" failed with returncode {}".format(returncode)) + if _rescue_changes(git_executable, folder): + print(">>> Running: git reset --hard") + returncode, stdout, stderr = _git( + ["reset", "--hard"], folder, git_executable=git_executable + ) + if returncode is None or returncode != 0: + raise RuntimeError( + 'Could not update, "git reset --hard" failed with returncode {}'.format( + returncode + ) + ) - print(">>> Running: git clean -f -d -e *-preupdate.patch") - returncode, stdout, stderr = _git(["clean", "-f", "-d", "-e", "*-preupdate.patch"], folder, git_executable=git_executable) - if returncode is None or returncode != 0: - raise RuntimeError("Could not update, \"git clean -f\" failed with returncode {}".format(returncode)) + print(">>> Running: git clean -f -d -e *-preupdate.patch") + returncode, stdout, stderr = _git( + ["clean", "-f", "-d", "-e", "*-preupdate.patch"], + folder, + git_executable=git_executable, + ) + if returncode is None or returncode != 0: + raise RuntimeError( + 'Could not update, "git clean -f" failed with returncode {}'.format( + returncode + ) + ) - print(">>> Running: git fetch") - returncode, stdout, stderr = _git(["fetch"], folder, git_executable=git_executable) - if returncode is None or returncode != 0: - raise RuntimeError("Could not update, \"git fetch\" failed with returncode {}".format(returncode)) + print(">>> Running: git fetch") + returncode, stdout, stderr = _git(["fetch"], folder, git_executable=git_executable) + if returncode is None or returncode != 0: + raise RuntimeError( + 'Could not update, "git fetch" failed with returncode {}'.format(returncode) + ) - if branch is not None and branch.strip() != "": - print(">>> Running: git checkout {}".format(branch)) - returncode, stdout, stderr = _git(["checkout", branch], folder, git_executable=git_executable) - if returncode is None or returncode != 0: - raise RuntimeError("Could not update, \"git checkout\" failed with returncode {}".format(returncode)) + if branch is not None and branch.strip() != "": + print(">>> Running: git checkout {}".format(branch)) + returncode, stdout, stderr = _git( + ["checkout", branch], folder, git_executable=git_executable + ) + if returncode is None or returncode != 0: + raise RuntimeError( + 'Could not update, "git checkout" failed with returncode {}'.format( + returncode + ) + ) - print(">>> Running: git pull") - returncode, stdout, stderr = _git(["pull"], folder, git_executable=git_executable) - if returncode is None or returncode != 0: - raise RuntimeError("Could not update, \"git pull\" failed with returncode {}".format(returncode)) + print(">>> Running: git pull") + returncode, stdout, stderr = _git(["pull"], folder, git_executable=git_executable) + if returncode is None or returncode != 0: + raise RuntimeError( + 'Could not update, "git pull" failed with returncode {}'.format(returncode) + ) - if force: - reset_command = ["reset", "--hard"] - reset_command += [target] + if force: + reset_command = ["reset", "--hard"] + reset_command += [target] - print(">>> Running: git {}".format(" ".join(reset_command))) - returncode, stdout, stderr = _git(reset_command, folder, git_executable=git_executable) - if returncode is None or returncode != 0: - raise RuntimeError("Error while updating, \"git {}\" failed with returncode {}".format(" ".join(reset_command), returncode)) + print(">>> Running: git {}".format(" ".join(reset_command))) + returncode, stdout, stderr = _git( + reset_command, folder, git_executable=git_executable + ) + if returncode is None or returncode != 0: + raise RuntimeError( + 'Error while updating, "git {}" failed with returncode {}'.format( + " ".join(reset_command), returncode + ) + ) def install_source(python_executable, folder, user=False, sudo=False): - print(">>> Running: python setup.py clean") - returncode, stdout, stderr = _python(["setup.py", "clean"], folder, python_executable) - if returncode is None or returncode != 0: - print("\"python setup.py clean\" failed with returncode {}".format(returncode)) - print("Continuing anyways") + print(">>> Running: python setup.py clean") + returncode, stdout, stderr = _python(["setup.py", "clean"], folder, python_executable) + if returncode is None or returncode != 0: + print('"python setup.py clean" failed with returncode {}'.format(returncode)) + print("Continuing anyways") - print(">>> Running: python setup.py install") - args = ["setup.py", "install"] - if user: - args.append("--user") - returncode, stdout, stderr = _python(args, folder, python_executable, sudo=sudo) - if returncode is None or returncode != 0: - raise RuntimeError("Could not update, \"python setup.py install\" failed with returncode {}".format(returncode)) + print(">>> Running: python setup.py install") + args = ["setup.py", "install"] + if user: + args.append("--user") + returncode, stdout, stderr = _python(args, folder, python_executable, sudo=sudo) + if returncode is None or returncode != 0: + raise RuntimeError( + 'Could not update, "python setup.py install" failed with returncode {}'.format( + returncode + ) + ) def parse_arguments(): - import argparse + import argparse - boolean_trues = ["true", "yes", "1"] + boolean_trues = ["true", "yes", "1"] - parser = argparse.ArgumentParser(prog="update-octoprint.py") + parser = argparse.ArgumentParser(prog="update-octoprint.py") - parser.add_argument("--git", action="store", type=str, dest="git_executable", - help="Specify git executable to use") - parser.add_argument("--python", action="store", type=str, dest="python_executable", - help="Specify python executable to use") - parser.add_argument("--force", action="store", type=lambda x: x in boolean_trues, - dest="force", default=False, - help="Set this to true to force the update to only the specified version (nothing newer, nothing older)") - parser.add_argument("--sudo", action="store_true", dest="sudo", - help="Install with sudo") - parser.add_argument("--user", action="store_true", dest="user", - help="Install to the user site directory instead of the general site directory") - parser.add_argument("--branch", action="store", type=str, dest="branch", default=None, - help="Specify the branch to make sure is checked out") - parser.add_argument("folder", type=str, - help="Specify the base folder of the OctoPrint installation to update") - parser.add_argument("target", type=str, - help="Specify the commit or tag to which to update") + parser.add_argument( + "--git", + action="store", + type=str, + dest="git_executable", + help="Specify git executable to use", + ) + parser.add_argument( + "--python", + action="store", + type=str, + dest="python_executable", + help="Specify python executable to use", + ) + parser.add_argument( + "--force", + action="store", + type=lambda x: x in boolean_trues, + dest="force", + default=False, + help="Set this to true to force the update to only the specified version (nothing newer, nothing older)", + ) + parser.add_argument( + "--sudo", action="store_true", dest="sudo", help="Install with sudo" + ) + parser.add_argument( + "--user", + action="store_true", + dest="user", + help="Install to the user site directory instead of the general site directory", + ) + parser.add_argument( + "--branch", + action="store", + type=str, + dest="branch", + default=None, + help="Specify the branch to make sure is checked out", + ) + parser.add_argument( + "folder", + type=str, + help="Specify the base folder of the OctoPrint installation to update", + ) + parser.add_argument( + "target", type=str, help="Specify the commit or tag to which to update" + ) - args = parser.parse_args() + args = parser.parse_args() + + return args - return args def main(): - args = parse_arguments() + args = parse_arguments() - git_executable = None - if args.git_executable: - git_executable = args.git_executable + git_executable = None + if args.git_executable: + git_executable = args.git_executable - python_executable = sys.executable - if args.python_executable: - python_executable = args.python_executable - if python_executable.startswith('"'): - python_executable = python_executable[1:] - if python_executable.endswith('"'): - python_executable = python_executable[:-1] + python_executable = sys.executable + if args.python_executable: + python_executable = args.python_executable + if python_executable.startswith('"'): + python_executable = python_executable[1:] + if python_executable.endswith('"'): + python_executable = python_executable[:-1] - print("Python executable: {!r}".format(python_executable)) + print("Python executable: {!r}".format(python_executable)) - folder = args.folder + folder = args.folder - import os - if not os.access(folder, os.W_OK): - raise RuntimeError("Could not update, base folder is not writable") + import os + + if not os.access(folder, os.W_OK): + raise RuntimeError("Could not update, base folder is not writable") + + update_source( + git_executable, folder, args.target, force=args.force, branch=args.branch + ) + install_source(python_executable, folder, user=args.user, sudo=args.sudo) - update_source(git_executable, folder, args.target, force=args.force, branch=args.branch) - install_source(python_executable, folder, user=args.user, sudo=args.sudo) if __name__ == "__main__": - main() + main() diff --git a/src/octoprint/plugins/softwareupdate/updaters/__init__.py b/src/octoprint/plugins/softwareupdate/updaters/__init__.py index 6c76224bf..330dc3918 100644 --- a/src/octoprint/plugins/softwareupdate/updaters/__init__.py +++ b/src/octoprint/plugins/softwareupdate/updaters/__init__.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" from . import pip, python_updater, update_script, sleep_a_bit, single_file_plugin diff --git a/src/octoprint/plugins/softwareupdate/updaters/pip.py b/src/octoprint/plugins/softwareupdate/updaters/pip.py index c3c4362b5..7823d89b4 100644 --- a/src/octoprint/plugins/softwareupdate/updaters/pip.py +++ b/src/octoprint/plugins/softwareupdate/updaters/pip.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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" @@ -14,7 +14,9 @@ from octoprint.util.version import get_comparable_version from .. import exceptions logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pip") -console_logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pip.console") +console_logger = logging.getLogger( + "octoprint.plugins.softwareupdate.updaters.pip.console" +) _ALREADY_INSTALLED = "Requirement already satisfied (use --upgrade to upgrade)" _POTENTIAL_EGG_PROBLEM_POSIX = "No such file or directory" @@ -23,108 +25,144 @@ _POTENTIAL_EGG_PROBLEM_WINDOWS = "The system cannot find the file specified" _pip_callers = {} _pip_version_dependency_links = pkg_resources.parse_version("1.5") + def can_perform_update(target, check, online=True): - from .. import MINIMUM_PIP - pip_caller = _get_pip_caller(command=check["pip_command"] if "pip_command" in check else None) - return "pip" in check \ - and pip_caller is not None \ - and pip_caller.available \ - and pip_caller.version >= get_comparable_version(MINIMUM_PIP) \ - and (online or check.get("offline", False)) + from .. import MINIMUM_PIP + + pip_caller = _get_pip_caller( + command=check["pip_command"] if "pip_command" in check else None + ) + return ( + "pip" in check + and pip_caller is not None + and pip_caller.available + and pip_caller.version >= get_comparable_version(MINIMUM_PIP) + and (online or check.get("offline", False)) + ) + def _get_pip_caller(command=None): - key = command - if command is None: - key = "__default" + key = command + if command is None: + key = "__default" - if not key in _pip_callers: - try: - _pip_callers[key] = PipCaller(configured=command) - except UnknownPip: - _pip_callers[key] = None + if not key in _pip_callers: + try: + _pip_callers[key] = PipCaller(configured=command) + except UnknownPip: + _pip_callers[key] = None + + return _pip_callers[key] - return _pip_callers[key] def perform_update(target, check, target_version, log_cb=None, online=True, force=False): - pip_command = None - if "pip_command" in check: - pip_command = check["pip_command"] + pip_command = None + if "pip_command" in check: + pip_command = check["pip_command"] - pip_working_directory = None - if "pip_cwd" in check: - pip_working_directory = check["pip_cwd"] + pip_working_directory = None + if "pip_cwd" in check: + pip_working_directory = check["pip_cwd"] - if not online and not check.get("offline", False): - raise exceptions.CannotUpdateOffline() + if not online and not check.get("offline", False): + raise exceptions.CannotUpdateOffline() - pip_caller = _get_pip_caller(command=pip_command) - if pip_caller is None: - raise exceptions.UpdateError("Can't run pip", None) + pip_caller = _get_pip_caller(command=pip_command) + if pip_caller is None: + raise exceptions.UpdateError("Can't run pip", None) - def _log_call(*lines): - _log(lines, prefix=" ", stream="call") + def _log_call(*lines): + _log(lines, prefix=" ", stream="call") - def _log_stdout(*lines): - _log(lines, prefix=">", stream="stdout") + def _log_stdout(*lines): + _log(lines, prefix=">", stream="stdout") - def _log_stderr(*lines): - _log(lines, prefix="!", stream="stderr") + def _log_stderr(*lines): + _log(lines, prefix="!", stream="stderr") - def _log_message(*lines): - _log(lines, prefix="#", stream="message") + def _log_message(*lines): + _log(lines, prefix="#", stream="message") - def _log(lines, prefix=None, stream=None): - if log_cb is None: - return - log_cb(lines, prefix=prefix, stream=stream) + def _log(lines, prefix=None, stream=None): + if log_cb is None: + return + log_cb(lines, prefix=prefix, stream=stream) - if log_cb is not None: - pip_caller.on_log_call = _log_call - pip_caller.on_log_stdout = _log_stdout - pip_caller.on_log_stderr = _log_stderr + if log_cb is not None: + pip_caller.on_log_call = _log_call + pip_caller.on_log_stdout = _log_stdout + pip_caller.on_log_stderr = _log_stderr - install_arg = check["pip"].format(target_version=target_version, target=target_version) + install_arg = check["pip"].format( + target_version=target_version, target=target_version + ) - logger.debug("Target: %s, executing pip install %s" % (target, install_arg)) - pip_args = ["--disable-pip-version-check", "install", install_arg, "--no-cache-dir"] - pip_kwargs = {"env": {"PYTHONWARNINGS": b"ignore:DEPRECATION::pip._internal.cli.base_command"}} - if pip_working_directory is not None: - pip_kwargs.update(cwd=pip_working_directory) + logger.debug("Target: %s, executing pip install %s" % (target, install_arg)) + pip_args = ["--disable-pip-version-check", "install", install_arg, "--no-cache-dir"] + pip_kwargs = { + "env": {"PYTHONWARNINGS": b"ignore:DEPRECATION::pip._internal.cli.base_command"} + } + if pip_working_directory is not None: + pip_kwargs.update(cwd=pip_working_directory) - if "dependency_links" in check and check["dependency_links"]: - pip_args += ["--process-dependency-links"] + if "dependency_links" in check and check["dependency_links"]: + pip_args += ["--process-dependency-links"] - returncode, stdout, stderr = pip_caller.execute(*pip_args, **pip_kwargs) - if returncode != 0: - # This could be caused by an issue with pip/setuptools: If something (target or dependency of target) was - # installed as an egg at an earlier date (e.g. thanks to just running python setup.py install), pip install - # will throw an error after updating that something to a newer (non-egg) version since it will still have - # the egg on its sys.path and expect to read data from it. Running the exact same command a second time - # solved this during hunt for a workaround, so this is what we'll now do if it indeed looks like this - # specific problem - def is_egg_problem(line): - return (_POTENTIAL_EGG_PROBLEM_POSIX in line or _POTENTIAL_EGG_PROBLEM_WINDOWS in line) and ".egg" in line + returncode, stdout, stderr = pip_caller.execute(*pip_args, **pip_kwargs) + if returncode != 0: + # This could be caused by an issue with pip/setuptools: If something (target or dependency of target) was + # installed as an egg at an earlier date (e.g. thanks to just running python setup.py install), pip install + # will throw an error after updating that something to a newer (non-egg) version since it will still have + # the egg on its sys.path and expect to read data from it. Running the exact same command a second time + # solved this during hunt for a workaround, so this is what we'll now do if it indeed looks like this + # specific problem + def is_egg_problem(line): + return ( + _POTENTIAL_EGG_PROBLEM_POSIX in line + or _POTENTIAL_EGG_PROBLEM_WINDOWS in line + ) and ".egg" in line - if any(map(lambda x: is_egg_problem(x), stderr)) or any(map(lambda x: is_egg_problem(x), stdout)): - _log_message("This looks like an error caused by a specific issue in upgrading Python \"eggs\"", - "via current versions of pip.", - "Performing a second install attempt as a work around.") - returncode, stdout, stderr = pip_caller.execute(*pip_args, **pip_kwargs) - if returncode != 0: - raise exceptions.UpdateError("Error while executing pip install", (stdout, stderr)) - else: - raise exceptions.UpdateError("Error while executing pip install", (stdout, stderr)) + if any(map(lambda x: is_egg_problem(x), stderr)) or any( + map(lambda x: is_egg_problem(x), stdout) + ): + _log_message( + 'This looks like an error caused by a specific issue in upgrading Python "eggs"', + "via current versions of pip.", + "Performing a second install attempt as a work around.", + ) + returncode, stdout, stderr = pip_caller.execute(*pip_args, **pip_kwargs) + if returncode != 0: + raise exceptions.UpdateError( + "Error while executing pip install", (stdout, stderr) + ) + else: + raise exceptions.UpdateError( + "Error while executing pip install", (stdout, stderr) + ) - if not force and any(map(lambda x: x.strip().startswith(_ALREADY_INSTALLED) and (install_arg in x or install_arg in x.lower()), stdout)): - _log_message("Looks like we were already installed in this version. Forcing a reinstall.") - force = True + if not force and any( + map( + lambda x: x.strip().startswith(_ALREADY_INSTALLED) + and (install_arg in x or install_arg in x.lower()), + stdout, + ) + ): + _log_message( + "Looks like we were already installed in this version. Forcing a reinstall." + ) + force = True - if force: - logger.debug("Target: %s, executing pip install %s --ignore-reinstalled --force-reinstall --no-deps" % (target, install_arg)) - pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"] + if force: + logger.debug( + "Target: %s, executing pip install %s --ignore-reinstalled --force-reinstall --no-deps" + % (target, install_arg) + ) + pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"] - returncode, stdout, stderr = pip_caller.execute(*pip_args, **pip_kwargs) - if returncode != 0: - raise exceptions.UpdateError("Error while executing pip install --force-reinstall", (stdout, stderr)) + returncode, stdout, stderr = pip_caller.execute(*pip_args, **pip_kwargs) + if returncode != 0: + raise exceptions.UpdateError( + "Error while executing pip install --force-reinstall", (stdout, stderr) + ) - return "ok" + return "ok" diff --git a/src/octoprint/plugins/softwareupdate/updaters/python_updater.py b/src/octoprint/plugins/softwareupdate/updaters/python_updater.py index caf5ce636..f78bdbb1d 100644 --- a/src/octoprint/plugins/softwareupdate/updaters/python_updater.py +++ b/src/octoprint/plugins/softwareupdate/updaters/python_updater.py @@ -2,28 +2,38 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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" def can_perform_update(target, check, online=True): - return "python_updater" in check and check["python_updater"] is not None and hasattr(check["python_updater"], "perform_update") and (online or check.get("offline", False)) + return ( + "python_updater" in check + and check["python_updater"] is not None + and hasattr(check["python_updater"], "perform_update") + and (online or check.get("offline", False)) + ) def perform_update(target, check, target_version, log_cb=None, online=True): - from ..exceptions import CannotUpdateOffline + from ..exceptions import CannotUpdateOffline - if not online and not check("offline", False): - raise CannotUpdateOffline() + if not online and not check("offline", False): + raise CannotUpdateOffline() - try: - return check["python_updater"].perform_update(target, check, target_version, log_cb=log_cb, online=online) - except Exception: - import inspect - args, _, _, _ = inspect.getargspec(check["python_updater"].perform_update) - if "online" not in args: - # old python_updater footprint, simply leave out the online parameter - return check["python_updater"].perform_update(target, check, target_version, log_cb=log_cb) + try: + return check["python_updater"].perform_update( + target, check, target_version, log_cb=log_cb, online=online + ) + except Exception: + import inspect - # some other error, raise again - raise + args, _, _, _ = inspect.getargspec(check["python_updater"].perform_update) + if "online" not in args: + # old python_updater footprint, simply leave out the online parameter + return check["python_updater"].perform_update( + target, check, target_version, log_cb=log_cb + ) + + # some other error, raise again + raise diff --git a/src/octoprint/plugins/softwareupdate/updaters/single_file_plugin.py b/src/octoprint/plugins/softwareupdate/updaters/single_file_plugin.py index 22fb09ea6..c5724f16f 100644 --- a/src/octoprint/plugins/softwareupdate/updaters/single_file_plugin.py +++ b/src/octoprint/plugins/softwareupdate/updaters/single_file_plugin.py @@ -1,7 +1,7 @@ # -*- 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License" import logging @@ -15,61 +15,73 @@ from octoprint.util.net import download_file from octoprint.settings import settings from .. import exceptions -logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.download_single_file_plugin") +logger = logging.getLogger( + "octoprint.plugins.softwareupdate.updaters.download_single_file_plugin" +) + def can_perform_update(target, check, online=True): - return online or check.get("offline", False) + return online or check.get("offline", False) + def perform_update(target, check, target_version, log_cb=None, online=True, force=False): - if not online and not check.get("offline", False): - raise exceptions.CannotUpdateOffline() + if not online and not check.get("offline", False): + raise exceptions.CannotUpdateOffline() - url = check.get("url") - if url is None: - raise exceptions.ConfigurationInvalid("download_single_file_plugin updater needs url set") + url = check.get("url") + if url is None: + raise exceptions.ConfigurationInvalid( + "download_single_file_plugin updater needs url set" + ) - def _log_call(*lines): - _log(lines, prefix=" ", stream="call") + def _log_call(*lines): + _log(lines, prefix=" ", stream="call") - def _log_message(*lines): - _log(lines, prefix="#", stream="message") + def _log_message(*lines): + _log(lines, prefix="#", stream="message") - def _log(lines, prefix=None, stream=None): - if log_cb is None: - return - log_cb(lines, prefix=prefix, stream=stream) + def _log(lines, prefix=None, stream=None): + if log_cb is None: + return + log_cb(lines, prefix=prefix, stream=stream) - folder = None - try: - try: - _log_message("Download file from {}".format(url)) - folder = TemporaryDirectory() - path = download_file(url, folder.name) - except Exception as exc: - raise exceptions.NetworkError(cause=exc) + folder = None + try: + try: + _log_message("Download file from {}".format(url)) + folder = TemporaryDirectory() + path = download_file(url, folder.name) + except Exception as exc: + raise exceptions.NetworkError(cause=exc) - filename = os.path.basename(path) - _, ext = os.path.splitext(filename) - if ext not in (".py",): - raise exceptions.UpdateError("File is not a python file: {}".format(filename), None) + filename = os.path.basename(path) + _, ext = os.path.splitext(filename) + if ext not in (".py",): + raise exceptions.UpdateError( + "File is not a python file: {}".format(filename), None + ) - try: - with io.open(path, 'rb') as f: - ast.parse(f.read(), filename=path) - except Exception: - logger.exception("Could not parse {} as python file".format(path), None) - raise exceptions.UpdateError("Could not parse {} as python file.".format(filename), None) + try: + with io.open(path, "rb") as f: + ast.parse(f.read(), filename=path) + except Exception: + logger.exception("Could not parse {} as python file".format(path), None) + raise exceptions.UpdateError( + "Could not parse {} as python file.".format(filename), None + ) - destination = os.path.join(settings().getBaseFolder("plugins"), filename) + destination = os.path.join(settings().getBaseFolder("plugins"), filename) - try: - _log_message("Copy {} to {}".format(path, destination)) - shutil.copy(path, destination) - except Exception: - logger.exception("Could not copy {} to {}".format(path, destination)) - raise exceptions.UpdateError("Could not copy {} to {}".format(path, destination), None) + try: + _log_message("Copy {} to {}".format(path, destination)) + shutil.copy(path, destination) + except Exception: + logger.exception("Could not copy {} to {}".format(path, destination)) + raise exceptions.UpdateError( + "Could not copy {} to {}".format(path, destination), None + ) - return "ok" - finally: - if folder is not None: - folder.cleanup() + return "ok" + finally: + if folder is not None: + folder.cleanup() diff --git a/src/octoprint/plugins/softwareupdate/updaters/sleep_a_bit.py b/src/octoprint/plugins/softwareupdate/updaters/sleep_a_bit.py index a4ff75b8b..6d3b74c7c 100644 --- a/src/octoprint/plugins/softwareupdate/updaters/sleep_a_bit.py +++ b/src/octoprint/plugins/softwareupdate/updaters/sleep_a_bit.py @@ -1,7 +1,7 @@ # -*- 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -9,16 +9,17 @@ import time from octoprint.util import monotonic_time + def can_perform_update(target, check, online=True): - return True + return True def perform_update(target, check, target_version, log_cb=None, online=True): - duration = check.get("duration", 30) + duration = check.get("duration", 30) - now = monotonic_time() - end = now + duration - while now < end: - log_cb(["{}s left...".format(end - now)], prefix=">", stream="output") - time.sleep(5) - now = monotonic_time() + now = monotonic_time() + end = now + duration + while now < end: + log_cb(["{}s left...".format(end - now)], prefix=">", stream="output") + time.sleep(5) + now = monotonic_time() diff --git a/src/octoprint/plugins/softwareupdate/updaters/update_script.py b/src/octoprint/plugins/softwareupdate/updaters/update_script.py index 247da85a2..3a994c946 100644 --- a/src/octoprint/plugins/softwareupdate/updaters/update_script.py +++ b/src/octoprint/plugins/softwareupdate/updaters/update_script.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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 sys @@ -14,92 +14,119 @@ from octoprint.util.commandline import CommandlineCaller, CommandlineError def _get_caller(log_cb=None): - def _log_call(*lines): - _log(lines, prefix=" ", stream="call") + def _log_call(*lines): + _log(lines, prefix=" ", stream="call") - def _log_stdout(*lines): - _log(lines, prefix=">", stream="stdout") + def _log_stdout(*lines): + _log(lines, prefix=">", stream="stdout") - def _log_stderr(*lines): - _log(lines, prefix="!", stream="stderr") + def _log_stderr(*lines): + _log(lines, prefix="!", stream="stderr") - def _log(lines, prefix=None, stream=None): - if log_cb is None: - return - log_cb(lines, prefix=prefix, stream=stream) + def _log(lines, prefix=None, stream=None): + if log_cb is None: + return + log_cb(lines, prefix=prefix, stream=stream) - caller = CommandlineCaller() - if log_cb is not None: - caller.on_log_call = _log_call - caller.on_log_stdout = _log_stdout - caller.on_log_stderr = _log_stderr - return caller + caller = CommandlineCaller() + if log_cb is not None: + caller.on_log_call = _log_call + caller.on_log_stdout = _log_stdout + caller.on_log_stderr = _log_stderr + return caller def can_perform_update(target, check, online=True): - import os - script_configured = bool("update_script" in check and check["update_script"]) + import os - folder = None - if "update_folder" in check: - folder = check["update_folder"] - elif "checkout_folder" in check: - folder = check["checkout_folder"] - folder_configured = bool(folder and os.path.isdir(folder)) + script_configured = bool("update_script" in check and check["update_script"]) - return script_configured and folder_configured and (online or check.get("offline", False)) + folder = None + if "update_folder" in check: + folder = check["update_folder"] + elif "checkout_folder" in check: + folder = check["checkout_folder"] + folder_configured = bool(folder and os.path.isdir(folder)) + + return ( + script_configured + and folder_configured + and (online or check.get("offline", False)) + ) def perform_update(target, check, target_version, log_cb=None, online=True): - logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.update_script") + logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.update_script") - if not online and not check("offline", False): - raise CannotUpdateOffline() + if not online and not check("offline", False): + raise CannotUpdateOffline() - if not can_perform_update(target, check): - raise ConfigurationInvalid("checkout_folder and update_folder are missing for update target %s, one is needed" % target) + if not can_perform_update(target, check): + raise ConfigurationInvalid( + "checkout_folder and update_folder are missing for update target %s, one is needed" + % target + ) - update_script = check["update_script"] - update_branch = check.get("update_branch", "") - force_exact_version = check.get("force_exact_version", False) - folder = check.get("update_folder", check.get("checkout_folder")) # either should be set, tested above - pre_update_script = check.get("pre_update_script", None) - post_update_script = check.get("post_update_script", None) + update_script = check["update_script"] + update_branch = check.get("update_branch", "") + force_exact_version = check.get("force_exact_version", False) + folder = check.get( + "update_folder", check.get("checkout_folder") + ) # either should be set, tested above + pre_update_script = check.get("pre_update_script", None) + post_update_script = check.get("post_update_script", None) - caller = _get_caller(log_cb=log_cb) + caller = _get_caller(log_cb=log_cb) - ### pre update + ### pre update - if pre_update_script is not None: - logger.debug("Target: %s, running pre-update script: %s" % (target, pre_update_script)) - try: - caller.checked_call(pre_update_script, cwd=folder) - except CommandlineError as e: - logger.exception("Target: %s, error while executing pre update script, got returncode %r" % (target, e.returncode)) + if pre_update_script is not None: + logger.debug( + "Target: %s, running pre-update script: %s" % (target, pre_update_script) + ) + try: + caller.checked_call(pre_update_script, cwd=folder) + except CommandlineError as e: + logger.exception( + "Target: %s, error while executing pre update script, got returncode %r" + % (target, e.returncode) + ) - ### update + ### update - try: - update_command = update_script.format(python=sys.executable, - folder=folder, - target=target_version, - branch=update_branch, - force="true" if force_exact_version else "false") + try: + update_command = update_script.format( + python=sys.executable, + folder=folder, + target=target_version, + branch=update_branch, + force="true" if force_exact_version else "false", + ) - logger.debug("Target %s, running update script: %s" % (target, update_command)) + logger.debug("Target %s, running update script: %s" % (target, update_command)) - caller.checked_call(update_command, cwd=folder) - except CommandlineError as e: - logger.exception("Target: %s, error while executing update script, got returncode %r" % (target, e.returncode)) - raise UpdateError("Error while executing update script for %s", (e.stdout, e.stderr)) + caller.checked_call(update_command, cwd=folder) + except CommandlineError as e: + logger.exception( + "Target: %s, error while executing update script, got returncode %r" + % (target, e.returncode) + ) + raise UpdateError( + "Error while executing update script for %s", (e.stdout, e.stderr) + ) - ### post update + ### post update - if post_update_script is not None: - logger.debug("Target: %s, running post-update script %s..." % (target, post_update_script)) - try: - caller.checked_call(post_update_script, cwd=folder) - except CommandlineError as e: - logger.exception("Target: %s, error while executing post update script, got returncode %r" % (target, e.returncode)) + if post_update_script is not None: + logger.debug( + "Target: %s, running post-update script %s..." % (target, post_update_script) + ) + try: + caller.checked_call(post_update_script, cwd=folder) + except CommandlineError as e: + logger.exception( + "Target: %s, error while executing post update script, got returncode %r" + % (target, e.returncode) + ) - return "ok" + return "ok" diff --git a/src/octoprint/plugins/softwareupdate/util.py b/src/octoprint/plugins/softwareupdate/util.py index ed29dda7a..ddac79b1e 100644 --- a/src/octoprint/plugins/softwareupdate/util.py +++ b/src/octoprint/plugins/softwareupdate/util.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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" @@ -12,23 +12,34 @@ import logging from octoprint.util.platform import CLOSE_FDS + def execute(command, cwd=None, evaluate_returncode=True, **kwargs): - do_async = kwargs.get("do_async", kwargs.get("async", False)) + do_async = kwargs.get("do_async", kwargs.get("async", False)) - import sarge - p = None + import sarge - try: - p = sarge.run(command, close_fds=CLOSE_FDS, cwd=cwd, stdout=sarge.Capture(), stderr=sarge.Capture(), async_=do_async) - except Exception: - logging.getLogger(__name__).exception("Error while executing command: {}".format(command)) - returncode = p.returncode if p is not None else None - stdout = p.stdout.text if p is not None and p.stdout is not None else "" - stderr = p.stderr.text if p is not None and p.stderr is not None else "" - raise ScriptError(returncode, stdout, stderr) + p = None - if evaluate_returncode and p.returncode != 0: - raise ScriptError(p.returncode, p.stdout.text, p.stderr.text) + try: + p = sarge.run( + command, + close_fds=CLOSE_FDS, + cwd=cwd, + stdout=sarge.Capture(), + stderr=sarge.Capture(), + async_=do_async, + ) + except Exception: + logging.getLogger(__name__).exception( + "Error while executing command: {}".format(command) + ) + returncode = p.returncode if p is not None else None + stdout = p.stdout.text if p is not None and p.stdout is not None else "" + stderr = p.stderr.text if p is not None and p.stderr is not None else "" + raise ScriptError(returncode, stdout, stderr) - if not do_async: - return p.returncode, p.stdout.text, p.stderr.text + if evaluate_returncode and p.returncode != 0: + raise ScriptError(p.returncode, p.stdout.text, p.stderr.text) + + if not do_async: + return p.returncode, p.stdout.text, p.stderr.text diff --git a/src/octoprint/plugins/softwareupdate/version_checks/__init__.py b/src/octoprint/plugins/softwareupdate/version_checks/__init__.py index d769a224b..c5e35da34 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/__init__.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/__init__.py @@ -2,20 +2,39 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" -from . import commandline, git_commit, github_commit, github_release, bitbucket_commit, \ - python_checker, never_current, always_current, pypi_release, httpheader, jsondata +from . import ( + commandline, + git_commit, + github_commit, + github_release, + bitbucket_commit, + python_checker, + never_current, + always_current, + pypi_release, + httpheader, + jsondata, +) + def log_github_ratelimit(logger, r): - ratelimit = r.headers["X-RateLimit-Limit"] if "X-RateLimit-Limit" in r.headers else "?" - remaining = r.headers["X-RateLimit-Remaining"] if "X-RateLimit-Remaining" in r.headers else "?" - reset = r.headers["X-RateLimit-Reset"] if "X-RateLimit-Reset" in r.headers else None - try: - import time - reset = time.strftime("%Y-%m-%d %H:%M", time.gmtime(int(reset))) - except Exception: - reset = "?" + ratelimit = ( + r.headers["X-RateLimit-Limit"] if "X-RateLimit-Limit" in r.headers else "?" + ) + remaining = ( + r.headers["X-RateLimit-Remaining"] + if "X-RateLimit-Remaining" in r.headers + else "?" + ) + reset = r.headers["X-RateLimit-Reset"] if "X-RateLimit-Reset" in r.headers else None + try: + import time - logger.debug("Github rate limit: %s/%s, reset at %s" % (remaining, ratelimit, reset)) + reset = time.strftime("%Y-%m-%d %H:%M", time.gmtime(int(reset))) + except Exception: + reset = "?" + + logger.debug("Github rate limit: %s/%s, reset at %s" % (remaining, ratelimit, reset)) diff --git a/src/octoprint/plugins/softwareupdate/version_checks/always_current.py b/src/octoprint/plugins/softwareupdate/version_checks/always_current.py index e9bf0131a..df8499894 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/always_current.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/always_current.py @@ -1,13 +1,16 @@ # -*- 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" + def get_latest(target, check, online=True): - current_version = check.get("current_version", "1.0.0") + current_version = check.get("current_version", "1.0.0") - information = {"local": {"name": current_version, "value": current_version}, - "remote": {"name": current_version, "value": current_version}} + information = { + "local": {"name": current_version, "value": current_version}, + "remote": {"name": current_version, "value": current_version}, + } - return information, True + return information, True diff --git a/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py b/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py index cd5e6abe3..0d2935161 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py @@ -1,70 +1,93 @@ # -*- 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" import requests import logging import base64 -BRANCH_HEAD_URL = "https://api.bitbucket.org/2.0/repositories/{user}/{repo}/commit/{branch}" +BRANCH_HEAD_URL = ( + "https://api.bitbucket.org/2.0/repositories/{user}/{repo}/commit/{branch}" +) -logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.bitbucket_commit") +logger = logging.getLogger( + "octoprint.plugins.softwareupdate.version_checks.bitbucket_commit" +) def _get_latest_commit(user, repo, branch, api_user=None, api_password=None): - from ..exceptions import NetworkError + from ..exceptions import NetworkError - url = BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch) - headers = {} - if api_user is not None and api_password is not None: - auth_value = base64.b64encode(b"{user}:{pw}".format(user=api_user, pw=api_password)) - headers["authorization"] = "Basic {}".format(auth_value) + url = BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch) + headers = {} + if api_user is not None and api_password is not None: + auth_value = base64.b64encode( + b"{user}:{pw}".format(user=api_user, pw=api_password) + ) + headers["authorization"] = "Basic {}".format(auth_value) - try: - r = requests.get(url, headers=headers, timeout=(3.05, 30)) - except requests.ConnectionError as exc: - raise NetworkError(cause=exc) + try: + r = requests.get(url, headers=headers, timeout=(3.05, 30)) + except requests.ConnectionError as exc: + raise NetworkError(cause=exc) - if not r.status_code == requests.codes.ok: - return None + if not r.status_code == requests.codes.ok: + return None - reference = r.json() - if not "hash" in reference: - return None + reference = r.json() + if not "hash" in reference: + return None - return reference["hash"] + return reference["hash"] def get_latest(target, check, online=True): - from ..exceptions import ConfigurationInvalid + from ..exceptions import ConfigurationInvalid - if "user" not in check or "repo" not in check: - raise ConfigurationInvalid("Update configuration for %s of type bitbucket_commit needs all of user and repo" % target) + if "user" not in check or "repo" not in check: + raise ConfigurationInvalid( + "Update configuration for %s of type bitbucket_commit needs all of user and repo" + % target + ) - branch = "master" - if "branch" in check and check["branch"] is not None: - branch = check["branch"] + branch = "master" + if "branch" in check and check["branch"] is not None: + branch = check["branch"] - api_user = check.get("api_user") - api_password = check.get("api_password") + api_user = check.get("api_user") + api_password = check.get("api_password") - current = check.get("current") + current = check.get("current") - information = {"local": {"name": "Commit {commit}".format(commit=current if current is not None else "unknown"), "value": current}, - "remote": {"name": "?", "value": "?"}, - "needs_online": not check.get("offline", False)} - if not online and information["needs_online"]: - return information, True + information = { + "local": { + "name": "Commit {commit}".format( + commit=current if current is not None else "unknown" + ), + "value": current, + }, + "remote": {"name": "?", "value": "?"}, + "needs_online": not check.get("offline", False), + } + if not online and information["needs_online"]: + return information, True - remote_commit = _get_latest_commit(check["user"], check["repo"], branch, api_user, api_password) - remote_name = "Commit {commit}".format(commit=remote_commit) if remote_commit is not None else "-" + remote_commit = _get_latest_commit( + check["user"], check["repo"], branch, api_user, api_password + ) + remote_name = ( + "Commit {commit}".format(commit=remote_commit) + if remote_commit is not None + else "-" + ) - information["remote"] = {"name": remote_name, "value": remote_commit} - is_current = (current is not None and current == remote_commit) or remote_commit is None + information["remote"] = {"name": remote_name, "value": remote_commit} + is_current = ( + current is not None and current == remote_commit + ) or remote_commit is None - logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_commit)) - - return information, is_current + logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_commit)) + return information, is_current diff --git a/src/octoprint/plugins/softwareupdate/version_checks/commandline.py b/src/octoprint/plugins/softwareupdate/version_checks/commandline.py index 828de2d88..8ca0a7aca 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/commandline.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/commandline.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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" @@ -11,38 +11,54 @@ import logging from ..exceptions import ConfigurationInvalid, CannotCheckOffline from ..util import execute + def get_latest(target, check, online=True): - command = check.get("command") - if command is None: - raise ConfigurationInvalid("Update configuration for {} of type commandline needs command set and not None".format(target)) + command = check.get("command") + if command is None: + raise ConfigurationInvalid( + "Update configuration for {} of type commandline needs command set and not None".format( + target + ) + ) - if not online and not check.get("offline", False): - raise CannotCheckOffline("{} isn't marked as 'offline' capable, but we are apparently offline right now".format(target)) + if not online and not check.get("offline", False): + raise CannotCheckOffline( + "{} isn't marked as 'offline' capable, but we are apparently offline right now".format( + target + ) + ) - returncode, stdout, stderr = execute(command, evaluate_returncode=False) + returncode, stdout, stderr = execute(command, evaluate_returncode=False) - # We expect command line check commands to - # - # * have a return code of 0 if an update is available, a value != 0 otherwise - # * return the display name of the new version as the final line on stdout - # * return the display name of the current version as the next to final line on stdout - # - # Example output: - # 1.1.0 - # 1.1.1 - # - # 1.1.0 is the current version, 1.1.1 is the remote version. If only one line is output, it's taken to be the - # display name of the new version + # We expect command line check commands to + # + # * have a return code of 0 if an update is available, a value != 0 otherwise + # * return the display name of the new version as the final line on stdout + # * return the display name of the current version as the next to final line on stdout + # + # Example output: + # 1.1.0 + # 1.1.1 + # + # 1.1.0 is the current version, 1.1.1 is the remote version. If only one line is output, it's taken to be the + # display name of the new version - stdout_lines = list(filter(lambda x: len(x.strip()), stdout.splitlines())) - local_name = stdout_lines[-2] if len(stdout_lines) >= 2 else "unknown" - remote_name = stdout_lines[-1] if len(stdout_lines) >= 1 else "unknown" - is_current = returncode != 0 + stdout_lines = list(filter(lambda x: len(x.strip()), stdout.splitlines())) + local_name = stdout_lines[-2] if len(stdout_lines) >= 2 else "unknown" + remote_name = stdout_lines[-1] if len(stdout_lines) >= 1 else "unknown" + is_current = returncode != 0 - information ={"local": {"name": local_name, "value": local_name,}, - "remote": {"name": remote_name, "value": remote_name}} + information = { + "local": { + "name": local_name, + "value": local_name, + }, + "remote": {"name": remote_name, "value": remote_name}, + } - logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.github_commit") - logger.debug("Target: %s, local: %s, remote: %s" % (target, local_name, remote_name)) + logger = logging.getLogger( + "octoprint.plugins.softwareupdate.version_checks.github_commit" + ) + logger.debug("Target: %s, local: %s, remote: %s" % (target, local_name, remote_name)) - return information, is_current + return information, is_current diff --git a/src/octoprint/plugins/softwareupdate/version_checks/git_commit.py b/src/octoprint/plugins/softwareupdate/version_checks/git_commit.py index 10875ef2b..2d19a0019 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/git_commit.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/git_commit.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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" @@ -13,75 +13,95 @@ import logging from ..exceptions import ConfigurationInvalid + def _get_git_executables(): - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - return GITS + GITS = ["git"] + if sys.platform == "win32": + GITS = ["git.cmd", "git.exe"] + return GITS def _git(args, cwd, hide_stderr=False): - commands = _get_git_executables() + commands = _get_git_executables() - for c in commands: - try: - p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None)) - break - except EnvironmentError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - return None, None - else: - return None, None + for c in commands: + try: + p = subprocess.Popen( + [c] + args, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr else None), + ) + break + except EnvironmentError: + e = sys.exc_info()[1] + if e.errno == errno.ENOENT: + continue + return None, None + else: + return None, None - stdout = p.communicate()[0].strip() - if sys.version >= '3': - stdout = stdout.decode() + stdout = p.communicate()[0].strip() + if sys.version >= "3": + stdout = stdout.decode() - if p.returncode != 0: - return p.returncode, None + if p.returncode != 0: + return p.returncode, None - return p.returncode, stdout + return p.returncode, stdout def get_latest(target, check, online=True): - checkout_folder = check.get("checkout_folder") - if checkout_folder is None: - raise ConfigurationInvalid("Update configuration for {} of type git_commit needs checkout_folder set and not None".format(target)) + checkout_folder = check.get("checkout_folder") + if checkout_folder is None: + raise ConfigurationInvalid( + "Update configuration for {} of type git_commit needs checkout_folder set and not None".format( + target + ) + ) - returncode, local_commit = _git(["rev-parse", "@{0}"], checkout_folder) - if returncode != 0: - return None, True + returncode, local_commit = _git(["rev-parse", "@{0}"], checkout_folder) + if returncode != 0: + return None, True - information = {"local": {"name": "Commit %s" % local_commit, "value": local_commit}, - "remote": {"name": "?", "value": "?"}, - "needs_online": not check.get("offline", False)} - if not online and information["needs_online"]: - return information, True + information = { + "local": {"name": "Commit %s" % local_commit, "value": local_commit}, + "remote": {"name": "?", "value": "?"}, + "needs_online": not check.get("offline", False), + } + if not online and information["needs_online"]: + return information, True - returncode, _ = _git(["fetch"], checkout_folder) - if returncode != 0: - return information, True + returncode, _ = _git(["fetch"], checkout_folder) + if returncode != 0: + return information, True - returncode, remote_commit = _git(["rev-parse", "@{u}"], checkout_folder) - if returncode != 0: - return information, True + returncode, remote_commit = _git(["rev-parse", "@{u}"], checkout_folder) + if returncode != 0: + return information, True - returncode, base = _git(["merge-base", "@{0}", "@{u}"], checkout_folder) - if returncode != 0: - return information, True + returncode, base = _git(["merge-base", "@{0}", "@{u}"], checkout_folder) + if returncode != 0: + return information, True - if local_commit == remote_commit or remote_commit == base: - information["remote"] = {"name": "Commit %s" % local_commit, "value": local_commit} - is_current = True - else: - information["remote"] = {"name": "Commit %s" % remote_commit, "value": remote_commit} - is_current = local_commit == remote_commit + if local_commit == remote_commit or remote_commit == base: + information["remote"] = { + "name": "Commit %s" % local_commit, + "value": local_commit, + } + is_current = True + else: + information["remote"] = { + "name": "Commit %s" % remote_commit, + "value": remote_commit, + } + is_current = local_commit == remote_commit - logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.git_commit") - logger.debug("Target: %s, local: %s, remote: %s" % (target, local_commit, remote_commit)) + logger = logging.getLogger( + "octoprint.plugins.softwareupdate.version_checks.git_commit" + ) + logger.debug( + "Target: %s, local: %s, remote: %s" % (target, local_commit, remote_commit) + ) - return information, is_current + return information, is_current diff --git a/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py b/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py index b9e4f3a70..6d6f62287 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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 requests @@ -10,57 +10,80 @@ import logging BRANCH_HEAD_URL = "https://api.github.com/repos/{user}/{repo}/git/refs/heads/{branch}" -logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.github_commit") +logger = logging.getLogger( + "octoprint.plugins.softwareupdate.version_checks.github_commit" +) + def _get_latest_commit(user, repo, branch): - from ..exceptions import NetworkError + from ..exceptions import NetworkError - try: - r = requests.get(BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch), timeout=(3.05, 30)) - except requests.ConnectionError as exc: - raise NetworkError(cause=exc) + try: + r = requests.get( + BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch), + timeout=(3.05, 30), + ) + except requests.ConnectionError as exc: + raise NetworkError(cause=exc) - from . import log_github_ratelimit - log_github_ratelimit(logger, r) + from . import log_github_ratelimit - if not r.status_code == requests.codes.ok: - return None + log_github_ratelimit(logger, r) - reference = r.json() - if not "object" in reference or not "sha" in reference["object"]: - return None + if not r.status_code == requests.codes.ok: + return None - return reference["object"]["sha"] + reference = r.json() + if not "object" in reference or not "sha" in reference["object"]: + return None + + return reference["object"]["sha"] def get_latest(target, check, online=True): - from ..exceptions import ConfigurationInvalid + from ..exceptions import ConfigurationInvalid - user = check.get("user") - repo = check.get("repo") + user = check.get("user") + repo = check.get("repo") - if user is None or repo is None: - raise ConfigurationInvalid("Update configuration for {} of type github_commit needs user and repo set and not None".format(target)) + if user is None or repo is None: + raise ConfigurationInvalid( + "Update configuration for {} of type github_commit needs user and repo set and not None".format( + target + ) + ) - branch = "master" - if "branch" in check and check["branch"] is not None: - branch = check["branch"] + branch = "master" + if "branch" in check and check["branch"] is not None: + branch = check["branch"] - current = check.get("current") + current = check.get("current") - information = {"local": {"name": "Commit {commit}".format(commit=current if current is not None else "?"), "value": current}, - "remote": {"name": "?", "value": "?"}, - "needs_online": not check.get("offline", False)} - if not online and information["needs_online"]: - return information, True + information = { + "local": { + "name": "Commit {commit}".format( + commit=current if current is not None else "?" + ), + "value": current, + }, + "remote": {"name": "?", "value": "?"}, + "needs_online": not check.get("offline", False), + } + if not online and information["needs_online"]: + return information, True - remote_commit = _get_latest_commit(check["user"], check["repo"], branch) - remote_name = "Commit {commit}".format(commit=remote_commit) if remote_commit is not None else "-" + remote_commit = _get_latest_commit(check["user"], check["repo"], branch) + remote_name = ( + "Commit {commit}".format(commit=remote_commit) + if remote_commit is not None + else "-" + ) - information["remote"] = {"name": remote_name, "value": remote_commit} - is_current = (current is not None and current == remote_commit) or remote_commit is None + information["remote"] = {"name": remote_name, "value": remote_commit} + is_current = ( + current is not None and current == remote_commit + ) or remote_commit is None - logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_commit)) - - return information, is_current + logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_commit)) + return information, is_current diff --git a/src/octoprint/plugins/softwareupdate/version_checks/github_release.py b/src/octoprint/plugins/softwareupdate/version_checks/github_release.py index 1fbf5d31a..0f30a55c0 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/github_release.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/github_release.py @@ -1,9 +1,10 @@ # -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function + # MO unicode_literals because fixing all the doctests is too annoying :-P __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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 requests @@ -14,289 +15,332 @@ from octoprint.util.version import get_comparable_version RELEASE_URL = "https://api.github.com/repos/{user}/{repo}/releases" -logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.github_release") - -def _filter_out_latest(releases, - sort_key=None, - include_prerelease=False, - commitish=None): - """ - Filters out the newest of all matching releases. - - Tests: - - >>> release_1_2_15 = dict(name="1.2.15", tag_name="1.2.15", html_url="some_url", published_at="2016-07-29T19:53:29Z", prerelease=False, draft=False, target_commitish="prerelease") - >>> release_1_2_16rc1 = dict(name="1.2.16rc1", tag_name="1.2.16rc1", html_url="some_url", published_at="2016-08-29T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance") - >>> release_1_2_16rc2 = dict(name="1.2.16rc2", tag_name="1.2.16rc2", html_url="some_url", published_at="2016-08-30T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance") - >>> release_1_2_17rc1 = dict(name="1.2.17rc1", tag_name="1.2.17rc1", html_url="some_url", published_at="2016-08-31T12:00:00Z", prerelease=True, draft=True, target_commitish="rc/maintenance") - >>> release_1_3_0rc1 = dict(name="1.3.0rc1", tag_name="1.3.0rc1", html_url="some_url", published_at="2016-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/devel") - >>> release_1_3_5rc1 = dict(name="1.3.5rc1", tag_name="1.3.5rc1", html_url="some_url", published_at="2017-06-14T10:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance") - >>> release_1_2_18 = dict(name="1.2.18", tag_name="1.2.18", html_url="some_url", published_at="2016-12-13T12:00:00Z", prerelease=False, draft=False, target_commitish="master") - >>> release_1_4_0rc1 = dict(name="1.4.0rc1", tag_name="1.4.0rc1", html_url="some_url", published_at="2017-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/future") - >>> release_1_4_0rc1_devel = dict(name="1.4.0rc1", tag_name="1.4.0rc1", html_url="some_url", published_at="2017-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/devel") - >>> releases = [release_1_2_15, release_1_2_16rc1, release_1_2_16rc2, release_1_2_17rc1, release_1_3_0rc1, release_1_4_0rc1] - >>> _filter_out_latest(releases, include_prerelease=False, commitish=None) - ('1.2.15', '1.2.15', 'some_url') - >>> _filter_out_latest(releases, include_prerelease=True, commitish=["rc/maintenance"]) - ('1.2.16rc2', '1.2.16rc2', 'some_url') - >>> _filter_out_latest(releases, include_prerelease=True, commitish=["rc/devel"]) - ('1.3.0rc1', '1.3.0rc1', 'some_url') - >>> _filter_out_latest(releases, include_prerelease=True, commitish=None) - ('1.4.0rc1', '1.4.0rc1', 'some_url') - >>> _filter_out_latest(releases, include_prerelease=True, commitish=["rc/doesntexist"]) - ('1.2.15', '1.2.15', 'some_url') - >>> _filter_out_latest([release_1_2_17rc1]) - (None, None, None) - >>> _filter_out_latest([release_1_2_16rc1, release_1_2_16rc2]) - (None, None, None) - - >>> comparable_factory = _get_comparable_factory("python", force_base=True) - >>> sort_key = lambda release: comparable_factory(_get_sanitized_version(release["tag_name"])) - >>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=False, commitish=None, sort_key=sort_key) - ('1.2.18', '1.2.18', 'some_url') - >>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, commitish=["rc/maintenance"], sort_key=sort_key) - ('1.2.18', '1.2.18', 'some_url') - >>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, commitish=["rc/devel"], sort_key=sort_key) - ('1.3.0rc1', '1.3.0rc1', 'some_url') - - >>> _filter_out_latest([release_1_2_18, release_1_3_5rc1], include_prerelease=True, commitish=["rc/maintenance"]) - ('1.3.5rc1', '1.3.5rc1', 'some_url') - >>> _filter_out_latest([release_1_2_18, release_1_3_5rc1], include_prerelease=True, commitish=["rc/maintenance", "rc/devel"]) - ('1.3.5rc1', '1.3.5rc1', 'some_url') - >>> _filter_out_latest([release_1_2_18, release_1_3_5rc1, release_1_4_0rc1_devel], include_prerelease=True, commitish=["rc/maintenance"]) - ('1.3.5rc1', '1.3.5rc1', 'some_url') - >>> _filter_out_latest([release_1_2_18, release_1_3_5rc1, release_1_4_0rc1_devel], include_prerelease=True, commitish=["rc/maintenance", "rc/devel"]) - ('1.4.0rc1', '1.4.0rc1', 'some_url') - """ - - nothing = None, None, None - - if sort_key is None: - sort_key = lambda release: sv(release.get("published_at", None)) - - # filter out prereleases and drafts - filter_function = lambda rel: not rel["prerelease"] and not rel["draft"] - if include_prerelease: - if commitish: - filter_function = lambda rel: not rel["draft"] and \ - (not rel["prerelease"] or rel["target_commitish"] in commitish) - else: - filter_function = lambda rel: not rel["draft"] - - releases = list(filter(filter_function, releases)) - if not releases: - return nothing - - # sort by sort_key - releases = sorted(releases, key=sort_key) - - # latest release = last in list - latest = releases[-1] - - return latest["name"], latest["tag_name"], latest.get("html_url", None) +logger = logging.getLogger( + "octoprint.plugins.softwareupdate.version_checks.github_release" +) -def _get_latest_release(user, repo, compare_type, - include_prerelease=False, - commitish=None, - force_base=True): - from ..exceptions import NetworkError +def _filter_out_latest(releases, sort_key=None, include_prerelease=False, commitish=None): + """ + Filters out the newest of all matching releases. - nothing = None, None, None + Tests: - try: - r = requests.get(RELEASE_URL.format(user=user, repo=repo), timeout=(3.05, 30)) - except requests.ConnectionError as exc: - raise NetworkError(cause=exc) + >>> release_1_2_15 = dict(name="1.2.15", tag_name="1.2.15", html_url="some_url", published_at="2016-07-29T19:53:29Z", prerelease=False, draft=False, target_commitish="prerelease") + >>> release_1_2_16rc1 = dict(name="1.2.16rc1", tag_name="1.2.16rc1", html_url="some_url", published_at="2016-08-29T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance") + >>> release_1_2_16rc2 = dict(name="1.2.16rc2", tag_name="1.2.16rc2", html_url="some_url", published_at="2016-08-30T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance") + >>> release_1_2_17rc1 = dict(name="1.2.17rc1", tag_name="1.2.17rc1", html_url="some_url", published_at="2016-08-31T12:00:00Z", prerelease=True, draft=True, target_commitish="rc/maintenance") + >>> release_1_3_0rc1 = dict(name="1.3.0rc1", tag_name="1.3.0rc1", html_url="some_url", published_at="2016-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/devel") + >>> release_1_3_5rc1 = dict(name="1.3.5rc1", tag_name="1.3.5rc1", html_url="some_url", published_at="2017-06-14T10:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance") + >>> release_1_2_18 = dict(name="1.2.18", tag_name="1.2.18", html_url="some_url", published_at="2016-12-13T12:00:00Z", prerelease=False, draft=False, target_commitish="master") + >>> release_1_4_0rc1 = dict(name="1.4.0rc1", tag_name="1.4.0rc1", html_url="some_url", published_at="2017-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/future") + >>> release_1_4_0rc1_devel = dict(name="1.4.0rc1", tag_name="1.4.0rc1", html_url="some_url", published_at="2017-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/devel") + >>> releases = [release_1_2_15, release_1_2_16rc1, release_1_2_16rc2, release_1_2_17rc1, release_1_3_0rc1, release_1_4_0rc1] + >>> _filter_out_latest(releases, include_prerelease=False, commitish=None) + ('1.2.15', '1.2.15', 'some_url') + >>> _filter_out_latest(releases, include_prerelease=True, commitish=["rc/maintenance"]) + ('1.2.16rc2', '1.2.16rc2', 'some_url') + >>> _filter_out_latest(releases, include_prerelease=True, commitish=["rc/devel"]) + ('1.3.0rc1', '1.3.0rc1', 'some_url') + >>> _filter_out_latest(releases, include_prerelease=True, commitish=None) + ('1.4.0rc1', '1.4.0rc1', 'some_url') + >>> _filter_out_latest(releases, include_prerelease=True, commitish=["rc/doesntexist"]) + ('1.2.15', '1.2.15', 'some_url') + >>> _filter_out_latest([release_1_2_17rc1]) + (None, None, None) + >>> _filter_out_latest([release_1_2_16rc1, release_1_2_16rc2]) + (None, None, None) - from . import log_github_ratelimit - log_github_ratelimit(logger, r) + >>> comparable_factory = _get_comparable_factory("python", force_base=True) + >>> sort_key = lambda release: comparable_factory(_get_sanitized_version(release["tag_name"])) + >>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=False, commitish=None, sort_key=sort_key) + ('1.2.18', '1.2.18', 'some_url') + >>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, commitish=["rc/maintenance"], sort_key=sort_key) + ('1.2.18', '1.2.18', 'some_url') + >>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, commitish=["rc/devel"], sort_key=sort_key) + ('1.3.0rc1', '1.3.0rc1', 'some_url') - if not r.status_code == requests.codes.ok: - return nothing + >>> _filter_out_latest([release_1_2_18, release_1_3_5rc1], include_prerelease=True, commitish=["rc/maintenance"]) + ('1.3.5rc1', '1.3.5rc1', 'some_url') + >>> _filter_out_latest([release_1_2_18, release_1_3_5rc1], include_prerelease=True, commitish=["rc/maintenance", "rc/devel"]) + ('1.3.5rc1', '1.3.5rc1', 'some_url') + >>> _filter_out_latest([release_1_2_18, release_1_3_5rc1, release_1_4_0rc1_devel], include_prerelease=True, commitish=["rc/maintenance"]) + ('1.3.5rc1', '1.3.5rc1', 'some_url') + >>> _filter_out_latest([release_1_2_18, release_1_3_5rc1, release_1_4_0rc1_devel], include_prerelease=True, commitish=["rc/maintenance", "rc/devel"]) + ('1.4.0rc1', '1.4.0rc1', 'some_url') + """ - releases = r.json() + nothing = None, None, None - # sanitize - required_fields = {"name", "tag_name", "html_url", "draft", "prerelease", "published_at", "target_commitish"} - releases = list(filter(lambda rel: set(rel.keys()) & required_fields == required_fields, - releases)) + if sort_key is None: + sort_key = lambda release: sv(release.get("published_at", None)) - comparable_factory = _get_comparable_factory(compare_type, - force_base=force_base) - sort_key = lambda release: comparable_factory(_get_sanitized_version(release["tag_name"])) + # filter out prereleases and drafts + filter_function = lambda rel: not rel["prerelease"] and not rel["draft"] + if include_prerelease: + if commitish: + filter_function = lambda rel: not rel["draft"] and ( + not rel["prerelease"] or rel["target_commitish"] in commitish + ) + else: + filter_function = lambda rel: not rel["draft"] - return _filter_out_latest(releases, - sort_key=sort_key, - include_prerelease=include_prerelease, - commitish=commitish) + releases = list(filter(filter_function, releases)) + if not releases: + return nothing + + # sort by sort_key + releases = sorted(releases, key=sort_key) + + # latest release = last in list + latest = releases[-1] + + return latest["name"], latest["tag_name"], latest.get("html_url", None) + + +def _get_latest_release( + user, repo, compare_type, include_prerelease=False, commitish=None, force_base=True +): + from ..exceptions import NetworkError + + nothing = None, None, None + + try: + r = requests.get(RELEASE_URL.format(user=user, repo=repo), timeout=(3.05, 30)) + except requests.ConnectionError as exc: + raise NetworkError(cause=exc) + + from . import log_github_ratelimit + + log_github_ratelimit(logger, r) + + if not r.status_code == requests.codes.ok: + return nothing + + releases = r.json() + + # sanitize + required_fields = { + "name", + "tag_name", + "html_url", + "draft", + "prerelease", + "published_at", + "target_commitish", + } + releases = list( + filter(lambda rel: set(rel.keys()) & required_fields == required_fields, releases) + ) + + comparable_factory = _get_comparable_factory(compare_type, force_base=force_base) + sort_key = lambda release: comparable_factory( + _get_sanitized_version(release["tag_name"]) + ) + + return _filter_out_latest( + releases, + sort_key=sort_key, + include_prerelease=include_prerelease, + commitish=commitish, + ) def _get_sanitized_version(version_string): - """ - Removes "-..." prefix from version strings. + """ + Removes "-..." prefix from version strings. - Tests: - >>> _get_sanitized_version(None) - >>> _get_sanitized_version("1.2.15") - '1.2.15' - >>> _get_sanitized_version("1.2.15-dev12") - '1.2.15' - """ + Tests: + >>> _get_sanitized_version(None) + >>> _get_sanitized_version("1.2.15") + '1.2.15' + >>> _get_sanitized_version("1.2.15-dev12") + '1.2.15' + """ - if version_string is not None and "-" in version_string: - version_string = version_string[:version_string.find("-")] - return version_string + if version_string is not None and "-" in version_string: + version_string = version_string[: version_string.find("-")] + return version_string def _get_base_from_version_tuple(version_tuple): - """ - Reduces version tuple to base version. + """ + Reduces version tuple to base version. - Tests: + Tests: - >>> _get_base_from_version_tuple(("1", "2", "15")) - ('1', '2', '15') - >>> _get_base_from_version_tuple(("1", "2", "15", "*", "dev12")) - ('1', '2', '15') - """ + >>> _get_base_from_version_tuple(("1", "2", "15")) + ('1', '2', '15') + >>> _get_base_from_version_tuple(("1", "2", "15", "*", "dev12")) + ('1', '2', '15') + """ - base_version = [] - for part in version_tuple: - if part.startswith("*"): - break - base_version.append(part) - return tuple(base_version) + base_version = [] + for part in version_tuple: + if part.startswith("*"): + break + base_version.append(part) + return tuple(base_version) def _get_comparable_version_semantic(version_string, force_base=True): - import semantic_version + import semantic_version - version = semantic_version.Version.coerce(version_string, partial=False) + version = semantic_version.Version.coerce(version_string, partial=False) - if force_base: - version_string = "{}.{}.{}".format(version.major, version.minor, version.patch) - version = semantic_version.Version.coerce(version_string, partial=False) + if force_base: + version_string = "{}.{}.{}".format(version.major, version.minor, version.patch) + version = semantic_version.Version.coerce(version_string, partial=False) - return version + return version def _get_sanitized_compare_type(compare_type, custom=None): - if not compare_type in ("python", "python_unequal", - "semantic", "semantic_unequal", - "unequal", "custom") or compare_type == "custom" and custom is None: - compare_type = "python" - return compare_type + if ( + not compare_type + in ( + "python", + "python_unequal", + "semantic", + "semantic_unequal", + "unequal", + "custom", + ) + or compare_type == "custom" + and custom is None + ): + compare_type = "python" + return compare_type def _get_comparable_factory(compare_type, force_base=True): - if compare_type in ("python", "python_unequal"): - return lambda version: get_comparable_version(version, base=force_base) - elif compare_type in ("semantic", "semantic_unequal"): - return lambda version: _get_comparable_version_semantic(version, force_base=force_base) - else: - return lambda version: version + if compare_type in ("python", "python_unequal"): + return lambda version: get_comparable_version(version, base=force_base) + elif compare_type in ("semantic", "semantic_unequal"): + return lambda version: _get_comparable_version_semantic( + version, force_base=force_base + ) + else: + return lambda version: version def _get_comparator(compare_type, custom=None): - if compare_type in ("python", "semantic"): - return lambda a, b: a >= b - elif compare_type == "custom": - return custom - else: - return lambda a, b: a == b + if compare_type in ("python", "semantic"): + return lambda a, b: a >= b + elif compare_type == "custom": + return custom + else: + return lambda a, b: a == b def _is_current(release_information, compare_type, custom=None, force_base=True): - """ - Checks if the provided release information indicates the version being the most current one. + """ + Checks if the provided release information indicates the version being the most current one. - Tests: + Tests: - >>> _is_current(dict(remote=dict(value=None)), "python") - True - >>> _is_current(dict(local=dict(value="1.2.15"), remote=dict(value="1.2.16")), "python") - False - >>> _is_current(dict(local=dict(value="1.2.16dev1"), remote=dict(value="1.2.16dev2")), "python") - True - >>> _is_current(dict(local=dict(value="1.2.16dev1"), remote=dict(value="1.2.16dev2")), "python", force_base=False) - False - >>> _is_current(dict(local=dict(value="1.2.16dev3"), remote=dict(value="1.2.16dev2")), "python", force_base=False) - True - >>> _is_current(dict(local=dict(value="1.2.16dev3"), remote=dict(value="1.2.16dev2")), "python_unequal", force_base=False) - False - >>> _is_current(dict(local=dict(value="1.3.0.post1+g1014712"), remote=dict(value="1.3.0")), "python") - True + >>> _is_current(dict(remote=dict(value=None)), "python") + True + >>> _is_current(dict(local=dict(value="1.2.15"), remote=dict(value="1.2.16")), "python") + False + >>> _is_current(dict(local=dict(value="1.2.16dev1"), remote=dict(value="1.2.16dev2")), "python") + True + >>> _is_current(dict(local=dict(value="1.2.16dev1"), remote=dict(value="1.2.16dev2")), "python", force_base=False) + False + >>> _is_current(dict(local=dict(value="1.2.16dev3"), remote=dict(value="1.2.16dev2")), "python", force_base=False) + True + >>> _is_current(dict(local=dict(value="1.2.16dev3"), remote=dict(value="1.2.16dev2")), "python_unequal", force_base=False) + False + >>> _is_current(dict(local=dict(value="1.3.0.post1+g1014712"), remote=dict(value="1.3.0")), "python") + True - """ + """ - if release_information["remote"]["value"] is None: - return True + if release_information["remote"]["value"] is None: + return True - compare_type = _get_sanitized_compare_type(compare_type, custom=custom) - comparable_factory = _get_comparable_factory(compare_type, force_base=force_base) - comparator = _get_comparator(compare_type, custom=custom) + compare_type = _get_sanitized_compare_type(compare_type, custom=custom) + comparable_factory = _get_comparable_factory(compare_type, force_base=force_base) + comparator = _get_comparator(compare_type, custom=custom) - sanitized_local = _get_sanitized_version(release_information["local"]["value"]) - sanitized_remote = _get_sanitized_version(release_information["remote"]["value"]) + sanitized_local = _get_sanitized_version(release_information["local"]["value"]) + sanitized_remote = _get_sanitized_version(release_information["remote"]["value"]) - try: - return comparator(comparable_factory(sanitized_local), - comparable_factory(sanitized_remote)) - except Exception: - logger.exception("Could not check if version is current due to an error, assuming it is") - return True + try: + return comparator( + comparable_factory(sanitized_local), comparable_factory(sanitized_remote) + ) + except Exception: + logger.exception( + "Could not check if version is current due to an error, assuming it is" + ) + return True def get_latest(target, check, custom_compare=None, online=True): - from ..exceptions import ConfigurationInvalid + from ..exceptions import ConfigurationInvalid - user = check.get("user", None) - repo = check.get("repo", None) - current = check.get("current", None) - if user is None or repo is None or current is None: - raise ConfigurationInvalid("Update configuration for {} of type github_release needs all of user, repo and current set and not None".format(target)) + user = check.get("user", None) + repo = check.get("repo", None) + current = check.get("current", None) + if user is None or repo is None or current is None: + raise ConfigurationInvalid( + "Update configuration for {} of type github_release needs all of user, repo and current set and not None".format( + target + ) + ) - information ={"local": {"name": current, "value": current}, - "remote": {"name": "?", "value": "?", "release_notes": None}, - "needs_online": not check.get("offline", False)} - if not online and information["needs_online"]: - return information, True + information = { + "local": {"name": current, "value": current}, + "remote": {"name": "?", "value": "?", "release_notes": None}, + "needs_online": not check.get("offline", False), + } + if not online and information["needs_online"]: + return information, True - include_prerelease = check.get("prerelease", False) - prerelease_channel = check.get("prerelease_channel", None) + include_prerelease = check.get("prerelease", False) + prerelease_channel = check.get("prerelease_channel", None) - # determine valid "commitish" values in case we track prereleases - commitish = None - if include_prerelease and prerelease_channel: - prerelease_branches = check.get("prerelease_branches", None) - if prerelease_branches: - # fetch valid commitish list from configured prerelease_branches for selected channel - commitishes = dict((x["branch"], x.get("commitish", [x["branch"]])) for x in prerelease_branches) - commitish = commitishes.get(prerelease_channel, [prerelease_channel]) + # determine valid "commitish" values in case we track prereleases + commitish = None + if include_prerelease and prerelease_channel: + prerelease_branches = check.get("prerelease_branches", None) + if prerelease_branches: + # fetch valid commitish list from configured prerelease_branches for selected channel + commitishes = dict( + (x["branch"], x.get("commitish", [x["branch"]])) + for x in prerelease_branches + ) + commitish = commitishes.get(prerelease_channel, [prerelease_channel]) - force_base = check.get("force_base", False) - compare_type = _get_sanitized_compare_type(check.get("release_compare", "python"), - custom=custom_compare) + force_base = check.get("force_base", False) + compare_type = _get_sanitized_compare_type( + check.get("release_compare", "python"), custom=custom_compare + ) - remote_name, remote_tag, release_notes = _get_latest_release(check["user"], - check["repo"], - compare_type, - include_prerelease=include_prerelease, - commitish=commitish, - force_base=force_base) + remote_name, remote_tag, release_notes = _get_latest_release( + check["user"], + check["repo"], + compare_type, + include_prerelease=include_prerelease, + commitish=commitish, + force_base=force_base, + ) - if not remote_name: - if remote_tag: - remote_name = remote_tag - else: - remote_name = "-" + if not remote_name: + if remote_tag: + remote_name = remote_tag + else: + remote_name = "-" - information["remote"] = {"name": remote_name, "value": remote_tag, "release_notes": release_notes} + information["remote"] = { + "name": remote_name, + "value": remote_tag, + "release_notes": release_notes, + } - logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_tag)) + logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_tag)) - return information, _is_current(information, - compare_type, - custom=custom_compare, - force_base=force_base) + return information, _is_current( + information, compare_type, custom=custom_compare, force_base=force_base + ) diff --git a/src/octoprint/plugins/softwareupdate/version_checks/httpheader.py b/src/octoprint/plugins/softwareupdate/version_checks/httpheader.py index 7a228310e..92ea45634 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/httpheader.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/httpheader.py @@ -1,7 +1,7 @@ # -*- 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License" import requests @@ -11,31 +11,46 @@ from ..exceptions import ConfigurationInvalid, NetworkError, CannotCheckOffline logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.etag") + def get_latest(target, check, online=True): - if not online: - raise CannotCheckOffline() + if not online: + raise CannotCheckOffline() - url = check.get("header_url", check.get("url")) - header = check.get("header_name") + url = check.get("header_url", check.get("url")) + header = check.get("header_name") - if url is None or header is None: - raise ConfigurationInvalid("HTTP header version check needs header_url or url and header_name set") + if url is None or header is None: + raise ConfigurationInvalid( + "HTTP header version check needs header_url or url and header_name set" + ) - current = check.get("current") - method = check.get("header_method", "head") - prefix = check.get("header_prefix", header) - if prefix: - prefix = "{} ".format(prefix) + current = check.get("current") + method = check.get("header_method", "head") + prefix = check.get("header_prefix", header) + if prefix: + prefix = "{} ".format(prefix) - try: - with requests.request(method, url) as r: - latest = r.headers.get(header) - except Exception as exc: - raise NetworkError(cause=exc) + try: + with requests.request(method, url) as r: + latest = r.headers.get(header) + except Exception as exc: + raise NetworkError(cause=exc) - information = {"local": {"name": "{}{}".format(prefix, current if current else "-"), "value": current}, - "remote": {"name": "{}{}".format(prefix, latest if latest else "-"), "value": latest}} + information = { + "local": { + "name": "{}{}".format(prefix, current if current else "-"), + "value": current, + }, + "remote": { + "name": "{}{}".format(prefix, latest if latest else "-"), + "value": latest, + }, + } - logger.debug("Target: {}, local: {}, remote: {}".format(target, information["local"]["name"], information["remote"]["name"])) + logger.debug( + "Target: {}, local: {}, remote: {}".format( + target, information["local"]["name"], information["remote"]["name"] + ) + ) - return information, current is None or current == latest or latest is None + return information, current is None or current == latest or latest is None diff --git a/src/octoprint/plugins/softwareupdate/version_checks/jsondata.py b/src/octoprint/plugins/softwareupdate/version_checks/jsondata.py index f6473174d..622a6230e 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/jsondata.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/jsondata.py @@ -1,7 +1,7 @@ # -*- 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License" import requests @@ -11,27 +11,34 @@ from ..exceptions import ConfigurationInvalid, NetworkError, CannotCheckOffline logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.jsondata") + def get_latest(target, check, online=True): - if not online: - raise CannotCheckOffline() + if not online: + raise CannotCheckOffline() - url = check.get("jsondata") - current = check.get("current") + url = check.get("jsondata") + current = check.get("current") - if url is None: - raise ConfigurationInvalid("jsondata version check needs jsondata set") + if url is None: + raise ConfigurationInvalid("jsondata version check needs jsondata set") - try: - with requests.get(url) as r: - data = r.json() - except Exception as exc: - raise NetworkError(cause=exc) + try: + with requests.get(url) as r: + data = r.json() + except Exception as exc: + raise NetworkError(cause=exc) - latest = data.get("version") + latest = data.get("version") - information = {"local": {"name": current if current else "-", "value": current}, - "remote": {"name": latest if latest else "-", "value": latest}} + information = { + "local": {"name": current if current else "-", "value": current}, + "remote": {"name": latest if latest else "-", "value": latest}, + } - logger.debug("Target: {}, local: {}, remote: {}".format(target, information["local"]["name"], information["remote"]["name"])) + logger.debug( + "Target: {}, local: {}, remote: {}".format( + target, information["local"]["name"], information["remote"]["name"] + ) + ) - return information, current is None or current == latest or latest is None + return information, current is None or current == latest or latest is None diff --git a/src/octoprint/plugins/softwareupdate/version_checks/never_current.py b/src/octoprint/plugins/softwareupdate/version_checks/never_current.py index 16cdb694c..63043c286 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/never_current.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/never_current.py @@ -1,14 +1,17 @@ # -*- 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" + def get_latest(target, check, online=True): - local_version = check.get("local_version", "1.0.0") - remote_version = check.get("remote_version", "1.0.1") + local_version = check.get("local_version", "1.0.0") + remote_version = check.get("remote_version", "1.0.1") - information = {"local": {"name": local_version, "value": local_version}, - "remote": {"name": remote_version, "value": remote_version}} + information = { + "local": {"name": local_version, "value": local_version}, + "remote": {"name": remote_version, "value": remote_version}, + } - return information, False + return information, False diff --git a/src/octoprint/plugins/softwareupdate/version_checks/pypi_release.py b/src/octoprint/plugins/softwareupdate/version_checks/pypi_release.py index 3f3cb833a..8e92d7bbd 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/pypi_release.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/pypi_release.py @@ -1,7 +1,7 @@ # 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License" import logging @@ -9,100 +9,122 @@ import pkg_resources import requests from octoprint.util import to_native_str -from octoprint.util.version import is_python_compatible, get_comparable_version, is_prerelease +from octoprint.util.version import ( + is_python_compatible, + get_comparable_version, + is_prerelease, +) INFO_URL = "https://pypi.org/pypi/{package}/json" logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.pypi_release") + def _filter_out_latest(releases, include_prerelease=False, python_version=None): - """ - Filters out the newest of all matching releases. + """ + Filters out the newest of all matching releases. - Tests: + Tests: - >>> requires_py2 = ">=2.7.9,<3" - >>> requires_py23 = ">=2.7.9, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, <4" - >>> requires_py3 = ">=3.6, <4" - >>> releases = {"1.3.12": [dict(requires_python=requires_py2, upload_time_iso_8601="2019-10-22T10:06:03.190293Z")], "1.4.0rc1": [dict(requires_python=requires_py23, upload_time_iso_8601="2019-11-22T10:06:03.190293Z")], "2.0.0rc1": [dict(requires_python=requires_py3, upload_time_iso_8601="2020-10-22T10:06:03.190293Z")]} - >>> to_native_str(_filter_out_latest(releases, python_version="2.7.9")) - '1.3.12' - >>> to_native_str(_filter_out_latest(releases, include_prerelease=True, python_version="2.7.9")) - '1.4.0rc1' - >>> to_native_str(_filter_out_latest(releases, include_prerelease=True, python_version="3.6.0")) - '2.0.0rc1' - >>> to_native_str(_filter_out_latest(releases, python_version="3.6.0")) - """ - releases = [{"version": k, "data": v[0]} for k, v in releases.items()] + >>> requires_py2 = ">=2.7.9,<3" + >>> requires_py23 = ">=2.7.9, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, <4" + >>> requires_py3 = ">=3.6, <4" + >>> releases = {"1.3.12": [dict(requires_python=requires_py2, upload_time_iso_8601="2019-10-22T10:06:03.190293Z")], "1.4.0rc1": [dict(requires_python=requires_py23, upload_time_iso_8601="2019-11-22T10:06:03.190293Z")], "2.0.0rc1": [dict(requires_python=requires_py3, upload_time_iso_8601="2020-10-22T10:06:03.190293Z")]} + >>> to_native_str(_filter_out_latest(releases, python_version="2.7.9")) + '1.3.12' + >>> to_native_str(_filter_out_latest(releases, include_prerelease=True, python_version="2.7.9")) + '1.4.0rc1' + >>> to_native_str(_filter_out_latest(releases, include_prerelease=True, python_version="3.6.0")) + '2.0.0rc1' + >>> to_native_str(_filter_out_latest(releases, python_version="3.6.0")) + """ + releases = [{"version": k, "data": v[0]} for k, v in releases.items()] - # filter out prereleases and versions incompatible to our python - filter_function = lambda release: not is_prerelease(release["version"]) and is_python_compatible(release["data"].get("requires_python", ""), python_version=python_version) - if include_prerelease: - filter_function = lambda release: is_python_compatible(release["data"].get("requires_python", ""), python_version=python_version) + # filter out prereleases and versions incompatible to our python + filter_function = lambda release: not is_prerelease( + release["version"] + ) and is_python_compatible( + release["data"].get("requires_python", ""), python_version=python_version + ) + if include_prerelease: + filter_function = lambda release: is_python_compatible( + release["data"].get("requires_python", ""), python_version=python_version + ) - releases = list(filter(filter_function, releases)) - if not releases: - return None + releases = list(filter(filter_function, releases)) + if not releases: + return None - # sort by upload date - releases = sorted(releases, key=lambda release: release["data"].get("upload_time_iso_8601", "")) + # sort by upload date + releases = sorted( + releases, key=lambda release: release["data"].get("upload_time_iso_8601", "") + ) - # latest release = last in list - latest = releases[-1] + # latest release = last in list + latest = releases[-1] + + return latest["version"] - return latest["version"] def _get_latest_release(package, include_prerelease): - from ..exceptions import NetworkError + from ..exceptions import NetworkError - try: - r = requests.get(INFO_URL.format(package=package), timeout=(3.05, 30)) - except requests.ConnectionError as exc: - raise NetworkError(cause=exc) + try: + r = requests.get(INFO_URL.format(package=package), timeout=(3.05, 30)) + except requests.ConnectionError as exc: + raise NetworkError(cause=exc) - if not r.status_code == requests.codes.ok: - return None + if not r.status_code == requests.codes.ok: + return None - data = r.json() - if not "info" in data or not "version" in data["info"]: - return None + data = r.json() + if not "info" in data or not "version" in data["info"]: + return None - requires_python = data["info"].get("requires_python") - if requires_python and not is_python_compatible(requires_python): - return None + requires_python = data["info"].get("requires_python") + if requires_python and not is_python_compatible(requires_python): + return None + + return _filter_out_latest(data["releases"], include_prerelease=include_prerelease) - return _filter_out_latest(data["releases"], - include_prerelease=include_prerelease) def _is_current(release_information): - if release_information["remote"]["value"] is None: - return True + if release_information["remote"]["value"] is None: + return True - local_version = get_comparable_version(release_information["local"]["value"]) - remote_version = get_comparable_version(release_information["remote"]["value"]) + local_version = get_comparable_version(release_information["local"]["value"]) + remote_version = get_comparable_version(release_information["remote"]["value"]) + + return remote_version <= local_version - return remote_version <= local_version def get_latest(target, check, online=True): - from ..exceptions import CannotUpdateOffline + from ..exceptions import CannotUpdateOffline - if not online and not check.get("offline", False): - raise CannotUpdateOffline() + if not online and not check.get("offline", False): + raise CannotUpdateOffline() - package = check.get("package") + package = check.get("package") - distribution = pkg_resources.get_distribution(package) - if distribution: - local_version = distribution.version - else: - local_version = None + distribution = pkg_resources.get_distribution(package) + if distribution: + local_version = distribution.version + else: + local_version = None - remote_version = _get_latest_release(package, - include_prerelease=check.get("prerelease", False)) + remote_version = _get_latest_release( + package, include_prerelease=check.get("prerelease", False) + ) - information = {"local": {"name": local_version, "value": local_version}, - "remote": {"name": remote_version, "value": remote_version}} + information = { + "local": {"name": local_version, "value": local_version}, + "remote": {"name": remote_version, "value": remote_version}, + } - logger.debug("Target: {}, local: {}, remote: {}".format(target, information["local"]["name"], information["remote"]["name"])) + logger.debug( + "Target: {}, local: {}, remote: {}".format( + target, information["local"]["name"], information["remote"]["name"] + ) + ) - return information, _is_current(information) + return information, _is_current(information) diff --git a/src/octoprint/plugins/softwareupdate/version_checks/python_checker.py b/src/octoprint/plugins/softwareupdate/version_checks/python_checker.py index cc78b71eb..157b07f87 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/python_checker.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/python_checker.py @@ -2,27 +2,39 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" from ..exceptions import ConfigurationInvalid, CannotCheckOffline + def get_latest(target, check, full_data=False, online=True): - python_checker = check.get("python_checker") - if python_checker is None or not hasattr(python_checker, "get_latest"): - raise ConfigurationInvalid("Update configuration for {} of type python_checker needs python_checker defined and have an attribute \"get_latest\"".format(target)) + python_checker = check.get("python_checker") + if python_checker is None or not hasattr(python_checker, "get_latest"): + raise ConfigurationInvalid( + 'Update configuration for {} of type python_checker needs python_checker defined and have an attribute "get_latest"'.format( + target + ) + ) - if not online and not check.get("offline", False): - raise CannotCheckOffline("{} isn't marked as 'offline' capable, but we are apparently offline right now".format(target)) + if not online and not check.get("offline", False): + raise CannotCheckOffline( + "{} isn't marked as 'offline' capable, but we are apparently offline right now".format( + target + ) + ) - try: - return check["python_checker"].get_latest(target, check, full_data=full_data, online=online) - except Exception: - import inspect - args, _, _, _ = inspect.getargspec(check["python_checker"].get_latest) - if "online" not in args: - # old python_checker footprint, simply leave out the online parameter - return check["python_checker"].get_latest(target, check, full_data=full_data) + try: + return check["python_checker"].get_latest( + target, check, full_data=full_data, online=online + ) + except Exception: + import inspect - # some other error, raise again - raise + args, _, _, _ = inspect.getargspec(check["python_checker"].get_latest) + if "online" not in args: + # old python_checker footprint, simply leave out the online parameter + return check["python_checker"].get_latest(target, check, full_data=full_data) + + # some other error, raise again + raise diff --git a/src/octoprint/plugins/tracking/__init__.py b/src/octoprint/plugins/tracking/__init__.py index 716e68c3b..e40f00735 100644 --- a/src/octoprint/plugins/tracking/__init__.py +++ b/src/octoprint/plugins/tracking/__init__.py @@ -1,7 +1,7 @@ # -*- 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" import octoprint.plugin @@ -13,10 +13,10 @@ import hashlib import logging try: - # noinspection PyCompatibility - from urllib.parse import urlencode + # noinspection PyCompatibility + from urllib.parse import urlencode except ImportError: - from urllib import urlencode + from urllib import urlencode # noinspection PyCompatibility import concurrent.futures @@ -28,427 +28,514 @@ from octoprint.events import Events TRACKING_URL = "https://tracking.octoprint.org/track/{id}/{event}/" # noinspection PyMissingConstructor -class TrackingPlugin(octoprint.plugin.SettingsPlugin, - octoprint.plugin.EnvironmentDetectionPlugin, - octoprint.plugin.StartupPlugin, - octoprint.plugin.ShutdownPlugin, - octoprint.plugin.TemplatePlugin, - octoprint.plugin.AssetPlugin, - octoprint.plugin.WizardPlugin, - octoprint.plugin.EventHandlerPlugin): - - def __init__(self): - self._environment = None - self._throttle_state = None - self._helpers_get_throttle_state = None - self._printer_connection_parameters = None - self._url = None - self._ping_worker = None - self._pong_worker = None - self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1) +class TrackingPlugin( + octoprint.plugin.SettingsPlugin, + octoprint.plugin.EnvironmentDetectionPlugin, + octoprint.plugin.StartupPlugin, + octoprint.plugin.ShutdownPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.AssetPlugin, + octoprint.plugin.WizardPlugin, + octoprint.plugin.EventHandlerPlugin, +): + def __init__(self): + self._environment = None + self._throttle_state = None + self._helpers_get_throttle_state = None + self._printer_connection_parameters = None + self._url = None + self._ping_worker = None + self._pong_worker = None + self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1) + + self._record_next_firmware_info = False + + self._startup_time = monotonic_time() + + def initialize(self): + self._init_id() + + ##~~ SettingsPlugin + + def get_settings_defaults(self): + return { + "enabled": None, + "unique_id": None, + "server": TRACKING_URL, + "ping": 15 * 60, + "pong": 24 * 60 * 60, + "events": { + "pong": True, + "startup": True, + "printjob": True, + "commerror": True, + "plugin": True, + "update": True, + "printer": True, + "printer_safety_check": True, + "throttled": True, + "slicing": True, + }, + } + + def get_settings_restricted_paths(self): + return { + "admin": [["enabled"], ["unique_id"], ["events"]], + "never": [["server"], ["ping"]], + } + + def on_settings_save(self, data): + enabled = self._settings.get(["enabled"]) + + octoprint.plugin.SettingsPlugin.on_settings_save(self, data) + + if enabled is None and self._settings.get(["enabled"]): + # tracking was just enabled, let's start up tracking + self._start_tracking() + + ##~~ EnvironmentDetectionPlugin + + def on_environment_detected(self, environment, *args, **kwargs): + self._environment = environment + + ##~~ StartupPlugin + + def on_after_startup(self): + self._start_tracking() + + ##~~ ShutdownPlugin + + def on_shutdown(self): + if not self._settings.get_boolean(["enabled"]): + return + self._track_shutdown() + self._executor.shutdown(wait=True) + + ##~~ EventHandlerPlugin + + # noinspection PyUnresolvedReferences + def on_event(self, event, payload): + if not self._settings.get_boolean(["enabled"]): + return + + if event in ( + Events.PRINT_STARTED, + Events.PRINT_DONE, + Events.PRINT_FAILED, + Events.PRINT_CANCELLED, + ): + self._track_printjob_event(event, payload) + + elif event in (Events.ERROR,): + self._track_commerror_event(event, payload) + + elif event in (Events.CONNECTED,): + self._printer_connection_parameters = { + "port": payload["port"], + "baudrate": payload["baudrate"], + } + self._record_next_firmware_info = True + + elif event in (Events.FIRMWARE_DATA,) and self._record_next_firmware_info: + self._record_next_firmware_info = False + self._track_printer_event(event, payload) + + elif event in (Events.SLICING_STARTED,): + self._track_slicing_event(event, payload) + + elif hasattr(Events, "PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN") and event in ( + Events.PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN, + Events.PLUGIN_PLUGINMANAGER_UNINSTALL_PLUGIN, + Events.PLUGIN_PLUGINMANAGER_ENABLE_PLUGIN, + Events.PLUGIN_PLUGINMANAGER_DISABLE_PLUGIN, + ): + self._track_plugin_event(event, payload) + + elif hasattr(Events, "PLUGIN_SOFTWAREUPDATE_UPDATE_SUCCEEDED") and event in ( + Events.PLUGIN_SOFTWAREUPDATE_UPDATE_SUCCEEDED, + Events.PLUGIN_SOFTWAREUPDATE_UPDATE_FAILED, + ): + self._track_update_event(event, payload) + + elif hasattr(Events, "PLUGIN_PI_SUPPORT_THROTTLE_STATE") and event in ( + Events.PLUGIN_PI_SUPPORT_THROTTLE_STATE, + ): + self._throttle_state = payload + self._track_throttle_event(event, payload) + + elif hasattr(Events, "PLUGIN_PRINTER_SAFETY_CHECK_WARNING") and event in ( + Events.PLUGIN_PRINTER_SAFETY_CHECK_WARNING, + ): + self._track_printer_safety_event(event, payload) + + ##~~ TemplatePlugin + + def get_template_configs(self): + return [ + { + "type": "settings", + "name": gettext("Anonymous Usage Tracking"), + "template": "tracking_settings.jinja2", + "custom_bindings": False, + }, + { + "type": "wizard", + "name": gettext("Anonymous Usage Tracking"), + "template": "tracking_wizard.jinja2", + "custom_bindings": True, + "mandatory": True, + }, + ] + + ##~~ AssetPlugin + + def get_assets(self): + return {"js": ["js/usage.js"]} + + ##~~ WizardPlugin + + def is_wizard_required(self): + return self._settings.get(["enabled"]) is None + + ##~~ helpers + + def _init_id(self): + if not self._settings.get(["unique_id"]): + import uuid + + self._settings.set(["unique_id"], str(uuid.uuid4())) + self._settings.save() + + def _start_tracking(self): + if not self._settings.get_boolean(["enabled"]): + return + + if self._ping_worker is None: + ping_interval = self._settings.get_int(["ping"]) + if ping_interval: + self._ping_worker = RepeatedTimer( + ping_interval, self._track_ping, run_first=True + ) + self._ping_worker.start() + + if self._pong_worker is None: + pong_interval = self._settings.get(["pong"]) + if pong_interval: + self._pong_worker = RepeatedTimer( + pong_interval, self._track_pong, run_first=True + ) + self._pong_worker.start() + + if self._helpers_get_throttle_state is None: + # cautiously look for the get_throttled helper from pi_support + pi_helper = self._plugin_manager.get_helpers("pi_support", "get_throttled") + if pi_helper and "get_throttled" in pi_helper: + self._helpers_get_throttle_state = pi_helper["get_throttled"] + + # now that we have everything set up, phone home. + self._track_startup() + + def _track_ping(self): + if not self._settings.get_boolean(["enabled"]): + return + + uptime = int(monotonic_time() - self._startup_time) + self._track("ping", octoprint_uptime=uptime) + + def _track_pong(self): + if not self._settings.get_boolean(["events", "pong"]): + return + + payload = self._get_environment_payload() + + plugins = self._plugin_manager.enabled_plugins + plugins_thirdparty = [plugin for plugin in plugins.values() if not plugin.bundled] + payload["plugins"] = ",".join( + map( + lambda x: "{}:{}".format( + x.key.lower(), x.version.lower() if x.version else "?" + ), + plugins_thirdparty, + ) + ) + + self._track("pong", body=True, **payload) + + def _track_startup(self): + if not self._settings.get_boolean(["events", "startup"]): + return + + payload = self._get_environment_payload() + + self._track("startup", **payload) + + def _track_shutdown(self): + if not self._settings.get_boolean(["enabled"]): + return + + if not self._settings.get_boolean(["events", "startup"]): + return + + self._track("shutdown") + + def _track_plugin_event(self, event, payload): + if not self._settings.get_boolean(["events", "plugin"]): + return + + if event.endswith("_install_plugin"): + self._track( + "install_plugin", + plugin=payload.get("id"), + plugin_version=payload.get("version"), + ) + elif event.endswith("_uninstall_plugin"): + self._track( + "uninstall_plugin", + plugin=payload.get("id"), + plugin_version=payload.get("version"), + ) + elif event.endswith("_enable_plugin"): + self._track( + "enable_plugin", + plugin=payload.get("id"), + plugin_version=payload.get("version"), + ) + elif event.endswith("_disable_plugin"): + self._track( + "disable_plugin", + plugin=payload.get("id"), + plugin_version=payload.get("version"), + ) + + def _track_update_event(self, event, payload): + if not self._settings.get_boolean(["events", "update"]): + return + + if event.endswith("_update_succeeded"): + self._track( + "update_successful", + target=payload.get("target"), + from_version=payload.get("from_version"), + to_version=payload.get("to_version"), + ) + elif event.endswith("_update_failed"): + self._track( + "update_failed", + target=payload.get("target"), + from_version=payload.get("from_version"), + to_version=payload.get("to_version"), + ) + + def _track_throttle_event(self, event, payload): + if not self._settings.get_boolean(["events", "throttled"]): + return + + args = { + "throttled_now": payload["current_issue"], + "throttled_past": payload["past_issue"], + "throttled_mask": payload["raw_value"], + "throttled_voltage_now": payload["current_undervoltage"], + "throttled_voltage_past": payload["past_undervoltage"], + "throttled_overheat_now": payload["current_overheat"], + "throttled_overheat_past": payload["past_overheat"], + } + + if payload["current_issue"]: + track_event = "system_throttled" + else: + track_event = "system_unthrottled" + + if track_event is not None: + self._track(track_event, **args) + + def _track_commerror_event(self, event, payload): + if not self._settings.get_boolean(["events", "commerror"]): + return + + if not "reason" in payload or not "error" in payload: + return + + track_event = "commerror_{}".format(payload["reason"]) + args = {"commerror_text": payload["error"]} + + if callable(self._helpers_get_throttle_state): + try: + throttle_state = self._helpers_get_throttle_state(run_now=True) + if throttle_state and ( + throttle_state.get("current_issue", False) + or throttle_state.get("past_issue", False) + ): + args["throttled_now"] = throttle_state["current_issue"] + args["throttled_past"] = throttle_state["past_issue"] + args["throttled_mask"] = throttle_state["raw_value"] + except Exception: + # ignored + pass + + self._track(track_event, **args) + + def _track_printjob_event(self, event, payload): + if not self._settings.get_boolean(["events", "printjob"]): + return + + unique_id = self._settings.get(["unique_id"]) + if not unique_id: + return + + sha = hashlib.sha1() + sha.update(payload.get("path").encode("utf-8")) + sha.update(unique_id.encode("utf-8")) + + track_event = None + args = {"origin": payload.get("origin"), "file": sha.hexdigest()} + + if event == Events.PRINT_STARTED: + track_event = "print_started" + elif event == Events.PRINT_DONE: + try: + elapsed = int(payload.get("time", 0)) + if elapsed: + args["elapsed"] = elapsed + except (ValueError, TypeError): + pass + track_event = "print_done" + elif event == Events.PRINT_FAILED: + try: + elapsed = int(payload.get("time", 0)) + if elapsed: + args["elapsed"] = elapsed + except (ValueError, TypeError): + pass + args["reason"] = payload.get("reason", "unknown") + + if "error" in payload and self._settings.get_boolean(["events", "commerror"]): + args["commerror_text"] = payload["error"] + + track_event = "print_failed" + elif event == Events.PRINT_CANCELLED: + try: + elapsed = int(payload.get("time", 0)) + if elapsed: + args["elapsed"] = elapsed + except (ValueError, TypeError): + pass + track_event = "print_cancelled" + + if callable(self._helpers_get_throttle_state): + try: + throttle_state = self._helpers_get_throttle_state(run_now=True) + if throttle_state and ( + throttle_state.get("current_issue", False) + or throttle_state.get("past_issue", False) + ): + args["throttled_now"] = throttle_state["current_issue"] + args["throttled_past"] = throttle_state["past_issue"] + args["throttled_mask"] = throttle_state["raw_value"] + except Exception: + # ignored + pass + + if track_event is not None: + self._track(track_event, **args) + + def _track_printer_event(self, event, payload): + if not self._settings.get_boolean(["events", "printer"]): + return + + if event in (Events.FIRMWARE_DATA,): + args = {"firmware_name": payload["name"]} + if self._printer_connection_parameters: + args["printer_port"] = self._printer_connection_parameters["port"] + args["printer_baudrate"] = self._printer_connection_parameters["baudrate"] + self._track("printer_connected", **args) + + def _track_printer_safety_event(self, event, payload): + if not self._settings.get_boolean(["events", "printer_safety_check"]): + return + + self._track( + "printer_safety_warning", + printer_safety_warning_type=payload.get("warning_type", "unknown"), + printer_safety_check_name=payload.get("check_name", "unknown"), + ) + + def _track_slicing_event(self, event, payload): + if not self._settings.get_boolean(["events", "slicing"]): + return + + self._track("slicing_started", slicer=payload.get(b"slicer", "unknown")) + + def _track(self, event, **kwargs): + if not self._settings.get_boolean(["enabled"]): + return + + self._executor.submit(self._do_track, event, **kwargs) + + def _do_track(self, event, body=False, **kwargs): + if not self._connectivity_checker.online: + return + + if not self._settings.get_boolean(["enabled"]): + return + + unique_id = self._settings.get(["unique_id"]) + if not unique_id: + return + + server = self._settings.get(["server"]) + url = server.format(id=unique_id, event=event) + # Don't print the URL or UUID! That would expose the UUID in forums/tickets + # if pasted. It's okay for the user to know their uuid, but it shouldn't be shared. + + headers = {"User-Agent": "OctoPrint/{}".format(get_octoprint_version_string())} + try: + params = urlencode(kwargs, doseq=True).replace("+", "%20") + + if body: + requests.post(url, data=params, timeout=3.1, headers=headers) + else: + requests.get(url, params=params, timeout=3.1, headers=headers) + + self._logger.info( + "Sent tracking event {}, payload: {!r}".format(event, kwargs) + ) + except Exception: + if self._logger.isEnabledFor(logging.DEBUG): + self._logger.exception( + "Error while sending event to anonymous usage tracking" + ) + else: + pass + + def _get_environment_payload(self): + payload = { + "version": get_octoprint_version_string(), + "os": self._environment["os"]["id"], + "python": self._environment["python"]["version"], + "pip": self._environment["python"]["pip"], + "cores": self._environment["hardware"]["cores"], + "freq": self._environment["hardware"]["freq"], + "ram": self._environment["hardware"]["ram"], + } + + if ( + "plugins" in self._environment + and "pi_support" in self._environment["plugins"] + ): + payload["pi_model"] = self._environment["plugins"]["pi_support"]["model"] + + if "octopi_version" in self._environment["plugins"]["pi_support"]: + payload["octopi_version"] = self._environment["plugins"]["pi_support"][ + "octopi_version" + ] + + return payload - self._record_next_firmware_info = False - - self._startup_time = monotonic_time() - - def initialize(self): - self._init_id() - - ##~~ SettingsPlugin - - def get_settings_defaults(self): - return {"enabled": None, - "unique_id": None, - "server": TRACKING_URL, - "ping": 15*60, - "pong": 24*60*60, - "events": {"pong": True, - "startup": True, - "printjob": True, - "commerror": True, - "plugin": True, - "update": True, - "printer": True, - "printer_safety_check": True, - "throttled": True, - "slicing": True}} - - def get_settings_restricted_paths(self): - return {"admin": [["enabled"], ["unique_id"], ["events"]], - "never": [["server"], ["ping"]]} - - def on_settings_save(self, data): - enabled = self._settings.get(["enabled"]) - - octoprint.plugin.SettingsPlugin.on_settings_save(self, data) - - if enabled is None and self._settings.get(["enabled"]): - # tracking was just enabled, let's start up tracking - self._start_tracking() - - ##~~ EnvironmentDetectionPlugin - - def on_environment_detected(self, environment, *args, **kwargs): - self._environment = environment - - ##~~ StartupPlugin - - def on_after_startup(self): - self._start_tracking() - - ##~~ ShutdownPlugin - - def on_shutdown(self): - if not self._settings.get_boolean(["enabled"]): - return - self._track_shutdown() - self._executor.shutdown(wait=True) - - ##~~ EventHandlerPlugin - - # noinspection PyUnresolvedReferences - def on_event(self, event, payload): - if not self._settings.get_boolean(["enabled"]): - return - - if event in (Events.PRINT_STARTED, Events.PRINT_DONE, Events.PRINT_FAILED, Events.PRINT_CANCELLED): - self._track_printjob_event(event, payload) - - elif event in (Events.ERROR,): - self._track_commerror_event(event, payload) - - elif event in (Events.CONNECTED,): - self._printer_connection_parameters = {"port": payload["port"], - "baudrate": payload["baudrate"]} - self._record_next_firmware_info = True - - elif event in (Events.FIRMWARE_DATA,) and self._record_next_firmware_info: - self._record_next_firmware_info = False - self._track_printer_event(event, payload) - - elif event in (Events.SLICING_STARTED,): - self._track_slicing_event(event, payload) - - elif hasattr(Events, "PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN") and \ - event in (Events.PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN, Events.PLUGIN_PLUGINMANAGER_UNINSTALL_PLUGIN, - Events.PLUGIN_PLUGINMANAGER_ENABLE_PLUGIN, Events.PLUGIN_PLUGINMANAGER_DISABLE_PLUGIN): - self._track_plugin_event(event, payload) - - elif hasattr(Events, "PLUGIN_SOFTWAREUPDATE_UPDATE_SUCCEEDED") and \ - event in (Events.PLUGIN_SOFTWAREUPDATE_UPDATE_SUCCEEDED, Events.PLUGIN_SOFTWAREUPDATE_UPDATE_FAILED): - self._track_update_event(event, payload) - - elif hasattr(Events, "PLUGIN_PI_SUPPORT_THROTTLE_STATE") and event in (Events.PLUGIN_PI_SUPPORT_THROTTLE_STATE,): - self._throttle_state = payload - self._track_throttle_event(event, payload) - - elif hasattr(Events, "PLUGIN_PRINTER_SAFETY_CHECK_WARNING") and event in (Events.PLUGIN_PRINTER_SAFETY_CHECK_WARNING,): - self._track_printer_safety_event(event, payload) - - ##~~ TemplatePlugin - - def get_template_configs(self): - return [ - {"type": "settings", "name": gettext("Anonymous Usage Tracking"), "template": "tracking_settings.jinja2", "custom_bindings": False}, - {"type": "wizard", "name": gettext("Anonymous Usage Tracking"), "template": "tracking_wizard.jinja2", "custom_bindings": True, "mandatory": True} - ] - - ##~~ AssetPlugin - - def get_assets(self): - return {"js": ["js/usage.js"]} - - ##~~ WizardPlugin - - def is_wizard_required(self): - return self._settings.get(["enabled"]) is None - - ##~~ helpers - - def _init_id(self): - if not self._settings.get(["unique_id"]): - import uuid - self._settings.set(["unique_id"], str(uuid.uuid4())) - self._settings.save() - - def _start_tracking(self): - if not self._settings.get_boolean(["enabled"]): - return - - if self._ping_worker is None: - ping_interval = self._settings.get_int(["ping"]) - if ping_interval: - self._ping_worker = RepeatedTimer(ping_interval, self._track_ping, run_first=True) - self._ping_worker.start() - - if self._pong_worker is None: - pong_interval = self._settings.get(["pong"]) - if pong_interval: - self._pong_worker = RepeatedTimer(pong_interval, self._track_pong, run_first=True) - self._pong_worker.start() - - if self._helpers_get_throttle_state is None: - # cautiously look for the get_throttled helper from pi_support - pi_helper = self._plugin_manager.get_helpers("pi_support", "get_throttled") - if pi_helper and 'get_throttled' in pi_helper: - self._helpers_get_throttle_state = pi_helper['get_throttled'] - - # now that we have everything set up, phone home. - self._track_startup() - - def _track_ping(self): - if not self._settings.get_boolean(["enabled"]): - return - - uptime = int(monotonic_time() - self._startup_time) - self._track("ping", octoprint_uptime=uptime) - - def _track_pong(self): - if not self._settings.get_boolean(["events", "pong"]): - return - - payload = self._get_environment_payload() - - plugins = self._plugin_manager.enabled_plugins - plugins_thirdparty = [plugin for plugin in plugins.values() if not plugin.bundled] - payload["plugins"] = ",".join(map(lambda x: "{}:{}".format(x.key.lower(), - x.version.lower() if x.version else "?"), - plugins_thirdparty)) - - self._track("pong", body=True, **payload) - - def _track_startup(self): - if not self._settings.get_boolean(["events", "startup"]): - return - - payload = self._get_environment_payload() - - self._track("startup", **payload) - - def _track_shutdown(self): - if not self._settings.get_boolean(["enabled"]): - return - - if not self._settings.get_boolean(["events", "startup"]): - return - - self._track("shutdown") - - def _track_plugin_event(self, event, payload): - if not self._settings.get_boolean(["events", "plugin"]): - return - - if event.endswith("_install_plugin"): - self._track("install_plugin", plugin=payload.get("id"), plugin_version=payload.get("version")) - elif event.endswith("_uninstall_plugin"): - self._track("uninstall_plugin", plugin=payload.get("id"), plugin_version=payload.get("version")) - elif event.endswith("_enable_plugin"): - self._track("enable_plugin", plugin=payload.get("id"), plugin_version=payload.get("version")) - elif event.endswith("_disable_plugin"): - self._track("disable_plugin", plugin=payload.get("id"), plugin_version=payload.get("version")) - - def _track_update_event(self, event, payload): - if not self._settings.get_boolean(["events", "update"]): - return - - if event.endswith("_update_succeeded"): - self._track("update_successful", target=payload.get("target"), from_version=payload.get("from_version"), to_version=payload.get("to_version")) - elif event.endswith("_update_failed"): - self._track("update_failed", target=payload.get("target"), from_version=payload.get("from_version"), to_version=payload.get("to_version")) - - def _track_throttle_event(self, event, payload): - if not self._settings.get_boolean(["events", "throttled"]): - return - - args = {"throttled_now": payload["current_issue"], - "throttled_past": payload["past_issue"], - "throttled_mask": payload["raw_value"], - "throttled_voltage_now": payload["current_undervoltage"], - "throttled_voltage_past": payload["past_undervoltage"], - "throttled_overheat_now": payload["current_overheat"], - "throttled_overheat_past": payload["past_overheat"]} - - if payload["current_issue"]: - track_event = "system_throttled" - else: - track_event = "system_unthrottled" - - if track_event is not None: - self._track(track_event, **args) - - def _track_commerror_event(self, event, payload): - if not self._settings.get_boolean(["events", "commerror"]): - return - - if not "reason" in payload or not "error" in payload: - return - - track_event = "commerror_{}".format(payload["reason"]) - args = {"commerror_text": payload["error"]} - - if callable(self._helpers_get_throttle_state): - try: - throttle_state = self._helpers_get_throttle_state(run_now=True) - if throttle_state and (throttle_state.get("current_issue", False) or throttle_state.get("past_issue", False)): - args["throttled_now"] = throttle_state["current_issue"] - args["throttled_past"] = throttle_state["past_issue"] - args["throttled_mask"] = throttle_state["raw_value"] - except Exception: - # ignored - pass - - self._track(track_event, **args) - - def _track_printjob_event(self, event, payload): - if not self._settings.get_boolean(["events", "printjob"]): - return - - unique_id = self._settings.get(["unique_id"]) - if not unique_id: - return - - sha = hashlib.sha1() - sha.update(payload.get("path").encode("utf-8")) - sha.update(unique_id.encode("utf-8")) - - track_event = None - args = {"origin": payload.get("origin"), "file": sha.hexdigest()} - - if event == Events.PRINT_STARTED: - track_event = "print_started" - elif event == Events.PRINT_DONE: - try: - elapsed = int(payload.get("time", 0)) - if elapsed: - args["elapsed"] = elapsed - except (ValueError, TypeError): - pass - track_event = "print_done" - elif event == Events.PRINT_FAILED: - try: - elapsed = int(payload.get("time", 0)) - if elapsed: - args["elapsed"] = elapsed - except (ValueError, TypeError): - pass - args["reason"] = payload.get("reason", "unknown") - - if "error" in payload and self._settings.get_boolean(["events", "commerror"]): - args["commerror_text"] = payload["error"] - - track_event = "print_failed" - elif event == Events.PRINT_CANCELLED: - try: - elapsed = int(payload.get("time", 0)) - if elapsed: - args["elapsed"] = elapsed - except (ValueError, TypeError): - pass - track_event = "print_cancelled" - - if callable(self._helpers_get_throttle_state): - try: - throttle_state = self._helpers_get_throttle_state(run_now=True) - if throttle_state and (throttle_state.get("current_issue", False) or throttle_state.get("past_issue", False)): - args["throttled_now"] = throttle_state["current_issue"] - args["throttled_past"] = throttle_state["past_issue"] - args["throttled_mask"] = throttle_state["raw_value"] - except Exception: - # ignored - pass - - if track_event is not None: - self._track(track_event, **args) - - def _track_printer_event(self, event, payload): - if not self._settings.get_boolean(["events", "printer"]): - return - - if event in (Events.FIRMWARE_DATA,): - args = {"firmware_name": payload["name"]} - if self._printer_connection_parameters: - args["printer_port"] = self._printer_connection_parameters["port"] - args["printer_baudrate"] = self._printer_connection_parameters["baudrate"] - self._track("printer_connected", **args) - - def _track_printer_safety_event(self, event, payload): - if not self._settings.get_boolean(["events", "printer_safety_check"]): - return - - self._track("printer_safety_warning", - printer_safety_warning_type=payload.get("warning_type", "unknown"), - printer_safety_check_name=payload.get("check_name", "unknown")) - - def _track_slicing_event(self, event, payload): - if not self._settings.get_boolean(["events", "slicing"]): - return - - self._track("slicing_started", - slicer=payload.get(b"slicer", "unknown")) - - def _track(self, event, **kwargs): - if not self._settings.get_boolean(["enabled"]): - return - - self._executor.submit(self._do_track, event, **kwargs) - - def _do_track(self, event, body=False, **kwargs): - if not self._connectivity_checker.online: - return - - if not self._settings.get_boolean(["enabled"]): - return - - unique_id = self._settings.get(["unique_id"]) - if not unique_id: - return - - server = self._settings.get(["server"]) - url = server.format(id=unique_id, event=event) - # Don't print the URL or UUID! That would expose the UUID in forums/tickets - # if pasted. It's okay for the user to know their uuid, but it shouldn't be shared. - - headers = {"User-Agent": "OctoPrint/{}".format(get_octoprint_version_string())} - try: - params = urlencode(kwargs, doseq=True).replace("+", "%20") - - if body: - requests.post(url, - data=params, - timeout=3.1, - headers=headers) - else: - requests.get(url, - params=params, - timeout=3.1, - headers=headers) - - self._logger.info("Sent tracking event {}, payload: {!r}".format(event, kwargs)) - except Exception: - if self._logger.isEnabledFor(logging.DEBUG): - self._logger.exception("Error while sending event to anonymous usage tracking") - else: - pass - - def _get_environment_payload(self): - payload = {"version": get_octoprint_version_string(), - "os": self._environment["os"]["id"], - "python": self._environment["python"]["version"], - "pip": self._environment["python"]["pip"], - "cores": self._environment["hardware"]["cores"], - "freq": self._environment["hardware"]["freq"], - "ram": self._environment["hardware"]["ram"]} - - if "plugins" in self._environment and "pi_support" in self._environment["plugins"]: - payload["pi_model"] = self._environment["plugins"]["pi_support"]["model"] - - if "octopi_version" in self._environment["plugins"]["pi_support"]: - payload["octopi_version"] = self._environment["plugins"]["pi_support"]["octopi_version"] - - return payload __plugin_name__ = "Anonymous Usage Tracking" -__plugin_description__ = "Anonymous version and usage tracking, see homepage for details on what gets tracked" +__plugin_description__ = ( + "Anonymous version and usage tracking, see homepage for details on what gets tracked" +) __plugin_url__ = "https://tracking.octoprint.org" __plugin_author__ = "Gina Häußge" __plugin_license__ = "AGPLv3" diff --git a/src/octoprint/plugins/virtual_printer/__init__.py b/src/octoprint/plugins/virtual_printer/__init__.py index 287e94c31..ab1ae4bb9 100644 --- a/src/octoprint/plugins/virtual_printer/__init__.py +++ b/src/octoprint/plugins/virtual_printer/__init__.py @@ -2,135 +2,143 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import octoprint.plugin -class VirtualPrinterPlugin(octoprint.plugin.SettingsPlugin, octoprint.plugin.TemplatePlugin): - def get_template_configs(self): - return [ - {"type": "settings", "custom_bindings": False} - ] +class VirtualPrinterPlugin( + octoprint.plugin.SettingsPlugin, octoprint.plugin.TemplatePlugin +): + def get_template_configs(self): + return [{"type": "settings", "custom_bindings": False}] - def get_settings_defaults(self): - return { - "enabled": False, - "okAfterResend": False, - "forceChecksum": False, - "numExtruders": 1, - "pinnedExtruders": None, - "includeCurrentToolInTemps": True, - "includeFilenameInOpened": True, - "hasBed": True, - "hasChamber": False, - "repetierStyleTargetTemperature": False, - "okBeforeCommandOutput": False, - "smoothieTemperatureReporting": False, - "klipperTemperatureReporting": False, - "reprapfwM114": False, - "sdFiles": { - "size": True, - "longname": False - }, - "throttle": 0.01, - "sendWait": True, - "waitInterval": 1.0, - "rxBuffer": 64, - "commandBuffer": 4, - "supportM112": True, - "echoOnM117": True, - "brokenM29": True, - "brokenResend": False, - "supportF": False, - "firmwareName": "Virtual Marlin 1.0", - "sharedNozzle": False, - "sendBusy": False, - "busyInterval": 2.0, - "simulateReset": True, - "resetLines": ['start', 'Marlin: Virtual Marlin!', '\x80', 'SD card ok'], - "preparedOks": [], - "okFormatString": "ok", - "m115FormatString": "FIRMWARE_NAME:{firmware_name} PROTOCOL_VERSION:1.0", - "m115ReportCapabilities": True, - "capabilities": { - "AUTOREPORT_TEMP": True, - "AUTOREPORT_SD_STATUS": True, - "EMERGENCY_PARSER": True - }, - "m114FormatString": "X:{x} Y:{y} Z:{z} E:{e[current]} Count: A:{a} B:{b} C:{c}", - "m105TargetFormatString": "{heater}:{actual:.2f}/ {target:.2f}", - "m105NoTargetFormatString": "{heater}:{actual:.2f}", - "ambientTemperature": 21.3, - "errors": { - "checksum_mismatch": "Checksum mismatch", - "checksum_missing": "Missing checksum", - "lineno_mismatch": "expected line {} got {}", - "lineno_missing": "No Line Number with checksum, Last Line: {}", - "maxtemp": "MAXTEMP triggered!", - "mintemp": "MINTEMP triggered!", - "command_unknown": "Unknown command {}" - } - } + def get_settings_defaults(self): + return { + "enabled": False, + "okAfterResend": False, + "forceChecksum": False, + "numExtruders": 1, + "pinnedExtruders": None, + "includeCurrentToolInTemps": True, + "includeFilenameInOpened": True, + "hasBed": True, + "hasChamber": False, + "repetierStyleTargetTemperature": False, + "okBeforeCommandOutput": False, + "smoothieTemperatureReporting": False, + "klipperTemperatureReporting": False, + "reprapfwM114": False, + "sdFiles": {"size": True, "longname": False}, + "throttle": 0.01, + "sendWait": True, + "waitInterval": 1.0, + "rxBuffer": 64, + "commandBuffer": 4, + "supportM112": True, + "echoOnM117": True, + "brokenM29": True, + "brokenResend": False, + "supportF": False, + "firmwareName": "Virtual Marlin 1.0", + "sharedNozzle": False, + "sendBusy": False, + "busyInterval": 2.0, + "simulateReset": True, + "resetLines": ["start", "Marlin: Virtual Marlin!", "\x80", "SD card ok"], + "preparedOks": [], + "okFormatString": "ok", + "m115FormatString": "FIRMWARE_NAME:{firmware_name} PROTOCOL_VERSION:1.0", + "m115ReportCapabilities": True, + "capabilities": { + "AUTOREPORT_TEMP": True, + "AUTOREPORT_SD_STATUS": True, + "EMERGENCY_PARSER": True, + }, + "m114FormatString": "X:{x} Y:{y} Z:{z} E:{e[current]} Count: A:{a} B:{b} C:{c}", + "m105TargetFormatString": "{heater}:{actual:.2f}/ {target:.2f}", + "m105NoTargetFormatString": "{heater}:{actual:.2f}", + "ambientTemperature": 21.3, + "errors": { + "checksum_mismatch": "Checksum mismatch", + "checksum_missing": "Missing checksum", + "lineno_mismatch": "expected line {} got {}", + "lineno_missing": "No Line Number with checksum, Last Line: {}", + "maxtemp": "MAXTEMP triggered!", + "mintemp": "MINTEMP triggered!", + "command_unknown": "Unknown command {}", + }, + } - def get_settings_version(self): - return 1 + def get_settings_version(self): + return 1 - def on_settings_migrate(self, target, current): - if current is None: - config = self._settings.global_get(["devel", "virtualPrinter"]) - if config: - self._logger.info("Migrating settings from devel.virtualPrinter to plugins.virtual_printer...") - self._settings.global_set(["plugins", "virtual_printer"], config, force=True) - self._settings.global_remove(["devel", "virtualPrinter"]) + def on_settings_migrate(self, target, current): + if current is None: + config = self._settings.global_get(["devel", "virtualPrinter"]) + if config: + self._logger.info( + "Migrating settings from devel.virtualPrinter to plugins.virtual_printer..." + ) + self._settings.global_set( + ["plugins", "virtual_printer"], config, force=True + ) + self._settings.global_remove(["devel", "virtualPrinter"]) - def virtual_printer_factory(self, comm_instance, port, baudrate, - read_timeout): - if not port == "VIRTUAL": - return None + def virtual_printer_factory(self, comm_instance, port, baudrate, read_timeout): + if not port == "VIRTUAL": + return None - if not self._settings.get_boolean(["enabled"]): - return None + if not self._settings.get_boolean(["enabled"]): + return None - import logging.handlers - from octoprint.logging.handlers import CleaningTimedRotatingFileHandler + import logging.handlers + from octoprint.logging.handlers import CleaningTimedRotatingFileHandler - seriallog_handler = CleaningTimedRotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="serial"), - when="D", - backupCount=3) - seriallog_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s")) - seriallog_handler.setLevel(logging.DEBUG) + seriallog_handler = CleaningTimedRotatingFileHandler( + self._settings.get_plugin_logfile_path(postfix="serial"), + when="D", + backupCount=3, + ) + seriallog_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s")) + seriallog_handler.setLevel(logging.DEBUG) - from . import virtual + from . import virtual - serial_obj = virtual.VirtualPrinter(self._settings, - seriallog_handler=seriallog_handler, - read_timeout=float(read_timeout), - faked_baudrate=baudrate) - return serial_obj + serial_obj = virtual.VirtualPrinter( + self._settings, + seriallog_handler=seriallog_handler, + read_timeout=float(read_timeout), + faked_baudrate=baudrate, + ) + return serial_obj + + def get_additional_port_names(self, *args, **kwargs): + if self._settings.get_boolean(["enabled"]): + return ["VIRTUAL"] + else: + return [] - def get_additional_port_names(self, *args, **kwargs): - if self._settings.get_boolean(["enabled"]): - return ["VIRTUAL"] - else: - return [] __plugin_name__ = "Virtual Printer" __plugin_author__ = "Gina Häußge, based on work by Daid Braam" -__plugin_homepage__ = "https://docs.octoprint.org/en/master/development/virtual_printer.html" +__plugin_homepage__ = ( + "https://docs.octoprint.org/en/master/development/virtual_printer.html" +) __plugin_license__ = "AGPLv3" __plugin_description__ = "Provides a virtual printer via a virtual serial port for development and testing purposes" __plugin_pythoncompat__ = ">=2.7,<4" + def __plugin_load__(): - plugin = VirtualPrinterPlugin() + plugin = VirtualPrinterPlugin() - global __plugin_implementation__ - __plugin_implementation__ = plugin + global __plugin_implementation__ + __plugin_implementation__ = plugin - global __plugin_hooks__ - __plugin_hooks__ = { - "octoprint.comm.transport.serial.factory": plugin.virtual_printer_factory, - "octoprint.comm.transport.serial.additional_port_names": plugin.get_additional_port_names - } + global __plugin_hooks__ + __plugin_hooks__ = { + "octoprint.comm.transport.serial.factory": plugin.virtual_printer_factory, + "octoprint.comm.transport.serial.additional_port_names": plugin.get_additional_port_names, + } diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py index 9767f62e4..bfd2961b6 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" import io @@ -12,15 +12,16 @@ import re import threading import math import collections -try: - import queue -except ImportError: - import Queue as queue try: - from os import scandir + import queue except ImportError: - from scandir import scandir + import Queue as queue + +try: + from os import scandir +except ImportError: + from scandir import scandir # noinspection PyCompatibility from past.builtins import basestring @@ -28,818 +29,886 @@ from past.builtins import basestring from serial import SerialTimeoutException from octoprint.plugin import plugin_manager -from octoprint.util import RepeatedTimer, monotonic_time, to_bytes, to_unicode, get_dos_filename +from octoprint.util import ( + RepeatedTimer, + monotonic_time, + to_bytes, + to_unicode, + get_dos_filename, +) from typing import Any # noinspection PyBroadException class VirtualPrinter(object): - command_regex = re.compile(r"^([GMTF])(\d+)") - sleep_regex = re.compile(r"sleep (\d+)") - sleep_after_regex = re.compile(r"sleep_after ([GMTF]\d+) (\d+)") - sleep_after_next_regex = re.compile(r"sleep_after_next ([GMTF]\d+) (\d+)") - custom_action_regex = re.compile(r"action_custom ([a-zA-Z0-9_]+)(\s+.*)?") - prepare_ok_regex = re.compile(r"prepare_ok (.*)") - send_regex = re.compile(r"send (.*)") - set_ambient_regex = re.compile(r"set_ambient ([-+]?[0-9]*\.?[0-9]+)") - start_sd_regex = re.compile(r"start_sd (.*)") - select_sd_regex = re.compile(r"select_sd (.*)") - - def __init__(self, settings, seriallog_handler=None, read_timeout=5.0, write_timeout=10.0, faked_baudrate=115200): - import logging - self._logger = logging.getLogger("octoprint.plugins.virtual_printer.VirtualPrinter") - - self._settings = settings - self._faked_baudrate = faked_baudrate - - self._seriallog = logging.getLogger("octoprint.plugin.virtual_printer.VirtualPrinter.serial") - self._seriallog.setLevel(logging.CRITICAL) - self._seriallog.propagate = False + command_regex = re.compile(r"^([GMTF])(\d+)") + sleep_regex = re.compile(r"sleep (\d+)") + sleep_after_regex = re.compile(r"sleep_after ([GMTF]\d+) (\d+)") + sleep_after_next_regex = re.compile(r"sleep_after_next ([GMTF]\d+) (\d+)") + custom_action_regex = re.compile(r"action_custom ([a-zA-Z0-9_]+)(\s+.*)?") + prepare_ok_regex = re.compile(r"prepare_ok (.*)") + send_regex = re.compile(r"send (.*)") + set_ambient_regex = re.compile(r"set_ambient ([-+]?[0-9]*\.?[0-9]+)") + start_sd_regex = re.compile(r"start_sd (.*)") + select_sd_regex = re.compile(r"select_sd (.*)") + + def __init__( + self, + settings, + seriallog_handler=None, + read_timeout=5.0, + write_timeout=10.0, + faked_baudrate=115200, + ): + import logging + + self._logger = logging.getLogger( + "octoprint.plugins.virtual_printer.VirtualPrinter" + ) + + self._settings = settings + self._faked_baudrate = faked_baudrate + + self._seriallog = logging.getLogger( + "octoprint.plugin.virtual_printer.VirtualPrinter.serial" + ) + self._seriallog.setLevel(logging.CRITICAL) + self._seriallog.propagate = False + + if seriallog_handler is not None: + import logging.handlers + + self._seriallog.addHandler(seriallog_handler) + self._seriallog.setLevel(logging.INFO) + + self._seriallog.info("-" * 78) + + self._read_timeout = read_timeout + self._write_timeout = write_timeout + + self._rx_buffer_size = self._settings.get_int(["rxBuffer"]) + + self.incoming = CharCountingQueue(self._rx_buffer_size, name="RxBuffer") + self.outgoing = queue.Queue() + self.buffered = queue.Queue(maxsize=self._settings.get_int(["commandBuffer"])) + + if self._settings.get_boolean(["simulateReset"]): + for item in self._settings.get(["resetLines"]): + self._send(item + "\n") + + self._prepared_oks = [] + prepared = self._settings.get(["preparedOks"]) + if prepared and isinstance(prepared, list): + for prep in prepared: + self._prepared_oks.append(prep) + + self._prepared_errors = [] - if seriallog_handler is not None: - import logging.handlers - self._seriallog.addHandler(seriallog_handler) - self._seriallog.setLevel(logging.INFO) - - self._seriallog.info(u"-"*78) - - self._read_timeout = read_timeout - self._write_timeout = write_timeout - - self._rx_buffer_size = self._settings.get_int(["rxBuffer"]) - - self.incoming = CharCountingQueue(self._rx_buffer_size, name="RxBuffer") - self.outgoing = queue.Queue() - self.buffered = queue.Queue(maxsize=self._settings.get_int(["commandBuffer"])) - - if self._settings.get_boolean(["simulateReset"]): - for item in self._settings.get(["resetLines"]): - self._send(item + "\n") - - self._prepared_oks = [] - prepared = self._settings.get(["preparedOks"]) - if prepared and isinstance(prepared, list): - for prep in prepared: - self._prepared_oks.append(prep) - - self._prepared_errors = [] - - self._errors = self._settings.get(["errors"], merged=True) - - self.currentExtruder = 0 - self.extruderCount = self._settings.get_int(["numExtruders"]) - self.pinnedExtruders = self._settings.get(["pinnedExtruders"]) - if self.pinnedExtruders is None: - self.pinnedExtruders = {} - self.sharedNozzle = self._settings.get_boolean(["sharedNozzle"]) - self.temperatureCount = (1 if self.sharedNozzle else self.extruderCount) - - self._ambient_temperature = self._settings.get_float(["ambientTemperature"]) - - self.temp = [self._ambient_temperature] * self.temperatureCount - self.targetTemp = [0.0] * self.temperatureCount - self.bedTemp = self._ambient_temperature - self.bedTargetTemp = 0.0 - self.chamberTemp = self._ambient_temperature - self.chamberTargetTemp = 0.0 - self.lastTempAt = monotonic_time() - - self._relative = True - self._lastX = 0.0 - self._lastY = 0.0 - self._lastZ = 0.0 - self._lastE = [0.0] * self.extruderCount - self._lastF = 200 - - self._unitModifier = 1 - self._feedrate_multiplier = 100 - self._flowrate_multiplier = 100 - - self._virtualSd = self._settings.global_get_basefolder("virtualSd") - self._sdCardReady = True - self._sdPrinter = None - self._sdPrintingSemaphore = threading.Event() - self._selectedSdFile = None - self._selectedSdFileSize = None - self._selectedSdFilePos = None - - self._writingToSd = False - self._writingToSdHandle = None - self._newSdFilePos = None - - self._heatingUp = False - - self._okBeforeCommandOutput = self._settings.get_boolean(["okBeforeCommandOutput"]) - self._supportM112 = self._settings.get_boolean(["supportM112"]) - self._supportF = self._settings.get_boolean(["supportF"]) - - self._sendWait = self._settings.get_boolean(["sendWait"]) - self._sendBusy = self._settings.get_boolean(["sendBusy"]) - self._waitInterval = self._settings.get_float(["waitInterval"]) - self._busyInterval = self._settings.get_float(["busyInterval"]) - - self._busy = None - self._busy_loop = None - - self._echoOnM117 = self._settings.get_boolean(["echoOnM117"]) - - self._brokenM29 = self._settings.get_boolean(["brokenM29"]) - self._brokenResend = self._settings.get_boolean(["brokenResend"]) - - self._m115FormatString = self._settings.get(["m115FormatString"]) - self._firmwareName = self._settings.get(["firmwareName"]) - - self._okFormatString = self._settings.get(["okFormatString"]) - - self._capabilities = self._settings.get(["capabilities"], merged=True) - - self._temperature_reporter = None - self._sdstatus_reporter = None - - self.current_line = 0 - self.lastN = 0 - - self._incoming_lock = threading.RLock() - - self._debug_awol = False - self._debug_sleep = 0 - self._sleepAfterNext = {} - self._sleepAfter = {} - self._rerequest_last = False - - self._dont_answer = False - - self._debug_drop_connection = False - - self._action_hooks = plugin_manager().get_hooks("octoprint.plugin.virtual_printer.custom_action") - - self._killed = False - - self._triggerResendAt100 = True - self._triggerResendWithTimeoutAt105 = True - self._triggerResendWithMissingLinenoAt110 = True - self._triggerResendWithChecksumMismatchAt115 = True - - readThread = threading.Thread(target=self._processIncoming, name="octoprint.plugins.virtual_printer.wait_thread") - readThread.start() - - bufferThread = threading.Thread(target=self._processBuffer, name="octoprint.plugins.virtual_printer.buffer_thread") - bufferThread.start() - - def __str__(self): - return "VIRTUAL(read_timeout={read_timeout},write_timeout={write_timeout},options={options})"\ - .format(read_timeout=self._read_timeout, write_timeout=self._write_timeout, options=self._settings.get([])) - - def _reset(self): - with self._incoming_lock: - self._relative = True - self._lastX = 0.0 - self._lastY = 0.0 - self._lastZ = 0.0 - self._lastE = [0.0] * self.extruderCount - self._lastF = 200 - - self._unitModifier = 1 - self._feedrate_multiplier = 100 - self._flowrate_multiplier = 100 - - self._sdCardReady = True - self._sdPrinting = False - if self._sdPrinter: - self._sdPrinting = False - self._sdPrintingSemaphore.set() - self._sdPrinter = None - self._selectedSdFile = None - self._selectedSdFileSize = None - self._selectedSdFilePos = None - - if self._writingToSdHandle: - try: - self._writingToSdHandle.close() - except Exception: - pass - self._writingToSd = False - self._writingToSdHandle = None - self._newSdFilePos = None - - self._heatingUp = False - - self.current_line = 0 - self.lastN = 0 - - self._debug_awol = False - self._debug_sleep = 0 - self._sleepAfterNext.clear() - self._sleepAfter.clear() - - self._dont_answer = False - - self._debug_drop_connection = False - - self._killed = False - - self._triggerResendAt100 = True - self._triggerResendWithTimeoutAt105 = True - self._triggerResendWithMissingLinenoAt110 = True - self._triggerResendWithChecksumMismatchAt115 = True - - if self._temperature_reporter is not None: - self._temperature_reporter.cancel() - self._temperature_reporter = None - - if self._sdstatus_reporter is not None: - self._sdstatus_reporter.cancel() - self._sdstatus_reporter = None - - self._clearQueue(self.incoming) - self._clearQueue(self.outgoing) - self._clearQueue(self.buffered) - - if self._settings.get_boolean(["simulateReset"]): - for item in self._settings.get(["resetLines"]): - self._send(item + "\n") - - @property - def timeout(self): - return self._read_timeout - - @timeout.setter - def timeout(self, value): - self._logger.debug("Setting read timeout to {}s".format(value)) - self._read_timeout = value - - @property - def write_timeout(self): - return self._write_timeout - - @write_timeout.setter - def write_timeout(self, value): - self._logger.debug("Setting write timeout to {}s".format(value)) - self._write_timeout = value - - @property - def port(self): - return "VIRTUAL" - - @property - def baudrate(self): - return self._faked_baudrate - - # noinspection PyMethodMayBeStatic - def _clearQueue(self, q): - try: - while q.get(block=False): - q.task_done() - continue - except queue.Empty: - pass - - def _processIncoming(self): - next_wait_timeout = monotonic_time() + self._waitInterval - buf = b"" - while self.incoming is not None and not self._killed: - self._simulateTemps() - - if self._heatingUp: - time.sleep(1) - continue - - try: - data = self.incoming.get(timeout=0.01) - data = to_bytes(data, encoding="ascii", errors="replace") - self.incoming.task_done() - except queue.Empty: - if self._sendWait and monotonic_time() > next_wait_timeout: - self._send("wait") - next_wait_timeout = monotonic_time() + self._waitInterval - continue - except Exception: - if self.incoming is None: - # just got closed - break - - if data is not None: - buf += data - nl = buf.find(b"\n")+1 - if nl > 0: - data = buf[:nl] - buf = buf[nl:] - else: - continue - - next_wait_timeout = monotonic_time() + self._waitInterval - - if data is None: - continue - - if self._dont_answer: - self._dont_answer = False - continue - - # strip checksum - if b"*" in data: - checksum = int(data[data.rfind(b"*") + 1:]) - data = data[:data.rfind(b"*")] - if not checksum == self._calculate_checksum(data): - self._triggerResend(expected=self.current_line + 1) - continue - - self.current_line += 1 - elif self._settings.get_boolean(["forceChecksum"]): - self._send(self._error("checksum_missing")) - continue - - # track N = N + 1 - if data.startswith(b"N") and b"M110" in data: - linenumber = int(re.search(b"N([0-9]+)", data).group(1)) - self.lastN = linenumber - self.current_line = linenumber - - self._triggerResendAt100 = True - self._triggerResendWithTimeoutAt105 = True - - self._sendOk() - continue - elif data.startswith(b"N"): - linenumber = int(re.search(b"N([0-9]+)", data).group(1)) - expected = self.lastN + 1 - if linenumber != expected: - self._triggerResend(actual=linenumber) - continue - elif linenumber == 100 and self._triggerResendAt100: - # simulate a resend at line 100 - self._triggerResendAt100 = False - self._triggerResend(expected=100) - continue - elif linenumber == 105 and self._triggerResendWithTimeoutAt105 and not self._writingToSd: - # simulate a resend with timeout at line 105 - self._triggerResendWithTimeoutAt105 = False - self._triggerResend(expected=105) - self._dont_answer = True - self.lastN = linenumber - continue - elif linenumber == 110 and self._triggerResendWithMissingLinenoAt110 and not self._writingToSd: - self._triggerResendWithMissingLinenoAt110 = False - self._send(self._error("lineno_missing", self.lastN)) - continue - elif linenumber == 115 and self._triggerResendWithChecksumMismatchAt115 and not self._writingToSd: - self._triggerResendWithChecksumMismatchAt115 = False - self._triggerResend(checksum=True) - continue - elif len(self._prepared_errors): - prepared = self._prepared_errors.pop(0) - # noinspection PyCompatibility - if callable(prepared): - prepared(linenumber, self.lastN, data) - continue - elif isinstance(prepared, basestring): - self._send(prepared) - continue - elif self._rerequest_last: - self._triggerResend(actual=linenumber) - continue - else: - self.lastN = linenumber - data = data.split(None, 1)[1].strip() - - data += b"\n" - - data = to_unicode(data, encoding="ascii", errors="replace").strip() - - if data.startswith("!!DEBUG:") or data.strip() == "!!DEBUG": - debug_command = "" - if data.startswith("!!DEBUG:"): - debug_command = data[len("!!DEBUG:"):].strip() - self._debugTrigger(debug_command) - continue - - # shortcut for writing to SD - if self._writingToSd and self._writingToSdHandle is not None and not "M29" in data: - self._writingToSdHandle.write(data) - self._sendOk() - continue - - if data.strip() == "version": - from octoprint import __version__ - self._send("OctoPrint VirtualPrinter v" + __version__) - continue - - # if we are sending oks before command output, send it now - if len(data.strip()) > 0 and self._okBeforeCommandOutput: - self._sendOk() - - # actual command handling - command_match = VirtualPrinter.command_regex.match(data) - if command_match is not None: - command = command_match.group(0) - letter = command_match.group(1) - - try: - # if we have a method _gcode_G, _gcode_M or _gcode_T, execute that first - letter_handler = "_gcode_{}".format(letter) - if hasattr(self, letter_handler): - code = command_match.group(2) - handled = getattr(self, letter_handler)(code, data) - if handled: - continue - - # then look for a method _gcode_ and execute that if it exists - command_handler = "_gcode_{}".format(command) - if hasattr(self, command_handler): - handled = getattr(self, command_handler)(data) - if handled: - continue - - finally: - # make sure that the debug sleepAfter and sleepAfterNext stuff works even - # if we continued above - if len(self._sleepAfter) or len(self._sleepAfterNext): - interval = None - if command in self._sleepAfter: - interval = self._sleepAfter[command] - elif command in self._sleepAfterNext: - interval = self._sleepAfterNext[command] - del self._sleepAfterNext[command] - - if interval is not None: - self._send("// sleeping for {interval} seconds".format(interval=interval)) - time.sleep(interval) - - # if we are sending oks after command output, send it now - if len(data.strip()) > 0 and not self._okBeforeCommandOutput: - self._sendOk() - - self._logger.info("Closing down read loop") - - ##~~ command implementations - - # noinspection PyUnusedLocal - def _gcode_T(self, code, data): - # type: (str, str) -> None - t = int(code) - if 0 <= t < self.extruderCount: - self.currentExtruder = t - self._send("Active Extruder: %d" % self.currentExtruder) - else: - self._send("echo:T{} Invalid extruder ".format(t)) - - # noinspection PyUnusedLocal - def _gcode_F(self, code, data): - # type: (str, str) -> bool - if self._supportF: - self._send("echo:changed F value") - return False - else: - self._send(self._error("command_unknown", "F")) - return True - - def _gcode_M104(self, data): - # type: (str) -> None - self._parseHotendCommand(data) - - def _gcode_M109(self, data): - # type: (str) -> None - self._parseHotendCommand(data, wait=True, support_r=True) - - def _gcode_M140(self, data): - # type: (str) -> None - self._parseBedCommand(data) - - def _gcode_M190(self, data): - # type: (str) -> None - self._parseBedCommand(data, wait=True, support_r=True) - - def _gcode_M141(self, data): - self._parseChamberCommand(data) - - def _gcode_M191(self, data): - self._parseChamberCommand(data, wait=True, support_r=True) - - # noinspection PyUnusedLocal - def _gcode_M105(self, data): - # type: (str) -> bool - self._processTemperatureQuery() - return True - - # noinspection PyUnusedLocal - def _gcode_M20(self, data): - # type: (str) -> None - if self._sdCardReady: - self._listSd() - - # noinspection PyUnusedLocal - def _gcode_M21(self, data): - # type: (str) -> None - self._sdCardReady = True - self._send("SD card ok") - - # noinspection PyUnusedLocal - def _gcode_M22(self, data): - # type: (str) -> None - self._sdCardReady = False - - def _gcode_M23(self, data): - # type: (str) -> None - if self._sdCardReady: - filename = data.split(None, 1)[1].strip() - self._selectSdFile(filename) - - # noinspection PyUnusedLocal - def _gcode_M24(self, data): - # type: (str) -> None - if self._sdCardReady: - self._startSdPrint() - - # noinspection PyUnusedLocal - def _gcode_M25(self, data): - # type: (str) -> None - if self._sdCardReady: - self._pauseSdPrint() - - def _gcode_M26(self, data): - # type: (str) -> None - if self._sdCardReady: - pos = int(re.search(r"S([0-9]+)", data).group(1)) - self._setSdPos(pos) - - def _gcode_M27(self, data): - # type: (str) -> None - def report(): - if self._sdCardReady: - self._reportSdStatus() - - matchS = re.search(r"S([0-9]+)", data) - if matchS: - interval = int(matchS.group(1)) - if self._sdstatus_reporter is not None: - self._sdstatus_reporter.cancel() - - if interval > 0: - self._sdstatus_reporter = RepeatedTimer(interval, report) - self._sdstatus_reporter.start() - else: - self._sdstatus_reporter = None - - report() - - def _gcode_M28(self, data): - # type: (str) -> None - if self._sdCardReady: - filename = data.split(None, 1)[1].strip() - self._writeSdFile(filename) - - # noinspection PyUnusedLocal - def _gcode_M29(self, data): - # type: (str) -> None - if self._sdCardReady: - self._finishSdFile() - - def _gcode_M30(self, data): - # type: (str) -> None - if self._sdCardReady: - filename = data.split(None, 1)[1].strip() - self._deleteSdFile(filename) - - def _gcode_M33(self, data): - # type: (str) -> None - if self._sdCardReady: - filename = data.split(None, 1)[1].strip() - if filename.startswith("/"): - filename = filename[1:] - files = self._mappedSdList() - file = files.get(filename.lower()) - if file is not None: - self._send(file["name"]) - - def _gcode_M113(self, data): - # type: (str) -> None - matchS = re.search(r"S([0-9]+)", data) - if matchS is not None: - interval = int(matchS.group(1)) - if 0 <= interval <= 60: - self._busyInterval = interval - - # noinspection PyUnusedLocal - def _gcode_M114(self, data): - # type: (str) -> bool - m114FormatString = self._settings.get(["m114FormatString"]) - e = dict((index, value) for index, value in enumerate(self._lastE)) - e["current"] = self._lastE[self.currentExtruder] - e["all"] = " ".join(["E{}:{}".format(num, self._lastE[self.currentExtruder]) for num in range(self.extruderCount)]) - output = m114FormatString.format(x=self._lastX, - y=self._lastY, - z=self._lastZ, - e=e, - f=self._lastF, - a=int(self._lastX*100), - b=int(self._lastY*100), - c=int(self._lastZ*100)) - - if not self._okBeforeCommandOutput: - ok = self._ok() - if ok: - output = "{} {}".format(self._ok(), output) - self._send(output) - return True - - # noinspection PyUnusedLocal - def _gcode_M115(self, data): - # type: (str) -> None - output = self._m115FormatString.format(firmware_name=self._firmwareName) - self._send(output) - - if self._settings.get_boolean(["m115ReportCapabilities"]): - for cap, enabled in self._capabilities.items(): - self._send("Cap:{}:{}".format(cap.upper(), "1" if enabled else "0")) - - def _gcode_M117(self, data): - # type: (str) -> None - # we'll just use this to echo a message, to allow playing around with pause triggers - if self._echoOnM117: - self._send("echo:%s" % re.search(r"M117\s+(.*)", data).group(1)) - - def _gcode_M155(self, data): - # type: (str) -> None - matchS = re.search(r"S([0-9]+)", data) - if matchS is not None: - interval = int(matchS.group(1)) - if self._temperature_reporter is not None: - self._temperature_reporter.cancel() - - if interval > 0: - self._temperature_reporter = RepeatedTimer(interval, lambda: self._send(self._generateTemperatureOutput())) - self._temperature_reporter.start() - else: - self._temperature_reporter = None - - def _gcode_M220(self, data): - # type: (str) -> None - matchS = re.search(r"S([0-9]+)", data) - if matchS is not None: - self._feedrate_multiplier = float(matchS.group(1)) - - def _gcode_M221(self, data): - # type: (str) -> None - matchS = re.search(r"S([0-9]+)", data) - if matchS is not None: - self._flowrate_multiplier = float(matchS.group(1)) - - # noinspection PyUnusedLocal - def _gcode_M400(self, data): - # type: (str) -> None - self.buffered.join() - - # noinspection PyUnusedLocal - def _gcode_M600(self, data): - # type: (str) -> None - self._send("//action:paused") - self._showPrompt("Heater Timeout", ["Reheat",]) - self._setBusy("paused for user") - return True # handled as we don't want to send an ok now, only when finishing the busy - - # noinspection PyUnusedLocal - def _gcode_M876(self, data): - # type: (str) -> None - self._hidePrompt() - if self._busy == "paused for user": - self._busy = None - - # noinspection PyUnusedLocal - def _gcode_M999(self, data): - # type: (str) -> None - # mirror Marlin behaviour - self._send("Resend: 1") - - # noinspection PyUnusedLocal - def _gcode_G20(self, data): - # type: (str) -> None - self._unitModifier = 1.0 / 2.54 - if self._lastX is not None: - self._lastX *= 2.54 - if self._lastY is not None: - self._lastY *= 2.54 - if self._lastZ is not None: - self._lastZ *= 2.54 - if self._lastE is not None: - self._lastE = [e * 2.54 if e is not None else None for e in self._lastE] - - # noinspection PyUnusedLocal - def _gcode_G21(self, data): - # type: (str) -> None - self._unitModifier = 1.0 - if self._lastX is not None: - self._lastX /= 2.54 - if self._lastY is not None: - self._lastY /= 2.54 - if self._lastZ is not None: - self._lastZ /= 2.54 - if self._lastE is not None: - self._lastE = [e / 2.54 if e is not None else None for e in self._lastE] - - # noinspection PyUnusedLocal - def _gcode_G90(self, data): - # type: (str) -> None - self._relative = False - - # noinspection PyUnusedLocal - def _gcode_G91(self, data): - # type: (str) -> None - self._relative = True - - def _gcode_G92(self, data): - # type: (str) -> None - self._setPosition(data) - - def _gcode_G28(self, data): - # type: (str) -> None - self._home(data) - - def _gcode_G0(self, data): - # type: (str) -> None - # simulate reprap buffered commands via a Queue with maxsize which internally simulates the moves - self.buffered.put(data) - _gcode_G1 = _gcode_G0 - _gcode_G2 = _gcode_G0 - _gcode_G3 = _gcode_G0 - - def _gcode_G4(self, data): - # type: (str) -> None - matchS = re.search(r'S([0-9]+)', data) - matchP = re.search(r'P([0-9]+)', data) - - _timeout = 0 - if matchP: - _timeout = float(matchP.group(1)) / 1000.0 - elif matchS: - _timeout = float(matchS.group(1)) - - if self._sendBusy and self._busyInterval > 0: - until = monotonic_time() + _timeout - while monotonic_time() < until: - time.sleep(self._busyInterval) - self._send("busy:processing") - else: - time.sleep(_timeout) - - # noinspection PyUnusedLocal - def _gcode_G33(self, data): - # type: (str) -> None - self._send("G33 Auto Calibrate") - self._send("Will take ~60s") - timeout = 60 - - if self._sendBusy and self._busyInterval > 0: - until = monotonic_time() + timeout - while monotonic_time() < until: - time.sleep(self._busyInterval) - self._send("busy:processing") - else: - time.sleep(timeout) - - ##~~ further helpers - - # noinspection PyMethodMayBeStatic - def _calculate_checksum(self, line): - # type: (bytes) -> int - checksum = 0 - for c in bytearray(line): - checksum ^= c - return checksum - - def _kill(self): - if not self._supportM112: - return - self._killed = True - self._send("echo:EMERGENCY SHUTDOWN DETECTED. KILLED.") - - def _triggerResend(self, expected=None, actual=None, checksum=None): - # type: (int, int, int) -> None - with self._incoming_lock: - if expected is None: - expected = self.lastN + 1 - else: - self.lastN = expected - 1 - - if actual is None: - if checksum: - self._send(self._error("checksum_mismatch")) - else: - self._send(self._error("checksum_missing")) - else: - self._send(self._error("lineno_mismatch", expected, actual)) - - def request_resend(): - self._send("Resend:%d" % expected) - if not self._brokenResend: - self._sendOk() - - request_resend() - - def _debugTrigger(self, data): - # type: (str) -> None - if data == "" or data == "help" or data == "?": - usage = """ + self._errors = self._settings.get(["errors"], merged=True) + + self.currentExtruder = 0 + self.extruderCount = self._settings.get_int(["numExtruders"]) + self.pinnedExtruders = self._settings.get(["pinnedExtruders"]) + if self.pinnedExtruders is None: + self.pinnedExtruders = {} + self.sharedNozzle = self._settings.get_boolean(["sharedNozzle"]) + self.temperatureCount = 1 if self.sharedNozzle else self.extruderCount + + self._ambient_temperature = self._settings.get_float(["ambientTemperature"]) + + self.temp = [self._ambient_temperature] * self.temperatureCount + self.targetTemp = [0.0] * self.temperatureCount + self.bedTemp = self._ambient_temperature + self.bedTargetTemp = 0.0 + self.chamberTemp = self._ambient_temperature + self.chamberTargetTemp = 0.0 + self.lastTempAt = monotonic_time() + + self._relative = True + self._lastX = 0.0 + self._lastY = 0.0 + self._lastZ = 0.0 + self._lastE = [0.0] * self.extruderCount + self._lastF = 200 + + self._unitModifier = 1 + self._feedrate_multiplier = 100 + self._flowrate_multiplier = 100 + + self._virtualSd = self._settings.global_get_basefolder("virtualSd") + self._sdCardReady = True + self._sdPrinter = None + self._sdPrintingSemaphore = threading.Event() + self._selectedSdFile = None + self._selectedSdFileSize = None + self._selectedSdFilePos = None + + self._writingToSd = False + self._writingToSdHandle = None + self._newSdFilePos = None + + self._heatingUp = False + + self._okBeforeCommandOutput = self._settings.get_boolean( + ["okBeforeCommandOutput"] + ) + self._supportM112 = self._settings.get_boolean(["supportM112"]) + self._supportF = self._settings.get_boolean(["supportF"]) + + self._sendWait = self._settings.get_boolean(["sendWait"]) + self._sendBusy = self._settings.get_boolean(["sendBusy"]) + self._waitInterval = self._settings.get_float(["waitInterval"]) + self._busyInterval = self._settings.get_float(["busyInterval"]) + + self._busy = None + self._busy_loop = None + + self._echoOnM117 = self._settings.get_boolean(["echoOnM117"]) + + self._brokenM29 = self._settings.get_boolean(["brokenM29"]) + self._brokenResend = self._settings.get_boolean(["brokenResend"]) + + self._m115FormatString = self._settings.get(["m115FormatString"]) + self._firmwareName = self._settings.get(["firmwareName"]) + + self._okFormatString = self._settings.get(["okFormatString"]) + + self._capabilities = self._settings.get(["capabilities"], merged=True) + + self._temperature_reporter = None + self._sdstatus_reporter = None + + self.current_line = 0 + self.lastN = 0 + + self._incoming_lock = threading.RLock() + + self._debug_awol = False + self._debug_sleep = 0 + self._sleepAfterNext = {} + self._sleepAfter = {} + self._rerequest_last = False + + self._dont_answer = False + + self._debug_drop_connection = False + + self._action_hooks = plugin_manager().get_hooks( + "octoprint.plugin.virtual_printer.custom_action" + ) + + self._killed = False + + self._triggerResendAt100 = True + self._triggerResendWithTimeoutAt105 = True + self._triggerResendWithMissingLinenoAt110 = True + self._triggerResendWithChecksumMismatchAt115 = True + + readThread = threading.Thread( + target=self._processIncoming, + name="octoprint.plugins.virtual_printer.wait_thread", + ) + readThread.start() + + bufferThread = threading.Thread( + target=self._processBuffer, + name="octoprint.plugins.virtual_printer.buffer_thread", + ) + bufferThread.start() + + def __str__(self): + return "VIRTUAL(read_timeout={read_timeout},write_timeout={write_timeout},options={options})".format( + read_timeout=self._read_timeout, + write_timeout=self._write_timeout, + options=self._settings.get([]), + ) + + def _reset(self): + with self._incoming_lock: + self._relative = True + self._lastX = 0.0 + self._lastY = 0.0 + self._lastZ = 0.0 + self._lastE = [0.0] * self.extruderCount + self._lastF = 200 + + self._unitModifier = 1 + self._feedrate_multiplier = 100 + self._flowrate_multiplier = 100 + + self._sdCardReady = True + self._sdPrinting = False + if self._sdPrinter: + self._sdPrinting = False + self._sdPrintingSemaphore.set() + self._sdPrinter = None + self._selectedSdFile = None + self._selectedSdFileSize = None + self._selectedSdFilePos = None + + if self._writingToSdHandle: + try: + self._writingToSdHandle.close() + except Exception: + pass + self._writingToSd = False + self._writingToSdHandle = None + self._newSdFilePos = None + + self._heatingUp = False + + self.current_line = 0 + self.lastN = 0 + + self._debug_awol = False + self._debug_sleep = 0 + self._sleepAfterNext.clear() + self._sleepAfter.clear() + + self._dont_answer = False + + self._debug_drop_connection = False + + self._killed = False + + self._triggerResendAt100 = True + self._triggerResendWithTimeoutAt105 = True + self._triggerResendWithMissingLinenoAt110 = True + self._triggerResendWithChecksumMismatchAt115 = True + + if self._temperature_reporter is not None: + self._temperature_reporter.cancel() + self._temperature_reporter = None + + if self._sdstatus_reporter is not None: + self._sdstatus_reporter.cancel() + self._sdstatus_reporter = None + + self._clearQueue(self.incoming) + self._clearQueue(self.outgoing) + self._clearQueue(self.buffered) + + if self._settings.get_boolean(["simulateReset"]): + for item in self._settings.get(["resetLines"]): + self._send(item + "\n") + + @property + def timeout(self): + return self._read_timeout + + @timeout.setter + def timeout(self, value): + self._logger.debug("Setting read timeout to {}s".format(value)) + self._read_timeout = value + + @property + def write_timeout(self): + return self._write_timeout + + @write_timeout.setter + def write_timeout(self, value): + self._logger.debug("Setting write timeout to {}s".format(value)) + self._write_timeout = value + + @property + def port(self): + return "VIRTUAL" + + @property + def baudrate(self): + return self._faked_baudrate + + # noinspection PyMethodMayBeStatic + def _clearQueue(self, q): + try: + while q.get(block=False): + q.task_done() + continue + except queue.Empty: + pass + + def _processIncoming(self): + next_wait_timeout = monotonic_time() + self._waitInterval + buf = b"" + while self.incoming is not None and not self._killed: + self._simulateTemps() + + if self._heatingUp: + time.sleep(1) + continue + + try: + data = self.incoming.get(timeout=0.01) + data = to_bytes(data, encoding="ascii", errors="replace") + self.incoming.task_done() + except queue.Empty: + if self._sendWait and monotonic_time() > next_wait_timeout: + self._send("wait") + next_wait_timeout = monotonic_time() + self._waitInterval + continue + except Exception: + if self.incoming is None: + # just got closed + break + + if data is not None: + buf += data + nl = buf.find(b"\n") + 1 + if nl > 0: + data = buf[:nl] + buf = buf[nl:] + else: + continue + + next_wait_timeout = monotonic_time() + self._waitInterval + + if data is None: + continue + + if self._dont_answer: + self._dont_answer = False + continue + + # strip checksum + if b"*" in data: + checksum = int(data[data.rfind(b"*") + 1 :]) + data = data[: data.rfind(b"*")] + if not checksum == self._calculate_checksum(data): + self._triggerResend(expected=self.current_line + 1) + continue + + self.current_line += 1 + elif self._settings.get_boolean(["forceChecksum"]): + self._send(self._error("checksum_missing")) + continue + + # track N = N + 1 + if data.startswith(b"N") and b"M110" in data: + linenumber = int(re.search(b"N([0-9]+)", data).group(1)) + self.lastN = linenumber + self.current_line = linenumber + + self._triggerResendAt100 = True + self._triggerResendWithTimeoutAt105 = True + + self._sendOk() + continue + elif data.startswith(b"N"): + linenumber = int(re.search(b"N([0-9]+)", data).group(1)) + expected = self.lastN + 1 + if linenumber != expected: + self._triggerResend(actual=linenumber) + continue + elif linenumber == 100 and self._triggerResendAt100: + # simulate a resend at line 100 + self._triggerResendAt100 = False + self._triggerResend(expected=100) + continue + elif ( + linenumber == 105 + and self._triggerResendWithTimeoutAt105 + and not self._writingToSd + ): + # simulate a resend with timeout at line 105 + self._triggerResendWithTimeoutAt105 = False + self._triggerResend(expected=105) + self._dont_answer = True + self.lastN = linenumber + continue + elif ( + linenumber == 110 + and self._triggerResendWithMissingLinenoAt110 + and not self._writingToSd + ): + self._triggerResendWithMissingLinenoAt110 = False + self._send(self._error("lineno_missing", self.lastN)) + continue + elif ( + linenumber == 115 + and self._triggerResendWithChecksumMismatchAt115 + and not self._writingToSd + ): + self._triggerResendWithChecksumMismatchAt115 = False + self._triggerResend(checksum=True) + continue + elif len(self._prepared_errors): + prepared = self._prepared_errors.pop(0) + # noinspection PyCompatibility + if callable(prepared): + prepared(linenumber, self.lastN, data) + continue + elif isinstance(prepared, basestring): + self._send(prepared) + continue + elif self._rerequest_last: + self._triggerResend(actual=linenumber) + continue + else: + self.lastN = linenumber + data = data.split(None, 1)[1].strip() + + data += b"\n" + + data = to_unicode(data, encoding="ascii", errors="replace").strip() + + if data.startswith("!!DEBUG:") or data.strip() == "!!DEBUG": + debug_command = "" + if data.startswith("!!DEBUG:"): + debug_command = data[len("!!DEBUG:") :].strip() + self._debugTrigger(debug_command) + continue + + # shortcut for writing to SD + if ( + self._writingToSd + and self._writingToSdHandle is not None + and not "M29" in data + ): + self._writingToSdHandle.write(data) + self._sendOk() + continue + + if data.strip() == "version": + from octoprint import __version__ + + self._send("OctoPrint VirtualPrinter v" + __version__) + continue + + # if we are sending oks before command output, send it now + if len(data.strip()) > 0 and self._okBeforeCommandOutput: + self._sendOk() + + # actual command handling + command_match = VirtualPrinter.command_regex.match(data) + if command_match is not None: + command = command_match.group(0) + letter = command_match.group(1) + + try: + # if we have a method _gcode_G, _gcode_M or _gcode_T, execute that first + letter_handler = "_gcode_{}".format(letter) + if hasattr(self, letter_handler): + code = command_match.group(2) + handled = getattr(self, letter_handler)(code, data) + if handled: + continue + + # then look for a method _gcode_ and execute that if it exists + command_handler = "_gcode_{}".format(command) + if hasattr(self, command_handler): + handled = getattr(self, command_handler)(data) + if handled: + continue + + finally: + # make sure that the debug sleepAfter and sleepAfterNext stuff works even + # if we continued above + if len(self._sleepAfter) or len(self._sleepAfterNext): + interval = None + if command in self._sleepAfter: + interval = self._sleepAfter[command] + elif command in self._sleepAfterNext: + interval = self._sleepAfterNext[command] + del self._sleepAfterNext[command] + + if interval is not None: + self._send( + "// sleeping for {interval} seconds".format( + interval=interval + ) + ) + time.sleep(interval) + + # if we are sending oks after command output, send it now + if len(data.strip()) > 0 and not self._okBeforeCommandOutput: + self._sendOk() + + self._logger.info("Closing down read loop") + + ##~~ command implementations + + # noinspection PyUnusedLocal + def _gcode_T(self, code, data): + # type: (str, str) -> None + t = int(code) + if 0 <= t < self.extruderCount: + self.currentExtruder = t + self._send("Active Extruder: %d" % self.currentExtruder) + else: + self._send("echo:T{} Invalid extruder ".format(t)) + + # noinspection PyUnusedLocal + def _gcode_F(self, code, data): + # type: (str, str) -> bool + if self._supportF: + self._send("echo:changed F value") + return False + else: + self._send(self._error("command_unknown", "F")) + return True + + def _gcode_M104(self, data): + # type: (str) -> None + self._parseHotendCommand(data) + + def _gcode_M109(self, data): + # type: (str) -> None + self._parseHotendCommand(data, wait=True, support_r=True) + + def _gcode_M140(self, data): + # type: (str) -> None + self._parseBedCommand(data) + + def _gcode_M190(self, data): + # type: (str) -> None + self._parseBedCommand(data, wait=True, support_r=True) + + def _gcode_M141(self, data): + self._parseChamberCommand(data) + + def _gcode_M191(self, data): + self._parseChamberCommand(data, wait=True, support_r=True) + + # noinspection PyUnusedLocal + def _gcode_M105(self, data): + # type: (str) -> bool + self._processTemperatureQuery() + return True + + # noinspection PyUnusedLocal + def _gcode_M20(self, data): + # type: (str) -> None + if self._sdCardReady: + self._listSd() + + # noinspection PyUnusedLocal + def _gcode_M21(self, data): + # type: (str) -> None + self._sdCardReady = True + self._send("SD card ok") + + # noinspection PyUnusedLocal + def _gcode_M22(self, data): + # type: (str) -> None + self._sdCardReady = False + + def _gcode_M23(self, data): + # type: (str) -> None + if self._sdCardReady: + filename = data.split(None, 1)[1].strip() + self._selectSdFile(filename) + + # noinspection PyUnusedLocal + def _gcode_M24(self, data): + # type: (str) -> None + if self._sdCardReady: + self._startSdPrint() + + # noinspection PyUnusedLocal + def _gcode_M25(self, data): + # type: (str) -> None + if self._sdCardReady: + self._pauseSdPrint() + + def _gcode_M26(self, data): + # type: (str) -> None + if self._sdCardReady: + pos = int(re.search(r"S([0-9]+)", data).group(1)) + self._setSdPos(pos) + + def _gcode_M27(self, data): + # type: (str) -> None + def report(): + if self._sdCardReady: + self._reportSdStatus() + + matchS = re.search(r"S([0-9]+)", data) + if matchS: + interval = int(matchS.group(1)) + if self._sdstatus_reporter is not None: + self._sdstatus_reporter.cancel() + + if interval > 0: + self._sdstatus_reporter = RepeatedTimer(interval, report) + self._sdstatus_reporter.start() + else: + self._sdstatus_reporter = None + + report() + + def _gcode_M28(self, data): + # type: (str) -> None + if self._sdCardReady: + filename = data.split(None, 1)[1].strip() + self._writeSdFile(filename) + + # noinspection PyUnusedLocal + def _gcode_M29(self, data): + # type: (str) -> None + if self._sdCardReady: + self._finishSdFile() + + def _gcode_M30(self, data): + # type: (str) -> None + if self._sdCardReady: + filename = data.split(None, 1)[1].strip() + self._deleteSdFile(filename) + + def _gcode_M33(self, data): + # type: (str) -> None + if self._sdCardReady: + filename = data.split(None, 1)[1].strip() + if filename.startswith("/"): + filename = filename[1:] + files = self._mappedSdList() + file = files.get(filename.lower()) + if file is not None: + self._send(file["name"]) + + def _gcode_M113(self, data): + # type: (str) -> None + matchS = re.search(r"S([0-9]+)", data) + if matchS is not None: + interval = int(matchS.group(1)) + if 0 <= interval <= 60: + self._busyInterval = interval + + # noinspection PyUnusedLocal + def _gcode_M114(self, data): + # type: (str) -> bool + m114FormatString = self._settings.get(["m114FormatString"]) + e = dict((index, value) for index, value in enumerate(self._lastE)) + e["current"] = self._lastE[self.currentExtruder] + e["all"] = " ".join( + [ + "E{}:{}".format(num, self._lastE[self.currentExtruder]) + for num in range(self.extruderCount) + ] + ) + output = m114FormatString.format( + x=self._lastX, + y=self._lastY, + z=self._lastZ, + e=e, + f=self._lastF, + a=int(self._lastX * 100), + b=int(self._lastY * 100), + c=int(self._lastZ * 100), + ) + + if not self._okBeforeCommandOutput: + ok = self._ok() + if ok: + output = "{} {}".format(self._ok(), output) + self._send(output) + return True + + # noinspection PyUnusedLocal + def _gcode_M115(self, data): + # type: (str) -> None + output = self._m115FormatString.format(firmware_name=self._firmwareName) + self._send(output) + + if self._settings.get_boolean(["m115ReportCapabilities"]): + for cap, enabled in self._capabilities.items(): + self._send("Cap:{}:{}".format(cap.upper(), "1" if enabled else "0")) + + def _gcode_M117(self, data): + # type: (str) -> None + # we'll just use this to echo a message, to allow playing around with pause triggers + if self._echoOnM117: + self._send("echo:%s" % re.search(r"M117\s+(.*)", data).group(1)) + + def _gcode_M155(self, data): + # type: (str) -> None + matchS = re.search(r"S([0-9]+)", data) + if matchS is not None: + interval = int(matchS.group(1)) + if self._temperature_reporter is not None: + self._temperature_reporter.cancel() + + if interval > 0: + self._temperature_reporter = RepeatedTimer( + interval, lambda: self._send(self._generateTemperatureOutput()) + ) + self._temperature_reporter.start() + else: + self._temperature_reporter = None + + def _gcode_M220(self, data): + # type: (str) -> None + matchS = re.search(r"S([0-9]+)", data) + if matchS is not None: + self._feedrate_multiplier = float(matchS.group(1)) + + def _gcode_M221(self, data): + # type: (str) -> None + matchS = re.search(r"S([0-9]+)", data) + if matchS is not None: + self._flowrate_multiplier = float(matchS.group(1)) + + # noinspection PyUnusedLocal + def _gcode_M400(self, data): + # type: (str) -> None + self.buffered.join() + + # noinspection PyUnusedLocal + def _gcode_M600(self, data): + # type: (str) -> None + self._send("//action:paused") + self._showPrompt( + "Heater Timeout", + [ + "Reheat", + ], + ) + self._setBusy("paused for user") + return True # handled as we don't want to send an ok now, only when finishing the busy + + # noinspection PyUnusedLocal + def _gcode_M876(self, data): + # type: (str) -> None + self._hidePrompt() + if self._busy == "paused for user": + self._busy = None + + # noinspection PyUnusedLocal + def _gcode_M999(self, data): + # type: (str) -> None + # mirror Marlin behaviour + self._send("Resend: 1") + + # noinspection PyUnusedLocal + def _gcode_G20(self, data): + # type: (str) -> None + self._unitModifier = 1.0 / 2.54 + if self._lastX is not None: + self._lastX *= 2.54 + if self._lastY is not None: + self._lastY *= 2.54 + if self._lastZ is not None: + self._lastZ *= 2.54 + if self._lastE is not None: + self._lastE = [e * 2.54 if e is not None else None for e in self._lastE] + + # noinspection PyUnusedLocal + def _gcode_G21(self, data): + # type: (str) -> None + self._unitModifier = 1.0 + if self._lastX is not None: + self._lastX /= 2.54 + if self._lastY is not None: + self._lastY /= 2.54 + if self._lastZ is not None: + self._lastZ /= 2.54 + if self._lastE is not None: + self._lastE = [e / 2.54 if e is not None else None for e in self._lastE] + + # noinspection PyUnusedLocal + def _gcode_G90(self, data): + # type: (str) -> None + self._relative = False + + # noinspection PyUnusedLocal + def _gcode_G91(self, data): + # type: (str) -> None + self._relative = True + + def _gcode_G92(self, data): + # type: (str) -> None + self._setPosition(data) + + def _gcode_G28(self, data): + # type: (str) -> None + self._home(data) + + def _gcode_G0(self, data): + # type: (str) -> None + # simulate reprap buffered commands via a Queue with maxsize which internally simulates the moves + self.buffered.put(data) + + _gcode_G1 = _gcode_G0 + _gcode_G2 = _gcode_G0 + _gcode_G3 = _gcode_G0 + + def _gcode_G4(self, data): + # type: (str) -> None + matchS = re.search(r"S([0-9]+)", data) + matchP = re.search(r"P([0-9]+)", data) + + _timeout = 0 + if matchP: + _timeout = float(matchP.group(1)) / 1000.0 + elif matchS: + _timeout = float(matchS.group(1)) + + if self._sendBusy and self._busyInterval > 0: + until = monotonic_time() + _timeout + while monotonic_time() < until: + time.sleep(self._busyInterval) + self._send("busy:processing") + else: + time.sleep(_timeout) + + # noinspection PyUnusedLocal + def _gcode_G33(self, data): + # type: (str) -> None + self._send("G33 Auto Calibrate") + self._send("Will take ~60s") + timeout = 60 + + if self._sendBusy and self._busyInterval > 0: + until = monotonic_time() + timeout + while monotonic_time() < until: + time.sleep(self._busyInterval) + self._send("busy:processing") + else: + time.sleep(timeout) + + ##~~ further helpers + + # noinspection PyMethodMayBeStatic + def _calculate_checksum(self, line): + # type: (bytes) -> int + checksum = 0 + for c in bytearray(line): + checksum ^= c + return checksum + + def _kill(self): + if not self._supportM112: + return + self._killed = True + self._send("echo:EMERGENCY SHUTDOWN DETECTED. KILLED.") + + def _triggerResend(self, expected=None, actual=None, checksum=None): + # type: (int, int, int) -> None + with self._incoming_lock: + if expected is None: + expected = self.lastN + 1 + else: + self.lastN = expected - 1 + + if actual is None: + if checksum: + self._send(self._error("checksum_mismatch")) + else: + self._send(self._error("checksum_missing")) + else: + self._send(self._error("lineno_mismatch", expected, actual)) + + def request_resend(): + self._send("Resend:%d" % expected) + if not self._brokenResend: + self._sendOk() + + request_resend() + + def _debugTrigger(self, data): + # type: (str) -> None + if data == "" or data == "help" or data == "?": + usage = """ OctoPrint Virtual Printer debug commands help @@ -913,802 +982,889 @@ class VirtualPrinter(object): unbusy | Unsets the busy loop. """ - for line in usage.split("\n"): - self._send("echo: {}".format(line.strip())) - elif data == "action_pause": - self._send("// action:pause") - elif data == "action_resume": - self._send("// action:resume") - elif data == "action_disconnect": - self._send("// action:disconnect") - elif data == "dont_answer": - self._dont_answer = True - elif data == "trigger_resend_lineno": - self._prepared_errors.append(lambda cur, last, ln: self._triggerResend(expected=last, actual=last+1)) - elif data == "trigger_resend_checksum": - self._prepared_errors.append(lambda cur, last, ln: self._triggerResend(expected=last, checksum=True)) - elif data == "trigger_missing_checksum": - self._prepared_errors.append(lambda cur, last, ln: self._triggerResend(expected=last, checksum=False)) - elif data == "trigger_missing_lineno": - self._prepared_errors.append(lambda cur, last, ln: self._send(self._error("lineno_missing", last))) - elif data == "trigger_fatal_error_marlin": - self._send("Error:Thermal Runaway, system stopped! Heater_ID: bed") - self._send("Error:Printer halted. kill() called!") - elif data == "trigger_fatal_error_repetier": - self._send("fatal: Heater/sensor error - Printer stopped and heaters disabled due to this error. Fix error and restart with M999.") - elif data == "drop_connection": - self._debug_drop_connection = True - elif data == "reset": - self._reset() - elif data == "unbusy": - self._setUnbusy() - elif data == "mintemp_error": - self._send(self._error("mintemp")) - elif data == "maxtemp_error": - self._send(self._error("maxtemp")) - elif data == "go_awol": - self._send("// Going AWOL") - self._debug_awol = True - elif data == "rerequest_last": - self._send("// Entering rerequest loop") - self._rerequest_last = True - elif data == "cancel_sd": - if self._sdPrinting and self._sdPrinter: - self._pauseSdPrint() - self._sdPrinting = False - self._sdPrintingSemaphore.set() - self._sdPrinter.join() - self._finishSdPrint() - else: - try: - sleep_match = VirtualPrinter.sleep_regex.match(data) - sleep_after_match = VirtualPrinter.sleep_after_regex.match(data) - sleep_after_next_match = VirtualPrinter.sleep_after_next_regex.match(data) - custom_action_match = VirtualPrinter.custom_action_regex.match(data) - prepare_ok_match = VirtualPrinter.prepare_ok_regex.match(data) - send_match = VirtualPrinter.send_regex.match(data) - set_ambient_match = VirtualPrinter.set_ambient_regex.match(data) - start_sd_match = VirtualPrinter.start_sd_regex.match(data) - select_sd_match = VirtualPrinter.select_sd_regex.match(data) - - if sleep_match is not None: - interval = int(sleep_match.group(1)) - self._send("// sleeping for {interval} seconds".format(interval=interval)) - self._debug_sleep = interval - elif sleep_after_match is not None: - command = sleep_after_match.group(1) - interval = int(sleep_after_match.group(2)) - self._sleepAfter[command] = interval - self._send("// going to sleep {interval} seconds after each {command}".format(**locals())) - elif sleep_after_next_match is not None: - command = sleep_after_next_match.group(1) - interval = int(sleep_after_next_match.group(2)) - self._sleepAfterNext[command] = interval - self._send("// going to sleep {interval} seconds after next {command}".format(**locals())) - elif custom_action_match is not None: - action = custom_action_match.group(1) - params = custom_action_match.group(2) - params = params.strip() if params is not None else "" - self._send("// action:{action} {params}".format(**locals()).strip()) - elif prepare_ok_match is not None: - ok = prepare_ok_match.group(1) - self._prepared_oks.append(ok) - elif send_match is not None: - self._send(send_match.group(1)) - elif set_ambient_match is not None: - self._ambient_temperature = float(set_ambient_match.group(1)) - self._send("// set ambient temperature to {}".format(self._ambient_temperature)) - elif start_sd_match is not None: - self._selectSdFile(start_sd_match.group(1), check_already_open=True) - self._startSdPrint() - elif select_sd_match is not None: - self._selectSdFile(select_sd_match.group(1)) - except Exception: - self._logger.exception("While handling %r", data) - - def _listSd(self): - if self._settings.get_boolean(["sdFiles", "size"]): - if self._settings.get_boolean(["sdFiles", "longname"]): - line = "{dosname} {size} {name}" - else: - line = "{dosname} {size}" - else: - line = "{dosname}" - - files = self._mappedSdList() - items = map(lambda x: line.format(**x), files.values()) - - self._send("Begin file list") - for item in items: - self._send(item) - self._send("End file list") - - def _mappedSdList(self): - # type: () -> collections.OrderedDict - result = collections.OrderedDict() - for entry in scandir(self._virtualSd): - if not entry.is_file(): - continue - dosname = get_dos_filename(entry.name, existing_filenames=list(result.keys())).lower() - result[dosname] = {"name": entry.name, - "path": entry.path, - "dosname": dosname, - "size": entry.stat().st_size} - return result - - def _selectSdFile(self, filename, check_already_open=False): - # type: (str, bool) -> None - if filename.startswith("/"): - filename = filename[1:] - - files = self._mappedSdList() - file = files.get(filename) - if file is None or not os.path.exists(file["path"]) or not os.path.isfile(file["path"]): - self._send("open failed, File: %s." % filename) - return - - if self._selectedSdFile == file["path"] and check_already_open: - return - - self._selectedSdFile = file["path"] - self._selectedSdFileSize = file["size"] - if self._settings.get_boolean(["includeFilenameInOpened"]): - self._send("File opened: %s Size: %d" % (filename, self._selectedSdFileSize)) - else: - self._send("File opened") - self._send("File selected") - - def _startSdPrint(self): - if self._selectedSdFile is not None: - if self._sdPrinter is None: - self._sdPrinting = True - self._sdPrinter = threading.Thread(target=self._sdPrintingWorker) - self._sdPrinter.start() - self._sdPrintingSemaphore.set() - - def _pauseSdPrint(self): - self._sdPrintingSemaphore.clear() - - def _setSdPos(self, pos): - self._newSdFilePos = pos - - def _reportSdStatus(self): - if self._sdPrinter is not None and self._sdPrintingSemaphore.is_set: - self._send("SD printing byte %d/%d" % (self._selectedSdFilePos, self._selectedSdFileSize)) - else: - self._send("Not SD printing") - - def _generateTemperatureOutput(self): - # type: () -> str - if self._settings.get_boolean(["repetierStyleTargetTemperature"]): - template = self._settings.get(["m105NoTargetFormatString"]) - else: - template = self._settings.get(["m105TargetFormatString"]) - - temps = collections.OrderedDict() - - # send simulated temperature data - if self.temperatureCount > 1: - if self._settings.get_boolean(["smoothieTemperatureReporting"]): - temps["T"] = (self.temp[0], self.targetTemp[0]) - elif self._settings.get_boolean(["includeCurrentToolInTemps"]): - temps["T"] = (self.temp[self.currentExtruder], self.targetTemp[self.currentExtruder]) - - for i in range(len(self.temp)): - if i == 0 and self._settings.get_boolean(["smoothieTemperatureReporting"]): - continue - temps["T{}".format(i)] = (self.temp[i], self.targetTemp[i]) - - if self._settings.get_boolean(["hasBed"]): - temps["B"] = (self.bedTemp, self.bedTargetTemp) - - if self._settings.get_boolean(["hasChamber"]): - temps["C"] = (self.chamberTemp, self.chamberTargetTemp) - - else: - heater = "T" - if self._settings.get_boolean(["klipperTemperatureReporting"]): - heater = "T0" - - temps[heater] = (self.temp[0], self.targetTemp[0]) - - if self._settings.get_boolean(["hasBed"]): - temps["B"] = (self.bedTemp, self.bedTargetTemp) - - if self._settings.get_boolean(["hasChamber"]): - temps["C"] = (self.chamberTemp, self.chamberTargetTemp) - - output = " ".join(map(lambda x: template.format(heater=x[0], actual=x[1][0], target=x[1][1]), temps.items())) - output += " @:64\n" - return output - - def _processTemperatureQuery(self): - includeOk = not self._okBeforeCommandOutput - output = self._generateTemperatureOutput() - - if includeOk: - ok = self._ok() - if ok: - output = "{} {}".format(ok, output) - self._send(output) - - def _parseHotendCommand(self, line, wait=False, support_r=False): - # type: (str, bool, bool) -> None - only_wait_if_higher = True - tool = 0 - toolMatch = re.search(r'T([0-9]+)', line) - if toolMatch: - tool = int(toolMatch.group(1)) - - if tool >= self.temperatureCount: - return - - try: - self.targetTemp[tool] = float(re.search(r'S([0-9]+)', line).group(1)) - except Exception: - if support_r: - try: - self.targetTemp[tool] = float(re.search(r'R([0-9]+)', line).group(1)) - only_wait_if_higher = False - except Exception: - pass - - if wait: - self._waitForHeatup("tool%d" % tool, only_wait_if_higher) - if self._settings.get_boolean(["repetierStyleTargetTemperature"]): - self._send("TargetExtr%d:%d" % (tool, self.targetTemp[tool])) - - def _parseBedCommand(self, line, wait=False, support_r=False): - # type: (str, bool, bool) -> None - if not self._settings.get_boolean(["hasBed"]): - return - - only_wait_if_higher = True - try: - self.bedTargetTemp = float(re.search(r'S([0-9]+)', line).group(1)) - except Exception: - if support_r: - try: - self.bedTargetTemp = float(re.search(r'R([0-9]+)', line).group(1)) - only_wait_if_higher = False - except Exception: - pass - - if wait: - self._waitForHeatup("bed", only_wait_if_higher) - if self._settings.get_boolean(["repetierStyleTargetTemperature"]): - self._send("TargetBed:%d" % self.bedTargetTemp) - - def _parseChamberCommand(self, line, wait=False, support_r=False): - if not self._settings.get_boolean(["hasChamber"]): - return - - only_wait_if_higher = True - try: - self.chamberTargetTemp = float(re.search('S([0-9]+)', line).group(1)) - except: - if support_r: - try: - self.chamberTargetTemp = float(re.search('R([0-9]+)', line).group(1)) - only_wait_if_higher = False - except: - pass - - if wait: - self._waitForHeatup("chamber", only_wait_if_higher) - - def _performMove(self, line): - # type: (str) -> None - matchX = re.search(r"X(-?[0-9.]+)", line) - matchY = re.search(r"Y(-?[0-9.]+)", line) - matchZ = re.search(r"Z(-?[0-9.]+)", line) - matchE = re.search(r"E(-?[0-9.]+)", line) - matchF = re.search(r"F([0-9.]+)", line) - - duration = 0.0 - if matchF is not None: - try: - self._lastF = float(matchF.group(1)) - except ValueError: - pass - - speedXYZ = self._lastF * (self._feedrate_multiplier / 100.0) - speedE = self._lastF * (self._flowrate_multiplier / 100.0) - if speedXYZ == 0: - speedXYZ = 999999999999 - if speedE == 0: - speedE = 999999999999 - - if matchX is not None: - try: - x = float(matchX.group(1)) - except ValueError: - pass - else: - if self._relative or self._lastX is None: - duration = max(duration, x * self._unitModifier / speedXYZ * 60.0) - else: - duration = max(duration, (x - self._lastX) * self._unitModifier / speedXYZ * 60.0) - - if self._relative and self._lastX is not None: - self._lastX += x - else: - self._lastX = x - if matchY is not None: - try: - y = float(matchY.group(1)) - except ValueError: - pass - else: - if self._relative or self._lastY is None: - duration = max(duration, y * self._unitModifier / speedXYZ * 60.0) - else: - duration = max(duration, (y - self._lastY) * self._unitModifier / speedXYZ * 60.0) - - if self._relative and self._lastY is not None: - self._lastY += y - else: - self._lastY = y - if matchZ is not None: - try: - z = float(matchZ.group(1)) - except ValueError: - pass - else: - if self._relative or self._lastZ is None: - duration = max(duration, z * self._unitModifier / speedXYZ * 60.0) - else: - duration = max(duration, (z - self._lastZ) * self._unitModifier / speedXYZ * 60.0) - - if self._relative and self._lastZ is not None: - self._lastZ += z - else: - self._lastZ = z - if matchE is not None: - try: - e = float(matchE.group(1)) - except ValueError: - pass - else: - lastE = self._lastE[self.currentExtruder] - if self._relative or lastE is None: - duration = max(duration, e * self._unitModifier / speedE * 60.0) - else: - duration = max(duration, (e - lastE) * self._unitModifier / speedE * 60.0) - - if self._relative and lastE is not None: - self._lastE[self.currentExtruder] += e - else: - self._lastE[self.currentExtruder] = e - - if duration: - duration *= 0.1 - if duration > self._read_timeout: - slept = 0 - while duration - slept > self._read_timeout and not self._killed: - time.sleep(self._read_timeout) - slept += self._read_timeout - else: - time.sleep(duration) - - def _setPosition(self, line): - # type: (str) -> None - matchX = re.search(r"X(-?[0-9.]+)", line) - matchY = re.search(r"Y(-?[0-9.]+)", line) - matchZ = re.search(r"Z(-?[0-9.]+)", line) - matchE = re.search(r"E(-?[0-9.]+)", line) - - if matchX is None and matchY is None and matchZ is None and matchE is None: - self._lastX = self._lastY = self._lastZ = self._lastE[self.currentExtruder] = 0 - else: - if matchX is not None: - try: - self._lastX = float(matchX.group(1)) - except ValueError: - pass - if matchY is not None: - try: - self._lastY = float(matchY.group(1)) - except ValueError: - pass - if matchZ is not None: - try: - self._lastZ = float(matchZ.group(1)) - except ValueError: - pass - if matchE is not None: - try: - self._lastE[self.currentExtruder] = float(matchE.group(1)) - except ValueError: - pass - - def _home(self, line): - x = y = z = e = None - - if "X" in line: - x = True - if "Y" in line: - y = True - if "Z" in line: - z = True - if "E" in line: - e = True - - if x is None and y is None and z is None and e is None: - self._lastX = self._lastY = self._lastZ = self._lastE[self.currentExtruder] = 0 - else: - if x: - self._lastX = 0 - if y: - self._lastY = 0 - if z: - self._lastZ = 0 - if e: - self._lastE = 0 - - def _writeSdFile(self, filename): - # type: (str) -> None - filename = filename - if filename.startswith("/"): - filename = filename[1:] - file = os.path.join(self._virtualSd, filename).lower() - if os.path.exists(file): - if os.path.isfile(file): - os.remove(file) - else: - self._send("error writing to file") - - handle = None - try: - handle = io.open(file, 'wt', encoding='utf-8') - except Exception: - self._send("error writing to file") - self._writingToSdHandle = handle - self._writingToSd = True - self._selectedSdFile = file - self._send("Writing to file: %s" % filename) - - def _finishSdFile(self): - try: - self._writingToSdHandle.close() - except Exception: - pass - finally: - self._writingToSdHandle = None - self._writingToSd = False - self._selectedSdFile = None - self._send("Done saving file") - - def _sdPrintingWorker(self): - self._selectedSdFilePos = 0 - try: - with io.open(self._selectedSdFile, 'rt', encoding='utf-8') as f: - for line in iter(f.readline, ""): - if self._killed or not self._sdPrinting: - break - - # reset position if requested by client - if self._newSdFilePos is not None: - f.seek(self._newSdFilePos) - self._newSdFilePos = None - - # read current file position - self._selectedSdFilePos = f.tell() - - # if we are paused, wait for resuming - self._sdPrintingSemaphore.wait() - if self._killed or not self._sdPrinting: - break - - # set target temps - if 'M104' in line or 'M109' in line: - self._parseHotendCommand(line, wait='M109' in line) - elif 'M140' in line or 'M190' in line: - self._parseBedCommand(line, wait='M190' in line) - elif line.startswith("G0") or line.startswith("G1") or line.startswith("G2") or line.startswith("G3"): - # simulate reprap buffered commands via a Queue with maxsize which internally simulates the moves - self.buffered.put(line) - - except AttributeError: - if self.outgoing is not None: - raise - - self._finishSdPrint() - - def _finishSdPrint(self): - if not self._killed: - self._sdPrintingSemaphore.clear() - self._send("Done printing file") - self._selectedSdFilePos = 0 - self._sdPrinting = False - self._sdPrinter = None - - def _waitForHeatup(self, heater, only_wait_if_higher): - # type: (str, bool) -> None - delta = 1 - delay = 1 - last_busy = monotonic_time() - - self._heatingUp = True - try: - if heater.startswith("tool"): - toolNum = int(heater[len("tool"):]) - test = lambda: self.temp[toolNum] < self.targetTemp[toolNum] - delta or (not only_wait_if_higher and self.temp[toolNum] > self.targetTemp[toolNum] + delta) - output = lambda: "T:%0.2f" % self.temp[toolNum] - elif heater == "bed": - test = lambda: self.bedTemp < self.bedTargetTemp - delta or (not only_wait_if_higher and self.bedTemp > self.bedTargetTemp + delta) - output = lambda: "B:%0.2f" % self.bedTemp - elif heater == "chamber": - test = lambda: self.chamberTemp < self.chamberTargetTemp - delta or (not only_wait_if_higher and self.chamberTemp > self.chamberTargetTemp + delta) - output = lambda: "C:%0.2f" % self.chamberTemp - else: - return - - while not self._killed and self._heatingUp and test(): - self._simulateTemps(delta=delta) - self._send(output()) - if self._sendBusy and monotonic_time() - last_busy >= self._busyInterval: - self._send("echo:busy: processing") - last_busy = monotonic_time() - time.sleep(delay) - except AttributeError: - if self.outgoing is not None: - raise - finally: - self._heatingUp = False - - def _deleteSdFile(self, filename): - # type: (str) -> None - if filename.startswith("/"): - filename = filename[1:] - files = self._mappedSdList() - file = files.get(filename) - if file is not None and os.path.exists(file["path"]) and os.path.isfile(file["path"]): - os.remove(file["path"]) - - def _simulateTemps(self, delta=0.5): - timeDiff = self.lastTempAt - monotonic_time() - self.lastTempAt = monotonic_time() - - def simulate(actual, target, ambient): - if target > 0: - goal = target - remaining = abs(actual - target) - if remaining > delta: - factor = 10 - elif remaining < delta: - factor = remaining - elif not target and abs(actual - ambient) > delta: - goal = ambient - factor = 2 - else: - return actual - - old = actual - actual += math.copysign(timeDiff * factor, goal - actual) - - if math.copysign(1, goal - old) != math.copysign(1, goal - actual): - actual = goal - - return actual - - for i in range(len(self.temp)): - if i in self.pinnedExtruders: - self.temp[i] = self.pinnedExtruders[i] - continue - self.temp[i] = simulate(self.temp[i], self.targetTemp[i], self._ambient_temperature) - self.bedTemp = simulate(self.bedTemp, self.bedTargetTemp, self._ambient_temperature) - self.chamberTemp = simulate(self.chamberTemp, self.chamberTargetTemp, self._ambient_temperature) - - def _processBuffer(self): - while self.buffered is not None: - try: - line = self.buffered.get(timeout=0.5) - except queue.Empty: - continue - - if line is None: - continue - - self._performMove(line) - self.buffered.task_done() - - self._logger.info("Closing down buffer loop") - - def _setBusy(self, reason="processing"): - if not self._sendBusy: - return - - def loop(): - while self._busy: - self._send("echo:busy {}".format(self._busy)) - time.sleep(self._busyInterval) - self._sendOk() - - self._busy = reason - self._busy_loop = threading.Thread(target=loop) - self._busy_loop.daemon = True - self._busy_loop.start() - - def _setUnbusy(self): - self._busy = None - - def _showPrompt(self, text, choices): - self._hidePrompt() - self._send("//action:prompt_begin {}".format(text)) - for choice in choices: - self._send("//action:prompt_button {}".format(choice)) - self._send("//action:prompt_show") - - def _hidePrompt(self): - self._send("//action:prompt_end") - - def write(self, data): - # type: (bytes) -> int - data = to_bytes(data, errors="replace") - u_data = to_unicode(data, errors="replace") - - if self._debug_awol: - return len(data) - - if self._debug_drop_connection: - self._logger.info("Debug drop of connection requested, raising SerialTimeoutException") - raise SerialTimeoutException() - - with self._incoming_lock: - if self.incoming is None or self.outgoing is None: - return 0 - - if b"M112" in data and self._supportM112: - self._seriallog.info("<<< {}".format(u_data)) - self._kill() - return len(data) - - try: - written = self.incoming.put(data, timeout=self._write_timeout, partial=True) - self._seriallog.info("<<< {}".format(u_data)) - return written - except queue.Full: - self._logger.info("Incoming queue is full, raising SerialTimeoutException") - raise SerialTimeoutException() - - def readline(self): - # type: () -> bytes - if self._debug_awol: - time.sleep(self._read_timeout) - return b"" - - if self._debug_drop_connection: - raise SerialTimeoutException() - - if self._debug_sleep > 0: - # if we are supposed to sleep, we sleep not longer than the read timeout - # (and then on the next call sleep again if there's time to sleep left) - sleep_for = min(self._debug_sleep, self._read_timeout) - self._debug_sleep -= sleep_for - time.sleep(sleep_for) - - if self._debug_sleep > 0: - # we slept the full read timeout, return an empty line - return b"" - - # otherwise our left over timeout is the read timeout minus what we already - # slept for - timeout = self._read_timeout - sleep_for - - else: - # use the full read timeout as timeout - timeout = self._read_timeout - - try: - # fetch a line from the queue, wait no longer than timeout - line = to_unicode(self.outgoing.get(timeout=timeout), errors="replace") - self._seriallog.info(u">>> {}".format(line.strip())) - self.outgoing.task_done() - return to_bytes(line) - except queue.Empty: - # queue empty? return empty line - return b"" - - def close(self): - self._killed = True - self.incoming = None - self.outgoing = None - self.buffered = None - - def _sendOk(self): - if self.outgoing is None: - return - ok = self._ok() - if ok: - self._send(ok) - - def _sendWaitAfterTimeout(self, timeout=5): - time.sleep(timeout) - if self.outgoing is not None: - self._send("wait") - - def _send(self, line): - # type: (str) -> None - if self.outgoing is not None: - self.outgoing.put(line) - - def _ok(self): - ok = self._okFormatString - if self._prepared_oks: - ok = self._prepared_oks.pop(0) - if ok is None: - return ok - - return ok.format(ok, lastN=self.lastN, buffer=self.buffered.maxsize - self.buffered.qsize()) - - def _error(self, error, *args, **kwargs): - # type: (str, Any, Any) -> str - return "Error: {}".format(self._errors.get(error).format(*args, **kwargs)) + for line in usage.split("\n"): + self._send("echo: {}".format(line.strip())) + elif data == "action_pause": + self._send("// action:pause") + elif data == "action_resume": + self._send("// action:resume") + elif data == "action_disconnect": + self._send("// action:disconnect") + elif data == "dont_answer": + self._dont_answer = True + elif data == "trigger_resend_lineno": + self._prepared_errors.append( + lambda cur, last, ln: self._triggerResend(expected=last, actual=last + 1) + ) + elif data == "trigger_resend_checksum": + self._prepared_errors.append( + lambda cur, last, ln: self._triggerResend(expected=last, checksum=True) + ) + elif data == "trigger_missing_checksum": + self._prepared_errors.append( + lambda cur, last, ln: self._triggerResend(expected=last, checksum=False) + ) + elif data == "trigger_missing_lineno": + self._prepared_errors.append( + lambda cur, last, ln: self._send(self._error("lineno_missing", last)) + ) + elif data == "trigger_fatal_error_marlin": + self._send("Error:Thermal Runaway, system stopped! Heater_ID: bed") + self._send("Error:Printer halted. kill() called!") + elif data == "trigger_fatal_error_repetier": + self._send( + "fatal: Heater/sensor error - Printer stopped and heaters disabled due to this error. Fix error and restart with M999." + ) + elif data == "drop_connection": + self._debug_drop_connection = True + elif data == "reset": + self._reset() + elif data == "unbusy": + self._setUnbusy() + elif data == "mintemp_error": + self._send(self._error("mintemp")) + elif data == "maxtemp_error": + self._send(self._error("maxtemp")) + elif data == "go_awol": + self._send("// Going AWOL") + self._debug_awol = True + elif data == "rerequest_last": + self._send("// Entering rerequest loop") + self._rerequest_last = True + elif data == "cancel_sd": + if self._sdPrinting and self._sdPrinter: + self._pauseSdPrint() + self._sdPrinting = False + self._sdPrintingSemaphore.set() + self._sdPrinter.join() + self._finishSdPrint() + else: + try: + sleep_match = VirtualPrinter.sleep_regex.match(data) + sleep_after_match = VirtualPrinter.sleep_after_regex.match(data) + sleep_after_next_match = VirtualPrinter.sleep_after_next_regex.match(data) + custom_action_match = VirtualPrinter.custom_action_regex.match(data) + prepare_ok_match = VirtualPrinter.prepare_ok_regex.match(data) + send_match = VirtualPrinter.send_regex.match(data) + set_ambient_match = VirtualPrinter.set_ambient_regex.match(data) + start_sd_match = VirtualPrinter.start_sd_regex.match(data) + select_sd_match = VirtualPrinter.select_sd_regex.match(data) + + if sleep_match is not None: + interval = int(sleep_match.group(1)) + self._send( + "// sleeping for {interval} seconds".format(interval=interval) + ) + self._debug_sleep = interval + elif sleep_after_match is not None: + command = sleep_after_match.group(1) + interval = int(sleep_after_match.group(2)) + self._sleepAfter[command] = interval + self._send( + "// going to sleep {interval} seconds after each {command}".format( + **locals() + ) + ) + elif sleep_after_next_match is not None: + command = sleep_after_next_match.group(1) + interval = int(sleep_after_next_match.group(2)) + self._sleepAfterNext[command] = interval + self._send( + "// going to sleep {interval} seconds after next {command}".format( + **locals() + ) + ) + elif custom_action_match is not None: + action = custom_action_match.group(1) + params = custom_action_match.group(2) + params = params.strip() if params is not None else "" + self._send("// action:{action} {params}".format(**locals()).strip()) + elif prepare_ok_match is not None: + ok = prepare_ok_match.group(1) + self._prepared_oks.append(ok) + elif send_match is not None: + self._send(send_match.group(1)) + elif set_ambient_match is not None: + self._ambient_temperature = float(set_ambient_match.group(1)) + self._send( + "// set ambient temperature to {}".format( + self._ambient_temperature + ) + ) + elif start_sd_match is not None: + self._selectSdFile(start_sd_match.group(1), check_already_open=True) + self._startSdPrint() + elif select_sd_match is not None: + self._selectSdFile(select_sd_match.group(1)) + except Exception: + self._logger.exception("While handling %r", data) + + def _listSd(self): + if self._settings.get_boolean(["sdFiles", "size"]): + if self._settings.get_boolean(["sdFiles", "longname"]): + line = "{dosname} {size} {name}" + else: + line = "{dosname} {size}" + else: + line = "{dosname}" + + files = self._mappedSdList() + items = map(lambda x: line.format(**x), files.values()) + + self._send("Begin file list") + for item in items: + self._send(item) + self._send("End file list") + + def _mappedSdList(self): + # type: () -> collections.OrderedDict + result = collections.OrderedDict() + for entry in scandir(self._virtualSd): + if not entry.is_file(): + continue + dosname = get_dos_filename( + entry.name, existing_filenames=list(result.keys()) + ).lower() + result[dosname] = { + "name": entry.name, + "path": entry.path, + "dosname": dosname, + "size": entry.stat().st_size, + } + return result + + def _selectSdFile(self, filename, check_already_open=False): + # type: (str, bool) -> None + if filename.startswith("/"): + filename = filename[1:] + + files = self._mappedSdList() + file = files.get(filename) + if ( + file is None + or not os.path.exists(file["path"]) + or not os.path.isfile(file["path"]) + ): + self._send("open failed, File: %s." % filename) + return + + if self._selectedSdFile == file["path"] and check_already_open: + return + + self._selectedSdFile = file["path"] + self._selectedSdFileSize = file["size"] + if self._settings.get_boolean(["includeFilenameInOpened"]): + self._send("File opened: %s Size: %d" % (filename, self._selectedSdFileSize)) + else: + self._send("File opened") + self._send("File selected") + + def _startSdPrint(self): + if self._selectedSdFile is not None: + if self._sdPrinter is None: + self._sdPrinting = True + self._sdPrinter = threading.Thread(target=self._sdPrintingWorker) + self._sdPrinter.start() + self._sdPrintingSemaphore.set() + + def _pauseSdPrint(self): + self._sdPrintingSemaphore.clear() + + def _setSdPos(self, pos): + self._newSdFilePos = pos + + def _reportSdStatus(self): + if self._sdPrinter is not None and self._sdPrintingSemaphore.is_set: + self._send( + "SD printing byte %d/%d" + % (self._selectedSdFilePos, self._selectedSdFileSize) + ) + else: + self._send("Not SD printing") + + def _generateTemperatureOutput(self): + # type: () -> str + if self._settings.get_boolean(["repetierStyleTargetTemperature"]): + template = self._settings.get(["m105NoTargetFormatString"]) + else: + template = self._settings.get(["m105TargetFormatString"]) + + temps = collections.OrderedDict() + + # send simulated temperature data + if self.temperatureCount > 1: + if self._settings.get_boolean(["smoothieTemperatureReporting"]): + temps["T"] = (self.temp[0], self.targetTemp[0]) + elif self._settings.get_boolean(["includeCurrentToolInTemps"]): + temps["T"] = ( + self.temp[self.currentExtruder], + self.targetTemp[self.currentExtruder], + ) + + for i in range(len(self.temp)): + if i == 0 and self._settings.get_boolean( + ["smoothieTemperatureReporting"] + ): + continue + temps["T{}".format(i)] = (self.temp[i], self.targetTemp[i]) + + if self._settings.get_boolean(["hasBed"]): + temps["B"] = (self.bedTemp, self.bedTargetTemp) + + if self._settings.get_boolean(["hasChamber"]): + temps["C"] = (self.chamberTemp, self.chamberTargetTemp) + + else: + heater = "T" + if self._settings.get_boolean(["klipperTemperatureReporting"]): + heater = "T0" + + temps[heater] = (self.temp[0], self.targetTemp[0]) + + if self._settings.get_boolean(["hasBed"]): + temps["B"] = (self.bedTemp, self.bedTargetTemp) + + if self._settings.get_boolean(["hasChamber"]): + temps["C"] = (self.chamberTemp, self.chamberTargetTemp) + + output = " ".join( + map( + lambda x: template.format(heater=x[0], actual=x[1][0], target=x[1][1]), + temps.items(), + ) + ) + output += " @:64\n" + return output + + def _processTemperatureQuery(self): + includeOk = not self._okBeforeCommandOutput + output = self._generateTemperatureOutput() + + if includeOk: + ok = self._ok() + if ok: + output = "{} {}".format(ok, output) + self._send(output) + + def _parseHotendCommand(self, line, wait=False, support_r=False): + # type: (str, bool, bool) -> None + only_wait_if_higher = True + tool = 0 + toolMatch = re.search(r"T([0-9]+)", line) + if toolMatch: + tool = int(toolMatch.group(1)) + + if tool >= self.temperatureCount: + return + + try: + self.targetTemp[tool] = float(re.search(r"S([0-9]+)", line).group(1)) + except Exception: + if support_r: + try: + self.targetTemp[tool] = float(re.search(r"R([0-9]+)", line).group(1)) + only_wait_if_higher = False + except Exception: + pass + + if wait: + self._waitForHeatup("tool%d" % tool, only_wait_if_higher) + if self._settings.get_boolean(["repetierStyleTargetTemperature"]): + self._send("TargetExtr%d:%d" % (tool, self.targetTemp[tool])) + + def _parseBedCommand(self, line, wait=False, support_r=False): + # type: (str, bool, bool) -> None + if not self._settings.get_boolean(["hasBed"]): + return + + only_wait_if_higher = True + try: + self.bedTargetTemp = float(re.search(r"S([0-9]+)", line).group(1)) + except Exception: + if support_r: + try: + self.bedTargetTemp = float(re.search(r"R([0-9]+)", line).group(1)) + only_wait_if_higher = False + except Exception: + pass + + if wait: + self._waitForHeatup("bed", only_wait_if_higher) + if self._settings.get_boolean(["repetierStyleTargetTemperature"]): + self._send("TargetBed:%d" % self.bedTargetTemp) + + def _parseChamberCommand(self, line, wait=False, support_r=False): + if not self._settings.get_boolean(["hasChamber"]): + return + + only_wait_if_higher = True + try: + self.chamberTargetTemp = float(re.search("S([0-9]+)", line).group(1)) + except: + if support_r: + try: + self.chamberTargetTemp = float(re.search("R([0-9]+)", line).group(1)) + only_wait_if_higher = False + except: + pass + + if wait: + self._waitForHeatup("chamber", only_wait_if_higher) + + def _performMove(self, line): + # type: (str) -> None + matchX = re.search(r"X(-?[0-9.]+)", line) + matchY = re.search(r"Y(-?[0-9.]+)", line) + matchZ = re.search(r"Z(-?[0-9.]+)", line) + matchE = re.search(r"E(-?[0-9.]+)", line) + matchF = re.search(r"F([0-9.]+)", line) + + duration = 0.0 + if matchF is not None: + try: + self._lastF = float(matchF.group(1)) + except ValueError: + pass + + speedXYZ = self._lastF * (self._feedrate_multiplier / 100.0) + speedE = self._lastF * (self._flowrate_multiplier / 100.0) + if speedXYZ == 0: + speedXYZ = 999999999999 + if speedE == 0: + speedE = 999999999999 + + if matchX is not None: + try: + x = float(matchX.group(1)) + except ValueError: + pass + else: + if self._relative or self._lastX is None: + duration = max(duration, x * self._unitModifier / speedXYZ * 60.0) + else: + duration = max( + duration, (x - self._lastX) * self._unitModifier / speedXYZ * 60.0 + ) + + if self._relative and self._lastX is not None: + self._lastX += x + else: + self._lastX = x + if matchY is not None: + try: + y = float(matchY.group(1)) + except ValueError: + pass + else: + if self._relative or self._lastY is None: + duration = max(duration, y * self._unitModifier / speedXYZ * 60.0) + else: + duration = max( + duration, (y - self._lastY) * self._unitModifier / speedXYZ * 60.0 + ) + + if self._relative and self._lastY is not None: + self._lastY += y + else: + self._lastY = y + if matchZ is not None: + try: + z = float(matchZ.group(1)) + except ValueError: + pass + else: + if self._relative or self._lastZ is None: + duration = max(duration, z * self._unitModifier / speedXYZ * 60.0) + else: + duration = max( + duration, (z - self._lastZ) * self._unitModifier / speedXYZ * 60.0 + ) + + if self._relative and self._lastZ is not None: + self._lastZ += z + else: + self._lastZ = z + if matchE is not None: + try: + e = float(matchE.group(1)) + except ValueError: + pass + else: + lastE = self._lastE[self.currentExtruder] + if self._relative or lastE is None: + duration = max(duration, e * self._unitModifier / speedE * 60.0) + else: + duration = max( + duration, (e - lastE) * self._unitModifier / speedE * 60.0 + ) + + if self._relative and lastE is not None: + self._lastE[self.currentExtruder] += e + else: + self._lastE[self.currentExtruder] = e + + if duration: + duration *= 0.1 + if duration > self._read_timeout: + slept = 0 + while duration - slept > self._read_timeout and not self._killed: + time.sleep(self._read_timeout) + slept += self._read_timeout + else: + time.sleep(duration) + + def _setPosition(self, line): + # type: (str) -> None + matchX = re.search(r"X(-?[0-9.]+)", line) + matchY = re.search(r"Y(-?[0-9.]+)", line) + matchZ = re.search(r"Z(-?[0-9.]+)", line) + matchE = re.search(r"E(-?[0-9.]+)", line) + + if matchX is None and matchY is None and matchZ is None and matchE is None: + self._lastX = self._lastY = self._lastZ = self._lastE[ + self.currentExtruder + ] = 0 + else: + if matchX is not None: + try: + self._lastX = float(matchX.group(1)) + except ValueError: + pass + if matchY is not None: + try: + self._lastY = float(matchY.group(1)) + except ValueError: + pass + if matchZ is not None: + try: + self._lastZ = float(matchZ.group(1)) + except ValueError: + pass + if matchE is not None: + try: + self._lastE[self.currentExtruder] = float(matchE.group(1)) + except ValueError: + pass + + def _home(self, line): + x = y = z = e = None + + if "X" in line: + x = True + if "Y" in line: + y = True + if "Z" in line: + z = True + if "E" in line: + e = True + + if x is None and y is None and z is None and e is None: + self._lastX = self._lastY = self._lastZ = self._lastE[ + self.currentExtruder + ] = 0 + else: + if x: + self._lastX = 0 + if y: + self._lastY = 0 + if z: + self._lastZ = 0 + if e: + self._lastE = 0 + + def _writeSdFile(self, filename): + # type: (str) -> None + filename = filename + if filename.startswith("/"): + filename = filename[1:] + file = os.path.join(self._virtualSd, filename).lower() + if os.path.exists(file): + if os.path.isfile(file): + os.remove(file) + else: + self._send("error writing to file") + + handle = None + try: + handle = io.open(file, "wt", encoding="utf-8") + except Exception: + self._send("error writing to file") + self._writingToSdHandle = handle + self._writingToSd = True + self._selectedSdFile = file + self._send("Writing to file: %s" % filename) + + def _finishSdFile(self): + try: + self._writingToSdHandle.close() + except Exception: + pass + finally: + self._writingToSdHandle = None + self._writingToSd = False + self._selectedSdFile = None + self._send("Done saving file") + + def _sdPrintingWorker(self): + self._selectedSdFilePos = 0 + try: + with io.open(self._selectedSdFile, "rt", encoding="utf-8") as f: + for line in iter(f.readline, ""): + if self._killed or not self._sdPrinting: + break + + # reset position if requested by client + if self._newSdFilePos is not None: + f.seek(self._newSdFilePos) + self._newSdFilePos = None + + # read current file position + self._selectedSdFilePos = f.tell() + + # if we are paused, wait for resuming + self._sdPrintingSemaphore.wait() + if self._killed or not self._sdPrinting: + break + + # set target temps + if "M104" in line or "M109" in line: + self._parseHotendCommand(line, wait="M109" in line) + elif "M140" in line or "M190" in line: + self._parseBedCommand(line, wait="M190" in line) + elif ( + line.startswith("G0") + or line.startswith("G1") + or line.startswith("G2") + or line.startswith("G3") + ): + # simulate reprap buffered commands via a Queue with maxsize which internally simulates the moves + self.buffered.put(line) + + except AttributeError: + if self.outgoing is not None: + raise + + self._finishSdPrint() + + def _finishSdPrint(self): + if not self._killed: + self._sdPrintingSemaphore.clear() + self._send("Done printing file") + self._selectedSdFilePos = 0 + self._sdPrinting = False + self._sdPrinter = None + + def _waitForHeatup(self, heater, only_wait_if_higher): + # type: (str, bool) -> None + delta = 1 + delay = 1 + last_busy = monotonic_time() + + self._heatingUp = True + try: + if heater.startswith("tool"): + toolNum = int(heater[len("tool") :]) + test = lambda: self.temp[toolNum] < self.targetTemp[toolNum] - delta or ( + not only_wait_if_higher + and self.temp[toolNum] > self.targetTemp[toolNum] + delta + ) + output = lambda: "T:%0.2f" % self.temp[toolNum] + elif heater == "bed": + test = lambda: self.bedTemp < self.bedTargetTemp - delta or ( + not only_wait_if_higher and self.bedTemp > self.bedTargetTemp + delta + ) + output = lambda: "B:%0.2f" % self.bedTemp + elif heater == "chamber": + test = lambda: self.chamberTemp < self.chamberTargetTemp - delta or ( + not only_wait_if_higher + and self.chamberTemp > self.chamberTargetTemp + delta + ) + output = lambda: "C:%0.2f" % self.chamberTemp + else: + return + + while not self._killed and self._heatingUp and test(): + self._simulateTemps(delta=delta) + self._send(output()) + if self._sendBusy and monotonic_time() - last_busy >= self._busyInterval: + self._send("echo:busy: processing") + last_busy = monotonic_time() + time.sleep(delay) + except AttributeError: + if self.outgoing is not None: + raise + finally: + self._heatingUp = False + + def _deleteSdFile(self, filename): + # type: (str) -> None + if filename.startswith("/"): + filename = filename[1:] + files = self._mappedSdList() + file = files.get(filename) + if ( + file is not None + and os.path.exists(file["path"]) + and os.path.isfile(file["path"]) + ): + os.remove(file["path"]) + + def _simulateTemps(self, delta=0.5): + timeDiff = self.lastTempAt - monotonic_time() + self.lastTempAt = monotonic_time() + + def simulate(actual, target, ambient): + if target > 0: + goal = target + remaining = abs(actual - target) + if remaining > delta: + factor = 10 + elif remaining < delta: + factor = remaining + elif not target and abs(actual - ambient) > delta: + goal = ambient + factor = 2 + else: + return actual + + old = actual + actual += math.copysign(timeDiff * factor, goal - actual) + + if math.copysign(1, goal - old) != math.copysign(1, goal - actual): + actual = goal + + return actual + + for i in range(len(self.temp)): + if i in self.pinnedExtruders: + self.temp[i] = self.pinnedExtruders[i] + continue + self.temp[i] = simulate( + self.temp[i], self.targetTemp[i], self._ambient_temperature + ) + self.bedTemp = simulate( + self.bedTemp, self.bedTargetTemp, self._ambient_temperature + ) + self.chamberTemp = simulate( + self.chamberTemp, self.chamberTargetTemp, self._ambient_temperature + ) + + def _processBuffer(self): + while self.buffered is not None: + try: + line = self.buffered.get(timeout=0.5) + except queue.Empty: + continue + + if line is None: + continue + + self._performMove(line) + self.buffered.task_done() + + self._logger.info("Closing down buffer loop") + + def _setBusy(self, reason="processing"): + if not self._sendBusy: + return + + def loop(): + while self._busy: + self._send("echo:busy {}".format(self._busy)) + time.sleep(self._busyInterval) + self._sendOk() + + self._busy = reason + self._busy_loop = threading.Thread(target=loop) + self._busy_loop.daemon = True + self._busy_loop.start() + + def _setUnbusy(self): + self._busy = None + + def _showPrompt(self, text, choices): + self._hidePrompt() + self._send("//action:prompt_begin {}".format(text)) + for choice in choices: + self._send("//action:prompt_button {}".format(choice)) + self._send("//action:prompt_show") + + def _hidePrompt(self): + self._send("//action:prompt_end") + + def write(self, data): + # type: (bytes) -> int + data = to_bytes(data, errors="replace") + u_data = to_unicode(data, errors="replace") + + if self._debug_awol: + return len(data) + + if self._debug_drop_connection: + self._logger.info( + "Debug drop of connection requested, raising SerialTimeoutException" + ) + raise SerialTimeoutException() + + with self._incoming_lock: + if self.incoming is None or self.outgoing is None: + return 0 + + if b"M112" in data and self._supportM112: + self._seriallog.info("<<< {}".format(u_data)) + self._kill() + return len(data) + + try: + written = self.incoming.put( + data, timeout=self._write_timeout, partial=True + ) + self._seriallog.info("<<< {}".format(u_data)) + return written + except queue.Full: + self._logger.info( + "Incoming queue is full, raising SerialTimeoutException" + ) + raise SerialTimeoutException() + + def readline(self): + # type: () -> bytes + if self._debug_awol: + time.sleep(self._read_timeout) + return b"" + + if self._debug_drop_connection: + raise SerialTimeoutException() + + if self._debug_sleep > 0: + # if we are supposed to sleep, we sleep not longer than the read timeout + # (and then on the next call sleep again if there's time to sleep left) + sleep_for = min(self._debug_sleep, self._read_timeout) + self._debug_sleep -= sleep_for + time.sleep(sleep_for) + + if self._debug_sleep > 0: + # we slept the full read timeout, return an empty line + return b"" + + # otherwise our left over timeout is the read timeout minus what we already + # slept for + timeout = self._read_timeout - sleep_for + + else: + # use the full read timeout as timeout + timeout = self._read_timeout + + try: + # fetch a line from the queue, wait no longer than timeout + line = to_unicode(self.outgoing.get(timeout=timeout), errors="replace") + self._seriallog.info(">>> {}".format(line.strip())) + self.outgoing.task_done() + return to_bytes(line) + except queue.Empty: + # queue empty? return empty line + return b"" + + def close(self): + self._killed = True + self.incoming = None + self.outgoing = None + self.buffered = None + + def _sendOk(self): + if self.outgoing is None: + return + ok = self._ok() + if ok: + self._send(ok) + + def _sendWaitAfterTimeout(self, timeout=5): + time.sleep(timeout) + if self.outgoing is not None: + self._send("wait") + + def _send(self, line): + # type: (str) -> None + if self.outgoing is not None: + self.outgoing.put(line) + + def _ok(self): + ok = self._okFormatString + if self._prepared_oks: + ok = self._prepared_oks.pop(0) + if ok is None: + return ok + + return ok.format( + ok, lastN=self.lastN, buffer=self.buffered.maxsize - self.buffered.qsize() + ) + + def _error(self, error, *args, **kwargs): + # type: (str, Any, Any) -> str + return "Error: {}".format(self._errors.get(error).format(*args, **kwargs)) # noinspection PyUnresolvedReferences class CharCountingQueue(queue.Queue): + def __init__(self, maxsize, name=None): + queue.Queue.__init__(self, maxsize=maxsize) + self._size = 0 + self._name = name - def __init__(self, maxsize, name=None): - queue.Queue.__init__(self, maxsize=maxsize) - self._size = 0 - self._name = name + def clear(self): + with self.mutex: + self.queue.clear() - def clear(self): - with self.mutex: - self.queue.clear() + def put(self, item, block=True, timeout=None, partial=False): + self.not_full.acquire() - def put(self, item, block=True, timeout=None, partial=False): - self.not_full.acquire() + try: + if not self._will_it_fit(item) and partial: + space_left = self.maxsize - self._qsize() + if space_left: + item = item[:space_left] - try: - if not self._will_it_fit(item) and partial: - space_left = self.maxsize - self._qsize() - if space_left: - item = item[:space_left] + if not block: + if not self._will_it_fit(item): + raise queue.Full + elif timeout is None: + while not self._will_it_fit(item): + self.not_full.wait() + elif timeout < 0: + raise ValueError("'timeout' must be a positive number") + else: + endtime = monotonic_time() + timeout + while not self._will_it_fit(item): + remaining = endtime - monotonic_time() + if remaining <= 0.0: + raise queue.Full + self.not_full.wait(remaining) - if not block: - if not self._will_it_fit(item): - raise queue.Full - elif timeout is None: - while not self._will_it_fit(item): - self.not_full.wait() - elif timeout < 0: - raise ValueError("'timeout' must be a positive number") - else: - endtime = monotonic_time() + timeout - while not self._will_it_fit(item): - remaining = endtime - monotonic_time() - if remaining <= 0.0: - raise queue.Full - self.not_full.wait(remaining) + self._put(item) + self.unfinished_tasks += 1 + self.not_empty.notify() - self._put(item) - self.unfinished_tasks += 1 - self.not_empty.notify() + return self._len(item) + finally: + self.not_full.release() - return self._len(item) - finally: - self.not_full.release() + # noinspection PyMethodMayBeStatic + def _len(self, item): + return len(item) - # noinspection PyMethodMayBeStatic - def _len(self, item): - return len(item) + def _qsize(self, l=len): + return self._size - def _qsize(self, l=len): - return self._size + # Put a new item in the queue + def _put(self, item): + self.queue.append(item) + self._size += self._len(item) - # Put a new item in the queue - def _put(self, item): - self.queue.append(item) - self._size += self._len(item) + # Get an item from the queue + def _get(self): + item = self.queue.popleft() + self._size -= self._len(item) + return item - # Get an item from the queue - def _get(self): - item = self.queue.popleft() - self._size -= self._len(item) - return item - - def _will_it_fit(self, item): - return self.maxsize - self._qsize() >= self._len(item) + def _will_it_fit(self, item): + return self.maxsize - self._qsize() >= self._len(item) diff --git a/src/octoprint/printer/__init__.py b/src/octoprint/printer/__init__.py index 529b0d475..4f372465c 100644 --- a/src/octoprint/printer/__init__.py +++ b/src/octoprint/printer/__init__.py @@ -18,7 +18,7 @@ abstracted version of the actual printer communication. """ __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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 re @@ -28,695 +28,707 @@ from octoprint.util import deprecated, natural_key from octoprint.filemanager import FileDestinations -@deprecated(message="get_connection_options has been replaced by PrinterInterface.get_connection_options", - includedoc="Replaced by :func:`PrinterInterface.get_connection_options`", - since="1.3.0") +@deprecated( + message="get_connection_options has been replaced by PrinterInterface.get_connection_options", + includedoc="Replaced by :func:`PrinterInterface.get_connection_options`", + since="1.3.0", +) def get_connection_options(): - return PrinterInterface.get_connection_options() + return PrinterInterface.get_connection_options() class PrinterInterface(object): - """ - The :class:`PrinterInterface` represents the developer interface to the :class:`~octoprint.printer.standard.Printer` - instance. - """ - - valid_axes = ("x", "y", "z", "e") - """Valid axes identifiers.""" - - valid_tool_regex = re.compile(r"^(tool\d+)$") - """Regex for valid tool identifiers.""" - - valid_heater_regex = re.compile(r"^(tool\d+|bed|chamber)$") - """Regex for valid heater identifiers.""" - - @classmethod - def get_connection_options(cls, *args, **kwargs): - """ - Retrieves the available ports, baudrates, preferred port and baudrate for connecting to the printer. - - Returned ``dict`` has the following structure:: - - ports: - baudrates: - portPreference: - baudratePreference: - autoconnect: - - Returns: - (dict): A dictionary holding the connection options in the structure specified above - """ - import octoprint.util.comm as comm - return { - "ports": sorted(comm.serialList(), key=natural_key), - "baudrates": sorted(comm.baudrateList(), reverse=True), - "portPreference": settings().get(["serial", "port"]), - "baudratePreference": settings().getInt(["serial", "baudrate"]), - "autoconnect": settings().getBoolean(["serial", "autoconnect"]) - } - - def connect(self, port=None, baudrate=None, profile=None, *args, **kwargs): - """ - Connects to the printer, using the specified serial ``port``, ``baudrate`` and printer ``profile``. If a - connection is already established, that connection will be closed prior to connecting anew with the provided - parameters. - - Arguments: - port (str): Name of the serial port to connect to. If not provided, an auto detection will be attempted. - baudrate (int): Baudrate to connect with. If not provided, an auto detection will be attempted. - profile (str): Name of the printer profile to use for this connection. If not provided, the default - will be retrieved from the :class:`PrinterProfileManager`. - """ - pass - - def disconnect(self, *args, **kwargs): - """ - Disconnects from the printer. Does nothing if no connection is currently established. - """ - raise NotImplementedError() - - def get_transport(self, *args, **kwargs): - """ - Returns the communication layer's transport object, if a connection is currently established. - - Note that this doesn't have to necessarily be a :class:`serial.Serial` instance, it might also be something - different, so take care to do instance checks before attempting to access any properties or methods. - - Returns: - object: The communication layer's transport object - """ - raise NotImplementedError() - - def job_on_hold(self, blocking=True, *args, **kwargs): - """ - Contextmanager that allows executing code while printing while making sure that no commands from the file - being printed are continued to be sent to the printer. Note that this will only work for local files, - NOT SD files. - - Example: - - .. code-block:: python - - with printer.job_on_hold(): - park_printhead() - take_snapshot() - send_printhead_back() - - It should be used sparingly and only for very specific situations (such as parking the print head somewhere, - taking a snapshot from the webcam, then continuing). If you abuse this, you WILL cause print quality issues! - - A lock is in place that ensures that the context can only actually be held by one thread at a time. If you - don't want to block on acquire, be sure to set ``blocking`` to ``False`` and catch the ``RuntimeException`` thrown - if the lock can't be acquired. - - Args: - blocking (bool): Whether to block while attempting to acquire the lock (default) or not - """ - raise NotImplementedError() - - def set_job_on_hold(self, value, blocking=True, *args, **kwargs): - """ - Setter for finer control over putting jobs on hold. Set to ``True`` to ensure that no commands from the file - being printed are continued to be sent to the printer. Set to ``False`` to resume. Note that this will only - work for local files, NOT SD files. - - Make absolutely sure that if you set this flag, you will always also unset it again. If you don't, the job will - be stuck forever. - - Example: - - .. code-block:: python - - if printer.set_job_on_hold(True): - try: - park_printhead() - take_snapshot() - send_printhead_back() - finally: - printer.set_job_on_hold(False) - - Just like :func:`~octoprint.printer.PrinterInterface.job_on_hold` this should be used sparingly and only for - very specific situations. If you abuse this, you WILL cause print quality issues! - - Args: - value (bool): The value to set - blocking (bool): Whether to block while attempting to set the value (default) or not - - Returns: - (bool) Whether the value could be set successfully (True) or a timeout was encountered (False) - """ - raise NotImplementedError() - - def fake_ack(self, *args, **kwargs): - """ - Fakes an acknowledgment for the communication layer. If the communication between OctoPrint and the printer - gets stuck due to lost "ok" responses from the server due to communication issues, this can be used to get - things going again. - """ - raise NotImplementedError() - - def commands(self, commands, tags=None, force=False, *args, **kwargs): - """ - Sends the provided ``commands`` to the printer. - - Arguments: - commands (str, list): The commands to send. Might be a single command provided just as a string or a list - of multiple commands to send in order. - tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle - force (bool): Whether to force sending of the command right away or allow queuing while printing - """ - raise NotImplementedError() - - def script(self, name, context=None, tags=None, *args, **kwargs): - """ - Sends the GCODE script ``name`` to the printer. - - The script will be run through the template engine, the rendering context can be extended by providing a - ``context`` with additional template variables to use. - - If the script is unknown, an :class:`UnknownScriptException` will be raised. - - Arguments: - name (str): The name of the GCODE script to render. - context (dict): An optional context of additional template variables to provide to the renderer. - tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle - - Raises: - UnknownScriptException: There is no GCODE script with name ``name`` - """ - raise NotImplementedError() - - def jog(self, axes, relative=True, speed=None, tags=None, *args, **kwargs): - """ - Jogs the specified printer ``axis`` by the specified ``amount`` in mm. - - Arguments: - axes (dict): Axes and distances to jog, keys are axes ("x", "y", "z"), values are distances in mm - relative (bool): Whether to interpret the distance values as relative (true, default) or absolute (false) - coordinates - speed (int, bool or None): Speed at which to jog (F parameter). If set to ``False`` no speed will be set - specifically. If set to ``None`` (or left out) the minimum of all involved axes speeds from the printer - profile will be used. - tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle - """ - raise NotImplementedError() - - def home(self, axes, tags=None, *args, **kwargs): - """ - Homes the specified printer ``axes``. - - Arguments: - axes (str, list): The axis or axes to home, each of which must converted to lower case must match one of - "x", "y", "z" and "e" - tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle - """ - raise NotImplementedError() - - def extrude(self, amount, speed=None, tags=None, *args, **kwargs): - """ - Extrude ``amount`` millimeters of material from the tool. - - Arguments: - amount (int, float): The amount of material to extrude in mm - speed (int, None): Speed at which to extrude (F parameter). If set to ``None`` (or left out) - the maximum speed of E axis from the printer profile will be used. - tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle - """ - raise NotImplementedError() - - def change_tool(self, tool, tags=None, *args, **kwargs): - """ - Switch the currently active ``tool`` (for which extrude commands will apply). - - Arguments: - tool (str): The tool to switch to, matching the regex "tool[0-9]+" (e.g. "tool0", "tool1", ...) - tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle - """ - raise NotImplementedError() - - def set_temperature(self, heater, value, tags=None, *args, **kwargs): - """ - Sets the target temperature on the specified ``heater`` to the given ``value`` in celsius. - - Arguments: - heater (str): The heater for which to set the target temperature. Either "bed" for setting the bed - temperature or something matching the regular expression "tool[0-9]+" (e.g. "tool0", "tool1", ...) for - the hotends of the printer - value (int, float): The temperature in celsius to set the target temperature to. - tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle - """ - raise NotImplementedError() - - def set_temperature_offset(self, offsets=None, tags=None, *args, **kwargs): - """ - Sets the temperature ``offsets`` to apply to target temperatures read from a GCODE file while printing. - - Arguments: - offsets (dict): A dictionary specifying the offsets to apply. Keys must match the format for the ``heater`` - parameter to :func:`set_temperature`, so "bed" for the offset for the bed target temperature and - "tool[0-9]+" for the offsets to the hotend target temperatures. - tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle - """ - raise NotImplementedError() - - def feed_rate(self, factor, tags=None, *args, **kwargs): - """ - Sets the ``factor`` for the printer's feed rate. - - Arguments: - factor (int, float): The factor for the feed rate to send to the firmware. Percentage expressed as either an - int between 0 and 100 or a float between 0 and 1. - tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle - """ - raise NotImplementedError() - - def flow_rate(self, factor, tags=None, *args, **kwargs): - """ - Sets the ``factor`` for the printer's flow rate. - - Arguments: - factor (int, float): The factor for the flow rate to send to the firmware. Percentage expressed as either an - int between 0 and 100 or a float between 0 and 1. - tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle - """ - raise NotImplementedError() - - def can_modify_file(self, path, sd, *args, **kwargs): - """ - Determines whether the ``path`` (on the printer's SD if ``sd`` is True) may be modified (updated or deleted) - or not. - - A file that is currently being printed is not allowed to be modified. Any other file or the current file - when it is not being printed is fine though. - - :since: 1.3.2 - - .. warning:: - - This was introduced in 1.3.2 to work around an issue when updating a file that is already selected. - I'm not 100% sure at this point if this is the best approach to solve this issue, so if you decide - to depend on this particular method in this interface, be advised that it might vanish in future - versions! - - Arguments: - path (str): path in storage of the file to check - sd (bool): True if to check against SD storage, False otherwise - - Returns: - (bool) True if the file may be modified, False otherwise - """ - return not (self.is_current_file(path, sd) and (self.is_printing() or self.is_paused())) - - def is_current_file(self, path, sd, *args, **kwargs): - """ - Returns whether the provided ``path`` (on the printer's SD if ``sd`` is True) is the currently selected - file for printing. - - :since: 1.3.2 - - .. warning:: - - This was introduced in 1.3.2 to work around an issue when updating a file that is already selected. - I'm not 100% sure at this point if this is the best approach to solve this issue, so if you decide - to depend on this particular method in this interface, be advised that it might vanish in future - versions! - - Arguments: - path (str): path in storage of the file to check - sd (bool): True if to check against SD storage, False otherwise - - Returns: - (bool) True if the file is currently selected, False otherwise - """ - current_job = self.get_current_job() - if current_job is not None and "file" in current_job: - current_job_file = current_job["file"] - if "path" in current_job_file and "origin" in current_job_file: - current_file_path = current_job_file["path"] - current_file_origin = current_job_file["origin"] - - return path == current_file_path and sd == (current_file_origin == FileDestinations.SDCARD) - - return False - - def select_file(self, path, sd, printAfterSelect=False, pos=None, tags=None, *args, **kwargs): - """ - Selects the specified ``path`` for printing, specifying if the file is to be found on the ``sd`` or not. - Optionally can also directly start the print after selecting the file. - - Arguments: - path (str): The path to select for printing. Either an absolute path or relative path to a local file in - the uploads folder or a filename on the printer's SD card. - sd (boolean): Indicates whether the file is on the printer's SD card or not. - printAfterSelect (boolean): Indicates whether a print should be started - after the file is selected. - tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle - - Raises: - InvalidFileType: if the file is not a machinecode file and hence cannot be printed - InvalidFileLocation: if an absolute path was provided and not contained within local storage or - doesn't exist - """ - raise NotImplementedError() - - def unselect_file(self, *args, **kwargs): - """ - Unselects and currently selected file. - """ - raise NotImplementedError() - - def start_print(self, tags=None, *args, **kwargs): - """ - Starts printing the currently selected file. If no file is currently selected, does nothing. - - Arguments: - tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle - """ - raise NotImplementedError() - - def pause_print(self, tags=None, *args, **kwargs): - """ - Pauses the current print job if it is currently running, does nothing otherwise. - - Arguments: - tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle - """ - raise NotImplementedError() - - def resume_print(self, tags=None, *args, **kwargs): - """ - Resumes the current print job if it is currently paused, does nothing otherwise. - - Arguments: - tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle - """ - raise NotImplementedError() - - def toggle_pause_print(self, tags=None, *args, **kwargs): - """ - Pauses the current print job if it is currently running or resumes it if it is currently paused. - - Arguments: - tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle - """ - if self.is_printing(): - self.pause_print(tags=tags, *args, **kwargs) - elif self.is_paused(): - self.resume_print(tags=tags, *args, **kwargs) - - def cancel_print(self, tags=None, *args, **kwargs): - """ - Cancels the current print job. - - Arguments: - tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle - """ - raise NotImplementedError() - - def log_lines(self, *lines): - """ - Logs the provided lines to the printer log and serial.log - Args: - *lines: the lines to log - """ - pass - - def get_state_string(self, *args, **kwargs): - """ - Returns: - (str) A human readable string corresponding to the current communication state. - """ - raise NotImplementedError() - - def get_state_id(self, *args, **kwargs): - """ - Identifier of the current communication state. - - Possible values are: - - * OPEN_SERIAL - * DETECT_SERIAL - * DETECT_BAUDRATE - * CONNECTING - * OPERATIONAL - * PRINTING - * PAUSED - * CLOSED - * ERROR - * CLOSED_WITH_ERROR - * TRANSFERING_FILE - * OFFLINE - * UNKNOWN - * NONE - - Returns: - (str) A unique identifier corresponding to the current communication state. - """ - - def get_current_data(self, *args, **kwargs): - """ - Returns: - (dict) The current state data. - """ - raise NotImplementedError() - - def get_current_job(self, *args, **kwargs): - """ - Returns: - (dict) The data of the current job. - """ - raise NotImplementedError() - - def get_current_temperatures(self, *args, **kwargs): - """ - Returns: - (dict) The current temperatures. - """ - raise NotImplementedError() - - def get_temperature_history(self, *args, **kwargs): - """ - Returns: - (list) The temperature history. - """ - raise NotImplementedError() - - def get_current_connection(self, *args, **kwargs): - """ - Returns: - (tuple) The current connection information as a 4-tuple ``(connection_string, port, baudrate, printer_profile)``. - If the printer is currently not connected, the tuple will be ``("Closed", None, None, None)``. - """ - raise NotImplementedError() - - def is_closed_or_error(self, *args, **kwargs): - """ - Returns: - (boolean) Whether the printer is currently disconnected and/or in an error state. - """ - raise NotImplementedError() - - def is_operational(self, *args, **kwargs): - """ - Returns: - (boolean) Whether the printer is currently connected and available. - """ - raise NotImplementedError() - - def is_printing(self, *args, **kwargs): - """ - Returns: - (boolean) Whether the printer is currently printing. - """ - raise NotImplementedError() - - def is_cancelling(self, *args, **kwargs): - """ - Returns: - (boolean) Whether the printer is currently cancelling a print. - """ - raise NotImplementedError() - - def is_pausing(self, *args, **kwargs): - """ - Returns: - (boolean) Whether the printer is currently pausing a print. - """ - raise NotImplementedError() - - def is_paused(self, *args, **kwargs): - """ - Returns: - (boolean) Whether the printer is currently paused. - """ - raise NotImplementedError() - - def is_error(self, *args, **kwargs): - """ - Returns: - (boolean) Whether the printer is currently in an error state. - """ - raise NotImplementedError() - - def is_ready(self, *args, **kwargs): - """ - Returns: - (boolean) Whether the printer is currently operational and ready for new print jobs (not printing). - """ - raise NotImplementedError() - - def register_callback(self, callback, *args, **kwargs): - """ - Registers a :class:`PrinterCallback` with the instance. - - Arguments: - callback (PrinterCallback): The callback object to register. - """ - raise NotImplementedError() - - def unregister_callback(self, callback, *args, **kwargs): - """ - Unregisters a :class:`PrinterCallback` from the instance. - - Arguments: - callback (PrinterCallback): The callback object to unregister. - """ - raise NotImplementedError() - - def send_initial_callback(self, callback): - """ - Sends the initial printer update to :class:`PrinterCallback`. - - Arguments: - callback (PrinterCallback): The callback object to send initial data to. - """ - raise NotImplementedError() + """ + The :class:`PrinterInterface` represents the developer interface to the :class:`~octoprint.printer.standard.Printer` + instance. + """ + + valid_axes = ("x", "y", "z", "e") + """Valid axes identifiers.""" + + valid_tool_regex = re.compile(r"^(tool\d+)$") + """Regex for valid tool identifiers.""" + + valid_heater_regex = re.compile(r"^(tool\d+|bed|chamber)$") + """Regex for valid heater identifiers.""" + + @classmethod + def get_connection_options(cls, *args, **kwargs): + """ + Retrieves the available ports, baudrates, preferred port and baudrate for connecting to the printer. + + Returned ``dict`` has the following structure:: + + ports: + baudrates: + portPreference: + baudratePreference: + autoconnect: + + Returns: + (dict): A dictionary holding the connection options in the structure specified above + """ + import octoprint.util.comm as comm + + return { + "ports": sorted(comm.serialList(), key=natural_key), + "baudrates": sorted(comm.baudrateList(), reverse=True), + "portPreference": settings().get(["serial", "port"]), + "baudratePreference": settings().getInt(["serial", "baudrate"]), + "autoconnect": settings().getBoolean(["serial", "autoconnect"]), + } + + def connect(self, port=None, baudrate=None, profile=None, *args, **kwargs): + """ + Connects to the printer, using the specified serial ``port``, ``baudrate`` and printer ``profile``. If a + connection is already established, that connection will be closed prior to connecting anew with the provided + parameters. + + Arguments: + port (str): Name of the serial port to connect to. If not provided, an auto detection will be attempted. + baudrate (int): Baudrate to connect with. If not provided, an auto detection will be attempted. + profile (str): Name of the printer profile to use for this connection. If not provided, the default + will be retrieved from the :class:`PrinterProfileManager`. + """ + pass + + def disconnect(self, *args, **kwargs): + """ + Disconnects from the printer. Does nothing if no connection is currently established. + """ + raise NotImplementedError() + + def get_transport(self, *args, **kwargs): + """ + Returns the communication layer's transport object, if a connection is currently established. + + Note that this doesn't have to necessarily be a :class:`serial.Serial` instance, it might also be something + different, so take care to do instance checks before attempting to access any properties or methods. + + Returns: + object: The communication layer's transport object + """ + raise NotImplementedError() + + def job_on_hold(self, blocking=True, *args, **kwargs): + """ + Contextmanager that allows executing code while printing while making sure that no commands from the file + being printed are continued to be sent to the printer. Note that this will only work for local files, + NOT SD files. + + Example: + + .. code-block:: python + + with printer.job_on_hold(): + park_printhead() + take_snapshot() + send_printhead_back() + + It should be used sparingly and only for very specific situations (such as parking the print head somewhere, + taking a snapshot from the webcam, then continuing). If you abuse this, you WILL cause print quality issues! + + A lock is in place that ensures that the context can only actually be held by one thread at a time. If you + don't want to block on acquire, be sure to set ``blocking`` to ``False`` and catch the ``RuntimeException`` thrown + if the lock can't be acquired. + + Args: + blocking (bool): Whether to block while attempting to acquire the lock (default) or not + """ + raise NotImplementedError() + + def set_job_on_hold(self, value, blocking=True, *args, **kwargs): + """ + Setter for finer control over putting jobs on hold. Set to ``True`` to ensure that no commands from the file + being printed are continued to be sent to the printer. Set to ``False`` to resume. Note that this will only + work for local files, NOT SD files. + + Make absolutely sure that if you set this flag, you will always also unset it again. If you don't, the job will + be stuck forever. + + Example: + + .. code-block:: python + + if printer.set_job_on_hold(True): + try: + park_printhead() + take_snapshot() + send_printhead_back() + finally: + printer.set_job_on_hold(False) + + Just like :func:`~octoprint.printer.PrinterInterface.job_on_hold` this should be used sparingly and only for + very specific situations. If you abuse this, you WILL cause print quality issues! + + Args: + value (bool): The value to set + blocking (bool): Whether to block while attempting to set the value (default) or not + + Returns: + (bool) Whether the value could be set successfully (True) or a timeout was encountered (False) + """ + raise NotImplementedError() + + def fake_ack(self, *args, **kwargs): + """ + Fakes an acknowledgment for the communication layer. If the communication between OctoPrint and the printer + gets stuck due to lost "ok" responses from the server due to communication issues, this can be used to get + things going again. + """ + raise NotImplementedError() + + def commands(self, commands, tags=None, force=False, *args, **kwargs): + """ + Sends the provided ``commands`` to the printer. + + Arguments: + commands (str, list): The commands to send. Might be a single command provided just as a string or a list + of multiple commands to send in order. + tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle + force (bool): Whether to force sending of the command right away or allow queuing while printing + """ + raise NotImplementedError() + + def script(self, name, context=None, tags=None, *args, **kwargs): + """ + Sends the GCODE script ``name`` to the printer. + + The script will be run through the template engine, the rendering context can be extended by providing a + ``context`` with additional template variables to use. + + If the script is unknown, an :class:`UnknownScriptException` will be raised. + + Arguments: + name (str): The name of the GCODE script to render. + context (dict): An optional context of additional template variables to provide to the renderer. + tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle + + Raises: + UnknownScriptException: There is no GCODE script with name ``name`` + """ + raise NotImplementedError() + + def jog(self, axes, relative=True, speed=None, tags=None, *args, **kwargs): + """ + Jogs the specified printer ``axis`` by the specified ``amount`` in mm. + + Arguments: + axes (dict): Axes and distances to jog, keys are axes ("x", "y", "z"), values are distances in mm + relative (bool): Whether to interpret the distance values as relative (true, default) or absolute (false) + coordinates + speed (int, bool or None): Speed at which to jog (F parameter). If set to ``False`` no speed will be set + specifically. If set to ``None`` (or left out) the minimum of all involved axes speeds from the printer + profile will be used. + tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle + """ + raise NotImplementedError() + + def home(self, axes, tags=None, *args, **kwargs): + """ + Homes the specified printer ``axes``. + + Arguments: + axes (str, list): The axis or axes to home, each of which must converted to lower case must match one of + "x", "y", "z" and "e" + tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle + """ + raise NotImplementedError() + + def extrude(self, amount, speed=None, tags=None, *args, **kwargs): + """ + Extrude ``amount`` millimeters of material from the tool. + + Arguments: + amount (int, float): The amount of material to extrude in mm + speed (int, None): Speed at which to extrude (F parameter). If set to ``None`` (or left out) + the maximum speed of E axis from the printer profile will be used. + tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle + """ + raise NotImplementedError() + + def change_tool(self, tool, tags=None, *args, **kwargs): + """ + Switch the currently active ``tool`` (for which extrude commands will apply). + + Arguments: + tool (str): The tool to switch to, matching the regex "tool[0-9]+" (e.g. "tool0", "tool1", ...) + tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle + """ + raise NotImplementedError() + + def set_temperature(self, heater, value, tags=None, *args, **kwargs): + """ + Sets the target temperature on the specified ``heater`` to the given ``value`` in celsius. + + Arguments: + heater (str): The heater for which to set the target temperature. Either "bed" for setting the bed + temperature or something matching the regular expression "tool[0-9]+" (e.g. "tool0", "tool1", ...) for + the hotends of the printer + value (int, float): The temperature in celsius to set the target temperature to. + tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle + """ + raise NotImplementedError() + + def set_temperature_offset(self, offsets=None, tags=None, *args, **kwargs): + """ + Sets the temperature ``offsets`` to apply to target temperatures read from a GCODE file while printing. + + Arguments: + offsets (dict): A dictionary specifying the offsets to apply. Keys must match the format for the ``heater`` + parameter to :func:`set_temperature`, so "bed" for the offset for the bed target temperature and + "tool[0-9]+" for the offsets to the hotend target temperatures. + tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle + """ + raise NotImplementedError() + + def feed_rate(self, factor, tags=None, *args, **kwargs): + """ + Sets the ``factor`` for the printer's feed rate. + + Arguments: + factor (int, float): The factor for the feed rate to send to the firmware. Percentage expressed as either an + int between 0 and 100 or a float between 0 and 1. + tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle + """ + raise NotImplementedError() + + def flow_rate(self, factor, tags=None, *args, **kwargs): + """ + Sets the ``factor`` for the printer's flow rate. + + Arguments: + factor (int, float): The factor for the flow rate to send to the firmware. Percentage expressed as either an + int between 0 and 100 or a float between 0 and 1. + tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle + """ + raise NotImplementedError() + + def can_modify_file(self, path, sd, *args, **kwargs): + """ + Determines whether the ``path`` (on the printer's SD if ``sd`` is True) may be modified (updated or deleted) + or not. + + A file that is currently being printed is not allowed to be modified. Any other file or the current file + when it is not being printed is fine though. + + :since: 1.3.2 + + .. warning:: + + This was introduced in 1.3.2 to work around an issue when updating a file that is already selected. + I'm not 100% sure at this point if this is the best approach to solve this issue, so if you decide + to depend on this particular method in this interface, be advised that it might vanish in future + versions! + + Arguments: + path (str): path in storage of the file to check + sd (bool): True if to check against SD storage, False otherwise + + Returns: + (bool) True if the file may be modified, False otherwise + """ + return not ( + self.is_current_file(path, sd) and (self.is_printing() or self.is_paused()) + ) + + def is_current_file(self, path, sd, *args, **kwargs): + """ + Returns whether the provided ``path`` (on the printer's SD if ``sd`` is True) is the currently selected + file for printing. + + :since: 1.3.2 + + .. warning:: + + This was introduced in 1.3.2 to work around an issue when updating a file that is already selected. + I'm not 100% sure at this point if this is the best approach to solve this issue, so if you decide + to depend on this particular method in this interface, be advised that it might vanish in future + versions! + + Arguments: + path (str): path in storage of the file to check + sd (bool): True if to check against SD storage, False otherwise + + Returns: + (bool) True if the file is currently selected, False otherwise + """ + current_job = self.get_current_job() + if current_job is not None and "file" in current_job: + current_job_file = current_job["file"] + if "path" in current_job_file and "origin" in current_job_file: + current_file_path = current_job_file["path"] + current_file_origin = current_job_file["origin"] + + return path == current_file_path and sd == ( + current_file_origin == FileDestinations.SDCARD + ) + + return False + + def select_file( + self, path, sd, printAfterSelect=False, pos=None, tags=None, *args, **kwargs + ): + """ + Selects the specified ``path`` for printing, specifying if the file is to be found on the ``sd`` or not. + Optionally can also directly start the print after selecting the file. + + Arguments: + path (str): The path to select for printing. Either an absolute path or relative path to a local file in + the uploads folder or a filename on the printer's SD card. + sd (boolean): Indicates whether the file is on the printer's SD card or not. + printAfterSelect (boolean): Indicates whether a print should be started + after the file is selected. + tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle + + Raises: + InvalidFileType: if the file is not a machinecode file and hence cannot be printed + InvalidFileLocation: if an absolute path was provided and not contained within local storage or + doesn't exist + """ + raise NotImplementedError() + + def unselect_file(self, *args, **kwargs): + """ + Unselects and currently selected file. + """ + raise NotImplementedError() + + def start_print(self, tags=None, *args, **kwargs): + """ + Starts printing the currently selected file. If no file is currently selected, does nothing. + + Arguments: + tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle + """ + raise NotImplementedError() + + def pause_print(self, tags=None, *args, **kwargs): + """ + Pauses the current print job if it is currently running, does nothing otherwise. + + Arguments: + tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle + """ + raise NotImplementedError() + + def resume_print(self, tags=None, *args, **kwargs): + """ + Resumes the current print job if it is currently paused, does nothing otherwise. + + Arguments: + tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle + """ + raise NotImplementedError() + + def toggle_pause_print(self, tags=None, *args, **kwargs): + """ + Pauses the current print job if it is currently running or resumes it if it is currently paused. + + Arguments: + tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle + """ + if self.is_printing(): + self.pause_print(tags=tags, *args, **kwargs) + elif self.is_paused(): + self.resume_print(tags=tags, *args, **kwargs) + + def cancel_print(self, tags=None, *args, **kwargs): + """ + Cancels the current print job. + + Arguments: + tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle + """ + raise NotImplementedError() + + def log_lines(self, *lines): + """ + Logs the provided lines to the printer log and serial.log + Args: + *lines: the lines to log + """ + pass + + def get_state_string(self, *args, **kwargs): + """ + Returns: + (str) A human readable string corresponding to the current communication state. + """ + raise NotImplementedError() + + def get_state_id(self, *args, **kwargs): + """ + Identifier of the current communication state. + + Possible values are: + + * OPEN_SERIAL + * DETECT_SERIAL + * DETECT_BAUDRATE + * CONNECTING + * OPERATIONAL + * PRINTING + * PAUSED + * CLOSED + * ERROR + * CLOSED_WITH_ERROR + * TRANSFERING_FILE + * OFFLINE + * UNKNOWN + * NONE + + Returns: + (str) A unique identifier corresponding to the current communication state. + """ + + def get_current_data(self, *args, **kwargs): + """ + Returns: + (dict) The current state data. + """ + raise NotImplementedError() + + def get_current_job(self, *args, **kwargs): + """ + Returns: + (dict) The data of the current job. + """ + raise NotImplementedError() + + def get_current_temperatures(self, *args, **kwargs): + """ + Returns: + (dict) The current temperatures. + """ + raise NotImplementedError() + + def get_temperature_history(self, *args, **kwargs): + """ + Returns: + (list) The temperature history. + """ + raise NotImplementedError() + + def get_current_connection(self, *args, **kwargs): + """ + Returns: + (tuple) The current connection information as a 4-tuple ``(connection_string, port, baudrate, printer_profile)``. + If the printer is currently not connected, the tuple will be ``("Closed", None, None, None)``. + """ + raise NotImplementedError() + + def is_closed_or_error(self, *args, **kwargs): + """ + Returns: + (boolean) Whether the printer is currently disconnected and/or in an error state. + """ + raise NotImplementedError() + + def is_operational(self, *args, **kwargs): + """ + Returns: + (boolean) Whether the printer is currently connected and available. + """ + raise NotImplementedError() + + def is_printing(self, *args, **kwargs): + """ + Returns: + (boolean) Whether the printer is currently printing. + """ + raise NotImplementedError() + + def is_cancelling(self, *args, **kwargs): + """ + Returns: + (boolean) Whether the printer is currently cancelling a print. + """ + raise NotImplementedError() + + def is_pausing(self, *args, **kwargs): + """ + Returns: + (boolean) Whether the printer is currently pausing a print. + """ + raise NotImplementedError() + + def is_paused(self, *args, **kwargs): + """ + Returns: + (boolean) Whether the printer is currently paused. + """ + raise NotImplementedError() + + def is_error(self, *args, **kwargs): + """ + Returns: + (boolean) Whether the printer is currently in an error state. + """ + raise NotImplementedError() + + def is_ready(self, *args, **kwargs): + """ + Returns: + (boolean) Whether the printer is currently operational and ready for new print jobs (not printing). + """ + raise NotImplementedError() + + def register_callback(self, callback, *args, **kwargs): + """ + Registers a :class:`PrinterCallback` with the instance. + + Arguments: + callback (PrinterCallback): The callback object to register. + """ + raise NotImplementedError() + + def unregister_callback(self, callback, *args, **kwargs): + """ + Unregisters a :class:`PrinterCallback` from the instance. + + Arguments: + callback (PrinterCallback): The callback object to unregister. + """ + raise NotImplementedError() + + def send_initial_callback(self, callback): + """ + Sends the initial printer update to :class:`PrinterCallback`. + + Arguments: + callback (PrinterCallback): The callback object to send initial data to. + """ + raise NotImplementedError() class PrinterCallback(object): - def on_printer_add_log(self, data): - """ - Called when the :class:`PrinterInterface` receives a new communication log entry from the communication layer. + def on_printer_add_log(self, data): + """ + Called when the :class:`PrinterInterface` receives a new communication log entry from the communication layer. - Arguments: - data (str): The received log line. - """ - pass + Arguments: + data (str): The received log line. + """ + pass - def on_printer_add_message(self, data): - """ - Called when the :class:`PrinterInterface` receives a new message from the communication layer. + def on_printer_add_message(self, data): + """ + Called when the :class:`PrinterInterface` receives a new message from the communication layer. - Arguments: - data (str): The received message. - """ - pass + Arguments: + data (str): The received message. + """ + pass - def on_printer_add_temperature(self, data): - """ - Called when the :class:`PrinterInterface` receives a new temperature data set from the communication layer. + def on_printer_add_temperature(self, data): + """ + Called when the :class:`PrinterInterface` receives a new temperature data set from the communication layer. - ``data`` is a ``dict`` of the following structure:: + ``data`` is a ``dict`` of the following structure:: - tool0: - actual: - target: - ... - bed: - actual: - target: - chamber: - actual: - target: + tool0: + actual: + target: + ... + bed: + actual: + target: + chamber: + actual: + target: - Arguments: - data (dict): A dict of all current temperatures in the format as specified above - """ - pass + Arguments: + data (dict): A dict of all current temperatures in the format as specified above + """ + pass - def on_printer_received_registered_message(self, name, output): - """ - Called when the :class:`PrinterInterface` received a registered message, e.g. from a feedback command. + def on_printer_received_registered_message(self, name, output): + """ + Called when the :class:`PrinterInterface` received a registered message, e.g. from a feedback command. - Arguments: - name (str): Name of the registered message (e.g. the feedback command) - output (str): Output for the registered message - """ - pass + Arguments: + name (str): Name of the registered message (e.g. the feedback command) + output (str): Output for the registered message + """ + pass - def on_printer_send_initial_data(self, data): - """ - Called when registering as a callback with the :class:`PrinterInterface` to receive the initial data (state, - log and temperature history etc) from the printer. + def on_printer_send_initial_data(self, data): + """ + Called when registering as a callback with the :class:`PrinterInterface` to receive the initial data (state, + log and temperature history etc) from the printer. - ``data`` is a ``dict`` of the following structure:: + ``data`` is a ``dict`` of the following structure:: - temps: - - time: - tool0: - actual: - target: - ... - bed: - actual: - target: - - ... - logs: - messages: + temps: + - time: + tool0: + actual: + target: + ... + bed: + actual: + target: + - ... + logs: + messages: - Arguments: - data (dict): The initial data in the format as specified above. - """ - pass + Arguments: + data (dict): The initial data in the format as specified above. + """ + pass - def on_printer_send_current_data(self, data): - """ - Called when the internal state of the :class:`PrinterInterface` changes, due to changes in the printer state, - temperatures, log lines, job progress etc. Updates via this method are guaranteed to be throttled to a maximum - of 2 calls per second. + def on_printer_send_current_data(self, data): + """ + Called when the internal state of the :class:`PrinterInterface` changes, due to changes in the printer state, + temperatures, log lines, job progress etc. Updates via this method are guaranteed to be throttled to a maximum + of 2 calls per second. - ``data`` is a ``dict`` of the following structure:: + ``data`` is a ``dict`` of the following structure:: - state: - text: - flags: - operational: - printing: - closedOrError: - error: - paused: - ready: - sdReady: - job: - file: - name: , - size: , - origin: , - date: - estimatedPrintTime: - lastPrintTime: - filament: - length: - volume: - progress: - completion: - filepos: - printTime: - printTimeLeft: - currentZ: - offsets: + state: + text: + flags: + operational: + printing: + closedOrError: + error: + paused: + ready: + sdReady: + job: + file: + name: , + size: , + origin: , + date: + estimatedPrintTime: + lastPrintTime: + filament: + length: + volume: + progress: + completion: + filepos: + printTime: + printTimeLeft: + currentZ: + offsets: + + Arguments: + data (dict): The current data in the format as specified above. + """ + pass - Arguments: - data (dict): The current data in the format as specified above. - """ - pass class UnknownScript(Exception): - def __init__(self, name, *args, **kwargs): - self.name = name + def __init__(self, name, *args, **kwargs): + self.name = name + class InvalidFileLocation(Exception): - pass + pass + class InvalidFileType(Exception): - pass + pass diff --git a/src/octoprint/printer/estimation.py b/src/octoprint/printer/estimation.py index 228bc6353..29e530160 100644 --- a/src/octoprint/printer/estimation.py +++ b/src/octoprint/printer/estimation.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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" @@ -10,229 +10,265 @@ from octoprint.settings import settings class PrintTimeEstimator(object): - """ - Estimator implementation. + """ + Estimator implementation. - Subclass this and register via the octoprint.printer.estimation.factory hook to provide your own implementation. - """ + Subclass this and register via the octoprint.printer.estimation.factory hook to provide your own implementation. + """ - def __init__(self, job_type): - self.stats_weighing_until = settings().getFloat(["estimation", "printTime", "statsWeighingUntil"]) - self.validity_range = settings().getFloat(["estimation", "printTime", "validityRange"]) - self.force_dumb_from_percent = settings().getFloat(["estimation", "printTime", "forceDumbFromPercent"]) - self.force_dumb_after_min = settings().getFloat(["estimation", "printTime", "forceDumbAfterMin"]) + def __init__(self, job_type): + self.stats_weighing_until = settings().getFloat( + ["estimation", "printTime", "statsWeighingUntil"] + ) + self.validity_range = settings().getFloat( + ["estimation", "printTime", "validityRange"] + ) + self.force_dumb_from_percent = settings().getFloat( + ["estimation", "printTime", "forceDumbFromPercent"] + ) + self.force_dumb_after_min = settings().getFloat( + ["estimation", "printTime", "forceDumbAfterMin"] + ) - threshold = None - rolling_window = None - countdown = None + threshold = None + rolling_window = None + countdown = None - if job_type == "local" or job_type == "sdcard": - # we are happy if the average of the estimates stays within 60s of the prior one - threshold = settings().getFloat(["estimation", "printTime", "stableThreshold"]) + if job_type == "local" or job_type == "sdcard": + # we are happy if the average of the estimates stays within 60s of the prior one + threshold = settings().getFloat( + ["estimation", "printTime", "stableThreshold"] + ) - if job_type == "sdcard": - # we are interesting in a rolling window of roughly the last 15s, so the number of entries has to be derived - # by that divided by the sd status polling interval - interval = settings().getFloat(["serial", "timeout", "sdStatus"]) - if interval <= 0: - interval = 1.0 - rolling_window = int(15 // interval) - if rolling_window < 1: - rolling_window = 1 + if job_type == "sdcard": + # we are interesting in a rolling window of roughly the last 15s, so the number of entries has to be derived + # by that divided by the sd status polling interval + interval = settings().getFloat(["serial", "timeout", "sdStatus"]) + if interval <= 0: + interval = 1.0 + rolling_window = int(15 // interval) + if rolling_window < 1: + rolling_window = 1 - # we are happy when one rolling window has been stable - countdown = rolling_window + # we are happy when one rolling window has been stable + countdown = rolling_window - self._data = TimeEstimationHelper(rolling_window=rolling_window, countdown=countdown, threshold=threshold) + self._data = TimeEstimationHelper( + rolling_window=rolling_window, countdown=countdown, threshold=threshold + ) - def estimate(self, progress, printTime, cleanedPrintTime, statisticalTotalPrintTime, statisticalTotalPrintTimeType): - """ - Tries to estimate the print time left for the print job + def estimate( + self, + progress, + printTime, + cleanedPrintTime, + statisticalTotalPrintTime, + statisticalTotalPrintTimeType, + ): + """ + Tries to estimate the print time left for the print job - This is somewhat horrible since accurate print time estimation is pretty much impossible to - achieve, considering that we basically have only two data points (current progress in file and - time needed for that so far - former prints or a file analysis might not have happened or simply - be completely impossible e.g. if the file is stored on the printer's SD card) and - hence can only do a linear estimation of a completely non-linear process. That's a recipe - for inaccurate predictions right there. Yay. + This is somewhat horrible since accurate print time estimation is pretty much impossible to + achieve, considering that we basically have only two data points (current progress in file and + time needed for that so far - former prints or a file analysis might not have happened or simply + be completely impossible e.g. if the file is stored on the printer's SD card) and + hence can only do a linear estimation of a completely non-linear process. That's a recipe + for inaccurate predictions right there. Yay. - Anyhow, here's how this implementation works. This method gets the current progress in the - printed file (percentage based on bytes read vs total bytes), the print time that elapsed, - the same print time with the heat up times subtracted (if possible) and if available also - some statistical total print time (former prints or a result from the GCODE analysis). + Anyhow, here's how this implementation works. This method gets the current progress in the + printed file (percentage based on bytes read vs total bytes), the print time that elapsed, + the same print time with the heat up times subtracted (if possible) and if available also + some statistical total print time (former prints or a result from the GCODE analysis). - 1. First get an "intelligent" estimate based on the :class:`~octoprint.printer.estimation.TimeEstimationHelper`. - That thing tries to detect if the estimation based on our progress and time needed for that becomes - stable over time through a rolling window and only returns a result once that appears to be the - case. - 2. If we have any statistical data (former prints or a result from the GCODE analysis) - but no intelligent estimate yet, we'll use that for the next step. Otherwise, up to a certain percentage - in the print we do a percentage based weighing of the statistical data and the intelligent - estimate - the closer to the beginning of the print, the more precedence for the statistical - data, the closer to the cut off point, the more precedence for the intelligent estimate. This - is our preliminary total print time. - 3. If the total print time is set, we do a sanity check for it. Based on the total print time - estimate and the time we already spent printing, we calculate at what percentage we SHOULD be - and compare that to the percentage at which we actually ARE. If it's too far off, our total - can't be trusted and we fall back on the dumb estimate. Same if the time we spent printing is - already higher than our total estimate. - 4. If we do NOT have a total print time estimate yet but we've been printing for longer than - a configured amount of minutes or are further in the file than a configured percentage, we - also use the dumb estimate for now. + 1. First get an "intelligent" estimate based on the :class:`~octoprint.printer.estimation.TimeEstimationHelper`. + That thing tries to detect if the estimation based on our progress and time needed for that becomes + stable over time through a rolling window and only returns a result once that appears to be the + case. + 2. If we have any statistical data (former prints or a result from the GCODE analysis) + but no intelligent estimate yet, we'll use that for the next step. Otherwise, up to a certain percentage + in the print we do a percentage based weighing of the statistical data and the intelligent + estimate - the closer to the beginning of the print, the more precedence for the statistical + data, the closer to the cut off point, the more precedence for the intelligent estimate. This + is our preliminary total print time. + 3. If the total print time is set, we do a sanity check for it. Based on the total print time + estimate and the time we already spent printing, we calculate at what percentage we SHOULD be + and compare that to the percentage at which we actually ARE. If it's too far off, our total + can't be trusted and we fall back on the dumb estimate. Same if the time we spent printing is + already higher than our total estimate. + 4. If we do NOT have a total print time estimate yet but we've been printing for longer than + a configured amount of minutes or are further in the file than a configured percentage, we + also use the dumb estimate for now. - Yes, all this still produces horribly inaccurate results. But we have to do this live during the print and - hence can't produce to much computational overhead, we do not have any insight into the firmware implementation - with regards to planner setup and acceleration settings, we might not even have access to the printed file's - contents and such we need to find something that works "mostly" all of the time without costing too many - resources. Feel free to propose a better solution within the above limitations (and I mean that, this solution - here makes me unhappy). + Yes, all this still produces horribly inaccurate results. But we have to do this live during the print and + hence can't produce to much computational overhead, we do not have any insight into the firmware implementation + with regards to planner setup and acceleration settings, we might not even have access to the printed file's + contents and such we need to find something that works "mostly" all of the time without costing too many + resources. Feel free to propose a better solution within the above limitations (and I mean that, this solution + here makes me unhappy). - Args: - progress (float or None): Current percentage in the printed file - printTime (float or None): Print time elapsed so far - cleanedPrintTime (float or None): Print time elapsed minus the time needed for getting up to temperature - (if detectable). - statisticalTotalPrintTime (float or None): Total print time of past prints against same printer profile, - or estimated total print time from GCODE analysis. - statisticalTotalPrintTimeType (str or None): Type of statistical print time, either "average" (total time - of former prints) or "analysis" + Args: + progress (float or None): Current percentage in the printed file + printTime (float or None): Print time elapsed so far + cleanedPrintTime (float or None): Print time elapsed minus the time needed for getting up to temperature + (if detectable). + statisticalTotalPrintTime (float or None): Total print time of past prints against same printer profile, + or estimated total print time from GCODE analysis. + statisticalTotalPrintTimeType (str or None): Type of statistical print time, either "average" (total time + of former prints) or "analysis" - Returns: - (2-tuple) estimated print time left or None if not proper estimate could be made at all, origin of estimation - """ + Returns: + (2-tuple) estimated print time left or None if not proper estimate could be made at all, origin of estimation + """ - if progress is None or progress == 0 or printTime is None or cleanedPrintTime is None: - return None, None + if ( + progress is None + or progress == 0 + or printTime is None + or cleanedPrintTime is None + ): + return None, None - dumbTotalPrintTime = printTime / progress - estimatedTotalPrintTime = self.estimate_total(progress, cleanedPrintTime) - totalPrintTime = estimatedTotalPrintTime + dumbTotalPrintTime = printTime / progress + estimatedTotalPrintTime = self.estimate_total(progress, cleanedPrintTime) + totalPrintTime = estimatedTotalPrintTime - printTimeLeftOrigin = "estimate" - if statisticalTotalPrintTime is not None: - if estimatedTotalPrintTime is None: - # no estimate yet, we'll use the statistical total - totalPrintTime = statisticalTotalPrintTime - printTimeLeftOrigin = statisticalTotalPrintTimeType + printTimeLeftOrigin = "estimate" + if statisticalTotalPrintTime is not None: + if estimatedTotalPrintTime is None: + # no estimate yet, we'll use the statistical total + totalPrintTime = statisticalTotalPrintTime + printTimeLeftOrigin = statisticalTotalPrintTimeType - else: - if progress < self.stats_weighing_until: - # still inside weighing range, use part stats, part current estimate - sub_progress = progress * (1 / self.stats_weighing_until) - if sub_progress > 1.0: - sub_progress = 1.0 - printTimeLeftOrigin = "mixed-" + statisticalTotalPrintTimeType - else: - # use only the current estimate - sub_progress = 1.0 - printTimeLeftOrigin = "estimate" + else: + if progress < self.stats_weighing_until: + # still inside weighing range, use part stats, part current estimate + sub_progress = progress * (1 / self.stats_weighing_until) + if sub_progress > 1.0: + sub_progress = 1.0 + printTimeLeftOrigin = "mixed-" + statisticalTotalPrintTimeType + else: + # use only the current estimate + sub_progress = 1.0 + printTimeLeftOrigin = "estimate" - # combine - totalPrintTime = - sub_progress * statisticalTotalPrintTime \ - + sub_progress * estimatedTotalPrintTime + # combine + totalPrintTime = ( + -sub_progress * statisticalTotalPrintTime + + sub_progress * estimatedTotalPrintTime + ) - printTimeLeft = None - if totalPrintTime is not None: - # sanity check current total print time estimate - assumed_progress = cleanedPrintTime / totalPrintTime - min_progress = progress - self.validity_range - max_progress = progress + self.validity_range + printTimeLeft = None + if totalPrintTime is not None: + # sanity check current total print time estimate + assumed_progress = cleanedPrintTime / totalPrintTime + min_progress = progress - self.validity_range + max_progress = progress + self.validity_range - if min_progress <= assumed_progress <= max_progress and totalPrintTime > cleanedPrintTime: - # appears sane, we'll use it - printTimeLeft = totalPrintTime - cleanedPrintTime + if ( + min_progress <= assumed_progress <= max_progress + and totalPrintTime > cleanedPrintTime + ): + # appears sane, we'll use it + printTimeLeft = totalPrintTime - cleanedPrintTime - else: - # too far from the actual progress or negative, - # we use the dumb print time instead - printTimeLeft = dumbTotalPrintTime - cleanedPrintTime - printTimeLeftOrigin = "linear" + else: + # too far from the actual progress or negative, + # we use the dumb print time instead + printTimeLeft = dumbTotalPrintTime - cleanedPrintTime + printTimeLeftOrigin = "linear" - else: - printTimeLeftOrigin = "linear" - if progress > self.force_dumb_from_percent or \ - cleanedPrintTime >= self.force_dumb_after_min * 60: - # more than x% or y min printed and still no real estimate, ok, we'll use the dumb variant :/ - printTimeLeft = dumbTotalPrintTime - cleanedPrintTime + else: + printTimeLeftOrigin = "linear" + if ( + progress > self.force_dumb_from_percent + or cleanedPrintTime >= self.force_dumb_after_min * 60 + ): + # more than x% or y min printed and still no real estimate, ok, we'll use the dumb variant :/ + printTimeLeft = dumbTotalPrintTime - cleanedPrintTime - if printTimeLeft is not None and printTimeLeft < 0: - # shouldn't actually happen, but let's make sure - printTimeLeft = None + if printTimeLeft is not None and printTimeLeft < 0: + # shouldn't actually happen, but let's make sure + printTimeLeft = None - return printTimeLeft, printTimeLeftOrigin + return printTimeLeft, printTimeLeftOrigin - def estimate_total(self, progress, printTime): - if not progress or not printTime or not self._data: - return None - else: - return self._data.update(printTime / progress) + def estimate_total(self, progress, printTime): + if not progress or not printTime or not self._data: + return None + else: + return self._data.update(printTime / progress) class TimeEstimationHelper(object): - STABLE_THRESHOLD = 0.1 - STABLE_COUNTDOWN = 250 - STABLE_ROLLING_WINDOW = 250 + STABLE_THRESHOLD = 0.1 + STABLE_COUNTDOWN = 250 + STABLE_ROLLING_WINDOW = 250 - def __init__(self, rolling_window=None, countdown=None, threshold=None): - if rolling_window is None: - rolling_window = self.__class__.STABLE_ROLLING_WINDOW - if countdown is None: - countdown = self.__class__.STABLE_COUNTDOWN - if threshold is None: - threshold = self.__class__.STABLE_THRESHOLD + def __init__(self, rolling_window=None, countdown=None, threshold=None): + if rolling_window is None: + rolling_window = self.__class__.STABLE_ROLLING_WINDOW + if countdown is None: + countdown = self.__class__.STABLE_COUNTDOWN + if threshold is None: + threshold = self.__class__.STABLE_THRESHOLD - self._rolling_window = rolling_window - self._countdown = countdown - self._threshold = threshold + self._rolling_window = rolling_window + self._countdown = countdown + self._threshold = threshold - import collections - self._distances = collections.deque([], self._rolling_window) - self._totals = collections.deque([], self._rolling_window) - self._sum_total = 0 - self._count = 0 - self._stable_counter = -1 + import collections - def is_stable(self): - return self._stable_counter >= self._countdown + self._distances = collections.deque([], self._rolling_window) + self._totals = collections.deque([], self._rolling_window) + self._sum_total = 0 + self._count = 0 + self._stable_counter = -1 - def update(self, new_estimate): - old_average_total = self.average_total + def is_stable(self): + return self._stable_counter >= self._countdown - self._sum_total += new_estimate - self._totals.append(new_estimate) - self._count += 1 + def update(self, new_estimate): + old_average_total = self.average_total - if old_average_total: - self._distances.append(abs(self.average_total - old_average_total)) + self._sum_total += new_estimate + self._totals.append(new_estimate) + self._count += 1 - if -self._threshold < self.average_distance < self._threshold: - self._stable_counter += 1 - else: - self._stable_counter = -1 + if old_average_total: + self._distances.append(abs(self.average_total - old_average_total)) - if self.is_stable(): - return self.average_total_rolling - else: - return None + if -self._threshold < self.average_distance < self._threshold: + self._stable_counter += 1 + else: + self._stable_counter = -1 - @property - def average_total(self): - if not self._count: - return 0 - else: - return self._sum_total / self._count + if self.is_stable(): + return self.average_total_rolling + else: + return None - @property - def average_total_rolling(self): - if not self._count or self._count < self._rolling_window or not len(self._totals): - return -1 - else: - return sum(self._totals) / len(self._totals) + @property + def average_total(self): + if not self._count: + return 0 + else: + return self._sum_total / self._count - @property - def average_distance(self): - if not self._count or self._count < self._rolling_window + 1 or not len(self._distances): - return -1 - else: - return sum(self._distances) / len(self._distances) + @property + def average_total_rolling(self): + if not self._count or self._count < self._rolling_window or not len(self._totals): + return -1 + else: + return sum(self._totals) / len(self._totals) + + @property + def average_distance(self): + if ( + not self._count + or self._count < self._rolling_window + 1 + or not len(self._distances) + ): + return -1 + else: + return sum(self._distances) / len(self._distances) diff --git a/src/octoprint/printer/profile.py b/src/octoprint/printer/profile.py index 13ab10d94..25d0e47e2 100644 --- a/src/octoprint/printer/profile.py +++ b/src/octoprint/printer/profile.py @@ -143,7 +143,7 @@ A printer profile is a ``dict`` of the following structure: """ __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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" @@ -154,502 +154,664 @@ import re import logging try: - from os import scandir + from os import scandir except ImportError: - from scandir import scandir + from scandir import scandir from octoprint.settings import settings from octoprint.util import dict_merge, dict_sanitize, dict_contains_keys, is_hidden_path + class SaveError(Exception): - """Saving a profile failed""" - pass + """Saving a profile failed""" + + pass + class CouldNotOverwriteError(SaveError): - """Overwriting of a profile not allowed""" - pass + """Overwriting of a profile not allowed""" + + pass + class InvalidProfileError(Exception): - """Profile invalid""" - pass + """Profile invalid""" + + pass + class BedFormFactor(object): - """Valid values for bed form factor""" + """Valid values for bed form factor""" - RECTANGULAR = "rectangular" - """Rectangular bed""" + RECTANGULAR = "rectangular" + """Rectangular bed""" - CIRCULAR = "circular" - """Circular bed""" + CIRCULAR = "circular" + """Circular bed""" + + @classmethod + def values(cls): + return [ + getattr(cls, name) + for name in cls.__dict__ + if not (name.startswith("__") or name == "values") + ] - @classmethod - def values(cls): - return [getattr(cls, name) for name in cls.__dict__ if not (name.startswith("__") or name == "values")] BedTypes = BedFormFactor """Deprecated name of :class:`BedFormFactors`""" + class BedOrigin(object): - """Valid values for bed origin""" + """Valid values for bed origin""" - LOWERLEFT = "lowerleft" - """Origin at lower left corner of the bed when looking from the top""" + LOWERLEFT = "lowerleft" + """Origin at lower left corner of the bed when looking from the top""" - CENTER = "center" - """Origin at the center of the bed when looking from top""" + CENTER = "center" + """Origin at the center of the bed when looking from top""" + + @classmethod + def values(cls): + return [ + getattr(cls, name) + for name in cls.__dict__ + if not (name.startswith("__") or name == "values") + ] - @classmethod - def values(cls): - return [getattr(cls, name) for name in cls.__dict__ if not (name.startswith("__") or name == "values")] class PrinterProfileManager(object): - """ - Manager for printer profiles. Offers methods to select the globally used printer profile and to list, add, remove, - load and save printer profiles. - """ - - default = {"id": "_default", - "name": "Default", - "model": "Generic RepRap Printer", - "color": "default", - "volume": {"width": 200, - "depth": 200, - "height": 200, - "formFactor": BedFormFactor.RECTANGULAR, - "origin": BedOrigin.LOWERLEFT, - "custom_box": False}, - "heatedBed": True, - "heatedChamber": False, - "extruder": {"count": 1, - "offsets": [ - (0, 0) - ], - "nozzleDiameter": 0.4, - "sharedNozzle": False}, - "axes": {"x": {"speed": 6000, "inverted": False}, - "y": {"speed": 6000, "inverted": False}, - "z": {"speed": 200, "inverted": False}, - "e": {"speed": 300, "inverted": False}}} - - def __init__(self): - self._current = None - self._folder = settings().getBaseFolder("printerProfiles") - self._logger = logging.getLogger(__name__) - - self._migrate_old_default_profile() - self._verify_default_available() - - def _migrate_old_default_profile(self): - default_overrides = settings().get(["printerProfiles", "defaultProfile"]) - if not default_overrides: - return - - if self.exists("_default"): - return - - if not isinstance(default_overrides, dict): - self._logger.warning("Existing default profile from settings is not a valid profile, refusing to migrate: {!r}".format(default_overrides)) - return - - default_overrides["id"] = "_default" - self.save(default_overrides) - - settings().set(["printerProfiles", "defaultProfile"], None) - settings().save() - - self._logger.info("Migrated default printer profile from settings to _default.profile: {!r}".format(default_overrides)) - - def _verify_default_available(self): - default_id = settings().get(["printerProfiles", "default"]) - if default_id is None: - default_id = "_default" - - if not self.exists(default_id): - if not self.exists("_default"): - if default_id == "_default": - self._logger.error("Profile _default does not exist, creating _default again and setting it as default") - else: - self._logger.error("Selected default profile {} and _default do not exist, creating _default again and setting it as default".format(default_id)) - self.save(self.__class__.default, allow_overwrite=True, make_default=True) - else: - self._logger.error("Selected default profile {} does not exists, resetting to _default".format(default_id)) - settings().set(["printerProfiles", "default"], "_default") - settings().save() - default_id = "_default" - - profile = self.get(default_id) - if profile is None: - self._logger.error("Selected default profile {} is invalid, resetting to default values".format(default_id)) - profile = copy.deepcopy(self.__class__.default) - profile["id"] = default_id - self.save(self.__class__.default, allow_overwrite=True, make_default=True) - - def select(self, identifier): - if identifier is None or not self.exists(identifier): - self._current = self.get_default() - return False - else: - self._current = self.get(identifier) - if self._current is None: - self._logger.error("Profile {} is invalid, cannot select, falling back to default".format(identifier)) - self._current = self.get_default() - return False - else: - return True - - def deselect(self): - self._current = None - - def get_all(self): - return self._load_all() - - def get(self, identifier): - try: - if self.exists(identifier): - return self._load_from_path(self._get_profile_path(identifier)) - else: - return None - except InvalidProfileError: - return None - - def remove(self, identifier, trigger_event=False): - if self._current is not None and self._current["id"] == identifier: - return False - elif settings().get(["printerProfiles", "default"]) == identifier: - return False - - removed = self._remove_from_path(self._get_profile_path(identifier)) - if removed and trigger_event: - from octoprint.events import eventManager, Events - payload = {"identifier": identifier} - eventManager().fire(Events.PRINTER_PROFILE_DELETED, payload=payload) - - return removed - - def save(self, profile, allow_overwrite=False, make_default=False, trigger_event=False): - if "id" in profile: - identifier = profile["id"] - elif "name" in profile: - identifier = profile["name"] - else: - raise InvalidProfileError("profile must contain either id or name") - - identifier = self._sanitize(identifier) - profile["id"] = identifier - - self._migrate_profile(profile) - profile = dict_sanitize(profile, self.__class__.default) - profile = dict_merge(self.__class__.default, profile) - - path = self._get_profile_path(identifier) - is_overwrite = os.path.exists(path) - - self._save_to_path(path, profile, allow_overwrite=allow_overwrite) - - if make_default: - settings().set(["printerProfiles", "default"], identifier) - settings().save() - - if self._current is not None and self._current["id"] == identifier: - self.select(identifier) - - from octoprint.events import eventManager, Events - if trigger_event: - payload = {"identifier": identifier} - event = Events.PRINTER_PROFILE_MODIFIED if is_overwrite else Events.PRINTER_PROFILE_ADDED - eventManager().fire(event, payload=payload) - - return self.get(identifier) - - def is_default_unmodified(self): - default = settings().get(["printerProfiles", "default"]) - return default is None or default == "_default" or not self.exists("_default") - - @property - def profile_count(self): - return len(self._load_all_identifiers()) - - @property - def last_modified(self): - dates = [os.stat(self._folder).st_mtime] - dates += [entry.stat().st_mtime for entry in scandir(self._folder) if entry.name.endswith(".profile")] - return max(dates) - - def get_default(self): - default = settings().get(["printerProfiles", "default"]) - if default is not None and self.exists(default): - profile = self.get(default) - if profile is not None: - return profile - else: - self._logger.warning("Default profile {} is invalid, falling back to built-in defaults".format(default)) - - return copy.deepcopy(self.__class__.default) - - def set_default(self, identifier): - all_identifiers = self._load_all_identifiers() - if identifier is not None and not identifier in all_identifiers: - return - - settings().set(["printerProfiles", "default"], identifier) - settings().save() - - def get_current_or_default(self): - if self._current is not None: - return self._current - else: - return self.get_default() - - def get_current(self): - return self._current - - def exists(self, identifier): - if identifier is None: - return False - else: - path = self._get_profile_path(identifier) - return os.path.exists(path) and os.path.isfile(path) - - def _load_all(self): - all_identifiers = self._load_all_identifiers() - results = {} - for identifier, path in all_identifiers.items(): - try: - profile = self._load_from_path(path) - except InvalidProfileError: - self._logger.warning("Profile {} is invalid, skipping".format(identifier)) - continue - - if profile is None: - continue - - results[identifier] = dict_merge(self.__class__.default, profile) - return results - - def _load_all_identifiers(self): - results = {} - for entry in scandir(self._folder): - if is_hidden_path(entry.name) or not entry.name.endswith(".profile"): - continue - - if not entry.is_file(): - continue - - identifier = entry.name[:-len(".profile")] - results[identifier] = entry.path - return results - - def _load_from_path(self, path): - if not os.path.exists(path) or not os.path.isfile(path): - return None - - import yaml - with io.open(path, 'rt', encoding='utf-8') as f: - profile = yaml.safe_load(f) - - if profile is None or not isinstance(profile, dict): - raise InvalidProfileError("Profile is None or not a dictionary") - - if self._migrate_profile(profile): - try: - self._save_to_path(path, profile, allow_overwrite=True) - except Exception: - self._logger.exception("Tried to save profile to {path} after migrating it while loading, ran into exception".format(path=path)) - - profile = self._ensure_valid_profile(profile) - - if not profile: - self._logger.warning("Invalid profile: %s" % path) - raise InvalidProfileError() - return profile - - def _save_to_path(self, path, profile, allow_overwrite=False): - validated_profile = self._ensure_valid_profile(profile) - if not validated_profile: - raise InvalidProfileError() - - if os.path.exists(path) and not allow_overwrite: - raise SaveError("Profile %s already exists and not allowed to overwrite" % profile["id"]) - - from octoprint.util import atomic_write - import yaml - 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) - except Exception as e: - self._logger.exception("Error while trying to save profile %s" % profile["id"]) - raise SaveError("Cannot save profile %s: %s" % (profile["id"], str(e))) - - def _remove_from_path(self, path): - try: - os.remove(path) - return True - except Exception: - return False - - def _get_profile_path(self, identifier): - return os.path.join(self._folder, "%s.profile" % identifier) - - def _sanitize(self, name): - if name is None: - return None - - if "/" in name or "\\" in name: - raise ValueError("name must not contain / or \\") - - import string - valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits) - sanitized_name = ''.join(c for c in name if c in valid_chars) - sanitized_name = sanitized_name.replace(" ", "_") - return sanitized_name - - def _migrate_profile(self, profile): - # make sure profile format is up to date - modified = False - - if "volume" in profile and "formFactor" in profile["volume"] and not "origin" in profile["volume"]: - profile["volume"]["origin"] = BedOrigin.CENTER if profile["volume"]["formFactor"] == BedFormFactor.CIRCULAR else BedOrigin.LOWERLEFT - modified = True - - if "volume" in profile and not "custom_box" in profile["volume"]: - profile["volume"]["custom_box"] = False - modified = True - - if "extruder" in profile and not "sharedNozzle" in profile["extruder"]: - profile["extruder"]["sharedNozzle"] = False - modified = True - - if "extruder" in profile and "sharedNozzle" in profile["extruder"] and profile["extruder"]["sharedNozzle"]: - profile["extruder"]["offsets"] = [(0.0, 0.0)] - modified = True - - if not "heatedChamber" in profile: - profile["heatedChamber"] = False - modified = True - - return modified - - def _ensure_valid_profile(self, profile): - # ensure all keys are present - if not dict_contains_keys(self.default, profile): - self._logger.warning("Profile invalid, missing keys. Expected: {expected!r}. Actual: {actual!r}".format(expected=list(self.default.keys()), actual=list(profile.keys()))) - return False - - # conversion helper - def convert_value(profile, path, converter): - value = profile - for part in path[:-1]: - if not isinstance(value, dict) or not part in value: - raise RuntimeError("%s is not contained in profile" % ".".join(path)) - value = value[part] - - if not isinstance(value, dict) or not path[-1] in value: - raise RuntimeError("%s is not contained in profile" % ".".join(path)) - - value[path[-1]] = converter(value[path[-1]]) - - # convert ints - for path in (("extruder", "count"), ("axes", "x", "speed"), ("axes", "y", "speed"), ("axes", "z", "speed")): - try: - convert_value(profile, path, int) - except Exception as e: - self._logger.warning("Profile has invalid value for path {path!r}: {msg}".format(path=".".join(path), msg=str(e))) - return False - - # convert floats - for path in (("volume", "width"), ("volume", "depth"), ("volume", "height"), ("extruder", "nozzleDiameter")): - try: - convert_value(profile, path, float) - except Exception as e: - self._logger.warning("Profile has invalid value for path {path!r}: {msg}".format(path=".".join(path), msg=str(e))) - return False - - # convert booleans - for path in (("axes", "x", "inverted"), ("axes", "y", "inverted"), ("axes", "z", "inverted"), ("extruder", "sharedNozzle")): - try: - convert_value(profile, path, bool) - except Exception as e: - self._logger.warning("Profile has invalid value for path {path!r}: {msg}".format(path=".".join(path), msg=str(e))) - return False - - # validate form factor - if not profile["volume"]["formFactor"] in BedFormFactor.values(): - self._logger.warning("Profile has invalid value volume.formFactor: {formFactor}".format(formFactor=profile["volume"]["formFactor"])) - return False - - # validate origin type - if not profile["volume"]["origin"] in BedOrigin.values(): - self._logger.warning("Profile has invalid value in volume.origin: {origin}".format(origin=profile["volume"]["origin"])) - return False - - # ensure origin and form factor combination is legal - if profile["volume"]["formFactor"] == BedFormFactor.CIRCULAR and not profile["volume"]["origin"] == BedOrigin.CENTER: - profile["volume"]["origin"] = BedOrigin.CENTER - - # force width and depth of volume to be identical for circular beds, with width being the reference - if profile["volume"]["formFactor"] == BedFormFactor.CIRCULAR: - profile["volume"]["depth"] = profile["volume"]["width"] - - # if we have a custom bounding box, validate it - if profile["volume"]["custom_box"] and isinstance(profile["volume"]["custom_box"], dict): - if not len(profile["volume"]["custom_box"]): - profile["volume"]["custom_box"] = False - - else: - default_box = self._default_box_for_volume(profile["volume"]) - for prop, limiter in (("x_min", min), ("y_min", min), ("z_min", min), - ("x_max", max), ("y_max", max), ("z_max", max)): - if prop not in profile["volume"]["custom_box"] or profile["volume"]["custom_box"][prop] is None: - profile["volume"]["custom_box"][prop] = default_box[prop] - else: - value = profile["volume"]["custom_box"][prop] - try: - value = limiter(float(value), default_box[prop]) - profile["volume"]["custom_box"][prop] = value - except Exception: - self._logger.warning("Profile has invalid value in volume.custom_box.{}: {!r}".format(prop, value)) - return False - - # make sure we actually do have a custom box and not just the same values as the - # default box - for prop in profile["volume"]["custom_box"]: - if profile["volume"]["custom_box"][prop] != default_box[prop]: - break - else: - # exactly the same as the default box, remove custom box - profile["volume"]["custom_box"] = False - - # validate offsets - offsets = [] - for offset in profile["extruder"]["offsets"]: - if not len(offset) == 2: - self._logger.warning("Profile has an invalid extruder.offsets entry: {entry!r}".format(entry=offset)) - return False - x_offset, y_offset = offset - try: - offsets.append((float(x_offset), float(y_offset))) - except Exception: - self._logger.warning("Profile has an extruder.offsets entry with non-float values: {entry!r}".format(entry=offset)) - return False - profile["extruder"]["offsets"] = offsets - - return profile - - @staticmethod - def _default_box_for_volume(volume): - if volume["origin"] == BedOrigin.CENTER: - half_width = volume["width"] / 2.0 - half_depth = volume["depth"] / 2.0 - return {"x_min": -half_width, - "x_max": half_width, - "y_min": -half_depth, - "y_max": half_depth, - "z_min": 0.0, - "z_max": volume["height"]} - else: - return {"x_min": 0.0, - "x_max": volume["width"], - "y_min": 0.0, - "y_max": volume["depth"], - "z_min": 0.0, - "z_max": volume["height"]} + """ + Manager for printer profiles. Offers methods to select the globally used printer profile and to list, add, remove, + load and save printer profiles. + """ + + default = { + "id": "_default", + "name": "Default", + "model": "Generic RepRap Printer", + "color": "default", + "volume": { + "width": 200, + "depth": 200, + "height": 200, + "formFactor": BedFormFactor.RECTANGULAR, + "origin": BedOrigin.LOWERLEFT, + "custom_box": False, + }, + "heatedBed": True, + "heatedChamber": False, + "extruder": { + "count": 1, + "offsets": [(0, 0)], + "nozzleDiameter": 0.4, + "sharedNozzle": False, + }, + "axes": { + "x": {"speed": 6000, "inverted": False}, + "y": {"speed": 6000, "inverted": False}, + "z": {"speed": 200, "inverted": False}, + "e": {"speed": 300, "inverted": False}, + }, + } + + def __init__(self): + self._current = None + self._folder = settings().getBaseFolder("printerProfiles") + self._logger = logging.getLogger(__name__) + + self._migrate_old_default_profile() + self._verify_default_available() + + def _migrate_old_default_profile(self): + default_overrides = settings().get(["printerProfiles", "defaultProfile"]) + if not default_overrides: + return + + if self.exists("_default"): + return + + if not isinstance(default_overrides, dict): + self._logger.warning( + "Existing default profile from settings is not a valid profile, refusing to migrate: {!r}".format( + default_overrides + ) + ) + return + + default_overrides["id"] = "_default" + self.save(default_overrides) + + settings().set(["printerProfiles", "defaultProfile"], None) + settings().save() + + self._logger.info( + "Migrated default printer profile from settings to _default.profile: {!r}".format( + default_overrides + ) + ) + + def _verify_default_available(self): + default_id = settings().get(["printerProfiles", "default"]) + if default_id is None: + default_id = "_default" + + if not self.exists(default_id): + if not self.exists("_default"): + if default_id == "_default": + self._logger.error( + "Profile _default does not exist, creating _default again and setting it as default" + ) + else: + self._logger.error( + "Selected default profile {} and _default do not exist, creating _default again and setting it as default".format( + default_id + ) + ) + self.save(self.__class__.default, allow_overwrite=True, make_default=True) + else: + self._logger.error( + "Selected default profile {} does not exists, resetting to _default".format( + default_id + ) + ) + settings().set(["printerProfiles", "default"], "_default") + settings().save() + default_id = "_default" + + profile = self.get(default_id) + if profile is None: + self._logger.error( + "Selected default profile {} is invalid, resetting to default values".format( + default_id + ) + ) + profile = copy.deepcopy(self.__class__.default) + profile["id"] = default_id + self.save(self.__class__.default, allow_overwrite=True, make_default=True) + + def select(self, identifier): + if identifier is None or not self.exists(identifier): + self._current = self.get_default() + return False + else: + self._current = self.get(identifier) + if self._current is None: + self._logger.error( + "Profile {} is invalid, cannot select, falling back to default".format( + identifier + ) + ) + self._current = self.get_default() + return False + else: + return True + + def deselect(self): + self._current = None + + def get_all(self): + return self._load_all() + + def get(self, identifier): + try: + if self.exists(identifier): + return self._load_from_path(self._get_profile_path(identifier)) + else: + return None + except InvalidProfileError: + return None + + def remove(self, identifier, trigger_event=False): + if self._current is not None and self._current["id"] == identifier: + return False + elif settings().get(["printerProfiles", "default"]) == identifier: + return False + + removed = self._remove_from_path(self._get_profile_path(identifier)) + if removed and trigger_event: + from octoprint.events import eventManager, Events + + payload = {"identifier": identifier} + eventManager().fire(Events.PRINTER_PROFILE_DELETED, payload=payload) + + return removed + + def save( + self, profile, allow_overwrite=False, make_default=False, trigger_event=False + ): + if "id" in profile: + identifier = profile["id"] + elif "name" in profile: + identifier = profile["name"] + else: + raise InvalidProfileError("profile must contain either id or name") + + identifier = self._sanitize(identifier) + profile["id"] = identifier + + self._migrate_profile(profile) + profile = dict_sanitize(profile, self.__class__.default) + profile = dict_merge(self.__class__.default, profile) + + path = self._get_profile_path(identifier) + is_overwrite = os.path.exists(path) + + self._save_to_path(path, profile, allow_overwrite=allow_overwrite) + + if make_default: + settings().set(["printerProfiles", "default"], identifier) + settings().save() + + if self._current is not None and self._current["id"] == identifier: + self.select(identifier) + + from octoprint.events import eventManager, Events + + if trigger_event: + payload = {"identifier": identifier} + event = ( + Events.PRINTER_PROFILE_MODIFIED + if is_overwrite + else Events.PRINTER_PROFILE_ADDED + ) + eventManager().fire(event, payload=payload) + + return self.get(identifier) + + def is_default_unmodified(self): + default = settings().get(["printerProfiles", "default"]) + return default is None or default == "_default" or not self.exists("_default") + + @property + def profile_count(self): + return len(self._load_all_identifiers()) + + @property + def last_modified(self): + dates = [os.stat(self._folder).st_mtime] + dates += [ + entry.stat().st_mtime + for entry in scandir(self._folder) + if entry.name.endswith(".profile") + ] + return max(dates) + + def get_default(self): + default = settings().get(["printerProfiles", "default"]) + if default is not None and self.exists(default): + profile = self.get(default) + if profile is not None: + return profile + else: + self._logger.warning( + "Default profile {} is invalid, falling back to built-in defaults".format( + default + ) + ) + + return copy.deepcopy(self.__class__.default) + + def set_default(self, identifier): + all_identifiers = self._load_all_identifiers() + if identifier is not None and not identifier in all_identifiers: + return + + settings().set(["printerProfiles", "default"], identifier) + settings().save() + + def get_current_or_default(self): + if self._current is not None: + return self._current + else: + return self.get_default() + + def get_current(self): + return self._current + + def exists(self, identifier): + if identifier is None: + return False + else: + path = self._get_profile_path(identifier) + return os.path.exists(path) and os.path.isfile(path) + + def _load_all(self): + all_identifiers = self._load_all_identifiers() + results = {} + for identifier, path in all_identifiers.items(): + try: + profile = self._load_from_path(path) + except InvalidProfileError: + self._logger.warning("Profile {} is invalid, skipping".format(identifier)) + continue + + if profile is None: + continue + + results[identifier] = dict_merge(self.__class__.default, profile) + return results + + def _load_all_identifiers(self): + results = {} + for entry in scandir(self._folder): + if is_hidden_path(entry.name) or not entry.name.endswith(".profile"): + continue + + if not entry.is_file(): + continue + + identifier = entry.name[: -len(".profile")] + results[identifier] = entry.path + return results + + def _load_from_path(self, path): + if not os.path.exists(path) or not os.path.isfile(path): + return None + + import yaml + + with io.open(path, "rt", encoding="utf-8") as f: + profile = yaml.safe_load(f) + + if profile is None or not isinstance(profile, dict): + raise InvalidProfileError("Profile is None or not a dictionary") + + if self._migrate_profile(profile): + try: + self._save_to_path(path, profile, allow_overwrite=True) + except Exception: + self._logger.exception( + "Tried to save profile to {path} after migrating it while loading, ran into exception".format( + path=path + ) + ) + + profile = self._ensure_valid_profile(profile) + + if not profile: + self._logger.warning("Invalid profile: %s" % path) + raise InvalidProfileError() + return profile + + def _save_to_path(self, path, profile, allow_overwrite=False): + validated_profile = self._ensure_valid_profile(profile) + if not validated_profile: + raise InvalidProfileError() + + if os.path.exists(path) and not allow_overwrite: + raise SaveError( + "Profile %s already exists and not allowed to overwrite" % profile["id"] + ) + + from octoprint.util import atomic_write + import yaml + + 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 + ) + except Exception as e: + self._logger.exception( + "Error while trying to save profile %s" % profile["id"] + ) + raise SaveError("Cannot save profile %s: %s" % (profile["id"], str(e))) + + def _remove_from_path(self, path): + try: + os.remove(path) + return True + except Exception: + return False + + def _get_profile_path(self, identifier): + return os.path.join(self._folder, "%s.profile" % identifier) + + def _sanitize(self, name): + if name is None: + return None + + if "/" in name or "\\" in name: + raise ValueError("name must not contain / or \\") + + import string + + valid_chars = "-_.() {ascii}{digits}".format( + ascii=string.ascii_letters, digits=string.digits + ) + sanitized_name = "".join(c for c in name if c in valid_chars) + sanitized_name = sanitized_name.replace(" ", "_") + return sanitized_name + + def _migrate_profile(self, profile): + # make sure profile format is up to date + modified = False + + if ( + "volume" in profile + and "formFactor" in profile["volume"] + and not "origin" in profile["volume"] + ): + profile["volume"]["origin"] = ( + BedOrigin.CENTER + if profile["volume"]["formFactor"] == BedFormFactor.CIRCULAR + else BedOrigin.LOWERLEFT + ) + modified = True + + if "volume" in profile and not "custom_box" in profile["volume"]: + profile["volume"]["custom_box"] = False + modified = True + + if "extruder" in profile and not "sharedNozzle" in profile["extruder"]: + profile["extruder"]["sharedNozzle"] = False + modified = True + + if ( + "extruder" in profile + and "sharedNozzle" in profile["extruder"] + and profile["extruder"]["sharedNozzle"] + ): + profile["extruder"]["offsets"] = [(0.0, 0.0)] + modified = True + + if not "heatedChamber" in profile: + profile["heatedChamber"] = False + modified = True + + return modified + + def _ensure_valid_profile(self, profile): + # ensure all keys are present + if not dict_contains_keys(self.default, profile): + self._logger.warning( + "Profile invalid, missing keys. Expected: {expected!r}. Actual: {actual!r}".format( + expected=list(self.default.keys()), actual=list(profile.keys()) + ) + ) + return False + + # conversion helper + def convert_value(profile, path, converter): + value = profile + for part in path[:-1]: + if not isinstance(value, dict) or not part in value: + raise RuntimeError("%s is not contained in profile" % ".".join(path)) + value = value[part] + + if not isinstance(value, dict) or not path[-1] in value: + raise RuntimeError("%s is not contained in profile" % ".".join(path)) + + value[path[-1]] = converter(value[path[-1]]) + + # convert ints + for path in ( + ("extruder", "count"), + ("axes", "x", "speed"), + ("axes", "y", "speed"), + ("axes", "z", "speed"), + ): + try: + convert_value(profile, path, int) + except Exception as e: + self._logger.warning( + "Profile has invalid value for path {path!r}: {msg}".format( + path=".".join(path), msg=str(e) + ) + ) + return False + + # convert floats + for path in ( + ("volume", "width"), + ("volume", "depth"), + ("volume", "height"), + ("extruder", "nozzleDiameter"), + ): + try: + convert_value(profile, path, float) + except Exception as e: + self._logger.warning( + "Profile has invalid value for path {path!r}: {msg}".format( + path=".".join(path), msg=str(e) + ) + ) + return False + + # convert booleans + for path in ( + ("axes", "x", "inverted"), + ("axes", "y", "inverted"), + ("axes", "z", "inverted"), + ("extruder", "sharedNozzle"), + ): + try: + convert_value(profile, path, bool) + except Exception as e: + self._logger.warning( + "Profile has invalid value for path {path!r}: {msg}".format( + path=".".join(path), msg=str(e) + ) + ) + return False + + # validate form factor + if not profile["volume"]["formFactor"] in BedFormFactor.values(): + self._logger.warning( + "Profile has invalid value volume.formFactor: {formFactor}".format( + formFactor=profile["volume"]["formFactor"] + ) + ) + return False + + # validate origin type + if not profile["volume"]["origin"] in BedOrigin.values(): + self._logger.warning( + "Profile has invalid value in volume.origin: {origin}".format( + origin=profile["volume"]["origin"] + ) + ) + return False + + # ensure origin and form factor combination is legal + if ( + profile["volume"]["formFactor"] == BedFormFactor.CIRCULAR + and not profile["volume"]["origin"] == BedOrigin.CENTER + ): + profile["volume"]["origin"] = BedOrigin.CENTER + + # force width and depth of volume to be identical for circular beds, with width being the reference + if profile["volume"]["formFactor"] == BedFormFactor.CIRCULAR: + profile["volume"]["depth"] = profile["volume"]["width"] + + # if we have a custom bounding box, validate it + if profile["volume"]["custom_box"] and isinstance( + profile["volume"]["custom_box"], dict + ): + if not len(profile["volume"]["custom_box"]): + profile["volume"]["custom_box"] = False + + else: + default_box = self._default_box_for_volume(profile["volume"]) + for prop, limiter in ( + ("x_min", min), + ("y_min", min), + ("z_min", min), + ("x_max", max), + ("y_max", max), + ("z_max", max), + ): + if ( + prop not in profile["volume"]["custom_box"] + or profile["volume"]["custom_box"][prop] is None + ): + profile["volume"]["custom_box"][prop] = default_box[prop] + else: + value = profile["volume"]["custom_box"][prop] + try: + value = limiter(float(value), default_box[prop]) + profile["volume"]["custom_box"][prop] = value + except Exception: + self._logger.warning( + "Profile has invalid value in volume.custom_box.{}: {!r}".format( + prop, value + ) + ) + return False + + # make sure we actually do have a custom box and not just the same values as the + # default box + for prop in profile["volume"]["custom_box"]: + if profile["volume"]["custom_box"][prop] != default_box[prop]: + break + else: + # exactly the same as the default box, remove custom box + profile["volume"]["custom_box"] = False + + # validate offsets + offsets = [] + for offset in profile["extruder"]["offsets"]: + if not len(offset) == 2: + self._logger.warning( + "Profile has an invalid extruder.offsets entry: {entry!r}".format( + entry=offset + ) + ) + return False + x_offset, y_offset = offset + try: + offsets.append((float(x_offset), float(y_offset))) + except Exception: + self._logger.warning( + "Profile has an extruder.offsets entry with non-float values: {entry!r}".format( + entry=offset + ) + ) + return False + profile["extruder"]["offsets"] = offsets + + return profile + + @staticmethod + def _default_box_for_volume(volume): + if volume["origin"] == BedOrigin.CENTER: + half_width = volume["width"] / 2.0 + half_depth = volume["depth"] / 2.0 + return { + "x_min": -half_width, + "x_max": half_width, + "y_min": -half_depth, + "y_max": half_depth, + "z_min": 0.0, + "z_max": volume["height"], + } + else: + return { + "x_min": 0.0, + "x_max": volume["width"], + "y_min": 0.0, + "y_max": volume["depth"], + "z_min": 0.0, + "z_max": volume["height"], + } diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index b08bf9a68..a5d8822c8 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -6,7 +6,7 @@ This module holds the standard implementation of the :class:`PrinterInterface` a """ __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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 @@ -23,7 +23,13 @@ from octoprint import util as util from octoprint.events import eventManager, Events from octoprint.filemanager import FileDestinations, NoSuchStorage, valid_file_type from octoprint.plugin import plugin_manager, ProgressPlugin -from octoprint.printer import PrinterInterface, PrinterCallback, UnknownScript, InvalidFileLocation, InvalidFileType +from octoprint.printer import ( + PrinterInterface, + PrinterCallback, + UnknownScript, + InvalidFileLocation, + InvalidFileType, +) from octoprint.printer.estimation import PrintTimeEstimator from octoprint.settings import settings from octoprint.util import comm as comm @@ -34,1543 +40,1928 @@ from octoprint.util import get_fully_qualified_classname as fqcn class Printer(PrinterInterface, comm.MachineComPrintCallback): - """ - Default implementation of the :class:`PrinterInterface`. Manages the communication layer object and registers - itself with it as a callback to react to changes on the communication layer. - """ - - def __init__(self, fileManager, analysisQueue, printerProfileManager): - from collections import deque - - self._logger = logging.getLogger(__name__) - self._logger_job = logging.getLogger("{}.job".format(__name__)) - - self._dict = frozendict if settings().getBoolean(["devel", "useFrozenDictForPrinterState"]) else dict - - self._analysisQueue = analysisQueue - self._fileManager = fileManager - self._printerProfileManager = printerProfileManager - - # state - # TODO do we really need to hold the temperature here? - self._temp = None - self._bedTemp = None - self._chamberTemp = None - self._targetTemp = None - self._targetBedTemp = None - self._targetChamberTemp = None - self._temps = TemperatureHistory(cutoff=settings().getInt(["temperature", "cutoff"])*60) - self._tempBacklog = [] - - self._messages = deque([], 300) - self._messageBacklog = [] - - self._log = deque([], 300) - self._logBacklog = [] - - self._state = None - - self._currentZ = None - - self._printAfterSelect = False - self._posAfterSelect = None - - # sd handling - self._sdPrinting = False - self._sdStreaming = False - self._sdFilelistAvailable = threading.Event() - self._streamingFinishedCallback = None - self._streamingFailedCallback = None - - # job handling & estimation - self._selectedFileMutex = threading.RLock() - self._selectedFile = None - - self._estimator_factory = PrintTimeEstimator - self._estimator = None - analysis_queue_hooks = plugin_manager().get_hooks("octoprint.printer.estimation.factory") - for name, hook in analysis_queue_hooks.items(): - try: - estimator = hook() - if estimator is not None: - self._logger.info("Using print time estimator provided by {}".format(name)) - self._estimator_factory = estimator - except Exception: - self._logger.exception("Error while processing analysis queues from {}".format(name), - extra={"plugin": name}) - - #hook card upload - self.sd_card_upload_hooks = plugin_manager().get_hooks("octoprint.printer.sdcardupload") - - # comm - self._comm = None - - # callbacks - self._callbacks = [] - - # progress plugins - self._lastProgressReport = None - self._progressPlugins = plugin_manager().get_implementations(ProgressPlugin) - - self._additional_data_hooks = plugin_manager().get_hooks("octoprint.printer.additional_state_data") - self._blacklisted_data_hooks = [] - - self._stateMonitor = StateMonitor( - interval=0.5, - on_update=self._sendCurrentDataCallbacks, - on_add_temperature=self._sendAddTemperatureCallbacks, - on_add_log=self._sendAddLogCallbacks, - on_add_message=self._sendAddMessageCallbacks, - on_get_progress=self._updateProgressDataCallback - ) - self._stateMonitor.reset( - state=self._dict(text=self.get_state_string(), flags=self._getStateFlags()), - job_data=self._dict(file=self._dict(name=None, - path=None, - size=None, - origin=None, - date=None), - estimatedPrintTime=None, - lastPrintTime=None, - filament=self._dict(length=None, - volume=None), - user=None), - progress=self._dict(completion=None, - filepos=None, - printTime=None, - printTimeLeft=None, - printTimeOrigin=None), - current_z=None, - offsets=self._dict() - ) - - eventManager().subscribe(Events.METADATA_ANALYSIS_FINISHED, self._on_event_MetadataAnalysisFinished) - eventManager().subscribe(Events.METADATA_STATISTICS_UPDATED, self._on_event_MetadataStatisticsUpdated) - - def _create_estimator(self, job_type=None): - if job_type is None: - with self._selectedFileMutex: - if self._selectedFile is None: - return - - if self._selectedFile["sd"]: - job_type = "sdcard" - else: - job_type = "local" - - self._estimator = self._estimator_factory(job_type) - - #~~ handling of PrinterCallbacks - - def register_callback(self, callback, *args, **kwargs): - if not isinstance(callback, PrinterCallback): - self._logger.warning("Registering an object as printer callback which doesn't implement the PrinterCallback interface") - self._callbacks.append(callback) - - def unregister_callback(self, callback, *args, **kwargs): - try: - self._callbacks.remove(callback) - except ValueError: - # not registered - pass - - def send_initial_callback(self, callback): - if callback in self._callbacks: - self._sendInitialStateUpdate(callback) - - def _sendAddTemperatureCallbacks(self, data): - for callback in self._callbacks: - try: - callback.on_printer_add_temperature(data) - except Exception: - self._logger.exception("Exception while adding temperature data point to callback {}".format(callback), - extra={"callback": fqcn(callback)}) - - def _sendAddLogCallbacks(self, data): - for callback in self._callbacks: - try: - callback.on_printer_add_log(data) - except Exception: - self._logger.exception("Exception while adding communication log entry to callback {}".format(callback), - extra={"callback": fqcn(callback)}) - - def _sendAddMessageCallbacks(self, data): - for callback in self._callbacks: - try: - callback.on_printer_add_message(data) - except Exception: - self._logger.exception("Exception while adding printer message to callback {}".format(callback), - extra={"callback": fqcn(callback)}) - - def _sendCurrentDataCallbacks(self, data): - plugin_data = self._get_additional_plugin_data(initial=False) - for callback in self._callbacks: - try: - data_copy = copy.deepcopy(data) - if plugin_data: - data_copy.update(plugins=copy.deepcopy(plugin_data)) - callback.on_printer_send_current_data(data_copy) - except Exception: - self._logger.exception("Exception while pushing current data to callback {}".format(callback), - extra={"callback": fqcn(callback)}) - - def _get_additional_plugin_data(self, initial=False): - plugin_data = {} - - for name, hook in self._additional_data_hooks.items(): - if name in self._blacklisted_data_hooks: - continue - try: - additional = hook(initial=initial) - if additional and isinstance(additional, dict): - plugin_data[name] = additional - except Exception: - self._logger.exception("Error while retrieving additional data from plugin {}, blacklisting it for further loops".format(name), - extra={"plugin": name}) - self._blacklisted_data_hooks.append(name) - - return plugin_data - - #~~ callback from metadata analysis event - - def _on_event_MetadataAnalysisFinished(self, event, data): - with self._selectedFileMutex: - if self._selectedFile: - self._setJobData(self._selectedFile["filename"], - self._selectedFile["filesize"], - self._selectedFile["sd"], - self._selectedFile["user"]) - - def _on_event_MetadataStatisticsUpdated(self, event, data): - with self._selectedFileMutex: - if self._selectedFile: - self._setJobData(self._selectedFile["filename"], - self._selectedFile["filesize"], - self._selectedFile["sd"], - self._selectedFile["user"]) - - #~~ progress plugin reporting - - def _reportPrintProgressToPlugins(self, progress): - with self._selectedFileMutex: - if progress is None or not self._selectedFile or not "sd" in self._selectedFile or not "filename" in self._selectedFile: - return - - storage = "sdcard" if self._selectedFile["sd"] else "local" - filename = self._selectedFile["filename"] - - def call_plugins(storage, filename, progress): - for plugin in self._progressPlugins: - try: - plugin.on_print_progress(storage, filename, progress) - except Exception: - self._logger.exception("Exception while sending print progress to plugin %s" % plugin._identifier, - extra={"plugin": plugin._identifier}) - - thread = threading.Thread(target=call_plugins, args=(storage, filename, progress)) - thread.daemon = False - thread.start() - - #~~ PrinterInterface implementation - - def connect(self, port=None, baudrate=None, profile=None, *args, **kwargs): - """ - Connects to the printer. If port and/or baudrate is provided, uses these settings, otherwise autodetection - will be attempted. - """ - if self._comm is not None: - return - - eventManager().fire(Events.CONNECTING) - self._printerProfileManager.select(profile) - - from octoprint.logging.handlers import SerialLogHandler - SerialLogHandler.arm_rollover() - if not logging.getLogger("SERIAL").isEnabledFor(logging.DEBUG): - # if serial.log is not enabled, log a line to explain that to reduce "serial.log is empty" in tickets... - logging.getLogger("SERIAL").info("serial.log is currently not enabled, you can enable it via Settings > Serial Connection > Log communication to serial.log") - - self._comm = comm.MachineCom(port, baudrate, callbackObject=self, printerProfileManager=self._printerProfileManager) - self._comm.start() - - def disconnect(self, *args, **kwargs): - """ - Closes the connection to the printer. - """ - eventManager().fire(Events.DISCONNECTING) - if self._comm is not None: - self._comm.close() - else: - eventManager().fire(Events.DISCONNECTED) - - def get_transport(self, *args, **kwargs): - - if self._comm is None: - return None - - return self._comm.getTransport() - getTransport = util.deprecated("getTransport has been renamed to get_transport", since="1.2.0-dev-590", includedoc="Replaced by :func:`get_transport`") - - def job_on_hold(self, blocking=True, *args, **kwargs): - if self._comm is None: - raise RuntimeError("No connection to the printer") - return self._comm.job_put_on_hold(blocking=blocking) - - def set_job_on_hold(self, value, blocking=True, *args, **kwargs): - if self._comm is None: - raise RuntimeError("No connection to the printer") - return self._comm.set_job_on_hold(value, blocking=blocking) - - def fake_ack(self, *args, **kwargs): - if self._comm is None: - return - - self._comm.fakeOk() - - def commands(self, commands, tags=None, force=False, *args, **kwargs): - """ - Sends one or more gcode commands to the printer. - """ - if self._comm is None: - return - - if not isinstance(commands, (list, tuple)): - commands = [commands] - - if tags is None: - tags = set() - tags |= {"trigger:printer.commands"} - - for command in commands: - self._comm.sendCommand(command, - tags=tags, - force=force) - - def script(self, name, context=None, must_be_set=True, part_of_job=False, *args, **kwargs): - if self._comm is None: - return - - if name is None or not name: - raise ValueError("name must be set") - - result = self._comm.sendGcodeScript(name, - part_of_job=part_of_job, - replacements=context, - tags=kwargs.get("tags", set()) | {"trigger:printer.script"}) - if not result and must_be_set: - raise UnknownScript(name) - - def jog(self, axes, relative=True, speed=None, *args, **kwargs): - if isinstance(axes, basestring): - # legacy parameter format, there should be an amount as first anonymous positional arguments too - axis = axes - - if not len(args) >= 1: - raise ValueError("amount not set") - amount = args[0] - if not isinstance(amount, (int, long, float)): - raise ValueError("amount must be a valid number: {amount}".format(amount=amount)) - - axes = {} - axes[axis] = amount - - if not axes: - raise ValueError("At least one axis to jog must be provided") - - for axis in axes: - if not axis in PrinterInterface.valid_axes: - raise ValueError("Invalid axis {}, valid axes are {}".format(axis, ", ".join(PrinterInterface.valid_axes))) - - command = "G1 {}".format(" ".join(["{}{}".format(axis.upper(), amt) for axis, amt in axes.items()])) - - if speed is None: - printer_profile = self._printerProfileManager.get_current_or_default() - speed = min([printer_profile["axes"][axis]["speed"] for axis in axes]) - - if speed and not isinstance(speed, bool): - command += " F{}".format(speed) - - if relative: - commands = ["G91", command, "G90"] - else: - commands = ["G90", command] - - self.commands(commands, tags=kwargs.get("tags", set()) | {"trigger:printer.jog"}) - - def home(self, axes, *args, **kwargs): - if not isinstance(axes, (list, tuple)): - if isinstance(axes, basestring): - axes = [axes] - else: - raise ValueError("axes is neither a list nor a string: {axes}".format(axes=axes)) - - validated_axes = list(filter(lambda x: x in PrinterInterface.valid_axes, map(lambda x: x.lower(), axes))) - if len(axes) != len(validated_axes): - raise ValueError("axes contains invalid axes: {axes}".format(axes=axes)) - - self.commands(["G91", "G28 %s" % " ".join(map(lambda x: "%s0" % x.upper(), validated_axes)), "G90"], - tags=kwargs.get("tags", set) | {"trigger:printer.home"}) - - def extrude(self, amount, speed=None, *args, **kwargs): - if not isinstance(amount, (int, long, float)): - raise ValueError("amount must be a valid number: {amount}".format(amount=amount)) - - printer_profile = self._printerProfileManager.get_current_or_default() - - # Use specified speed (if any) - max_e_speed = printer_profile["axes"]["e"]["speed"] - - if speed is None: - # No speed was specified so default to value configured in printer profile - extrusion_speed = max_e_speed - else: - # Make sure that specified value is not greater than maximum as defined in printer profile - extrusion_speed = min([speed, max_e_speed]) - - self.commands(["G91", "M83", "G1 E%s F%d" % (amount, extrusion_speed), "M82", "G90"], - tags=kwargs.get("tags", set()) | {"trigger:printer.extrude"}) - - def change_tool(self, tool, *args, **kwargs): - if not PrinterInterface.valid_tool_regex.match(tool): - raise ValueError("tool must match \"tool[0-9]+\": {tool}".format(tool=tool)) - - tool_num = int(tool[len("tool"):]) - self.commands("T%d" % tool_num, tags=kwargs.get("tags", set()) | {"trigger:printer.change_tool"}) - - def set_temperature(self, heater, value, *args, **kwargs): - if not PrinterInterface.valid_heater_regex.match(heater): - raise ValueError("heater must match \"tool[0-9]+\", \"bed\" or \"chamber\": {heater}".format(heater=heater)) - - if not isinstance(value, (int, long, float)) or value < 0: - raise ValueError("value must be a valid number >= 0: {value}".format(value=value)) - - tags = kwargs.get("tags", set()) | {"trigger:printer.set_temperature"} - - if heater.startswith("tool"): - printer_profile = self._printerProfileManager.get_current_or_default() - extruder_count = printer_profile["extruder"]["count"] - shared_nozzle = printer_profile["extruder"]["sharedNozzle"] - if extruder_count > 1 and not shared_nozzle: - toolNum = int(heater[len("tool"):]) - self.commands("M104 T{} S{}".format(toolNum, value), - tags=tags) - else: - self.commands("M104 S{}".format(value), - tags=tags) - - elif heater == "bed": - self.commands("M140 S{}".format(value), - tags=tags) - - elif heater == "chamber": - self.commands("M141 S{}".format(value), - tags=tags) - - def set_temperature_offset(self, offsets=None, *args, **kwargs): - if offsets is None: - offsets = {} - - if not isinstance(offsets, dict): - raise ValueError("offsets must be a dict") - - validated_keys = list(filter(lambda x: PrinterInterface.valid_heater_regex.match(x), offsets.keys())) - validated_values = list(filter(lambda x: isinstance(x, (int, long, float)), offsets.values())) - - if len(validated_keys) != len(offsets): - raise ValueError("offsets contains invalid keys: {offsets}".format(offsets=offsets)) - if len(validated_values) != len(offsets): - raise ValueError("offsets contains invalid values: {offsets}".format(offsets=offsets)) - - if self._comm is None: - return - - self._comm.setTemperatureOffset(offsets) - self._setOffsets(self._comm.getOffsets()) - - def _convert_rate_value(self, factor, min_val=None, max_val=None): - if not isinstance(factor, (int, float, long)): - raise ValueError("factor is not a number") - - if isinstance(factor, float): - factor = int(factor * 100.0) - - if min_val and factor < min_val: - raise ValueError("factor must be a value >={}".format(min_val)) - elif max_val and factor > max_val: - raise ValueError("factor must be a value <={}".format(max_val)) - - return factor - - def feed_rate(self, factor, *args, **kwargs): - factor = self._convert_rate_value(factor, min_val=1) - self.commands("M220 S%d" % factor, - tags=kwargs.get("tags", set()) | {"trigger:printer.feed_rate"}) - - def flow_rate(self, factor, *args, **kwargs): - factor = self._convert_rate_value(factor, min_val=1) - self.commands("M221 S%d" % factor, - tags=kwargs.get("tags", set()) | {"trigger:printer.flow_rate"}) - - def select_file(self, path, sd, printAfterSelect=False, user=None, pos=None, *args, **kwargs): - if self._comm is None or (self._comm.isBusy() or self._comm.isStreaming()): - self._logger.info("Cannot load file: printer not connected or currently busy") - return - - self._validateJob(path, sd) - - origin = FileDestinations.SDCARD if sd else FileDestinations.LOCAL - if sd: - path_on_disk = "/" + path - path_in_storage = path - else: - path_on_disk = self._fileManager.path_on_disk(origin, path) - path_in_storage = self._fileManager.path_in_storage(origin, path_on_disk) - - try: - recovery_data = self._fileManager.get_recovery_data() - if recovery_data: - # clean up recovery data if we just selected a different file - actual_origin = recovery_data.get("origin", None) - actual_path = recovery_data.get("path", None) - - if actual_origin is None or actual_path is None or actual_origin != origin or actual_path != path_in_storage: - self._fileManager.delete_recovery_data() - except Exception: - # anything goes wrong with the recovery data, we ignore it - self._logger.exception("Something was wrong with processing the recovery data") - - self._printAfterSelect = printAfterSelect - self._posAfterSelect = pos - self._comm.selectFile("/" + path if sd else path_on_disk, sd, - user=user, - tags=kwargs.get("tags", set()) | {"trigger:printer.select_file"}) - self._updateProgressData() - self._setCurrentZ(None) - - def unselect_file(self, *args, **kwargs): - if self._comm is not None and (self._comm.isBusy() or self._comm.isStreaming()): - return - - self._comm.unselectFile() - self._updateProgressData() - self._setCurrentZ(None) - - def get_file_position(self): - if self._comm is None: - return None - - with self._selectedFileMutex: - if self._selectedFile is None: - return None - - return self._comm.getFilePosition() - - def start_print(self, pos=None, user=None, *args, **kwargs): - """ - Starts the currently loaded print job. - Only starts if the printer is connected and operational, not currently printing and a printjob is loaded - """ - if self._comm is None or not self._comm.isOperational() or self._comm.isPrinting(): - return - - with self._selectedFileMutex: - if self._selectedFile is None: - return - - self._fileManager.delete_recovery_data() - - self._lastProgressReport = None - self._updateProgressData() - self._setCurrentZ(None) - self._comm.startPrint(pos=pos, - user=user, - tags=kwargs.get("tags", set()) | {"trigger:printer.start_print"}) - - def pause_print(self, user=None, *args, **kwargs): - """ - Pause the current printjob. - """ - if self._comm is None: - return - - if self._comm.isPaused(): - return - - self._comm.setPause(True, - user=user, - tags=kwargs.get("tags", set()) | {"trigger:printer.pause_print"}) - - def resume_print(self, user=None, *args, **kwargs): - """ - Resume the current printjob. - """ - if self._comm is None: - return - - if not self._comm.isPaused(): - return - - self._comm.setPause(False, - user=user, - tags=kwargs.get("tags", set()) | {"trigger:printer.resume_print"}) - - def cancel_print(self, user=None, *args, **kwargs): - """ - Cancel the current printjob. - """ - if self._comm is None: - return - - # tell comm layer to cancel - will also trigger our cancelled handler - # for further processing - self._comm.cancelPrint(user=user, - tags=kwargs.get("tags", set()) | {"trigger:printer.cancel_print"}) - - def log_lines(self, *lines): - serial_logger = logging.getLogger("SERIAL") - self.on_comm_log("\n".join(lines)) - for line in lines: - serial_logger.debug(line) - - def get_state_string(self, state=None, *args, **kwargs): - if self._comm is None: - return "Offline" - else: - return self._comm.getStateString(state=state) - - def get_state_id(self, state=None, *args, **kwargs): - if self._comm is None: - return "OFFLINE" - else: - return self._comm.getStateId(state=state) - - def get_current_data(self, *args, **kwargs): - return util.thaw_frozendict(self._stateMonitor.get_current_data()) - - def get_current_job(self, *args, **kwargs): - currentData = self._stateMonitor.get_current_data() - return util.thaw_frozendict(currentData["job"]) - - def get_current_temperatures(self, *args, **kwargs): - if self._comm is not None: - offsets = self._comm.getOffsets() - else: - offsets = {} - - result = {} - if self._temp is not None: - for tool in self._temp.keys(): - result["tool%d" % tool] = { - "actual": self._temp[tool][0], - "target": self._temp[tool][1], - "offset": offsets[tool] if tool in offsets and offsets[tool] is not None else 0 - } - if self._bedTemp is not None: - result["bed"] = { - "actual": self._bedTemp[0], - "target": self._bedTemp[1], - "offset": offsets["bed"] if "bed" in offsets and offsets["bed"] is not None else 0 - } - if self._chamberTemp is not None: - result["chamber"] = { - "actual": self._chamberTemp[0], - "target": self._chamberTemp[1], - "offset": offsets["chamber"] if "chamber" in offsets and offsets["chamber"] is not None else 0 - } - - return result - - def get_temperature_history(self, *args, **kwargs): - return self._temps - - def get_current_connection(self, *args, **kwargs): - if self._comm is None: - return "Closed", None, None, None - - port, baudrate = self._comm.getConnection() - printer_profile = self._printerProfileManager.get_current_or_default() - return self._comm.getStateString(), port, baudrate, printer_profile - - def is_closed_or_error(self, *args, **kwargs): - return self._comm is None or self._comm.isClosedOrError() - - def is_operational(self, *args, **kwargs): - return self._comm is not None and self._comm.isOperational() - - def is_printing(self, *args, **kwargs): - return self._comm is not None and self._comm.isPrinting() - - def is_cancelling(self, *args, **kwargs): - return self._comm is not None and self._comm.isCancelling() - - def is_pausing(self, *args, **kwargs): - return self._comm is not None and self._comm.isPausing() - - def is_paused(self, *args, **kwargs): - return self._comm is not None and self._comm.isPaused() - - def is_resuming(self, *args, **kwargs): - return self._comm is not None and self._comm.isResuming() - - def is_finishing(self, *args, **kwargs): - return self._comm is not None and self._comm.isFinishing() - - def is_error(self, *args, **kwargs): - return self._comm is not None and self._comm.isError() - - def is_ready(self, *args, **kwargs): - return self.is_operational() and not self.is_printing() and not self._comm.isStreaming() - - def is_sd_ready(self, *args, **kwargs): - if not settings().getBoolean(["feature", "sdSupport"]) or self._comm is None: - return False - else: - return self._comm.isSdReady() - - #~~ sd file handling - - def get_sd_files(self, *args, **kwargs): - if self._comm is None or not self._comm.isSdReady(): - result = [] - else: - result = list(map(lambda x: {"name": x[0][1:], "size": x[1], "display": x[2]}, self._comm.getSdFiles())) - return result - - def add_sd_file(self, filename, path, on_success=None, on_failure=None, *args, **kwargs): - if not self._comm or self._comm.isBusy() or not self._comm.isSdReady(): - self._logger.error("No connection to printer or printer is busy") - return - - self._streamingFinishedCallback = on_success - self._streamingFailedCallback = on_failure - - def sd_upload_started(local_filename, remote_filename): - eventManager().fire(Events.TRANSFER_STARTED, {"local": local_filename, - "remote": remote_filename}) - - def sd_upload_succeeded(local_filename, remote_filename, elapsed): - payload = {"local": local_filename, - "remote": remote_filename, - "time": elapsed} - eventManager().fire(Events.TRANSFER_DONE, payload) - if callable(self._streamingFinishedCallback): - self._streamingFinishedCallback(remote_filename, remote_filename, FileDestinations.SDCARD) - - def sd_upload_failed(local_filename, remote_filename, elapsed): - payload = {"local": local_filename, - "remote": remote_filename, - "time": elapsed} - eventManager().fire(Events.TRANSFER_FAILED, payload) - if callable(self._streamingFailedCallback): - self._streamingFailedCallback(remote_filename, remote_filename, FileDestinations.SDCARD) - - for name, hook in self.sd_card_upload_hooks.items(): - # first sd card upload plugin that feels responsible gets the job - try: - result = hook(self, filename, path, sd_upload_started, sd_upload_succeeded, sd_upload_failed, - *args, **kwargs) - if result is not None: - return result - except Exception: - self._logger.exception("There was an error running the sd upload " - "hook provided by plugin {}".format(name), - extra={"plugin": name}) - - else: - # no plugin feels responsible, use the default implementation - return self._add_sd_file(filename, path, tags=kwargs.get("tags")) - - def _get_free_remote_name(self, filename): - self.refresh_sd_files(blocking=True) - existingSdFiles = list(map(lambda x: x[0], self._comm.getSdFiles())) - - if valid_file_type(filename, "gcode"): - # figure out remote filename - remote_name = util.get_dos_filename(filename, - existing_filenames=existingSdFiles, - extension="gco", - whitelisted_extensions=["gco", "g"]) - else: - # probably something else added through a plugin, use it's basename as-is - remote_name = os.path.basename(filename) - - return remote_name - - def _add_sd_file(self, filename, path, tags=None): - if tags is None: - tags = set() - - remote_name = self._get_free_remote_name(filename) - self._create_estimator("stream") - self._comm.startFileTransfer(path, filename, "/" + remote_name, - special=not valid_file_type(filename, "gcode"), - tags=tags | {"trigger:printer.add_sd_file"}) - - return remote_name - - def delete_sd_file(self, filename, *args, **kwargs): - if not self._comm or not self._comm.isSdReady(): - return - self._comm.deleteSdFile("/" + filename, tags=kwargs.get("tags", set()) | {"trigger:printer.delete_sd_file"}) - - def init_sd_card(self, *args, **kwargs): - if not self._comm or self._comm.isSdReady(): - return - self._comm.initSdCard(tags=kwargs.get("tags", set()) | {"trigger:printer.init_sd_card"}) - - def release_sd_card(self, *args, **kwargs): - if not self._comm or not self._comm.isSdReady(): - return - self._comm.releaseSdCard(tags=kwargs.get("tags", set()) | {"trigger:printer.release_sd_card"}) - - def refresh_sd_files(self, blocking=False, *args, **kwargs): - """ - Refreshes the list of file stored on the SD card attached to printer (if available and printer communication - available). Optional blocking parameter allows making the method block (max 10s) until the file list has been - received (and can be accessed via self._comm.getSdFiles()). Defaults to an asynchronous operation. - """ - if not self._comm or not self._comm.isSdReady(): - return - self._sdFilelistAvailable.clear() - self._comm.refreshSdFiles(tags=kwargs.get("tags", set()) | {"trigger:printer.refresh_sd_files"}) - if blocking: - self._sdFilelistAvailable.wait(kwargs.get("timeout", 10000)) - - #~~ state monitoring - - def _setOffsets(self, offsets): - self._stateMonitor.set_temp_offsets(offsets) - - def _setCurrentZ(self, currentZ): - self._currentZ = currentZ - self._stateMonitor.set_current_z(self._currentZ) - - def _setState(self, state, state_string=None): - if state_string is None: - state_string = self.get_state_string() - - self._state = state - self._stateMonitor.set_state(self._dict(text=state_string, flags=self._getStateFlags())) - - payload = {"state_id": self.get_state_id(self._state), - "state_string": self.get_state_string(self._state)} - eventManager().fire(Events.PRINTER_STATE_CHANGED, payload) - - def _addLog(self, log): - self._log.append(log) - self._stateMonitor.add_log(log) - - def _addMessage(self, message): - self._messages.append(message) - self._stateMonitor.add_message(message) - - def _updateProgressData(self, completion=None, filepos=None, printTime=None, printTimeLeft=None, printTimeLeftOrigin=None): - self._stateMonitor.set_progress(self._dict(completion=int(completion * 100) if completion is not None else None, - filepos=filepos, - printTime=int(printTime) if printTime is not None else None, - printTimeLeft=int(printTimeLeft) if printTimeLeft is not None else None, - printTimeLeftOrigin=printTimeLeftOrigin)) - - def _updateProgressDataCallback(self): - if self._comm is None: - progress = None - filepos = None - printTime = None - cleanedPrintTime = None - else: - progress = self._comm.getPrintProgress() - filepos = self._comm.getPrintFilepos() - printTime = self._comm.getPrintTime() - cleanedPrintTime = self._comm.getCleanedPrintTime() - - printTimeLeft = printTimeLeftOrigin = None - estimator = self._estimator - if progress is not None: - progress_int = int(progress * 100) - if self._lastProgressReport != progress_int: - self._lastProgressReport = progress_int - self._reportPrintProgressToPlugins(progress_int) - - if progress == 0: - printTimeLeft = None - printTimeLeftOrigin = None - elif progress == 1.0: - printTimeLeft = 0 - printTimeLeftOrigin = None - elif estimator is not None: - statisticalTotalPrintTime = None - statisticalTotalPrintTimeType = None - with self._selectedFileMutex: - if self._selectedFile and "estimatedPrintTime" in self._selectedFile \ - and self._selectedFile["estimatedPrintTime"]: - statisticalTotalPrintTime = self._selectedFile["estimatedPrintTime"] - statisticalTotalPrintTimeType = self._selectedFile.get("estimatedPrintTimeType", None) - - try: - printTimeLeft, printTimeLeftOrigin = estimator.estimate(progress, - printTime, - cleanedPrintTime, - statisticalTotalPrintTime, - statisticalTotalPrintTimeType) - except Exception: - self._logger.exception("Error while estimating print time via {}".format(estimator)) - - return self._dict(completion=progress * 100 if progress is not None else None, - filepos=filepos, - printTime=int(printTime) if printTime is not None else None, - printTimeLeft=int(printTimeLeft) if printTimeLeft is not None else None, - printTimeLeftOrigin=printTimeLeftOrigin) - - def _addTemperatureData(self, tools=None, bed=None, chamber=None, custom=None): - if tools is None: - tools = {} - if custom is None: - custom = {} - - data = {"time": int(time.time())} - for tool in tools.keys(): - data["tool%d" % tool] = self._dict(actual=tools[tool][0], target=tools[tool][1]) - if bed is not None and isinstance(bed, tuple): - data["bed"] = self._dict(actual=bed[0], target=bed[1]) - if chamber is not None and isinstance(chamber, tuple): - data["chamber"] = self._dict(actual=chamber[0], target=chamber[1]) - for identifier, values in custom.items(): - data[identifier] = self._dict(actual=values[0], target=values[1]) - - self._temps.append(data) - - self._temp = tools - self._bedTemp = bed - self._chamberTemp = chamber - self._custom = custom - - self._stateMonitor.add_temperature(self._dict(**data)) - - def _validateJob(self, filename, sd): - if not valid_file_type(filename, type="machinecode"): - raise InvalidFileType("{} is not a machinecode file, cannot print".format(filename)) - - if sd: - return - - path_on_disk = self._fileManager.path_on_disk(FileDestinations.LOCAL, filename) - if os.path.isabs(filename) and not filename == path_on_disk: - raise InvalidFileLocation("{} is not located within local storage, cannot select for printing".format(filename)) - if not os.path.isfile(path_on_disk): - raise InvalidFileLocation("{} does not exist in local storage, cannot select for printing".format(filename)) - - def _setJobData(self, filename, filesize, sd, user=None): - with self._selectedFileMutex: - if filename is not None: - if sd: - name_in_storage = filename - if name_in_storage.startswith("/"): - name_in_storage = name_in_storage[1:] - path_in_storage = name_in_storage - path_on_disk = None - else: - path_in_storage = self._fileManager.path_in_storage(FileDestinations.LOCAL, filename) - path_on_disk = self._fileManager.path_on_disk(FileDestinations.LOCAL, filename) - _, name_in_storage = self._fileManager.split_path(FileDestinations.LOCAL, path_in_storage) - self._selectedFile = { - "filename": path_in_storage, - "filesize": filesize, - "sd": sd, - "estimatedPrintTime": None, - "user": user - } - else: - self._selectedFile = None - self._stateMonitor.set_job_data(self._dict(file=self._dict(name=None, - path=None, - display=None, - origin=None, - size=None, - date=None), - estimatedPrintTime=None, - averagePrintTime=None, - lastPrintTime=None, - filament=None, - user=None)) - return - - estimatedPrintTime = None - lastPrintTime = None - averagePrintTime = None - date = None - filament = None - display_name = name_in_storage - if path_on_disk: - # Use a string for mtime because it could be float and the - # javascript needs to exact match - if not sd: - date = int(os.stat(path_on_disk).st_mtime) - - try: - fileData = self._fileManager.get_metadata(FileDestinations.SDCARD if sd else FileDestinations.LOCAL, path_on_disk) - except Exception: - self._logger.exception("Error generating fileData") - fileData = None - if fileData is not None: - if "display" in fileData: - display_name = fileData["display"] - if "analysis" in fileData: - if estimatedPrintTime is None and "estimatedPrintTime" in fileData["analysis"]: - estimatedPrintTime = fileData["analysis"]["estimatedPrintTime"] - if "filament" in fileData["analysis"]: - filament = fileData["analysis"]["filament"] - if "statistics" in fileData: - printer_profile = self._printerProfileManager.get_current_or_default()["id"] - if "averagePrintTime" in fileData["statistics"] and printer_profile in fileData["statistics"]["averagePrintTime"]: - averagePrintTime = fileData["statistics"]["averagePrintTime"][printer_profile] - if "lastPrintTime" in fileData["statistics"] and printer_profile in fileData["statistics"]["lastPrintTime"]: - lastPrintTime = fileData["statistics"]["lastPrintTime"][printer_profile] - - if averagePrintTime is not None: - self._selectedFile["estimatedPrintTime"] = averagePrintTime - self._selectedFile["estimatedPrintTimeType"] = "average" - elif estimatedPrintTime is not None: - # TODO apply factor which first needs to be tracked! - self._selectedFile["estimatedPrintTime"] = estimatedPrintTime - self._selectedFile["estimatedPrintTimeType"] = "analysis" - - self._stateMonitor.set_job_data(self._dict(file=self._dict(name=name_in_storage, - path=path_in_storage, - display=display_name, - origin=FileDestinations.SDCARD if sd else FileDestinations.LOCAL, - size=filesize, - date=date), - estimatedPrintTime=estimatedPrintTime, - averagePrintTime=averagePrintTime, - lastPrintTime=lastPrintTime, - filament=filament, - user=user)) - - def _updateJobUser(self, user): - with self._selectedFileMutex: - if self._selectedFile is not None and self._selectedFile.get("user", None) != user: - self._selectedFile["user"] = user - - job_data = self.get_current_job() - self._stateMonitor.set_job_data(self._dict(file=job_data["file"], - estimatedPrintTime=job_data["estimatedPrintTime"], - averagePrintTime=job_data["averagePrintTime"], - lastPrintTime=job_data["lastPrintTime"], - filament=job_data["filament"], - user=user)) - - def _sendInitialStateUpdate(self, callback): - try: - data = self._stateMonitor.get_current_data() - data.update(temps=list(self._temps), - logs=list(self._log), - messages=list(self._messages)) - - plugin_data = self._get_additional_plugin_data(initial=False) - if plugin_data: - data.update(plugins=copy.deepcopy(plugin_data)) - - callback.on_printer_send_initial_data(data) - except Exception: - self._logger.exception(u"Error while pushing initial state update to callback {}".format(callback), - extra={"callback": fqcn(callback)}) - - def _getStateFlags(self): - return self._dict(operational=self.is_operational(), - printing=self.is_printing(), - cancelling=self.is_cancelling(), - pausing=self.is_pausing(), - resuming=self.is_resuming(), - finishing=self.is_finishing(), - closedOrError=self.is_closed_or_error(), - error=self.is_error(), - paused=self.is_paused(), - ready=self.is_ready(), - sdReady=self.is_sd_ready()) - - #~~ comm.MachineComPrintCallback implementation - - def on_comm_log(self, message): - """ - Callback method for the comm object, called upon log output. - """ - self._addLog(to_unicode(message, "utf-8", errors="replace")) - - def on_comm_temperature_update(self, tools, bed, chamber, custom=None): - if custom is None: - custom = {} - self._addTemperatureData(tools=copy.deepcopy(tools), - bed=copy.deepcopy(bed), - chamber=copy.deepcopy(chamber), - custom=copy.deepcopy(custom)) - - def on_comm_position_update(self, position, reason=None): - payload = {"reason": reason} - payload.update(position) - eventManager().fire(Events.POSITION_UPDATE, payload) - - def on_comm_state_change(self, state): - """ - Callback method for the comm object, called if the connection state changes. - """ - oldState = self._state - - state_string = None - if self._comm is not None: - state_string = self._comm.getStateString() - - if oldState in (comm.MachineCom.STATE_PRINTING,): - # if we were still printing and went into an error state, mark the print as failed - if state in (comm.MachineCom.STATE_CLOSED, comm.MachineCom.STATE_ERROR, comm.MachineCom.STATE_CLOSED_WITH_ERROR): - with self._selectedFileMutex: - if self._selectedFile is not None: - payload = self._payload_for_print_job_event() - if payload: - payload["time"] = self._comm.getPrintTime() - payload["reason"] = "error" - payload["error"] = self._comm.getErrorString() - - def finalize(): - self._fileManager.log_print(payload["origin"], - payload["path"], - time.time(), - payload["time"], - False, - self._printerProfileManager.get_current_or_default()["id"]) - eventManager().fire(Events.PRINT_FAILED, payload) - - thread = threading.Thread(target=finalize) - thread.daemon = True - thread.start() - - try: - self._analysisQueue.resume() # printing done, put those cpu cycles to good use - except Exception: - self._logger.exception("Error while resuming the analysis queue") - - elif state == comm.MachineCom.STATE_PRINTING: - if settings().get(["gcodeAnalysis", "runAt"]) == "idle": - try: - self._analysisQueue.pause() # only analyse files while idle - except Exception: - self._logger.exception("Error while pausing the analysis queue") - - if state == comm.MachineCom.STATE_CLOSED or state == comm.MachineCom.STATE_CLOSED_WITH_ERROR: - if self._comm is not None: - self._comm = None - - self._updateProgressData() - self._setCurrentZ(None) - self._setJobData(None, None, None) - self._setOffsets(None) - self._addTemperatureData() - self._printerProfileManager.deselect() - eventManager().fire(Events.DISCONNECTED) - - self._setState(state, state_string=state_string) - - def on_comm_message(self, message): - """ - Callback method for the comm object, called upon message exchanges via serial. - Stores the message in the message buffer, truncates buffer to the last 300 lines. - """ - self._addMessage(to_unicode(message, "utf-8", errors="replace")) - - def on_comm_progress(self): - """ - Callback method for the comm object, called upon any change in progress of the printjob. - Triggers storage of new values for printTime, printTimeLeft and the current progress. - """ - - self._stateMonitor.trigger_progress_update() - - def on_comm_z_change(self, newZ): - """ - Callback method for the comm object, called upon change of the z-layer. - """ - oldZ = self._currentZ - if newZ != oldZ: - # we have to react to all z-changes, even those that might "go backward" due to a slicer's retraction or - # anti-backlash-routines. Event subscribes should individually take care to filter out "wrong" z-changes - eventManager().fire(Events.Z_CHANGE, {"new": newZ, "old": oldZ}) - - self._setCurrentZ(newZ) - - def on_comm_sd_state_change(self, sdReady): - self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags())) - - def on_comm_sd_files(self, files): - eventManager().fire(Events.UPDATED_FILES, {"type": "printables"}) - self._sdFilelistAvailable.set() - - def on_comm_file_selected(self, full_path, size, sd, user=None): - if full_path is not None: - payload = self._payload_for_print_job_event(location=FileDestinations.SDCARD if sd else FileDestinations.LOCAL, - print_job_file=full_path, - print_job_user=user, - action_user=user) - eventManager().fire(Events.FILE_SELECTED, payload) - self._logger_job.info("Print job selected - origin: {}, path: {}, owner: {}, user: {}".format(payload.get("origin"), - payload.get("path"), - payload.get("owner"), - payload.get("user"))) - else: - eventManager().fire(Events.FILE_DESELECTED) - self._logger_job.info("Print job deselected - user: {}".format(user if user else "n/a")) - - self._setJobData(full_path, size, sd, user=user) - self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags())) - - self._create_estimator() - - if self._printAfterSelect: - self._printAfterSelect = False - self.start_print(pos=self._posAfterSelect, user=user) - - def on_comm_print_job_started(self, suppress_script=False, user=None): - self._updateJobUser(user) # the final job owner should always be whoever _started_ the job - self._stateMonitor.trigger_progress_update() - payload = self._payload_for_print_job_event(print_job_user=user, - action_user=user) - if payload: - eventManager().fire(Events.PRINT_STARTED, payload) - self._logger_job.info("Print job started - origin: {}, path: {}, owner: {}, user: {}".format(payload.get("origin"), - payload.get("path"), - payload.get("owner"), - payload.get("user"))) - - if not suppress_script: - self.script("beforePrintStarted", - context={"event": payload}, - part_of_job=True, - must_be_set=False) - - def on_comm_print_job_done(self, suppress_script=False): - self._fileManager.delete_recovery_data() - - payload = self._payload_for_print_job_event() - if payload: - payload["time"] = self._comm.getPrintTime() - self._updateProgressData(completion=1.0, - filepos=payload["size"], - printTime=payload["time"], - printTimeLeft=0) - self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags())) - - eventManager().fire(Events.PRINT_DONE, payload) - self._logger_job.info("Print job done - origin: {}, path: {}, owner: {}".format(payload.get("origin"), - payload.get("path"), - payload.get("owner"))) - - if not suppress_script: - self.script("afterPrintDone", - context={"event": payload}, - part_of_job=True, - must_be_set=False) - - def log_print(): - self._fileManager.log_print(payload["origin"], - payload["path"], - time.time(), - payload["time"], - True, - self._printerProfileManager.get_current_or_default()["id"]) - - thread = threading.Thread(target=log_print) - thread.daemon = True - thread.start() - - else: - self._updateProgressData() - self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags())) - - - def on_comm_print_job_cancelling(self, firmware_error=None, user=None): - payload = self._payload_for_print_job_event(action_user=user) - if payload: - if firmware_error: - payload["firmwareError"] = firmware_error - eventManager().fire(Events.PRINT_CANCELLING, payload) - - def on_comm_print_job_cancelled(self, suppress_script=False, user=None): - self._setCurrentZ(None) - self._updateProgressData() - - payload = self._payload_for_print_job_event(position=self._comm.cancel_position.as_dict() if self._comm and self._comm.cancel_position else None, - action_user=user) - if payload: - payload["time"] = self._comm.getPrintTime() - - eventManager().fire(Events.PRINT_CANCELLED, payload) - self._logger_job.info("Print job cancelled - origin: {}, path: {}, owner: {}, user: {}".format(payload.get("origin"), - payload.get("path"), - payload.get("owner"), - payload.get("user"))) - - if not suppress_script: - self.script("afterPrintCancelled", - context={"event": payload}, - part_of_job=True, - must_be_set=False) - - payload["reason"] = "cancelled" - - def finalize(): - self._fileManager.log_print(payload["origin"], - payload["path"], - time.time(), - payload["time"], - False, - self._printerProfileManager.get_current_or_default()["id"]) - eventManager().fire(Events.PRINT_FAILED, payload) - - thread = threading.Thread(target=finalize) - thread.daemon = True - thread.start() - - def on_comm_print_job_paused(self, suppress_script=False, user=None): - payload = self._payload_for_print_job_event(position=self._comm.pause_position.as_dict() if self._comm and self._comm.pause_position and not suppress_script else None, - action_user=user) - if payload: - eventManager().fire(Events.PRINT_PAUSED, payload) - self._logger_job.info("Print job paused - origin: {}, path: {}, owner: {}, user: {}".format(payload.get("origin"), - payload.get("path"), - payload.get("owner"), - payload.get("user"))) - if not suppress_script: - self.script("afterPrintPaused", - context={"event": payload}, - part_of_job=True, - must_be_set=False) - - def on_comm_print_job_resumed(self, suppress_script=False, user=None): - payload = self._payload_for_print_job_event(action_user=user) - if payload: - eventManager().fire(Events.PRINT_RESUMED, payload) - self._logger_job.info("Print job resumed - origin: {}, path: {}, owner: {}, user: {}".format(payload.get("origin"), - payload.get("path"), - payload.get("owner"), - payload.get("user"))) - - if not suppress_script: - self.script("beforePrintResumed", - context={"event": payload}, - part_of_job=True, - must_be_set=False) - - def on_comm_file_transfer_started(self, local_filename, remote_filename, filesize, user=None): - eventManager().fire(Events.TRANSFER_STARTED, {"local": local_filename, - "remote": remote_filename}) - - self._sdStreaming = True - - self._setJobData(remote_filename, filesize, True, user=user) - self._updateProgressData(completion=0.0, filepos=0, printTime=0) - self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags())) - - def on_comm_file_transfer_done(self, local_filename, remote_filename, elapsed, failed=False): - self._sdStreaming = False - - payload = {"local": local_filename, - "remote": remote_filename, - "time": elapsed} - - if failed: - eventManager().fire(Events.TRANSFER_FAILED, payload) - if callable(self._streamingFailedCallback): - self._streamingFailedCallback(remote_filename, remote_filename, FileDestinations.SDCARD) - else: - eventManager().fire(Events.TRANSFER_DONE, payload) - if callable(self._streamingFinishedCallback): - self._streamingFinishedCallback(remote_filename, remote_filename, FileDestinations.SDCARD) - - self._setCurrentZ(None) - self._setJobData(None, None, None) - self._updateProgressData() - self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags())) - - def on_comm_file_transfer_failed(self, local_filename, remote_filename, elapsed): - self.on_comm_file_transfer_done(local_filename, remote_filename, elapsed, failed=True) - - def on_comm_force_disconnect(self): - self.disconnect() - - def on_comm_record_fileposition(self, origin, name, pos): - try: - self._fileManager.save_recovery_data(origin, name, pos) - except NoSuchStorage: - pass - except Exception: - self._logger.exception("Error while trying to persist print recovery data") - - def _payload_for_print_job_event(self, location=None, print_job_file=None, print_job_size=None, print_job_user=None, - position=None, action_user=None): - if print_job_file is None: - with self._selectedFileMutex: - selected_file = self._selectedFile - if not selected_file: - return {} - - print_job_file = selected_file.get("filename", None) - print_job_size = selected_file.get("filesize", None) - print_job_user = selected_file.get("user", None) - location = FileDestinations.SDCARD if selected_file.get("sd", False) else FileDestinations.LOCAL - - if not print_job_file or not location: - return {} - - if location == FileDestinations.SDCARD: - full_path = print_job_file - if full_path.startswith("/"): - full_path = full_path[1:] - name = path = full_path - origin = FileDestinations.SDCARD - - else: - full_path = self._fileManager.path_on_disk(FileDestinations.LOCAL, print_job_file) - path = self._fileManager.path_in_storage(FileDestinations.LOCAL, print_job_file) - _, name = self._fileManager.split_path(FileDestinations.LOCAL, path) - origin = FileDestinations.LOCAL - - result= {"name": name, - "path": path, - "origin": origin, - "size": print_job_size} - - if position is not None: - result["position"] = position - - if print_job_user is not None: - result["owner"] = print_job_user - - if action_user is not None: - result["user"] = action_user - - return result + """ + Default implementation of the :class:`PrinterInterface`. Manages the communication layer object and registers + itself with it as a callback to react to changes on the communication layer. + """ + + def __init__(self, fileManager, analysisQueue, printerProfileManager): + from collections import deque + + self._logger = logging.getLogger(__name__) + self._logger_job = logging.getLogger("{}.job".format(__name__)) + + self._dict = ( + frozendict + if settings().getBoolean(["devel", "useFrozenDictForPrinterState"]) + else dict + ) + + self._analysisQueue = analysisQueue + self._fileManager = fileManager + self._printerProfileManager = printerProfileManager + + # state + # TODO do we really need to hold the temperature here? + self._temp = None + self._bedTemp = None + self._chamberTemp = None + self._targetTemp = None + self._targetBedTemp = None + self._targetChamberTemp = None + self._temps = TemperatureHistory( + cutoff=settings().getInt(["temperature", "cutoff"]) * 60 + ) + self._tempBacklog = [] + + self._messages = deque([], 300) + self._messageBacklog = [] + + self._log = deque([], 300) + self._logBacklog = [] + + self._state = None + + self._currentZ = None + + self._printAfterSelect = False + self._posAfterSelect = None + + # sd handling + self._sdPrinting = False + self._sdStreaming = False + self._sdFilelistAvailable = threading.Event() + self._streamingFinishedCallback = None + self._streamingFailedCallback = None + + # job handling & estimation + self._selectedFileMutex = threading.RLock() + self._selectedFile = None + + self._estimator_factory = PrintTimeEstimator + self._estimator = None + analysis_queue_hooks = plugin_manager().get_hooks( + "octoprint.printer.estimation.factory" + ) + for name, hook in analysis_queue_hooks.items(): + try: + estimator = hook() + if estimator is not None: + self._logger.info( + "Using print time estimator provided by {}".format(name) + ) + self._estimator_factory = estimator + except Exception: + self._logger.exception( + "Error while processing analysis queues from {}".format(name), + extra={"plugin": name}, + ) + + # hook card upload + self.sd_card_upload_hooks = plugin_manager().get_hooks( + "octoprint.printer.sdcardupload" + ) + + # comm + self._comm = None + + # callbacks + self._callbacks = [] + + # progress plugins + self._lastProgressReport = None + self._progressPlugins = plugin_manager().get_implementations(ProgressPlugin) + + self._additional_data_hooks = plugin_manager().get_hooks( + "octoprint.printer.additional_state_data" + ) + self._blacklisted_data_hooks = [] + + self._stateMonitor = StateMonitor( + interval=0.5, + on_update=self._sendCurrentDataCallbacks, + on_add_temperature=self._sendAddTemperatureCallbacks, + on_add_log=self._sendAddLogCallbacks, + on_add_message=self._sendAddMessageCallbacks, + on_get_progress=self._updateProgressDataCallback, + ) + self._stateMonitor.reset( + state=self._dict(text=self.get_state_string(), flags=self._getStateFlags()), + job_data=self._dict( + file=self._dict(name=None, path=None, size=None, origin=None, date=None), + estimatedPrintTime=None, + lastPrintTime=None, + filament=self._dict(length=None, volume=None), + user=None, + ), + progress=self._dict( + completion=None, + filepos=None, + printTime=None, + printTimeLeft=None, + printTimeOrigin=None, + ), + current_z=None, + offsets=self._dict(), + ) + + eventManager().subscribe( + Events.METADATA_ANALYSIS_FINISHED, self._on_event_MetadataAnalysisFinished + ) + eventManager().subscribe( + Events.METADATA_STATISTICS_UPDATED, self._on_event_MetadataStatisticsUpdated + ) + + def _create_estimator(self, job_type=None): + if job_type is None: + with self._selectedFileMutex: + if self._selectedFile is None: + return + + if self._selectedFile["sd"]: + job_type = "sdcard" + else: + job_type = "local" + + self._estimator = self._estimator_factory(job_type) + + # ~~ handling of PrinterCallbacks + + def register_callback(self, callback, *args, **kwargs): + if not isinstance(callback, PrinterCallback): + self._logger.warning( + "Registering an object as printer callback which doesn't implement the PrinterCallback interface" + ) + self._callbacks.append(callback) + + def unregister_callback(self, callback, *args, **kwargs): + try: + self._callbacks.remove(callback) + except ValueError: + # not registered + pass + + def send_initial_callback(self, callback): + if callback in self._callbacks: + self._sendInitialStateUpdate(callback) + + def _sendAddTemperatureCallbacks(self, data): + for callback in self._callbacks: + try: + callback.on_printer_add_temperature(data) + except Exception: + self._logger.exception( + "Exception while adding temperature data point to callback {}".format( + callback + ), + extra={"callback": fqcn(callback)}, + ) + + def _sendAddLogCallbacks(self, data): + for callback in self._callbacks: + try: + callback.on_printer_add_log(data) + except Exception: + self._logger.exception( + "Exception while adding communication log entry to callback {}".format( + callback + ), + extra={"callback": fqcn(callback)}, + ) + + def _sendAddMessageCallbacks(self, data): + for callback in self._callbacks: + try: + callback.on_printer_add_message(data) + except Exception: + self._logger.exception( + "Exception while adding printer message to callback {}".format( + callback + ), + extra={"callback": fqcn(callback)}, + ) + + def _sendCurrentDataCallbacks(self, data): + plugin_data = self._get_additional_plugin_data(initial=False) + for callback in self._callbacks: + try: + data_copy = copy.deepcopy(data) + if plugin_data: + data_copy.update(plugins=copy.deepcopy(plugin_data)) + callback.on_printer_send_current_data(data_copy) + except Exception: + self._logger.exception( + "Exception while pushing current data to callback {}".format( + callback + ), + extra={"callback": fqcn(callback)}, + ) + + def _get_additional_plugin_data(self, initial=False): + plugin_data = {} + + for name, hook in self._additional_data_hooks.items(): + if name in self._blacklisted_data_hooks: + continue + try: + additional = hook(initial=initial) + if additional and isinstance(additional, dict): + plugin_data[name] = additional + except Exception: + self._logger.exception( + "Error while retrieving additional data from plugin {}, blacklisting it for further loops".format( + name + ), + extra={"plugin": name}, + ) + self._blacklisted_data_hooks.append(name) + + return plugin_data + + # ~~ callback from metadata analysis event + + def _on_event_MetadataAnalysisFinished(self, event, data): + with self._selectedFileMutex: + if self._selectedFile: + self._setJobData( + self._selectedFile["filename"], + self._selectedFile["filesize"], + self._selectedFile["sd"], + self._selectedFile["user"], + ) + + def _on_event_MetadataStatisticsUpdated(self, event, data): + with self._selectedFileMutex: + if self._selectedFile: + self._setJobData( + self._selectedFile["filename"], + self._selectedFile["filesize"], + self._selectedFile["sd"], + self._selectedFile["user"], + ) + + # ~~ progress plugin reporting + + def _reportPrintProgressToPlugins(self, progress): + with self._selectedFileMutex: + if ( + progress is None + or not self._selectedFile + or not "sd" in self._selectedFile + or not "filename" in self._selectedFile + ): + return + + storage = "sdcard" if self._selectedFile["sd"] else "local" + filename = self._selectedFile["filename"] + + def call_plugins(storage, filename, progress): + for plugin in self._progressPlugins: + try: + plugin.on_print_progress(storage, filename, progress) + except Exception: + self._logger.exception( + "Exception while sending print progress to plugin %s" + % plugin._identifier, + extra={"plugin": plugin._identifier}, + ) + + thread = threading.Thread(target=call_plugins, args=(storage, filename, progress)) + thread.daemon = False + thread.start() + + # ~~ PrinterInterface implementation + + def connect(self, port=None, baudrate=None, profile=None, *args, **kwargs): + """ + Connects to the printer. If port and/or baudrate is provided, uses these settings, otherwise autodetection + will be attempted. + """ + if self._comm is not None: + return + + eventManager().fire(Events.CONNECTING) + self._printerProfileManager.select(profile) + + from octoprint.logging.handlers import SerialLogHandler + + SerialLogHandler.arm_rollover() + if not logging.getLogger("SERIAL").isEnabledFor(logging.DEBUG): + # if serial.log is not enabled, log a line to explain that to reduce "serial.log is empty" in tickets... + logging.getLogger("SERIAL").info( + "serial.log is currently not enabled, you can enable it via Settings > Serial Connection > Log communication to serial.log" + ) + + self._comm = comm.MachineCom( + port, + baudrate, + callbackObject=self, + printerProfileManager=self._printerProfileManager, + ) + self._comm.start() + + def disconnect(self, *args, **kwargs): + """ + Closes the connection to the printer. + """ + eventManager().fire(Events.DISCONNECTING) + if self._comm is not None: + self._comm.close() + else: + eventManager().fire(Events.DISCONNECTED) + + def get_transport(self, *args, **kwargs): + + if self._comm is None: + return None + + return self._comm.getTransport() + + getTransport = util.deprecated( + "getTransport has been renamed to get_transport", + since="1.2.0-dev-590", + includedoc="Replaced by :func:`get_transport`", + ) + + def job_on_hold(self, blocking=True, *args, **kwargs): + if self._comm is None: + raise RuntimeError("No connection to the printer") + return self._comm.job_put_on_hold(blocking=blocking) + + def set_job_on_hold(self, value, blocking=True, *args, **kwargs): + if self._comm is None: + raise RuntimeError("No connection to the printer") + return self._comm.set_job_on_hold(value, blocking=blocking) + + def fake_ack(self, *args, **kwargs): + if self._comm is None: + return + + self._comm.fakeOk() + + def commands(self, commands, tags=None, force=False, *args, **kwargs): + """ + Sends one or more gcode commands to the printer. + """ + if self._comm is None: + return + + if not isinstance(commands, (list, tuple)): + commands = [commands] + + if tags is None: + tags = set() + tags |= {"trigger:printer.commands"} + + for command in commands: + self._comm.sendCommand(command, tags=tags, force=force) + + def script( + self, name, context=None, must_be_set=True, part_of_job=False, *args, **kwargs + ): + if self._comm is None: + return + + if name is None or not name: + raise ValueError("name must be set") + + result = self._comm.sendGcodeScript( + name, + part_of_job=part_of_job, + replacements=context, + tags=kwargs.get("tags", set()) | {"trigger:printer.script"}, + ) + if not result and must_be_set: + raise UnknownScript(name) + + def jog(self, axes, relative=True, speed=None, *args, **kwargs): + if isinstance(axes, basestring): + # legacy parameter format, there should be an amount as first anonymous positional arguments too + axis = axes + + if not len(args) >= 1: + raise ValueError("amount not set") + amount = args[0] + if not isinstance(amount, (int, long, float)): + raise ValueError( + "amount must be a valid number: {amount}".format(amount=amount) + ) + + axes = {} + axes[axis] = amount + + if not axes: + raise ValueError("At least one axis to jog must be provided") + + for axis in axes: + if not axis in PrinterInterface.valid_axes: + raise ValueError( + "Invalid axis {}, valid axes are {}".format( + axis, ", ".join(PrinterInterface.valid_axes) + ) + ) + + command = "G1 {}".format( + " ".join(["{}{}".format(axis.upper(), amt) for axis, amt in axes.items()]) + ) + + if speed is None: + printer_profile = self._printerProfileManager.get_current_or_default() + speed = min([printer_profile["axes"][axis]["speed"] for axis in axes]) + + if speed and not isinstance(speed, bool): + command += " F{}".format(speed) + + if relative: + commands = ["G91", command, "G90"] + else: + commands = ["G90", command] + + self.commands(commands, tags=kwargs.get("tags", set()) | {"trigger:printer.jog"}) + + def home(self, axes, *args, **kwargs): + if not isinstance(axes, (list, tuple)): + if isinstance(axes, basestring): + axes = [axes] + else: + raise ValueError( + "axes is neither a list nor a string: {axes}".format(axes=axes) + ) + + validated_axes = list( + filter( + lambda x: x in PrinterInterface.valid_axes, map(lambda x: x.lower(), axes) + ) + ) + if len(axes) != len(validated_axes): + raise ValueError("axes contains invalid axes: {axes}".format(axes=axes)) + + self.commands( + [ + "G91", + "G28 %s" % " ".join(map(lambda x: "%s0" % x.upper(), validated_axes)), + "G90", + ], + tags=kwargs.get("tags", set) | {"trigger:printer.home"}, + ) + + def extrude(self, amount, speed=None, *args, **kwargs): + if not isinstance(amount, (int, long, float)): + raise ValueError( + "amount must be a valid number: {amount}".format(amount=amount) + ) + + printer_profile = self._printerProfileManager.get_current_or_default() + + # Use specified speed (if any) + max_e_speed = printer_profile["axes"]["e"]["speed"] + + if speed is None: + # No speed was specified so default to value configured in printer profile + extrusion_speed = max_e_speed + else: + # Make sure that specified value is not greater than maximum as defined in printer profile + extrusion_speed = min([speed, max_e_speed]) + + self.commands( + ["G91", "M83", "G1 E%s F%d" % (amount, extrusion_speed), "M82", "G90"], + tags=kwargs.get("tags", set()) | {"trigger:printer.extrude"}, + ) + + def change_tool(self, tool, *args, **kwargs): + if not PrinterInterface.valid_tool_regex.match(tool): + raise ValueError('tool must match "tool[0-9]+": {tool}'.format(tool=tool)) + + tool_num = int(tool[len("tool") :]) + self.commands( + "T%d" % tool_num, + tags=kwargs.get("tags", set()) | {"trigger:printer.change_tool"}, + ) + + def set_temperature(self, heater, value, *args, **kwargs): + if not PrinterInterface.valid_heater_regex.match(heater): + raise ValueError( + 'heater must match "tool[0-9]+", "bed" or "chamber": {heater}'.format( + heater=heater + ) + ) + + if not isinstance(value, (int, long, float)) or value < 0: + raise ValueError( + "value must be a valid number >= 0: {value}".format(value=value) + ) + + tags = kwargs.get("tags", set()) | {"trigger:printer.set_temperature"} + + if heater.startswith("tool"): + printer_profile = self._printerProfileManager.get_current_or_default() + extruder_count = printer_profile["extruder"]["count"] + shared_nozzle = printer_profile["extruder"]["sharedNozzle"] + if extruder_count > 1 and not shared_nozzle: + toolNum = int(heater[len("tool") :]) + self.commands("M104 T{} S{}".format(toolNum, value), tags=tags) + else: + self.commands("M104 S{}".format(value), tags=tags) + + elif heater == "bed": + self.commands("M140 S{}".format(value), tags=tags) + + elif heater == "chamber": + self.commands("M141 S{}".format(value), tags=tags) + + def set_temperature_offset(self, offsets=None, *args, **kwargs): + if offsets is None: + offsets = {} + + if not isinstance(offsets, dict): + raise ValueError("offsets must be a dict") + + validated_keys = list( + filter(lambda x: PrinterInterface.valid_heater_regex.match(x), offsets.keys()) + ) + validated_values = list( + filter(lambda x: isinstance(x, (int, long, float)), offsets.values()) + ) + + if len(validated_keys) != len(offsets): + raise ValueError( + "offsets contains invalid keys: {offsets}".format(offsets=offsets) + ) + if len(validated_values) != len(offsets): + raise ValueError( + "offsets contains invalid values: {offsets}".format(offsets=offsets) + ) + + if self._comm is None: + return + + self._comm.setTemperatureOffset(offsets) + self._setOffsets(self._comm.getOffsets()) + + def _convert_rate_value(self, factor, min_val=None, max_val=None): + if not isinstance(factor, (int, float, long)): + raise ValueError("factor is not a number") + + if isinstance(factor, float): + factor = int(factor * 100.0) + + if min_val and factor < min_val: + raise ValueError("factor must be a value >={}".format(min_val)) + elif max_val and factor > max_val: + raise ValueError("factor must be a value <={}".format(max_val)) + + return factor + + def feed_rate(self, factor, *args, **kwargs): + factor = self._convert_rate_value(factor, min_val=1) + self.commands( + "M220 S%d" % factor, + tags=kwargs.get("tags", set()) | {"trigger:printer.feed_rate"}, + ) + + def flow_rate(self, factor, *args, **kwargs): + factor = self._convert_rate_value(factor, min_val=1) + self.commands( + "M221 S%d" % factor, + tags=kwargs.get("tags", set()) | {"trigger:printer.flow_rate"}, + ) + + def select_file( + self, path, sd, printAfterSelect=False, user=None, pos=None, *args, **kwargs + ): + if self._comm is None or (self._comm.isBusy() or self._comm.isStreaming()): + self._logger.info("Cannot load file: printer not connected or currently busy") + return + + self._validateJob(path, sd) + + origin = FileDestinations.SDCARD if sd else FileDestinations.LOCAL + if sd: + path_on_disk = "/" + path + path_in_storage = path + else: + path_on_disk = self._fileManager.path_on_disk(origin, path) + path_in_storage = self._fileManager.path_in_storage(origin, path_on_disk) + + try: + recovery_data = self._fileManager.get_recovery_data() + if recovery_data: + # clean up recovery data if we just selected a different file + actual_origin = recovery_data.get("origin", None) + actual_path = recovery_data.get("path", None) + + if ( + actual_origin is None + or actual_path is None + or actual_origin != origin + or actual_path != path_in_storage + ): + self._fileManager.delete_recovery_data() + except Exception: + # anything goes wrong with the recovery data, we ignore it + self._logger.exception( + "Something was wrong with processing the recovery data" + ) + + self._printAfterSelect = printAfterSelect + self._posAfterSelect = pos + self._comm.selectFile( + "/" + path if sd else path_on_disk, + sd, + user=user, + tags=kwargs.get("tags", set()) | {"trigger:printer.select_file"}, + ) + self._updateProgressData() + self._setCurrentZ(None) + + def unselect_file(self, *args, **kwargs): + if self._comm is not None and (self._comm.isBusy() or self._comm.isStreaming()): + return + + self._comm.unselectFile() + self._updateProgressData() + self._setCurrentZ(None) + + def get_file_position(self): + if self._comm is None: + return None + + with self._selectedFileMutex: + if self._selectedFile is None: + return None + + return self._comm.getFilePosition() + + def start_print(self, pos=None, user=None, *args, **kwargs): + """ + Starts the currently loaded print job. + Only starts if the printer is connected and operational, not currently printing and a printjob is loaded + """ + if ( + self._comm is None + or not self._comm.isOperational() + or self._comm.isPrinting() + ): + return + + with self._selectedFileMutex: + if self._selectedFile is None: + return + + self._fileManager.delete_recovery_data() + + self._lastProgressReport = None + self._updateProgressData() + self._setCurrentZ(None) + self._comm.startPrint( + pos=pos, + user=user, + tags=kwargs.get("tags", set()) | {"trigger:printer.start_print"}, + ) + + def pause_print(self, user=None, *args, **kwargs): + """ + Pause the current printjob. + """ + if self._comm is None: + return + + if self._comm.isPaused(): + return + + self._comm.setPause( + True, + user=user, + tags=kwargs.get("tags", set()) | {"trigger:printer.pause_print"}, + ) + + def resume_print(self, user=None, *args, **kwargs): + """ + Resume the current printjob. + """ + if self._comm is None: + return + + if not self._comm.isPaused(): + return + + self._comm.setPause( + False, + user=user, + tags=kwargs.get("tags", set()) | {"trigger:printer.resume_print"}, + ) + + def cancel_print(self, user=None, *args, **kwargs): + """ + Cancel the current printjob. + """ + if self._comm is None: + return + + # tell comm layer to cancel - will also trigger our cancelled handler + # for further processing + self._comm.cancelPrint( + user=user, tags=kwargs.get("tags", set()) | {"trigger:printer.cancel_print"} + ) + + def log_lines(self, *lines): + serial_logger = logging.getLogger("SERIAL") + self.on_comm_log("\n".join(lines)) + for line in lines: + serial_logger.debug(line) + + def get_state_string(self, state=None, *args, **kwargs): + if self._comm is None: + return "Offline" + else: + return self._comm.getStateString(state=state) + + def get_state_id(self, state=None, *args, **kwargs): + if self._comm is None: + return "OFFLINE" + else: + return self._comm.getStateId(state=state) + + def get_current_data(self, *args, **kwargs): + return util.thaw_frozendict(self._stateMonitor.get_current_data()) + + def get_current_job(self, *args, **kwargs): + currentData = self._stateMonitor.get_current_data() + return util.thaw_frozendict(currentData["job"]) + + def get_current_temperatures(self, *args, **kwargs): + if self._comm is not None: + offsets = self._comm.getOffsets() + else: + offsets = {} + + result = {} + if self._temp is not None: + for tool in self._temp.keys(): + result["tool%d" % tool] = { + "actual": self._temp[tool][0], + "target": self._temp[tool][1], + "offset": offsets[tool] + if tool in offsets and offsets[tool] is not None + else 0, + } + if self._bedTemp is not None: + result["bed"] = { + "actual": self._bedTemp[0], + "target": self._bedTemp[1], + "offset": offsets["bed"] + if "bed" in offsets and offsets["bed"] is not None + else 0, + } + if self._chamberTemp is not None: + result["chamber"] = { + "actual": self._chamberTemp[0], + "target": self._chamberTemp[1], + "offset": offsets["chamber"] + if "chamber" in offsets and offsets["chamber"] is not None + else 0, + } + + return result + + def get_temperature_history(self, *args, **kwargs): + return self._temps + + def get_current_connection(self, *args, **kwargs): + if self._comm is None: + return "Closed", None, None, None + + port, baudrate = self._comm.getConnection() + printer_profile = self._printerProfileManager.get_current_or_default() + return self._comm.getStateString(), port, baudrate, printer_profile + + def is_closed_or_error(self, *args, **kwargs): + return self._comm is None or self._comm.isClosedOrError() + + def is_operational(self, *args, **kwargs): + return self._comm is not None and self._comm.isOperational() + + def is_printing(self, *args, **kwargs): + return self._comm is not None and self._comm.isPrinting() + + def is_cancelling(self, *args, **kwargs): + return self._comm is not None and self._comm.isCancelling() + + def is_pausing(self, *args, **kwargs): + return self._comm is not None and self._comm.isPausing() + + def is_paused(self, *args, **kwargs): + return self._comm is not None and self._comm.isPaused() + + def is_resuming(self, *args, **kwargs): + return self._comm is not None and self._comm.isResuming() + + def is_finishing(self, *args, **kwargs): + return self._comm is not None and self._comm.isFinishing() + + def is_error(self, *args, **kwargs): + return self._comm is not None and self._comm.isError() + + def is_ready(self, *args, **kwargs): + return ( + self.is_operational() + and not self.is_printing() + and not self._comm.isStreaming() + ) + + def is_sd_ready(self, *args, **kwargs): + if not settings().getBoolean(["feature", "sdSupport"]) or self._comm is None: + return False + else: + return self._comm.isSdReady() + + # ~~ sd file handling + + def get_sd_files(self, *args, **kwargs): + if self._comm is None or not self._comm.isSdReady(): + result = [] + else: + result = list( + map( + lambda x: {"name": x[0][1:], "size": x[1], "display": x[2]}, + self._comm.getSdFiles(), + ) + ) + return result + + def add_sd_file( + self, filename, path, on_success=None, on_failure=None, *args, **kwargs + ): + if not self._comm or self._comm.isBusy() or not self._comm.isSdReady(): + self._logger.error("No connection to printer or printer is busy") + return + + self._streamingFinishedCallback = on_success + self._streamingFailedCallback = on_failure + + def sd_upload_started(local_filename, remote_filename): + eventManager().fire( + Events.TRANSFER_STARTED, + {"local": local_filename, "remote": remote_filename}, + ) + + def sd_upload_succeeded(local_filename, remote_filename, elapsed): + payload = { + "local": local_filename, + "remote": remote_filename, + "time": elapsed, + } + eventManager().fire(Events.TRANSFER_DONE, payload) + if callable(self._streamingFinishedCallback): + self._streamingFinishedCallback( + remote_filename, remote_filename, FileDestinations.SDCARD + ) + + def sd_upload_failed(local_filename, remote_filename, elapsed): + payload = { + "local": local_filename, + "remote": remote_filename, + "time": elapsed, + } + eventManager().fire(Events.TRANSFER_FAILED, payload) + if callable(self._streamingFailedCallback): + self._streamingFailedCallback( + remote_filename, remote_filename, FileDestinations.SDCARD + ) + + for name, hook in self.sd_card_upload_hooks.items(): + # first sd card upload plugin that feels responsible gets the job + try: + result = hook( + self, + filename, + path, + sd_upload_started, + sd_upload_succeeded, + sd_upload_failed, + *args, + **kwargs + ) + if result is not None: + return result + except Exception: + self._logger.exception( + "There was an error running the sd upload " + "hook provided by plugin {}".format(name), + extra={"plugin": name}, + ) + + else: + # no plugin feels responsible, use the default implementation + return self._add_sd_file(filename, path, tags=kwargs.get("tags")) + + def _get_free_remote_name(self, filename): + self.refresh_sd_files(blocking=True) + existingSdFiles = list(map(lambda x: x[0], self._comm.getSdFiles())) + + if valid_file_type(filename, "gcode"): + # figure out remote filename + remote_name = util.get_dos_filename( + filename, + existing_filenames=existingSdFiles, + extension="gco", + whitelisted_extensions=["gco", "g"], + ) + else: + # probably something else added through a plugin, use it's basename as-is + remote_name = os.path.basename(filename) + + return remote_name + + def _add_sd_file(self, filename, path, tags=None): + if tags is None: + tags = set() + + remote_name = self._get_free_remote_name(filename) + self._create_estimator("stream") + self._comm.startFileTransfer( + path, + filename, + "/" + remote_name, + special=not valid_file_type(filename, "gcode"), + tags=tags | {"trigger:printer.add_sd_file"}, + ) + + return remote_name + + def delete_sd_file(self, filename, *args, **kwargs): + if not self._comm or not self._comm.isSdReady(): + return + self._comm.deleteSdFile( + "/" + filename, + tags=kwargs.get("tags", set()) | {"trigger:printer.delete_sd_file"}, + ) + + def init_sd_card(self, *args, **kwargs): + if not self._comm or self._comm.isSdReady(): + return + self._comm.initSdCard( + tags=kwargs.get("tags", set()) | {"trigger:printer.init_sd_card"} + ) + + def release_sd_card(self, *args, **kwargs): + if not self._comm or not self._comm.isSdReady(): + return + self._comm.releaseSdCard( + tags=kwargs.get("tags", set()) | {"trigger:printer.release_sd_card"} + ) + + def refresh_sd_files(self, blocking=False, *args, **kwargs): + """ + Refreshes the list of file stored on the SD card attached to printer (if available and printer communication + available). Optional blocking parameter allows making the method block (max 10s) until the file list has been + received (and can be accessed via self._comm.getSdFiles()). Defaults to an asynchronous operation. + """ + if not self._comm or not self._comm.isSdReady(): + return + self._sdFilelistAvailable.clear() + self._comm.refreshSdFiles( + tags=kwargs.get("tags", set()) | {"trigger:printer.refresh_sd_files"} + ) + if blocking: + self._sdFilelistAvailable.wait(kwargs.get("timeout", 10000)) + + # ~~ state monitoring + + def _setOffsets(self, offsets): + self._stateMonitor.set_temp_offsets(offsets) + + def _setCurrentZ(self, currentZ): + self._currentZ = currentZ + self._stateMonitor.set_current_z(self._currentZ) + + def _setState(self, state, state_string=None): + if state_string is None: + state_string = self.get_state_string() + + self._state = state + self._stateMonitor.set_state( + self._dict(text=state_string, flags=self._getStateFlags()) + ) + + payload = { + "state_id": self.get_state_id(self._state), + "state_string": self.get_state_string(self._state), + } + eventManager().fire(Events.PRINTER_STATE_CHANGED, payload) + + def _addLog(self, log): + self._log.append(log) + self._stateMonitor.add_log(log) + + def _addMessage(self, message): + self._messages.append(message) + self._stateMonitor.add_message(message) + + def _updateProgressData( + self, + completion=None, + filepos=None, + printTime=None, + printTimeLeft=None, + printTimeLeftOrigin=None, + ): + self._stateMonitor.set_progress( + self._dict( + completion=int(completion * 100) if completion is not None else None, + filepos=filepos, + printTime=int(printTime) if printTime is not None else None, + printTimeLeft=int(printTimeLeft) if printTimeLeft is not None else None, + printTimeLeftOrigin=printTimeLeftOrigin, + ) + ) + + def _updateProgressDataCallback(self): + if self._comm is None: + progress = None + filepos = None + printTime = None + cleanedPrintTime = None + else: + progress = self._comm.getPrintProgress() + filepos = self._comm.getPrintFilepos() + printTime = self._comm.getPrintTime() + cleanedPrintTime = self._comm.getCleanedPrintTime() + + printTimeLeft = printTimeLeftOrigin = None + estimator = self._estimator + if progress is not None: + progress_int = int(progress * 100) + if self._lastProgressReport != progress_int: + self._lastProgressReport = progress_int + self._reportPrintProgressToPlugins(progress_int) + + if progress == 0: + printTimeLeft = None + printTimeLeftOrigin = None + elif progress == 1.0: + printTimeLeft = 0 + printTimeLeftOrigin = None + elif estimator is not None: + statisticalTotalPrintTime = None + statisticalTotalPrintTimeType = None + with self._selectedFileMutex: + if ( + self._selectedFile + and "estimatedPrintTime" in self._selectedFile + and self._selectedFile["estimatedPrintTime"] + ): + statisticalTotalPrintTime = self._selectedFile[ + "estimatedPrintTime" + ] + statisticalTotalPrintTimeType = self._selectedFile.get( + "estimatedPrintTimeType", None + ) + + try: + printTimeLeft, printTimeLeftOrigin = estimator.estimate( + progress, + printTime, + cleanedPrintTime, + statisticalTotalPrintTime, + statisticalTotalPrintTimeType, + ) + except Exception: + self._logger.exception( + "Error while estimating print time via {}".format(estimator) + ) + + return self._dict( + completion=progress * 100 if progress is not None else None, + filepos=filepos, + printTime=int(printTime) if printTime is not None else None, + printTimeLeft=int(printTimeLeft) if printTimeLeft is not None else None, + printTimeLeftOrigin=printTimeLeftOrigin, + ) + + def _addTemperatureData(self, tools=None, bed=None, chamber=None, custom=None): + if tools is None: + tools = {} + if custom is None: + custom = {} + + data = {"time": int(time.time())} + for tool in tools.keys(): + data["tool%d" % tool] = self._dict( + actual=tools[tool][0], target=tools[tool][1] + ) + if bed is not None and isinstance(bed, tuple): + data["bed"] = self._dict(actual=bed[0], target=bed[1]) + if chamber is not None and isinstance(chamber, tuple): + data["chamber"] = self._dict(actual=chamber[0], target=chamber[1]) + for identifier, values in custom.items(): + data[identifier] = self._dict(actual=values[0], target=values[1]) + + self._temps.append(data) + + self._temp = tools + self._bedTemp = bed + self._chamberTemp = chamber + self._custom = custom + + self._stateMonitor.add_temperature(self._dict(**data)) + + def _validateJob(self, filename, sd): + if not valid_file_type(filename, type="machinecode"): + raise InvalidFileType( + "{} is not a machinecode file, cannot print".format(filename) + ) + + if sd: + return + + path_on_disk = self._fileManager.path_on_disk(FileDestinations.LOCAL, filename) + if os.path.isabs(filename) and not filename == path_on_disk: + raise InvalidFileLocation( + "{} is not located within local storage, cannot select for printing".format( + filename + ) + ) + if not os.path.isfile(path_on_disk): + raise InvalidFileLocation( + "{} does not exist in local storage, cannot select for printing".format( + filename + ) + ) + + def _setJobData(self, filename, filesize, sd, user=None): + with self._selectedFileMutex: + if filename is not None: + if sd: + name_in_storage = filename + if name_in_storage.startswith("/"): + name_in_storage = name_in_storage[1:] + path_in_storage = name_in_storage + path_on_disk = None + else: + path_in_storage = self._fileManager.path_in_storage( + FileDestinations.LOCAL, filename + ) + path_on_disk = self._fileManager.path_on_disk( + FileDestinations.LOCAL, filename + ) + _, name_in_storage = self._fileManager.split_path( + FileDestinations.LOCAL, path_in_storage + ) + self._selectedFile = { + "filename": path_in_storage, + "filesize": filesize, + "sd": sd, + "estimatedPrintTime": None, + "user": user, + } + else: + self._selectedFile = None + self._stateMonitor.set_job_data( + self._dict( + file=self._dict( + name=None, + path=None, + display=None, + origin=None, + size=None, + date=None, + ), + estimatedPrintTime=None, + averagePrintTime=None, + lastPrintTime=None, + filament=None, + user=None, + ) + ) + return + + estimatedPrintTime = None + lastPrintTime = None + averagePrintTime = None + date = None + filament = None + display_name = name_in_storage + if path_on_disk: + # Use a string for mtime because it could be float and the + # javascript needs to exact match + if not sd: + date = int(os.stat(path_on_disk).st_mtime) + + try: + fileData = self._fileManager.get_metadata( + FileDestinations.SDCARD if sd else FileDestinations.LOCAL, + path_on_disk, + ) + except Exception: + self._logger.exception("Error generating fileData") + fileData = None + if fileData is not None: + if "display" in fileData: + display_name = fileData["display"] + if "analysis" in fileData: + if ( + estimatedPrintTime is None + and "estimatedPrintTime" in fileData["analysis"] + ): + estimatedPrintTime = fileData["analysis"][ + "estimatedPrintTime" + ] + if "filament" in fileData["analysis"]: + filament = fileData["analysis"]["filament"] + if "statistics" in fileData: + printer_profile = ( + self._printerProfileManager.get_current_or_default()["id"] + ) + if ( + "averagePrintTime" in fileData["statistics"] + and printer_profile + in fileData["statistics"]["averagePrintTime"] + ): + averagePrintTime = fileData["statistics"]["averagePrintTime"][ + printer_profile + ] + if ( + "lastPrintTime" in fileData["statistics"] + and printer_profile in fileData["statistics"]["lastPrintTime"] + ): + lastPrintTime = fileData["statistics"]["lastPrintTime"][ + printer_profile + ] + + if averagePrintTime is not None: + self._selectedFile["estimatedPrintTime"] = averagePrintTime + self._selectedFile["estimatedPrintTimeType"] = "average" + elif estimatedPrintTime is not None: + # TODO apply factor which first needs to be tracked! + self._selectedFile["estimatedPrintTime"] = estimatedPrintTime + self._selectedFile["estimatedPrintTimeType"] = "analysis" + + self._stateMonitor.set_job_data( + self._dict( + file=self._dict( + name=name_in_storage, + path=path_in_storage, + display=display_name, + origin=FileDestinations.SDCARD if sd else FileDestinations.LOCAL, + size=filesize, + date=date, + ), + estimatedPrintTime=estimatedPrintTime, + averagePrintTime=averagePrintTime, + lastPrintTime=lastPrintTime, + filament=filament, + user=user, + ) + ) + + def _updateJobUser(self, user): + with self._selectedFileMutex: + if ( + self._selectedFile is not None + and self._selectedFile.get("user", None) != user + ): + self._selectedFile["user"] = user + + job_data = self.get_current_job() + self._stateMonitor.set_job_data( + self._dict( + file=job_data["file"], + estimatedPrintTime=job_data["estimatedPrintTime"], + averagePrintTime=job_data["averagePrintTime"], + lastPrintTime=job_data["lastPrintTime"], + filament=job_data["filament"], + user=user, + ) + ) + + def _sendInitialStateUpdate(self, callback): + try: + data = self._stateMonitor.get_current_data() + data.update( + temps=list(self._temps), + logs=list(self._log), + messages=list(self._messages), + ) + + plugin_data = self._get_additional_plugin_data(initial=False) + if plugin_data: + data.update(plugins=copy.deepcopy(plugin_data)) + + callback.on_printer_send_initial_data(data) + except Exception: + self._logger.exception( + "Error while pushing initial state update to callback {}".format( + callback + ), + extra={"callback": fqcn(callback)}, + ) + + def _getStateFlags(self): + return self._dict( + operational=self.is_operational(), + printing=self.is_printing(), + cancelling=self.is_cancelling(), + pausing=self.is_pausing(), + resuming=self.is_resuming(), + finishing=self.is_finishing(), + closedOrError=self.is_closed_or_error(), + error=self.is_error(), + paused=self.is_paused(), + ready=self.is_ready(), + sdReady=self.is_sd_ready(), + ) + + # ~~ comm.MachineComPrintCallback implementation + + def on_comm_log(self, message): + """ + Callback method for the comm object, called upon log output. + """ + self._addLog(to_unicode(message, "utf-8", errors="replace")) + + def on_comm_temperature_update(self, tools, bed, chamber, custom=None): + if custom is None: + custom = {} + self._addTemperatureData( + tools=copy.deepcopy(tools), + bed=copy.deepcopy(bed), + chamber=copy.deepcopy(chamber), + custom=copy.deepcopy(custom), + ) + + def on_comm_position_update(self, position, reason=None): + payload = {"reason": reason} + payload.update(position) + eventManager().fire(Events.POSITION_UPDATE, payload) + + def on_comm_state_change(self, state): + """ + Callback method for the comm object, called if the connection state changes. + """ + oldState = self._state + + state_string = None + if self._comm is not None: + state_string = self._comm.getStateString() + + if oldState in (comm.MachineCom.STATE_PRINTING,): + # if we were still printing and went into an error state, mark the print as failed + if state in ( + comm.MachineCom.STATE_CLOSED, + comm.MachineCom.STATE_ERROR, + comm.MachineCom.STATE_CLOSED_WITH_ERROR, + ): + with self._selectedFileMutex: + if self._selectedFile is not None: + payload = self._payload_for_print_job_event() + if payload: + payload["time"] = self._comm.getPrintTime() + payload["reason"] = "error" + payload["error"] = self._comm.getErrorString() + + def finalize(): + self._fileManager.log_print( + payload["origin"], + payload["path"], + time.time(), + payload["time"], + False, + self._printerProfileManager.get_current_or_default()[ + "id" + ], + ) + eventManager().fire(Events.PRINT_FAILED, payload) + + thread = threading.Thread(target=finalize) + thread.daemon = True + thread.start() + + try: + self._analysisQueue.resume() # printing done, put those cpu cycles to good use + except Exception: + self._logger.exception("Error while resuming the analysis queue") + + elif state == comm.MachineCom.STATE_PRINTING: + if settings().get(["gcodeAnalysis", "runAt"]) == "idle": + try: + self._analysisQueue.pause() # only analyse files while idle + except Exception: + self._logger.exception("Error while pausing the analysis queue") + + if ( + state == comm.MachineCom.STATE_CLOSED + or state == comm.MachineCom.STATE_CLOSED_WITH_ERROR + ): + if self._comm is not None: + self._comm = None + + self._updateProgressData() + self._setCurrentZ(None) + self._setJobData(None, None, None) + self._setOffsets(None) + self._addTemperatureData() + self._printerProfileManager.deselect() + eventManager().fire(Events.DISCONNECTED) + + self._setState(state, state_string=state_string) + + def on_comm_message(self, message): + """ + Callback method for the comm object, called upon message exchanges via serial. + Stores the message in the message buffer, truncates buffer to the last 300 lines. + """ + self._addMessage(to_unicode(message, "utf-8", errors="replace")) + + def on_comm_progress(self): + """ + Callback method for the comm object, called upon any change in progress of the printjob. + Triggers storage of new values for printTime, printTimeLeft and the current progress. + """ + + self._stateMonitor.trigger_progress_update() + + def on_comm_z_change(self, newZ): + """ + Callback method for the comm object, called upon change of the z-layer. + """ + oldZ = self._currentZ + if newZ != oldZ: + # we have to react to all z-changes, even those that might "go backward" due to a slicer's retraction or + # anti-backlash-routines. Event subscribes should individually take care to filter out "wrong" z-changes + eventManager().fire(Events.Z_CHANGE, {"new": newZ, "old": oldZ}) + + self._setCurrentZ(newZ) + + def on_comm_sd_state_change(self, sdReady): + self._stateMonitor.set_state( + self._dict(text=self.get_state_string(), flags=self._getStateFlags()) + ) + + def on_comm_sd_files(self, files): + eventManager().fire(Events.UPDATED_FILES, {"type": "printables"}) + self._sdFilelistAvailable.set() + + def on_comm_file_selected(self, full_path, size, sd, user=None): + if full_path is not None: + payload = self._payload_for_print_job_event( + location=FileDestinations.SDCARD if sd else FileDestinations.LOCAL, + print_job_file=full_path, + print_job_user=user, + action_user=user, + ) + eventManager().fire(Events.FILE_SELECTED, payload) + self._logger_job.info( + "Print job selected - origin: {}, path: {}, owner: {}, user: {}".format( + payload.get("origin"), + payload.get("path"), + payload.get("owner"), + payload.get("user"), + ) + ) + else: + eventManager().fire(Events.FILE_DESELECTED) + self._logger_job.info( + "Print job deselected - user: {}".format(user if user else "n/a") + ) + + self._setJobData(full_path, size, sd, user=user) + self._stateMonitor.set_state( + self._dict(text=self.get_state_string(), flags=self._getStateFlags()) + ) + + self._create_estimator() + + if self._printAfterSelect: + self._printAfterSelect = False + self.start_print(pos=self._posAfterSelect, user=user) + + def on_comm_print_job_started(self, suppress_script=False, user=None): + self._updateJobUser( + user + ) # the final job owner should always be whoever _started_ the job + self._stateMonitor.trigger_progress_update() + payload = self._payload_for_print_job_event(print_job_user=user, action_user=user) + if payload: + eventManager().fire(Events.PRINT_STARTED, payload) + self._logger_job.info( + "Print job started - origin: {}, path: {}, owner: {}, user: {}".format( + payload.get("origin"), + payload.get("path"), + payload.get("owner"), + payload.get("user"), + ) + ) + + if not suppress_script: + self.script( + "beforePrintStarted", + context={"event": payload}, + part_of_job=True, + must_be_set=False, + ) + + def on_comm_print_job_done(self, suppress_script=False): + self._fileManager.delete_recovery_data() + + payload = self._payload_for_print_job_event() + if payload: + payload["time"] = self._comm.getPrintTime() + self._updateProgressData( + completion=1.0, + filepos=payload["size"], + printTime=payload["time"], + printTimeLeft=0, + ) + self._stateMonitor.set_state( + self._dict(text=self.get_state_string(), flags=self._getStateFlags()) + ) + + eventManager().fire(Events.PRINT_DONE, payload) + self._logger_job.info( + "Print job done - origin: {}, path: {}, owner: {}".format( + payload.get("origin"), payload.get("path"), payload.get("owner") + ) + ) + + if not suppress_script: + self.script( + "afterPrintDone", + context={"event": payload}, + part_of_job=True, + must_be_set=False, + ) + + def log_print(): + self._fileManager.log_print( + payload["origin"], + payload["path"], + time.time(), + payload["time"], + True, + self._printerProfileManager.get_current_or_default()["id"], + ) + + thread = threading.Thread(target=log_print) + thread.daemon = True + thread.start() + + else: + self._updateProgressData() + self._stateMonitor.set_state( + self._dict(text=self.get_state_string(), flags=self._getStateFlags()) + ) + + def on_comm_print_job_cancelling(self, firmware_error=None, user=None): + payload = self._payload_for_print_job_event(action_user=user) + if payload: + if firmware_error: + payload["firmwareError"] = firmware_error + eventManager().fire(Events.PRINT_CANCELLING, payload) + + def on_comm_print_job_cancelled(self, suppress_script=False, user=None): + self._setCurrentZ(None) + self._updateProgressData() + + payload = self._payload_for_print_job_event( + position=self._comm.cancel_position.as_dict() + if self._comm and self._comm.cancel_position + else None, + action_user=user, + ) + if payload: + payload["time"] = self._comm.getPrintTime() + + eventManager().fire(Events.PRINT_CANCELLED, payload) + self._logger_job.info( + "Print job cancelled - origin: {}, path: {}, owner: {}, user: {}".format( + payload.get("origin"), + payload.get("path"), + payload.get("owner"), + payload.get("user"), + ) + ) + + if not suppress_script: + self.script( + "afterPrintCancelled", + context={"event": payload}, + part_of_job=True, + must_be_set=False, + ) + + payload["reason"] = "cancelled" + + def finalize(): + self._fileManager.log_print( + payload["origin"], + payload["path"], + time.time(), + payload["time"], + False, + self._printerProfileManager.get_current_or_default()["id"], + ) + eventManager().fire(Events.PRINT_FAILED, payload) + + thread = threading.Thread(target=finalize) + thread.daemon = True + thread.start() + + def on_comm_print_job_paused(self, suppress_script=False, user=None): + payload = self._payload_for_print_job_event( + position=self._comm.pause_position.as_dict() + if self._comm and self._comm.pause_position and not suppress_script + else None, + action_user=user, + ) + if payload: + eventManager().fire(Events.PRINT_PAUSED, payload) + self._logger_job.info( + "Print job paused - origin: {}, path: {}, owner: {}, user: {}".format( + payload.get("origin"), + payload.get("path"), + payload.get("owner"), + payload.get("user"), + ) + ) + if not suppress_script: + self.script( + "afterPrintPaused", + context={"event": payload}, + part_of_job=True, + must_be_set=False, + ) + + def on_comm_print_job_resumed(self, suppress_script=False, user=None): + payload = self._payload_for_print_job_event(action_user=user) + if payload: + eventManager().fire(Events.PRINT_RESUMED, payload) + self._logger_job.info( + "Print job resumed - origin: {}, path: {}, owner: {}, user: {}".format( + payload.get("origin"), + payload.get("path"), + payload.get("owner"), + payload.get("user"), + ) + ) + + if not suppress_script: + self.script( + "beforePrintResumed", + context={"event": payload}, + part_of_job=True, + must_be_set=False, + ) + + def on_comm_file_transfer_started( + self, local_filename, remote_filename, filesize, user=None + ): + eventManager().fire( + Events.TRANSFER_STARTED, {"local": local_filename, "remote": remote_filename} + ) + + self._sdStreaming = True + + self._setJobData(remote_filename, filesize, True, user=user) + self._updateProgressData(completion=0.0, filepos=0, printTime=0) + self._stateMonitor.set_state( + self._dict(text=self.get_state_string(), flags=self._getStateFlags()) + ) + + def on_comm_file_transfer_done( + self, local_filename, remote_filename, elapsed, failed=False + ): + self._sdStreaming = False + + payload = {"local": local_filename, "remote": remote_filename, "time": elapsed} + + if failed: + eventManager().fire(Events.TRANSFER_FAILED, payload) + if callable(self._streamingFailedCallback): + self._streamingFailedCallback( + remote_filename, remote_filename, FileDestinations.SDCARD + ) + else: + eventManager().fire(Events.TRANSFER_DONE, payload) + if callable(self._streamingFinishedCallback): + self._streamingFinishedCallback( + remote_filename, remote_filename, FileDestinations.SDCARD + ) + + self._setCurrentZ(None) + self._setJobData(None, None, None) + self._updateProgressData() + self._stateMonitor.set_state( + self._dict(text=self.get_state_string(), flags=self._getStateFlags()) + ) + + def on_comm_file_transfer_failed(self, local_filename, remote_filename, elapsed): + self.on_comm_file_transfer_done( + local_filename, remote_filename, elapsed, failed=True + ) + + def on_comm_force_disconnect(self): + self.disconnect() + + def on_comm_record_fileposition(self, origin, name, pos): + try: + self._fileManager.save_recovery_data(origin, name, pos) + except NoSuchStorage: + pass + except Exception: + self._logger.exception("Error while trying to persist print recovery data") + + def _payload_for_print_job_event( + self, + location=None, + print_job_file=None, + print_job_size=None, + print_job_user=None, + position=None, + action_user=None, + ): + if print_job_file is None: + with self._selectedFileMutex: + selected_file = self._selectedFile + if not selected_file: + return {} + + print_job_file = selected_file.get("filename", None) + print_job_size = selected_file.get("filesize", None) + print_job_user = selected_file.get("user", None) + location = ( + FileDestinations.SDCARD + if selected_file.get("sd", False) + else FileDestinations.LOCAL + ) + + if not print_job_file or not location: + return {} + + if location == FileDestinations.SDCARD: + full_path = print_job_file + if full_path.startswith("/"): + full_path = full_path[1:] + name = path = full_path + origin = FileDestinations.SDCARD + + else: + full_path = self._fileManager.path_on_disk( + FileDestinations.LOCAL, print_job_file + ) + path = self._fileManager.path_in_storage( + FileDestinations.LOCAL, print_job_file + ) + _, name = self._fileManager.split_path(FileDestinations.LOCAL, path) + origin = FileDestinations.LOCAL + + result = {"name": name, "path": path, "origin": origin, "size": print_job_size} + + if position is not None: + result["position"] = position + + if print_job_user is not None: + result["owner"] = print_job_user + + if action_user is not None: + result["user"] = action_user + + return result class StateMonitor(object): - def __init__(self, interval=0.5, on_update=None, on_add_temperature=None, on_add_log=None, on_add_message=None, on_get_progress=None): - self._interval = interval - self._update_callback = on_update - self._on_add_temperature = on_add_temperature - self._on_add_log = on_add_log - self._on_add_message = on_add_message - self._on_get_progress = on_get_progress + def __init__( + self, + interval=0.5, + on_update=None, + on_add_temperature=None, + on_add_log=None, + on_add_message=None, + on_get_progress=None, + ): + self._interval = interval + self._update_callback = on_update + self._on_add_temperature = on_add_temperature + self._on_add_log = on_add_log + self._on_add_message = on_add_message + self._on_get_progress = on_get_progress - self._state = None - self._job_data = None - self._current_z = None - self._offsets = {} - self._progress = None + self._state = None + self._job_data = None + self._current_z = None + self._offsets = {} + self._progress = None - self._progress_dirty = False + self._progress_dirty = False - self._change_event = threading.Event() - self._state_lock = threading.Lock() - self._progress_lock = threading.Lock() + self._change_event = threading.Event() + self._state_lock = threading.Lock() + self._progress_lock = threading.Lock() - self._last_update = monotonic_time() - self._worker = threading.Thread(target=self._work) - self._worker.daemon = True - self._worker.start() + self._last_update = monotonic_time() + self._worker = threading.Thread(target=self._work) + self._worker.daemon = True + self._worker.start() - def _get_current_progress(self): - if callable(self._on_get_progress): - return self._on_get_progress() - return self._progress + def _get_current_progress(self): + if callable(self._on_get_progress): + return self._on_get_progress() + return self._progress - def reset(self, state=None, job_data=None, progress=None, current_z=None, offsets=None): - self.set_state(state) - self.set_job_data(job_data) - self.set_progress(progress) - self.set_current_z(current_z) - self.set_temp_offsets(offsets) + def reset( + self, state=None, job_data=None, progress=None, current_z=None, offsets=None + ): + self.set_state(state) + self.set_job_data(job_data) + self.set_progress(progress) + self.set_current_z(current_z) + self.set_temp_offsets(offsets) - def add_temperature(self, temperature): - self._on_add_temperature(temperature) - self._change_event.set() + def add_temperature(self, temperature): + self._on_add_temperature(temperature) + self._change_event.set() - def add_log(self, log): - self._on_add_log(log) - self._change_event.set() + def add_log(self, log): + self._on_add_log(log) + self._change_event.set() - def add_message(self, message): - self._on_add_message(message) - self._change_event.set() + def add_message(self, message): + self._on_add_message(message) + self._change_event.set() - def set_current_z(self, current_z): - self._current_z = current_z - self._change_event.set() + def set_current_z(self, current_z): + self._current_z = current_z + self._change_event.set() - def set_state(self, state): - with self._state_lock: - self._state = state - self._change_event.set() + def set_state(self, state): + with self._state_lock: + self._state = state + self._change_event.set() - def set_job_data(self, job_data): - self._job_data = job_data - self._change_event.set() + def set_job_data(self, job_data): + self._job_data = job_data + self._change_event.set() - def trigger_progress_update(self): - with self._progress_lock: - self._progress_dirty = True - self._change_event.set() + def trigger_progress_update(self): + with self._progress_lock: + self._progress_dirty = True + self._change_event.set() - def set_progress(self, progress): - with self._progress_lock: - self._progress_dirty = False - self._progress = progress - self._change_event.set() + def set_progress(self, progress): + with self._progress_lock: + self._progress_dirty = False + self._progress = progress + self._change_event.set() - def set_temp_offsets(self, offsets): - if offsets is None: - offsets = {} - self._offsets = offsets - self._change_event.set() + def set_temp_offsets(self, offsets): + if offsets is None: + offsets = {} + self._offsets = offsets + self._change_event.set() - def _work(self): - try: - while True: - self._change_event.wait() + def _work(self): + try: + while True: + self._change_event.wait() - now = monotonic_time() - delta = now - self._last_update - additional_wait_time = self._interval - delta - if additional_wait_time > 0: - time.sleep(additional_wait_time) + now = monotonic_time() + delta = now - self._last_update + additional_wait_time = self._interval - delta + if additional_wait_time > 0: + time.sleep(additional_wait_time) - with self._state_lock: - data = self.get_current_data() - self._update_callback(data) - self._last_update = monotonic_time() - self._change_event.clear() - except Exception: - logging.getLogger(__name__).exception("Looks like something crashed inside the state update worker. " - "Please report this on the OctoPrint issue tracker (make sure " - "to include logs!)") + with self._state_lock: + data = self.get_current_data() + self._update_callback(data) + self._last_update = monotonic_time() + self._change_event.clear() + except Exception: + logging.getLogger(__name__).exception( + "Looks like something crashed inside the state update worker. " + "Please report this on the OctoPrint issue tracker (make sure " + "to include logs!)" + ) - def get_current_data(self): - with self._progress_lock: - if self._progress_dirty: - self._progress = self._get_current_progress() - self._progress_dirty = False + def get_current_data(self): + with self._progress_lock: + if self._progress_dirty: + self._progress = self._get_current_progress() + self._progress_dirty = False - return { - "state": self._state, - "job": self._job_data, - "currentZ": self._current_z, - "progress": self._progress, - "offsets": self._offsets - } + return { + "state": self._state, + "job": self._job_data, + "currentZ": self._current_z, + "progress": self._progress, + "offsets": self._offsets, + } class TemperatureHistory(InvariantContainer): - def __init__(self, cutoff=30 * 60): + def __init__(self, cutoff=30 * 60): + def temperature_invariant(data): + data.sort(key=lambda x: x["time"]) + now = int(time.time()) + return [item for item in data if item["time"] >= now - cutoff] - def temperature_invariant(data): - data.sort(key=lambda x: x["time"]) - now = int(time.time()) - return [item for item in data if item["time"] >= now - cutoff] - - InvariantContainer.__init__(self, guarantee_invariant=temperature_invariant) + InvariantContainer.__init__(self, guarantee_invariant=temperature_invariant) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 28d50cf64..5c2c41013 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -2,14 +2,33 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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 uuid from octoprint.vendor.sockjs.tornado import SockJSRouter -from flask import Flask, g, request, session, Blueprint, Request, Response, current_app, make_response +from flask import ( + Flask, + g, + request, + session, + Blueprint, + Request, + Response, + current_app, + make_response, +) from flask_login import LoginManager, current_user, session_protected, user_logged_out -from octoprint.vendor.flask_principal import Principal, Permission, RoleNeed, identity_loaded, identity_changed, UserNeed, Identity, AnonymousIdentity +from octoprint.vendor.flask_principal import ( + Principal, + Permission, + RoleNeed, + identity_loaded, + identity_changed, + UserNeed, + Identity, + AnonymousIdentity, +) from flask_babel import Babel, gettext, ngettext from flask_assets import Environment, Bundle from babel import Locale @@ -38,9 +57,9 @@ import base64 import re try: - import fcntl + import fcntl except ImportError: - fcntl = None + fcntl = None SUCCESS = {} NO_CONTENT = ("", 204) @@ -76,14 +95,16 @@ import octoprint.access.permissions as permissions import octoprint.access.groups as groups # we set admin_permission to a GroupPermission with the default admin group -admin_permission = octoprint.util.variable_deprecated("admin_permission has been deprecated, " - "please use individual Permissions instead", - since="1.4.0")(groups.GroupPermission(groups.ADMIN_GROUP)) +admin_permission = octoprint.util.variable_deprecated( + "admin_permission has been deprecated, " "please use individual Permissions instead", + since="1.4.0", +)(groups.GroupPermission(groups.ADMIN_GROUP)) # we set user_permission to a GroupPermission with the default user group -user_permission = octoprint.util.variable_deprecated("user_permission has been deprecated, " - "please use individual Permissions instead", - since="1.4.0")(groups.GroupPermission(groups.USER_GROUP)) +user_permission = octoprint.util.variable_deprecated( + "user_permission has been deprecated, " "please use individual Permissions instead", + since="1.4.0", +)(groups.GroupPermission(groups.USER_GROUP)) # only import further octoprint stuff down here, as it might depend on things defined above to be initialized already from octoprint import __version__, __branch__, __display_version__, __revision__ @@ -99,8 +120,12 @@ import octoprint._version import octoprint.filemanager.storage import octoprint.filemanager.analysis import octoprint.slicing -from octoprint.server.util import loginFromApiKeyRequestHandler, corsRequestHandler, \ - corsResponseHandler, requireLoginRequestHandler +from octoprint.server.util import ( + loginFromApiKeyRequestHandler, + corsRequestHandler, + corsResponseHandler, + requireLoginRequestHandler, +) from octoprint.server.util.flask import PreemptiveCache VERSION = __version__ @@ -111,1969 +136,2579 @@ REVISION = __revision__ LOCALES = [] LANGUAGES = set() + @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): - user = load_user(identity.id) - if user is None: - user = userManager.anonymous_user_factory() + user = load_user(identity.id) + if user is None: + user = userManager.anonymous_user_factory() - identity.provides.add(UserNeed(user.get_id())) - for need in user.needs: - identity.provides.add(need) + identity.provides.add(UserNeed(user.get_id())) + for need in user.needs: + identity.provides.add(need) def _clear_identity(sender): - # Remove session keys set by Flask-Principal - for key in ('identity.id', 'identity.name', 'identity.auth_type'): - session.pop(key, None) + # Remove session keys set by Flask-Principal + for key in ("identity.id", "identity.name", "identity.auth_type"): + session.pop(key, None) - # switch to anonymous identity - identity_changed.send(sender, identity=AnonymousIdentity()) + # switch to anonymous identity + identity_changed.send(sender, identity=AnonymousIdentity()) @session_protected.connect_via(app) def on_session_protected(sender): - # session was deleted by session protection, that means the user is no more and we need to clear our identity - if session.get("remember", None) == "clear": - _clear_identity(sender) + # session was deleted by session protection, that means the user is no more and we need to clear our identity + if session.get("remember", None) == "clear": + _clear_identity(sender) @user_logged_out.connect_via(app) def on_user_logged_out(sender, user=None): - # user was logged out, clear identity - _clear_identity(sender) + # user was logged out, clear identity + _clear_identity(sender) + def load_user(id): - if id is None or not userManager.enabled: - return None + if id is None or not userManager.enabled: + return None - if id == "_api": - return userManager.api_user_factory() + if id == "_api": + return userManager.api_user_factory() - if session and "usersession.id" in session: - sessionid = session["usersession.id"] - else: - sessionid = None + if session and "usersession.id" in session: + sessionid = session["usersession.id"] + else: + sessionid = None - if sessionid: - user = userManager.find_user(userid=id, session=sessionid) - else: - user = userManager.find_user(userid=id) + if sessionid: + user = userManager.find_user(userid=id, session=sessionid) + else: + user = userManager.find_user(userid=id) - if user and user.is_active: - return user + if user and user.is_active: + return user + + return None - return None def load_user_from_request(request): - user = None + user = None - if settings().getBoolean(["accessControl", "trustBasicAuthentication"]): - # Basic Authentication? - user = util.get_user_for_authorization_header(request.headers.get('Authorization')) + if settings().getBoolean(["accessControl", "trustBasicAuthentication"]): + # Basic Authentication? + user = util.get_user_for_authorization_header( + request.headers.get("Authorization") + ) - if settings().getBoolean(["accessControl", "trustRemoteUser"]): - # Remote user header? - user = util.get_user_for_remote_user_header(request) + if settings().getBoolean(["accessControl", "trustRemoteUser"]): + # Remote user header? + user = util.get_user_for_remote_user_header(request) + + return user - return user def unauthorized_user(): - from flask import abort - abort(403) + from flask import abort + + abort(403) -#~~ startup code +# ~~ startup code class Server(object): - def __init__(self, settings=None, plugin_manager=None, connectivity_checker=None, environment_detector=None, - event_manager=None, host=None, port=None, v6_only=False, debug=False, safe_mode=False, allow_root=False, - octoprint_daemon=None): - self._settings = settings - self._plugin_manager = plugin_manager - self._connectivity_checker = connectivity_checker - self._environment_detector = environment_detector - self._event_manager = event_manager - self._host = host - self._port = port - self._v6_only = v6_only - self._debug = debug - self._safe_mode = safe_mode - self._allow_root = allow_root - self._octoprint_daemon = octoprint_daemon - self._server = None - - self._logger = None - - self._lifecycle_callbacks = defaultdict(list) - - self._template_searchpaths = [] - - self._intermediary_server = None - - def run(self): - if not self._allow_root: - self._check_for_root() - - if self._settings is None: - self._settings = settings() - - if not self._settings.getBoolean(["server", "ignoreIncompleteStartup"]): - self._settings.setBoolean(["server", "incompleteStartup"], True) - self._settings.save() - - if self._plugin_manager is None: - self._plugin_manager = octoprint.plugin.plugin_manager() - - global app - global babel - - global printer - global printerProfileManager - global fileManager - global slicingManager - global analysisQueue - global userManager - global permissionManager - global groupManager - global eventManager - global loginManager - global pluginManager - global pluginLifecycleManager - global preemptiveCache - global jsonEncoder - global jsonDecoder - global connectivityChecker - global debug - global safe_mode - - from tornado.ioloop import IOLoop - from tornado.web import Application - - debug = self._debug - safe_mode = self._safe_mode - - if self._v6_only and not octoprint.util.net.HAS_V6: - raise RuntimeError("IPv6 only mode configured but system doesn't support IPv6") - - if self._host is None: - host = self._settings.get(["server", "host"]) - if host is None: - if octoprint.util.net.HAS_V6: - host = "::" - else: - host = "0.0.0.0" - - self._host = host - - if ":" in self._host and not octoprint.util.net.HAS_V6: - raise RuntimeError("IPv6 host address {!r} configured but system doesn't support IPv6".format(self._host)) - - if self._port is None: - self._port = self._settings.getInt(["server", "port"]) - if self._port is None: - self._port = 5000 - - self._logger = logging.getLogger(__name__) - self._setup_heartbeat_logging() - pluginManager = self._plugin_manager - - # monkey patch/fix some stuff - util.tornado.fix_json_encode() - util.tornado.fix_websocket_check_origin() - util.flask.fix_flask_jsonify() - util.watchdog.fix_scandir() - - self._setup_mimetypes() - - additional_translation_folders = [] - if not safe_mode: - additional_translation_folders += [self._settings.getBaseFolder("translations")] - util.flask.enable_additional_translations(additional_folders=additional_translation_folders) - - # setup app - self._setup_app(app) - - # setup i18n - self._setup_i18n(app) - - if self._settings.getBoolean(["serial", "log"]): - # enable debug logging to serial.log - logging.getLogger("SERIAL").setLevel(logging.DEBUG) - - if self._settings.getBoolean(["devel", "pluginTimings"]): - # enable plugin timings log - logging.getLogger("PLUGIN_TIMINGS").setLevel(logging.DEBUG) - - # start the intermediary server - self._start_intermediary_server() - - ### IMPORTANT! - ### - ### Best do not start any subprocesses until the intermediary server shuts down again or they MIGHT inherit the - ### open port and prevent us from firing up Tornado later. - ### - ### The intermediary server's socket should have the CLOSE_EXEC flag (or its equivalent) set where possible, but - ### we can only do that if fcntl is available or we are on Windows, so better safe than sorry. - ### - ### See also issues #2035 and #2090 - - # then initialize the plugin manager - pluginManager.reload_plugins(startup=True, initialize_implementations=False) - - printerProfileManager = PrinterProfileManager() - eventManager = self._event_manager - - analysis_queue_factories = {"gcode": octoprint.filemanager.analysis.GcodeAnalysisQueue} - analysis_queue_hooks = pluginManager.get_hooks("octoprint.filemanager.analysis.factory") - for name, hook in analysis_queue_hooks.items(): - try: - additional_factories = hook() - analysis_queue_factories.update(**additional_factories) - except Exception: - self._logger.exception("Error while processing analysis queues from {}".format(name), - extra={"plugin": name}) - analysisQueue = octoprint.filemanager.analysis.AnalysisQueue(analysis_queue_factories) - - slicingManager = octoprint.slicing.SlicingManager(self._settings.getBaseFolder("slicingProfiles"), printerProfileManager) - - storage_managers = {} - storage_managers[octoprint.filemanager.FileDestinations.LOCAL] = octoprint.filemanager.storage.LocalFileStorage(self._settings.getBaseFolder("uploads")) - - fileManager = octoprint.filemanager.FileManager(analysisQueue, slicingManager, printerProfileManager, initial_storage_managers=storage_managers) - pluginLifecycleManager = LifecycleManager(pluginManager) - preemptiveCache = PreemptiveCache(os.path.join(self._settings.getBaseFolder("data"), "preemptive_cache_config.yaml")) - - JsonEncoding.add_encoder(users.User, lambda obj: obj.as_dict()) - JsonEncoding.add_encoder(groups.Group, lambda obj: obj.as_dict()) - JsonEncoding.add_encoder(permissions.OctoPrintPermission, lambda obj: obj.as_dict()) - - # start regular check if we are connected to the internet - def on_connectivity_change(old_value, new_value): - eventManager.fire(events.Events.CONNECTIVITY_CHANGED, payload={"old": old_value, "new": new_value}) - - connectivityChecker = self._connectivity_checker - - def on_settings_update(*args, **kwargs): - # make sure our connectivity checker runs with the latest settings - connectivityEnabled = self._settings.getBoolean(["server", "onlineCheck", "enabled"]) - connectivityInterval = self._settings.getInt(["server", "onlineCheck", "interval"]) - connectivityHost = self._settings.get(["server", "onlineCheck", "host"]) - connectivityPort = self._settings.getInt(["server", "onlineCheck", "port"]) - connectivityName = self._settings.get(["server", "onlineCheck", "name"]) - - if connectivityChecker.enabled != connectivityEnabled \ - or connectivityChecker.interval != connectivityInterval \ - or connectivityChecker.host != connectivityHost \ - or connectivityChecker.port != connectivityPort \ - or connectivityChecker.name != connectivityName: - connectivityChecker.enabled = connectivityEnabled - connectivityChecker.interval = connectivityInterval - connectivityChecker.host = connectivityHost - connectivityChecker.port = connectivityPort - connectivityChecker.name = connectivityName - connectivityChecker.check_immediately() - - eventManager.subscribe(events.Events.SETTINGS_UPDATED, on_settings_update) - - components = {"plugin_manager": pluginManager, - "printer_profile_manager": printerProfileManager, - "event_bus": eventManager, - "analysis_queue": analysisQueue, - "slicing_manager": slicingManager, - "file_manager": fileManager, - "plugin_lifecycle_manager": pluginLifecycleManager, - "preemptive_cache": preemptiveCache, - "json_encoder": jsonEncoder, - "json_decoder": jsonDecoder, - "connectivity_checker": connectivityChecker, - "environment_detector": self._environment_detector} - - #~~ setup access control - - # get additional permissions from plugins - self._setup_plugin_permissions() - - # create group manager instance - group_manager_factories = pluginManager.get_hooks("octoprint.access.groups.factory") - for name, factory in group_manager_factories.items(): - try: - groupManager = factory(components, self._settings) - if groupManager is not None: - self._logger.debug("Created group manager instance from factory {}".format(name)) - break - except Exception: - self._logger.exception("Error while creating group manager instance from factory {}".format(name)) - else: - group_manager_name = self._settings.get(["accessControl", "groupManager"]) - try: - clazz = octoprint.util.get_class(group_manager_name) - groupManager = clazz() - except AttributeError: - self._logger.exception("Could not instantiate group manager {}, " - "falling back to FilebasedGroupManager!".format(group_manager_name)) - groupManager = octoprint.access.groups.FilebasedGroupManager() - components.update({"group_manager": groupManager}) - - # create user manager instance - user_manager_factories = pluginManager.get_hooks("octoprint.users.factory") # legacy, set first so that new wins - user_manager_factories.update(pluginManager.get_hooks("octoprint.access.users.factory")) - for name, factory in user_manager_factories.items(): - try: - userManager = factory(components, self._settings) - if userManager is not None: - self._logger.debug("Created user manager instance from factory {}".format(name)) - break - except Exception: - self._logger.exception("Error while creating user manager instance from factory {}".format(name), - extra={"plugin": name}) - else: - user_manager_name = self._settings.get(["accessControl", "userManager"]) - try: - clazz = octoprint.util.get_class(user_manager_name) - userManager = clazz(groupManager) - except Exception: - self._logger.exception("Could not instantiate user manager {}, " - "falling back to FilebasedUserManager!".format(user_manager_name)) - userManager = octoprint.access.users.FilebasedUserManager(groupManager) - finally: - userManager.enabled = self._settings.getBoolean(["accessControl", "enabled"]) - components.update({"user_manager": userManager}) - - # create printer instance - printer_factories = pluginManager.get_hooks("octoprint.printer.factory") - for name, factory in printer_factories.items(): - try: - printer = factory(components) - if printer is not None: - self._logger.debug("Created printer instance from factory {}".format(name)) - break - except Exception: - self._logger.exception("Error while creating printer instance from factory {}".format(name), - extra={"plugin": name}) - else: - printer = Printer(fileManager, analysisQueue, printerProfileManager) - components.update({"printer": printer}) - - def octoprint_plugin_inject_factory(name, implementation): - """Factory for injections for all OctoPrintPlugins""" - if not isinstance(implementation, octoprint.plugin.OctoPrintPlugin): - return None - - components_copy = dict(components) - if "printer" in components: - import wrapt - import functools - - def tagwrap(f): - @functools.wraps(f) - def wrapper(*args, **kwargs): - tags = kwargs.get("tags", set()) | {"source:plugin", - "plugin:{}".format(name)} - kwargs["tags"] = tags - return f(*args, **kwargs) - setattr(wrapper, "__tagwrapped__", True) - return wrapper - - class TaggedFuncsPrinter(wrapt.ObjectProxy): - def __getattribute__(self, attr): - __wrapped__ = super(TaggedFuncsPrinter, self).__getattribute__("__wrapped__") - if attr == "__wrapped__": - return __wrapped__ - - item = getattr(__wrapped__, attr) - if callable(item) \ - and ("tags" in item.__code__.co_varnames or "kwargs" in item.__code__.co_varnames) \ - and not getattr(item, "__tagwrapped__", False): - return tagwrap(item) - else: - return item - - components_copy["printer"] = TaggedFuncsPrinter(components["printer"]) - - props = {} - props.update(components_copy) - props.update({"data_folder": os.path.join(self._settings.getBaseFolder("data"), name)}) - return props - - def settings_plugin_inject_factory(name, implementation): - """Factory for additional injections/initializations depending on plugin type""" - if not isinstance(implementation, octoprint.plugin.SettingsPlugin): - return - - default_settings_overlay = {"plugins": {}} - default_settings_overlay["plugins"][name] = implementation.get_settings_defaults() - self._settings.add_overlay(default_settings_overlay, at_end=True) - - plugin_settings = octoprint.plugin.plugin_settings_for_settings_plugin(name, implementation) - if plugin_settings is None: - return - - return {"settings": plugin_settings} - - def settings_plugin_config_migration_and_cleanup(identifier, implementation): - """Take care of migrating and cleaning up any old settings""" - - if not isinstance(implementation, octoprint.plugin.SettingsPlugin): - return - - settings_version = implementation.get_settings_version() - settings_migrator = implementation.on_settings_migrate - - if settings_version is not None and settings_migrator is not None: - stored_version = implementation._settings.get_int([octoprint.plugin.SettingsPlugin.config_version_key]) - if stored_version is None or stored_version < settings_version: - settings_migrator(settings_version, stored_version) - implementation._settings.set_int([octoprint.plugin.SettingsPlugin.config_version_key], settings_version, force=True) - - implementation.on_settings_cleanup() - implementation._settings.save() - - implementation.on_settings_initialized() - - custom_events_hooks = pluginManager.get_hooks("octoprint.events.register_custom_events") - for name, hook in custom_events_hooks.items(): - try: - result = hook() - if isinstance(result, (list, tuple)): - for event in result: - constant, value = octoprint.events.Events.register_event(event, prefix="plugin_{}_".format(name)) - self._logger.debug("Registered event {} of plugin {} as Events.{} = \"{}\"".format(event, name, constant, value)) - except Exception: - self._logger.exception("Error while retrieving custom event list from plugin {}".format(name), - extra={"plugin": name}) - - pluginManager.implementation_inject_factories=[octoprint_plugin_inject_factory, - settings_plugin_inject_factory] - pluginManager.initialize_implementations() - - settingsPlugins = pluginManager.get_implementations(octoprint.plugin.SettingsPlugin) - for implementation in settingsPlugins: - try: - settings_plugin_config_migration_and_cleanup(implementation._identifier, implementation) - except Exception: - self._logger.exception("Error while trying to migrate settings for " - "plugin {}, ignoring it".format(implementation._identifier), - extra={"plugin": implementation._identifier}) - - pluginManager.implementation_post_inits=[settings_plugin_config_migration_and_cleanup] - - pluginManager.log_all_plugins() - - # log environment data now - self._environment_detector.log_detected_environment() - - # initialize file manager and register it for changes in the registered plugins - fileManager.initialize() - pluginLifecycleManager.add_callback(["enabled", "disabled"], lambda name, plugin: fileManager.reload_plugins()) - - # initialize slicing manager and register it for changes in the registered plugins - slicingManager.initialize() - pluginLifecycleManager.add_callback(["enabled", "disabled"], lambda name, plugin: slicingManager.reload_slicers()) - - # setup jinja2 - self._setup_jinja2() - - # setup assets - self._setup_assets() - - # configure timelapse - octoprint.timelapse.valid_timelapse("test") - octoprint.timelapse.configure_timelapse() - - # setup command triggers - events.CommandTrigger(printer) - if self._debug: - events.DebugEventListener() - - # setup login manager - self._setup_login_manager() - - # register API blueprint - self._setup_blueprints() - - ## Tornado initialization starts here - - ioloop = IOLoop() - ioloop.install() - - enable_cors = settings().getBoolean(["api", "allowCrossOrigin"]) - - self._router = SockJSRouter(self._create_socket_connection, "/sockjs", - session_kls=util.sockjs.ThreadSafeSession, - user_settings={"websocket_allow_origin": "*" if enable_cors else "", - "jsessionid": False, - "sockjs_url": "../../static/js/lib/sockjs.min.js"}) - - upload_suffixes = {"name": self._settings.get(["server", "uploads", "nameSuffix"]), "path": self._settings.get(["server", "uploads", "pathSuffix"])} - - def mime_type_guesser(path): - from octoprint.filemanager import get_mime_type - return get_mime_type(path) - - def download_name_generator(path): - metadata = fileManager.get_metadata("local", path) - if metadata and "display" in metadata: - return metadata["display"] - - download_handler_kwargs = {"as_attachment": True, - "allow_client_caching": False} - - additional_mime_types={"mime_type_guesser": mime_type_guesser} - - ##~~ Permission validators - - access_validators_from_plugins = [] - for plugin, hook in pluginManager.get_hooks("octoprint.server.http.access_validator").items(): - try: - access_validators_from_plugins.append(util.tornado.access_validation_factory(app, hook)) - except Exception: - self._logger.exception("Error while adding tornado access validator from plugin {}".format(plugin), - extra={"plugin": plugin}) - access_validator = {"access_validation": util.tornado.validation_chain(*access_validators_from_plugins)} - - timelapse_validators = [util.tornado.access_validation_factory(app, util.flask.permission_validator, permissions.Permissions.TIMELAPSE_LIST),] + access_validators_from_plugins - download_validators = [util.tornado.access_validation_factory(app, util.flask.permission_validator, permissions.Permissions.FILES_DOWNLOAD),] + access_validators_from_plugins - log_validators = [util.tornado.access_validation_factory(app, util.flask.permission_validator, permissions.Permissions.PLUGIN_LOGGING_MANAGE),] + access_validators_from_plugins - camera_validators = [util.tornado.access_validation_factory(app, util.flask.permission_validator, permissions.Permissions.WEBCAM),] + access_validators_from_plugins - - timelapse_permission_validator = {"access_validation": util.tornado.validation_chain(*timelapse_validators)} - download_permission_validator = {"access_validation": util.tornado.validation_chain(*download_validators)} - log_permission_validator = {"access_validation": util.tornado.validation_chain(*log_validators)} - camera_permission_validator = {"access_validation": util.tornado.validation_chain(*camera_validators)} - - no_hidden_files_validator = {"path_validation": util.tornado.path_validation_factory(lambda path: not octoprint.util.is_hidden_path(path), - status_code=404)} - timelapse_path_validator = {"path_validation": util.tornado.path_validation_factory(lambda path: not octoprint.util.is_hidden_path(path) and octoprint.timelapse.valid_timelapse(path), - status_code=404)} - - def joined_dict(*dicts): - if not len(dicts): - return {} - - joined = {} - for d in dicts: - joined.update(d) - return joined - - util.tornado.RequestlessExceptionLoggingMixin.LOG_REQUEST = debug - util.tornado.CorsSupportMixin.ENABLE_CORS = enable_cors - - server_routes = self._router.urls + [ - # various downloads - # .mpg and .mp4 timelapses: - (r"/downloads/timelapse/(.*)", util.tornado.LargeResponseHandler, joined_dict({"path": self._settings.getBaseFolder("timelapse")}, - timelapse_permission_validator, - download_handler_kwargs, - timelapse_path_validator)), - (r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, joined_dict({"path": self._settings.getBaseFolder("uploads"), - "as_attachment": True, - "name_generator": download_name_generator}, - download_permission_validator, - download_handler_kwargs, - no_hidden_files_validator, - additional_mime_types)), - (r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, joined_dict({"path": self._settings.getBaseFolder("logs"), - "mime_type_guesser": lambda *args, **kwargs: "text/plain", - "stream_body": True}, - download_handler_kwargs, - log_permission_validator)), - # camera snapshot - (r"/downloads/camera/current", util.tornado.UrlProxyHandler, joined_dict({"url": self._settings.get(["webcam", "snapshot"]), - "as_attachment": True}, - camera_permission_validator)), - # generated webassets - (r"/static/webassets/(.*)", util.tornado.LargeResponseHandler, {"path": os.path.join(self._settings.getBaseFolder("generated"), "webassets"), - "is_pre_compressed": True}), - - # online indicators - text file with "online" as content and a transparent gif - (r"/online.txt", util.tornado.StaticDataHandler, {"data": "online\n"}), - (r"/online.gif", util.tornado.StaticDataHandler, {"data": bytes(base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")), - "content_type": "image/gif"}), - - # deprecated endpoints - (r"/api/logs", util.tornado.DeprecatedEndpointHandler, {"url": "/plugin/logging/logs"}), - (r"/api/logs/(.*)", util.tornado.DeprecatedEndpointHandler, {"url": "/plugin/logging/logs/{0}"}), - ] - - # fetch additional routes from plugins - for name, hook in pluginManager.get_hooks("octoprint.server.http.routes").items(): - try: - result = hook(list(server_routes)) - except Exception: - self._logger.exception("There was an error while retrieving additional " - "server routes from plugin hook {name}".format(**locals()), - extra={"plugin": name}) - else: - if isinstance(result, (list, tuple)): - for entry in result: - if not isinstance(entry, tuple) or not len(entry) == 3: - continue - if not isinstance(entry[0], basestring): - continue - if not isinstance(entry[2], dict): - continue - - route, handler, kwargs = entry - route = r"/plugin/{name}/{route}".format(name=name, route=route if not route.startswith("/") else route[1:]) - - self._logger.debug("Adding additional route {route} handled by handler {handler} and with additional arguments {kwargs!r}".format(**locals())) - server_routes.append((route, handler, kwargs)) - - headers = {"X-Robots-Tag": "noindex, nofollow, noimageindex", - "X-Content-Type-Options": "nosniff"} - if not settings().getBoolean(["server", "allowFraming"]): - headers["X-Frame-Options"] = "sameorigin" - - removed_headers = ["Server"] - - server_routes.append((r".*", util.tornado.UploadStorageFallbackHandler, {"fallback": util.tornado.WsgiInputContainer(app.wsgi_app, - headers=headers, - removed_headers=removed_headers), - "file_prefix": "octoprint-file-upload-", - "file_suffix": ".tmp", - "suffixes": upload_suffixes})) - - transforms = [util.tornado.GlobalHeaderTransform.for_headers("OctoPrintGlobalHeaderTransform", - headers=headers, - removed_headers=removed_headers)] - - self._tornado_app = Application(handlers=server_routes, - transforms=transforms) - max_body_sizes = [ - ("POST", r"/api/files/([^/]*)", self._settings.getInt(["server", "uploads", "maxSize"])), - ("POST", r"/api/languages", 5 * 1024 * 1024) - ] - - # allow plugins to extend allowed maximum body sizes - for name, hook in pluginManager.get_hooks("octoprint.server.http.bodysize").items(): - try: - result = hook(list(max_body_sizes)) - except Exception: - self._logger.exception("There was an error while retrieving additional " - "upload sizes from plugin hook {name}".format(**locals()), - extra={"plugin": name}) - else: - if isinstance(result, (list, tuple)): - for entry in result: - if not isinstance(entry, tuple) or not len(entry) == 3: - continue - if not entry[0] in util.tornado.UploadStorageFallbackHandler.BODY_METHODS: - continue - if not isinstance(entry[2], int): - continue - - method, route, size = entry - route = r"/plugin/{name}/{route}".format(name=name, route=route if not route.startswith("/") else route[1:]) - - self._logger.debug("Adding maximum body size of {size}B for {method} requests to {route})".format(**locals())) - max_body_sizes.append((method, route, size)) - - self._stop_intermediary_server() - - # initialize and bind the server - trusted_downstream = self._settings.get(["server", "reverseProxy", "trustedDownstream"]) - if not isinstance(trusted_downstream, list): - self._logger.warning("server.reverseProxy.trustedDownstream is not a list, skipping") - trusted_downstreams = [] - - server_kwargs = {"max_body_sizes": max_body_sizes, - "default_max_body_size": self._settings.getInt(["server", "maxSize"]), - "xheaders": True, - "trusted_downstream": trusted_downstream} - if sys.platform == "win32": - # set 10min idle timeout under windows to hopefully make #2916 less likely - server_kwargs.update({"idle_connection_timeout": 600}) - - self._server = util.tornado.CustomHTTPServer(self._tornado_app, **server_kwargs) - - listening_address = self._host - if self._host == "::" and not self._v6_only: - # special case - tornado only listens on v4 _and_ v6 if we use None as address - listening_address = None - - self._server.listen(self._port, address=listening_address) - - ### From now on it's ok to launch subprocesses again - - eventManager.fire(events.Events.STARTUP) - - # analysis backlog - fileManager.process_backlog() - - # auto connect - if self._settings.getBoolean(["serial", "autoconnect"]): - self._logger.info("Autoconnect on startup is configured, trying to connect to the printer...") - try: - (port, baudrate) = self._settings.get(["serial", "port"]), self._settings.getInt(["serial", "baudrate"]) - printer_profile = printerProfileManager.get_default() - connectionOptions = printer.__class__.get_connection_options() - if port in connectionOptions["ports"] or port == "AUTO" or port is None: - self._logger.info("Trying to connect to configured serial port {}".format(port)) - printer.connect(port=port, baudrate=baudrate, profile=printer_profile["id"] if "id" in printer_profile else "_default") - else: - self._logger.info("Could not find configured serial port {} in the system, cannot automatically connect to a non existing printer. Is it plugged in and booted up yet?") - except Exception: - self._logger.exception("Something went wrong while attempting to automatically connect to the printer") - - # start up watchdogs - try: - watched = self._settings.getBaseFolder("watched") - watchdog_handler = util.watchdog.GcodeWatchdogHandler(fileManager, printer) - watchdog_handler.initial_scan(watched) - - if self._settings.getBoolean(["feature", "pollWatched"]): - # use less performant polling observer if explicitly configured - observer = PollingObserver() - else: - # use os default - observer = Observer() - - observer.schedule(watchdog_handler, watched, recursive=True) - observer.start() - except Exception: - self._logger.exception("Error starting watched folder observer") - - # run our startup plugins - octoprint.plugin.call_plugin(octoprint.plugin.StartupPlugin, - "on_startup", - args=(self._host, self._port), - sorting_context="StartupPlugin.on_startup") - - def call_on_startup(name, plugin): - implementation = plugin.get_implementation(octoprint.plugin.StartupPlugin) - if implementation is None: - return - implementation.on_startup(self._host, self._port) - pluginLifecycleManager.add_callback("enabled", call_on_startup) - - # prepare our after startup function - def on_after_startup(): - if self._host == "::": - if self._v6_only: - # only v6 - self._logger.info("Listening on http://[::]:{port}".format(port=self._port)) - else: - # all v4 and v6 - self._logger.info("Listening on http://0.0.0.0:{port} and http://[::]:{port}".format(port=self._port)) - else: - self._logger.info("Listening on http://{}:{}".format(self._host if not ":" in self._host else "[" + self._host + "]", - self._port)) - - if safe_mode and self._settings.getBoolean(["server", "startOnceInSafeMode"]): - self._logger.info("Server started successfully in safe mode as requested from config, removing flag") - self._settings.setBoolean(["server", "startOnceInSafeMode"], False) - self._settings.save() - - # now this is somewhat ugly, but the issue is the following: startup plugins might want to do things for - # which they need the server to be already alive (e.g. for being able to resolve urls, such as favicons - # or service xmls or the like). While they are working though the ioloop would block. Therefore we'll - # create a single use thread in which to perform our after-startup-tasks, start that and hand back - # control to the ioloop - def work(): - octoprint.plugin.call_plugin(octoprint.plugin.StartupPlugin, - "on_after_startup", - sorting_context="StartupPlugin.on_after_startup") - - def call_on_after_startup(name, plugin): - implementation = plugin.get_implementation(octoprint.plugin.StartupPlugin) - if implementation is None: - return - implementation.on_after_startup() - pluginLifecycleManager.add_callback("enabled", call_on_after_startup) - - # if there was a rogue plugin we wouldn't even have made it here, so remove startup triggered safe mode - # flag again... - self._settings.setBoolean(["server", "incompleteStartup"], False) - self._settings.save() - - # make a backup of the current config - self._settings.backup(ext="backup") - - # when we are through with that we also run our preemptive cache - if settings().getBoolean(["devel", "cache", "preemptive"]): - self._execute_preemptive_flask_caching(preemptiveCache) - - import threading - threading.Thread(target=work).start() - ioloop.add_callback(on_after_startup) - - # prepare our shutdown function - def on_shutdown(): - # will be called on clean system exit and shutdown the watchdog observer and call the on_shutdown methods - # on all registered ShutdownPlugins - self._logger.info("Shutting down...") - observer.stop() - observer.join() - eventManager.fire(events.Events.SHUTDOWN) - - self._logger.info("Calling on_shutdown on plugins") - octoprint.plugin.call_plugin(octoprint.plugin.ShutdownPlugin, - "on_shutdown", - sorting_context="ShutdownPlugin.on_shutdown") - - # wait for shutdown event to be processed, but maximally for 15s - event_timeout = 15.0 - if eventManager.join(timeout=event_timeout): - self._logger.warning("Event loop was still busy processing after {}s, shutting down anyhow".format(event_timeout)) - - if self._octoprint_daemon is not None: - self._logger.info("Cleaning up daemon pidfile") - self._octoprint_daemon.terminated() - - self._logger.info("Goodbye!") - atexit.register(on_shutdown) - - def sigterm_handler(*args, **kwargs): - # will stop tornado on SIGTERM, making the program exit cleanly - def shutdown_tornado(): - self._logger.debug("Shutting down tornado's IOLoop...") - ioloop.stop() - self._logger.debug("SIGTERM received...") - ioloop.add_callback_from_signal(shutdown_tornado) - signal.signal(signal.SIGTERM, sigterm_handler) - - try: - # this is the main loop - as long as tornado is running, OctoPrint is running - ioloop.start() - self._logger.debug("Tornado's IOLoop stopped") - except (KeyboardInterrupt, SystemExit): - pass - except Exception: - self._logger.fatal("Now that is embarrassing... Something really really went wrong here. Please report this including the stacktrace below in OctoPrint's bugtracker. Thanks!") - self._logger.exception("Stacktrace follows:") - - def _create_socket_connection(self, session): - global printer, fileManager, analysisQueue, userManager, eventManager - return util.sockjs.PrinterStateConnection(printer, fileManager, analysisQueue, userManager, groupManager, - eventManager, pluginManager, session) - - def _check_for_root(self): - if "geteuid" in dir(os) and os.geteuid() == 0: - exit("You should not run OctoPrint as root!") - - def _get_locale(self): - global LANGUAGES - - if "l10n" in request.values: - return Locale.negotiate([request.values["l10n"]], LANGUAGES) - - if "X-Locale" in request.headers: - return Locale.negotiate([request.headers["X-Locale"]], LANGUAGES) - - if hasattr(g, "identity") and g.identity and userManager.enabled: - userid = g.identity.id - try: - user_language = userManager.get_user_setting(userid, ("interface", "language")) - if user_language is not None and not user_language == "_default": - return Locale.negotiate([user_language], LANGUAGES) - except octoprint.access.users.UnknownUser: - pass - - default_language = self._settings.get(["appearance", "defaultLanguage"]) - if default_language is not None and not default_language == "_default" and default_language in LANGUAGES: - return Locale.negotiate([default_language], LANGUAGES) - - return Locale.parse(request.accept_languages.best_match(LANGUAGES)) - - def _setup_heartbeat_logging(self): - logger = logging.getLogger(__name__ + ".heartbeat") - - def log_heartbeat(): - logger.info("Server heartbeat <3") - - interval = settings().getFloat(["server", "heartbeat"]) - logger.info("Starting server heartbeat, {}s interval".format(interval)) - - timer = octoprint.util.RepeatedTimer(interval, log_heartbeat) - timer.start() - - def _setup_app(self, app): - from octoprint.server.util.flask import ReverseProxiedEnvironment, OctoPrintFlaskRequest, \ - OctoPrintFlaskResponse, OctoPrintJsonEncoder, OctoPrintSessionInterface - - s = settings() - - # setup octoprint's flask json serialization/deserialization - app.json_encoder = OctoPrintJsonEncoder - - app.debug = self._debug - app.config["TEMPLATES_AUTO_RELOAD"] = True - app.config["JSONIFY_PRETTYPRINT_REGULAR"] = False - - secret_key = s.get(["server", "secretKey"]) - if not secret_key: - import string - from random import choice - chars = string.ascii_lowercase + string.ascii_uppercase + string.digits - secret_key = "".join(choice(chars) for _ in range(32)) - s.set(["server", "secretKey"], secret_key) - s.save() - - app.secret_key = secret_key - - reverse_proxied = ReverseProxiedEnvironment( - header_prefix=s.get(["server", "reverseProxy", "prefixHeader"]), - header_scheme=s.get(["server", "reverseProxy", "schemeHeader"]), - header_host=s.get(["server", "reverseProxy", "hostHeader"]), - header_server=s.get(["server", "reverseProxy", "serverHeader"]), - header_port=s.get(["server", "reverseProxy", "portHeader"]), - prefix=s.get(["server", "reverseProxy", "prefixFallback"]), - scheme=s.get(["server", "reverseProxy", "schemeFallback"]), - host=s.get(["server", "reverseProxy", "hostFallback"]), - server=s.get(["server", "reverseProxy", "serverFallback"]), - port=s.get(["server", "reverseProxy", "portFallback"]) - ) - - OctoPrintFlaskRequest.environment_wrapper = reverse_proxied - app.request_class = OctoPrintFlaskRequest - app.response_class = OctoPrintFlaskResponse - app.session_interface = OctoPrintSessionInterface() - - @app.before_request - def before_request(): - g.locale = self._get_locale() - if self._debug and "perfprofile" in request.args: - try: - from pyinstrument import Profiler - g.perfprofiler = Profiler() - g.perfprofiler.start() - except ImportError: - # profiler dependency not installed, ignore - pass - - - @app.after_request - def after_request(response): - # send no-cache headers with all POST responses - if request.method == "POST": - response.cache_control.no_cache = True - - response.headers.add("X-Clacks-Overhead", "GNU Terry Pratchett") - - if hasattr(g, "perfprofiler"): - g.perfprofiler.stop() - output_html = g.perfprofiler.output_html() - return make_response(output_html) - - return response - - from octoprint.util.jinja import MarkdownFilter - MarkdownFilter(app) - - def _setup_i18n(self, app): - global babel - global LOCALES - global LANGUAGES - - babel = Babel(app) - - def get_available_locale_identifiers(locales): - result = set() - - # add available translations - for locale in locales: - result.add(locale.language) - if locale.territory: - # if a territory is specified, add that too - result.add("%s_%s" % (locale.language, locale.territory)) - - return result - - LOCALES = babel.list_translations() - LANGUAGES = get_available_locale_identifiers(LOCALES) - - @babel.localeselector - def get_locale(): - return self._get_locale() - - def _setup_jinja2(self): - import re - - app.jinja_env.add_extension("jinja2.ext.do") - app.jinja_env.add_extension("octoprint.util.jinja.trycatch") - - def regex_replace(s, find, replace): - return re.sub(find, replace, s) - - html_header_regex = re.compile(r"[1-6])>(?P.*?)") - def offset_html_headers(s, offset): - def repl(match): - number = int(match.group("number")) - number += offset - if number > 6: - number = 6 - elif number < 1: - number = 1 - return "{content}".format(number=number, content=match.group("content")) - return html_header_regex.sub(repl, s) - - markdown_header_regex = re.compile(r"^(?P#+)\s+(?P.*)$", flags=re.MULTILINE) - def offset_markdown_headers(s, offset): - def repl(match): - number = len(match.group("hashs")) - number += offset - if number > 6: - number = 6 - elif number < 1: - number = 1 - return "{hashs} {content}".format(hashs="#" * number, content=match.group("content")) - return markdown_header_regex.sub(repl, s) - - html_link_regex = re.compile(r"<(?Pa.*?)>(?P.*?)") - def externalize_links(text): - def repl(match): - tag = match.group("tag") - if not "href" in tag: - return match.group(0) - - if not "target=" in tag and not "rel=" in tag: - tag += " target=\"_blank\" rel=\"noreferrer noopener\"" - - content = match.group("content") - return "<{tag}>{content}".format(tag=tag, content=content) - return html_link_regex.sub(repl, text) - - single_quote_regex = re.compile("(? cutoff_timestamp - - def filter_http_entries(entry): - """Returns True for entries targeting http or https.""" - return "base_url" in entry \ - and entry["base_url"] \ - and (entry["base_url"].startswith("http://") - or entry["base_url"].startswith("https://")) - - def filter_entries(entry): - """Combined filter.""" - filters = (filter_current_entries, - filter_http_entries) - return all([f(entry) for f in filters]) - - # filter out all old and non-http entries - cache_data = preemptive_cache.clean_all_data(lambda root, entries: list(filter(filter_entries, entries))) - if not cache_data: - return - - def execute_caching(): - logger = logging.getLogger(__name__ + ".preemptive_cache") - - for route in sorted(cache_data.keys(), key=lambda x: (x.count("/"), x)): - entries = reversed(sorted(cache_data[route], key=lambda x: x.get("_count", 0))) - for kwargs in entries: - plugin = kwargs.get("plugin", None) - if plugin: - try: - plugin_info = pluginManager.get_plugin_info(plugin, require_enabled=True) - if plugin_info is None: - logger.info("About to preemptively cache plugin {} but it is not installed or enabled, preemptive caching makes no sense".format(plugin)) - continue - - implementation = plugin_info.implementation - if implementation is None or not isinstance(implementation, octoprint.plugin.UiPlugin): - logger.info("About to preemptively cache plugin {} but it is not a UiPlugin, preemptive caching makes no sense".format(plugin)) - continue - if not implementation.get_ui_preemptive_caching_enabled(): - logger.info("About to preemptively cache plugin {} but it has disabled preemptive caching".format(plugin)) - continue - except Exception: - logger.exception("Error while trying to check if plugin {} has preemptive caching enabled, skipping entry") - continue - - additional_request_data = kwargs.get("_additional_request_data", {}) - kwargs = dict((k, v) for k, v in kwargs.items() if not k.startswith("_") and not k == "plugin") - kwargs.update(additional_request_data) - - try: - start = octoprint.util.monotonic_time() - if plugin: - logger.info("Preemptively caching {} (ui {}) for {!r}".format(route, plugin, kwargs)) - else: - logger.info("Preemptively caching {} (ui _default) for {!r}".format(route, kwargs)) - - headers = kwargs.get("headers", {}) - headers["X-Force-View"] = plugin if plugin else "_default" - headers["X-Preemptive-Recording"] = "yes" - kwargs["headers"] = headers - - builder = EnvironBuilder(**kwargs) - app(builder.get_environ(), lambda *a, **kw: None) - - logger.info("... done in {:.2f}s".format(octoprint.util.monotonic_time() - start)) - except Exception: - logger.exception("Error while trying to preemptively cache {} for {!r}".format(route, kwargs)) - - # asynchronous caching - import threading - cache_thread = threading.Thread(target=execute_caching, name="Preemptive Cache Worker") - cache_thread.daemon = True - cache_thread.start() - - def _register_template_plugins(self): - template_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin) - for plugin in template_plugins: - try: - self._register_additional_template_plugin(plugin) - except Exception: - self._logger.exception("Error while trying to register templates of plugin {}, ignoring it".format(plugin._identifier)) - - def _register_additional_template_plugin(self, plugin): - folder = plugin.get_template_folder() - if folder is not None and not folder in self._template_searchpaths: - self._template_searchpaths.append(folder) - - def _unregister_additional_template_plugin(self, plugin): - folder = plugin.get_template_folder() - if folder is not None and folder in self._template_searchpaths: - self._template_searchpaths.remove(folder) - - def _setup_blueprints(self): - from octoprint.server.api import api - import octoprint.server.views # do not remove or the index view won't be found - - blueprints = OrderedDict() - blueprints["/api"] = api - - # also register any blueprints defined in BlueprintPlugins - blueprints.update(self._prepare_blueprint_plugins()) - - # and register a blueprint for serving the static files of asset plugins which are not blueprint plugins themselves - blueprints.update(self._prepare_asset_plugins()) - - # make sure all before/after_request hook results are attached as well - self._add_plugin_request_handlers_to_blueprints(*blueprints.values()) - - # register everything with the system - for url_prefix, blueprint in blueprints.items(): - app.register_blueprint(blueprint, url_prefix=url_prefix) - - def _prepare_blueprint_plugins(self): - blueprints = OrderedDict() - - blueprint_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.BlueprintPlugin) - for plugin in blueprint_plugins: - try: - blueprint, prefix = self._prepare_blueprint_plugin(plugin) - blueprints[prefix] = blueprint - except Exception: - self._logger.exception("Error while registering blueprint of " - "plugin {}, ignoring it".format(plugin._identifier), - extra={"plugin": plugin._identifier}) - continue - - return blueprints - - def _prepare_asset_plugins(self): - blueprints = OrderedDict() - - asset_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.AssetPlugin) - for plugin in asset_plugins: - if isinstance(plugin, octoprint.plugin.BlueprintPlugin): - continue - try: - blueprint, prefix = self._prepare_asset_plugin(plugin) - blueprints[prefix] = blueprint - except Exception: - self._logger.exception("Error while registering assets of plugin " - "{}, ignoring it".format(plugin._identifier), - extra={"plugin": plugin._identifier}) - continue - - return blueprints - - def _prepare_blueprint_plugin(self, plugin): - name = plugin._identifier - blueprint = plugin.get_blueprint() - if blueprint is None: - return - - blueprint.before_request(corsRequestHandler) - blueprint.before_request(loginFromApiKeyRequestHandler) - blueprint.after_request(corsResponseHandler) - - if plugin.is_blueprint_protected(): - blueprint.before_request(requireLoginRequestHandler) - - url_prefix = "/plugin/{name}".format(name=name) - app.register_blueprint(blueprint, url_prefix=url_prefix) - - if self._logger: - self._logger.debug("Registered API of plugin {name} under URL prefix {url_prefix}".format(name=name, url_prefix=url_prefix)) - - return blueprint, url_prefix - - def _prepare_asset_plugin(self, plugin): - name = plugin._identifier - - url_prefix = "/plugin/{name}".format(name=name) - blueprint = Blueprint("plugin." + name, name, static_folder=plugin.get_asset_folder()) - app.register_blueprint(blueprint, url_prefix=url_prefix) - - if self._logger: - self._logger.debug("Registered assets of plugin {name} under URL prefix {url_prefix}".format(name=name, url_prefix=url_prefix)) - - return blueprint, url_prefix - - def _add_plugin_request_handlers_to_blueprints(self, *blueprints): - before_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.server.api.before_request") - after_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.server.api.after_request") - - for name, hook in before_hooks.items(): - plugin = octoprint.plugin.plugin_manager().get_plugin(name) - for blueprint in blueprints: - try: - result = hook(plugin=plugin) - if isinstance(result, (list, tuple)): - for h in result: - blueprint.before_request(h) - except Exception: - self._logger.exception("Error processing before_request hooks from plugin {}".format(plugin), - extra={"plugin": name}) - - for name, hook in after_hooks.items(): - plugin = octoprint.plugin.plugin_manager().get_plugin(name) - for blueprint in blueprints: - try: - result = hook(plugin=plugin) - if isinstance(result, (list, tuple)): - for h in result: - blueprint.after_request(h) - except Exception: - self._logger.exception("Error processing after_request hooks from plugin {}".format(plugin), - extra={"plugin": name}) - - def _setup_mimetypes(self): - # Safety measures for Windows... apparently the mimetypes module takes its translation from the windows - # registry, and if for some weird reason that gets borked the reported MIME types can be all over the place. - # Since at least in Chrome that can cause hilarious issues with JS files (refusal to run them and thus a - # borked UI) we make sure that .js always maps to the correct application/javascript, and also throw in a - # .css -> text/css for good measure. - # - # See #3367 - mimetypes.add_type("application/javascript", ".js") - mimetypes.add_type("text/css", ".css") - - def _setup_assets(self): - global app - global assets - global pluginManager - - util.flask.fix_webassets_cache() - util.flask.fix_webassets_filtertool() - - base_folder = self._settings.getBaseFolder("generated") - - # clean the folder - if self._settings.getBoolean(["devel", "webassets", "clean_on_startup"]): - import shutil - import errno - - for entry in ("webassets", ".webassets-cache"): - path = os.path.join(base_folder, entry) - - # delete path if it exists - if os.path.isdir(path): - try: - self._logger.debug("Deleting {path}...".format(**locals())) - shutil.rmtree(path) - except Exception: - self._logger.exception("Error while trying to delete {path}, " - "leaving it alone".format(**locals())) - 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 - 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())) - pass - else: - # this will only get executed if we never did - # successfully execute makedirs above - self._logger.exception(error_text) - continue - else: - # not an access error, 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())) - - AdjustedEnvironment = type(Environment)(Environment.__name__, - (Environment,), - {"resolver_class": util.flask.PluginAssetResolver}) - class CustomDirectoryEnvironment(AdjustedEnvironment): - @property - def directory(self): - return base_folder - - assets = CustomDirectoryEnvironment(app) - assets.debug = not self._settings.getBoolean(["devel", "webassets", "bundle"]) - - UpdaterType = type(util.flask.SettingsCheckUpdater)(util.flask.SettingsCheckUpdater.__name__, - (util.flask.SettingsCheckUpdater,), - {"updater": assets.updater}) - assets.updater = UpdaterType - - preferred_stylesheet = self._settings.get(["devel", "stylesheet"]) - - dynamic_core_assets = util.flask.collect_core_assets() - dynamic_plugin_assets = util.flask.collect_plugin_assets(preferred_stylesheet=preferred_stylesheet) - - js_libs = [ - "js/lib/jquery/jquery.min.js", - "js/lib/modernizr.custom.js", - "js/lib/lodash.min.js", - "js/lib/sprintf.min.js", - "js/lib/knockout.js", - "js/lib/knockout.mapping-latest.js", - "js/lib/babel.js", - "js/lib/avltree.js", - "js/lib/bootstrap/bootstrap.js", - "js/lib/bootstrap/bootstrap-modalmanager.js", - "js/lib/bootstrap/bootstrap-modal.js", - "js/lib/bootstrap/bootstrap-slider.js", - "js/lib/bootstrap/bootstrap-tabdrop.js", - "js/lib/jquery/jquery.ui.core.js", - "js/lib/jquery/jquery.ui.widget.js", - "js/lib/jquery/jquery.ui.mouse.js", - "js/lib/jquery/jquery.flot.js", - "js/lib/jquery/jquery.flot.time.js", - "js/lib/jquery/jquery.flot.crosshair.js", - "js/lib/jquery/jquery.flot.resize.js", - "js/lib/jquery/jquery.iframe-transport.js", - "js/lib/jquery/jquery.fileupload.js", - "js/lib/jquery/jquery.slimscroll.min.js", - "js/lib/jquery/jquery.qrcode.min.js", - "js/lib/jquery/jquery.bootstrap.wizard.js", - "js/lib/pnotify/pnotify.core.min.js", - "js/lib/pnotify/pnotify.buttons.min.js", - "js/lib/pnotify/pnotify.callbacks.min.js", - "js/lib/pnotify/pnotify.confirm.min.js", - "js/lib/pnotify/pnotify.desktop.min.js", - "js/lib/pnotify/pnotify.history.min.js", - "js/lib/pnotify/pnotify.mobile.min.js", - "js/lib/pnotify/pnotify.nonblock.min.js", - "js/lib/pnotify/pnotify.reference.min.js", - "js/lib/pnotify/pnotify.tooltip.min.js", - "js/lib/pnotify/pnotify.maxheight.js", - "js/lib/moment-with-locales.min.js", - "js/lib/pusher.color.min.js", - "js/lib/detectmobilebrowser.js", - "js/lib/md5.min.js", - "js/lib/bootstrap-slider-knockout-binding.js", - "js/lib/loglevel.min.js", - "js/lib/sockjs.min.js", - "js/lib/ResizeSensor.js", - "js/lib/less.min.js", - "js/lib/hls.js" - ] - js_client = [ - "js/app/client/base.js", - "js/app/client/socket.js", - "js/app/client/browser.js", - "js/app/client/connection.js", - "js/app/client/control.js", - "js/app/client/files.js", - "js/app/client/job.js", - "js/app/client/languages.js", - "js/app/client/printer.js", - "js/app/client/printerprofiles.js", - "js/app/client/settings.js", - "js/app/client/slicing.js", - "js/app/client/system.js", - "js/app/client/timelapse.js", - "js/app/client/users.js", - "js/app/client/util.js", - "js/app/client/wizard.js", - "js/app/client/access.js" - ] - - css_libs = [ - "css/bootstrap.min.css", - "css/bootstrap-modal.css", - "css/bootstrap-slider.css", - "css/bootstrap-tabdrop.css", - "vendor/font-awesome-3.2.1/css/font-awesome.min.css", - "vendor/font-awesome-4.7.0/css/font-awesome.min.css", - "css/jquery.fileupload-ui.css", - "css/pnotify.core.min.css", - "css/pnotify.buttons.min.css", - "css/pnotify.history.min.css" - ] - - # a couple of custom filters - from octoprint.server.util.webassets import LessImportRewrite, JsDelimiterBundler, \ - SourceMapRewrite, SourceMapRemove, JsPluginBundle, GzipFile - from webassets.filter import register_filter - - register_filter(LessImportRewrite) - register_filter(SourceMapRewrite) - register_filter(SourceMapRemove) - register_filter(JsDelimiterBundler) - register_filter(GzipFile) - - def all_assets_for_plugins(collection): - """Gets all plugin assets for a dict of plugin->assets""" - result = [] - for assets in collection.values(): - result += assets - return result - - # -- JS -------------------------------------------------------------------------------------------------------- - - filters = ["sourcemap_remove", "js_delimiter_bundler"] - if self._settings.getBoolean(["devel", "webassets", "minify"]): - filters.append("rjsmin") - filters.append("gzip") - - js_filters = filters - if self._settings.getBoolean(["devel", "webassets", "minify_plugins"]): - js_plugin_filters = js_filters - else: - js_plugin_filters = [x for x in js_filters if x not in ("rjsmin",)] - - def js_bundles_for_plugins(collection, filters=None): - """Produces JsPluginBundle instances that output IIFE wrapped assets""" - result = OrderedDict() - for plugin, assets in collection.items(): - if len(assets): - result[plugin] = JsPluginBundle(plugin, *assets, filters=filters) - return result - - js_core = dynamic_core_assets["js"] + \ - all_assets_for_plugins(dynamic_plugin_assets["bundled"]["js"]) + \ - ["js/app/dataupdater.js", - "js/app/helpers.js", - "js/app/main.js"] - js_plugins = js_bundles_for_plugins(dynamic_plugin_assets["external"]["js"], - filters="js_delimiter_bundler") - - clientjs_core = dynamic_core_assets["clientjs"] + \ - all_assets_for_plugins(dynamic_plugin_assets["bundled"]["clientjs"]) - clientjs_plugins = js_bundles_for_plugins(dynamic_plugin_assets["external"]["clientjs"], - filters="js_delimiter_bundler") - - js_libs_bundle = Bundle(*js_libs, - output="webassets/packed_libs.js", - filters=",".join(js_filters)) - - js_core_bundle = Bundle(*js_core, - output="webassets/packed_core.js", - filters=",".join(js_filters)) - - if len(js_plugins) == 0: - js_plugins_bundle = Bundle(*[]) - else: - js_plugins_bundle = Bundle(*js_plugins.values(), - output="webassets/packed_plugins.js", - filters=",".join(js_plugin_filters)) - - js_app_bundle = Bundle(js_plugins_bundle, js_core_bundle, - output="webassets/packed_app.js", - filters=",".join(js_plugin_filters)) - - js_client_core_bundle = Bundle(*clientjs_core, - output="webassets/packed_client_core.js", - filters=",".join(js_filters)) - - if len(clientjs_plugins) == 0: - js_client_plugins_bundle = Bundle(*[]) - else: - js_client_plugins_bundle = Bundle(*clientjs_plugins.values(), - output="webassets/packed_client_plugins.js", - filters=",".join(js_plugin_filters)) - - js_client_bundle = Bundle(js_client_core_bundle, js_client_plugins_bundle, - output="webassets/packed_client.js", - filters=",".join(js_plugin_filters)) - - # -- CSS ------------------------------------------------------------------------------------------------------- - - css_filters = ["cssrewrite", "gzip"] - - css_core = list(dynamic_core_assets["css"]) \ - + all_assets_for_plugins(dynamic_plugin_assets["bundled"]["css"]) - css_plugins = list(all_assets_for_plugins(dynamic_plugin_assets["external"]["css"])) - - css_libs_bundle = Bundle(*css_libs, - output="webassets/packed_libs.css", - filters=",".join(css_filters)) - - if len(css_core) == 0: - css_core_bundle = Bundle(*[]) - else: - css_core_bundle = Bundle(*css_core, - output="webassets/packed_core.css", - filters=",".join(css_filters)) - - if len(css_plugins) == 0: - css_plugins_bundle = Bundle(*[]) - else: - css_plugins_bundle = Bundle(*css_plugins, - output="webassets/packed_plugins.css", - filters=",".join(css_filters)) - - css_app_bundle = Bundle(css_core, css_plugins, - output="webassets/packed_app.css", - filters=",".join(css_filters)) - - # -- LESS ------------------------------------------------------------------------------------------------------ - - less_filters = ["cssrewrite", "less_importrewrite", "gzip"] - - less_core = list(dynamic_core_assets["less"]) \ - + all_assets_for_plugins(dynamic_plugin_assets["bundled"]["less"]) - less_plugins = all_assets_for_plugins(dynamic_plugin_assets["external"]["less"]) - - if len(less_core) == 0: - less_core_bundle = Bundle(*[]) - else: - less_core_bundle = Bundle(*less_core, - output="webassets/packed_core.less", - filters=",".join(less_filters)) - - if len(less_plugins) == 0: - less_plugins_bundle = Bundle(*[]) - else: - less_plugins_bundle = Bundle(*less_plugins, - output="webassets/packed_plugins.less", - filters=",".join(less_filters)) - - less_app_bundle = Bundle(less_core, less_plugins, - output="webassets/packed_app.less", - filters=",".join(less_filters)) - - # -- asset registration ---------------------------------------------------------------------------------------- - - assets.register("js_libs", js_libs_bundle) - assets.register("js_client_core", js_client_core_bundle) - for plugin, bundle in clientjs_plugins.items(): - # register our collected clientjs plugin bundles so that they are bound to the environment - assets.register("js_client_plugin_{}".format(plugin), bundle) - assets.register("js_client_plugins", js_client_plugins_bundle) - assets.register("js_client", js_client_bundle) - assets.register("js_core", js_core_bundle) - for plugin, bundle in js_plugins.items(): - # register our collected plugin bundles so that they are bound to the environment - assets.register("js_plugin_{}".format(plugin), bundle) - assets.register("js_plugins", js_plugins_bundle) - assets.register("js_app", js_app_bundle) - assets.register("css_libs", css_libs_bundle) - assets.register("css_core", css_core_bundle) - assets.register("css_plugins", css_plugins_bundle) - assets.register("css_app", css_app_bundle) - assets.register("less_core", less_core_bundle) - assets.register("less_plugins", less_plugins_bundle) - assets.register("less_app", less_app_bundle) - - def _setup_login_manager(self): - global loginManager - - loginManager = LoginManager() - - # "strong" is incompatible to remember me, see maxcountryman/flask-login#156. It also causes issues with - # clients toggling between IPv4 and IPv6 client addresses due to names being resolved one way or the other as - # at least observed on a Win10 client targeting "localhost", resolved as both "127.0.0.1" and "::1" - loginManager.session_protection = "basic" - - loginManager.user_loader(load_user) - loginManager.unauthorized_handler(unauthorized_user) - loginManager.anonymous_user = userManager.anonymous_user_factory - loginManager.request_loader(load_user_from_request) - - loginManager.init_app(app, add_context_processor=False) - - def _start_intermediary_server(self): - try: - # noinspection PyCompatibility - from http.server import HTTPServer, BaseHTTPRequestHandler - except ImportError: - # noinspection PyCompatibility - from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler - - import threading - import socket - - host = self._host - port = self._port - - class IntermediaryServerHandler(BaseHTTPRequestHandler): - def __init__(self, rules=None, *args, **kwargs): - if rules is None: - rules = [] - self.rules = rules - BaseHTTPRequestHandler.__init__(self, *args, **kwargs) - - def do_GET(self): - request_path = self.path - if "?" in request_path: - request_path = request_path[0:request_path.find("?")] - - for rule in self.rules: - path, data, content_type = rule - if request_path == path: - self.send_response(200) - if content_type: - self.send_header("Content-Type", content_type) - self.end_headers() - if isinstance(data, unicode): - data = data.encode("utf-8") - self.wfile.write(data) - break - else: - self.send_response(404) - self.wfile.write("Not found".encode("utf-8")) - - base_path = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "static")) - rules = [ - ("/", ["intermediary.html",], "text/html"), - ("/favicon.ico", ["img", "tentacle-20x20.png"], "image/png"), - ("/intermediary.gif", bytes(base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")), "image/gif") - ] - - def contents(args): - path = os.path.join(base_path, *args) - if not os.path.isfile(path): - return "" - - with io.open(path, 'rb') as f: - data = f.read() - return data - - def process(rule): - if len(rule) == 2: - path, data = rule - content_type = None - else: - path, data, content_type = rule - - if isinstance(data, (list, tuple)): - data = contents(data) - - return path, data, content_type - - rules = list(map(process, filter(lambda rule: len(rule) == 2 or len(rule) == 3, rules))) - - HTTPServerV4 = HTTPServer - - class HTTPServerV6(HTTPServer): - address_family = socket.AF_INET6 - - class HTTPServerV6SingleStack(HTTPServerV6): - def __init__(self, *args, **kwargs): - HTTPServerV6.__init__(self, *args, **kwargs) - - # explicitly set V6ONLY flag - seems to be the default, but just to make sure... - self.socket.setsockopt(octoprint.util.net.IPPROTO_IPV6, octoprint.util.net.IPV6_V6ONLY, 1) - - class HTTPServerV6DualStack(HTTPServerV6): - def __init__(self, *args, **kwargs): - HTTPServerV6.__init__(self, *args, **kwargs) - - # explicitly unset V6ONLY flag - self.socket.setsockopt(octoprint.util.net.IPPROTO_IPV6, octoprint.util.net.IPV6_V6ONLY, 0) - - if ":" in host: - # v6 - if host == "::" and not self._v6_only: - ServerClass = HTTPServerV6DualStack - else: - ServerClass = HTTPServerV6SingleStack - else: - # v4 - ServerClass = HTTPServerV4 - - if host == "::": - if self._v6_only: - self._logger.debug("Starting intermediary server on http://[::]:{port}".format(port=port)) - else: - self._logger.debug("Starting intermediary server on http://0.0.0.0:{port} and http://[::]:{port}".format(port=port)) - else: - self._logger.debug("Starting intermediary server on http://{}:{}".format(host if not ":" in host else "[" + host + "]", port)) - - self._intermediary_server = ServerClass((host, port), - lambda *args, **kwargs: IntermediaryServerHandler(rules, *args, **kwargs), - bind_and_activate=False) - - # if possible, make sure our socket's port descriptor isn't handed over to subprocesses - from octoprint.util.platform import set_close_exec - try: - set_close_exec(self._intermediary_server.fileno()) - except Exception: - self._logger.exception("Error while attempting to set_close_exec on intermediary server socket") - - # then bind the server and have it serve our handler until stopped - try: - self._intermediary_server.server_bind() - self._intermediary_server.server_activate() - except Exception: - self._intermediary_server.server_close() - raise - - def serve(): - try: - self._intermediary_server.serve_forever() - except Exception: - self._logger.exception("Error in intermediary server") - - thread = threading.Thread(target=serve) - thread.daemon = True - thread.start() - - self._logger.info("Intermediary server started") - - def _stop_intermediary_server(self): - if self._intermediary_server is None: - return - self._logger.info("Shutting down intermediary server...") - self._intermediary_server.shutdown() - self._intermediary_server.server_close() - self._logger.info("Intermediary server shut down") - - def _setup_plugin_permissions(self): - global pluginManager - - from octoprint.access.permissions import PluginOctoPrintPermission - - key_whitelist = re.compile(r"[A-Za-z0-9_]*") - - def permission_key(plugin, definition): - return "PLUGIN_{}_{}".format(plugin.upper(), definition["key"].upper()) - - def permission_name(plugin, definition): - return "{}: {}".format(plugin, definition["name"]) - - def permission_role(plugin, role): - return "plugin_{}_{}".format(plugin, role) - - def process_regular_permission(plugin_info, definition): - permissions = [] - for key in definition.get("permissions", []): - permission = octoprint.access.permissions.Permissions.find(key) - - if permission is None: - # if there is still no permission found, postpone this - maybe it is a permission from - # another plugin that hasn't been loaded yet - return False - - permissions.append(permission) - - roles = definition.get("roles", []) - description = definition.get("description", "") - dangerous = definition.get("dangerous", False) - default_groups = definition.get("default_groups", []) - - roles_and_permissions = [permission_role(plugin_info.key, role) for role in roles] + permissions - - key = permission_key(plugin_info.key, definition) - permission = PluginOctoPrintPermission(permission_name(plugin_info.name, definition), - description, - plugin=plugin_info.key, - dangerous=dangerous, - default_groups=default_groups, - *roles_and_permissions) - setattr(octoprint.access.permissions.Permissions, - key, - PluginOctoPrintPermission(permission_name(plugin_info.name, definition), - description, - plugin=plugin_info.key, - dangerous=dangerous, - default_groups=default_groups, - *roles_and_permissions)) - - self._logger.info("Added new permission from plugin {}: {} (needs: {!r})".format(plugin_info.key, - key, - ", ".join(map(repr, permission.needs)))) - return True - - postponed = [] - - hooks = pluginManager.get_hooks("octoprint.access.permissions") - for name, factory in hooks.items(): - try: - if isinstance(factory, (tuple, list)): - additional_permissions = list(factory) - elif callable(factory): - additional_permissions = factory() - else: - raise ValueError("factory must be either a callable, tuple or list") - - if not isinstance(additional_permissions, (tuple, list)): - raise ValueError("factory result must be either a tuple or a list of permission definition dicts") - - plugin_info = pluginManager.get_plugin_info(name) - for p in additional_permissions: - if not isinstance(p, dict): - continue - - if not "key" in p or not "name" in p: - continue - - if not key_whitelist.match(p["key"]): - self._logger.warning("Got permission with invalid key from plugin {}: {}".format(name, p["key"])) - continue - - if not process_regular_permission(plugin_info, p): - postponed.append((plugin_info, p)) - except Exception: - self._logger.exception("Error while creating permission instance/s from {}".format(name)) - - # final resolution passes - pass_number = 1 - still_postponed = [] - while len(postponed): - start_length = len(postponed) - self._logger.debug("Plugin permission resolution pass #{}, " - "{} unresolved permissions...".format(pass_number, start_length)) - - for plugin_info, definition in postponed: - if not process_regular_permission(plugin_info, definition): - still_postponed.append((plugin_info, definition)) - - self._logger.debug("... pass #{} done, {} permissions left to resolve".format(pass_number, - len(still_postponed))) - - if len(still_postponed) == start_length: - # no change, looks like some stuff is unresolvable - let's bail - for plugin_info, definition in still_postponed: - self._logger.warning("Unable to resolve permission from {}: {!r}".format(plugin_info.key, definition)) - break - - postponed = still_postponed - still_postponed = [] - pass_number += 1 + def __init__( + self, + settings=None, + plugin_manager=None, + connectivity_checker=None, + environment_detector=None, + event_manager=None, + host=None, + port=None, + v6_only=False, + debug=False, + safe_mode=False, + allow_root=False, + octoprint_daemon=None, + ): + self._settings = settings + self._plugin_manager = plugin_manager + self._connectivity_checker = connectivity_checker + self._environment_detector = environment_detector + self._event_manager = event_manager + self._host = host + self._port = port + self._v6_only = v6_only + self._debug = debug + self._safe_mode = safe_mode + self._allow_root = allow_root + self._octoprint_daemon = octoprint_daemon + self._server = None + + self._logger = None + + self._lifecycle_callbacks = defaultdict(list) + + self._template_searchpaths = [] + + self._intermediary_server = None + + def run(self): + if not self._allow_root: + self._check_for_root() + + if self._settings is None: + self._settings = settings() + + if not self._settings.getBoolean(["server", "ignoreIncompleteStartup"]): + self._settings.setBoolean(["server", "incompleteStartup"], True) + self._settings.save() + + if self._plugin_manager is None: + self._plugin_manager = octoprint.plugin.plugin_manager() + + global app + global babel + + global printer + global printerProfileManager + global fileManager + global slicingManager + global analysisQueue + global userManager + global permissionManager + global groupManager + global eventManager + global loginManager + global pluginManager + global pluginLifecycleManager + global preemptiveCache + global jsonEncoder + global jsonDecoder + global connectivityChecker + global debug + global safe_mode + + from tornado.ioloop import IOLoop + from tornado.web import Application + + debug = self._debug + safe_mode = self._safe_mode + + if self._v6_only and not octoprint.util.net.HAS_V6: + raise RuntimeError( + "IPv6 only mode configured but system doesn't support IPv6" + ) + + if self._host is None: + host = self._settings.get(["server", "host"]) + if host is None: + if octoprint.util.net.HAS_V6: + host = "::" + else: + host = "0.0.0.0" + + self._host = host + + if ":" in self._host and not octoprint.util.net.HAS_V6: + raise RuntimeError( + "IPv6 host address {!r} configured but system doesn't support IPv6".format( + self._host + ) + ) + + if self._port is None: + self._port = self._settings.getInt(["server", "port"]) + if self._port is None: + self._port = 5000 + + self._logger = logging.getLogger(__name__) + self._setup_heartbeat_logging() + pluginManager = self._plugin_manager + + # monkey patch/fix some stuff + util.tornado.fix_json_encode() + util.tornado.fix_websocket_check_origin() + util.flask.fix_flask_jsonify() + util.watchdog.fix_scandir() + + self._setup_mimetypes() + + additional_translation_folders = [] + if not safe_mode: + additional_translation_folders += [ + self._settings.getBaseFolder("translations") + ] + util.flask.enable_additional_translations( + additional_folders=additional_translation_folders + ) + + # setup app + self._setup_app(app) + + # setup i18n + self._setup_i18n(app) + + if self._settings.getBoolean(["serial", "log"]): + # enable debug logging to serial.log + logging.getLogger("SERIAL").setLevel(logging.DEBUG) + + if self._settings.getBoolean(["devel", "pluginTimings"]): + # enable plugin timings log + logging.getLogger("PLUGIN_TIMINGS").setLevel(logging.DEBUG) + + # start the intermediary server + self._start_intermediary_server() + + ### IMPORTANT! + ### + ### Best do not start any subprocesses until the intermediary server shuts down again or they MIGHT inherit the + ### open port and prevent us from firing up Tornado later. + ### + ### The intermediary server's socket should have the CLOSE_EXEC flag (or its equivalent) set where possible, but + ### we can only do that if fcntl is available or we are on Windows, so better safe than sorry. + ### + ### See also issues #2035 and #2090 + + # then initialize the plugin manager + pluginManager.reload_plugins(startup=True, initialize_implementations=False) + + printerProfileManager = PrinterProfileManager() + eventManager = self._event_manager + + analysis_queue_factories = { + "gcode": octoprint.filemanager.analysis.GcodeAnalysisQueue + } + analysis_queue_hooks = pluginManager.get_hooks( + "octoprint.filemanager.analysis.factory" + ) + for name, hook in analysis_queue_hooks.items(): + try: + additional_factories = hook() + analysis_queue_factories.update(**additional_factories) + except Exception: + self._logger.exception( + "Error while processing analysis queues from {}".format(name), + extra={"plugin": name}, + ) + analysisQueue = octoprint.filemanager.analysis.AnalysisQueue( + analysis_queue_factories + ) + + slicingManager = octoprint.slicing.SlicingManager( + self._settings.getBaseFolder("slicingProfiles"), printerProfileManager + ) + + storage_managers = {} + storage_managers[ + octoprint.filemanager.FileDestinations.LOCAL + ] = octoprint.filemanager.storage.LocalFileStorage( + self._settings.getBaseFolder("uploads") + ) + + fileManager = octoprint.filemanager.FileManager( + analysisQueue, + slicingManager, + printerProfileManager, + initial_storage_managers=storage_managers, + ) + pluginLifecycleManager = LifecycleManager(pluginManager) + preemptiveCache = PreemptiveCache( + os.path.join( + self._settings.getBaseFolder("data"), "preemptive_cache_config.yaml" + ) + ) + + JsonEncoding.add_encoder(users.User, lambda obj: obj.as_dict()) + JsonEncoding.add_encoder(groups.Group, lambda obj: obj.as_dict()) + JsonEncoding.add_encoder( + permissions.OctoPrintPermission, lambda obj: obj.as_dict() + ) + + # start regular check if we are connected to the internet + def on_connectivity_change(old_value, new_value): + eventManager.fire( + events.Events.CONNECTIVITY_CHANGED, + payload={"old": old_value, "new": new_value}, + ) + + connectivityChecker = self._connectivity_checker + + def on_settings_update(*args, **kwargs): + # make sure our connectivity checker runs with the latest settings + connectivityEnabled = self._settings.getBoolean( + ["server", "onlineCheck", "enabled"] + ) + connectivityInterval = self._settings.getInt( + ["server", "onlineCheck", "interval"] + ) + connectivityHost = self._settings.get(["server", "onlineCheck", "host"]) + connectivityPort = self._settings.getInt(["server", "onlineCheck", "port"]) + connectivityName = self._settings.get(["server", "onlineCheck", "name"]) + + if ( + connectivityChecker.enabled != connectivityEnabled + or connectivityChecker.interval != connectivityInterval + or connectivityChecker.host != connectivityHost + or connectivityChecker.port != connectivityPort + or connectivityChecker.name != connectivityName + ): + connectivityChecker.enabled = connectivityEnabled + connectivityChecker.interval = connectivityInterval + connectivityChecker.host = connectivityHost + connectivityChecker.port = connectivityPort + connectivityChecker.name = connectivityName + connectivityChecker.check_immediately() + + eventManager.subscribe(events.Events.SETTINGS_UPDATED, on_settings_update) + + components = { + "plugin_manager": pluginManager, + "printer_profile_manager": printerProfileManager, + "event_bus": eventManager, + "analysis_queue": analysisQueue, + "slicing_manager": slicingManager, + "file_manager": fileManager, + "plugin_lifecycle_manager": pluginLifecycleManager, + "preemptive_cache": preemptiveCache, + "json_encoder": jsonEncoder, + "json_decoder": jsonDecoder, + "connectivity_checker": connectivityChecker, + "environment_detector": self._environment_detector, + } + + # ~~ setup access control + + # get additional permissions from plugins + self._setup_plugin_permissions() + + # create group manager instance + group_manager_factories = pluginManager.get_hooks( + "octoprint.access.groups.factory" + ) + for name, factory in group_manager_factories.items(): + try: + groupManager = factory(components, self._settings) + if groupManager is not None: + self._logger.debug( + "Created group manager instance from factory {}".format(name) + ) + break + except Exception: + self._logger.exception( + "Error while creating group manager instance from factory {}".format( + name + ) + ) + else: + group_manager_name = self._settings.get(["accessControl", "groupManager"]) + try: + clazz = octoprint.util.get_class(group_manager_name) + groupManager = clazz() + except AttributeError: + self._logger.exception( + "Could not instantiate group manager {}, " + "falling back to FilebasedGroupManager!".format(group_manager_name) + ) + groupManager = octoprint.access.groups.FilebasedGroupManager() + components.update({"group_manager": groupManager}) + + # create user manager instance + user_manager_factories = pluginManager.get_hooks( + "octoprint.users.factory" + ) # legacy, set first so that new wins + user_manager_factories.update( + pluginManager.get_hooks("octoprint.access.users.factory") + ) + for name, factory in user_manager_factories.items(): + try: + userManager = factory(components, self._settings) + if userManager is not None: + self._logger.debug( + "Created user manager instance from factory {}".format(name) + ) + break + except Exception: + self._logger.exception( + "Error while creating user manager instance from factory {}".format( + name + ), + extra={"plugin": name}, + ) + else: + user_manager_name = self._settings.get(["accessControl", "userManager"]) + try: + clazz = octoprint.util.get_class(user_manager_name) + userManager = clazz(groupManager) + except Exception: + self._logger.exception( + "Could not instantiate user manager {}, " + "falling back to FilebasedUserManager!".format(user_manager_name) + ) + userManager = octoprint.access.users.FilebasedUserManager(groupManager) + finally: + userManager.enabled = self._settings.getBoolean( + ["accessControl", "enabled"] + ) + components.update({"user_manager": userManager}) + + # create printer instance + printer_factories = pluginManager.get_hooks("octoprint.printer.factory") + for name, factory in printer_factories.items(): + try: + printer = factory(components) + if printer is not None: + self._logger.debug( + "Created printer instance from factory {}".format(name) + ) + break + except Exception: + self._logger.exception( + "Error while creating printer instance from factory {}".format(name), + extra={"plugin": name}, + ) + else: + printer = Printer(fileManager, analysisQueue, printerProfileManager) + components.update({"printer": printer}) + + def octoprint_plugin_inject_factory(name, implementation): + """Factory for injections for all OctoPrintPlugins""" + if not isinstance(implementation, octoprint.plugin.OctoPrintPlugin): + return None + + components_copy = dict(components) + if "printer" in components: + import wrapt + import functools + + def tagwrap(f): + @functools.wraps(f) + def wrapper(*args, **kwargs): + tags = kwargs.get("tags", set()) | { + "source:plugin", + "plugin:{}".format(name), + } + kwargs["tags"] = tags + return f(*args, **kwargs) + + setattr(wrapper, "__tagwrapped__", True) + return wrapper + + class TaggedFuncsPrinter(wrapt.ObjectProxy): + def __getattribute__(self, attr): + __wrapped__ = super(TaggedFuncsPrinter, self).__getattribute__( + "__wrapped__" + ) + if attr == "__wrapped__": + return __wrapped__ + + item = getattr(__wrapped__, attr) + if ( + callable(item) + and ( + "tags" in item.__code__.co_varnames + or "kwargs" in item.__code__.co_varnames + ) + and not getattr(item, "__tagwrapped__", False) + ): + return tagwrap(item) + else: + return item + + components_copy["printer"] = TaggedFuncsPrinter(components["printer"]) + + props = {} + props.update(components_copy) + props.update( + {"data_folder": os.path.join(self._settings.getBaseFolder("data"), name)} + ) + return props + + def settings_plugin_inject_factory(name, implementation): + """Factory for additional injections/initializations depending on plugin type""" + if not isinstance(implementation, octoprint.plugin.SettingsPlugin): + return + + default_settings_overlay = {"plugins": {}} + default_settings_overlay["plugins"][ + name + ] = implementation.get_settings_defaults() + self._settings.add_overlay(default_settings_overlay, at_end=True) + + plugin_settings = octoprint.plugin.plugin_settings_for_settings_plugin( + name, implementation + ) + if plugin_settings is None: + return + + return {"settings": plugin_settings} + + def settings_plugin_config_migration_and_cleanup(identifier, implementation): + """Take care of migrating and cleaning up any old settings""" + + if not isinstance(implementation, octoprint.plugin.SettingsPlugin): + return + + settings_version = implementation.get_settings_version() + settings_migrator = implementation.on_settings_migrate + + if settings_version is not None and settings_migrator is not None: + stored_version = implementation._settings.get_int( + [octoprint.plugin.SettingsPlugin.config_version_key] + ) + if stored_version is None or stored_version < settings_version: + settings_migrator(settings_version, stored_version) + implementation._settings.set_int( + [octoprint.plugin.SettingsPlugin.config_version_key], + settings_version, + force=True, + ) + + implementation.on_settings_cleanup() + implementation._settings.save() + + implementation.on_settings_initialized() + + custom_events_hooks = pluginManager.get_hooks( + "octoprint.events.register_custom_events" + ) + for name, hook in custom_events_hooks.items(): + try: + result = hook() + if isinstance(result, (list, tuple)): + for event in result: + constant, value = octoprint.events.Events.register_event( + event, prefix="plugin_{}_".format(name) + ) + self._logger.debug( + 'Registered event {} of plugin {} as Events.{} = "{}"'.format( + event, name, constant, value + ) + ) + except Exception: + self._logger.exception( + "Error while retrieving custom event list from plugin {}".format( + name + ), + extra={"plugin": name}, + ) + + pluginManager.implementation_inject_factories = [ + octoprint_plugin_inject_factory, + settings_plugin_inject_factory, + ] + pluginManager.initialize_implementations() + + settingsPlugins = pluginManager.get_implementations( + octoprint.plugin.SettingsPlugin + ) + for implementation in settingsPlugins: + try: + settings_plugin_config_migration_and_cleanup( + implementation._identifier, implementation + ) + except Exception: + self._logger.exception( + "Error while trying to migrate settings for " + "plugin {}, ignoring it".format(implementation._identifier), + extra={"plugin": implementation._identifier}, + ) + + pluginManager.implementation_post_inits = [ + settings_plugin_config_migration_and_cleanup + ] + + pluginManager.log_all_plugins() + + # log environment data now + self._environment_detector.log_detected_environment() + + # initialize file manager and register it for changes in the registered plugins + fileManager.initialize() + pluginLifecycleManager.add_callback( + ["enabled", "disabled"], lambda name, plugin: fileManager.reload_plugins() + ) + + # initialize slicing manager and register it for changes in the registered plugins + slicingManager.initialize() + pluginLifecycleManager.add_callback( + ["enabled", "disabled"], lambda name, plugin: slicingManager.reload_slicers() + ) + + # setup jinja2 + self._setup_jinja2() + + # setup assets + self._setup_assets() + + # configure timelapse + octoprint.timelapse.valid_timelapse("test") + octoprint.timelapse.configure_timelapse() + + # setup command triggers + events.CommandTrigger(printer) + if self._debug: + events.DebugEventListener() + + # setup login manager + self._setup_login_manager() + + # register API blueprint + self._setup_blueprints() + + ## Tornado initialization starts here + + ioloop = IOLoop() + ioloop.install() + + enable_cors = settings().getBoolean(["api", "allowCrossOrigin"]) + + self._router = SockJSRouter( + self._create_socket_connection, + "/sockjs", + session_kls=util.sockjs.ThreadSafeSession, + user_settings={ + "websocket_allow_origin": "*" if enable_cors else "", + "jsessionid": False, + "sockjs_url": "../../static/js/lib/sockjs.min.js", + }, + ) + + upload_suffixes = { + "name": self._settings.get(["server", "uploads", "nameSuffix"]), + "path": self._settings.get(["server", "uploads", "pathSuffix"]), + } + + def mime_type_guesser(path): + from octoprint.filemanager import get_mime_type + + return get_mime_type(path) + + def download_name_generator(path): + metadata = fileManager.get_metadata("local", path) + if metadata and "display" in metadata: + return metadata["display"] + + download_handler_kwargs = {"as_attachment": True, "allow_client_caching": False} + + additional_mime_types = {"mime_type_guesser": mime_type_guesser} + + ##~~ Permission validators + + access_validators_from_plugins = [] + for plugin, hook in pluginManager.get_hooks( + "octoprint.server.http.access_validator" + ).items(): + try: + access_validators_from_plugins.append( + util.tornado.access_validation_factory(app, hook) + ) + except Exception: + self._logger.exception( + "Error while adding tornado access validator from plugin {}".format( + plugin + ), + extra={"plugin": plugin}, + ) + access_validator = { + "access_validation": util.tornado.validation_chain( + *access_validators_from_plugins + ) + } + + timelapse_validators = [ + util.tornado.access_validation_factory( + app, + util.flask.permission_validator, + permissions.Permissions.TIMELAPSE_LIST, + ), + ] + access_validators_from_plugins + download_validators = [ + util.tornado.access_validation_factory( + app, + util.flask.permission_validator, + permissions.Permissions.FILES_DOWNLOAD, + ), + ] + access_validators_from_plugins + log_validators = [ + util.tornado.access_validation_factory( + app, + util.flask.permission_validator, + permissions.Permissions.PLUGIN_LOGGING_MANAGE, + ), + ] + access_validators_from_plugins + camera_validators = [ + util.tornado.access_validation_factory( + app, util.flask.permission_validator, permissions.Permissions.WEBCAM + ), + ] + access_validators_from_plugins + + timelapse_permission_validator = { + "access_validation": util.tornado.validation_chain(*timelapse_validators) + } + download_permission_validator = { + "access_validation": util.tornado.validation_chain(*download_validators) + } + log_permission_validator = { + "access_validation": util.tornado.validation_chain(*log_validators) + } + camera_permission_validator = { + "access_validation": util.tornado.validation_chain(*camera_validators) + } + + no_hidden_files_validator = { + "path_validation": util.tornado.path_validation_factory( + lambda path: not octoprint.util.is_hidden_path(path), status_code=404 + ) + } + timelapse_path_validator = { + "path_validation": util.tornado.path_validation_factory( + lambda path: not octoprint.util.is_hidden_path(path) + and octoprint.timelapse.valid_timelapse(path), + status_code=404, + ) + } + + def joined_dict(*dicts): + if not len(dicts): + return {} + + joined = {} + for d in dicts: + joined.update(d) + return joined + + util.tornado.RequestlessExceptionLoggingMixin.LOG_REQUEST = debug + util.tornado.CorsSupportMixin.ENABLE_CORS = enable_cors + + server_routes = self._router.urls + [ + # various downloads + # .mpg and .mp4 timelapses: + ( + r"/downloads/timelapse/(.*)", + util.tornado.LargeResponseHandler, + joined_dict( + {"path": self._settings.getBaseFolder("timelapse")}, + timelapse_permission_validator, + download_handler_kwargs, + timelapse_path_validator, + ), + ), + ( + r"/downloads/files/local/(.*)", + util.tornado.LargeResponseHandler, + joined_dict( + { + "path": self._settings.getBaseFolder("uploads"), + "as_attachment": True, + "name_generator": download_name_generator, + }, + download_permission_validator, + download_handler_kwargs, + no_hidden_files_validator, + additional_mime_types, + ), + ), + ( + r"/downloads/logs/([^/]*)", + util.tornado.LargeResponseHandler, + joined_dict( + { + "path": self._settings.getBaseFolder("logs"), + "mime_type_guesser": lambda *args, **kwargs: "text/plain", + "stream_body": True, + }, + download_handler_kwargs, + log_permission_validator, + ), + ), + # camera snapshot + ( + r"/downloads/camera/current", + util.tornado.UrlProxyHandler, + joined_dict( + { + "url": self._settings.get(["webcam", "snapshot"]), + "as_attachment": True, + }, + camera_permission_validator, + ), + ), + # generated webassets + ( + r"/static/webassets/(.*)", + util.tornado.LargeResponseHandler, + { + "path": os.path.join( + self._settings.getBaseFolder("generated"), "webassets" + ), + "is_pre_compressed": True, + }, + ), + # online indicators - text file with "online" as content and a transparent gif + (r"/online.txt", util.tornado.StaticDataHandler, {"data": "online\n"}), + ( + r"/online.gif", + util.tornado.StaticDataHandler, + { + "data": bytes( + base64.b64decode( + "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" + ) + ), + "content_type": "image/gif", + }, + ), + # deprecated endpoints + ( + r"/api/logs", + util.tornado.DeprecatedEndpointHandler, + {"url": "/plugin/logging/logs"}, + ), + ( + r"/api/logs/(.*)", + util.tornado.DeprecatedEndpointHandler, + {"url": "/plugin/logging/logs/{0}"}, + ), + ] + + # fetch additional routes from plugins + for name, hook in pluginManager.get_hooks("octoprint.server.http.routes").items(): + try: + result = hook(list(server_routes)) + except Exception: + self._logger.exception( + "There was an error while retrieving additional " + "server routes from plugin hook {name}".format(**locals()), + extra={"plugin": name}, + ) + else: + if isinstance(result, (list, tuple)): + for entry in result: + if not isinstance(entry, tuple) or not len(entry) == 3: + continue + if not isinstance(entry[0], basestring): + continue + if not isinstance(entry[2], dict): + continue + + route, handler, kwargs = entry + route = r"/plugin/{name}/{route}".format( + name=name, + route=route if not route.startswith("/") else route[1:], + ) + + self._logger.debug( + "Adding additional route {route} handled by handler {handler} and with additional arguments {kwargs!r}".format( + **locals() + ) + ) + server_routes.append((route, handler, kwargs)) + + headers = { + "X-Robots-Tag": "noindex, nofollow, noimageindex", + "X-Content-Type-Options": "nosniff", + } + if not settings().getBoolean(["server", "allowFraming"]): + headers["X-Frame-Options"] = "sameorigin" + + removed_headers = ["Server"] + + server_routes.append( + ( + r".*", + util.tornado.UploadStorageFallbackHandler, + { + "fallback": util.tornado.WsgiInputContainer( + app.wsgi_app, headers=headers, removed_headers=removed_headers + ), + "file_prefix": "octoprint-file-upload-", + "file_suffix": ".tmp", + "suffixes": upload_suffixes, + }, + ) + ) + + transforms = [ + util.tornado.GlobalHeaderTransform.for_headers( + "OctoPrintGlobalHeaderTransform", + headers=headers, + removed_headers=removed_headers, + ) + ] + + self._tornado_app = Application(handlers=server_routes, transforms=transforms) + max_body_sizes = [ + ( + "POST", + r"/api/files/([^/]*)", + self._settings.getInt(["server", "uploads", "maxSize"]), + ), + ("POST", r"/api/languages", 5 * 1024 * 1024), + ] + + # allow plugins to extend allowed maximum body sizes + for name, hook in pluginManager.get_hooks( + "octoprint.server.http.bodysize" + ).items(): + try: + result = hook(list(max_body_sizes)) + except Exception: + self._logger.exception( + "There was an error while retrieving additional " + "upload sizes from plugin hook {name}".format(**locals()), + extra={"plugin": name}, + ) + else: + if isinstance(result, (list, tuple)): + for entry in result: + if not isinstance(entry, tuple) or not len(entry) == 3: + continue + if ( + not entry[0] + in util.tornado.UploadStorageFallbackHandler.BODY_METHODS + ): + continue + if not isinstance(entry[2], int): + continue + + method, route, size = entry + route = r"/plugin/{name}/{route}".format( + name=name, + route=route if not route.startswith("/") else route[1:], + ) + + self._logger.debug( + "Adding maximum body size of {size}B for {method} requests to {route})".format( + **locals() + ) + ) + max_body_sizes.append((method, route, size)) + + self._stop_intermediary_server() + + # initialize and bind the server + trusted_downstream = self._settings.get( + ["server", "reverseProxy", "trustedDownstream"] + ) + if not isinstance(trusted_downstream, list): + self._logger.warning( + "server.reverseProxy.trustedDownstream is not a list, skipping" + ) + trusted_downstreams = [] + + server_kwargs = { + "max_body_sizes": max_body_sizes, + "default_max_body_size": self._settings.getInt(["server", "maxSize"]), + "xheaders": True, + "trusted_downstream": trusted_downstream, + } + if sys.platform == "win32": + # set 10min idle timeout under windows to hopefully make #2916 less likely + server_kwargs.update({"idle_connection_timeout": 600}) + + self._server = util.tornado.CustomHTTPServer(self._tornado_app, **server_kwargs) + + listening_address = self._host + if self._host == "::" and not self._v6_only: + # special case - tornado only listens on v4 _and_ v6 if we use None as address + listening_address = None + + self._server.listen(self._port, address=listening_address) + + ### From now on it's ok to launch subprocesses again + + eventManager.fire(events.Events.STARTUP) + + # analysis backlog + fileManager.process_backlog() + + # auto connect + if self._settings.getBoolean(["serial", "autoconnect"]): + self._logger.info( + "Autoconnect on startup is configured, trying to connect to the printer..." + ) + try: + (port, baudrate) = ( + self._settings.get(["serial", "port"]), + self._settings.getInt(["serial", "baudrate"]), + ) + printer_profile = printerProfileManager.get_default() + connectionOptions = printer.__class__.get_connection_options() + if port in connectionOptions["ports"] or port == "AUTO" or port is None: + self._logger.info( + "Trying to connect to configured serial port {}".format(port) + ) + printer.connect( + port=port, + baudrate=baudrate, + profile=printer_profile["id"] + if "id" in printer_profile + else "_default", + ) + else: + self._logger.info( + "Could not find configured serial port {} in the system, cannot automatically connect to a non existing printer. Is it plugged in and booted up yet?" + ) + except Exception: + self._logger.exception( + "Something went wrong while attempting to automatically connect to the printer" + ) + + # start up watchdogs + try: + watched = self._settings.getBaseFolder("watched") + watchdog_handler = util.watchdog.GcodeWatchdogHandler(fileManager, printer) + watchdog_handler.initial_scan(watched) + + if self._settings.getBoolean(["feature", "pollWatched"]): + # use less performant polling observer if explicitly configured + observer = PollingObserver() + else: + # use os default + observer = Observer() + + observer.schedule(watchdog_handler, watched, recursive=True) + observer.start() + except Exception: + self._logger.exception("Error starting watched folder observer") + + # run our startup plugins + octoprint.plugin.call_plugin( + octoprint.plugin.StartupPlugin, + "on_startup", + args=(self._host, self._port), + sorting_context="StartupPlugin.on_startup", + ) + + def call_on_startup(name, plugin): + implementation = plugin.get_implementation(octoprint.plugin.StartupPlugin) + if implementation is None: + return + implementation.on_startup(self._host, self._port) + + pluginLifecycleManager.add_callback("enabled", call_on_startup) + + # prepare our after startup function + def on_after_startup(): + if self._host == "::": + if self._v6_only: + # only v6 + self._logger.info( + "Listening on http://[::]:{port}".format(port=self._port) + ) + else: + # all v4 and v6 + self._logger.info( + "Listening on http://0.0.0.0:{port} and http://[::]:{port}".format( + port=self._port + ) + ) + else: + self._logger.info( + "Listening on http://{}:{}".format( + self._host if not ":" in self._host else "[" + self._host + "]", + self._port, + ) + ) + + if safe_mode and self._settings.getBoolean(["server", "startOnceInSafeMode"]): + self._logger.info( + "Server started successfully in safe mode as requested from config, removing flag" + ) + self._settings.setBoolean(["server", "startOnceInSafeMode"], False) + self._settings.save() + + # now this is somewhat ugly, but the issue is the following: startup plugins might want to do things for + # which they need the server to be already alive (e.g. for being able to resolve urls, such as favicons + # or service xmls or the like). While they are working though the ioloop would block. Therefore we'll + # create a single use thread in which to perform our after-startup-tasks, start that and hand back + # control to the ioloop + def work(): + octoprint.plugin.call_plugin( + octoprint.plugin.StartupPlugin, + "on_after_startup", + sorting_context="StartupPlugin.on_after_startup", + ) + + def call_on_after_startup(name, plugin): + implementation = plugin.get_implementation( + octoprint.plugin.StartupPlugin + ) + if implementation is None: + return + implementation.on_after_startup() + + pluginLifecycleManager.add_callback("enabled", call_on_after_startup) + + # if there was a rogue plugin we wouldn't even have made it here, so remove startup triggered safe mode + # flag again... + self._settings.setBoolean(["server", "incompleteStartup"], False) + self._settings.save() + + # make a backup of the current config + self._settings.backup(ext="backup") + + # when we are through with that we also run our preemptive cache + if settings().getBoolean(["devel", "cache", "preemptive"]): + self._execute_preemptive_flask_caching(preemptiveCache) + + import threading + + threading.Thread(target=work).start() + + ioloop.add_callback(on_after_startup) + + # prepare our shutdown function + def on_shutdown(): + # will be called on clean system exit and shutdown the watchdog observer and call the on_shutdown methods + # on all registered ShutdownPlugins + self._logger.info("Shutting down...") + observer.stop() + observer.join() + eventManager.fire(events.Events.SHUTDOWN) + + self._logger.info("Calling on_shutdown on plugins") + octoprint.plugin.call_plugin( + octoprint.plugin.ShutdownPlugin, + "on_shutdown", + sorting_context="ShutdownPlugin.on_shutdown", + ) + + # wait for shutdown event to be processed, but maximally for 15s + event_timeout = 15.0 + if eventManager.join(timeout=event_timeout): + self._logger.warning( + "Event loop was still busy processing after {}s, shutting down anyhow".format( + event_timeout + ) + ) + + if self._octoprint_daemon is not None: + self._logger.info("Cleaning up daemon pidfile") + self._octoprint_daemon.terminated() + + self._logger.info("Goodbye!") + + atexit.register(on_shutdown) + + def sigterm_handler(*args, **kwargs): + # will stop tornado on SIGTERM, making the program exit cleanly + def shutdown_tornado(): + self._logger.debug("Shutting down tornado's IOLoop...") + ioloop.stop() + + self._logger.debug("SIGTERM received...") + ioloop.add_callback_from_signal(shutdown_tornado) + + signal.signal(signal.SIGTERM, sigterm_handler) + + try: + # this is the main loop - as long as tornado is running, OctoPrint is running + ioloop.start() + self._logger.debug("Tornado's IOLoop stopped") + except (KeyboardInterrupt, SystemExit): + pass + except Exception: + self._logger.fatal( + "Now that is embarrassing... Something really really went wrong here. Please report this including the stacktrace below in OctoPrint's bugtracker. Thanks!" + ) + self._logger.exception("Stacktrace follows:") + + def _create_socket_connection(self, session): + global printer, fileManager, analysisQueue, userManager, eventManager + return util.sockjs.PrinterStateConnection( + printer, + fileManager, + analysisQueue, + userManager, + groupManager, + eventManager, + pluginManager, + session, + ) + + def _check_for_root(self): + if "geteuid" in dir(os) and os.geteuid() == 0: + exit("You should not run OctoPrint as root!") + + def _get_locale(self): + global LANGUAGES + + if "l10n" in request.values: + return Locale.negotiate([request.values["l10n"]], LANGUAGES) + + if "X-Locale" in request.headers: + return Locale.negotiate([request.headers["X-Locale"]], LANGUAGES) + + if hasattr(g, "identity") and g.identity and userManager.enabled: + userid = g.identity.id + try: + user_language = userManager.get_user_setting( + userid, ("interface", "language") + ) + if user_language is not None and not user_language == "_default": + return Locale.negotiate([user_language], LANGUAGES) + except octoprint.access.users.UnknownUser: + pass + + default_language = self._settings.get(["appearance", "defaultLanguage"]) + if ( + default_language is not None + and not default_language == "_default" + and default_language in LANGUAGES + ): + return Locale.negotiate([default_language], LANGUAGES) + + return Locale.parse(request.accept_languages.best_match(LANGUAGES)) + + def _setup_heartbeat_logging(self): + logger = logging.getLogger(__name__ + ".heartbeat") + + def log_heartbeat(): + logger.info("Server heartbeat <3") + + interval = settings().getFloat(["server", "heartbeat"]) + logger.info("Starting server heartbeat, {}s interval".format(interval)) + + timer = octoprint.util.RepeatedTimer(interval, log_heartbeat) + timer.start() + + def _setup_app(self, app): + from octoprint.server.util.flask import ( + ReverseProxiedEnvironment, + OctoPrintFlaskRequest, + OctoPrintFlaskResponse, + OctoPrintJsonEncoder, + OctoPrintSessionInterface, + ) + + s = settings() + + # setup octoprint's flask json serialization/deserialization + app.json_encoder = OctoPrintJsonEncoder + + app.debug = self._debug + app.config["TEMPLATES_AUTO_RELOAD"] = True + app.config["JSONIFY_PRETTYPRINT_REGULAR"] = False + + secret_key = s.get(["server", "secretKey"]) + if not secret_key: + import string + from random import choice + + chars = string.ascii_lowercase + string.ascii_uppercase + string.digits + secret_key = "".join(choice(chars) for _ in range(32)) + s.set(["server", "secretKey"], secret_key) + s.save() + + app.secret_key = secret_key + + reverse_proxied = ReverseProxiedEnvironment( + header_prefix=s.get(["server", "reverseProxy", "prefixHeader"]), + header_scheme=s.get(["server", "reverseProxy", "schemeHeader"]), + header_host=s.get(["server", "reverseProxy", "hostHeader"]), + header_server=s.get(["server", "reverseProxy", "serverHeader"]), + header_port=s.get(["server", "reverseProxy", "portHeader"]), + prefix=s.get(["server", "reverseProxy", "prefixFallback"]), + scheme=s.get(["server", "reverseProxy", "schemeFallback"]), + host=s.get(["server", "reverseProxy", "hostFallback"]), + server=s.get(["server", "reverseProxy", "serverFallback"]), + port=s.get(["server", "reverseProxy", "portFallback"]), + ) + + OctoPrintFlaskRequest.environment_wrapper = reverse_proxied + app.request_class = OctoPrintFlaskRequest + app.response_class = OctoPrintFlaskResponse + app.session_interface = OctoPrintSessionInterface() + + @app.before_request + def before_request(): + g.locale = self._get_locale() + if self._debug and "perfprofile" in request.args: + try: + from pyinstrument import Profiler + + g.perfprofiler = Profiler() + g.perfprofiler.start() + except ImportError: + # profiler dependency not installed, ignore + pass + + @app.after_request + def after_request(response): + # send no-cache headers with all POST responses + if request.method == "POST": + response.cache_control.no_cache = True + + response.headers.add("X-Clacks-Overhead", "GNU Terry Pratchett") + + if hasattr(g, "perfprofiler"): + g.perfprofiler.stop() + output_html = g.perfprofiler.output_html() + return make_response(output_html) + + return response + + from octoprint.util.jinja import MarkdownFilter + + MarkdownFilter(app) + + def _setup_i18n(self, app): + global babel + global LOCALES + global LANGUAGES + + babel = Babel(app) + + def get_available_locale_identifiers(locales): + result = set() + + # add available translations + for locale in locales: + result.add(locale.language) + if locale.territory: + # if a territory is specified, add that too + result.add("%s_%s" % (locale.language, locale.territory)) + + return result + + LOCALES = babel.list_translations() + LANGUAGES = get_available_locale_identifiers(LOCALES) + + @babel.localeselector + def get_locale(): + return self._get_locale() + + def _setup_jinja2(self): + import re + + app.jinja_env.add_extension("jinja2.ext.do") + app.jinja_env.add_extension("octoprint.util.jinja.trycatch") + + def regex_replace(s, find, replace): + return re.sub(find, replace, s) + + html_header_regex = re.compile( + r"[1-6])>(?P.*?)" + ) + + def offset_html_headers(s, offset): + def repl(match): + number = int(match.group("number")) + number += offset + if number > 6: + number = 6 + elif number < 1: + number = 1 + return "{content}".format( + number=number, content=match.group("content") + ) + + return html_header_regex.sub(repl, s) + + markdown_header_regex = re.compile( + r"^(?P#+)\s+(?P.*)$", flags=re.MULTILINE + ) + + def offset_markdown_headers(s, offset): + def repl(match): + number = len(match.group("hashs")) + number += offset + if number > 6: + number = 6 + elif number < 1: + number = 1 + return "{hashs} {content}".format( + hashs="#" * number, content=match.group("content") + ) + + return markdown_header_regex.sub(repl, s) + + html_link_regex = re.compile(r"<(?Pa.*?)>(?P.*?)") + + def externalize_links(text): + def repl(match): + tag = match.group("tag") + if not "href" in tag: + return match.group(0) + + if not "target=" in tag and not "rel=" in tag: + tag += ' target="_blank" rel="noreferrer noopener"' + + content = match.group("content") + return "<{tag}>{content}".format(tag=tag, content=content) + + return html_link_regex.sub(repl, text) + + single_quote_regex = re.compile("(? cutoff_timestamp + + def filter_http_entries(entry): + """Returns True for entries targeting http or https.""" + return ( + "base_url" in entry + and entry["base_url"] + and ( + entry["base_url"].startswith("http://") + or entry["base_url"].startswith("https://") + ) + ) + + def filter_entries(entry): + """Combined filter.""" + filters = (filter_current_entries, filter_http_entries) + return all([f(entry) for f in filters]) + + # filter out all old and non-http entries + cache_data = preemptive_cache.clean_all_data( + lambda root, entries: list(filter(filter_entries, entries)) + ) + if not cache_data: + return + + def execute_caching(): + logger = logging.getLogger(__name__ + ".preemptive_cache") + + for route in sorted(cache_data.keys(), key=lambda x: (x.count("/"), x)): + entries = reversed( + sorted(cache_data[route], key=lambda x: x.get("_count", 0)) + ) + for kwargs in entries: + plugin = kwargs.get("plugin", None) + if plugin: + try: + plugin_info = pluginManager.get_plugin_info( + plugin, require_enabled=True + ) + if plugin_info is None: + logger.info( + "About to preemptively cache plugin {} but it is not installed or enabled, preemptive caching makes no sense".format( + plugin + ) + ) + continue + + implementation = plugin_info.implementation + if implementation is None or not isinstance( + implementation, octoprint.plugin.UiPlugin + ): + logger.info( + "About to preemptively cache plugin {} but it is not a UiPlugin, preemptive caching makes no sense".format( + plugin + ) + ) + continue + if not implementation.get_ui_preemptive_caching_enabled(): + logger.info( + "About to preemptively cache plugin {} but it has disabled preemptive caching".format( + plugin + ) + ) + continue + except Exception: + logger.exception( + "Error while trying to check if plugin {} has preemptive caching enabled, skipping entry" + ) + continue + + additional_request_data = kwargs.get("_additional_request_data", {}) + kwargs = dict( + (k, v) + for k, v in kwargs.items() + if not k.startswith("_") and not k == "plugin" + ) + kwargs.update(additional_request_data) + + try: + start = octoprint.util.monotonic_time() + if plugin: + logger.info( + "Preemptively caching {} (ui {}) for {!r}".format( + route, plugin, kwargs + ) + ) + else: + logger.info( + "Preemptively caching {} (ui _default) for {!r}".format( + route, kwargs + ) + ) + + headers = kwargs.get("headers", {}) + headers["X-Force-View"] = plugin if plugin else "_default" + headers["X-Preemptive-Recording"] = "yes" + kwargs["headers"] = headers + + builder = EnvironBuilder(**kwargs) + app(builder.get_environ(), lambda *a, **kw: None) + + logger.info( + "... done in {:.2f}s".format( + octoprint.util.monotonic_time() - start + ) + ) + except Exception: + logger.exception( + "Error while trying to preemptively cache {} for {!r}".format( + route, kwargs + ) + ) + + # asynchronous caching + import threading + + cache_thread = threading.Thread( + target=execute_caching, name="Preemptive Cache Worker" + ) + cache_thread.daemon = True + cache_thread.start() + + def _register_template_plugins(self): + template_plugins = pluginManager.get_implementations( + octoprint.plugin.TemplatePlugin + ) + for plugin in template_plugins: + try: + self._register_additional_template_plugin(plugin) + except Exception: + self._logger.exception( + "Error while trying to register templates of plugin {}, ignoring it".format( + plugin._identifier + ) + ) + + def _register_additional_template_plugin(self, plugin): + folder = plugin.get_template_folder() + if folder is not None and not folder in self._template_searchpaths: + self._template_searchpaths.append(folder) + + def _unregister_additional_template_plugin(self, plugin): + folder = plugin.get_template_folder() + if folder is not None and folder in self._template_searchpaths: + self._template_searchpaths.remove(folder) + + def _setup_blueprints(self): + from octoprint.server.api import api + import octoprint.server.views # do not remove or the index view won't be found + + blueprints = OrderedDict() + blueprints["/api"] = api + + # also register any blueprints defined in BlueprintPlugins + blueprints.update(self._prepare_blueprint_plugins()) + + # and register a blueprint for serving the static files of asset plugins which are not blueprint plugins themselves + blueprints.update(self._prepare_asset_plugins()) + + # make sure all before/after_request hook results are attached as well + self._add_plugin_request_handlers_to_blueprints(*blueprints.values()) + + # register everything with the system + for url_prefix, blueprint in blueprints.items(): + app.register_blueprint(blueprint, url_prefix=url_prefix) + + def _prepare_blueprint_plugins(self): + blueprints = OrderedDict() + + blueprint_plugins = octoprint.plugin.plugin_manager().get_implementations( + octoprint.plugin.BlueprintPlugin + ) + for plugin in blueprint_plugins: + try: + blueprint, prefix = self._prepare_blueprint_plugin(plugin) + blueprints[prefix] = blueprint + except Exception: + self._logger.exception( + "Error while registering blueprint of " + "plugin {}, ignoring it".format(plugin._identifier), + extra={"plugin": plugin._identifier}, + ) + continue + + return blueprints + + def _prepare_asset_plugins(self): + blueprints = OrderedDict() + + asset_plugins = octoprint.plugin.plugin_manager().get_implementations( + octoprint.plugin.AssetPlugin + ) + for plugin in asset_plugins: + if isinstance(plugin, octoprint.plugin.BlueprintPlugin): + continue + try: + blueprint, prefix = self._prepare_asset_plugin(plugin) + blueprints[prefix] = blueprint + except Exception: + self._logger.exception( + "Error while registering assets of plugin " + "{}, ignoring it".format(plugin._identifier), + extra={"plugin": plugin._identifier}, + ) + continue + + return blueprints + + def _prepare_blueprint_plugin(self, plugin): + name = plugin._identifier + blueprint = plugin.get_blueprint() + if blueprint is None: + return + + blueprint.before_request(corsRequestHandler) + blueprint.before_request(loginFromApiKeyRequestHandler) + blueprint.after_request(corsResponseHandler) + + if plugin.is_blueprint_protected(): + blueprint.before_request(requireLoginRequestHandler) + + url_prefix = "/plugin/{name}".format(name=name) + app.register_blueprint(blueprint, url_prefix=url_prefix) + + if self._logger: + self._logger.debug( + "Registered API of plugin {name} under URL prefix {url_prefix}".format( + name=name, url_prefix=url_prefix + ) + ) + + return blueprint, url_prefix + + def _prepare_asset_plugin(self, plugin): + name = plugin._identifier + + url_prefix = "/plugin/{name}".format(name=name) + blueprint = Blueprint( + "plugin." + name, name, static_folder=plugin.get_asset_folder() + ) + app.register_blueprint(blueprint, url_prefix=url_prefix) + + if self._logger: + self._logger.debug( + "Registered assets of plugin {name} under URL prefix {url_prefix}".format( + name=name, url_prefix=url_prefix + ) + ) + + return blueprint, url_prefix + + def _add_plugin_request_handlers_to_blueprints(self, *blueprints): + before_hooks = octoprint.plugin.plugin_manager().get_hooks( + "octoprint.server.api.before_request" + ) + after_hooks = octoprint.plugin.plugin_manager().get_hooks( + "octoprint.server.api.after_request" + ) + + for name, hook in before_hooks.items(): + plugin = octoprint.plugin.plugin_manager().get_plugin(name) + for blueprint in blueprints: + try: + result = hook(plugin=plugin) + if isinstance(result, (list, tuple)): + for h in result: + blueprint.before_request(h) + except Exception: + self._logger.exception( + "Error processing before_request hooks from plugin {}".format( + plugin + ), + extra={"plugin": name}, + ) + + for name, hook in after_hooks.items(): + plugin = octoprint.plugin.plugin_manager().get_plugin(name) + for blueprint in blueprints: + try: + result = hook(plugin=plugin) + if isinstance(result, (list, tuple)): + for h in result: + blueprint.after_request(h) + except Exception: + self._logger.exception( + "Error processing after_request hooks from plugin {}".format( + plugin + ), + extra={"plugin": name}, + ) + + def _setup_mimetypes(self): + # Safety measures for Windows... apparently the mimetypes module takes its translation from the windows + # registry, and if for some weird reason that gets borked the reported MIME types can be all over the place. + # Since at least in Chrome that can cause hilarious issues with JS files (refusal to run them and thus a + # borked UI) we make sure that .js always maps to the correct application/javascript, and also throw in a + # .css -> text/css for good measure. + # + # See #3367 + mimetypes.add_type("application/javascript", ".js") + mimetypes.add_type("text/css", ".css") + + def _setup_assets(self): + global app + global assets + global pluginManager + + util.flask.fix_webassets_cache() + util.flask.fix_webassets_filtertool() + + base_folder = self._settings.getBaseFolder("generated") + + # clean the folder + if self._settings.getBoolean(["devel", "webassets", "clean_on_startup"]): + import shutil + import errno + + for entry in ("webassets", ".webassets-cache"): + path = os.path.join(base_folder, entry) + + # delete path if it exists + if os.path.isdir(path): + try: + self._logger.debug("Deleting {path}...".format(**locals())) + shutil.rmtree(path) + except Exception: + self._logger.exception( + "Error while trying to delete {path}, " + "leaving it alone".format(**locals()) + ) + 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 + + 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()) + ) + pass + else: + # this will only get executed if we never did + # successfully execute makedirs above + self._logger.exception(error_text) + continue + else: + # not an access error, 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())) + + AdjustedEnvironment = type(Environment)( + Environment.__name__, + (Environment,), + {"resolver_class": util.flask.PluginAssetResolver}, + ) + + class CustomDirectoryEnvironment(AdjustedEnvironment): + @property + def directory(self): + return base_folder + + assets = CustomDirectoryEnvironment(app) + assets.debug = not self._settings.getBoolean(["devel", "webassets", "bundle"]) + + UpdaterType = type(util.flask.SettingsCheckUpdater)( + util.flask.SettingsCheckUpdater.__name__, + (util.flask.SettingsCheckUpdater,), + {"updater": assets.updater}, + ) + assets.updater = UpdaterType + + preferred_stylesheet = self._settings.get(["devel", "stylesheet"]) + + dynamic_core_assets = util.flask.collect_core_assets() + dynamic_plugin_assets = util.flask.collect_plugin_assets( + preferred_stylesheet=preferred_stylesheet + ) + + js_libs = [ + "js/lib/jquery/jquery.min.js", + "js/lib/modernizr.custom.js", + "js/lib/lodash.min.js", + "js/lib/sprintf.min.js", + "js/lib/knockout.js", + "js/lib/knockout.mapping-latest.js", + "js/lib/babel.js", + "js/lib/avltree.js", + "js/lib/bootstrap/bootstrap.js", + "js/lib/bootstrap/bootstrap-modalmanager.js", + "js/lib/bootstrap/bootstrap-modal.js", + "js/lib/bootstrap/bootstrap-slider.js", + "js/lib/bootstrap/bootstrap-tabdrop.js", + "js/lib/jquery/jquery.ui.core.js", + "js/lib/jquery/jquery.ui.widget.js", + "js/lib/jquery/jquery.ui.mouse.js", + "js/lib/jquery/jquery.flot.js", + "js/lib/jquery/jquery.flot.time.js", + "js/lib/jquery/jquery.flot.crosshair.js", + "js/lib/jquery/jquery.flot.resize.js", + "js/lib/jquery/jquery.iframe-transport.js", + "js/lib/jquery/jquery.fileupload.js", + "js/lib/jquery/jquery.slimscroll.min.js", + "js/lib/jquery/jquery.qrcode.min.js", + "js/lib/jquery/jquery.bootstrap.wizard.js", + "js/lib/pnotify/pnotify.core.min.js", + "js/lib/pnotify/pnotify.buttons.min.js", + "js/lib/pnotify/pnotify.callbacks.min.js", + "js/lib/pnotify/pnotify.confirm.min.js", + "js/lib/pnotify/pnotify.desktop.min.js", + "js/lib/pnotify/pnotify.history.min.js", + "js/lib/pnotify/pnotify.mobile.min.js", + "js/lib/pnotify/pnotify.nonblock.min.js", + "js/lib/pnotify/pnotify.reference.min.js", + "js/lib/pnotify/pnotify.tooltip.min.js", + "js/lib/pnotify/pnotify.maxheight.js", + "js/lib/moment-with-locales.min.js", + "js/lib/pusher.color.min.js", + "js/lib/detectmobilebrowser.js", + "js/lib/md5.min.js", + "js/lib/bootstrap-slider-knockout-binding.js", + "js/lib/loglevel.min.js", + "js/lib/sockjs.min.js", + "js/lib/ResizeSensor.js", + "js/lib/less.min.js", + "js/lib/hls.js", + ] + js_client = [ + "js/app/client/base.js", + "js/app/client/socket.js", + "js/app/client/browser.js", + "js/app/client/connection.js", + "js/app/client/control.js", + "js/app/client/files.js", + "js/app/client/job.js", + "js/app/client/languages.js", + "js/app/client/printer.js", + "js/app/client/printerprofiles.js", + "js/app/client/settings.js", + "js/app/client/slicing.js", + "js/app/client/system.js", + "js/app/client/timelapse.js", + "js/app/client/users.js", + "js/app/client/util.js", + "js/app/client/wizard.js", + "js/app/client/access.js", + ] + + css_libs = [ + "css/bootstrap.min.css", + "css/bootstrap-modal.css", + "css/bootstrap-slider.css", + "css/bootstrap-tabdrop.css", + "vendor/font-awesome-3.2.1/css/font-awesome.min.css", + "vendor/font-awesome-4.7.0/css/font-awesome.min.css", + "css/jquery.fileupload-ui.css", + "css/pnotify.core.min.css", + "css/pnotify.buttons.min.css", + "css/pnotify.history.min.css", + ] + + # a couple of custom filters + from octoprint.server.util.webassets import ( + LessImportRewrite, + JsDelimiterBundler, + SourceMapRewrite, + SourceMapRemove, + JsPluginBundle, + GzipFile, + ) + from webassets.filter import register_filter + + register_filter(LessImportRewrite) + register_filter(SourceMapRewrite) + register_filter(SourceMapRemove) + register_filter(JsDelimiterBundler) + register_filter(GzipFile) + + def all_assets_for_plugins(collection): + """Gets all plugin assets for a dict of plugin->assets""" + result = [] + for assets in collection.values(): + result += assets + return result + + # -- JS -------------------------------------------------------------------------------------------------------- + + filters = ["sourcemap_remove", "js_delimiter_bundler"] + if self._settings.getBoolean(["devel", "webassets", "minify"]): + filters.append("rjsmin") + filters.append("gzip") + + js_filters = filters + if self._settings.getBoolean(["devel", "webassets", "minify_plugins"]): + js_plugin_filters = js_filters + else: + js_plugin_filters = [x for x in js_filters if x not in ("rjsmin",)] + + def js_bundles_for_plugins(collection, filters=None): + """Produces JsPluginBundle instances that output IIFE wrapped assets""" + result = OrderedDict() + for plugin, assets in collection.items(): + if len(assets): + result[plugin] = JsPluginBundle(plugin, *assets, filters=filters) + return result + + js_core = ( + dynamic_core_assets["js"] + + all_assets_for_plugins(dynamic_plugin_assets["bundled"]["js"]) + + ["js/app/dataupdater.js", "js/app/helpers.js", "js/app/main.js"] + ) + js_plugins = js_bundles_for_plugins( + dynamic_plugin_assets["external"]["js"], filters="js_delimiter_bundler" + ) + + clientjs_core = dynamic_core_assets["clientjs"] + all_assets_for_plugins( + dynamic_plugin_assets["bundled"]["clientjs"] + ) + clientjs_plugins = js_bundles_for_plugins( + dynamic_plugin_assets["external"]["clientjs"], filters="js_delimiter_bundler" + ) + + js_libs_bundle = Bundle( + *js_libs, output="webassets/packed_libs.js", filters=",".join(js_filters) + ) + + js_core_bundle = Bundle( + *js_core, output="webassets/packed_core.js", filters=",".join(js_filters) + ) + + if len(js_plugins) == 0: + js_plugins_bundle = Bundle(*[]) + else: + js_plugins_bundle = Bundle( + *js_plugins.values(), + output="webassets/packed_plugins.js", + filters=",".join(js_plugin_filters) + ) + + js_app_bundle = Bundle( + js_plugins_bundle, + js_core_bundle, + output="webassets/packed_app.js", + filters=",".join(js_plugin_filters), + ) + + js_client_core_bundle = Bundle( + *clientjs_core, + output="webassets/packed_client_core.js", + filters=",".join(js_filters) + ) + + if len(clientjs_plugins) == 0: + js_client_plugins_bundle = Bundle(*[]) + else: + js_client_plugins_bundle = Bundle( + *clientjs_plugins.values(), + output="webassets/packed_client_plugins.js", + filters=",".join(js_plugin_filters) + ) + + js_client_bundle = Bundle( + js_client_core_bundle, + js_client_plugins_bundle, + output="webassets/packed_client.js", + filters=",".join(js_plugin_filters), + ) + + # -- CSS ------------------------------------------------------------------------------------------------------- + + css_filters = ["cssrewrite", "gzip"] + + css_core = list(dynamic_core_assets["css"]) + all_assets_for_plugins( + dynamic_plugin_assets["bundled"]["css"] + ) + css_plugins = list( + all_assets_for_plugins(dynamic_plugin_assets["external"]["css"]) + ) + + css_libs_bundle = Bundle( + *css_libs, output="webassets/packed_libs.css", filters=",".join(css_filters) + ) + + if len(css_core) == 0: + css_core_bundle = Bundle(*[]) + else: + css_core_bundle = Bundle( + *css_core, + output="webassets/packed_core.css", + filters=",".join(css_filters) + ) + + if len(css_plugins) == 0: + css_plugins_bundle = Bundle(*[]) + else: + css_plugins_bundle = Bundle( + *css_plugins, + output="webassets/packed_plugins.css", + filters=",".join(css_filters) + ) + + css_app_bundle = Bundle( + css_core, + css_plugins, + output="webassets/packed_app.css", + filters=",".join(css_filters), + ) + + # -- LESS ------------------------------------------------------------------------------------------------------ + + less_filters = ["cssrewrite", "less_importrewrite", "gzip"] + + less_core = list(dynamic_core_assets["less"]) + all_assets_for_plugins( + dynamic_plugin_assets["bundled"]["less"] + ) + less_plugins = all_assets_for_plugins(dynamic_plugin_assets["external"]["less"]) + + if len(less_core) == 0: + less_core_bundle = Bundle(*[]) + else: + less_core_bundle = Bundle( + *less_core, + output="webassets/packed_core.less", + filters=",".join(less_filters) + ) + + if len(less_plugins) == 0: + less_plugins_bundle = Bundle(*[]) + else: + less_plugins_bundle = Bundle( + *less_plugins, + output="webassets/packed_plugins.less", + filters=",".join(less_filters) + ) + + less_app_bundle = Bundle( + less_core, + less_plugins, + output="webassets/packed_app.less", + filters=",".join(less_filters), + ) + + # -- asset registration ---------------------------------------------------------------------------------------- + + assets.register("js_libs", js_libs_bundle) + assets.register("js_client_core", js_client_core_bundle) + for plugin, bundle in clientjs_plugins.items(): + # register our collected clientjs plugin bundles so that they are bound to the environment + assets.register("js_client_plugin_{}".format(plugin), bundle) + assets.register("js_client_plugins", js_client_plugins_bundle) + assets.register("js_client", js_client_bundle) + assets.register("js_core", js_core_bundle) + for plugin, bundle in js_plugins.items(): + # register our collected plugin bundles so that they are bound to the environment + assets.register("js_plugin_{}".format(plugin), bundle) + assets.register("js_plugins", js_plugins_bundle) + assets.register("js_app", js_app_bundle) + assets.register("css_libs", css_libs_bundle) + assets.register("css_core", css_core_bundle) + assets.register("css_plugins", css_plugins_bundle) + assets.register("css_app", css_app_bundle) + assets.register("less_core", less_core_bundle) + assets.register("less_plugins", less_plugins_bundle) + assets.register("less_app", less_app_bundle) + + def _setup_login_manager(self): + global loginManager + + loginManager = LoginManager() + + # "strong" is incompatible to remember me, see maxcountryman/flask-login#156. It also causes issues with + # clients toggling between IPv4 and IPv6 client addresses due to names being resolved one way or the other as + # at least observed on a Win10 client targeting "localhost", resolved as both "127.0.0.1" and "::1" + loginManager.session_protection = "basic" + + loginManager.user_loader(load_user) + loginManager.unauthorized_handler(unauthorized_user) + loginManager.anonymous_user = userManager.anonymous_user_factory + loginManager.request_loader(load_user_from_request) + + loginManager.init_app(app, add_context_processor=False) + + def _start_intermediary_server(self): + try: + # noinspection PyCompatibility + from http.server import HTTPServer, BaseHTTPRequestHandler + except ImportError: + # noinspection PyCompatibility + from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler + + import threading + import socket + + host = self._host + port = self._port + + class IntermediaryServerHandler(BaseHTTPRequestHandler): + def __init__(self, rules=None, *args, **kwargs): + if rules is None: + rules = [] + self.rules = rules + BaseHTTPRequestHandler.__init__(self, *args, **kwargs) + + def do_GET(self): + request_path = self.path + if "?" in request_path: + request_path = request_path[0 : request_path.find("?")] + + for rule in self.rules: + path, data, content_type = rule + if request_path == path: + self.send_response(200) + if content_type: + self.send_header("Content-Type", content_type) + self.end_headers() + if isinstance(data, unicode): + data = data.encode("utf-8") + self.wfile.write(data) + break + else: + self.send_response(404) + self.wfile.write("Not found".encode("utf-8")) + + base_path = os.path.realpath( + os.path.join(os.path.dirname(__file__), "..", "static") + ) + rules = [ + ( + "/", + [ + "intermediary.html", + ], + "text/html", + ), + ("/favicon.ico", ["img", "tentacle-20x20.png"], "image/png"), + ( + "/intermediary.gif", + bytes( + base64.b64decode( + "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" + ) + ), + "image/gif", + ), + ] + + def contents(args): + path = os.path.join(base_path, *args) + if not os.path.isfile(path): + return "" + + with io.open(path, "rb") as f: + data = f.read() + return data + + def process(rule): + if len(rule) == 2: + path, data = rule + content_type = None + else: + path, data, content_type = rule + + if isinstance(data, (list, tuple)): + data = contents(data) + + return path, data, content_type + + rules = list( + map(process, filter(lambda rule: len(rule) == 2 or len(rule) == 3, rules)) + ) + + HTTPServerV4 = HTTPServer + + class HTTPServerV6(HTTPServer): + address_family = socket.AF_INET6 + + class HTTPServerV6SingleStack(HTTPServerV6): + def __init__(self, *args, **kwargs): + HTTPServerV6.__init__(self, *args, **kwargs) + + # explicitly set V6ONLY flag - seems to be the default, but just to make sure... + self.socket.setsockopt( + octoprint.util.net.IPPROTO_IPV6, octoprint.util.net.IPV6_V6ONLY, 1 + ) + + class HTTPServerV6DualStack(HTTPServerV6): + def __init__(self, *args, **kwargs): + HTTPServerV6.__init__(self, *args, **kwargs) + + # explicitly unset V6ONLY flag + self.socket.setsockopt( + octoprint.util.net.IPPROTO_IPV6, octoprint.util.net.IPV6_V6ONLY, 0 + ) + + if ":" in host: + # v6 + if host == "::" and not self._v6_only: + ServerClass = HTTPServerV6DualStack + else: + ServerClass = HTTPServerV6SingleStack + else: + # v4 + ServerClass = HTTPServerV4 + + if host == "::": + if self._v6_only: + self._logger.debug( + "Starting intermediary server on http://[::]:{port}".format(port=port) + ) + else: + self._logger.debug( + "Starting intermediary server on http://0.0.0.0:{port} and http://[::]:{port}".format( + port=port + ) + ) + else: + self._logger.debug( + "Starting intermediary server on http://{}:{}".format( + host if not ":" in host else "[" + host + "]", port + ) + ) + + self._intermediary_server = ServerClass( + (host, port), + lambda *args, **kwargs: IntermediaryServerHandler(rules, *args, **kwargs), + bind_and_activate=False, + ) + + # if possible, make sure our socket's port descriptor isn't handed over to subprocesses + from octoprint.util.platform import set_close_exec + + try: + set_close_exec(self._intermediary_server.fileno()) + except Exception: + self._logger.exception( + "Error while attempting to set_close_exec on intermediary server socket" + ) + + # then bind the server and have it serve our handler until stopped + try: + self._intermediary_server.server_bind() + self._intermediary_server.server_activate() + except Exception: + self._intermediary_server.server_close() + raise + + def serve(): + try: + self._intermediary_server.serve_forever() + except Exception: + self._logger.exception("Error in intermediary server") + + thread = threading.Thread(target=serve) + thread.daemon = True + thread.start() + + self._logger.info("Intermediary server started") + + def _stop_intermediary_server(self): + if self._intermediary_server is None: + return + self._logger.info("Shutting down intermediary server...") + self._intermediary_server.shutdown() + self._intermediary_server.server_close() + self._logger.info("Intermediary server shut down") + + def _setup_plugin_permissions(self): + global pluginManager + + from octoprint.access.permissions import PluginOctoPrintPermission + + key_whitelist = re.compile(r"[A-Za-z0-9_]*") + + def permission_key(plugin, definition): + return "PLUGIN_{}_{}".format(plugin.upper(), definition["key"].upper()) + + def permission_name(plugin, definition): + return "{}: {}".format(plugin, definition["name"]) + + def permission_role(plugin, role): + return "plugin_{}_{}".format(plugin, role) + + def process_regular_permission(plugin_info, definition): + permissions = [] + for key in definition.get("permissions", []): + permission = octoprint.access.permissions.Permissions.find(key) + + if permission is None: + # if there is still no permission found, postpone this - maybe it is a permission from + # another plugin that hasn't been loaded yet + return False + + permissions.append(permission) + + roles = definition.get("roles", []) + description = definition.get("description", "") + dangerous = definition.get("dangerous", False) + default_groups = definition.get("default_groups", []) + + roles_and_permissions = [ + permission_role(plugin_info.key, role) for role in roles + ] + permissions + + key = permission_key(plugin_info.key, definition) + permission = PluginOctoPrintPermission( + permission_name(plugin_info.name, definition), + description, + plugin=plugin_info.key, + dangerous=dangerous, + default_groups=default_groups, + *roles_and_permissions + ) + setattr( + octoprint.access.permissions.Permissions, + key, + PluginOctoPrintPermission( + permission_name(plugin_info.name, definition), + description, + plugin=plugin_info.key, + dangerous=dangerous, + default_groups=default_groups, + *roles_and_permissions + ), + ) + + self._logger.info( + "Added new permission from plugin {}: {} (needs: {!r})".format( + plugin_info.key, key, ", ".join(map(repr, permission.needs)) + ) + ) + return True + + postponed = [] + + hooks = pluginManager.get_hooks("octoprint.access.permissions") + for name, factory in hooks.items(): + try: + if isinstance(factory, (tuple, list)): + additional_permissions = list(factory) + elif callable(factory): + additional_permissions = factory() + else: + raise ValueError("factory must be either a callable, tuple or list") + + if not isinstance(additional_permissions, (tuple, list)): + raise ValueError( + "factory result must be either a tuple or a list of permission definition dicts" + ) + + plugin_info = pluginManager.get_plugin_info(name) + for p in additional_permissions: + if not isinstance(p, dict): + continue + + if not "key" in p or not "name" in p: + continue + + if not key_whitelist.match(p["key"]): + self._logger.warning( + "Got permission with invalid key from plugin {}: {}".format( + name, p["key"] + ) + ) + continue + + if not process_regular_permission(plugin_info, p): + postponed.append((plugin_info, p)) + except Exception: + self._logger.exception( + "Error while creating permission instance/s from {}".format(name) + ) + + # final resolution passes + pass_number = 1 + still_postponed = [] + while len(postponed): + start_length = len(postponed) + self._logger.debug( + "Plugin permission resolution pass #{}, " + "{} unresolved permissions...".format(pass_number, start_length) + ) + + for plugin_info, definition in postponed: + if not process_regular_permission(plugin_info, definition): + still_postponed.append((plugin_info, definition)) + + self._logger.debug( + "... pass #{} done, {} permissions left to resolve".format( + pass_number, len(still_postponed) + ) + ) + + if len(still_postponed) == start_length: + # no change, looks like some stuff is unresolvable - let's bail + for plugin_info, definition in still_postponed: + self._logger.warning( + "Unable to resolve permission from {}: {!r}".format( + plugin_info.key, definition + ) + ) + break + + postponed = still_postponed + still_postponed = [] + pass_number += 1 class LifecycleManager(object): - def __init__(self, plugin_manager): - self._plugin_manager = plugin_manager + def __init__(self, plugin_manager): + self._plugin_manager = plugin_manager - self._plugin_lifecycle_callbacks = defaultdict(list) - self._logger = logging.getLogger(__name__) + self._plugin_lifecycle_callbacks = defaultdict(list) + self._logger = logging.getLogger(__name__) - def wrap_plugin_event(lifecycle_event, new_handler): - orig_handler = getattr(self._plugin_manager, "on_plugin_" + lifecycle_event) + def wrap_plugin_event(lifecycle_event, new_handler): + orig_handler = getattr(self._plugin_manager, "on_plugin_" + lifecycle_event) - def handler(*args, **kwargs): - if callable(orig_handler): - orig_handler(*args, **kwargs) - if callable(new_handler): - new_handler(*args, **kwargs) + def handler(*args, **kwargs): + if callable(orig_handler): + orig_handler(*args, **kwargs) + if callable(new_handler): + new_handler(*args, **kwargs) - return handler + return handler - def on_plugin_event_factory(lifecycle_event): - def on_plugin_event(name, plugin): - self.on_plugin_event(lifecycle_event, name, plugin) - return on_plugin_event + def on_plugin_event_factory(lifecycle_event): + def on_plugin_event(name, plugin): + self.on_plugin_event(lifecycle_event, name, plugin) - for event in ("loaded", "unloaded", "enabled", "disabled"): - wrap_plugin_event(event, on_plugin_event_factory(event)) + return on_plugin_event - def on_plugin_event(self, event, name, plugin): - for lifecycle_callback in self._plugin_lifecycle_callbacks[event]: - lifecycle_callback(name, plugin) + for event in ("loaded", "unloaded", "enabled", "disabled"): + wrap_plugin_event(event, on_plugin_event_factory(event)) - def add_callback(self, events, callback): - if isinstance(events, basestring): - events = [events] + def on_plugin_event(self, event, name, plugin): + for lifecycle_callback in self._plugin_lifecycle_callbacks[event]: + lifecycle_callback(name, plugin) - for event in events: - self._plugin_lifecycle_callbacks[event].append(callback) + def add_callback(self, events, callback): + if isinstance(events, basestring): + events = [events] - def remove_callback(self, callback, events=None): - if events is None: - for event in self._plugin_lifecycle_callbacks: - if callback in self._plugin_lifecycle_callbacks[event]: - self._plugin_lifecycle_callbacks[event].remove(callback) - else: - if isinstance(events, basestring): - events = [events] + for event in events: + self._plugin_lifecycle_callbacks[event].append(callback) - for event in events: - if callback in self._plugin_lifecycle_callbacks[event]: - self._plugin_lifecycle_callbacks[event].remove(callback) + def remove_callback(self, callback, events=None): + if events is None: + for event in self._plugin_lifecycle_callbacks: + if callback in self._plugin_lifecycle_callbacks[event]: + self._plugin_lifecycle_callbacks[event].remove(callback) + else: + if isinstance(events, basestring): + events = [events] + + for event in events: + if callback in self._plugin_lifecycle_callbacks[event]: + self._plugin_lifecycle_callbacks[event].remove(callback) diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index be25fc679..a228f872f 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -2,13 +2,22 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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 io import logging -from flask import Blueprint, request, jsonify, abort, current_app, session, make_response, g +from flask import ( + Blueprint, + request, + jsonify, + abort, + current_app, + session, + make_response, + g, +) from flask_login import login_user, logout_user, current_user from werkzeug.exceptions import HTTPException from octoprint.vendor.flask_principal import Identity, identity_changed, AnonymousIdentity @@ -19,13 +28,24 @@ import octoprint.server import octoprint.plugin from octoprint.server import NO_CONTENT from octoprint.settings import settings as s, valid_boolean_trues -from octoprint.server.util import noCachingExceptGetResponseHandler, loginFromApiKeyRequestHandler, loginFromAuthorizationHeaderRequestHandler, corsRequestHandler, corsResponseHandler -from octoprint.server.util.flask import no_firstrun_access, get_json_command_from_request, passive_login, get_remote_address +from octoprint.server.util import ( + noCachingExceptGetResponseHandler, + loginFromApiKeyRequestHandler, + loginFromAuthorizationHeaderRequestHandler, + corsRequestHandler, + corsResponseHandler, +) +from octoprint.server.util.flask import ( + no_firstrun_access, + get_json_command_from_request, + passive_login, + get_remote_address, +) from octoprint.access.permissions import Permissions from octoprint.events import eventManager, Events -#~~ init api blueprint, including sub modules +# ~~ init api blueprint, including sub modules api = Blueprint("api", __name__) @@ -52,530 +72,665 @@ api.before_request(loginFromAuthorizationHeaderRequestHandler) api.before_request(loginFromApiKeyRequestHandler) api.after_request(corsResponseHandler) -#~~ data from plugins +# ~~ data from plugins + @api.route("/plugin/", methods=["GET"]) def pluginData(name): - api_plugins = octoprint.plugin.plugin_manager().get_filtered_implementations(lambda p: p._identifier == name, octoprint.plugin.SimpleApiPlugin) - if not api_plugins: - return make_response("Not found", 404) + api_plugins = octoprint.plugin.plugin_manager().get_filtered_implementations( + lambda p: p._identifier == name, octoprint.plugin.SimpleApiPlugin + ) + if not api_plugins: + return make_response("Not found", 404) - if len(api_plugins) > 1: - return make_response("More than one api provider registered for {name}, can't proceed".format(name=name), 500) + if len(api_plugins) > 1: + return make_response( + "More than one api provider registered for {name}, can't proceed".format( + name=name + ), + 500, + ) - try: - api_plugin = api_plugins[0] - if api_plugin.is_api_adminonly() and not current_user.is_admin: - return make_response("Forbidden", 403) + try: + api_plugin = api_plugins[0] + if api_plugin.is_api_adminonly() and not current_user.is_admin: + return make_response("Forbidden", 403) - response = api_plugin.on_api_get(request) + response = api_plugin.on_api_get(request) - if response is not None: - return response - return NO_CONTENT - except HTTPException: - raise - except Exception: - logging.getLogger(__name__).exception("Error calling SimpleApiPlugin {}".format(name), - extra={"plugin": name}) - return abort(500) + if response is not None: + return response + return NO_CONTENT + except HTTPException: + raise + except Exception: + logging.getLogger(__name__).exception( + "Error calling SimpleApiPlugin {}".format(name), extra={"plugin": name} + ) + return abort(500) + + +# ~~ commands for plugins -#~~ commands for plugins @api.route("/plugin/", methods=["POST"]) @no_firstrun_access def pluginCommand(name): - api_plugins = octoprint.plugin.plugin_manager().get_filtered_implementations(lambda p: p._identifier == name, octoprint.plugin.SimpleApiPlugin) + api_plugins = octoprint.plugin.plugin_manager().get_filtered_implementations( + lambda p: p._identifier == name, octoprint.plugin.SimpleApiPlugin + ) - if not api_plugins: - return make_response("Not found", 404) + if not api_plugins: + return make_response("Not found", 404) - if len(api_plugins) > 1: - return make_response("More than one api provider registered for {name}, can't proceed".format(name=name), 500) + if len(api_plugins) > 1: + return make_response( + "More than one api provider registered for {name}, can't proceed".format( + name=name + ), + 500, + ) - api_plugin = api_plugins[0] - try: - valid_commands = api_plugin.get_api_commands() - if valid_commands is None: - return make_response("Method not allowed", 405) + api_plugin = api_plugins[0] + try: + valid_commands = api_plugin.get_api_commands() + if valid_commands is None: + return make_response("Method not allowed", 405) - if api_plugin.is_api_adminonly() and not Permissions.ADMIN.can(): - return make_response("Forbidden", 403) + if api_plugin.is_api_adminonly() and not Permissions.ADMIN.can(): + return make_response("Forbidden", 403) - command, data, response = get_json_command_from_request(request, valid_commands) - if response is not None: - return response + command, data, response = get_json_command_from_request(request, valid_commands) + if response is not None: + return response - response = api_plugin.on_api_command(command, data) - if response is not None: - return response - return NO_CONTENT - except HTTPException: - raise - except Exception: - logging.getLogger(__name__).exception("Error while executing SimpleApiPlugin {}".format(name), - extra={"plugin": name}) - return abort(500) + response = api_plugin.on_api_command(command, data) + if response is not None: + return response + return NO_CONTENT + except HTTPException: + raise + except Exception: + logging.getLogger(__name__).exception( + "Error while executing SimpleApiPlugin {}".format(name), + extra={"plugin": name}, + ) + return abort(500) + + +# ~~ first run setup -#~~ first run setup @api.route("/setup/wizard", methods=["GET"]) def wizardState(): - if not s().getBoolean(["server", "firstRun"]) and not Permissions.ADMIN.can(): - abort(403) + if not s().getBoolean(["server", "firstRun"]) and not Permissions.ADMIN.can(): + abort(403) - seen_wizards = s().get(["server", "seenWizards"]) + seen_wizards = s().get(["server", "seenWizards"]) - result = {} - wizard_plugins = octoprint.server.pluginManager.get_implementations(octoprint.plugin.WizardPlugin) - for implementation in wizard_plugins: - name = implementation._identifier - try: - required = implementation.is_wizard_required() - details = implementation.get_wizard_details() - version = implementation.get_wizard_version() - ignored = octoprint.plugin.WizardPlugin.is_wizard_ignored(seen_wizards, implementation) - except Exception: - logging.getLogger(__name__).exception("There was an error fetching wizard " - "details for {}, ignoring".format(name), - extra={"plugin": name}) - else: - result[name] = {"required": required, "details": details, "version": version, "ignored": ignored} + result = {} + wizard_plugins = octoprint.server.pluginManager.get_implementations( + octoprint.plugin.WizardPlugin + ) + for implementation in wizard_plugins: + name = implementation._identifier + try: + required = implementation.is_wizard_required() + details = implementation.get_wizard_details() + version = implementation.get_wizard_version() + ignored = octoprint.plugin.WizardPlugin.is_wizard_ignored( + seen_wizards, implementation + ) + except Exception: + logging.getLogger(__name__).exception( + "There was an error fetching wizard " + "details for {}, ignoring".format(name), + extra={"plugin": name}, + ) + else: + result[name] = { + "required": required, + "details": details, + "version": version, + "ignored": ignored, + } - return jsonify(result) + return jsonify(result) @api.route("/setup/wizard", methods=["POST"]) def wizardFinish(): - if not s().getBoolean(["server", "firstRun"]) and not Permissions.ADMIN.can(): - abort(403) + if not s().getBoolean(["server", "firstRun"]) and not Permissions.ADMIN.can(): + abort(403) - data = {} - try: - data = request.get_json() - except Exception: - abort(400) + data = {} + try: + data = request.get_json() + except Exception: + abort(400) - if data is None: - abort(400) + if data is None: + abort(400) - if not "handled" in data: - abort(400) - handled = data["handled"] + if not "handled" in data: + abort(400) + handled = data["handled"] - if s().getBoolean(["server", "firstRun"]): - s().setBoolean(["server", "firstRun"], False) + if s().getBoolean(["server", "firstRun"]): + s().setBoolean(["server", "firstRun"], False) - seen_wizards = dict(s().get(["server", "seenWizards"])) + seen_wizards = dict(s().get(["server", "seenWizards"])) - wizard_plugins = octoprint.server.pluginManager.get_implementations(octoprint.plugin.WizardPlugin) - for implementation in wizard_plugins: - name = implementation._identifier - try: - implementation.on_wizard_finish(name in handled) - if name in handled: - seen_wizards[name] = implementation.get_wizard_version() - except Exception: - logging.getLogger(__name__).exception("There was an error finishing the " - "wizard for {}, ignoring".format(name), - extra={"plugin": name}) + wizard_plugins = octoprint.server.pluginManager.get_implementations( + octoprint.plugin.WizardPlugin + ) + for implementation in wizard_plugins: + name = implementation._identifier + try: + implementation.on_wizard_finish(name in handled) + if name in handled: + seen_wizards[name] = implementation.get_wizard_version() + except Exception: + logging.getLogger(__name__).exception( + "There was an error finishing the " + "wizard for {}, ignoring".format(name), + extra={"plugin": name}, + ) - s().set(["server", "seenWizards"], seen_wizards) - s().save() + s().set(["server", "seenWizards"], seen_wizards) + s().save() - return NO_CONTENT + return NO_CONTENT -#~~ system state +# ~~ system state @api.route("/state", methods=["GET"]) @no_firstrun_access def apiPrinterState(): - return make_response(("/api/state has been deprecated, use /api/printer instead", 405, [])) + return make_response( + ("/api/state has been deprecated, use /api/printer instead", 405, []) + ) @api.route("/version", methods=["GET"]) @Permissions.STATUS.require(403) def apiVersion(): - return jsonify(server=octoprint.server.VERSION, - api=VERSION, - text="OctoPrint {}".format(octoprint.server.DISPLAY_VERSION)) + return jsonify( + server=octoprint.server.VERSION, + api=VERSION, + text="OctoPrint {}".format(octoprint.server.DISPLAY_VERSION), + ) @api.route("/server", methods=["GET"]) @Permissions.STATUS.require(403) def serverStatus(): - return jsonify(version=octoprint.server.VERSION, - safemode=octoprint.server.safe_mode) + return jsonify(version=octoprint.server.VERSION, safemode=octoprint.server.safe_mode) -#~~ Login/user handling + +# ~~ Login/user handling @api.route("/login", methods=["POST"]) def login(): - data = request.get_json() - if not data: - data = request.values + data = request.get_json() + if not data: + data = request.values - if octoprint.server.userManager.enabled and "user" in data and "pass" in data: - username = data["user"] - password = data["pass"] + if octoprint.server.userManager.enabled and "user" in data and "pass" in data: + username = data["user"] + password = data["pass"] - if "remember" in data and data["remember"] in valid_boolean_trues: - remember = True - else: - remember = False + if "remember" in data and data["remember"] in valid_boolean_trues: + remember = True + else: + remember = False - if "usersession.id" in session: - _logout(current_user) + if "usersession.id" in session: + _logout(current_user) - user = octoprint.server.userManager.find_user(username) - if user is not None: - if octoprint.server.userManager.check_password(username, password): - if not user.is_active: - return make_response(("Your account is deactivated", 403, [])) + user = octoprint.server.userManager.find_user(username) + if user is not None: + if octoprint.server.userManager.check_password(username, password): + if not user.is_active: + return make_response(("Your account is deactivated", 403, [])) - if octoprint.server.userManager.enabled: - user = octoprint.server.userManager.login_user(user) - session["usersession.id"] = user.session - g.user = user - login_user(user, remember=remember) - identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id())) - session["login_mechanism"] = "http" + if octoprint.server.userManager.enabled: + user = octoprint.server.userManager.login_user(user) + session["usersession.id"] = user.session + g.user = user + login_user(user, remember=remember) + identity_changed.send( + current_app._get_current_object(), identity=Identity(user.get_id()) + ) + session["login_mechanism"] = "http" - remote_addr = get_remote_address(request) - logging.getLogger(__name__).info("Actively logging in user {} from {}".format(user.get_id(), remote_addr)) + remote_addr = get_remote_address(request) + logging.getLogger(__name__).info( + "Actively logging in user {} from {}".format( + user.get_id(), remote_addr + ) + ) - response = user.as_dict() - response["_is_external_client"] = s().getBoolean(["server", "ipCheck", "enabled"]) \ - and not util_net.is_lan_address(remote_addr, - additional_private=s().get(["server", "ipCheck", "trustedSubnets"])) - response["_login_mechanism"] = session["login_mechanism"] + response = user.as_dict() + response["_is_external_client"] = s().getBoolean( + ["server", "ipCheck", "enabled"] + ) and not util_net.is_lan_address( + remote_addr, + additional_private=s().get(["server", "ipCheck", "trustedSubnets"]), + ) + response["_login_mechanism"] = session["login_mechanism"] - r = make_response(jsonify(response)) - r.delete_cookie("active_logout") + r = make_response(jsonify(response)) + r.delete_cookie("active_logout") - eventManager().fire(Events.USER_LOGGED_IN, payload={"username": user.get_id()}) + eventManager().fire( + Events.USER_LOGGED_IN, payload={"username": user.get_id()} + ) - return r + return r - return make_response(("User unknown or password incorrect", 403, [])) + return make_response(("User unknown or password incorrect", 403, [])) - elif "passive" in data: - return passive_login() + elif "passive" in data: + return passive_login() - return make_response("Neither user and pass attributes nor passive flag present", 400) + return make_response("Neither user and pass attributes nor passive flag present", 400) @api.route("/logout", methods=["POST"]) def logout(): - username = None - if current_user: - username = current_user.get_id() + username = None + if current_user: + username = current_user.get_id() - # logout from user manager... - _logout(current_user) + # logout from user manager... + _logout(current_user) - # ... and from flask login (and principal) - logout_user() + # ... and from flask login (and principal) + logout_user() - # ... and send an active logout session cookie - r = make_response(jsonify(octoprint.server.userManager.anonymous_user_factory())) - r.set_cookie("active_logout", "true") + # ... and send an active logout session cookie + r = make_response(jsonify(octoprint.server.userManager.anonymous_user_factory())) + r.set_cookie("active_logout", "true") - if username: - eventManager().fire(Events.USER_LOGGED_OUT, payload={"username": username}) + if username: + eventManager().fire(Events.USER_LOGGED_OUT, payload={"username": username}) - return r + return r def _logout(user): - if "usersession.id" in session: - del session["usersession.id"] - if "login_mechanism" in session: - del session["login_mechanism"] - octoprint.server.userManager.logout_user(user) + if "usersession.id" in session: + del session["usersession.id"] + if "login_mechanism" in session: + del session["login_mechanism"] + octoprint.server.userManager.logout_user(user) @api.route("/currentuser", methods=["GET"]) def get_current_user(): - return jsonify(name=current_user.get_name(), - permissions=[permission.key for permission in current_user.effective_permissions], - groups=[group.key for group in current_user.groups]) + return jsonify( + name=current_user.get_name(), + permissions=[permission.key for permission in current_user.effective_permissions], + groups=[group.key for group in current_user.groups], + ) -#~~ Test utils +# ~~ Test utils @api.route("/util/test", methods=["POST"]) @no_firstrun_access @Permissions.ADMIN.require(403) def utilTest(): - valid_commands = {"path": ["path"], - "url": ["url"], - "server": ["host", "port"], - "resolution": ["name"]} + valid_commands = { + "path": ["path"], + "url": ["url"], + "server": ["host", "port"], + "resolution": ["name"], + } - command, data, response = get_json_command_from_request(request, valid_commands) - if response is not None: - return response + command, data, response = get_json_command_from_request(request, valid_commands) + if response is not None: + return response + + if command == "path": + return _test_path(data) + elif command == "url": + return _test_url(data) + elif command == "server": + return _test_server(data) + elif command == "resolution": + return _test_resolution(data) - if command == "path": - return _test_path(data) - elif command == "url": - return _test_url(data) - elif command == "server": - return _test_server(data) - elif command == "resolution": - return _test_resolution(data) def _test_path(data): - import os - from octoprint.util.paths import normalize + import os + from octoprint.util.paths import normalize - path = normalize(data["path"], real=False) - if not path: - return jsonify(path=path, exists=False, typeok=False, broken_symlink=False, access=False, result=False) + path = normalize(data["path"], real=False) + if not path: + return jsonify( + path=path, + exists=False, + typeok=False, + broken_symlink=False, + access=False, + result=False, + ) - unreal_path = path - path = os.path.realpath(path) + unreal_path = path + path = os.path.realpath(path) - check_type = None - check_access = [] + check_type = None + check_access = [] - if "check_type" in data and data["check_type"] in ("file", "dir"): - check_type = data["check_type"] + if "check_type" in data and data["check_type"] in ("file", "dir"): + check_type = data["check_type"] - if "check_access" in data: - request_check_access = data["check_access"] - if not isinstance(request_check_access, list): - request_check_access = list(request_check_access) + if "check_access" in data: + request_check_access = data["check_access"] + if not isinstance(request_check_access, list): + request_check_access = list(request_check_access) - check_access = [check for check in request_check_access if check in ("r", "w", "x")] + check_access = [ + check for check in request_check_access if check in ("r", "w", "x") + ] - allow_create_dir = data.get("allow_create_dir", False) and check_type == "dir" - check_writable_dir = data.get("check_writable_dir", False) and check_type == "dir" - if check_writable_dir and "w" not in check_access: - check_access.append("w") + allow_create_dir = data.get("allow_create_dir", False) and check_type == "dir" + check_writable_dir = data.get("check_writable_dir", False) and check_type == "dir" + if check_writable_dir and "w" not in check_access: + check_access.append("w") - # check if path exists - exists = os.path.exists(path) - if not exists: - if os.path.islink(unreal_path): - # broken symlink, see #2644 - logging.getLogger(__name__).error("{} is a broken symlink pointing at non existing {}".format(unreal_path, path)) - return jsonify(path=unreal_path, exists=False, typeok=False, broken_symlink=True, access=False, result=False) + # check if path exists + exists = os.path.exists(path) + if not exists: + if os.path.islink(unreal_path): + # broken symlink, see #2644 + logging.getLogger(__name__).error( + "{} is a broken symlink pointing at non existing {}".format( + unreal_path, path + ) + ) + return jsonify( + path=unreal_path, + exists=False, + typeok=False, + broken_symlink=True, + access=False, + result=False, + ) - elif check_type == "dir" and allow_create_dir: - try: - os.makedirs(path) - except Exception: - logging.getLogger(__name__).exception("Error while trying to create {}".format(path)) - return jsonify(path=path, exists=False, typeok=False, broken_symlink=False, access=False, result=False) - else: - exists = True + elif check_type == "dir" and allow_create_dir: + try: + os.makedirs(path) + except Exception: + logging.getLogger(__name__).exception( + "Error while trying to create {}".format(path) + ) + return jsonify( + path=path, + exists=False, + typeok=False, + broken_symlink=False, + access=False, + result=False, + ) + else: + exists = True - # check path type - type_mapping = {"file": os.path.isfile, "dir": os.path.isdir} - if check_type: - typeok = type_mapping[check_type](path) - else: - typeok = exists + # check path type + type_mapping = {"file": os.path.isfile, "dir": os.path.isdir} + if check_type: + typeok = type_mapping[check_type](path) + else: + typeok = exists - # check if path allows requested access - access_mapping = {"r": os.R_OK, "w": os.W_OK, "x": os.X_OK} - if check_access: - mode = 0 - for a in map(lambda x: access_mapping[x], check_access): - mode |= a - access = os.access(path, mode) - else: - access = exists + # check if path allows requested access + access_mapping = {"r": os.R_OK, "w": os.W_OK, "x": os.X_OK} + if check_access: + mode = 0 + for a in map(lambda x: access_mapping[x], check_access): + mode |= a + access = os.access(path, mode) + else: + access = exists - if check_writable_dir and check_type == "dir": - try: - test_path = os.path.join(path, ".testballoon.txt") - with io.open(test_path, 'wb') as f: - f.write(b"Test") - os.remove(test_path) - except Exception: - logging.getLogger(__name__).exception("Error while testing if {} is really writable".format(path)) - return jsonify(path=path, exists=exists, typeok=typeok, broken_symlink=False, access=False, result=False) + if check_writable_dir and check_type == "dir": + try: + test_path = os.path.join(path, ".testballoon.txt") + with io.open(test_path, "wb") as f: + f.write(b"Test") + os.remove(test_path) + except Exception: + logging.getLogger(__name__).exception( + "Error while testing if {} is really writable".format(path) + ) + return jsonify( + path=path, + exists=exists, + typeok=typeok, + broken_symlink=False, + access=False, + result=False, + ) - return jsonify(path=path, exists=exists, typeok=typeok, broken_symlink=False, access=access, result=exists and typeok and access) + return jsonify( + path=path, + exists=exists, + typeok=typeok, + broken_symlink=False, + access=access, + result=exists and typeok and access, + ) def _test_url(data): - import requests - from octoprint import util as util + import requests + from octoprint import util as util - class StatusCodeRange(object): - def __init__(self, start=None, end=None): - self.start = start - self.end = end + class StatusCodeRange(object): + def __init__(self, start=None, end=None): + self.start = start + self.end = end - def __contains__(self, item): - if not isinstance(item, int): - return False - if self.start and self.end: - return self.start <= item < self.end - elif self.start: - return self.start <= item - elif self.end: - return item < self.end - else: - return False + def __contains__(self, item): + if not isinstance(item, int): + return False + if self.start and self.end: + return self.start <= item < self.end + elif self.start: + return self.start <= item + elif self.end: + return item < self.end + else: + return False - def as_dict(self): - return {"start": self.start, - "end": self.end} + def as_dict(self): + return {"start": self.start, "end": self.end} - status_ranges = {"informational": StatusCodeRange(start=100, end=200), - "success": StatusCodeRange(start=200, end=300), - "redirection": StatusCodeRange(start=300, end=400), - "client_error": StatusCodeRange(start=400, end=500), - "server_error": StatusCodeRange(start=500, end=600), - "normal": StatusCodeRange(end=400), - "error": StatusCodeRange(start=400, end=600), - "any": StatusCodeRange(start=100), - "timeout": StatusCodeRange(start=0, end=1)} + status_ranges = { + "informational": StatusCodeRange(start=100, end=200), + "success": StatusCodeRange(start=200, end=300), + "redirection": StatusCodeRange(start=300, end=400), + "client_error": StatusCodeRange(start=400, end=500), + "server_error": StatusCodeRange(start=500, end=600), + "normal": StatusCodeRange(end=400), + "error": StatusCodeRange(start=400, end=600), + "any": StatusCodeRange(start=100), + "timeout": StatusCodeRange(start=0, end=1), + } - url = data["url"] - method = data.get("method", "HEAD") - timeout = 3.0 - valid_ssl = True - check_status = [status_ranges["normal"]] - content_type_whitelist = None - content_type_blacklist = None + url = data["url"] + method = data.get("method", "HEAD") + timeout = 3.0 + valid_ssl = True + check_status = [status_ranges["normal"]] + content_type_whitelist = None + content_type_blacklist = None - if "timeout" in data: - try: - timeout = float(data["timeout"]) - except Exception: - return make_response("{!r} is not a valid value for timeout (must be int or float)".format(data["timeout"]), - 400) + if "timeout" in data: + try: + timeout = float(data["timeout"]) + except Exception: + return make_response( + "{!r} is not a valid value for timeout (must be int or float)".format( + data["timeout"] + ), + 400, + ) - if "validSsl" in data: - valid_ssl = data["validSsl"] in valid_boolean_trues + if "validSsl" in data: + valid_ssl = data["validSsl"] in valid_boolean_trues - if "status" in data: - request_status = data["status"] - if not isinstance(request_status, list): - request_status = [request_status] + if "status" in data: + request_status = data["status"] + if not isinstance(request_status, list): + request_status = [request_status] - check_status = [] - for rs in request_status: - if isinstance(rs, int): - check_status.append([rs]) - else: - if rs in status_ranges: - check_status.append(status_ranges[rs]) - else: - code = requests.codes[rs] - if code is not None: - check_status.append([code]) + check_status = [] + for rs in request_status: + if isinstance(rs, int): + check_status.append([rs]) + else: + if rs in status_ranges: + check_status.append(status_ranges[rs]) + else: + code = requests.codes[rs] + if code is not None: + check_status.append([code]) - if "content_type_whitelist" in data: - if not isinstance(data["content_type_whitelist"], (list, tuple)): - return make_response("content_type_whitelist must be a list of mime types") - content_type_whitelist = list(map(util.parse_mime_type, data["content_type_whitelist"])) - if "content_type_blacklist" in data: - if not isinstance(data["content_type_whitelist"], (list, tuple)): - return make_response("content_type_blacklist must be a list of mime types") - content_type_blacklist = list(map(util.parse_mime_type, data["content_type_blacklist"])) + if "content_type_whitelist" in data: + if not isinstance(data["content_type_whitelist"], (list, tuple)): + return make_response("content_type_whitelist must be a list of mime types") + content_type_whitelist = list( + map(util.parse_mime_type, data["content_type_whitelist"]) + ) + if "content_type_blacklist" in data: + if not isinstance(data["content_type_whitelist"], (list, tuple)): + return make_response("content_type_blacklist must be a list of mime types") + content_type_blacklist = list( + map(util.parse_mime_type, data["content_type_blacklist"]) + ) - response_result = None - outcome = True - status = 0 - try: - with requests.request(method=method, url=url, timeout=timeout, verify=valid_ssl, stream=True) as response: - status = response.status_code - outcome = outcome and any(map(lambda x: status in x, check_status)) - content_type = response.headers.get("content-type") + response_result = None + outcome = True + status = 0 + try: + with requests.request( + method=method, url=url, timeout=timeout, verify=valid_ssl, stream=True + ) as response: + status = response.status_code + outcome = outcome and any(map(lambda x: status in x, check_status)) + content_type = response.headers.get("content-type") - response_result = {"headers": dict(response.headers), - "content_type": content_type} + response_result = { + "headers": dict(response.headers), + "content_type": content_type, + } - if not content_type and data.get("content_type_guess") in valid_boolean_trues: - content = response.content - content_type = util.guess_mime_type(bytearray(content)) + if not content_type and data.get("content_type_guess") in valid_boolean_trues: + content = response.content + content_type = util.guess_mime_type(bytearray(content)) - if not content_type: - content_type = "application/octet-stream" + if not content_type: + content_type = "application/octet-stream" - response_result = {"assumed_content_type": content_type} + response_result = {"assumed_content_type": content_type} - parsed_content_type = util.parse_mime_type(content_type) + parsed_content_type = util.parse_mime_type(content_type) - in_whitelist = content_type_whitelist is None or any( - map(lambda x: util.mime_type_matches(parsed_content_type, x), content_type_whitelist)) - in_blacklist = content_type_blacklist is not None and any( - map(lambda x: util.mime_type_matches(parsed_content_type, x), content_type_blacklist)) + in_whitelist = content_type_whitelist is None or any( + map( + lambda x: util.mime_type_matches(parsed_content_type, x), + content_type_whitelist, + ) + ) + in_blacklist = content_type_blacklist is not None and any( + map( + lambda x: util.mime_type_matches(parsed_content_type, x), + content_type_blacklist, + ) + ) - if not in_whitelist or in_blacklist: - # we don't support this content type - response.close() - outcome = False + if not in_whitelist or in_blacklist: + # we don't support this content type + response.close() + outcome = False - elif "response" in data and ( - data["response"] in valid_boolean_trues or data["response"] in ("json", "bytes")): - if data["response"] == "json": - content = response.json() + elif "response" in data and ( + data["response"] in valid_boolean_trues + or data["response"] in ("json", "bytes") + ): + if data["response"] == "json": + content = response.json() - else: - import base64 - content = base64.standard_b64encode(response.content) + else: + import base64 - response_result["content"] = content - except Exception: - logging.getLogger(__name__).exception("Error while running a test {} request on {}".format(method, url)) - outcome = False + content = base64.standard_b64encode(response.content) - result = {"url": url, - "status": status, - "result": outcome} - if response_result: - result["response"] = response_result + response_result["content"] = content + except Exception: + logging.getLogger(__name__).exception( + "Error while running a test {} request on {}".format(method, url) + ) + outcome = False + + result = {"url": url, "status": status, "result": outcome} + if response_result: + result["response"] = response_result + + return jsonify(**result) - return jsonify(**result) def _test_server(data): - host = data["host"] - try: - port = int(data["port"]) - except Exception: - return make_response("{!r} is not a valid value for port (must be int)".format(data["port"]), 400) + host = data["host"] + try: + port = int(data["port"]) + except Exception: + return make_response( + "{!r} is not a valid value for port (must be int)".format(data["port"]), 400 + ) - timeout = 3.05 - if "timeout" in data: - try: - timeout = float(data["timeout"]) - except Exception: - return make_response("{!r} is not a valid value for timeout (must be int or float)".format(data["timeout"]), - 400) + timeout = 3.05 + if "timeout" in data: + try: + timeout = float(data["timeout"]) + except Exception: + return make_response( + "{!r} is not a valid value for timeout (must be int or float)".format( + data["timeout"] + ), + 400, + ) - protocol = data.get("protocol", "tcp") - if protocol not in ("tcp", "udp"): - return make_response("{!r} is not a valid value for protocol, must be tcp or udp".format(protocol), 400) + protocol = data.get("protocol", "tcp") + if protocol not in ("tcp", "udp"): + return make_response( + "{!r} is not a valid value for protocol, must be tcp or udp".format(protocol), + 400, + ) - from octoprint.util import server_reachable - reachable = server_reachable(host, port, timeout=timeout, proto=protocol) + from octoprint.util import server_reachable - result = {"host": host, - "port": port, - "protocol": protocol, - "result": reachable} + reachable = server_reachable(host, port, timeout=timeout, proto=protocol) + + result = {"host": host, "port": port, "protocol": protocol, "result": reachable} + + return jsonify(**result) - return jsonify(**result) def _test_resolution(data): - name = data["name"] + name = data["name"] - from octoprint.util.net import resolve_host - resolvable = len(resolve_host(name)) > 0 + from octoprint.util.net import resolve_host - result = {"name": name, - "result": resolvable} + resolvable = len(resolve_host(name)) > 0 - return jsonify(**result) + result = {"name": name, "result": resolvable} + + return jsonify(**result) diff --git a/src/octoprint/server/api/access.py b/src/octoprint/server/api/access.py index 6b8d86e02..1780a0d15 100644 --- a/src/octoprint/server/api/access.py +++ b/src/octoprint/server/api/access.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Marc Hannappel " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" from flask import request, jsonify, abort, make_response @@ -17,335 +17,391 @@ from octoprint.server.api import api, valid_boolean_trues from octoprint.server.util.flask import no_firstrun_access from octoprint.access.permissions import Permissions -#~~ permission api +# ~~ permission api + @api.route("/access/permissions", methods=["GET"]) def get_permissions(): - return jsonify(permissions=[permission.as_dict() for permission in Permissions.all()]) + return jsonify(permissions=[permission.as_dict() for permission in Permissions.all()]) + + +# ~~ group api -#~~ group api @api.route("/access/groups", methods=["GET"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def get_groups(): - return jsonify(groups=list(map(lambda g: g.as_dict(), groupManager.groups))) + return jsonify(groups=list(map(lambda g: g.as_dict(), groupManager.groups))) @api.route("/access/groups", methods=["POST"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def add_group(): - if not "application/json" in request.headers["Content-Type"]: - return make_response("Expected content-type JSON", 400) + if not "application/json" in request.headers["Content-Type"]: + return make_response("Expected content-type JSON", 400) - try: - data = request.get_json() - except BadRequest: - return make_response("Malformed JSON body in request", 400) + try: + data = request.get_json() + except BadRequest: + return make_response("Malformed JSON body in request", 400) - if not "key" in data: - return make_response("Missing mandatory key field", 400) - if not "name" in data: - return make_response("Missing mandatory name field", 400) - if not "permissions" in data: - return make_response("Missing mandatory permissions field", 400) + if not "key" in data: + return make_response("Missing mandatory key field", 400) + if not "name" in data: + return make_response("Missing mandatory name field", 400) + if not "permissions" in data: + return make_response("Missing mandatory permissions field", 400) - key = data["key"] - name = data["name"] - description = data.get("description", "") - permissions = data["permissions"] - subgroups = data["subgroups"] - default = data.get("default", False) + key = data["key"] + name = data["name"] + description = data.get("description", "") + permissions = data["permissions"] + subgroups = data["subgroups"] + default = data.get("default", False) - try: - groupManager.add_group(key, name, description=description, permissions=permissions, subgroups=subgroups, default=default) - except groups.GroupAlreadyExists: - abort(409) - return get_groups() + try: + groupManager.add_group( + key, + name, + description=description, + permissions=permissions, + subgroups=subgroups, + default=default, + ) + except groups.GroupAlreadyExists: + abort(409) + return get_groups() @api.route("/access/groups/", methods=["GET"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def get_group(key): - group = groupManager.find_group(key) - if group is not None: - return jsonify(group) - else: - abort(404) + group = groupManager.find_group(key) + if group is not None: + return jsonify(group) + else: + abort(404) @api.route("/access/groups/", methods=["PUT"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def update_group(key): - if "application/json" not in request.headers["Content-Type"]: - return make_response("Expected content-type JSON", 400) + if "application/json" not in request.headers["Content-Type"]: + return make_response("Expected content-type JSON", 400) - try: - data = request.get_json() - except BadRequest: - return make_response("Malformed JSON body in request", 400) + try: + data = request.get_json() + except BadRequest: + return make_response("Malformed JSON body in request", 400) - try: - kwargs = {} + try: + kwargs = {} - if "permissions" in data: - kwargs["permissions"] = data["permissions"] + if "permissions" in data: + kwargs["permissions"] = data["permissions"] - if "subgroups" in data: - kwargs["subgroups"] = data["subgroups"] + if "subgroups" in data: + kwargs["subgroups"] = data["subgroups"] - if "default" in data: - kwargs["default"] = data["default"] in valid_boolean_trues + if "default" in data: + kwargs["default"] = data["default"] in valid_boolean_trues - if "description" in data: - kwargs["description"] = data["description"] + if "description" in data: + kwargs["description"] = data["description"] - groupManager.update_group(key, **kwargs) + groupManager.update_group(key, **kwargs) - return get_groups() - except groups.GroupCantBeChanged: - abort(403) - except groups.UnknownGroup: - abort(404) + return get_groups() + except groups.GroupCantBeChanged: + abort(403) + except groups.UnknownGroup: + abort(404) @api.route("/access/groups/", methods=["DELETE"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def remove_group(key): - try: - groupManager.remove_group(key) - return get_groups() - except groups.UnknownGroup: - abort(404) - except groups.GroupUnremovable: - abort(403) + try: + groupManager.remove_group(key) + return get_groups() + except groups.UnknownGroup: + abort(404) + except groups.GroupUnremovable: + abort(403) + + +# ~~ user api -#~~ user api @api.route("/access/users", methods=["GET"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def get_users(): - if not userManager.enabled: - return jsonify(SUCCESS) + if not userManager.enabled: + return jsonify(SUCCESS) - return jsonify(users=list(map(lambda u: u.as_dict(), userManager.get_all_users()))) + return jsonify(users=list(map(lambda u: u.as_dict(), userManager.get_all_users()))) @api.route("/access/users", methods=["POST"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def add_user(): - if not userManager.enabled: - return jsonify(SUCCESS) + if not userManager.enabled: + return jsonify(SUCCESS) - if not "application/json" in request.headers["Content-Type"]: - return make_response("Expected content-type JSON", 400) + if not "application/json" in request.headers["Content-Type"]: + return make_response("Expected content-type JSON", 400) - try: - data = request.get_json() - except BadRequest: - return make_response("Malformed JSON body in request", 400) + try: + data = request.get_json() + except BadRequest: + return make_response("Malformed JSON body in request", 400) - if data is None: - return make_response("Malformed JSON body in request", 400) + if data is None: + return make_response("Malformed JSON body in request", 400) - if not "name" in data: - return make_response("Missing mandatory name field", 400) - if not "password" in data: - return make_response("Missing mandatory password field", 400) - if not "active" in data: - return make_response("Missing mandatory active field", 400) + if not "name" in data: + return make_response("Missing mandatory name field", 400) + if not "password" in data: + return make_response("Missing mandatory password field", 400) + if not "active" in data: + return make_response("Missing mandatory active field", 400) - name = data["name"] - password = data["password"] - active = data["active"] in valid_boolean_trues + name = data["name"] + password = data["password"] + active = data["active"] in valid_boolean_trues - groups = data.get("groups", None) - permissions = data.get("permissions", None) + groups = data.get("groups", None) + permissions = data.get("permissions", None) - try: - userManager.add_user(name, password, active, permissions, groups) - except users.UserAlreadyExists: - abort(409) - return get_users() + try: + userManager.add_user(name, password, active, permissions, groups) + except users.UserAlreadyExists: + abort(409) + return get_users() @api.route("/access/users/", methods=["GET"]) @no_firstrun_access def get_user(username): - if not userManager.enabled: - return jsonify(SUCCESS) + if not userManager.enabled: + return jsonify(SUCCESS) - if current_user is not None and not current_user.is_anonymous and (current_user.get_name() == username or current_user.has_permission(Permissions.ADMIN)): - user = userManager.find_user(username) - if user is not None: - return jsonify(user) - else: - abort(404) - else: - abort(403) + if ( + current_user is not None + and not current_user.is_anonymous + and ( + current_user.get_name() == username + or current_user.has_permission(Permissions.ADMIN) + ) + ): + user = userManager.find_user(username) + if user is not None: + return jsonify(user) + else: + abort(404) + else: + abort(403) @api.route("/access/users/", methods=["PUT"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def update_user(username): - if not userManager.enabled: - return jsonify(SUCCESS) + if not userManager.enabled: + return jsonify(SUCCESS) - user = userManager.find_user(username) - if user is not None: - if not "application/json" in request.headers["Content-Type"]: - return make_response("Expected content-type JSON", 400) + user = userManager.find_user(username) + if user is not None: + if not "application/json" in request.headers["Content-Type"]: + return make_response("Expected content-type JSON", 400) - try: - data = request.get_json() - except BadRequest: - return make_response("Malformed JSON body in request", 400) + try: + data = request.get_json() + except BadRequest: + return make_response("Malformed JSON body in request", 400) + # change groups + if "groups" in data: + groups = data["groups"] + userManager.change_user_groups(username, groups) - # change groups - if "groups" in data: - groups = data["groups"] - userManager.change_user_groups(username, groups) + # change permissions + if "permissions" in data: + permissions = data["permissions"] + userManager.change_user_permissions(username, permissions) - # change permissions - if "permissions" in data: - permissions = data["permissions"] - userManager.change_user_permissions(username, permissions) + if data is None: + return make_response("Malformed JSON body in request", 400) - if data is None: - return make_response("Malformed JSON body in request", 400) + # change activation + if "active" in data: + userManager.change_user_activation( + username, data["active"] in valid_boolean_trues + ) - # change activation - if "active" in data: - userManager.change_user_activation(username, data["active"] in valid_boolean_trues) - - return get_users() - else: - abort(404) + return get_users() + else: + abort(404) @api.route("/access/users/", methods=["DELETE"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def remove_user(username): - if not userManager.enabled: - return jsonify(SUCCESS) + if not userManager.enabled: + return jsonify(SUCCESS) - try: - userManager.remove_user(username) - return get_users() - except users.UnknownUser: - abort(404) + try: + userManager.remove_user(username) + return get_users() + except users.UnknownUser: + abort(404) @api.route("/access/users//password", methods=["PUT"]) @no_firstrun_access def change_password_for_user(username): - if not userManager.enabled: - return jsonify(SUCCESS) + if not userManager.enabled: + return jsonify(SUCCESS) - if current_user is not None and not current_user.is_anonymous and (current_user.get_name() == username or current_user.is_admin): - if not "application/json" in request.headers["Content-Type"]: - return make_response("Expected content-type JSON", 400) + if ( + current_user is not None + and not current_user.is_anonymous + and (current_user.get_name() == username or current_user.is_admin) + ): + if not "application/json" in request.headers["Content-Type"]: + return make_response("Expected content-type JSON", 400) - try: - data = request.get_json() - except BadRequest: - return make_response("Malformed JSON body in request", 400) + try: + data = request.get_json() + except BadRequest: + return make_response("Malformed JSON body in request", 400) - if data is None: - return make_response("Malformed JSON body in request", 400) + if data is None: + return make_response("Malformed JSON body in request", 400) - if not "password" in data or not data["password"]: - return make_response("password is missing from request", 400) + if not "password" in data or not data["password"]: + return make_response("password is missing from request", 400) - try: - userManager.change_user_password(username, data["password"]) - except users.UnknownUser: - return make_response(("Unknown user: %s" % username, 404, [])) + try: + userManager.change_user_password(username, data["password"]) + except users.UnknownUser: + return make_response(("Unknown user: %s" % username, 404, [])) - return jsonify(SUCCESS) - else: - return make_response(("Forbidden", 403, [])) + return jsonify(SUCCESS) + else: + return make_response(("Forbidden", 403, [])) @api.route("/access/users//settings", methods=["GET"]) @no_firstrun_access def get_settings_for_user(username): - if not userManager.enabled: - return jsonify(SUCCESS) + if not userManager.enabled: + return jsonify(SUCCESS) - if current_user is None or current_user.is_anonymous or (current_user.get_name() != username and not current_user.has_permission(Permissions.ADMIN)): - return make_response("Forbidden", 403) + if ( + current_user is None + or current_user.is_anonymous + or ( + current_user.get_name() != username + and not current_user.has_permission(Permissions.ADMIN) + ) + ): + return make_response("Forbidden", 403) + + try: + return jsonify(userManager.get_all_user_settings(username)) + except users.UnknownUser: + return make_response("Unknown user: %s" % username, 404) - try: - return jsonify(userManager.get_all_user_settings(username)) - except users.UnknownUser: - return make_response("Unknown user: %s" % username, 404) @api.route("/access/users//settings", methods=["PATCH"]) @no_firstrun_access def change_settings_for_user(username): - if not userManager.enabled: - return jsonify(SUCCESS) + if not userManager.enabled: + return jsonify(SUCCESS) - if current_user is None or current_user.is_anonymous or (current_user.get_name() != username and not current_user.has_permission(Permissions.ADMIN)): - return make_response("Forbidden", 403) + if ( + current_user is None + or current_user.is_anonymous + or ( + current_user.get_name() != username + and not current_user.has_permission(Permissions.ADMIN) + ) + ): + return make_response("Forbidden", 403) - try: - data = request.get_json() - except BadRequest: - return make_response("Malformed JSON body in request", 400) + try: + data = request.get_json() + except BadRequest: + return make_response("Malformed JSON body in request", 400) - if data is None: - return make_response("Malformed JSON body in request", 400) + if data is None: + return make_response("Malformed JSON body in request", 400) + + try: + userManager.change_user_settings(username, data) + return jsonify(SUCCESS) + except users.UnknownUser: + return make_response("Unknown user: %s" % username, 404) - try: - userManager.change_user_settings(username, data) - return jsonify(SUCCESS) - except users.UnknownUser: - return make_response("Unknown user: %s" % username, 404) @api.route("/access/users//apikey", methods=["DELETE"]) @no_firstrun_access def delete_apikey_for_user(username): - if not userManager.enabled: - return jsonify(SUCCESS) + if not userManager.enabled: + return jsonify(SUCCESS) - if current_user is not None and not current_user.is_anonymous and (current_user.get_name() == username or current_user.has_permission(Permissions.ADMIN)): - try: - userManager.delete_api_key(username) - except users.UnknownUser: - return make_response(("Unknown user: %s" % username, 404, [])) - return jsonify(SUCCESS) - else: - return make_response(("Forbidden", 403, [])) + if ( + current_user is not None + and not current_user.is_anonymous + and ( + current_user.get_name() == username + or current_user.has_permission(Permissions.ADMIN) + ) + ): + try: + userManager.delete_api_key(username) + except users.UnknownUser: + return make_response(("Unknown user: %s" % username, 404, [])) + return jsonify(SUCCESS) + else: + return make_response(("Forbidden", 403, [])) @api.route("/access/users//apikey", methods=["POST"]) @no_firstrun_access def generate_apikey_for_user(username): - if not userManager.enabled: - return jsonify(SUCCESS) + if not userManager.enabled: + return jsonify(SUCCESS) + + if ( + current_user is not None + and not current_user.is_anonymous + and ( + current_user.get_name() == username + or current_user.has_permission(Permissions.ADMIN) + ) + ): + try: + apikey = userManager.generate_api_key(username) + except users.UnknownUser: + return make_response(("Unknown user: %s" % username, 404, [])) + return jsonify({"apikey": apikey}) + else: + return make_response(("Forbidden", 403, [])) - if current_user is not None and not current_user.is_anonymous and (current_user.get_name() == username or current_user.has_permission(Permissions.ADMIN)): - try: - apikey = userManager.generate_api_key(username) - except users.UnknownUser: - return make_response(("Unknown user: %s" % username, 404, [])) - return jsonify({"apikey": apikey}) - else: - return make_response(("Forbidden", 403, [])) def _to_external_permissions(*permissions): - return list(map(lambda p: p.get_name(), permissions)) + return list(map(lambda p: p.get_name(), permissions)) + def _to_external_groups(*groups): - return list(map(lambda g: g.get_name(), groups)) + return list(map(lambda g: g.get_name(), groups)) diff --git a/src/octoprint/server/api/connection.py b/src/octoprint/server/api/connection.py index ab40d5d28..4d1ed3239 100644 --- a/src/octoprint/server/api/connection.py +++ b/src/octoprint/server/api/connection.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" from flask import request, jsonify, make_response @@ -13,77 +13,90 @@ from octoprint.server.api import api from octoprint.server.util.flask import no_firstrun_access, get_json_command_from_request from octoprint.access.permissions import Permissions + @api.route("/connection", methods=["GET"]) @Permissions.STATUS.require(403) def connectionState(): - state, port, baudrate, printer_profile = printer.get_current_connection() - current = { - "state": state, - "port": port, - "baudrate": baudrate, - "printerProfile": printer_profile["id"] if printer_profile is not None and "id" in printer_profile else "_default" - } + state, port, baudrate, printer_profile = printer.get_current_connection() + current = { + "state": state, + "port": port, + "baudrate": baudrate, + "printerProfile": printer_profile["id"] + if printer_profile is not None and "id" in printer_profile + else "_default", + } - return jsonify({"current": current, "options": _get_options()}) + return jsonify({"current": current, "options": _get_options()}) @api.route("/connection", methods=["POST"]) @no_firstrun_access @Permissions.CONNECTION.require(403) def connectionCommand(): - valid_commands = { - "connect": [], - "disconnect": [], - "fake_ack": [] - } + valid_commands = {"connect": [], "disconnect": [], "fake_ack": []} - command, data, response = get_json_command_from_request(request, valid_commands) - if response is not None: - return response + command, data, response = get_json_command_from_request(request, valid_commands) + if response is not None: + return response - if command == "connect": - connection_options = printer.__class__.get_connection_options() + if command == "connect": + connection_options = printer.__class__.get_connection_options() - port = None - baudrate = None - printerProfile = None - if "port" in data: - port = data["port"] - if port not in connection_options["ports"] and port != "AUTO": - return make_response("Invalid port: %s" % port, 400) - if "baudrate" in data: - baudrate = data["baudrate"] - if baudrate not in connection_options["baudrates"] and baudrate != 0: - return make_response("Invalid baudrate: %d" % baudrate, 400) - if "printerProfile" in data: - printerProfile = data["printerProfile"] - if not printerProfileManager.exists(printerProfile): - return make_response("Invalid printer profile: %s" % printerProfile, 400) - if "save" in data and data["save"]: - settings().set(["serial", "port"], port) - settings().setInt(["serial", "baudrate"], baudrate) - printerProfileManager.set_default(printerProfile) - if "autoconnect" in data: - settings().setBoolean(["serial", "autoconnect"], data["autoconnect"]) - settings().save() - printer.connect(port=port, baudrate=baudrate, profile=printerProfile) - elif command == "disconnect": - printer.disconnect() - elif command == "fake_ack": - printer.fake_ack() + port = None + baudrate = None + printerProfile = None + if "port" in data: + port = data["port"] + if port not in connection_options["ports"] and port != "AUTO": + return make_response("Invalid port: %s" % port, 400) + if "baudrate" in data: + baudrate = data["baudrate"] + if baudrate not in connection_options["baudrates"] and baudrate != 0: + return make_response("Invalid baudrate: %d" % baudrate, 400) + if "printerProfile" in data: + printerProfile = data["printerProfile"] + if not printerProfileManager.exists(printerProfile): + return make_response("Invalid printer profile: %s" % printerProfile, 400) + if "save" in data and data["save"]: + settings().set(["serial", "port"], port) + settings().setInt(["serial", "baudrate"], baudrate) + printerProfileManager.set_default(printerProfile) + if "autoconnect" in data: + settings().setBoolean(["serial", "autoconnect"], data["autoconnect"]) + settings().save() + printer.connect(port=port, baudrate=baudrate, profile=printerProfile) + elif command == "disconnect": + printer.disconnect() + elif command == "fake_ack": + printer.fake_ack() + + return NO_CONTENT - return NO_CONTENT def _get_options(): - connection_options = printer.__class__.get_connection_options() - profile_options = printerProfileManager.get_all() - default_profile = printerProfileManager.get_default() + connection_options = printer.__class__.get_connection_options() + profile_options = printerProfileManager.get_all() + default_profile = printerProfileManager.get_default() - options = {"ports": connection_options["ports"], - "baudrates": connection_options["baudrates"], - "printerProfiles": [{"id": printer_profile["id"], "name": printer_profile["name"] if "name" in printer_profile else printer_profile["id"]} for printer_profile in profile_options.values() if "id" in printer_profile], - "portPreference": connection_options["portPreference"], - "baudratePreference": connection_options["baudratePreference"], - "printerProfilePreference": default_profile["id"] if "id" in default_profile else None} + options = { + "ports": connection_options["ports"], + "baudrates": connection_options["baudrates"], + "printerProfiles": [ + { + "id": printer_profile["id"], + "name": printer_profile["name"] + if "name" in printer_profile + else printer_profile["id"], + } + for printer_profile in profile_options.values() + if "id" in printer_profile + ], + "portPreference": connection_options["portPreference"], + "baudratePreference": connection_options["baudratePreference"], + "printerProfilePreference": default_profile["id"] + if "id" in default_profile + else None, + } - return options + return options diff --git a/src/octoprint/server/api/files.py b/src/octoprint/server/api/files.py index fcd9f6fa5..9a073e2ef 100644 --- a/src/octoprint/server/api/files.py +++ b/src/octoprint/server/api/files.py @@ -2,15 +2,26 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" from flask import request, jsonify, make_response, url_for from octoprint.filemanager.destinations import FileDestinations from octoprint.settings import settings, valid_boolean_trues -from octoprint.server import printer, fileManager, slicingManager, eventManager, NO_CONTENT, current_user -from octoprint.server.util.flask import no_firstrun_access, get_json_command_from_request, with_revalidation_checking +from octoprint.server import ( + printer, + fileManager, + slicingManager, + eventManager, + NO_CONTENT, + current_user, +) +from octoprint.server.util.flask import ( + no_firstrun_access, + get_json_command_from_request, + with_revalidation_checking, +) from octoprint.server.api import api from octoprint.events import Events from octoprint.access.permissions import Permissions @@ -29,838 +40,1216 @@ import logging import threading -#~~ GCODE file handling +# ~~ GCODE file handling _file_cache = {} _file_cache_mutex = threading.RLock() _DATA_FORMAT_VERSION = "v2" + def _clear_file_cache(): - with _file_cache_mutex: - _file_cache.clear() + with _file_cache_mutex: + _file_cache.clear() + def _create_lastmodified(path, recursive): - path = path[len("/api/files"):] - if path.startswith("/"): - path = path[1:] + path = path[len("/api/files") :] + if path.startswith("/"): + path = path[1:] - if path == "": - # all storages involved - lms = [0] - for storage in fileManager.registered_storages: - try: - lms.append(fileManager.last_modified(storage, recursive=recursive)) - except Exception: - logging.getLogger(__name__).exception("There was an error retrieving the last modified data from storage {}".format(storage)) - lms.append(None) + if path == "": + # all storages involved + lms = [0] + for storage in fileManager.registered_storages: + try: + lms.append(fileManager.last_modified(storage, recursive=recursive)) + except Exception: + logging.getLogger(__name__).exception( + "There was an error retrieving the last modified data from storage {}".format( + storage + ) + ) + lms.append(None) - if any(filter(lambda x: x is None, lms)): - # we return None if ANY of the involved storages returned None - return None + if any(filter(lambda x: x is None, lms)): + # we return None if ANY of the involved storages returned None + return None - # if we reach this point, we return the maximum of all dates - return max(lms) + # if we reach this point, we return the maximum of all dates + return max(lms) - else: - if "/" in path: - storage, path_in_storage = path.split("/", 1) - else: - storage = path - path_in_storage = None + else: + if "/" in path: + storage, path_in_storage = path.split("/", 1) + else: + storage = path + path_in_storage = None - try: - return fileManager.last_modified(storage, path=path_in_storage, recursive=recursive) - except Exception: - logging.getLogger(__name__).exception("There was an error retrieving the last modified data from storage {} and path {}".format(storage, path_in_storage)) - return None + try: + return fileManager.last_modified( + storage, path=path_in_storage, recursive=recursive + ) + except Exception: + logging.getLogger(__name__).exception( + "There was an error retrieving the last modified data from storage {} and path {}".format( + storage, path_in_storage + ) + ) + return None def _create_etag(path, filter, recursive, lm=None): - if lm is None: - lm = _create_lastmodified(path, recursive) + if lm is None: + lm = _create_lastmodified(path, recursive) - if lm is None: - return None + if lm is None: + return None - hash = hashlib.sha1() - def hash_update(value): - value = value.encode('utf-8') - hash.update(value) - hash_update(str(lm)) - hash_update(str(filter)) - hash_update(str(recursive)) + hash = hashlib.sha1() - path = path[len("/api/files"):] - if path.startswith("/"): - path = path[1:] + def hash_update(value): + value = value.encode("utf-8") + hash.update(value) - if "/" in path: - storage, _ = path.split("/", 1) - else: - storage = path + hash_update(str(lm)) + hash_update(str(filter)) + hash_update(str(recursive)) - if path == "" or storage == FileDestinations.SDCARD: - # include sd data in etag - hash_update(repr(sorted(printer.get_sd_files(), key=lambda x: sv(x["name"])))) + path = path[len("/api/files") :] + if path.startswith("/"): + path = path[1:] - hash_update(_DATA_FORMAT_VERSION) # increment version if we change the API format + if "/" in path: + storage, _ = path.split("/", 1) + else: + storage = path - return hash.hexdigest() + if path == "" or storage == FileDestinations.SDCARD: + # include sd data in etag + hash_update(repr(sorted(printer.get_sd_files(), key=lambda x: sv(x["name"])))) + + hash_update(_DATA_FORMAT_VERSION) # increment version if we change the API format + + return hash.hexdigest() @api.route("/files", methods=["GET"]) @Permissions.FILES_LIST.require(403) -@with_revalidation_checking(etag_factory=lambda lm=None: _create_etag(request.path, - request.values.get("filter", False), - request.values.get("recursive", False), - lm=lm), - lastmodified_factory=lambda: _create_lastmodified(request.path, - request.values.get("recursive", False)), - unless=lambda: request.values.get("force", False) or request.values.get("_refresh", False)) +@with_revalidation_checking( + etag_factory=lambda lm=None: _create_etag( + request.path, + request.values.get("filter", False), + request.values.get("recursive", False), + lm=lm, + ), + lastmodified_factory=lambda: _create_lastmodified( + request.path, request.values.get("recursive", False) + ), + unless=lambda: request.values.get("force", False) + or request.values.get("_refresh", False), +) def readGcodeFiles(): - filter = request.values.get("filter", False) - recursive = request.values.get("recursive", "false") in valid_boolean_trues - force = request.values.get("force", "false") in valid_boolean_trues + filter = request.values.get("filter", False) + recursive = request.values.get("recursive", "false") in valid_boolean_trues + force = request.values.get("force", "false") in valid_boolean_trues - files = _getFileList(FileDestinations.LOCAL, filter=filter, recursive=recursive, allow_from_cache=not force) - files.extend(_getFileList(FileDestinations.SDCARD)) + files = _getFileList( + FileDestinations.LOCAL, + filter=filter, + recursive=recursive, + allow_from_cache=not force, + ) + files.extend(_getFileList(FileDestinations.SDCARD)) - usage = psutil.disk_usage(settings().getBaseFolder("uploads", check_writable=False)) - return jsonify(files=files, free=usage.free, total=usage.total) + usage = psutil.disk_usage(settings().getBaseFolder("uploads", check_writable=False)) + return jsonify(files=files, free=usage.free, total=usage.total) @api.route("/files/", methods=["GET"]) @Permissions.FILES_LIST.require(403) -@with_revalidation_checking(etag_factory=lambda lm=None: _create_etag(request.path, - request.values.get("filter", False), - request.values.get("recursive", False), - lm=lm), - lastmodified_factory=lambda: _create_lastmodified(request.path, - request.values.get("recursive", False)), - unless=lambda: request.values.get("force", False) or request.values.get("_refresh", False)) +@with_revalidation_checking( + etag_factory=lambda lm=None: _create_etag( + request.path, + request.values.get("filter", False), + request.values.get("recursive", False), + lm=lm, + ), + lastmodified_factory=lambda: _create_lastmodified( + request.path, request.values.get("recursive", False) + ), + unless=lambda: request.values.get("force", False) + or request.values.get("_refresh", False), +) def readGcodeFilesForOrigin(origin): - if origin not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: - return make_response("Unknown origin: %s" % origin, 404) + if origin not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: + return make_response("Unknown origin: %s" % origin, 404) - filter = request.values.get("filter", False) - recursive = request.values.get("recursive", "false") in valid_boolean_trues - force = request.values.get("force", "false") in valid_boolean_trues + filter = request.values.get("filter", False) + recursive = request.values.get("recursive", "false") in valid_boolean_trues + force = request.values.get("force", "false") in valid_boolean_trues - files = _getFileList(origin, filter=filter, recursive=recursive, allow_from_cache=not force) + files = _getFileList( + origin, filter=filter, recursive=recursive, allow_from_cache=not force + ) - if origin == FileDestinations.LOCAL: - usage = psutil.disk_usage(settings().getBaseFolder("uploads", check_writable=False)) - return jsonify(files=files, free=usage.free, total=usage.total) - else: - return jsonify(files=files) + if origin == FileDestinations.LOCAL: + usage = psutil.disk_usage( + settings().getBaseFolder("uploads", check_writable=False) + ) + return jsonify(files=files, free=usage.free, total=usage.total) + else: + return jsonify(files=files) @api.route("/files//", methods=["GET"]) @Permissions.FILES_LIST.require(403) -@with_revalidation_checking(etag_factory=lambda lm=None: _create_etag(request.path, - request.values.get("filter", False), - request.values.get("recursive", False), - lm=lm), - lastmodified_factory=lambda: _create_lastmodified(request.path, - request.values.get("recursive", False)), - unless=lambda: request.values.get("force", False) or request.values.get("_refresh", False)) +@with_revalidation_checking( + etag_factory=lambda lm=None: _create_etag( + request.path, + request.values.get("filter", False), + request.values.get("recursive", False), + lm=lm, + ), + lastmodified_factory=lambda: _create_lastmodified( + request.path, request.values.get("recursive", False) + ), + unless=lambda: request.values.get("force", False) + or request.values.get("_refresh", False), +) def readGcodeFile(target, filename): - if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: - return make_response("Unknown target: %s" % target, 404) + if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: + return make_response("Unknown target: %s" % target, 404) - recursive = False - if "recursive" in request.values: - recursive = request.values["recursive"] in valid_boolean_trues + recursive = False + if "recursive" in request.values: + recursive = request.values["recursive"] in valid_boolean_trues - file = _getFileDetails(target, filename, recursive=recursive) - if not file: - return make_response("File not found on '%s': %s" % (target, filename), 404) + file = _getFileDetails(target, filename, recursive=recursive) + if not file: + return make_response("File not found on '%s': %s" % (target, filename), 404) - return jsonify(file) + return jsonify(file) def _getFileDetails(origin, path, recursive=True): - parent, path = os.path.split(path) - files = _getFileList(origin, path=parent, recursive=recursive) + parent, path = os.path.split(path) + files = _getFileList(origin, path=parent, recursive=recursive) - for f in files: - if f["name"] == path: - return f - else: - return None + for f in files: + if f["name"] == path: + return f + else: + return None -@time_this(logtarget=__name__+'.timings', message="{func}({func_args},{func_kwargs}) took {timing:.2f}ms", incl_func_args=True) +@time_this( + logtarget=__name__ + ".timings", + message="{func}({func_args},{func_kwargs}) took {timing:.2f}ms", + incl_func_args=True, +) def _getFileList(origin, path=None, filter=None, recursive=False, allow_from_cache=True): - if origin == FileDestinations.SDCARD: - sdFileList = printer.get_sd_files() + if origin == FileDestinations.SDCARD: + sdFileList = printer.get_sd_files() - files = [] - if sdFileList is not None: - for f in sdFileList: - type_path = octoprint.filemanager.get_file_type(f["name"]) - if not type_path: - # only supported extensions - continue - else: - file_type = type_path[0] + files = [] + if sdFileList is not None: + for f in sdFileList: + type_path = octoprint.filemanager.get_file_type(f["name"]) + if not type_path: + # only supported extensions + continue + else: + file_type = type_path[0] - file = { - "type": file_type, - "typePath": type_path, - "name": f["name"], - "display": f["display"] if f["display"] else f["name"], - "path": f["name"], - "origin": FileDestinations.SDCARD, - "refs": { - "resource": url_for(".readGcodeFile", - target=FileDestinations.SDCARD, - filename=f["name"], - _external=True) - } - } - if f["size"] is not None: - file.update({"size": f["size"]}) - files.append(file) - else: - filter_func = None - if filter: - filter_func = lambda entry, entry_data: octoprint.filemanager.valid_file_type(entry, type=filter) + file = { + "type": file_type, + "typePath": type_path, + "name": f["name"], + "display": f["display"] if f["display"] else f["name"], + "path": f["name"], + "origin": FileDestinations.SDCARD, + "refs": { + "resource": url_for( + ".readGcodeFile", + target=FileDestinations.SDCARD, + filename=f["name"], + _external=True, + ) + }, + } + if f["size"] is not None: + file.update({"size": f["size"]}) + files.append(file) + else: + filter_func = None + if filter: + filter_func = lambda entry, entry_data: octoprint.filemanager.valid_file_type( + entry, type=filter + ) - with _file_cache_mutex: - cache_key = "{}:{}:{}:{}".format(origin, path, recursive, filter) - files, lastmodified = _file_cache.get(cache_key, ([], None)) - # recursive needs to be True for lastmodified queries so we get lastmodified of whole subtree - #3422 - if not allow_from_cache or lastmodified is None or lastmodified < fileManager.last_modified(origin, path=path, recursive=True): - files = list(fileManager.list_files(origin, path=path, filter=filter_func, recursive=recursive, force_refresh=not allow_from_cache)[origin].values()) - lastmodified = fileManager.last_modified(origin, path=path, recursive=True) - _file_cache[cache_key] = (files, lastmodified) + with _file_cache_mutex: + cache_key = "{}:{}:{}:{}".format(origin, path, recursive, filter) + files, lastmodified = _file_cache.get(cache_key, ([], None)) + # recursive needs to be True for lastmodified queries so we get lastmodified of whole subtree - #3422 + if ( + not allow_from_cache + or lastmodified is None + or lastmodified + < fileManager.last_modified(origin, path=path, recursive=True) + ): + files = list( + fileManager.list_files( + origin, + path=path, + filter=filter_func, + recursive=recursive, + force_refresh=not allow_from_cache, + )[origin].values() + ) + lastmodified = fileManager.last_modified( + origin, path=path, recursive=True + ) + _file_cache[cache_key] = (files, lastmodified) - def analyse_recursively(files, path=None): - if path is None: - path = "" + def analyse_recursively(files, path=None): + if path is None: + path = "" - result = [] - for file_or_folder in files: - # make a shallow copy in order to not accidentally modify the cached data - file_or_folder = dict(file_or_folder) + result = [] + for file_or_folder in files: + # make a shallow copy in order to not accidentally modify the cached data + file_or_folder = dict(file_or_folder) - file_or_folder["origin"] = FileDestinations.LOCAL + file_or_folder["origin"] = FileDestinations.LOCAL - if file_or_folder["type"] == "folder": - if "children" in file_or_folder: - file_or_folder["children"] = analyse_recursively(file_or_folder["children"].values(), path + file_or_folder["name"] + "/") + if file_or_folder["type"] == "folder": + if "children" in file_or_folder: + file_or_folder["children"] = analyse_recursively( + file_or_folder["children"].values(), + path + file_or_folder["name"] + "/", + ) - file_or_folder["refs"] = {"resource": url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=path + file_or_folder["name"], _external=True)} - else: - if "analysis" in file_or_folder and octoprint.filemanager.valid_file_type(file_or_folder["name"], type="gcode"): - file_or_folder["gcodeAnalysis"] = file_or_folder["analysis"] - del file_or_folder["analysis"] + file_or_folder["refs"] = { + "resource": url_for( + ".readGcodeFile", + target=FileDestinations.LOCAL, + filename=path + file_or_folder["name"], + _external=True, + ) + } + else: + if ( + "analysis" in file_or_folder + and octoprint.filemanager.valid_file_type( + file_or_folder["name"], type="gcode" + ) + ): + file_or_folder["gcodeAnalysis"] = file_or_folder["analysis"] + del file_or_folder["analysis"] - if "history" in file_or_folder and octoprint.filemanager.valid_file_type(file_or_folder["name"], type="gcode"): - # convert print log - history = file_or_folder["history"] - del file_or_folder["history"] - success = 0 - failure = 0 - last = None - for entry in history: - success += 1 if "success" in entry and entry["success"] else 0 - failure += 1 if "success" in entry and not entry["success"] else 0 - if not last or ("timestamp" in entry and "timestamp" in last and entry["timestamp"] > last["timestamp"]): - last = entry - if last: - prints = {"success": success, - "failure": failure, - "last": {"success": last["success"], - "date": last["timestamp"]}} - if "printTime" in last: - prints["last"]["printTime"] = last["printTime"] - file_or_folder["prints"] = prints + if ( + "history" in file_or_folder + and octoprint.filemanager.valid_file_type( + file_or_folder["name"], type="gcode" + ) + ): + # convert print log + history = file_or_folder["history"] + del file_or_folder["history"] + success = 0 + failure = 0 + last = None + for entry in history: + success += 1 if "success" in entry and entry["success"] else 0 + failure += ( + 1 if "success" in entry and not entry["success"] else 0 + ) + if not last or ( + "timestamp" in entry + and "timestamp" in last + and entry["timestamp"] > last["timestamp"] + ): + last = entry + if last: + prints = { + "success": success, + "failure": failure, + "last": { + "success": last["success"], + "date": last["timestamp"], + }, + } + if "printTime" in last: + prints["last"]["printTime"] = last["printTime"] + file_or_folder["prints"] = prints - file_or_folder["refs"] = {"resource": url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=file_or_folder["path"], _external=True), - "download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + file_or_folder["path"]} + file_or_folder["refs"] = { + "resource": url_for( + ".readGcodeFile", + target=FileDestinations.LOCAL, + filename=file_or_folder["path"], + _external=True, + ), + "download": url_for("index", _external=True) + + "downloads/files/" + + FileDestinations.LOCAL + + "/" + + file_or_folder["path"], + } - result.append(file_or_folder) + result.append(file_or_folder) - return result + return result - files = analyse_recursively(files) + files = analyse_recursively(files) - return files + return files def _verifyFileExists(origin, filename): - if origin == FileDestinations.SDCARD: - return filename in (x["name"] for x in printer.get_sd_files()) - else: - return fileManager.file_exists(origin, filename) + if origin == FileDestinations.SDCARD: + return filename in (x["name"] for x in printer.get_sd_files()) + else: + return fileManager.file_exists(origin, filename) def _verifyFolderExists(origin, foldername): - if origin == FileDestinations.SDCARD: - return False - else: - return fileManager.folder_exists(origin, foldername) + if origin == FileDestinations.SDCARD: + return False + else: + return fileManager.folder_exists(origin, foldername) def _isBusy(target, path): - currentOrigin, currentPath = _getCurrentFile() - if currentPath is not None and currentOrigin == target and fileManager.file_in_path(FileDestinations.LOCAL, path, currentPath) and (printer.is_printing() or printer.is_paused()): - return True + currentOrigin, currentPath = _getCurrentFile() + if ( + currentPath is not None + and currentOrigin == target + and fileManager.file_in_path(FileDestinations.LOCAL, path, currentPath) + and (printer.is_printing() or printer.is_paused()) + ): + return True + + return any( + target == x[0] and fileManager.file_in_path(FileDestinations.LOCAL, path, x[1]) + for x in fileManager.get_busy_files() + ) - return any(target == x[0] and fileManager.file_in_path(FileDestinations.LOCAL, path, x[1]) for x in fileManager.get_busy_files()) @api.route("/files/", methods=["POST"]) @no_firstrun_access @Permissions.FILES_UPLOAD.require(403) def uploadGcodeFile(target): - input_name = "file" - input_upload_name = input_name + "." + settings().get(["server", "uploads", "nameSuffix"]) - input_upload_path = input_name + "." + settings().get(["server", "uploads", "pathSuffix"]) - if input_upload_name in request.values and input_upload_path in request.values: - if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: - return make_response("Unknown target: %s" % target, 404) + input_name = "file" + input_upload_name = ( + input_name + "." + settings().get(["server", "uploads", "nameSuffix"]) + ) + input_upload_path = ( + input_name + "." + settings().get(["server", "uploads", "pathSuffix"]) + ) + if input_upload_name in request.values and input_upload_path in request.values: + if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: + return make_response("Unknown target: %s" % target, 404) - upload = octoprint.filemanager.util.DiskFileWrapper(request.values[input_upload_name], request.values[input_upload_path]) + upload = octoprint.filemanager.util.DiskFileWrapper( + request.values[input_upload_name], request.values[input_upload_path] + ) - # Store any additional user data the caller may have passed. - userdata = None - if "userdata" in request.values: - import json - try: - userdata = json.loads(request.values["userdata"]) - except Exception: - return make_response("userdata contains invalid JSON", 400) + # Store any additional user data the caller may have passed. + userdata = None + if "userdata" in request.values: + import json - if target == FileDestinations.SDCARD and not settings().getBoolean(["feature", "sdSupport"]): - return make_response("SD card support is disabled", 404) + try: + userdata = json.loads(request.values["userdata"]) + except Exception: + return make_response("userdata contains invalid JSON", 400) - sd = target == FileDestinations.SDCARD - selectAfterUpload = "select" in request.values and request.values["select"] in valid_boolean_trues and Permissions.FILES_SELECT.can() - printAfterSelect = "print" in request.values and request.values["print"] in valid_boolean_trues and Permissions.PRINT.can() + if target == FileDestinations.SDCARD and not settings().getBoolean( + ["feature", "sdSupport"] + ): + return make_response("SD card support is disabled", 404) - if sd: - # validate that all preconditions for SD upload are met before attempting it - if not (printer.is_operational() and not (printer.is_printing() or printer.is_paused())): - return make_response("Can not upload to SD card, printer is either not operational or already busy", 409) - if not printer.is_sd_ready(): - return make_response("Can not upload to SD card, not yet initialized", 409) + sd = target == FileDestinations.SDCARD + selectAfterUpload = ( + "select" in request.values + and request.values["select"] in valid_boolean_trues + and Permissions.FILES_SELECT.can() + ) + printAfterSelect = ( + "print" in request.values + and request.values["print"] in valid_boolean_trues + and Permissions.PRINT.can() + ) - # determine future filename of file to be uploaded, abort if it can't be uploaded - try: - # FileDestinations.LOCAL = should normally be target, but can't because SDCard handling isn't implemented yet - canonPath, canonFilename = fileManager.canonicalize(FileDestinations.LOCAL, upload.filename) - futurePath = fileManager.sanitize_path(FileDestinations.LOCAL, canonPath) - futureFilename = fileManager.sanitize_name(FileDestinations.LOCAL, canonFilename) - except Exception: - canonFilename = None - futurePath = None - futureFilename = None + if sd: + # validate that all preconditions for SD upload are met before attempting it + if not ( + printer.is_operational() + and not (printer.is_printing() or printer.is_paused()) + ): + return make_response( + "Can not upload to SD card, printer is either not operational or already busy", + 409, + ) + if not printer.is_sd_ready(): + return make_response( + "Can not upload to SD card, not yet initialized", 409 + ) - if futureFilename is None: - return make_response("Can not upload file %s, wrong format?" % upload.filename, 415) + # determine future filename of file to be uploaded, abort if it can't be uploaded + try: + # FileDestinations.LOCAL = should normally be target, but can't because SDCard handling isn't implemented yet + canonPath, canonFilename = fileManager.canonicalize( + FileDestinations.LOCAL, upload.filename + ) + futurePath = fileManager.sanitize_path(FileDestinations.LOCAL, canonPath) + futureFilename = fileManager.sanitize_name( + FileDestinations.LOCAL, canonFilename + ) + except Exception: + canonFilename = None + futurePath = None + futureFilename = None - if "path" in request.values and request.values["path"]: - # we currently only support uploads to sdcard via local, so first target is local instead of "target" - futurePath = fileManager.sanitize_path(FileDestinations.LOCAL, request.values["path"]) + if futureFilename is None: + return make_response( + "Can not upload file %s, wrong format?" % upload.filename, 415 + ) - # prohibit overwriting currently selected file while it's being printed - futureFullPath = fileManager.join_path(FileDestinations.LOCAL, futurePath, futureFilename) - futureFullPathInStorage = fileManager.path_in_storage(FileDestinations.LOCAL, futureFullPath) + if "path" in request.values and request.values["path"]: + # we currently only support uploads to sdcard via local, so first target is local instead of "target" + futurePath = fileManager.sanitize_path( + FileDestinations.LOCAL, request.values["path"] + ) - if not printer.can_modify_file(futureFullPathInStorage, sd): - return make_response("Trying to overwrite file that is currently being printed: %s" % futureFullPath, 409) + # prohibit overwriting currently selected file while it's being printed + futureFullPath = fileManager.join_path( + FileDestinations.LOCAL, futurePath, futureFilename + ) + futureFullPathInStorage = fileManager.path_in_storage( + FileDestinations.LOCAL, futureFullPath + ) - reselect = printer.is_current_file(futureFullPathInStorage, sd) + if not printer.can_modify_file(futureFullPathInStorage, sd): + return make_response( + "Trying to overwrite file that is currently being printed: %s" + % futureFullPath, + 409, + ) - user = current_user.get_name() + reselect = printer.is_current_file(futureFullPathInStorage, sd) - def fileProcessingFinished(filename, absFilename, destination): - """ - Callback for when the file processing (upload, optional slicing, addition to analysis queue) has - finished. + user = current_user.get_name() - Depending on the file's destination triggers either streaming to SD card or directly calls selectAndOrPrint. - """ + def fileProcessingFinished(filename, absFilename, destination): + """ + Callback for when the file processing (upload, optional slicing, addition to analysis queue) has + finished. - if destination == FileDestinations.SDCARD and octoprint.filemanager.valid_file_type(filename, "machinecode"): - return filename, printer.add_sd_file(filename, absFilename, - on_success=selectAndOrPrint, - tags={"source:api", "api:files.sd"}) - else: - selectAndOrPrint(filename, absFilename, destination) - return filename + Depending on the file's destination triggers either streaming to SD card or directly calls selectAndOrPrint. + """ - def selectAndOrPrint(filename, absFilename, destination): - """ - Callback for when the file is ready to be selected and optionally printed. For SD file uploads this is only - the case after they have finished streaming to the printer, which is why this callback is also used - for the corresponding call to addSdFile. + if ( + destination == FileDestinations.SDCARD + and octoprint.filemanager.valid_file_type(filename, "machinecode") + ): + return filename, printer.add_sd_file( + filename, + absFilename, + on_success=selectAndOrPrint, + tags={"source:api", "api:files.sd"}, + ) + else: + selectAndOrPrint(filename, absFilename, destination) + return filename - Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the - exact file is already selected, such reloading it. - """ - if octoprint.filemanager.valid_file_type(added_file, "gcode") and (selectAfterUpload or printAfterSelect or reselect): - printer.select_file(absFilename, destination == FileDestinations.SDCARD, printAfterSelect, user) + def selectAndOrPrint(filename, absFilename, destination): + """ + Callback for when the file is ready to be selected and optionally printed. For SD file uploads this is only + the case after they have finished streaming to the printer, which is why this callback is also used + for the corresponding call to addSdFile. - try: - added_file = fileManager.add_file(FileDestinations.LOCAL, futureFullPathInStorage, upload, - allow_overwrite=True, - display=canonFilename) - except octoprint.filemanager.storage.StorageError as e: - if e.code == octoprint.filemanager.storage.StorageError.INVALID_FILE: - return make_response("Could not upload the file \"{}\", invalid type".format(upload.filename), 400) - else: - return make_response("Could not upload the file \"{}\"".format(upload.filename), 500) + Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the + exact file is already selected, such reloading it. + """ + if octoprint.filemanager.valid_file_type(added_file, "gcode") and ( + selectAfterUpload or printAfterSelect or reselect + ): + printer.select_file( + absFilename, + destination == FileDestinations.SDCARD, + printAfterSelect, + user, + ) - if octoprint.filemanager.valid_file_type(added_file, "stl"): - filename = added_file - done = True - else: - filename = fileProcessingFinished(added_file, fileManager.path_on_disk(FileDestinations.LOCAL, added_file), target) - done = not sd + try: + added_file = fileManager.add_file( + FileDestinations.LOCAL, + futureFullPathInStorage, + upload, + allow_overwrite=True, + display=canonFilename, + ) + except octoprint.filemanager.storage.StorageError as e: + if e.code == octoprint.filemanager.storage.StorageError.INVALID_FILE: + return make_response( + 'Could not upload the file "{}", invalid type'.format( + upload.filename + ), + 400, + ) + else: + return make_response( + 'Could not upload the file "{}"'.format(upload.filename), 500 + ) - if userdata is not None: - # upload included userdata, add this now to the metadata - fileManager.set_additional_metadata(FileDestinations.LOCAL, added_file, "userdata", userdata) + if octoprint.filemanager.valid_file_type(added_file, "stl"): + filename = added_file + done = True + else: + filename = fileProcessingFinished( + added_file, + fileManager.path_on_disk(FileDestinations.LOCAL, added_file), + target, + ) + done = not sd - sdFilename = None - if isinstance(filename, tuple): - filename, sdFilename = filename + if userdata is not None: + # upload included userdata, add this now to the metadata + fileManager.set_additional_metadata( + FileDestinations.LOCAL, added_file, "userdata", userdata + ) - payload = {"name": futureFilename, - "path": filename, - "target": target, - "select": selectAfterUpload, - "print": printAfterSelect} - if userdata is not None: - payload["userdata"] = userdata - eventManager.fire(Events.UPLOAD, payload) + sdFilename = None + if isinstance(filename, tuple): + filename, sdFilename = filename - files = {} - location = url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=filename, _external=True) - files.update({ - FileDestinations.LOCAL: { - "name": futureFilename, - "path": filename, - "origin": FileDestinations.LOCAL, - "refs": { - "resource": location, - "download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + filename - } - } - }) + payload = { + "name": futureFilename, + "path": filename, + "target": target, + "select": selectAfterUpload, + "print": printAfterSelect, + } + if userdata is not None: + payload["userdata"] = userdata + eventManager.fire(Events.UPLOAD, payload) - if sd and sdFilename: - location = url_for(".readGcodeFile", target=FileDestinations.SDCARD, filename=sdFilename, _external=True) - files.update({ - FileDestinations.SDCARD: { - "name": sdFilename, - "path": sdFilename, - "origin": FileDestinations.SDCARD, - "refs": { - "resource": location - } - } - }) + files = {} + location = url_for( + ".readGcodeFile", + target=FileDestinations.LOCAL, + filename=filename, + _external=True, + ) + files.update( + { + FileDestinations.LOCAL: { + "name": futureFilename, + "path": filename, + "origin": FileDestinations.LOCAL, + "refs": { + "resource": location, + "download": url_for("index", _external=True) + + "downloads/files/" + + FileDestinations.LOCAL + + "/" + + filename, + }, + } + } + ) - r = make_response(jsonify(files=files, done=done), 201) - r.headers["Location"] = location - return r + if sd and sdFilename: + location = url_for( + ".readGcodeFile", + target=FileDestinations.SDCARD, + filename=sdFilename, + _external=True, + ) + files.update( + { + FileDestinations.SDCARD: { + "name": sdFilename, + "path": sdFilename, + "origin": FileDestinations.SDCARD, + "refs": {"resource": location}, + } + } + ) - elif "foldername" in request.values: - foldername = request.values["foldername"] + r = make_response(jsonify(files=files, done=done), 201) + r.headers["Location"] = location + return r - if not target in [FileDestinations.LOCAL]: - return make_response("Unknown target: %s" % target, 400) + elif "foldername" in request.values: + foldername = request.values["foldername"] - canonPath, canonName = fileManager.canonicalize(target, foldername) - futurePath = fileManager.sanitize_path(target, canonPath) - futureName = fileManager.sanitize_name(target, canonName) - if not futureName or not futurePath: - return make_response("Can't create a folder with an empty name", 400) + if not target in [FileDestinations.LOCAL]: + return make_response("Unknown target: %s" % target, 400) - if "path" in request.values and request.values["path"]: - futurePath = fileManager.sanitize_path(FileDestinations.LOCAL, - request.values["path"]) + canonPath, canonName = fileManager.canonicalize(target, foldername) + futurePath = fileManager.sanitize_path(target, canonPath) + futureName = fileManager.sanitize_name(target, canonName) + if not futureName or not futurePath: + return make_response("Can't create a folder with an empty name", 400) - futureFullPath = fileManager.join_path(target, futurePath, futureName) - if octoprint.filemanager.valid_file_type(futureName): - return make_response("Can't create a folder named %s, please try another name" % futureName, 409) + if "path" in request.values and request.values["path"]: + futurePath = fileManager.sanitize_path( + FileDestinations.LOCAL, request.values["path"] + ) - try: - added_folder = fileManager.add_folder(target, futureFullPath, display=canonName) - except octoprint.filemanager.storage.StorageError as e: - if e.code == octoprint.filemanager.storage.StorageError.INVALID_DIRECTORY: - return make_response("Could not create folder {}, invalid directory".format(futureName)) - else: - return make_response("Could not create folder {}".format(futureName)) + futureFullPath = fileManager.join_path(target, futurePath, futureName) + if octoprint.filemanager.valid_file_type(futureName): + return make_response( + "Can't create a folder named %s, please try another name" % futureName, + 409, + ) - location = url_for(".readGcodeFile", - target=FileDestinations.LOCAL, - filename=added_folder, - _external=True) - folder = {"name": futureName, - "path": added_folder, - "origin": target, - "refs": {"resource": location}} + try: + added_folder = fileManager.add_folder( + target, futureFullPath, display=canonName + ) + except octoprint.filemanager.storage.StorageError as e: + if e.code == octoprint.filemanager.storage.StorageError.INVALID_DIRECTORY: + return make_response( + "Could not create folder {}, invalid directory".format(futureName) + ) + else: + return make_response("Could not create folder {}".format(futureName)) - r = make_response(jsonify(folder=folder, done=True), 201) - r.headers["Location"] = location - return r + location = url_for( + ".readGcodeFile", + target=FileDestinations.LOCAL, + filename=added_folder, + _external=True, + ) + folder = { + "name": futureName, + "path": added_folder, + "origin": target, + "refs": {"resource": location}, + } - else: - return make_response("No file to upload and no folder to create", 400) + r = make_response(jsonify(folder=folder, done=True), 201) + r.headers["Location"] = location + return r + + else: + return make_response("No file to upload and no folder to create", 400) @api.route("/files//", methods=["POST"]) @no_firstrun_access def gcodeFileCommand(filename, target): - if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: - return make_response("Unknown target: %s" % target, 404) + if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: + return make_response("Unknown target: %s" % target, 404) - # valid file commands, dict mapping command name to mandatory parameters - valid_commands = { - "select": [], - "slice": [], - "analyse": [], - "copy": ["destination"], - "move": ["destination"] - } + # valid file commands, dict mapping command name to mandatory parameters + valid_commands = { + "select": [], + "slice": [], + "analyse": [], + "copy": ["destination"], + "move": ["destination"], + } - command, data, response = get_json_command_from_request(request, valid_commands) - if response is not None: - return response + command, data, response = get_json_command_from_request(request, valid_commands) + if response is not None: + return response - user = current_user.get_name() + user = current_user.get_name() - if command == "select": - with Permissions.FILES_SELECT.require(403): - if not _verifyFileExists(target, filename): - return make_response("File not found on '%s': %s" % (target, filename), 404) + if command == "select": + with Permissions.FILES_SELECT.require(403): + if not _verifyFileExists(target, filename): + return make_response( + "File not found on '%s': %s" % (target, filename), 404 + ) - # selects/loads a file - if not octoprint.filemanager.valid_file_type(filename, type="machinecode"): - return make_response("Cannot select {filename} for printing, not a machinecode file".format(**locals()), 415) + # selects/loads a file + if not octoprint.filemanager.valid_file_type(filename, type="machinecode"): + return make_response( + "Cannot select {filename} for printing, not a machinecode file".format( + **locals() + ), + 415, + ) - if not printer.is_ready(): - return make_response("Printer is already printing, cannot select a new file", 409) + if not printer.is_ready(): + return make_response( + "Printer is already printing, cannot select a new file", 409 + ) - printAfterLoading = False - if "print" in data and data["print"] in valid_boolean_trues: - with Permissions.PRINT.require(403): - if not printer.is_operational(): - return make_response("Printer is not operational, cannot directly start printing", 409) - printAfterLoading = True + printAfterLoading = False + if "print" in data and data["print"] in valid_boolean_trues: + with Permissions.PRINT.require(403): + if not printer.is_operational(): + return make_response( + "Printer is not operational, cannot directly start printing", + 409, + ) + printAfterLoading = True - sd = False - if target == FileDestinations.SDCARD: - filenameToSelect = filename - sd = True - else: - filenameToSelect = fileManager.path_on_disk(target, filename) - printer.select_file(filenameToSelect, sd, printAfterLoading, user) + sd = False + if target == FileDestinations.SDCARD: + filenameToSelect = filename + sd = True + else: + filenameToSelect = fileManager.path_on_disk(target, filename) + printer.select_file(filenameToSelect, sd, printAfterLoading, user) - elif command == "slice": - with Permissions.SLICE.require(403): - if not _verifyFileExists(target, filename): - return make_response("File not found on '%s': %s" % (target, filename), 404) + elif command == "slice": + with Permissions.SLICE.require(403): + if not _verifyFileExists(target, filename): + return make_response( + "File not found on '%s': %s" % (target, filename), 404 + ) - try: - if "slicer" in data: - slicer = data["slicer"] - del data["slicer"] - slicer_instance = slicingManager.get_slicer(slicer) + try: + if "slicer" in data: + slicer = data["slicer"] + del data["slicer"] + slicer_instance = slicingManager.get_slicer(slicer) - elif "cura" in slicingManager.registered_slicers: - slicer = "cura" - slicer_instance = slicingManager.get_slicer("cura") + elif "cura" in slicingManager.registered_slicers: + slicer = "cura" + slicer_instance = slicingManager.get_slicer("cura") - else: - return make_response("Cannot slice {filename}, no slicer available".format(**locals()), 415) - except octoprint.slicing.UnknownSlicer as e: - return make_response("Slicer {slicer} is not available".format(slicer=e.slicer), 400) + else: + return make_response( + "Cannot slice {filename}, no slicer available".format(**locals()), + 415, + ) + except octoprint.slicing.UnknownSlicer as e: + return make_response( + "Slicer {slicer} is not available".format(slicer=e.slicer), 400 + ) - if not any([octoprint.filemanager.valid_file_type(filename, type=source_file_type) for source_file_type in slicer_instance.get_slicer_properties().get("source_file_types", ["model"])]): - return make_response("Cannot slice {filename}, not a model file".format(**locals()), 415) + if not any( + [ + octoprint.filemanager.valid_file_type(filename, type=source_file_type) + for source_file_type in slicer_instance.get_slicer_properties().get( + "source_file_types", ["model"] + ) + ] + ): + return make_response( + "Cannot slice {filename}, not a model file".format(**locals()), 415 + ) - cores = psutil.cpu_count() - if slicer_instance.get_slicer_properties().get("same_device", True) and (printer.is_printing() or printer.is_paused()) and (cores is None or cores < 2): - # slicer runs on same device as OctoPrint, slicing while printing is hence disabled - return make_response("Cannot slice on {slicer} while printing on single core systems or systems of unknown core count due to performance reasons".format(**locals()), 409) + cores = psutil.cpu_count() + if ( + slicer_instance.get_slicer_properties().get("same_device", True) + and (printer.is_printing() or printer.is_paused()) + and (cores is None or cores < 2) + ): + # slicer runs on same device as OctoPrint, slicing while printing is hence disabled + return make_response( + "Cannot slice on {slicer} while printing on single core systems or systems of unknown core count due to performance reasons".format( + **locals() + ), + 409, + ) - if "destination" in data and data["destination"]: - destination = data["destination"] - del data["destination"] - elif "gcode" in data and data["gcode"]: - destination = data["gcode"] - del data["gcode"] - else: - import os - name, _ = os.path.splitext(filename) - destination = name + "." + slicer_instance.get_slicer_properties().get("destination_extensions", ["gco", "gcode", "g"])[0] + if "destination" in data and data["destination"]: + destination = data["destination"] + del data["destination"] + elif "gcode" in data and data["gcode"]: + destination = data["gcode"] + del data["gcode"] + else: + import os - full_path = destination - if "path" in data and data["path"]: - full_path = fileManager.join_path(target, data["path"], destination) - else: - path, _ = fileManager.split_path(target, filename) - if path: - full_path = fileManager.join_path(target, path, destination) + name, _ = os.path.splitext(filename) + destination = ( + name + + "." + + slicer_instance.get_slicer_properties().get( + "destination_extensions", ["gco", "gcode", "g"] + )[0] + ) - canon_path, canon_name = fileManager.canonicalize(target, full_path) - sanitized_name = fileManager.sanitize_name(target, canon_name) + full_path = destination + if "path" in data and data["path"]: + full_path = fileManager.join_path(target, data["path"], destination) + else: + path, _ = fileManager.split_path(target, filename) + if path: + full_path = fileManager.join_path(target, path, destination) - if canon_path: - full_path = fileManager.join_path(target, canon_path, sanitized_name) - else: - full_path = sanitized_name + canon_path, canon_name = fileManager.canonicalize(target, full_path) + sanitized_name = fileManager.sanitize_name(target, canon_name) - # prohibit overwriting the file that is currently being printed - currentOrigin, currentFilename = _getCurrentFile() - if currentFilename == full_path and currentOrigin == target and (printer.is_printing() or printer.is_paused()): - make_response("Trying to slice into file that is currently being printed: %s" % full_path, 409) + if canon_path: + full_path = fileManager.join_path(target, canon_path, sanitized_name) + else: + full_path = sanitized_name - if "profile" in data and data["profile"]: - profile = data["profile"] - del data["profile"] - else: - profile = None + # prohibit overwriting the file that is currently being printed + currentOrigin, currentFilename = _getCurrentFile() + if ( + currentFilename == full_path + and currentOrigin == target + and (printer.is_printing() or printer.is_paused()) + ): + make_response( + "Trying to slice into file that is currently being printed: %s" + % full_path, + 409, + ) - if "printerProfile" in data and data["printerProfile"]: - printerProfile = data["printerProfile"] - del data["printerProfile"] - else: - printerProfile = None + if "profile" in data and data["profile"]: + profile = data["profile"] + del data["profile"] + else: + profile = None - if "position" in data and data["position"] and isinstance(data["position"], dict) and "x" in data["position"] and "y" in data["position"]: - position = data["position"] - del data["position"] - else: - position = None + if "printerProfile" in data and data["printerProfile"]: + printerProfile = data["printerProfile"] + del data["printerProfile"] + else: + printerProfile = None - select_after_slicing = False - if "select" in data and data["select"] in valid_boolean_trues: - if not printer.is_operational(): - return make_response("Printer is not operational, cannot directly select for printing", 409) - select_after_slicing = True + if ( + "position" in data + and data["position"] + and isinstance(data["position"], dict) + and "x" in data["position"] + and "y" in data["position"] + ): + position = data["position"] + del data["position"] + else: + position = None - print_after_slicing = False - if "print" in data and data["print"] in valid_boolean_trues: - if not printer.is_operational(): - return make_response("Printer is not operational, cannot directly start printing", 409) - select_after_slicing = print_after_slicing = True + select_after_slicing = False + if "select" in data and data["select"] in valid_boolean_trues: + if not printer.is_operational(): + return make_response( + "Printer is not operational, cannot directly select for printing", + 409, + ) + select_after_slicing = True - override_keys = [k for k in data if k.startswith("profile.") and data[k] is not None] - overrides = {} - for key in override_keys: - overrides[key[len("profile."):]] = data[key] + print_after_slicing = False + if "print" in data and data["print"] in valid_boolean_trues: + if not printer.is_operational(): + return make_response( + "Printer is not operational, cannot directly start printing", 409 + ) + select_after_slicing = print_after_slicing = True - def slicing_done(target, path, select_after_slicing, print_after_slicing): - if select_after_slicing or print_after_slicing: - sd = False - if target == FileDestinations.SDCARD: - filenameToSelect = path - sd = True - else: - filenameToSelect = fileManager.path_on_disk(target, path) - printer.select_file(filenameToSelect, sd, print_after_slicing, user) + override_keys = [ + k for k in data if k.startswith("profile.") and data[k] is not None + ] + overrides = {} + for key in override_keys: + overrides[key[len("profile.") :]] = data[key] - try: - fileManager.slice(slicer, target, filename, target, full_path, - profile=profile, - printer_profile_id=printerProfile, - position=position, - overrides=overrides, - display=canon_name, - callback=slicing_done, - callback_args=(target, full_path, select_after_slicing, print_after_slicing)) - except octoprint.slicing.UnknownProfile: - return make_response("Profile {profile} doesn't exist".format(**locals()), 400) + def slicing_done(target, path, select_after_slicing, print_after_slicing): + if select_after_slicing or print_after_slicing: + sd = False + if target == FileDestinations.SDCARD: + filenameToSelect = path + sd = True + else: + filenameToSelect = fileManager.path_on_disk(target, path) + printer.select_file(filenameToSelect, sd, print_after_slicing, user) - files = {} - location = url_for(".readGcodeFile", target=target, filename=full_path, _external=True) - result = { - "name": destination, - "path": full_path, - "display": canon_name, - "origin": FileDestinations.LOCAL, - "refs": { - "resource": location, - "download": url_for("index", _external=True) + "downloads/files/" + target + "/" + full_path - } - } + try: + fileManager.slice( + slicer, + target, + filename, + target, + full_path, + profile=profile, + printer_profile_id=printerProfile, + position=position, + overrides=overrides, + display=canon_name, + callback=slicing_done, + callback_args=( + target, + full_path, + select_after_slicing, + print_after_slicing, + ), + ) + except octoprint.slicing.UnknownProfile: + return make_response( + "Profile {profile} doesn't exist".format(**locals()), 400 + ) - r = make_response(jsonify(result), 202) - r.headers["Location"] = location - return r + files = {} + location = url_for( + ".readGcodeFile", target=target, filename=full_path, _external=True + ) + result = { + "name": destination, + "path": full_path, + "display": canon_name, + "origin": FileDestinations.LOCAL, + "refs": { + "resource": location, + "download": url_for("index", _external=True) + + "downloads/files/" + + target + + "/" + + full_path, + }, + } - elif command == "analyse": - with Permissions.FILES_UPLOAD.require(403): - if not _verifyFileExists(target, filename): - return make_response("File not found on '%s': %s" % (target, filename), 404) + r = make_response(jsonify(result), 202) + r.headers["Location"] = location + return r - printer_profile = None - if "printerProfile" in data and data["printerProfile"]: - printer_profile = data["printerProfile"] + elif command == "analyse": + with Permissions.FILES_UPLOAD.require(403): + if not _verifyFileExists(target, filename): + return make_response( + "File not found on '%s': %s" % (target, filename), 404 + ) - if not fileManager.analyse(target, filename, printer_profile_id=printer_profile): - return make_response("No analysis possible for {} on {}".format(filename, target), 400) + printer_profile = None + if "printerProfile" in data and data["printerProfile"]: + printer_profile = data["printerProfile"] - elif command == "copy" or command == "move": - with Permissions.FILES_UPLOAD.require(403): - # Copy and move are only possible on local storage - if not target in [FileDestinations.LOCAL]: - return make_response("Unsupported target for {}: {}".format(command, target), 400) + if not fileManager.analyse( + target, filename, printer_profile_id=printer_profile + ): + return make_response( + "No analysis possible for {} on {}".format(filename, target), 400 + ) - if not _verifyFileExists(target, filename) and not _verifyFolderExists(target, filename): - return make_response("File or folder not found on {}: {}".format(target, filename), 404) + elif command == "copy" or command == "move": + with Permissions.FILES_UPLOAD.require(403): + # Copy and move are only possible on local storage + if not target in [FileDestinations.LOCAL]: + return make_response( + "Unsupported target for {}: {}".format(command, target), 400 + ) - path, name = fileManager.split_path(target, filename) + if not _verifyFileExists(target, filename) and not _verifyFolderExists( + target, filename + ): + return make_response( + "File or folder not found on {}: {}".format(target, filename), 404 + ) - destination = data["destination"] - dst_path, dst_name = fileManager.split_path(target, destination) - sanitized_destination = fileManager.join_path(target, dst_path, fileManager.sanitize_name(target, dst_name)) + path, name = fileManager.split_path(target, filename) - if _verifyFolderExists(target, destination) and sanitized_destination != filename: - # destination is an existing folder and not ourselves (= display rename), we'll assume we are supposed - # to move filename to this folder under the same name - destination = fileManager.join_path(target, destination, name) + destination = data["destination"] + dst_path, dst_name = fileManager.split_path(target, destination) + sanitized_destination = fileManager.join_path( + target, dst_path, fileManager.sanitize_name(target, dst_name) + ) - if _verifyFileExists(target, destination) or _verifyFolderExists(target, destination): - return make_response("File or folder does already exist on {}: {}".format(target, destination), 409) + if ( + _verifyFolderExists(target, destination) + and sanitized_destination != filename + ): + # destination is an existing folder and not ourselves (= display rename), we'll assume we are supposed + # to move filename to this folder under the same name + destination = fileManager.join_path(target, destination, name) - is_file = fileManager.file_exists(target, filename) - is_folder = fileManager.folder_exists(target, filename) + if _verifyFileExists(target, destination) or _verifyFolderExists( + target, destination + ): + return make_response( + "File or folder does already exist on {}: {}".format( + target, destination + ), + 409, + ) - if not (is_file or is_folder): - return make_response("{} on {} is neither file or folder, can't {}".format(filename, target, command), 400) + is_file = fileManager.file_exists(target, filename) + is_folder = fileManager.folder_exists(target, filename) - if command == "copy": - # destination already there? error... - if _verifyFileExists(target, destination) or _verifyFolderExists(target, destination): - return make_response("File or folder does already exist on {}: {}".format(target, destination), 409) + if not (is_file or is_folder): + return make_response( + "{} on {} is neither file or folder, can't {}".format( + filename, target, command + ), + 400, + ) - if is_file: - fileManager.copy_file(target, filename, destination) - else: - fileManager.copy_folder(target, filename, destination) + if command == "copy": + # destination already there? error... + if _verifyFileExists(target, destination) or _verifyFolderExists( + target, destination + ): + return make_response( + "File or folder does already exist on {}: {}".format( + target, destination + ), + 409, + ) - elif command == "move": - with Permissions.FILES_DELETE.require(403): - if _isBusy(target, filename): - return make_response("Trying to move a file or folder that is currently in use: {}".format(filename), 409) + if is_file: + fileManager.copy_file(target, filename, destination) + else: + fileManager.copy_folder(target, filename, destination) - # destination already there AND not ourselves (= display rename)? error... - if (_verifyFileExists(target, destination) or _verifyFolderExists(target, destination)) \ - and sanitized_destination != filename: - return make_response("File or folder does already exist on {}: {}".format(target, destination), 409) + elif command == "move": + with Permissions.FILES_DELETE.require(403): + if _isBusy(target, filename): + return make_response( + "Trying to move a file or folder that is currently in use: {}".format( + filename + ), + 409, + ) - # deselect the file if it's currently selected - currentOrigin, currentFilename = _getCurrentFile() - if currentFilename is not None and filename == currentFilename: - printer.unselect_file() + # destination already there AND not ourselves (= display rename)? error... + if ( + _verifyFileExists(target, destination) + or _verifyFolderExists(target, destination) + ) and sanitized_destination != filename: + return make_response( + "File or folder does already exist on {}: {}".format( + target, destination + ), + 409, + ) - if is_file: - fileManager.move_file(target, filename, destination) - else: - fileManager.move_folder(target, filename, destination) + # deselect the file if it's currently selected + currentOrigin, currentFilename = _getCurrentFile() + if currentFilename is not None and filename == currentFilename: + printer.unselect_file() - location = url_for(".readGcodeFile", target=target, filename=destination, _external=True) - result = { - "name": name, - "path": destination, - "origin": FileDestinations.LOCAL, - "refs": { - "resource": location - } - } - if is_file: - result["refs"]["download"] = url_for("index", _external=True) + "downloads/files/" + target + "/" + destination + if is_file: + fileManager.move_file(target, filename, destination) + else: + fileManager.move_folder(target, filename, destination) - r = make_response(jsonify(result), 201) - r.headers["Location"] = location - return r + location = url_for( + ".readGcodeFile", target=target, filename=destination, _external=True + ) + result = { + "name": name, + "path": destination, + "origin": FileDestinations.LOCAL, + "refs": {"resource": location}, + } + if is_file: + result["refs"]["download"] = ( + url_for("index", _external=True) + + "downloads/files/" + + target + + "/" + + destination + ) - return NO_CONTENT + r = make_response(jsonify(result), 201) + r.headers["Location"] = location + return r + + return NO_CONTENT @api.route("/files//", methods=["DELETE"]) @no_firstrun_access @Permissions.FILES_DELETE.require(403) def deleteGcodeFile(filename, target): - if not _verifyFileExists(target, filename) and not _verifyFolderExists(target, filename): - return make_response("File/Folder not found on '%s': %s" % (target, filename), 404) + if not _verifyFileExists(target, filename) and not _verifyFolderExists( + target, filename + ): + return make_response( + "File/Folder not found on '%s': %s" % (target, filename), 404 + ) - if _verifyFileExists(target, filename): - if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: - return make_response("Unknown target: %s" % target, 400) + if _verifyFileExists(target, filename): + if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: + return make_response("Unknown target: %s" % target, 400) - if _isBusy(target, filename): - return make_response("Trying to delete a file that is currently in use: %s" % filename, 409) + if _isBusy(target, filename): + return make_response( + "Trying to delete a file that is currently in use: %s" % filename, 409 + ) - # deselect the file if it's currently selected - currentOrigin, currentPath = _getCurrentFile() - if currentPath is not None and currentOrigin == target and filename == currentPath: - printer.unselect_file() + # deselect the file if it's currently selected + currentOrigin, currentPath = _getCurrentFile() + if ( + currentPath is not None + and currentOrigin == target + and filename == currentPath + ): + printer.unselect_file() - # delete it - if target == FileDestinations.SDCARD: - printer.delete_sd_file(filename, tags={"source:api", "api:files.sd"}) - else: - fileManager.remove_file(target, filename) + # delete it + if target == FileDestinations.SDCARD: + printer.delete_sd_file(filename, tags={"source:api", "api:files.sd"}) + else: + fileManager.remove_file(target, filename) - elif _verifyFolderExists(target, filename): - if not target in [FileDestinations.LOCAL]: - return make_response("Unknown target: %s" % target, 400) + elif _verifyFolderExists(target, filename): + if not target in [FileDestinations.LOCAL]: + return make_response("Unknown target: %s" % target, 400) - if _isBusy(target, filename): - return make_response("Trying to delete a folder that contains a file that is currently in use: %s" % filename, 409) + if _isBusy(target, filename): + return make_response( + "Trying to delete a folder that contains a file that is currently in use: %s" + % filename, + 409, + ) - # deselect the file if it's currently selected - currentOrigin, currentPath = _getCurrentFile() - if currentPath is not None and currentOrigin == target and fileManager.file_in_path(target, filename, currentPath): - printer.unselect_file() + # deselect the file if it's currently selected + currentOrigin, currentPath = _getCurrentFile() + if ( + currentPath is not None + and currentOrigin == target + and fileManager.file_in_path(target, filename, currentPath) + ): + printer.unselect_file() - # delete it - fileManager.remove_folder(target, filename, recursive=True) + # delete it + fileManager.remove_folder(target, filename, recursive=True) + + return NO_CONTENT - return NO_CONTENT def _getCurrentFile(): - currentJob = printer.get_current_job() - if currentJob is not None and "file" in currentJob and "path" in currentJob["file"] and "origin" in currentJob["file"]: - return currentJob["file"]["origin"], currentJob["file"]["path"] - else: - return None, None + currentJob = printer.get_current_job() + if ( + currentJob is not None + and "file" in currentJob + and "path" in currentJob["file"] + and "origin" in currentJob["file"] + ): + return currentJob["file"]["origin"], currentJob["file"]["path"] + else: + return None, None class WerkzeugFileWrapper(octoprint.filemanager.util.AbstractFileWrapper): - """ - A wrapper around a Werkzeug ``FileStorage`` object. + """ + A wrapper around a Werkzeug ``FileStorage`` object. - Arguments: - file_obj (werkzeug.datastructures.FileStorage): The Werkzeug ``FileStorage`` instance to wrap. + Arguments: + file_obj (werkzeug.datastructures.FileStorage): The Werkzeug ``FileStorage`` instance to wrap. - .. seealso:: + .. seealso:: - `werkzeug.datastructures.FileStorage `_ - The documentation of Werkzeug's ``FileStorage`` class. - """ - def __init__(self, file_obj): - octoprint.filemanager.util.AbstractFileWrapper.__init__(self, file_obj.filename) - self.file_obj = file_obj + `werkzeug.datastructures.FileStorage `_ + The documentation of Werkzeug's ``FileStorage`` class. + """ - def save(self, path): - """ - Delegates to ``werkzeug.datastructures.FileStorage.save`` - """ - self.file_obj.save(path) + def __init__(self, file_obj): + octoprint.filemanager.util.AbstractFileWrapper.__init__(self, file_obj.filename) + self.file_obj = file_obj - def stream(self): - """ - Returns ``werkzeug.datastructures.FileStorage.stream`` - """ - return self.file_obj.stream + def save(self, path): + """ + Delegates to ``werkzeug.datastructures.FileStorage.save`` + """ + self.file_obj.save(path) + + def stream(self): + """ + Returns ``werkzeug.datastructures.FileStorage.stream`` + """ + return self.file_obj.stream diff --git a/src/octoprint/server/api/job.py b/src/octoprint/server/api/job.py index 49939ba3d..1141044db 100644 --- a/src/octoprint/server/api/job.py +++ b/src/octoprint/server/api/job.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" from flask import request, make_response, jsonify @@ -12,63 +12,77 @@ from octoprint.server.util.flask import no_firstrun_access, get_json_command_fro from octoprint.server.api import api from octoprint.access.permissions import Permissions + @api.route("/job", methods=["POST"]) @no_firstrun_access def controlJob(): - if not printer.is_operational(): - return make_response("Printer is not operational", 409) + if not printer.is_operational(): + return make_response("Printer is not operational", 409) - valid_commands = { - "start": [], - "restart": [], - "pause": [], - "cancel": [] - } + valid_commands = {"start": [], "restart": [], "pause": [], "cancel": []} - command, data, response = get_json_command_from_request(request, valid_commands) - if response is not None: - return response + command, data, response = get_json_command_from_request(request, valid_commands) + if response is not None: + return response - activePrintjob = printer.is_printing() or printer.is_paused() + activePrintjob = printer.is_printing() or printer.is_paused() - tags = {"source:api", "api:job"} + tags = {"source:api", "api:job"} - user = current_user.get_name() + user = current_user.get_name() - with Permissions.PRINT.require(403): - if command == "start": - if activePrintjob: - return make_response("Printer already has an active print job, did you mean 'restart'?", 409) - printer.start_print(tags=tags, user=user) - elif command == "restart": - if not printer.is_paused(): - return make_response("Printer does not have an active print job or is not paused", 409) - printer.start_print(tags=tags, user=user) - elif command == "pause": - if not activePrintjob: - return make_response("Printer is neither printing nor paused, 'pause' command cannot be performed", 409) - action = data.get("action", "toggle") - if action == "toggle": - printer.toggle_pause_print(tags=tags, user=user) - elif action == "pause": - printer.pause_print(tags=tags, user=user) - elif action == "resume": - printer.resume_print(tags=tags, user=user) - else: - return make_response("Unknown action '{}', allowed values for action parameter are 'pause', 'resume' and 'toggle'".format(action), 400) - elif command == "cancel": - if not activePrintjob: - return make_response("Printer is neither printing nor paused, 'cancel' command cannot be performed", 409) - printer.cancel_print(tags=tags, user=user) - return NO_CONTENT + with Permissions.PRINT.require(403): + if command == "start": + if activePrintjob: + return make_response( + "Printer already has an active print job, did you mean 'restart'?", + 409, + ) + printer.start_print(tags=tags, user=user) + elif command == "restart": + if not printer.is_paused(): + return make_response( + "Printer does not have an active print job or is not paused", 409 + ) + printer.start_print(tags=tags, user=user) + elif command == "pause": + if not activePrintjob: + return make_response( + "Printer is neither printing nor paused, 'pause' command cannot be performed", + 409, + ) + action = data.get("action", "toggle") + if action == "toggle": + printer.toggle_pause_print(tags=tags, user=user) + elif action == "pause": + printer.pause_print(tags=tags, user=user) + elif action == "resume": + printer.resume_print(tags=tags, user=user) + else: + return make_response( + "Unknown action '{}', allowed values for action parameter are 'pause', 'resume' and 'toggle'".format( + action + ), + 400, + ) + elif command == "cancel": + if not activePrintjob: + return make_response( + "Printer is neither printing nor paused, 'cancel' command cannot be performed", + 409, + ) + printer.cancel_print(tags=tags, user=user) + return NO_CONTENT @api.route("/job", methods=["GET"]) @Permissions.STATUS.require(403) def jobState(): - currentData = printer.get_current_data() - return jsonify({ - "job": currentData["job"], - "progress": currentData["progress"], - "state": currentData["state"]["text"] - }) + currentData = printer.get_current_data() + return jsonify( + { + "job": currentData["job"], + "progress": currentData["progress"], + "state": currentData["state"]["text"], + } + ) diff --git a/src/octoprint/server/api/languages.py b/src/octoprint/server/api/languages.py index 226c693e7..36c50cbdd 100644 --- a/src/octoprint/server/api/languages.py +++ b/src/octoprint/server/api/languages.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import io @@ -12,9 +12,9 @@ import zipfile import logging try: - from os import scandir + from os import scandir except ImportError: - from scandir import scandir + from scandir import scandir from collections import defaultdict @@ -30,141 +30,183 @@ from octoprint.access.permissions import Permissions from flask_babel import Locale + @api.route("/languages", methods=["GET"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def getInstalledLanguagePacks(): - translation_folder = settings().getBaseFolder("translations", check_writable=False) - if not os.path.exists(translation_folder): - return jsonify(language_packs={"_core": []}) + translation_folder = settings().getBaseFolder("translations", check_writable=False) + if not os.path.exists(translation_folder): + return jsonify(language_packs={"_core": []}) - core_packs = [] - plugin_packs = defaultdict(lambda: {"identifier": None, "display": None, "languages": []}) - for entry in scandir(translation_folder): - if not entry.is_dir(): - continue + core_packs = [] + plugin_packs = defaultdict( + lambda: {"identifier": None, "display": None, "languages": []} + ) + for entry in scandir(translation_folder): + if not entry.is_dir(): + continue - def load_meta(path, locale): - meta = {} + def load_meta(path, locale): + meta = {} - meta_path = os.path.join(path, "meta.yaml") - if os.path.isfile(meta_path): - import yaml - try: - with io.open(meta_path, 'rt', encoding='utf-8') as f: - meta = yaml.safe_load(f) - except Exception: - logging.getLogger(__name__).exception("Could not load %s", meta_path) - pass - else: - import datetime - if "last_update" in meta and isinstance(meta["last_update"], datetime.datetime): - meta["last_update"] = (meta["last_update"] - datetime.datetime(1970,1,1)).total_seconds() + meta_path = os.path.join(path, "meta.yaml") + if os.path.isfile(meta_path): + import yaml - l = Locale.parse(locale) - meta["locale"] = locale - meta["locale_display"] = l.display_name - meta["locale_english"] = l.english_name - return meta + try: + with io.open(meta_path, "rt", encoding="utf-8") as f: + meta = yaml.safe_load(f) + except Exception: + logging.getLogger(__name__).exception("Could not load %s", meta_path) + pass + else: + import datetime - if entry.name == "_plugins": - for plugin_entry in scandir(entry.path): - if not plugin_entry.is_dir(): - continue + if "last_update" in meta and isinstance( + meta["last_update"], datetime.datetime + ): + meta["last_update"] = ( + meta["last_update"] - datetime.datetime(1970, 1, 1) + ).total_seconds() - if not plugin_entry.name in plugin_manager().plugins: - continue + l = Locale.parse(locale) + meta["locale"] = locale + meta["locale_display"] = l.display_name + meta["locale_english"] = l.english_name + return meta - plugin_info = plugin_manager().plugins[plugin_entry.name] + if entry.name == "_plugins": + for plugin_entry in scandir(entry.path): + if not plugin_entry.is_dir(): + continue - plugin_packs[plugin_entry.name]["identifier"] = plugin_entry.name - plugin_packs[plugin_entry.name]["display"] = plugin_info.name + if not plugin_entry.name in plugin_manager().plugins: + continue - for language_entry in scandir(plugin_entry.path): - try: - plugin_packs[plugin_entry.name]["languages"].append(load_meta(language_entry.path, language_entry.name)) - except Exception: - logging.getLogger(__name__).exception("Error while parsing metadata for language pack {} from {} for plugin {}".format(language_entry.name, - language_entry.path, - plugin_entry.name)) - continue - else: - try: - core_packs.append(load_meta(entry.path, entry.name)) - except ValueError: - logging.getLogger(__name__).exception("Core language pack {} doesn't appear to actually be one".format(entry.name)) - except Exception: - logging.getLogger(__name__).exception("Error while parsing metadata for core language pack {} from {}".format(entry.name, - entry.path)) + plugin_info = plugin_manager().plugins[plugin_entry.name] + + plugin_packs[plugin_entry.name]["identifier"] = plugin_entry.name + plugin_packs[plugin_entry.name]["display"] = plugin_info.name + + for language_entry in scandir(plugin_entry.path): + try: + plugin_packs[plugin_entry.name]["languages"].append( + load_meta(language_entry.path, language_entry.name) + ) + except Exception: + logging.getLogger(__name__).exception( + "Error while parsing metadata for language pack {} from {} for plugin {}".format( + language_entry.name, + language_entry.path, + plugin_entry.name, + ) + ) + continue + else: + try: + core_packs.append(load_meta(entry.path, entry.name)) + except ValueError: + logging.getLogger(__name__).exception( + "Core language pack {} doesn't appear to actually be one".format( + entry.name + ) + ) + except Exception: + logging.getLogger(__name__).exception( + "Error while parsing metadata for core language pack {} from {}".format( + entry.name, entry.path + ) + ) + + result = { + "_core": {"identifier": "_core", "display": "Core", "languages": core_packs} + } + result.update(plugin_packs) + return jsonify(language_packs=result) - result = {"_core": {"identifier": "_core", "display": "Core", "languages": core_packs}} - result.update(plugin_packs) - return jsonify(language_packs=result) @api.route("/languages", methods=["POST"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def uploadLanguagePack(): - input_name = "file" - input_upload_path = input_name + "." + settings().get(["server", "uploads", "pathSuffix"]) - input_upload_name = input_name + "." + settings().get(["server", "uploads", "nameSuffix"]) - if not input_upload_path in request.values or not input_upload_name in request.values: - return make_response("No file included", 400) + input_name = "file" + input_upload_path = ( + input_name + "." + settings().get(["server", "uploads", "pathSuffix"]) + ) + input_upload_name = ( + input_name + "." + settings().get(["server", "uploads", "nameSuffix"]) + ) + if not input_upload_path in request.values or not input_upload_name in request.values: + return make_response("No file included", 400) - upload_name = request.values[input_upload_name] - upload_path = request.values[input_upload_path] + upload_name = request.values[input_upload_name] + upload_path = request.values[input_upload_path] - exts = filter(lambda x: upload_name.lower().endswith(x), (".zip", ".tar.gz", ".tgz", ".tar")) - if not len(exts): - return make_response("File doesn't have a valid extension for a language pack archive", 400) + exts = filter( + lambda x: upload_name.lower().endswith(x), (".zip", ".tar.gz", ".tgz", ".tar") + ) + if not len(exts): + return make_response( + "File doesn't have a valid extension for a language pack archive", 400 + ) - target_path = settings().getBaseFolder("translations") + target_path = settings().getBaseFolder("translations") - if tarfile.is_tarfile(upload_path): - _unpack_uploaded_tarball(upload_path, target_path) - elif zipfile.is_zipfile(upload_path): - _unpack_uploaded_zipfile(upload_path, target_path) - else: - return make_response("Neither zip file nor tarball included", 400) + if tarfile.is_tarfile(upload_path): + _unpack_uploaded_tarball(upload_path, target_path) + elif zipfile.is_zipfile(upload_path): + _unpack_uploaded_zipfile(upload_path, target_path) + else: + return make_response("Neither zip file nor tarball included", 400) + + return getInstalledLanguagePacks() - return getInstalledLanguagePacks() @api.route("/languages//", methods=["DELETE"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def deleteInstalledLanguagePack(locale, pack): - if pack == "_core": - target_path = os.path.join(settings().getBaseFolder("translations"), locale) - else: - target_path = os.path.join(settings().getBaseFolder("translations"), "_plugins", pack, locale) + if pack == "_core": + target_path = os.path.join(settings().getBaseFolder("translations"), locale) + else: + target_path = os.path.join( + settings().getBaseFolder("translations"), "_plugins", pack, locale + ) - if os.path.isdir(target_path): - import shutil - shutil.rmtree(target_path) + if os.path.isdir(target_path): + import shutil + + shutil.rmtree(target_path) + + return getInstalledLanguagePacks() - return getInstalledLanguagePacks() def _unpack_uploaded_zipfile(path, target): - with zipfile.ZipFile(path, "r") as zip: - # sanity check - map(_validate_archive_name, zip.namelist()) + with zipfile.ZipFile(path, "r") as zip: + # sanity check + map(_validate_archive_name, zip.namelist()) + + # unpack everything + zip.extractall(target) - # unpack everything - zip.extractall(target) def _unpack_uploaded_tarball(path, target): - with tarfile.open(path, "r") as tar: - # sanity check - map(_validate_archive_name, tar.getmembers()) + with tarfile.open(path, "r") as tar: + # sanity check + map(_validate_archive_name, tar.getmembers()) + + # unpack everything + tar.extractall(target) - # unpack everything - tar.extractall(target) def _validate_archive_name(name): - if name.startswith("/") or ".." in name: - raise InvalidLanguagePack("Provided language pack contains invalid name {name}".format(**locals())) + if name.startswith("/") or ".." in name: + raise InvalidLanguagePack( + "Provided language pack contains invalid name {name}".format(**locals()) + ) class InvalidLanguagePack(Exception): - pass + pass diff --git a/src/octoprint/server/api/printer.py b/src/octoprint/server/api/printer.py index 9612621b0..0c02f9416 100644 --- a/src/octoprint/server/api/printer.py +++ b/src/octoprint/server/api/printer.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" from flask import request, jsonify, make_response, Response @@ -20,152 +20,163 @@ from octoprint.printer import UnknownScript from octoprint.access.permissions import Permissions -#~~ Printer +# ~~ Printer @api.route("/printer", methods=["GET"]) @Permissions.STATUS.require(403) def printerState(): - if not printer.is_operational(): - return make_response("Printer is not operational", 409) + if not printer.is_operational(): + return make_response("Printer is not operational", 409) - # process excludes - excludes = [] - if "exclude" in request.values: - excludeStr = request.values["exclude"] - if len(excludeStr.strip()) > 0: - excludes = list(filter(lambda x: x in ["temperature", "sd", "state"], map(lambda x: x.strip(), excludeStr.split(",")))) + # process excludes + excludes = [] + if "exclude" in request.values: + excludeStr = request.values["exclude"] + if len(excludeStr.strip()) > 0: + excludes = list( + filter( + lambda x: x in ["temperature", "sd", "state"], + map(lambda x: x.strip(), excludeStr.split(",")), + ) + ) - result = {} + result = {} - # add temperature information - if not "temperature" in excludes: - processor = lambda x: x - heated_bed = printerProfileManager.get_current_or_default()["heatedBed"] - heated_chamber = printerProfileManager.get_current_or_default()["heatedChamber"] - if not heated_bed and not heated_chamber: - processor = _keep_tools - elif not heated_bed: - processor = _delete_bed - elif not heated_chamber: - processor = _delete_chamber + # add temperature information + if not "temperature" in excludes: + processor = lambda x: x + heated_bed = printerProfileManager.get_current_or_default()["heatedBed"] + heated_chamber = printerProfileManager.get_current_or_default()["heatedChamber"] + if not heated_bed and not heated_chamber: + processor = _keep_tools + elif not heated_bed: + processor = _delete_bed + elif not heated_chamber: + processor = _delete_chamber - result.update({"temperature": _get_temperature_data(processor)}) + result.update({"temperature": _get_temperature_data(processor)}) - # add sd information - if not "sd" in excludes and settings().getBoolean(["feature", "sdSupport"]): - result.update({"sd": {"ready": printer.is_sd_ready()}}) + # add sd information + if not "sd" in excludes and settings().getBoolean(["feature", "sdSupport"]): + result.update({"sd": {"ready": printer.is_sd_ready()}}) - # add state information - if not "state" in excludes: - state = printer.get_current_data()["state"] - result.update({"state": state}) + # add state information + if not "state" in excludes: + state = printer.get_current_data()["state"] + result.update({"state": state}) - return jsonify(result) + return jsonify(result) -#~~ Tool +# ~~ Tool @api.route("/printer/tool", methods=["POST"]) @no_firstrun_access @Permissions.CONTROL.require(403) def printerToolCommand(): - if not printer.is_operational(): - return make_response("Printer is not operational", 409) + if not printer.is_operational(): + return make_response("Printer is not operational", 409) - valid_commands = { - "select": ["tool"], - "target": ["targets"], - "offset": ["offsets"], - "extrude": ["amount"], - "flowrate": ["factor"] - } - command, data, response = get_json_command_from_request(request, valid_commands) - if response is not None: - return response + valid_commands = { + "select": ["tool"], + "target": ["targets"], + "offset": ["offsets"], + "extrude": ["amount"], + "flowrate": ["factor"], + } + command, data, response = get_json_command_from_request(request, valid_commands) + if response is not None: + return response - validation_regex = re.compile(r"tool\d+") + validation_regex = re.compile(r"tool\d+") - tags = {"source:api", "api:printer.tool"} + tags = {"source:api", "api:printer.tool"} - ##~~ tool selection - if command == "select": - tool = data["tool"] - if not isinstance(tool, basestring) or re.match(validation_regex, tool) is None: - return make_response("Invalid tool: %s" % tool, 400) - if not tool.startswith("tool"): - return make_response("Invalid tool for selection: %s" % tool, 400) + ##~~ tool selection + if command == "select": + tool = data["tool"] + if not isinstance(tool, basestring) or re.match(validation_regex, tool) is None: + return make_response("Invalid tool: %s" % tool, 400) + if not tool.startswith("tool"): + return make_response("Invalid tool for selection: %s" % tool, 400) - printer.change_tool(tool, tags=tags) + printer.change_tool(tool, tags=tags) - ##~~ temperature - elif command == "target": - targets = data["targets"] + ##~~ temperature + elif command == "target": + targets = data["targets"] - # make sure the targets are valid and the values are numbers - validated_values = {} - for tool, value in targets.items(): - if re.match(validation_regex, tool) is None: - return make_response("Invalid target for setting temperature: %s" % tool, 400) - if not isinstance(value, (int, long, float)): - return make_response("Not a number for %s: %r" % (tool, value), 400) - validated_values[tool] = value + # make sure the targets are valid and the values are numbers + validated_values = {} + for tool, value in targets.items(): + if re.match(validation_regex, tool) is None: + return make_response( + "Invalid target for setting temperature: %s" % tool, 400 + ) + if not isinstance(value, (int, long, float)): + return make_response("Not a number for %s: %r" % (tool, value), 400) + validated_values[tool] = value - # perform the actual temperature commands - for tool in validated_values.keys(): - printer.set_temperature(tool, validated_values[tool], tags=tags) + # perform the actual temperature commands + for tool in validated_values.keys(): + printer.set_temperature(tool, validated_values[tool], tags=tags) - ##~~ temperature offset - elif command == "offset": - offsets = data["offsets"] + ##~~ temperature offset + elif command == "offset": + offsets = data["offsets"] - # make sure the targets are valid, the values are numbers and in the range [-50, 50] - validated_values = {} - for tool, value in offsets.items(): - if re.match(validation_regex, tool) is None: - return make_response("Invalid target for setting temperature: %s" % tool, 400) - if not isinstance(value, (int, long, float)): - return make_response("Not a number for %s: %r" % (tool, value), 400) - if not -50 <= value <= 50: - return make_response("Offset %s not in range [-50, 50]: %f" % (tool, value), 400) - validated_values[tool] = value + # make sure the targets are valid, the values are numbers and in the range [-50, 50] + validated_values = {} + for tool, value in offsets.items(): + if re.match(validation_regex, tool) is None: + return make_response( + "Invalid target for setting temperature: %s" % tool, 400 + ) + if not isinstance(value, (int, long, float)): + return make_response("Not a number for %s: %r" % (tool, value), 400) + if not -50 <= value <= 50: + return make_response( + "Offset %s not in range [-50, 50]: %f" % (tool, value), 400 + ) + validated_values[tool] = value - # set the offsets - printer.set_temperature_offset(validated_values) + # set the offsets + printer.set_temperature_offset(validated_values) - ##~~ extrusion - elif command == "extrude": - if printer.is_printing(): - # do not extrude when a print job is running - return make_response("Printer is currently printing", 409) + ##~~ extrusion + elif command == "extrude": + if printer.is_printing(): + # do not extrude when a print job is running + return make_response("Printer is currently printing", 409) - amount = data["amount"] - speed = data.get("speed", None) - if not isinstance(amount, (int, long, float)): - return make_response("Not a number for extrusion amount: %r" % amount, 400) - printer.extrude(amount, speed=speed, tags=tags) + amount = data["amount"] + speed = data.get("speed", None) + if not isinstance(amount, (int, long, float)): + return make_response("Not a number for extrusion amount: %r" % amount, 400) + printer.extrude(amount, speed=speed, tags=tags) - elif command == "flowrate": - factor = data["factor"] - if not isinstance(factor, (int, long, float)): - return make_response("Not a number for flow rate: %r" % factor, 400) - try: - printer.flow_rate(factor, tags=tags) - except ValueError as e: - return make_response("Invalid value for flow rate: %s" % str(e), 400) + elif command == "flowrate": + factor = data["factor"] + if not isinstance(factor, (int, long, float)): + return make_response("Not a number for flow rate: %r" % factor, 400) + try: + printer.flow_rate(factor, tags=tags) + except ValueError as e: + return make_response("Invalid value for flow rate: %s" % str(e), 400) - return NO_CONTENT + return NO_CONTENT @api.route("/printer/tool", methods=["GET"]) @no_firstrun_access @Permissions.STATUS.require(403) def printerToolState(): - if not printer.is_operational(): - return make_response("Printer is not operational", 409) + if not printer.is_operational(): + return make_response("Printer is not operational", 409) - return jsonify(_get_temperature_data(_keep_tools)) + return jsonify(_get_temperature_data(_keep_tools)) ##~~ Heated bed @@ -175,64 +186,61 @@ def printerToolState(): @no_firstrun_access @Permissions.CONTROL.require(403) def printerBedCommand(): - if not printer.is_operational(): - return make_response("Printer is not operational", 409) + if not printer.is_operational(): + return make_response("Printer is not operational", 409) - if not printerProfileManager.get_current_or_default()["heatedBed"]: - return make_response("Printer does not have a heated bed", 409) + if not printerProfileManager.get_current_or_default()["heatedBed"]: + return make_response("Printer does not have a heated bed", 409) - valid_commands = { - "target": ["target"], - "offset": ["offset"] - } - command, data, response = get_json_command_from_request(request, valid_commands) - if response is not None: - return response + valid_commands = {"target": ["target"], "offset": ["offset"]} + command, data, response = get_json_command_from_request(request, valid_commands) + if response is not None: + return response - tags = {"source:api", "api:printer.bed"} + tags = {"source:api", "api:printer.bed"} - ##~~ temperature - if command == "target": - target = data["target"] + ##~~ temperature + if command == "target": + target = data["target"] - # make sure the target is a number - if not isinstance(target, (int, long, float)): - return make_response("Not a number: %r" % target, 400) + # make sure the target is a number + if not isinstance(target, (int, long, float)): + return make_response("Not a number: %r" % target, 400) - # perform the actual temperature command - printer.set_temperature("bed", target, tags=tags) + # perform the actual temperature command + printer.set_temperature("bed", target, tags=tags) - ##~~ temperature offset - elif command == "offset": - offset = data["offset"] + ##~~ temperature offset + elif command == "offset": + offset = data["offset"] - # make sure the offset is valid - if not isinstance(offset, (int, long, float)): - return make_response("Not a number: %r" % offset, 400) - if not -50 <= offset <= 50: - return make_response("Offset not in range [-50, 50]: %f" % offset, 400) + # make sure the offset is valid + if not isinstance(offset, (int, long, float)): + return make_response("Not a number: %r" % offset, 400) + if not -50 <= offset <= 50: + return make_response("Offset not in range [-50, 50]: %f" % offset, 400) - # set the offsets - printer.set_temperature_offset({"bed": offset}) + # set the offsets + printer.set_temperature_offset({"bed": offset}) - return NO_CONTENT + return NO_CONTENT @api.route("/printer/bed", methods=["GET"]) @no_firstrun_access @Permissions.STATUS.require(403) def printerBedState(): - if not printer.is_operational(): - return make_response("Printer is not operational", 409) + if not printer.is_operational(): + return make_response("Printer is not operational", 409) - if not printerProfileManager.get_current_or_default()["heatedBed"]: - return make_response("Printer does not have a heated bed", 409) + if not printerProfileManager.get_current_or_default()["heatedBed"]: + return make_response("Printer does not have a heated bed", 409) - data = _get_temperature_data(_keep_bed) - if isinstance(data, Response): - return data - else: - return jsonify(data) + data = _get_temperature_data(_keep_bed) + if isinstance(data, Response): + return data + else: + return jsonify(data) ##~~ Heated chamber @@ -242,64 +250,61 @@ def printerBedState(): @no_firstrun_access @Permissions.CONTROL.require(403) def printerChamberCommand(): - if not printer.is_operational(): - return make_response("Printer is not operational", 409) + if not printer.is_operational(): + return make_response("Printer is not operational", 409) - if not printerProfileManager.get_current_or_default()["heatedChamber"]: - return make_response("Printer does not have a heated chamber", 409) + if not printerProfileManager.get_current_or_default()["heatedChamber"]: + return make_response("Printer does not have a heated chamber", 409) - valid_commands = { - "target": ["target"], - "offset": ["offset"] - } - command, data, response = get_json_command_from_request(request, valid_commands) - if response is not None: - return response + valid_commands = {"target": ["target"], "offset": ["offset"]} + command, data, response = get_json_command_from_request(request, valid_commands) + if response is not None: + return response - tags = {"source:api", "api:printer.chamber"} + tags = {"source:api", "api:printer.chamber"} - ##~~ temperature - if command == "target": - target = data["target"] + ##~~ temperature + if command == "target": + target = data["target"] - # make sure the target is a number - if not isinstance(target, (int, long, float)): - return make_response("Not a number: %r" % target, 400) + # make sure the target is a number + if not isinstance(target, (int, long, float)): + return make_response("Not a number: %r" % target, 400) - # perform the actual temperature command - printer.set_temperature("chamber", target, tags=tags) + # perform the actual temperature command + printer.set_temperature("chamber", target, tags=tags) - ##~~ temperature offset - elif command == "offset": - offset = data["offset"] + ##~~ temperature offset + elif command == "offset": + offset = data["offset"] - # make sure the offset is valid - if not isinstance(offset, (int, long, float)): - return make_response("Not a number: %r" % offset, 400) - if not -50 <= offset <= 50: - return make_response("Offset not in range [-50, 50]: %f" % offset, 400) + # make sure the offset is valid + if not isinstance(offset, (int, long, float)): + return make_response("Not a number: %r" % offset, 400) + if not -50 <= offset <= 50: + return make_response("Offset not in range [-50, 50]: %f" % offset, 400) - # set the offsets - printer.set_temperature_offset({"chamber": offset}) + # set the offsets + printer.set_temperature_offset({"chamber": offset}) - return NO_CONTENT + return NO_CONTENT @api.route("/printer/chamber", methods=["GET"]) @no_firstrun_access @Permissions.STATUS.require(403) def printerChamberState(): - if not printer.is_operational(): - return make_response("Printer is not operational", 409) + if not printer.is_operational(): + return make_response("Printer is not operational", 409) - if not printerProfileManager.get_current_or_default()["heatedChamber"]: - return make_response("Printer does not have a heated chamber", 409) + if not printerProfileManager.get_current_or_default()["heatedChamber"]: + return make_response("Printer does not have a heated chamber", 409) - data = _get_temperature_data(_keep_chamber) - if isinstance(data, Response): - return data - else: - return jsonify(data) + data = _get_temperature_data(_keep_chamber) + if isinstance(data, Response): + return data + else: + return jsonify(data) ##~~ Print head @@ -309,61 +314,59 @@ def printerChamberState(): @no_firstrun_access @Permissions.CONTROL.require(403) def printerPrintheadCommand(): - valid_commands = { - "jog": [], - "home": ["axes"], - "feedrate": ["factor"] - } - command, data, response = get_json_command_from_request(request, valid_commands) - if response is not None: - return response + valid_commands = {"jog": [], "home": ["axes"], "feedrate": ["factor"]} + command, data, response = get_json_command_from_request(request, valid_commands) + if response is not None: + return response - if not printer.is_operational() or (printer.is_printing() and command != "feedrate"): - # do not jog when a print job is running or we don't have a connection - return make_response("Printer is not operational or currently printing", 409) + if not printer.is_operational() or (printer.is_printing() and command != "feedrate"): + # do not jog when a print job is running or we don't have a connection + return make_response("Printer is not operational or currently printing", 409) - tags = {"source:api", "api:printer.printhead"} + tags = {"source:api", "api:printer.printhead"} - valid_axes = ["x", "y", "z"] - ##~~ jog command - if command == "jog": - # validate all jog instructions, make sure that the values are numbers - validated_values = {} - for axis in valid_axes: - if axis in data: - value = data[axis] - if not isinstance(value, (int, long, float)): - return make_response("Not a number for axis %s: %r" % (axis, value), 400) - validated_values[axis] = value + valid_axes = ["x", "y", "z"] + ##~~ jog command + if command == "jog": + # validate all jog instructions, make sure that the values are numbers + validated_values = {} + for axis in valid_axes: + if axis in data: + value = data[axis] + if not isinstance(value, (int, long, float)): + return make_response( + "Not a number for axis %s: %r" % (axis, value), 400 + ) + validated_values[axis] = value - absolute = "absolute" in data and data["absolute"] in valid_boolean_trues - speed = data.get("speed", None) + absolute = "absolute" in data and data["absolute"] in valid_boolean_trues + speed = data.get("speed", None) - # execute the jog commands - printer.jog(validated_values, relative=not absolute, speed=speed, tags=tags) + # execute the jog commands + printer.jog(validated_values, relative=not absolute, speed=speed, tags=tags) - ##~~ home command - elif command == "home": - validated_values = [] - axes = data["axes"] - for axis in axes: - if not axis in valid_axes: - return make_response("Invalid axis: %s" % axis, 400) - validated_values.append(axis) + ##~~ home command + elif command == "home": + validated_values = [] + axes = data["axes"] + for axis in axes: + if not axis in valid_axes: + return make_response("Invalid axis: %s" % axis, 400) + validated_values.append(axis) - # execute the home command - printer.home(validated_values, tags=tags) + # execute the home command + printer.home(validated_values, tags=tags) - elif command == "feedrate": - factor = data["factor"] - if not isinstance(factor, (int, long, float)): - return make_response("Not a number for feed rate: %r" % factor, 400) - try: - printer.feed_rate(factor, tags=tags) - except ValueError as e: - return make_response("Invalid value for feed rate: %s" % str(e), 400) + elif command == "feedrate": + factor = data["factor"] + if not isinstance(factor, (int, long, float)): + return make_response("Not a number for feed rate: %r" % factor, 400) + try: + printer.feed_rate(factor, tags=tags) + except ValueError as e: + return make_response("Invalid value for feed rate: %s" % str(e), 400) - return NO_CONTENT + return NO_CONTENT ##~~ SD Card @@ -373,41 +376,37 @@ def printerPrintheadCommand(): @no_firstrun_access @Permissions.CONTROL.require(403) def printerSdCommand(): - if not settings().getBoolean(["feature", "sdSupport"]): - return make_response("SD support is disabled", 404) + if not settings().getBoolean(["feature", "sdSupport"]): + return make_response("SD support is disabled", 404) - if not printer.is_operational() or printer.is_printing() or printer.is_paused(): - return make_response("Printer is not operational or currently busy", 409) + if not printer.is_operational() or printer.is_printing() or printer.is_paused(): + return make_response("Printer is not operational or currently busy", 409) - valid_commands = { - "init": [], - "refresh": [], - "release": [] - } - command, data, response = get_json_command_from_request(request, valid_commands) - if response is not None: - return response + valid_commands = {"init": [], "refresh": [], "release": []} + command, data, response = get_json_command_from_request(request, valid_commands) + if response is not None: + return response - tags = {"source:api", "api:printer.sd"} + tags = {"source:api", "api:printer.sd"} - if command == "init": - printer.init_sd_card(tags=tags) - elif command == "refresh": - printer.refresh_sd_files(tags=tags) - elif command == "release": - printer.release_sd_card(tags=tags) + if command == "init": + printer.init_sd_card(tags=tags) + elif command == "refresh": + printer.refresh_sd_files(tags=tags) + elif command == "release": + printer.release_sd_card(tags=tags) - return NO_CONTENT + return NO_CONTENT @api.route("/printer/sd", methods=["GET"]) @no_firstrun_access @Permissions.STATUS.require(403) def printerSdState(): - if not settings().getBoolean(["feature", "sdSupport"]): - return make_response("SD support is disabled", 404) + if not settings().getBoolean(["feature", "sdSupport"]): + return make_response("SD support is disabled", 404) - return jsonify(ready=printer.is_sd_ready()) + return jsonify(ready=printer.is_sd_ready()) ##~~ Commands @@ -417,116 +416,122 @@ def printerSdState(): @no_firstrun_access @Permissions.CONTROL.require(403) def printerCommand(): - if not printer.is_operational(): - return make_response("Printer is not operational", 409) + if not printer.is_operational(): + return make_response("Printer is not operational", 409) - if not "application/json" in request.headers["Content-Type"]: - return make_response("Expected content type JSON", 400) + if not "application/json" in request.headers["Content-Type"]: + return make_response("Expected content type JSON", 400) - try: - data = request.get_json() - except BadRequest: - return make_response("Malformed JSON body in request", 400) + try: + data = request.get_json() + except BadRequest: + return make_response("Malformed JSON body in request", 400) - if data is None: - return make_response("Malformed JSON body in request", 400) + if data is None: + return make_response("Malformed JSON body in request", 400) - if "command" in data and "commands" in data: - return make_response("'command' and 'commands' are mutually exclusive", 400) - elif ("command" in data or "commands" in data) and "script" in data: - return make_response("'command'/'commands' and 'script' are mutually exclusive", 400) - elif not ("command" in data or "commands" in data or "script" in data): - return make_response("Need one of 'command', 'commands' or 'script'", 400) + if "command" in data and "commands" in data: + return make_response("'command' and 'commands' are mutually exclusive", 400) + elif ("command" in data or "commands" in data) and "script" in data: + return make_response( + "'command'/'commands' and 'script' are mutually exclusive", 400 + ) + elif not ("command" in data or "commands" in data or "script" in data): + return make_response("Need one of 'command', 'commands' or 'script'", 400) - parameters = {} - if "parameters" in data: - parameters = data["parameters"] + parameters = {} + if "parameters" in data: + parameters = data["parameters"] - tags = {"source:api", "api:printer.command"} + tags = {"source:api", "api:printer.command"} - if "command" in data or "commands" in data: - if "command" in data: - commands = [data["command"]] - else: - if not isinstance(data["commands"], (list, tuple)): - return make_response("'commands' needs to be a list", 400) - commands = data["commands"] + if "command" in data or "commands" in data: + if "command" in data: + commands = [data["command"]] + else: + if not isinstance(data["commands"], (list, tuple)): + return make_response("'commands' needs to be a list", 400) + commands = data["commands"] - commandsToSend = [] - for command in commands: - commandToSend = command - if len(parameters) > 0: - commandToSend = command % parameters - commandsToSend.append(commandToSend) + commandsToSend = [] + for command in commands: + commandToSend = command + if len(parameters) > 0: + commandToSend = command % parameters + commandsToSend.append(commandToSend) - printer.commands(commandsToSend, tags=tags) + printer.commands(commandsToSend, tags=tags) - elif "script" in data: - script_name = data["script"] - context = {"parameters": parameters} - if "context" in data: - context["context"] = data["context"] + elif "script" in data: + script_name = data["script"] + context = {"parameters": parameters} + if "context" in data: + context["context"] = data["context"] - try: - printer.script(script_name, context=context, tags=tags) - except UnknownScript: - return make_response("Unknown script: {script_name}".format(**locals()), 404) + try: + printer.script(script_name, context=context, tags=tags) + except UnknownScript: + return make_response("Unknown script: {script_name}".format(**locals()), 404) + + return NO_CONTENT - return NO_CONTENT @api.route("/printer/command/custom", methods=["GET"]) @no_firstrun_access @Permissions.CONTROL.require(403) def getCustomControls(): - customControls = settings().get(["controls"]) - return jsonify(controls=customControls) + customControls = settings().get(["controls"]) + return jsonify(controls=customControls) def _get_temperature_data(preprocessor): - if not printer.is_operational(): - return make_response("Printer is not operational", 409) + if not printer.is_operational(): + return make_response("Printer is not operational", 409) - tempData = printer.get_current_temperatures() + tempData = printer.get_current_temperatures() - if "history" in request.values and request.values["history"] in valid_boolean_trues: - tempHistory = printer.get_temperature_history() + if "history" in request.values and request.values["history"] in valid_boolean_trues: + tempHistory = printer.get_temperature_history() - limit = 300 - if "limit" in request.values and unicode(request.values["limit"]).isnumeric(): - limit = int(request.values["limit"]) + limit = 300 + if "limit" in request.values and unicode(request.values["limit"]).isnumeric(): + limit = int(request.values["limit"]) - history = list(tempHistory) - limit = min(limit, len(history)) + history = list(tempHistory) + limit = min(limit, len(history)) - tempData.update({ - "history": list(map(lambda x: preprocessor(x), history[-limit:])) - }) + tempData.update( + {"history": list(map(lambda x: preprocessor(x), history[-limit:]))} + ) - return preprocessor(tempData) + return preprocessor(tempData) def _keep_tools(x): - return _delete_from_data(x, lambda k: not k.startswith("tool") and k != "history") + return _delete_from_data(x, lambda k: not k.startswith("tool") and k != "history") def _keep_bed(x): - return _delete_from_data(x, lambda k: k != "bed" and k != "history") + return _delete_from_data(x, lambda k: k != "bed" and k != "history") + def _delete_bed(x): - return _delete_from_data(x, lambda k: k == "bed") + return _delete_from_data(x, lambda k: k == "bed") + def _keep_chamber(x): - return _delete_from_data(x, lambda k: k != "chamber" and k != "history") + return _delete_from_data(x, lambda k: k != "chamber" and k != "history") + def _delete_chamber(x): - return _delete_from_data(x, lambda k: k == "chamber") + return _delete_from_data(x, lambda k: k == "chamber") def _delete_from_data(x, key_matcher): - data = dict(x) - # must make list of keys first to avoid - # RuntimeError: dictionary changed size during iteration - for k in list(data.keys()): - if key_matcher(k): - del data[k] - return data + data = dict(x) + # must make list of keys first to avoid + # RuntimeError: dictionary changed size during iteration + for k in list(data.keys()): + if key_matcher(k): + del data[k] + return data diff --git a/src/octoprint/server/api/printer_profiles.py b/src/octoprint/server/api/printer_profiles.py index dd86f829e..d7a1c5a6c 100644 --- a/src/octoprint/server/api/printer_profiles.py +++ b/src/octoprint/server/api/printer_profiles.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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" @@ -21,171 +21,200 @@ from octoprint.server import printerProfileManager from octoprint.printer.profile import InvalidProfileError, CouldNotOverwriteError from octoprint.access.permissions import Permissions + def _lastmodified(): - return printerProfileManager.last_modified + return printerProfileManager.last_modified + def _etag(lm=None): - if lm is None: - lm = _lastmodified() + if lm is None: + lm = _lastmodified() - import hashlib - hash = hashlib.sha1() - def hash_update(value): - value = value.encode('utf-8') - hash.update(value) - hash_update(str(lm)) - hash_update(repr(printerProfileManager.get_default())) - hash_update(repr(printerProfileManager.get_current())) - return hash.hexdigest() + import hashlib + + hash = hashlib.sha1() + + def hash_update(value): + value = value.encode("utf-8") + hash.update(value) + + hash_update(str(lm)) + hash_update(repr(printerProfileManager.get_default())) + hash_update(repr(printerProfileManager.get_current())) + return hash.hexdigest() @api.route("/printerprofiles", methods=["GET"]) -@with_revalidation_checking(etag_factory=_etag, - lastmodified_factory=_lastmodified, - unless=lambda: request.values.get("force", "false") in valid_boolean_trues) +@with_revalidation_checking( + etag_factory=_etag, + lastmodified_factory=_lastmodified, + unless=lambda: request.values.get("force", "false") in valid_boolean_trues, +) @no_firstrun_access @Permissions.CONNECTION.require(403) def printerProfilesList(): - all_profiles = printerProfileManager.get_all() - return jsonify({"profiles": _convert_profiles(all_profiles)}) + all_profiles = printerProfileManager.get_all() + return jsonify({"profiles": _convert_profiles(all_profiles)}) + @api.route("/printerprofiles", methods=["POST"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def printerProfilesAdd(): - if not "application/json" in request.headers["Content-Type"]: - return make_response("Expected content-type JSON", 400) + if not "application/json" in request.headers["Content-Type"]: + return make_response("Expected content-type JSON", 400) - try: - json_data = request.get_json() - except BadRequest: - return make_response("Malformed JSON body in request", 400) + try: + json_data = request.get_json() + except BadRequest: + return make_response("Malformed JSON body in request", 400) - if json_data is None: - return make_response("Malformed JSON body in request", 400) + if json_data is None: + return make_response("Malformed JSON body in request", 400) - if not "profile" in json_data: - return make_response("No profile included in request", 400) + if not "profile" in json_data: + return make_response("No profile included in request", 400) - base_profile = printerProfileManager.get_default() - if "basedOn" in json_data and isinstance(json_data["basedOn"], basestring): - other_profile = printerProfileManager.get(json_data["basedOn"]) - if other_profile is not None: - base_profile = other_profile + base_profile = printerProfileManager.get_default() + if "basedOn" in json_data and isinstance(json_data["basedOn"], basestring): + other_profile = printerProfileManager.get(json_data["basedOn"]) + if other_profile is not None: + base_profile = other_profile - if "id" in base_profile: - del base_profile["id"] - if "name" in base_profile: - del base_profile["name"] - if "default" in base_profile: - del base_profile["default"] + if "id" in base_profile: + del base_profile["id"] + if "name" in base_profile: + del base_profile["name"] + if "default" in base_profile: + del base_profile["default"] - new_profile = json_data["profile"] - make_default = False - if "default" in new_profile: - make_default = True - del new_profile["default"] + new_profile = json_data["profile"] + make_default = False + if "default" in new_profile: + make_default = True + del new_profile["default"] - profile = dict_merge(base_profile, new_profile) + profile = dict_merge(base_profile, new_profile) - if not "id" in profile: - return make_response("Profile does not contain mandatory 'id' field", 400) - if not "name" in profile: - return make_response("Profile does not contain mandatory 'name' field", 400) + if not "id" in profile: + return make_response("Profile does not contain mandatory 'id' field", 400) + if not "name" in profile: + return make_response("Profile does not contain mandatory 'name' field", 400) + + try: + saved_profile = printerProfileManager.save( + profile, allow_overwrite=False, make_default=make_default, trigger_event=True + ) + except InvalidProfileError: + return make_response("Profile is invalid", 400) + except CouldNotOverwriteError: + return make_response( + "Profile {} already exists and overwriting was not allowed".format( + profile["id"] + ), + 400, + ) + except Exception as e: + return make_response("Could not save profile: %s" % str(e), 500) + else: + return jsonify({"profile": _convert_profile(saved_profile)}) - try: - saved_profile = printerProfileManager.save(profile, allow_overwrite=False, make_default=make_default, - trigger_event=True) - except InvalidProfileError: - return make_response("Profile is invalid", 400) - except CouldNotOverwriteError: - return make_response("Profile {} already exists and overwriting was not allowed".format(profile["id"]), 400) - except Exception as e: - return make_response("Could not save profile: %s" % str(e), 500) - else: - return jsonify({"profile": _convert_profile(saved_profile)}) @api.route("/printerprofiles/", methods=["GET"]) @no_firstrun_access @Permissions.CONNECTION.require(403) def printerProfilesGet(identifier): - profile = printerProfileManager.get(identifier) - if profile is None: - return make_response("Unknown profile: %s" % identifier, 404) - else: - return jsonify(_convert_profile(profile)) + profile = printerProfileManager.get(identifier) + if profile is None: + return make_response("Unknown profile: %s" % identifier, 404) + else: + return jsonify(_convert_profile(profile)) + @api.route("/printerprofiles/", methods=["DELETE"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def printerProfilesDelete(identifier): - current_profile = printerProfileManager.get_current() - if current_profile and current_profile["id"] == identifier: - return make_response("Cannot delete currently selected profile: {}".format(identifier), 409) + current_profile = printerProfileManager.get_current() + if current_profile and current_profile["id"] == identifier: + return make_response( + "Cannot delete currently selected profile: {}".format(identifier), 409 + ) - default_profile = printerProfileManager.get_default() - if default_profile and default_profile["id"] == identifier: - return make_response("Cannot delete default profile: {}".format(identifier), 409) + default_profile = printerProfileManager.get_default() + if default_profile and default_profile["id"] == identifier: + return make_response("Cannot delete default profile: {}".format(identifier), 409) + + printerProfileManager.remove(identifier, trigger_event=True) + return NO_CONTENT - printerProfileManager.remove(identifier, trigger_event=True) - return NO_CONTENT @api.route("/printerprofiles/", methods=["PATCH"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def printerProfilesUpdate(identifier): - if not "application/json" in request.headers["Content-Type"]: - return make_response("Expected content-type JSON", 400) + if not "application/json" in request.headers["Content-Type"]: + return make_response("Expected content-type JSON", 400) - try: - json_data = request.get_json() - except BadRequest: - return make_response("Malformed JSON body in request", 400) + try: + json_data = request.get_json() + except BadRequest: + return make_response("Malformed JSON body in request", 400) - if json_data is None: - return make_response("Malformed JSON body in request", 400) + if json_data is None: + return make_response("Malformed JSON body in request", 400) - if not "profile" in json_data: - return make_response("No profile included in request", 400) + if not "profile" in json_data: + return make_response("No profile included in request", 400) - profile = printerProfileManager.get(identifier) - if profile is None: - profile = printerProfileManager.get_default() + profile = printerProfileManager.get(identifier) + if profile is None: + profile = printerProfileManager.get_default() - new_profile = json_data["profile"] - merged_profile = dict_merge(profile, new_profile) + new_profile = json_data["profile"] + merged_profile = dict_merge(profile, new_profile) - make_default = False - if "default" in merged_profile: - make_default = True - del new_profile["default"] + make_default = False + if "default" in merged_profile: + make_default = True + del new_profile["default"] - merged_profile["id"] = identifier + merged_profile["id"] = identifier + + try: + saved_profile = printerProfileManager.save( + merged_profile, + allow_overwrite=True, + make_default=make_default, + trigger_event=True, + ) + except InvalidProfileError: + return make_response("Profile is invalid", 400) + except CouldNotOverwriteError: + return make_response( + "Profile already exists and overwriting was not allowed", 400 + ) + except Exception as e: + return make_response("Could not save profile: %s" % str(e), 500) + else: + return jsonify({"profile": _convert_profile(saved_profile)}) - try: - saved_profile = printerProfileManager.save(merged_profile, allow_overwrite=True, make_default=make_default, - trigger_event=True) - except InvalidProfileError: - return make_response("Profile is invalid", 400) - except CouldNotOverwriteError: - return make_response("Profile already exists and overwriting was not allowed", 400) - except Exception as e: - return make_response("Could not save profile: %s" % str(e), 500) - else: - return jsonify({"profile": _convert_profile(saved_profile)}) def _convert_profiles(profiles): - result = {} - for identifier, profile in profiles.items(): - result[identifier] = _convert_profile(profile) - return result + result = {} + for identifier, profile in profiles.items(): + result[identifier] = _convert_profile(profile) + return result + def _convert_profile(profile): - default = printerProfileManager.get_default()["id"] - current = printerProfileManager.get_current_or_default()["id"] + default = printerProfileManager.get_default()["id"] + current = printerProfileManager.get_current_or_default()["id"] - converted = copy.deepcopy(profile) - converted["resource"] = url_for(".printerProfilesGet", identifier=profile["id"], _external=True) - converted["default"] = (profile["id"] == default) - converted["current"] = (profile["id"] == current) - return converted + converted = copy.deepcopy(profile) + converted["resource"] = url_for( + ".printerProfilesGet", identifier=profile["id"], _external=True + ) + converted["default"] = profile["id"] == default + converted["current"] = profile["id"] == current + return converted diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index b3a8b8aff..6bd50906c 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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 logging @@ -22,591 +22,1001 @@ from octoprint.access.permissions import Permissions import octoprint.plugin import octoprint.util -#~~ settings +# ~~ settings + def _lastmodified(): - return settings().last_modified + return settings().last_modified + def _etag(lm=None): - if lm is None: - lm = _lastmodified() + if lm is None: + lm = _lastmodified() - connection_options = printer.__class__.get_connection_options() - plugins = sorted(octoprint.plugin.plugin_manager().enabled_plugins) - plugin_settings = _get_plugin_settings() + connection_options = printer.__class__.get_connection_options() + plugins = sorted(octoprint.plugin.plugin_manager().enabled_plugins) + plugin_settings = _get_plugin_settings() - from collections import OrderedDict - sorted_plugin_settings = OrderedDict() - for key in sorted(plugin_settings.keys()): - sorted_plugin_settings[key] = plugin_settings.get(key, {}) + from collections import OrderedDict - if current_user is not None and not current_user.is_anonymous: - roles = sorted(current_user.permissions, key=lambda x: x.key) - else: - roles = [] + sorted_plugin_settings = OrderedDict() + for key in sorted(plugin_settings.keys()): + sorted_plugin_settings[key] = plugin_settings.get(key, {}) - import hashlib - hash = hashlib.sha1() - def hash_update(value): - value = value.encode('utf-8') - hash.update(value) + if current_user is not None and not current_user.is_anonymous: + roles = sorted(current_user.permissions, key=lambda x: x.key) + else: + roles = [] - # last modified timestamp - hash_update(str(lm)) + import hashlib - # effective config from config.yaml + overlays - hash_update(repr(settings().effective)) + hash = hashlib.sha1() - # might duplicate settings().effective, but plugins might also inject additional keys into the settings - # output that are not stored in config.yaml - hash_update(repr(sorted_plugin_settings)) + def hash_update(value): + value = value.encode("utf-8") + hash.update(value) - # connection options are also part of the settings - hash_update(repr(connection_options)) + # last modified timestamp + hash_update(str(lm)) - # if the list of plugins changes, the settings structure changes too - hash_update(repr(plugins)) + # effective config from config.yaml + overlays + hash_update(repr(settings().effective)) - # and likewise if the role of the user changes - hash_update(repr(roles)) + # might duplicate settings().effective, but plugins might also inject additional keys into the settings + # output that are not stored in config.yaml + hash_update(repr(sorted_plugin_settings)) + + # connection options are also part of the settings + hash_update(repr(connection_options)) + + # if the list of plugins changes, the settings structure changes too + hash_update(repr(plugins)) + + # and likewise if the role of the user changes + hash_update(repr(roles)) + + return hash.hexdigest() - return hash.hexdigest() @api.route("/settings", methods=["GET"]) -@with_revalidation_checking(etag_factory=_etag, - lastmodified_factory=_lastmodified, - unless=lambda: request.values.get("force", "false") in valid_boolean_trues or settings().getBoolean(["server", "firstRun"])) +@with_revalidation_checking( + etag_factory=_etag, + lastmodified_factory=_lastmodified, + unless=lambda: request.values.get("force", "false") in valid_boolean_trues + or settings().getBoolean(["server", "firstRun"]), +) def getSettings(): - if not Permissions.SETTINGS_READ.can() and not settings().getBoolean(["server", "firstRun"]): - abort(403) + if not Permissions.SETTINGS_READ.can() and not settings().getBoolean( + ["server", "firstRun"] + ): + abort(403) - s = settings() + s = settings() - connectionOptions = printer.__class__.get_connection_options() + connectionOptions = printer.__class__.get_connection_options() - # NOTE: Remember to adjust the docs of the data model on the Settings API if anything - # is changed, added or removed here + # NOTE: Remember to adjust the docs of the data model on the Settings API if anything + # is changed, added or removed here - data = { - "api": { - "key": s.get(["api", "key"]) if Permissions.ADMIN.can() else None, - "allowCrossOrigin": s.get(["api", "allowCrossOrigin"]) - }, - "appearance": { - "name": s.get(["appearance", "name"]), - "color": s.get(["appearance", "color"]), - "colorTransparent": s.getBoolean(["appearance", "colorTransparent"]), - "colorIcon": s.getBoolean(["appearance", "colorIcon"]), - "defaultLanguage": s.get(["appearance", "defaultLanguage"]), - "showFahrenheitAlso": s.getBoolean(["appearance", "showFahrenheitAlso"]), - "fuzzyTimes": s.getBoolean(["appearance", "fuzzyTimes"]), - "closeModalsWithClick": s.getBoolean(["appearance", "closeModalsWithClick"]) - }, - "printer": { - "defaultExtrusionLength": s.getInt(["printerParameters", "defaultExtrusionLength"]) - }, - "webcam": { - "webcamEnabled": s.getBoolean(["webcam", "webcamEnabled"]), - "timelapseEnabled": s.getBoolean(["webcam", "timelapseEnabled"]), - "streamUrl": s.get(["webcam", "stream"]), - "streamRatio": s.get(["webcam", "streamRatio"]), - "streamTimeout": s.getInt(["webcam", "streamTimeout"]), - "snapshotUrl": s.get(["webcam", "snapshot"]), - "snapshotTimeout": s.getInt(["webcam", "snapshotTimeout"]), - "snapshotSslValidation": s.getBoolean(["webcam", "snapshotSslValidation"]), - "ffmpegPath": s.get(["webcam", "ffmpeg"]), - "bitrate": s.get(["webcam", "bitrate"]), - "ffmpegThreads": s.get(["webcam", "ffmpegThreads"]), - "ffmpegVideoCodec": s.get(["webcam", "ffmpegVideoCodec"]), - "watermark": s.getBoolean(["webcam", "watermark"]), - "flipH": s.getBoolean(["webcam", "flipH"]), - "flipV": s.getBoolean(["webcam", "flipV"]), - "rotate90": s.getBoolean(["webcam", "rotate90"]) - }, - "feature": { - "temperatureGraph": s.getBoolean(["feature", "temperatureGraph"]), - "sdSupport": s.getBoolean(["feature", "sdSupport"]), - "keyboardControl": s.getBoolean(["feature", "keyboardControl"]), - "pollWatched": s.getBoolean(["feature", "pollWatched"]), - "modelSizeDetection": s.getBoolean(["feature", "modelSizeDetection"]), - "printStartConfirmation": s.getBoolean(["feature", "printStartConfirmation"]), - "printCancelConfirmation": s.getBoolean(["feature", "printCancelConfirmation"]), - "g90InfluencesExtruder": s.getBoolean(["feature", "g90InfluencesExtruder"]), - "autoUppercaseBlacklist": s.get(["feature", "autoUppercaseBlacklist"]) - }, - "gcodeAnalysis": { - "runAt": s.get(["gcodeAnalysis", "runAt"]) - }, - "serial": { - "port": connectionOptions["portPreference"], - "baudrate": connectionOptions["baudratePreference"], - "exclusive": s.getBoolean(["serial", "exclusive"]), - "portOptions": connectionOptions["ports"], - "baudrateOptions": connectionOptions["baudrates"], - "autoconnect": s.getBoolean(["serial", "autoconnect"]), - "timeoutConnection": s.getFloat(["serial", "timeout", "connection"]), - "timeoutDetectionFirst": s.getFloat(["serial", "timeout", "detectionFirst"]), - "timeoutDetectionConsecutive": s.getFloat(["serial", "timeout", "detectionConsecutive"]), - "timeoutCommunication": s.getFloat(["serial", "timeout", "communication"]), - "timeoutCommunicationBusy": s.getFloat(["serial", "timeout", "communicationBusy"]), - "timeoutTemperature": s.getFloat(["serial", "timeout", "temperature"]), - "timeoutTemperatureTargetSet": s.getFloat(["serial", "timeout", "temperatureTargetSet"]), - "timeoutTemperatureAutoreport": s.getFloat(["serial", "timeout", "temperatureAutoreport"]), - "timeoutSdStatus": s.getFloat(["serial", "timeout", "sdStatus"]), - "timeoutSdStatusAutoreport": s.getFloat(["serial", "timeout", "sdStatusAutoreport"]), - "timeoutBaudrateDetectionPause": s.getFloat(["serial", "timeout", "baudrateDetectionPause"]), - "timeoutPositionLogWait": s.getFloat(["serial", "timeout", "positionLogWait"]), - "log": s.getBoolean(["serial", "log"]), - "additionalPorts": s.get(["serial", "additionalPorts"]), - "additionalBaudrates": s.get(["serial", "additionalBaudrates"]), - "blacklistedPorts": s.get(["serial", "blacklistedPorts"]), - "blacklistedBaudrates": s.get(["serial", "blacklistedBaudrates"]), - "longRunningCommands": s.get(["serial", "longRunningCommands"]), - "checksumRequiringCommands": s.get(["serial", "checksumRequiringCommands"]), - "blockedCommands": s.get(["serial", "blockedCommands"]), - "pausingCommands": s.get(["serial", "pausingCommands"]), - "emergencyCommands": s.get(["serial", "emergencyCommands"]), - "helloCommand": s.get(["serial", "helloCommand"]), - "ignoreErrorsFromFirmware": s.getBoolean(["serial", "ignoreErrorsFromFirmware"]), - "disconnectOnErrors": s.getBoolean(["serial", "disconnectOnErrors"]), - "triggerOkForM29": s.getBoolean(["serial", "triggerOkForM29"]), - "logPositionOnPause": s.getBoolean(["serial", "logPositionOnPause"]), - "logPositionOnCancel": s.getBoolean(["serial", "logPositionOnCancel"]), - "abortHeatupOnCancel": s.getBoolean(["serial", "abortHeatupOnCancel"]), - "supportResendsWithoutOk": s.get(["serial", "supportResendsWithoutOk"]), - "waitForStart": s.getBoolean(["serial", "waitForStartOnConnect"]), - "alwaysSendChecksum": s.getBoolean(["serial", "alwaysSendChecksum"]), - "neverSendChecksum": s.getBoolean(["serial", "neverSendChecksum"]), - "sdRelativePath": s.getBoolean(["serial", "sdRelativePath"]), - "sdAlwaysAvailable": s.getBoolean(["serial", "sdAlwaysAvailable"]), - "swallowOkAfterResend": s.getBoolean(["serial", "swallowOkAfterResend"]), - "repetierTargetTemp": s.getBoolean(["serial", "repetierTargetTemp"]), - "externalHeatupDetection": s.getBoolean(["serial", "externalHeatupDetection"]), - "ignoreIdenticalResends": s.getBoolean(["serial", "ignoreIdenticalResends"]), - "firmwareDetection": s.getBoolean(["serial", "firmwareDetection"]), - "blockWhileDwelling": s.getBoolean(["serial", "blockWhileDwelling"]), - "useParityWorkaround": s.get(["serial", "useParityWorkaround"]), - "sanityCheckTools": s.getBoolean(["serial", "sanityCheckTools"]), - "sendM112OnError": s.getBoolean(["serial", "sendM112OnError"]), - "disableSdPrintingDetection": s.getBoolean(["serial", "disableSdPrintingDetection"]), - "ackMax": s.getInt(["serial", "ackMax"]), - "maxTimeoutsIdle": s.getInt(["serial", "maxCommunicationTimeouts", "idle"]), - "maxTimeoutsPrinting": s.getInt(["serial", "maxCommunicationTimeouts", "printing"]), - "maxTimeoutsLong": s.getInt(["serial", "maxCommunicationTimeouts", "long"]), - "capAutoreportTemp": s.getBoolean(["serial", "capabilities", "autoreport_temp"]), - "capAutoreportSdStatus": s.getBoolean(["serial", "capabilities", "autoreport_sdstatus"]), - "capBusyProtocol": s.getBoolean(["serial", "capabilities", "busy_protocol"]), - "capEmergencyParser": s.getBoolean(["serial", "capabilities", "emergency_parser"]) - }, - "folder": { - "uploads": s.getBaseFolder("uploads"), - "timelapse": s.getBaseFolder("timelapse"), - "timelapseTmp": s.getBaseFolder("timelapse_tmp"), - "logs": s.getBaseFolder("logs"), - "watched": s.getBaseFolder("watched") - }, - "temperature": { - "profiles": s.get(["temperature", "profiles"]), - "cutoff": s.getInt(["temperature", "cutoff"]), - "sendAutomatically": s.getBoolean(["temperature", "sendAutomatically"]), - "sendAutomaticallyAfter": s.getInt(["temperature", "sendAutomaticallyAfter"], min=0, max=30), - }, - "system": { - "actions": s.get(["system", "actions"]), - "events": s.get(["system", "events"]) - }, - "terminalFilters": s.get(["terminalFilters"]), - "scripts": { - "gcode": { - "afterPrinterConnected": None, - "beforePrinterDisconnected": None, - "beforePrintStarted": None, - "afterPrintCancelled": None, - "afterPrintDone": None, - "beforePrintPaused": None, - "afterPrintResumed": None, - "beforeToolChange": None, - "afterToolChange": None, - "snippets": {} - } - }, - "server": { - "commands": { - "systemShutdownCommand": s.get(["server", "commands", "systemShutdownCommand"]), - "systemRestartCommand": s.get(["server", "commands", "systemRestartCommand"]), - "serverRestartCommand": s.get(["server", "commands", "serverRestartCommand"]) - }, - "diskspace": { - "warning": s.getInt(["server", "diskspace", "warning"]), - "critical": s.getInt(["server", "diskspace", "critical"]) - }, - "onlineCheck": { - "enabled": s.getBoolean(["server", "onlineCheck", "enabled"]), - "interval": int(s.getInt(["server", "onlineCheck", "interval"]) / 60), - "host": s.get(["server", "onlineCheck", "host"]), - "port": s.getInt(["server", "onlineCheck", "port"]), - "name": s.get(["server", "onlineCheck", "name"]) - }, - "pluginBlacklist": { - "enabled": s.getBoolean(["server", "pluginBlacklist", "enabled"]), - "url": s.get(["server", "pluginBlacklist", "url"]), - "ttl": int(s.getInt(["server", "pluginBlacklist", "ttl"]) / 60) - }, - "allowFraming": s.getBoolean(["server", "allowFraming"]) - }, - "devel": { - "pluginTimings": s.getBoolean(["devel", "pluginTimings"]) - } - } + data = { + "api": { + "key": s.get(["api", "key"]) if Permissions.ADMIN.can() else None, + "allowCrossOrigin": s.get(["api", "allowCrossOrigin"]), + }, + "appearance": { + "name": s.get(["appearance", "name"]), + "color": s.get(["appearance", "color"]), + "colorTransparent": s.getBoolean(["appearance", "colorTransparent"]), + "colorIcon": s.getBoolean(["appearance", "colorIcon"]), + "defaultLanguage": s.get(["appearance", "defaultLanguage"]), + "showFahrenheitAlso": s.getBoolean(["appearance", "showFahrenheitAlso"]), + "fuzzyTimes": s.getBoolean(["appearance", "fuzzyTimes"]), + "closeModalsWithClick": s.getBoolean(["appearance", "closeModalsWithClick"]), + }, + "printer": { + "defaultExtrusionLength": s.getInt( + ["printerParameters", "defaultExtrusionLength"] + ) + }, + "webcam": { + "webcamEnabled": s.getBoolean(["webcam", "webcamEnabled"]), + "timelapseEnabled": s.getBoolean(["webcam", "timelapseEnabled"]), + "streamUrl": s.get(["webcam", "stream"]), + "streamRatio": s.get(["webcam", "streamRatio"]), + "streamTimeout": s.getInt(["webcam", "streamTimeout"]), + "snapshotUrl": s.get(["webcam", "snapshot"]), + "snapshotTimeout": s.getInt(["webcam", "snapshotTimeout"]), + "snapshotSslValidation": s.getBoolean(["webcam", "snapshotSslValidation"]), + "ffmpegPath": s.get(["webcam", "ffmpeg"]), + "bitrate": s.get(["webcam", "bitrate"]), + "ffmpegThreads": s.get(["webcam", "ffmpegThreads"]), + "ffmpegVideoCodec": s.get(["webcam", "ffmpegVideoCodec"]), + "watermark": s.getBoolean(["webcam", "watermark"]), + "flipH": s.getBoolean(["webcam", "flipH"]), + "flipV": s.getBoolean(["webcam", "flipV"]), + "rotate90": s.getBoolean(["webcam", "rotate90"]), + }, + "feature": { + "temperatureGraph": s.getBoolean(["feature", "temperatureGraph"]), + "sdSupport": s.getBoolean(["feature", "sdSupport"]), + "keyboardControl": s.getBoolean(["feature", "keyboardControl"]), + "pollWatched": s.getBoolean(["feature", "pollWatched"]), + "modelSizeDetection": s.getBoolean(["feature", "modelSizeDetection"]), + "printStartConfirmation": s.getBoolean(["feature", "printStartConfirmation"]), + "printCancelConfirmation": s.getBoolean( + ["feature", "printCancelConfirmation"] + ), + "g90InfluencesExtruder": s.getBoolean(["feature", "g90InfluencesExtruder"]), + "autoUppercaseBlacklist": s.get(["feature", "autoUppercaseBlacklist"]), + }, + "gcodeAnalysis": {"runAt": s.get(["gcodeAnalysis", "runAt"])}, + "serial": { + "port": connectionOptions["portPreference"], + "baudrate": connectionOptions["baudratePreference"], + "exclusive": s.getBoolean(["serial", "exclusive"]), + "portOptions": connectionOptions["ports"], + "baudrateOptions": connectionOptions["baudrates"], + "autoconnect": s.getBoolean(["serial", "autoconnect"]), + "timeoutConnection": s.getFloat(["serial", "timeout", "connection"]), + "timeoutDetectionFirst": s.getFloat(["serial", "timeout", "detectionFirst"]), + "timeoutDetectionConsecutive": s.getFloat( + ["serial", "timeout", "detectionConsecutive"] + ), + "timeoutCommunication": s.getFloat(["serial", "timeout", "communication"]), + "timeoutCommunicationBusy": s.getFloat( + ["serial", "timeout", "communicationBusy"] + ), + "timeoutTemperature": s.getFloat(["serial", "timeout", "temperature"]), + "timeoutTemperatureTargetSet": s.getFloat( + ["serial", "timeout", "temperatureTargetSet"] + ), + "timeoutTemperatureAutoreport": s.getFloat( + ["serial", "timeout", "temperatureAutoreport"] + ), + "timeoutSdStatus": s.getFloat(["serial", "timeout", "sdStatus"]), + "timeoutSdStatusAutoreport": s.getFloat( + ["serial", "timeout", "sdStatusAutoreport"] + ), + "timeoutBaudrateDetectionPause": s.getFloat( + ["serial", "timeout", "baudrateDetectionPause"] + ), + "timeoutPositionLogWait": s.getFloat( + ["serial", "timeout", "positionLogWait"] + ), + "log": s.getBoolean(["serial", "log"]), + "additionalPorts": s.get(["serial", "additionalPorts"]), + "additionalBaudrates": s.get(["serial", "additionalBaudrates"]), + "blacklistedPorts": s.get(["serial", "blacklistedPorts"]), + "blacklistedBaudrates": s.get(["serial", "blacklistedBaudrates"]), + "longRunningCommands": s.get(["serial", "longRunningCommands"]), + "checksumRequiringCommands": s.get(["serial", "checksumRequiringCommands"]), + "blockedCommands": s.get(["serial", "blockedCommands"]), + "pausingCommands": s.get(["serial", "pausingCommands"]), + "emergencyCommands": s.get(["serial", "emergencyCommands"]), + "helloCommand": s.get(["serial", "helloCommand"]), + "ignoreErrorsFromFirmware": s.getBoolean( + ["serial", "ignoreErrorsFromFirmware"] + ), + "disconnectOnErrors": s.getBoolean(["serial", "disconnectOnErrors"]), + "triggerOkForM29": s.getBoolean(["serial", "triggerOkForM29"]), + "logPositionOnPause": s.getBoolean(["serial", "logPositionOnPause"]), + "logPositionOnCancel": s.getBoolean(["serial", "logPositionOnCancel"]), + "abortHeatupOnCancel": s.getBoolean(["serial", "abortHeatupOnCancel"]), + "supportResendsWithoutOk": s.get(["serial", "supportResendsWithoutOk"]), + "waitForStart": s.getBoolean(["serial", "waitForStartOnConnect"]), + "alwaysSendChecksum": s.getBoolean(["serial", "alwaysSendChecksum"]), + "neverSendChecksum": s.getBoolean(["serial", "neverSendChecksum"]), + "sdRelativePath": s.getBoolean(["serial", "sdRelativePath"]), + "sdAlwaysAvailable": s.getBoolean(["serial", "sdAlwaysAvailable"]), + "swallowOkAfterResend": s.getBoolean(["serial", "swallowOkAfterResend"]), + "repetierTargetTemp": s.getBoolean(["serial", "repetierTargetTemp"]), + "externalHeatupDetection": s.getBoolean( + ["serial", "externalHeatupDetection"] + ), + "ignoreIdenticalResends": s.getBoolean(["serial", "ignoreIdenticalResends"]), + "firmwareDetection": s.getBoolean(["serial", "firmwareDetection"]), + "blockWhileDwelling": s.getBoolean(["serial", "blockWhileDwelling"]), + "useParityWorkaround": s.get(["serial", "useParityWorkaround"]), + "sanityCheckTools": s.getBoolean(["serial", "sanityCheckTools"]), + "sendM112OnError": s.getBoolean(["serial", "sendM112OnError"]), + "disableSdPrintingDetection": s.getBoolean( + ["serial", "disableSdPrintingDetection"] + ), + "ackMax": s.getInt(["serial", "ackMax"]), + "maxTimeoutsIdle": s.getInt(["serial", "maxCommunicationTimeouts", "idle"]), + "maxTimeoutsPrinting": s.getInt( + ["serial", "maxCommunicationTimeouts", "printing"] + ), + "maxTimeoutsLong": s.getInt(["serial", "maxCommunicationTimeouts", "long"]), + "capAutoreportTemp": s.getBoolean( + ["serial", "capabilities", "autoreport_temp"] + ), + "capAutoreportSdStatus": s.getBoolean( + ["serial", "capabilities", "autoreport_sdstatus"] + ), + "capBusyProtocol": s.getBoolean(["serial", "capabilities", "busy_protocol"]), + "capEmergencyParser": s.getBoolean( + ["serial", "capabilities", "emergency_parser"] + ), + }, + "folder": { + "uploads": s.getBaseFolder("uploads"), + "timelapse": s.getBaseFolder("timelapse"), + "timelapseTmp": s.getBaseFolder("timelapse_tmp"), + "logs": s.getBaseFolder("logs"), + "watched": s.getBaseFolder("watched"), + }, + "temperature": { + "profiles": s.get(["temperature", "profiles"]), + "cutoff": s.getInt(["temperature", "cutoff"]), + "sendAutomatically": s.getBoolean(["temperature", "sendAutomatically"]), + "sendAutomaticallyAfter": s.getInt( + ["temperature", "sendAutomaticallyAfter"], min=0, max=30 + ), + }, + "system": { + "actions": s.get(["system", "actions"]), + "events": s.get(["system", "events"]), + }, + "terminalFilters": s.get(["terminalFilters"]), + "scripts": { + "gcode": { + "afterPrinterConnected": None, + "beforePrinterDisconnected": None, + "beforePrintStarted": None, + "afterPrintCancelled": None, + "afterPrintDone": None, + "beforePrintPaused": None, + "afterPrintResumed": None, + "beforeToolChange": None, + "afterToolChange": None, + "snippets": {}, + } + }, + "server": { + "commands": { + "systemShutdownCommand": s.get( + ["server", "commands", "systemShutdownCommand"] + ), + "systemRestartCommand": s.get( + ["server", "commands", "systemRestartCommand"] + ), + "serverRestartCommand": s.get( + ["server", "commands", "serverRestartCommand"] + ), + }, + "diskspace": { + "warning": s.getInt(["server", "diskspace", "warning"]), + "critical": s.getInt(["server", "diskspace", "critical"]), + }, + "onlineCheck": { + "enabled": s.getBoolean(["server", "onlineCheck", "enabled"]), + "interval": int(s.getInt(["server", "onlineCheck", "interval"]) / 60), + "host": s.get(["server", "onlineCheck", "host"]), + "port": s.getInt(["server", "onlineCheck", "port"]), + "name": s.get(["server", "onlineCheck", "name"]), + }, + "pluginBlacklist": { + "enabled": s.getBoolean(["server", "pluginBlacklist", "enabled"]), + "url": s.get(["server", "pluginBlacklist", "url"]), + "ttl": int(s.getInt(["server", "pluginBlacklist", "ttl"]) / 60), + }, + "allowFraming": s.getBoolean(["server", "allowFraming"]), + }, + "devel": {"pluginTimings": s.getBoolean(["devel", "pluginTimings"])}, + } - gcode_scripts = s.listScripts("gcode") - if gcode_scripts: - data["scripts"] = {"gcode": {}} - for name in gcode_scripts: - data["scripts"]["gcode"][name] = s.loadScript("gcode", name, source=True) + gcode_scripts = s.listScripts("gcode") + if gcode_scripts: + data["scripts"] = {"gcode": {}} + for name in gcode_scripts: + data["scripts"]["gcode"][name] = s.loadScript("gcode", name, source=True) - plugin_settings = _get_plugin_settings() - if len(plugin_settings): - data["plugins"] = plugin_settings + plugin_settings = _get_plugin_settings() + if len(plugin_settings): + data["plugins"] = plugin_settings - return jsonify(data) + return jsonify(data) def _get_plugin_settings(): - logger = logging.getLogger(__name__) + logger = logging.getLogger(__name__) - data = {} + data = {} - def process_plugin_result(name, result): - if result: - try: - jsonify(test=result) - except Exception: - logger.exception("Error while jsonifying settings from plugin {}, please contact the plugin author about this".format(name)) - raise - else: - if "__enabled" in result: - del result["__enabled"] - data[name] = result + def process_plugin_result(name, result): + if result: + try: + jsonify(test=result) + except Exception: + logger.exception( + "Error while jsonifying settings from plugin {}, please contact the plugin author about this".format( + name + ) + ) + raise + else: + if "__enabled" in result: + del result["__enabled"] + data[name] = result - for plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin): - try: - result = plugin.on_settings_load() - process_plugin_result(plugin._identifier, result) - except Exception: - logger.exception("Could not load settings for plugin {name} ({version})".format(version=plugin._plugin_version, - name=plugin._plugin_name), - extra={"plugin": plugin._identifier}) + for plugin in octoprint.plugin.plugin_manager().get_implementations( + octoprint.plugin.SettingsPlugin + ): + try: + result = plugin.on_settings_load() + process_plugin_result(plugin._identifier, result) + except Exception: + logger.exception( + "Could not load settings for plugin {name} ({version})".format( + version=plugin._plugin_version, name=plugin._plugin_name + ), + extra={"plugin": plugin._identifier}, + ) - return data + return data @api.route("/settings", methods=["POST"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def setSettings(): - if not "application/json" in request.headers["Content-Type"]: - return make_response("Expected content-type JSON", 400) + if not "application/json" in request.headers["Content-Type"]: + return make_response("Expected content-type JSON", 400) - try: - data = request.get_json() - except BadRequest: - return make_response("Malformed JSON body in request", 400) + try: + data = request.get_json() + except BadRequest: + return make_response("Malformed JSON body in request", 400) - if data is None: - return make_response("Malformed JSON body in request", 400) + if data is None: + return make_response("Malformed JSON body in request", 400) - if not isinstance(data, dict): - return make_response("Malformed request, need settings dictionary, " - "got a {} instead: {!r}".format(type(data).__name__, data), 400) + if not isinstance(data, dict): + return make_response( + "Malformed request, need settings dictionary, " + "got a {} instead: {!r}".format(type(data).__name__, data), + 400, + ) - response = _saveSettings(data) - if response: - return response - return getSettings() + response = _saveSettings(data) + if response: + return response + return getSettings() @api.route("/settings/apikey", methods=["POST"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def generateApiKey(): - apikey = settings().generateApiKey() - return jsonify(apikey=apikey) + apikey = settings().generateApiKey() + return jsonify(apikey=apikey) @api.route("/settings/apikey", methods=["DELETE"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def deleteApiKey(): - settings().deleteApiKey() - return NO_CONTENT + settings().deleteApiKey() + return NO_CONTENT + @api.route("/settings/templates", methods=["GET"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def fetchTemplateData(): - from octoprint.server.views import fetch_template_data + from octoprint.server.views import fetch_template_data - refresh = request.values.get("refresh", "false") in valid_boolean_trues - templates, _, _ = fetch_template_data(refresh=refresh) + refresh = request.values.get("refresh", "false") in valid_boolean_trues + templates, _, _ = fetch_template_data(refresh=refresh) - result = {} - for tt in templates: - result[tt] = [] - for key in templates[tt]["order"]: - entry = templates[tt]["entries"].get(key) - if not entry: - continue + result = {} + for tt in templates: + result[tt] = [] + for key in templates[tt]["order"]: + entry = templates[tt]["entries"].get(key) + if not entry: + continue - if isinstance(entry, dict): - name = key - else: - name, entry = entry + if isinstance(entry, dict): + name = key + else: + name, entry = entry - data = {"id": key, "name": name} + data = {"id": key, "name": name} - if entry and "_plugin" in entry: - plugin = pluginManager.get_plugin_info(entry["_plugin"], require_enabled=False) - data["plugin_id"] = plugin.key - data["plugin_name"] = plugin.name + if entry and "_plugin" in entry: + plugin = pluginManager.get_plugin_info( + entry["_plugin"], require_enabled=False + ) + data["plugin_id"] = plugin.key + data["plugin_name"] = plugin.name - result[tt].append(data) + result[tt].append(data) + + return jsonify(order=result) - return jsonify(order=result) def _saveSettings(data): - logger = logging.getLogger(__name__) + logger = logging.getLogger(__name__) - s = settings() + s = settings() - # NOTE: Remember to adjust the docs of the data model on the Settings API if anything - # is changed, added or removed here + # NOTE: Remember to adjust the docs of the data model on the Settings API if anything + # is changed, added or removed here - if "folder" in data: - try: - if "uploads" in data["folder"]: s.setBaseFolder("uploads", data["folder"]["uploads"]) - if "timelapse" in data["folder"]: s.setBaseFolder("timelapse", data["folder"]["timelapse"]) - if "timelapseTmp" in data["folder"]: s.setBaseFolder("timelapse_tmp", data["folder"]["timelapseTmp"]) - if "logs" in data["folder"]: s.setBaseFolder("logs", data["folder"]["logs"]) - if "watched" in data["folder"]: s.setBaseFolder("watched", data["folder"]["watched"]) - except IOError: - return make_response("One of the configured folders is invalid", 400) + if "folder" in data: + try: + if "uploads" in data["folder"]: + s.setBaseFolder("uploads", data["folder"]["uploads"]) + if "timelapse" in data["folder"]: + s.setBaseFolder("timelapse", data["folder"]["timelapse"]) + if "timelapseTmp" in data["folder"]: + s.setBaseFolder("timelapse_tmp", data["folder"]["timelapseTmp"]) + if "logs" in data["folder"]: + s.setBaseFolder("logs", data["folder"]["logs"]) + if "watched" in data["folder"]: + s.setBaseFolder("watched", data["folder"]["watched"]) + except IOError: + return make_response("One of the configured folders is invalid", 400) - if "api" in data: - if "allowCrossOrigin" in data["api"]: s.setBoolean(["api", "allowCrossOrigin"], data["api"]["allowCrossOrigin"]) + if "api" in data: + if "allowCrossOrigin" in data["api"]: + s.setBoolean(["api", "allowCrossOrigin"], data["api"]["allowCrossOrigin"]) - if "appearance" in data: - if "name" in data["appearance"]: s.set(["appearance", "name"], data["appearance"]["name"]) - if "color" in data["appearance"]: s.set(["appearance", "color"], data["appearance"]["color"]) - if "colorTransparent" in data["appearance"]: s.setBoolean(["appearance", "colorTransparent"], data["appearance"]["colorTransparent"]) - if "colorIcon" in data["appearance"]: s.setBoolean(["appearance", "colorIcon"], data["appearance"]["colorIcon"]) - if "defaultLanguage" in data["appearance"]: s.set(["appearance", "defaultLanguage"], data["appearance"]["defaultLanguage"]) - if "showFahrenheitAlso" in data["appearance"]: s.setBoolean(["appearance", "showFahrenheitAlso"], data["appearance"]["showFahrenheitAlso"]) - if "fuzzyTimes" in data["appearance"]: s.setBoolean(["appearance", "fuzzyTimes"], data["appearance"]["fuzzyTimes"]) - if "closeModalsWithClick" in data["appearance"]: s.setBoolean(["appearance", "closeModalsWithClick"], data["appearance"]["closeModalsWithClick"]) + if "appearance" in data: + if "name" in data["appearance"]: + s.set(["appearance", "name"], data["appearance"]["name"]) + if "color" in data["appearance"]: + s.set(["appearance", "color"], data["appearance"]["color"]) + if "colorTransparent" in data["appearance"]: + s.setBoolean( + ["appearance", "colorTransparent"], data["appearance"]["colorTransparent"] + ) + if "colorIcon" in data["appearance"]: + s.setBoolean(["appearance", "colorIcon"], data["appearance"]["colorIcon"]) + if "defaultLanguage" in data["appearance"]: + s.set( + ["appearance", "defaultLanguage"], data["appearance"]["defaultLanguage"] + ) + if "showFahrenheitAlso" in data["appearance"]: + s.setBoolean( + ["appearance", "showFahrenheitAlso"], + data["appearance"]["showFahrenheitAlso"], + ) + if "fuzzyTimes" in data["appearance"]: + s.setBoolean(["appearance", "fuzzyTimes"], data["appearance"]["fuzzyTimes"]) + if "closeModalsWithClick" in data["appearance"]: + s.setBoolean( + ["appearance", "closeModalsWithClick"], + data["appearance"]["closeModalsWithClick"], + ) - if "printer" in data: - if "defaultExtrusionLength" in data["printer"]: s.setInt(["printerParameters", "defaultExtrusionLength"], data["printer"]["defaultExtrusionLength"]) + if "printer" in data: + if "defaultExtrusionLength" in data["printer"]: + s.setInt( + ["printerParameters", "defaultExtrusionLength"], + data["printer"]["defaultExtrusionLength"], + ) - if "webcam" in data: - if "webcamEnabled" in data["webcam"]: s.setBoolean(["webcam", "webcamEnabled"], data["webcam"]["webcamEnabled"]) - if "timelapseEnabled" in data["webcam"]: s.setBoolean(["webcam", "timelapseEnabled"], data["webcam"]["timelapseEnabled"]) - if "streamUrl" in data["webcam"]: s.set(["webcam", "stream"], data["webcam"]["streamUrl"]) - if "streamRatio" in data["webcam"] and data["webcam"]["streamRatio"] in ("16:9", "4:3"): s.set(["webcam", "streamRatio"], data["webcam"]["streamRatio"]) - if "streamTimeout" in data["webcam"]: s.setInt(["webcam", "streamTimeout"], data["webcam"]["streamTimeout"]) - if "snapshotUrl" in data["webcam"]: s.set(["webcam", "snapshot"], data["webcam"]["snapshotUrl"]) - if "snapshotTimeout" in data["webcam"]: s.setInt(["webcam", "snapshotTimeout"], data["webcam"]["snapshotTimeout"]) - if "snapshotSslValidation" in data["webcam"]: s.setBoolean(["webcam", "snapshotSslValidation"], data["webcam"]["snapshotSslValidation"]) - if "ffmpegPath" in data["webcam"]: s.set(["webcam", "ffmpeg"], data["webcam"]["ffmpegPath"]) - if "bitrate" in data["webcam"]: s.set(["webcam", "bitrate"], data["webcam"]["bitrate"]) - if "ffmpegThreads" in data["webcam"]: s.setInt(["webcam", "ffmpegThreads"], data["webcam"]["ffmpegThreads"]) - if "ffmpegVideoCodec" in data["webcam"] and data["webcam"]["ffmpegVideoCodec"] in ("mpeg2video", "libx264"): s.set(["webcam", "ffmpegVideoCodec"], data["webcam"]["ffmpegVideoCodec"]) - if "watermark" in data["webcam"]: s.setBoolean(["webcam", "watermark"], data["webcam"]["watermark"]) - if "flipH" in data["webcam"]: s.setBoolean(["webcam", "flipH"], data["webcam"]["flipH"]) - if "flipV" in data["webcam"]: s.setBoolean(["webcam", "flipV"], data["webcam"]["flipV"]) - if "rotate90" in data["webcam"]: s.setBoolean(["webcam", "rotate90"], data["webcam"]["rotate90"]) + if "webcam" in data: + if "webcamEnabled" in data["webcam"]: + s.setBoolean(["webcam", "webcamEnabled"], data["webcam"]["webcamEnabled"]) + if "timelapseEnabled" in data["webcam"]: + s.setBoolean( + ["webcam", "timelapseEnabled"], data["webcam"]["timelapseEnabled"] + ) + if "streamUrl" in data["webcam"]: + s.set(["webcam", "stream"], data["webcam"]["streamUrl"]) + if "streamRatio" in data["webcam"] and data["webcam"]["streamRatio"] in ( + "16:9", + "4:3", + ): + s.set(["webcam", "streamRatio"], data["webcam"]["streamRatio"]) + if "streamTimeout" in data["webcam"]: + s.setInt(["webcam", "streamTimeout"], data["webcam"]["streamTimeout"]) + if "snapshotUrl" in data["webcam"]: + s.set(["webcam", "snapshot"], data["webcam"]["snapshotUrl"]) + if "snapshotTimeout" in data["webcam"]: + s.setInt(["webcam", "snapshotTimeout"], data["webcam"]["snapshotTimeout"]) + if "snapshotSslValidation" in data["webcam"]: + s.setBoolean( + ["webcam", "snapshotSslValidation"], + data["webcam"]["snapshotSslValidation"], + ) + if "ffmpegPath" in data["webcam"]: + s.set(["webcam", "ffmpeg"], data["webcam"]["ffmpegPath"]) + if "bitrate" in data["webcam"]: + s.set(["webcam", "bitrate"], data["webcam"]["bitrate"]) + if "ffmpegThreads" in data["webcam"]: + s.setInt(["webcam", "ffmpegThreads"], data["webcam"]["ffmpegThreads"]) + if "ffmpegVideoCodec" in data["webcam"] and data["webcam"][ + "ffmpegVideoCodec" + ] in ("mpeg2video", "libx264"): + s.set(["webcam", "ffmpegVideoCodec"], data["webcam"]["ffmpegVideoCodec"]) + if "watermark" in data["webcam"]: + s.setBoolean(["webcam", "watermark"], data["webcam"]["watermark"]) + if "flipH" in data["webcam"]: + s.setBoolean(["webcam", "flipH"], data["webcam"]["flipH"]) + if "flipV" in data["webcam"]: + s.setBoolean(["webcam", "flipV"], data["webcam"]["flipV"]) + if "rotate90" in data["webcam"]: + s.setBoolean(["webcam", "rotate90"], data["webcam"]["rotate90"]) - if "feature" in data: - if "temperatureGraph" in data["feature"]: s.setBoolean(["feature", "temperatureGraph"], data["feature"]["temperatureGraph"]) - if "sdSupport" in data["feature"]: s.setBoolean(["feature", "sdSupport"], data["feature"]["sdSupport"]) - if "keyboardControl" in data["feature"]: s.setBoolean(["feature", "keyboardControl"], data["feature"]["keyboardControl"]) - if "pollWatched" in data["feature"]: s.setBoolean(["feature", "pollWatched"], data["feature"]["pollWatched"]) - if "modelSizeDetection" in data["feature"]: s.setBoolean(["feature", "modelSizeDetection"], data["feature"]["modelSizeDetection"]) - if "printStartConfirmation" in data["feature"]: s.setBoolean(["feature", "printStartConfirmation"], data["feature"]["printStartConfirmation"]) - if "printCancelConfirmation" in data["feature"]: s.setBoolean(["feature", "printCancelConfirmation"], data["feature"]["printCancelConfirmation"]) - if "g90InfluencesExtruder" in data["feature"]: s.setBoolean(["feature", "g90InfluencesExtruder"], data["feature"]["g90InfluencesExtruder"]) - if "autoUppercaseBlacklist" in data["feature"] and isinstance(data["feature"]["autoUppercaseBlacklist"], (list, tuple)): s.set(["feature", "autoUppercaseBlacklist"], data["feature"]["autoUppercaseBlacklist"]) + if "feature" in data: + if "temperatureGraph" in data["feature"]: + s.setBoolean( + ["feature", "temperatureGraph"], data["feature"]["temperatureGraph"] + ) + if "sdSupport" in data["feature"]: + s.setBoolean(["feature", "sdSupport"], data["feature"]["sdSupport"]) + if "keyboardControl" in data["feature"]: + s.setBoolean( + ["feature", "keyboardControl"], data["feature"]["keyboardControl"] + ) + if "pollWatched" in data["feature"]: + s.setBoolean(["feature", "pollWatched"], data["feature"]["pollWatched"]) + if "modelSizeDetection" in data["feature"]: + s.setBoolean( + ["feature", "modelSizeDetection"], data["feature"]["modelSizeDetection"] + ) + if "printStartConfirmation" in data["feature"]: + s.setBoolean( + ["feature", "printStartConfirmation"], + data["feature"]["printStartConfirmation"], + ) + if "printCancelConfirmation" in data["feature"]: + s.setBoolean( + ["feature", "printCancelConfirmation"], + data["feature"]["printCancelConfirmation"], + ) + if "g90InfluencesExtruder" in data["feature"]: + s.setBoolean( + ["feature", "g90InfluencesExtruder"], + data["feature"]["g90InfluencesExtruder"], + ) + if "autoUppercaseBlacklist" in data["feature"] and isinstance( + data["feature"]["autoUppercaseBlacklist"], (list, tuple) + ): + s.set( + ["feature", "autoUppercaseBlacklist"], + data["feature"]["autoUppercaseBlacklist"], + ) - if "gcodeAnalysis" in data: - if "runAt" in data["gcodeAnalysis"]: s.set(["gcodeAnalysis", "runAt"], data["gcodeAnalysis"]["runAt"]) + if "gcodeAnalysis" in data: + if "runAt" in data["gcodeAnalysis"]: + s.set(["gcodeAnalysis", "runAt"], data["gcodeAnalysis"]["runAt"]) - if "serial" in data: - if "autoconnect" in data["serial"]: s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"]) - if "port" in data["serial"]: s.set(["serial", "port"], data["serial"]["port"]) - if "baudrate" in data["serial"]: s.setInt(["serial", "baudrate"], data["serial"]["baudrate"]) - if "exclusive" in data["serial"]: s.setBoolean(["serial", "exclusive"], data["serial"]["exclusive"]) - if "timeoutConnection" in data["serial"]: s.setFloat(["serial", "timeout", "connection"], data["serial"]["timeoutConnection"], min=1.0) - if "timeoutDetectionFirst" in data["serial"]: s.setFloat(["serial", "timeout", "detectionFirst"], data["serial"]["timeoutDetectionFirst"], min=1.0) - if "timeoutDetectionConsecutive" in data["serial"]: s.setFloat(["serial", "timeout", "detectionConsecutive"], data["serial"]["timeoutDetectionConsecutive"], min=1.0) - if "timeoutCommunication" in data["serial"]: s.setFloat(["serial", "timeout", "communication"], data["serial"]["timeoutCommunication"], min=1.0) - if "timeoutCommunicationBusy" in data["serial"]: s.setFloat(["serial", "timeout", "communicationBusy"], data["serial"]["timeoutCommunicationBusy"], min=1.0) - if "timeoutTemperature" in data["serial"]: s.setFloat(["serial", "timeout", "temperature"], data["serial"]["timeoutTemperature"], min=1.0) - if "timeoutTemperatureTargetSet" in data["serial"]: s.setFloat(["serial", "timeout", "temperatureTargetSet"], data["serial"]["timeoutTemperatureTargetSet"], min=1.0) - if "timeoutTemperatureAutoreport" in data["serial"]: s.setFloat(["serial", "timeout", "temperatureAutoreport"], data["serial"]["timeoutTemperatureAutoreport"], min=0.0) - if "timeoutSdStatus" in data["serial"]: s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"], min=1.0) - if "timeoutSdStatusAutoreport" in data["serial"]: s.setFloat(["serial", "timeout", "sdStatusAutoreport"], data["serial"]["timeoutSdStatusAutoreport"], min=0.0) - if "timeoutBaudrateDetectionPause" in data["serial"]: s.setFloat(["serial", "timeout", "baudrateDetectionPause"], data["serial"]["timeoutBaudrateDetectionPause"], min=0.0) - if "timeoutPositionLogWait" in data["serial"]: s.setFloat(["serial", "timeout", "positionLogWait"], data["serial"]["timeoutPositionLogWait"], min=1.0) - if "additionalPorts" in data["serial"] and isinstance(data["serial"]["additionalPorts"], (list, tuple)): s.set(["serial", "additionalPorts"], data["serial"]["additionalPorts"]) - if "additionalBaudrates" in data["serial"] and isinstance(data["serial"]["additionalBaudrates"], (list, tuple)): s.set(["serial", "additionalBaudrates"], data["serial"]["additionalBaudrates"]) - if "blacklistedPorts" in data["serial"] and isinstance(data["serial"]["blacklistedPorts"], (list, tuple)): s.set(["serial", "blacklistedPorts"], data["serial"]["blacklistedPorts"]) - if "blacklistedBaudrates" in data["serial"] and isinstance(data["serial"]["blacklistedBaudrates"], (list, tuple)): s.set(["serial", "blacklistedBaudrates"], data["serial"]["blacklistedBaudrates"]) - if "longRunningCommands" in data["serial"] and isinstance(data["serial"]["longRunningCommands"], (list, tuple)): s.set(["serial", "longRunningCommands"], data["serial"]["longRunningCommands"]) - if "checksumRequiringCommands" in data["serial"] and isinstance(data["serial"]["checksumRequiringCommands"], (list, tuple)): s.set(["serial", "checksumRequiringCommands"], data["serial"]["checksumRequiringCommands"]) - if "blockedCommands" in data["serial"] and isinstance(data["serial"]["blockedCommands"], (list, tuple)): s.set(["serial", "blockedCommands"], data["serial"]["blockedCommands"]) - if "pausingCommands" in data["serial"] and isinstance(data["serial"]["pausingCommands"], (list, tuple)): s.set(["serial", "pausingCommands"], data["serial"]["pausingCommands"]) - if "emergencyCommands" in data["serial"] and isinstance(data["serial"]["emergencyCommands"], (list, tuple)): s.set(["serial", "emergencyCommands"], data["serial"]["emergencyCommands"]) - if "helloCommand" in data["serial"]: s.set(["serial", "helloCommand"], data["serial"]["helloCommand"]) - if "ignoreErrorsFromFirmware" in data["serial"]: s.setBoolean(["serial", "ignoreErrorsFromFirmware"], data["serial"]["ignoreErrorsFromFirmware"]) - if "disconnectOnErrors" in data["serial"]: s.setBoolean(["serial", "disconnectOnErrors"], data["serial"]["disconnectOnErrors"]) - if "triggerOkForM29" in data["serial"]: s.setBoolean(["serial", "triggerOkForM29"], data["serial"]["triggerOkForM29"]) - if "supportResendsWithoutOk" in data["serial"]: - value = data["serial"]["supportResendsWithoutOk"] - if value in ("always", "detect", "never"): - s.set(["serial", "supportResendsWithoutOk"], value) - if "waitForStart" in data["serial"]: s.setBoolean(["serial", "waitForStartOnConnect"], data["serial"]["waitForStart"]) - if "alwaysSendChecksum" in data["serial"]: s.setBoolean(["serial", "alwaysSendChecksum"], data["serial"]["alwaysSendChecksum"]) - if "neverSendChecksum" in data["serial"]: s.setBoolean(["serial", "neverSendChecksum"], data["serial"]["neverSendChecksum"]) - if "sdRelativePath" in data["serial"]: s.setBoolean(["serial", "sdRelativePath"], data["serial"]["sdRelativePath"]) - if "sdAlwaysAvailable" in data["serial"]: s.setBoolean(["serial", "sdAlwaysAvailable"], data["serial"]["sdAlwaysAvailable"]) - if "swallowOkAfterResend" in data["serial"]: s.setBoolean(["serial", "swallowOkAfterResend"], data["serial"]["swallowOkAfterResend"]) - if "repetierTargetTemp" in data["serial"]: s.setBoolean(["serial", "repetierTargetTemp"], data["serial"]["repetierTargetTemp"]) - if "externalHeatupDetection" in data["serial"]: s.setBoolean(["serial", "externalHeatupDetection"], data["serial"]["externalHeatupDetection"]) - if "ignoreIdenticalResends" in data["serial"]: s.setBoolean(["serial", "ignoreIdenticalResends"], data["serial"]["ignoreIdenticalResends"]) - if "firmwareDetection" in data["serial"]: s.setBoolean(["serial", "firmwareDetection"], data["serial"]["firmwareDetection"]) - if "blockWhileDwelling" in data["serial"]: s.setBoolean(["serial", "blockWhileDwelling"], data["serial"]["blockWhileDwelling"]) - if "useParityWorkaround" in data["serial"]: - value = data["serial"]["useParityWorkaround"] - if value in ("always", "detect", "never"): - s.set(["serial", "useParityWorkaround"], value) - if "sanityCheckTools" in data["serial"]: s.setBoolean(["serial", "sanityCheckTools"], data["serial"]["sanityCheckTools"]) - if "sendM112OnError" in data["serial"]: s.setBoolean(["serial", "sendM112OnError"], data["serial"]["sendM112OnError"]) - if "disableSdPrintingDetection" in data["serial"]: s.setBoolean(["serial", "disableSdPrintingDetection"], data["serial"]["disableSdPrintingDetection"]) - if "ackMax" in data["serial"]: s.setInt(["serial", "ackMax"], data["serial"]["ackMax"]) - if "logPositionOnPause" in data["serial"]: s.setBoolean(["serial", "logPositionOnPause"], data["serial"]["logPositionOnPause"]) - if "logPositionOnCancel" in data["serial"]: s.setBoolean(["serial", "logPositionOnCancel"], data["serial"]["logPositionOnCancel"]) - if "abortHeatupOnCancel" in data["serial"]: s.setBoolean(["serial", "abortHeatupOnCancel"], data["serial"]["abortHeatupOnCancel"]) - if "maxTimeoutsIdle" in data["serial"]: s.setInt(["serial", "maxCommunicationTimeouts", "idle"], data["serial"]["maxTimeoutsIdle"]) - if "maxTimeoutsPrinting" in data["serial"]: s.setInt(["serial", "maxCommunicationTimeouts", "printing"], data["serial"]["maxTimeoutsPrinting"]) - if "maxTimeoutsLong" in data["serial"]: s.setInt(["serial", "maxCommunicationTimeouts", "long"], data["serial"]["maxTimeoutsLong"]) - if "capAutoreportTemp" in data["serial"]: s.setBoolean(["serial", "capabilities", "autoreport_temp"], data["serial"]["capAutoreportTemp"]) - if "capAutoreportSdStatus" in data["serial"]: s.setBoolean(["serial", "capabilities", "autoreport_sdstatus"], data["serial"]["capAutoreportSdStatus"]) - if "capBusyProtocol" in data["serial"]: s.setBoolean(["serial", "capabilities", "busy_protocol"], data["serial"]["capBusyProtocol"]) - if "capEmergencyParser" in data["serial"]: s.setBoolean(["serial", "capabilities", "emergency_parser"], data["serial"]["capEmergencyParser"]) + if "serial" in data: + if "autoconnect" in data["serial"]: + s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"]) + if "port" in data["serial"]: + s.set(["serial", "port"], data["serial"]["port"]) + if "baudrate" in data["serial"]: + s.setInt(["serial", "baudrate"], data["serial"]["baudrate"]) + if "exclusive" in data["serial"]: + s.setBoolean(["serial", "exclusive"], data["serial"]["exclusive"]) + if "timeoutConnection" in data["serial"]: + s.setFloat( + ["serial", "timeout", "connection"], + data["serial"]["timeoutConnection"], + min=1.0, + ) + if "timeoutDetectionFirst" in data["serial"]: + s.setFloat( + ["serial", "timeout", "detectionFirst"], + data["serial"]["timeoutDetectionFirst"], + min=1.0, + ) + if "timeoutDetectionConsecutive" in data["serial"]: + s.setFloat( + ["serial", "timeout", "detectionConsecutive"], + data["serial"]["timeoutDetectionConsecutive"], + min=1.0, + ) + if "timeoutCommunication" in data["serial"]: + s.setFloat( + ["serial", "timeout", "communication"], + data["serial"]["timeoutCommunication"], + min=1.0, + ) + if "timeoutCommunicationBusy" in data["serial"]: + s.setFloat( + ["serial", "timeout", "communicationBusy"], + data["serial"]["timeoutCommunicationBusy"], + min=1.0, + ) + if "timeoutTemperature" in data["serial"]: + s.setFloat( + ["serial", "timeout", "temperature"], + data["serial"]["timeoutTemperature"], + min=1.0, + ) + if "timeoutTemperatureTargetSet" in data["serial"]: + s.setFloat( + ["serial", "timeout", "temperatureTargetSet"], + data["serial"]["timeoutTemperatureTargetSet"], + min=1.0, + ) + if "timeoutTemperatureAutoreport" in data["serial"]: + s.setFloat( + ["serial", "timeout", "temperatureAutoreport"], + data["serial"]["timeoutTemperatureAutoreport"], + min=0.0, + ) + if "timeoutSdStatus" in data["serial"]: + s.setFloat( + ["serial", "timeout", "sdStatus"], + data["serial"]["timeoutSdStatus"], + min=1.0, + ) + if "timeoutSdStatusAutoreport" in data["serial"]: + s.setFloat( + ["serial", "timeout", "sdStatusAutoreport"], + data["serial"]["timeoutSdStatusAutoreport"], + min=0.0, + ) + if "timeoutBaudrateDetectionPause" in data["serial"]: + s.setFloat( + ["serial", "timeout", "baudrateDetectionPause"], + data["serial"]["timeoutBaudrateDetectionPause"], + min=0.0, + ) + if "timeoutPositionLogWait" in data["serial"]: + s.setFloat( + ["serial", "timeout", "positionLogWait"], + data["serial"]["timeoutPositionLogWait"], + min=1.0, + ) + if "additionalPorts" in data["serial"] and isinstance( + data["serial"]["additionalPorts"], (list, tuple) + ): + s.set(["serial", "additionalPorts"], data["serial"]["additionalPorts"]) + if "additionalBaudrates" in data["serial"] and isinstance( + data["serial"]["additionalBaudrates"], (list, tuple) + ): + s.set( + ["serial", "additionalBaudrates"], data["serial"]["additionalBaudrates"] + ) + if "blacklistedPorts" in data["serial"] and isinstance( + data["serial"]["blacklistedPorts"], (list, tuple) + ): + s.set(["serial", "blacklistedPorts"], data["serial"]["blacklistedPorts"]) + if "blacklistedBaudrates" in data["serial"] and isinstance( + data["serial"]["blacklistedBaudrates"], (list, tuple) + ): + s.set( + ["serial", "blacklistedBaudrates"], data["serial"]["blacklistedBaudrates"] + ) + if "longRunningCommands" in data["serial"] and isinstance( + data["serial"]["longRunningCommands"], (list, tuple) + ): + s.set( + ["serial", "longRunningCommands"], data["serial"]["longRunningCommands"] + ) + if "checksumRequiringCommands" in data["serial"] and isinstance( + data["serial"]["checksumRequiringCommands"], (list, tuple) + ): + s.set( + ["serial", "checksumRequiringCommands"], + data["serial"]["checksumRequiringCommands"], + ) + if "blockedCommands" in data["serial"] and isinstance( + data["serial"]["blockedCommands"], (list, tuple) + ): + s.set(["serial", "blockedCommands"], data["serial"]["blockedCommands"]) + if "pausingCommands" in data["serial"] and isinstance( + data["serial"]["pausingCommands"], (list, tuple) + ): + s.set(["serial", "pausingCommands"], data["serial"]["pausingCommands"]) + if "emergencyCommands" in data["serial"] and isinstance( + data["serial"]["emergencyCommands"], (list, tuple) + ): + s.set(["serial", "emergencyCommands"], data["serial"]["emergencyCommands"]) + if "helloCommand" in data["serial"]: + s.set(["serial", "helloCommand"], data["serial"]["helloCommand"]) + if "ignoreErrorsFromFirmware" in data["serial"]: + s.setBoolean( + ["serial", "ignoreErrorsFromFirmware"], + data["serial"]["ignoreErrorsFromFirmware"], + ) + if "disconnectOnErrors" in data["serial"]: + s.setBoolean( + ["serial", "disconnectOnErrors"], data["serial"]["disconnectOnErrors"] + ) + if "triggerOkForM29" in data["serial"]: + s.setBoolean(["serial", "triggerOkForM29"], data["serial"]["triggerOkForM29"]) + if "supportResendsWithoutOk" in data["serial"]: + value = data["serial"]["supportResendsWithoutOk"] + if value in ("always", "detect", "never"): + s.set(["serial", "supportResendsWithoutOk"], value) + if "waitForStart" in data["serial"]: + s.setBoolean( + ["serial", "waitForStartOnConnect"], data["serial"]["waitForStart"] + ) + if "alwaysSendChecksum" in data["serial"]: + s.setBoolean( + ["serial", "alwaysSendChecksum"], data["serial"]["alwaysSendChecksum"] + ) + if "neverSendChecksum" in data["serial"]: + s.setBoolean( + ["serial", "neverSendChecksum"], data["serial"]["neverSendChecksum"] + ) + if "sdRelativePath" in data["serial"]: + s.setBoolean(["serial", "sdRelativePath"], data["serial"]["sdRelativePath"]) + if "sdAlwaysAvailable" in data["serial"]: + s.setBoolean( + ["serial", "sdAlwaysAvailable"], data["serial"]["sdAlwaysAvailable"] + ) + if "swallowOkAfterResend" in data["serial"]: + s.setBoolean( + ["serial", "swallowOkAfterResend"], data["serial"]["swallowOkAfterResend"] + ) + if "repetierTargetTemp" in data["serial"]: + s.setBoolean( + ["serial", "repetierTargetTemp"], data["serial"]["repetierTargetTemp"] + ) + if "externalHeatupDetection" in data["serial"]: + s.setBoolean( + ["serial", "externalHeatupDetection"], + data["serial"]["externalHeatupDetection"], + ) + if "ignoreIdenticalResends" in data["serial"]: + s.setBoolean( + ["serial", "ignoreIdenticalResends"], + data["serial"]["ignoreIdenticalResends"], + ) + if "firmwareDetection" in data["serial"]: + s.setBoolean( + ["serial", "firmwareDetection"], data["serial"]["firmwareDetection"] + ) + if "blockWhileDwelling" in data["serial"]: + s.setBoolean( + ["serial", "blockWhileDwelling"], data["serial"]["blockWhileDwelling"] + ) + if "useParityWorkaround" in data["serial"]: + value = data["serial"]["useParityWorkaround"] + if value in ("always", "detect", "never"): + s.set(["serial", "useParityWorkaround"], value) + if "sanityCheckTools" in data["serial"]: + s.setBoolean( + ["serial", "sanityCheckTools"], data["serial"]["sanityCheckTools"] + ) + if "sendM112OnError" in data["serial"]: + s.setBoolean(["serial", "sendM112OnError"], data["serial"]["sendM112OnError"]) + if "disableSdPrintingDetection" in data["serial"]: + s.setBoolean( + ["serial", "disableSdPrintingDetection"], + data["serial"]["disableSdPrintingDetection"], + ) + if "ackMax" in data["serial"]: + s.setInt(["serial", "ackMax"], data["serial"]["ackMax"]) + if "logPositionOnPause" in data["serial"]: + s.setBoolean( + ["serial", "logPositionOnPause"], data["serial"]["logPositionOnPause"] + ) + if "logPositionOnCancel" in data["serial"]: + s.setBoolean( + ["serial", "logPositionOnCancel"], data["serial"]["logPositionOnCancel"] + ) + if "abortHeatupOnCancel" in data["serial"]: + s.setBoolean( + ["serial", "abortHeatupOnCancel"], data["serial"]["abortHeatupOnCancel"] + ) + if "maxTimeoutsIdle" in data["serial"]: + s.setInt( + ["serial", "maxCommunicationTimeouts", "idle"], + data["serial"]["maxTimeoutsIdle"], + ) + if "maxTimeoutsPrinting" in data["serial"]: + s.setInt( + ["serial", "maxCommunicationTimeouts", "printing"], + data["serial"]["maxTimeoutsPrinting"], + ) + if "maxTimeoutsLong" in data["serial"]: + s.setInt( + ["serial", "maxCommunicationTimeouts", "long"], + data["serial"]["maxTimeoutsLong"], + ) + if "capAutoreportTemp" in data["serial"]: + s.setBoolean( + ["serial", "capabilities", "autoreport_temp"], + data["serial"]["capAutoreportTemp"], + ) + if "capAutoreportSdStatus" in data["serial"]: + s.setBoolean( + ["serial", "capabilities", "autoreport_sdstatus"], + data["serial"]["capAutoreportSdStatus"], + ) + if "capBusyProtocol" in data["serial"]: + s.setBoolean( + ["serial", "capabilities", "busy_protocol"], + data["serial"]["capBusyProtocol"], + ) + if "capEmergencyParser" in data["serial"]: + s.setBoolean( + ["serial", "capabilities", "emergency_parser"], + data["serial"]["capEmergencyParser"], + ) - oldLog = s.getBoolean(["serial", "log"]) - if "log" in data["serial"]: s.setBoolean(["serial", "log"], data["serial"]["log"]) - if oldLog and not s.getBoolean(["serial", "log"]): - # disable debug logging to serial.log - logging.getLogger("SERIAL").debug("Disabling serial logging") - logging.getLogger("SERIAL").setLevel(logging.CRITICAL) - elif not oldLog and s.getBoolean(["serial", "log"]): - # enable debug logging to serial.log - logging.getLogger("SERIAL").setLevel(logging.DEBUG) - logging.getLogger("SERIAL").debug("Enabling serial logging") + oldLog = s.getBoolean(["serial", "log"]) + if "log" in data["serial"]: + s.setBoolean(["serial", "log"], data["serial"]["log"]) + if oldLog and not s.getBoolean(["serial", "log"]): + # disable debug logging to serial.log + logging.getLogger("SERIAL").debug("Disabling serial logging") + logging.getLogger("SERIAL").setLevel(logging.CRITICAL) + elif not oldLog and s.getBoolean(["serial", "log"]): + # enable debug logging to serial.log + logging.getLogger("SERIAL").setLevel(logging.DEBUG) + logging.getLogger("SERIAL").debug("Enabling serial logging") - if "temperature" in data: - if "profiles" in data["temperature"]: - result = [] - for profile in data["temperature"]["profiles"]: - try: - profile["bed"] = int(profile["bed"]) - profile["extruder"] = int(profile["extruder"]) - except ValueError: - pass - result.append(profile) - s.set(["temperature", "profiles"], result) - if "cutoff" in data["temperature"]: - try: - cutoff = int(data["temperature"]["cutoff"]) - if cutoff > 1: - s.setInt(["temperature", "cutoff"], cutoff) - except ValueError: - pass - if "sendAutomatically" in data["temperature"]: s.setBoolean(["temperature", "sendAutomatically"], data["temperature"]["sendAutomatically"]) - if "sendAutomaticallyAfter" in data["temperature"]: s.setInt(["temperature", "sendAutomaticallyAfter"], data["temperature"]["sendAutomaticallyAfter"], min=0, max=30) + if "temperature" in data: + if "profiles" in data["temperature"]: + result = [] + for profile in data["temperature"]["profiles"]: + try: + profile["bed"] = int(profile["bed"]) + profile["extruder"] = int(profile["extruder"]) + except ValueError: + pass + result.append(profile) + s.set(["temperature", "profiles"], result) + if "cutoff" in data["temperature"]: + try: + cutoff = int(data["temperature"]["cutoff"]) + if cutoff > 1: + s.setInt(["temperature", "cutoff"], cutoff) + except ValueError: + pass + if "sendAutomatically" in data["temperature"]: + s.setBoolean( + ["temperature", "sendAutomatically"], + data["temperature"]["sendAutomatically"], + ) + if "sendAutomaticallyAfter" in data["temperature"]: + s.setInt( + ["temperature", "sendAutomaticallyAfter"], + data["temperature"]["sendAutomaticallyAfter"], + min=0, + max=30, + ) - if "terminalFilters" in data: - s.set(["terminalFilters"], data["terminalFilters"]) + if "terminalFilters" in data: + s.set(["terminalFilters"], data["terminalFilters"]) - if "system" in data: - if "actions" in data["system"]: s.set(["system", "actions"], data["system"]["actions"]) - if "events" in data["system"]: s.set(["system", "events"], data["system"]["events"]) + if "system" in data: + if "actions" in data["system"]: + s.set(["system", "actions"], data["system"]["actions"]) + if "events" in data["system"]: + s.set(["system", "events"], data["system"]["events"]) - if "scripts" in data: - if "gcode" in data["scripts"] and isinstance(data["scripts"]["gcode"], dict): - for name, script in data["scripts"]["gcode"].items(): - if name == "snippets": - continue - s.saveScript("gcode", name, script.replace("\r\n", "\n").replace("\r", "\n")) + if "scripts" in data: + if "gcode" in data["scripts"] and isinstance(data["scripts"]["gcode"], dict): + for name, script in data["scripts"]["gcode"].items(): + if name == "snippets": + continue + s.saveScript( + "gcode", name, script.replace("\r\n", "\n").replace("\r", "\n") + ) - if "server" in data: - if "commands" in data["server"]: - if "systemShutdownCommand" in data["server"]["commands"]: s.set(["server", "commands", "systemShutdownCommand"], data["server"]["commands"]["systemShutdownCommand"]) - if "systemRestartCommand" in data["server"]["commands"]: s.set(["server", "commands", "systemRestartCommand"], data["server"]["commands"]["systemRestartCommand"]) - if "serverRestartCommand" in data["server"]["commands"]: s.set(["server", "commands", "serverRestartCommand"], data["server"]["commands"]["serverRestartCommand"]) - if "diskspace" in data["server"]: - if "warning" in data["server"]["diskspace"]: s.setInt(["server", "diskspace", "warning"], data["server"]["diskspace"]["warning"]) - if "critical" in data["server"]["diskspace"]: s.setInt(["server", "diskspace", "critical"], data["server"]["diskspace"]["critical"]) - if "onlineCheck" in data["server"]: - if "enabled" in data["server"]["onlineCheck"]: s.setBoolean(["server", "onlineCheck", "enabled"], data["server"]["onlineCheck"]["enabled"]) - if "interval" in data["server"]["onlineCheck"]: - try: - interval = int(data["server"]["onlineCheck"]["interval"]) - s.setInt(["server", "onlineCheck", "interval"], interval*60) - except ValueError: - pass - if "host" in data["server"]["onlineCheck"]: s.set(["server", "onlineCheck", "host"], data["server"]["onlineCheck"]["host"]) - if "port" in data["server"]["onlineCheck"]: s.setInt(["server", "onlineCheck", "port"], data["server"]["onlineCheck"]["port"]) - if "name" in data["server"]["onlineCheck"]: s.set(["server", "onlineCheck", "name"], data["server"]["onlineCheck"]["name"]) - if "pluginBlacklist" in data["server"]: - if "enabled" in data["server"]["pluginBlacklist"]: s.setBoolean(["server", "pluginBlacklist", "enabled"], data["server"]["pluginBlacklist"]["enabled"]) - if "url" in data["server"]["pluginBlacklist"]: s.set(["server", "pluginBlacklist", "url"], data["server"]["pluginBlacklist"]["url"]) - if "ttl" in data["server"]["pluginBlacklist"]: - try: - ttl = int(data["server"]["pluginBlacklist"]["ttl"]) - s.setInt(["server", "pluginBlacklist", "ttl"], ttl * 60) - except ValueError: - pass - if "allowFraming" in data["server"]: - s.setBoolean(["server", "allowFraming"], data["server"]["allowFraming"]) + if "server" in data: + if "commands" in data["server"]: + if "systemShutdownCommand" in data["server"]["commands"]: + s.set( + ["server", "commands", "systemShutdownCommand"], + data["server"]["commands"]["systemShutdownCommand"], + ) + if "systemRestartCommand" in data["server"]["commands"]: + s.set( + ["server", "commands", "systemRestartCommand"], + data["server"]["commands"]["systemRestartCommand"], + ) + if "serverRestartCommand" in data["server"]["commands"]: + s.set( + ["server", "commands", "serverRestartCommand"], + data["server"]["commands"]["serverRestartCommand"], + ) + if "diskspace" in data["server"]: + if "warning" in data["server"]["diskspace"]: + s.setInt( + ["server", "diskspace", "warning"], + data["server"]["diskspace"]["warning"], + ) + if "critical" in data["server"]["diskspace"]: + s.setInt( + ["server", "diskspace", "critical"], + data["server"]["diskspace"]["critical"], + ) + if "onlineCheck" in data["server"]: + if "enabled" in data["server"]["onlineCheck"]: + s.setBoolean( + ["server", "onlineCheck", "enabled"], + data["server"]["onlineCheck"]["enabled"], + ) + if "interval" in data["server"]["onlineCheck"]: + try: + interval = int(data["server"]["onlineCheck"]["interval"]) + s.setInt(["server", "onlineCheck", "interval"], interval * 60) + except ValueError: + pass + if "host" in data["server"]["onlineCheck"]: + s.set( + ["server", "onlineCheck", "host"], + data["server"]["onlineCheck"]["host"], + ) + if "port" in data["server"]["onlineCheck"]: + s.setInt( + ["server", "onlineCheck", "port"], + data["server"]["onlineCheck"]["port"], + ) + if "name" in data["server"]["onlineCheck"]: + s.set( + ["server", "onlineCheck", "name"], + data["server"]["onlineCheck"]["name"], + ) + if "pluginBlacklist" in data["server"]: + if "enabled" in data["server"]["pluginBlacklist"]: + s.setBoolean( + ["server", "pluginBlacklist", "enabled"], + data["server"]["pluginBlacklist"]["enabled"], + ) + if "url" in data["server"]["pluginBlacklist"]: + s.set( + ["server", "pluginBlacklist", "url"], + data["server"]["pluginBlacklist"]["url"], + ) + if "ttl" in data["server"]["pluginBlacklist"]: + try: + ttl = int(data["server"]["pluginBlacklist"]["ttl"]) + s.setInt(["server", "pluginBlacklist", "ttl"], ttl * 60) + except ValueError: + pass + if "allowFraming" in data["server"]: + s.setBoolean(["server", "allowFraming"], data["server"]["allowFraming"]) - if "devel" in data: - oldLog = s.getBoolean(["devel", "pluginTimings"]) - if "pluginTimings" in data["devel"]: s.setBoolean(["devel", "pluginTimings"], data["devel"]["pluginTimings"]) - if oldLog and not s.getBoolean(["devel", "pluginTimings"]): - # disable plugin timing logging to plugintimings.log - logging.getLogger("PLUGIN_TIMINGS").debug("Disabling plugin timings logging") - logging.getLogger("PLUGIN_TIMINGS").setLevel(logging.INFO) - elif not oldLog and s.getBoolean(["devel", "pluginTimings"]): - # enable plugin timing logging to plugintimings.log - logging.getLogger("PLUGIN_TIMINGS").setLevel(logging.DEBUG) - logging.getLogger("PLUGIN_TIMINGS").debug("Enabling plugin timings logging") + if "devel" in data: + oldLog = s.getBoolean(["devel", "pluginTimings"]) + if "pluginTimings" in data["devel"]: + s.setBoolean(["devel", "pluginTimings"], data["devel"]["pluginTimings"]) + if oldLog and not s.getBoolean(["devel", "pluginTimings"]): + # disable plugin timing logging to plugintimings.log + logging.getLogger("PLUGIN_TIMINGS").debug("Disabling plugin timings logging") + logging.getLogger("PLUGIN_TIMINGS").setLevel(logging.INFO) + elif not oldLog and s.getBoolean(["devel", "pluginTimings"]): + # enable plugin timing logging to plugintimings.log + logging.getLogger("PLUGIN_TIMINGS").setLevel(logging.DEBUG) + logging.getLogger("PLUGIN_TIMINGS").debug("Enabling plugin timings logging") - if "plugins" in data: - for plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin): - plugin_id = plugin._identifier - if plugin_id in data["plugins"]: - try: - 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(name=plugin._plugin_name, version=plugin._plugin_version)) - logger.warning("in a way which has issues due to OctoPrint's dynamic reloading after plugin operations.") - logger.warning("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.") - except Exception: - logger.exception("Could not save settings for plugin {name} ({version})".format(version=plugin._plugin_version, - name=plugin._plugin_name), - extra={"plugin": plugin._identifier}) + if "plugins" in data: + for plugin in octoprint.plugin.plugin_manager().get_implementations( + octoprint.plugin.SettingsPlugin + ): + plugin_id = plugin._identifier + if plugin_id in data["plugins"]: + try: + 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( + name=plugin._plugin_name, version=plugin._plugin_version + ) + ) + logger.warning( + "in a way which has issues due to OctoPrint's dynamic reloading after plugin operations." + ) + logger.warning( + "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." + ) + except Exception: + logger.exception( + "Could not save settings for plugin {name} ({version})".format( + version=plugin._plugin_version, name=plugin._plugin_name + ), + extra={"plugin": plugin._identifier}, + ) - s.save(trigger_event=True) + s.save(trigger_event=True) diff --git a/src/octoprint/server/api/slicing.py b/src/octoprint/server/api/slicing.py index 0b8523ab4..73680cd82 100644 --- a/src/octoprint/server/api/slicing.py +++ b/src/octoprint/server/api/slicing.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" from flask import request, jsonify, make_response, url_for @@ -15,228 +15,289 @@ from octoprint.access.permissions import Permissions from octoprint.settings import settings as s, valid_boolean_trues -from octoprint.slicing import UnknownSlicer, SlicerNotConfigured, UnknownProfile, CouldNotDeleteProfile +from octoprint.slicing import ( + UnknownSlicer, + SlicerNotConfigured, + UnknownProfile, + CouldNotDeleteProfile, +) _DATA_FORMAT_VERSION = "v2" def _lastmodified(configured): - if configured: - slicers = slicingManager.configured_slicers - else: - slicers = slicingManager.registered_slicers + if configured: + slicers = slicingManager.configured_slicers + else: + slicers = slicingManager.registered_slicers - lms = [0] - for slicer in slicers: - lms.append(slicingManager.profiles_last_modified(slicer)) + lms = [0] + for slicer in slicers: + lms.append(slicingManager.profiles_last_modified(slicer)) - return max(lms) + return max(lms) def _etag(configured, lm=None): - if lm is None: - lm = _lastmodified(configured) + if lm is None: + lm = _lastmodified(configured) - import hashlib - hash = hashlib.sha1() - def hash_update(value): - value = value.encode('utf-8') - hash.update(value) - hash_update(str(lm)) + import hashlib - if configured: - slicers = slicingManager.configured_slicers - else: - slicers = slicingManager.registered_slicers + hash = hashlib.sha1() - default_slicer = s().get(["slicing", "defaultSlicer"]) + def hash_update(value): + value = value.encode("utf-8") + hash.update(value) - for slicer in sorted(slicers): - slicer_impl = slicingManager.get_slicer(slicer, require_configured=False) - hash_update(slicer) - hash_update(str(slicer_impl.is_slicer_configured())) - hash_update(str(slicer == default_slicer)) + hash_update(str(lm)) - hash_update(_DATA_FORMAT_VERSION) # increment version if we change the API format + if configured: + slicers = slicingManager.configured_slicers + else: + slicers = slicingManager.registered_slicers - return hash.hexdigest() + default_slicer = s().get(["slicing", "defaultSlicer"]) + + for slicer in sorted(slicers): + slicer_impl = slicingManager.get_slicer(slicer, require_configured=False) + hash_update(slicer) + hash_update(str(slicer_impl.is_slicer_configured())) + hash_update(str(slicer == default_slicer)) + + hash_update(_DATA_FORMAT_VERSION) # increment version if we change the API format + + return hash.hexdigest() @api.route("/slicing", methods=["GET"]) -@with_revalidation_checking(etag_factory=lambda lm=None: _etag(request.values.get("configured", "false") in valid_boolean_trues, lm=lm), - lastmodified_factory=lambda: _lastmodified(request.values.get("configured", "false") in valid_boolean_trues), - unless=lambda: request.values.get("force", "false") in valid_boolean_trues) +@with_revalidation_checking( + etag_factory=lambda lm=None: _etag( + request.values.get("configured", "false") in valid_boolean_trues, lm=lm + ), + lastmodified_factory=lambda: _lastmodified( + request.values.get("configured", "false") in valid_boolean_trues + ), + unless=lambda: request.values.get("force", "false") in valid_boolean_trues, +) @Permissions.SLICE.require(403) def slicingListAll(): - from octoprint.filemanager import get_extensions + from octoprint.filemanager import get_extensions - default_slicer = s().get(["slicing", "defaultSlicer"]) + default_slicer = s().get(["slicing", "defaultSlicer"]) - if "configured" in request.values and request.values["configured"] in valid_boolean_trues: - slicers = slicingManager.configured_slicers - else: - slicers = slicingManager.registered_slicers + if ( + "configured" in request.values + and request.values["configured"] in valid_boolean_trues + ): + slicers = slicingManager.configured_slicers + else: + slicers = slicingManager.registered_slicers - result = {} - for slicer in slicers: - try: - slicer_impl = slicingManager.get_slicer(slicer, require_configured=False) + result = {} + for slicer in slicers: + try: + slicer_impl = slicingManager.get_slicer(slicer, require_configured=False) - extensions = set() - for source_file_type in slicer_impl.get_slicer_properties().get("source_file_types", ["model"]): - extensions = extensions.union(get_extensions(source_file_type)) + extensions = set() + for source_file_type in slicer_impl.get_slicer_properties().get( + "source_file_types", ["model"] + ): + extensions = extensions.union(get_extensions(source_file_type)) - result[slicer] = {"key": slicer, - "displayName": slicer_impl.get_slicer_properties().get("name", "n/a"), - "sameDevice": slicer_impl.get_slicer_properties().get("same_device", True), - "default": default_slicer == slicer, - "configured": slicer_impl.is_slicer_configured(), - "profiles": _getSlicingProfilesData(slicer), - "extensions": {"source": list(extensions), - "destination": slicer_impl.get_slicer_properties().get("destination_extensions", ["gco", "gcode", "g"])}} - except (UnknownSlicer, SlicerNotConfigured): - # this should never happen - pass + result[slicer] = { + "key": slicer, + "displayName": slicer_impl.get_slicer_properties().get("name", "n/a"), + "sameDevice": slicer_impl.get_slicer_properties().get( + "same_device", True + ), + "default": default_slicer == slicer, + "configured": slicer_impl.is_slicer_configured(), + "profiles": _getSlicingProfilesData(slicer), + "extensions": { + "source": list(extensions), + "destination": slicer_impl.get_slicer_properties().get( + "destination_extensions", ["gco", "gcode", "g"] + ), + }, + } + except (UnknownSlicer, SlicerNotConfigured): + # this should never happen + pass + + return jsonify(result) - return jsonify(result) @api.route("/slicing//profiles", methods=["GET"]) @no_firstrun_access @Permissions.SLICE.require(403) def slicingListSlicerProfiles(slicer): - configured = False - if "configured" in request.values and request.values["configured"] in valid_boolean_trues: - configured = True + configured = False + if ( + "configured" in request.values + and request.values["configured"] in valid_boolean_trues + ): + configured = True + + try: + return jsonify(_getSlicingProfilesData(slicer, require_configured=configured)) + except (UnknownSlicer, SlicerNotConfigured): + return make_response("Unknown slicer {slicer}".format(**locals()), 404) - try: - return jsonify(_getSlicingProfilesData(slicer, require_configured=configured)) - except (UnknownSlicer, SlicerNotConfigured): - return make_response("Unknown slicer {slicer}".format(**locals()), 404) @api.route("/slicing//profiles/", methods=["GET"]) @no_firstrun_access @Permissions.SLICE.require(403) def slicingGetSlicerProfile(slicer, name): - try: - profile = slicingManager.load_profile(slicer, name, require_configured=False) - except UnknownSlicer: - return make_response("Unknown slicer {slicer}".format(**locals()), 404) - except UnknownProfile: - return make_response("Profile not found", 404) + try: + profile = slicingManager.load_profile(slicer, name, require_configured=False) + except UnknownSlicer: + return make_response("Unknown slicer {slicer}".format(**locals()), 404) + except UnknownProfile: + return make_response("Profile not found", 404) + + result = _getSlicingProfileData(slicer, name, profile) + result["data"] = profile.data + return jsonify(result) - result = _getSlicingProfileData(slicer, name, profile) - result["data"] = profile.data - return jsonify(result) @api.route("/slicing//profiles/", methods=["PUT"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def slicingAddSlicerProfile(slicer, name): - if not "application/json" in request.headers["Content-Type"]: - return make_response("Expected content-type JSON", 400) + if not "application/json" in request.headers["Content-Type"]: + return make_response("Expected content-type JSON", 400) - try: - json_data = request.get_json() - except BadRequest: - return make_response("Malformed JSON body in request", 400) + try: + json_data = request.get_json() + except BadRequest: + return make_response("Malformed JSON body in request", 400) - if json_data is None: - return make_response("Malformed JSON body in request", 400) + if json_data is None: + return make_response("Malformed JSON body in request", 400) - data = {} - display_name = None - description = None - if "data" in json_data: - data = json_data["data"] - if "displayName" in json_data: - display_name = json_data["displayName"] - if "description" in json_data: - description = json_data["description"] + data = {} + display_name = None + description = None + if "data" in json_data: + data = json_data["data"] + if "displayName" in json_data: + display_name = json_data["displayName"] + if "description" in json_data: + description = json_data["description"] - try: - profile = slicingManager.save_profile(slicer, name, data, - allow_overwrite=True, display_name=display_name, description=description) - except UnknownSlicer: - return make_response("Unknown slicer {slicer}".format(**locals()), 404) + try: + profile = slicingManager.save_profile( + slicer, + name, + data, + allow_overwrite=True, + display_name=display_name, + description=description, + ) + except UnknownSlicer: + return make_response("Unknown slicer {slicer}".format(**locals()), 404) + + result = _getSlicingProfileData(slicer, name, profile) + r = make_response(jsonify(result), 201) + r.headers["Location"] = result["resource"] + return r - result = _getSlicingProfileData(slicer, name, profile) - r = make_response(jsonify(result), 201) - r.headers["Location"] = result["resource"] - return r @api.route("/slicing//profiles/", methods=["PATCH"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def slicingPatchSlicerProfile(slicer, name): - if not "application/json" in request.headers["Content-Type"]: - return make_response("Expected content-type JSON", 400) + if not "application/json" in request.headers["Content-Type"]: + return make_response("Expected content-type JSON", 400) - try: - profile = slicingManager.load_profile(slicer, name, require_configured=False) - except UnknownSlicer: - return make_response("Unknown slicer {slicer}".format(**locals()), 404) - except UnknownProfile: - return make_response("Profile {name} for slicer {slicer} not found".format(**locals()), 404) + try: + profile = slicingManager.load_profile(slicer, name, require_configured=False) + except UnknownSlicer: + return make_response("Unknown slicer {slicer}".format(**locals()), 404) + except UnknownProfile: + return make_response( + "Profile {name} for slicer {slicer} not found".format(**locals()), 404 + ) - try: - json_data = request.get_json() - except BadRequest: - return make_response("Malformed JSON body in request", 400) + try: + json_data = request.get_json() + except BadRequest: + return make_response("Malformed JSON body in request", 400) - if json_data is None: - return make_response("Malformed JSON body in request", 400) + if json_data is None: + return make_response("Malformed JSON body in request", 400) - data = {} - display_name = None - description = None - if "data" in json_data: - data = json_data["data"] - if "displayName" in json_data: - display_name = json_data["displayName"] - if "description" in json_data: - description = json_data["description"] + data = {} + display_name = None + description = None + if "data" in json_data: + data = json_data["data"] + if "displayName" in json_data: + display_name = json_data["displayName"] + if "description" in json_data: + description = json_data["description"] - saved_profile = slicingManager.save_profile(slicer, name, profile, - allow_overwrite=True, - overrides=data, - display_name=display_name, - description=description) + saved_profile = slicingManager.save_profile( + slicer, + name, + profile, + allow_overwrite=True, + overrides=data, + display_name=display_name, + description=description, + ) - from octoprint.server.api import valid_boolean_trues - if "default" in json_data and json_data["default"] in valid_boolean_trues: - slicingManager.set_default_profile(slicer, name, require_exists=False) + from octoprint.server.api import valid_boolean_trues + + if "default" in json_data and json_data["default"] in valid_boolean_trues: + slicingManager.set_default_profile(slicer, name, require_exists=False) + + return jsonify(_getSlicingProfileData(slicer, name, saved_profile)) - return jsonify(_getSlicingProfileData(slicer, name, saved_profile)) @api.route("/slicing//profiles/", methods=["DELETE"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def slicingDelSlicerProfile(slicer, name): - try: - slicingManager.delete_profile(slicer, name) - except UnknownSlicer: - return make_response("Unknown slicer {slicer}".format(**locals()), 404) - except CouldNotDeleteProfile as e: - return make_response("Could not delete profile {profile} for slicer {slicer}: {cause}".format(profile=name, slicer=slicer, cause=str(e.cause)), 500) + try: + slicingManager.delete_profile(slicer, name) + except UnknownSlicer: + return make_response("Unknown slicer {slicer}".format(**locals()), 404) + except CouldNotDeleteProfile as e: + return make_response( + "Could not delete profile {profile} for slicer {slicer}: {cause}".format( + profile=name, slicer=slicer, cause=str(e.cause) + ), + 500, + ) + + return NO_CONTENT - return NO_CONTENT def _getSlicingProfilesData(slicer, require_configured=False): - profiles = slicingManager.all_profiles(slicer, require_configured=require_configured) + profiles = slicingManager.all_profiles(slicer, require_configured=require_configured) + + result = {} + for name, profile in profiles.items(): + result[name] = _getSlicingProfileData(slicer, name, profile) + return result - result = {} - for name, profile in profiles.items(): - result[name] = _getSlicingProfileData(slicer, name, profile) - return result def _getSlicingProfileData(slicer, name, profile): - defaultProfiles = s().get(["slicing", "defaultProfiles"]) - result = {"key": name, - "default": defaultProfiles and slicer in defaultProfiles and defaultProfiles[slicer] == name, - "resource": url_for(".slicingGetSlicerProfile", slicer=slicer, name=name, _external=True)} - if profile.display_name is not None: - result["displayName"] = profile.display_name - if profile.description is not None: - result["description"] = profile.description - return result + defaultProfiles = s().get(["slicing", "defaultProfiles"]) + result = { + "key": name, + "default": defaultProfiles + and slicer in defaultProfiles + and defaultProfiles[slicer] == name, + "resource": url_for( + ".slicingGetSlicerProfile", slicer=slicer, name=name, _external=True + ), + } + if profile.display_name is not None: + result["displayName"] = profile.display_name + if profile.description is not None: + result["description"] = profile.description + return result diff --git a/src/octoprint/server/api/system.py b/src/octoprint/server/api/system.py index 1a1bfc75e..a8b528f41 100644 --- a/src/octoprint/server/api/system.py +++ b/src/octoprint/server/api/system.py @@ -1,7 +1,7 @@ # -*- 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import collections @@ -23,223 +23,270 @@ from octoprint.access.permissions import Permissions from octoprint.logging import prefix_multilines from octoprint.util.platform import CLOSE_FDS + @api.route("/system/usage", methods=["GET"]) @no_firstrun_access @Permissions.SYSTEM.require(403) def readUsageForFolders(): - return jsonify(usage=_usageForFolders()) + return jsonify(usage=_usageForFolders()) + def _usageForFolders(): - data = {} - for folder_name in s().get(['folder']).keys(): - path = s().getBaseFolder(folder_name, check_writable=False) - if path is not None: - usage = psutil.disk_usage(path) - data[folder_name] = { 'free': usage.free, 'total': usage.total } - return data + data = {} + for folder_name in s().get(["folder"]).keys(): + path = s().getBaseFolder(folder_name, check_writable=False) + if path is not None: + usage = psutil.disk_usage(path) + data[folder_name] = {"free": usage.free, "total": usage.total} + return data + @api.route("/system", methods=["POST"]) @no_firstrun_access @Permissions.SYSTEM.require(403) def performSystemAction(): - logging.getLogger(__name__).warning("Deprecated API call to /api/system made by {}, should be migrated to use /system/commands/custom/".format(get_remote_address(request))) + logging.getLogger(__name__).warning( + "Deprecated API call to /api/system made by {}, should be migrated to use /system/commands/custom/".format( + get_remote_address(request) + ) + ) - data = request.get_json(silent=True) - if data is None: - data = request.values + data = request.get_json(silent=True) + if data is None: + data = request.values - if not "action" in data: - return make_response(u"action to perform is not defined", 400) + if not "action" in data: + return make_response("action to perform is not defined", 400) - return executeSystemCommand("custom", data["action"]) + return executeSystemCommand("custom", data["action"]) @api.route("/system/commands", methods=["GET"]) @no_firstrun_access @Permissions.SYSTEM.require(403) def retrieveSystemCommands(): - return jsonify(core=_to_client_specs(_get_core_command_specs()), - custom=_to_client_specs(_get_custom_command_specs())) + return jsonify( + core=_to_client_specs(_get_core_command_specs()), + custom=_to_client_specs(_get_custom_command_specs()), + ) @api.route("/system/commands/", methods=["GET"]) @no_firstrun_access @Permissions.SYSTEM.require(403) def retrieveSystemCommandsForSource(source): - if source == "core": - specs = _get_core_command_specs() - elif source == "custom": - specs = _get_custom_command_specs() - else: - return make_response(u"Unknown system command source: {}".format(source), 404) + if source == "core": + specs = _get_core_command_specs() + elif source == "custom": + specs = _get_custom_command_specs() + else: + return make_response("Unknown system command source: {}".format(source), 404) - return jsonify(_to_client_specs(specs)) + return jsonify(_to_client_specs(specs)) @api.route("/system/commands//", methods=["POST"]) @no_firstrun_access @Permissions.SYSTEM.require(403) def executeSystemCommand(source, command): - logger = logging.getLogger(__name__) + logger = logging.getLogger(__name__) - if command == "divider": - return make_response("Dividers cannot be executed", 400) + if command == "divider": + return make_response("Dividers cannot be executed", 400) - command_spec = _get_command_spec(source, command) - if not command_spec: - return make_response(u"Command {}:{} not found".format(source, command), 404) + command_spec = _get_command_spec(source, command) + if not command_spec: + return make_response("Command {}:{} not found".format(source, command), 404) - if not "command" in command_spec: - return make_response(u"Command {}:{} does not define a command to execute, can't proceed".format(source, command), 500) + if not "command" in command_spec: + return make_response( + "Command {}:{} does not define a command to execute, can't proceed".format( + source, command + ), + 500, + ) - do_async = command_spec.get("async", False) - do_ignore = command_spec.get("ignore", False) - debug = command_spec.get("debug", False) + do_async = command_spec.get("async", False) + do_ignore = command_spec.get("ignore", False) + debug = command_spec.get("debug", False) - if logger.isEnabledFor(logging.DEBUG) or debug: - logger.info(u"Performing command for {}:{}: {}".format(source, command, command_spec["command"])) - else: - logger.info(u"Performing command for {}:{}".format(source, command)) + if logger.isEnabledFor(logging.DEBUG) or debug: + logger.info( + "Performing command for {}:{}: {}".format( + source, command, command_spec["command"] + ) + ) + else: + logger.info("Performing command for {}:{}".format(source, command)) - try: - if "before" in command_spec and callable(command_spec["before"]): - command_spec["before"]() - except Exception as e: - if not do_ignore: - error = u"Command \"before\" for {}:{} failed: {}".format(source, command, e) - logger.warning(error) - return make_response(error, 500) + try: + if "before" in command_spec and callable(command_spec["before"]): + command_spec["before"]() + except Exception as e: + if not do_ignore: + error = 'Command "before" for {}:{} failed: {}'.format(source, command, e) + logger.warning(error) + return make_response(error, 500) - try: - def execute(): - # we run this with shell=True since we have to trust whatever - # our admin configured as command and since we want to allow - # shell-alike handling here... - p = sarge.run(command_spec["command"], - close_fds=CLOSE_FDS, - stdout=sarge.Capture(), - stderr=sarge.Capture(), - shell=True) + try: - if not do_ignore and p.returncode != 0: - returncode = p.returncode - stdout_text = p.stdout.text - stderr_text = p.stderr.text + def execute(): + # we run this with shell=True since we have to trust whatever + # our admin configured as command and since we want to allow + # shell-alike handling here... + p = sarge.run( + command_spec["command"], + close_fds=CLOSE_FDS, + stdout=sarge.Capture(), + stderr=sarge.Capture(), + shell=True, + ) - error = "Command for {}:{} failed with return code {}:\nSTDOUT: {}\nSTDERR: {}".format(source, command, - returncode, - stdout_text, - stderr_text) - logger.warning(prefix_multilines(error, prefix="! ")) - if not do_async: - raise CommandFailed(error) + if not do_ignore and p.returncode != 0: + returncode = p.returncode + stdout_text = p.stdout.text + stderr_text = p.stderr.text - if do_async: - thread = threading.Thread(target=execute) - thread.daemon = True - thread.start() + error = "Command for {}:{} failed with return code {}:\nSTDOUT: {}\nSTDERR: {}".format( + source, command, returncode, stdout_text, stderr_text + ) + logger.warning(prefix_multilines(error, prefix="! ")) + if not do_async: + raise CommandFailed(error) - else: - try: - execute() - except CommandFailed as exc: - return make_response(exc.error, 500) + if do_async: + thread = threading.Thread(target=execute) + thread.daemon = True + thread.start() - except Exception as e: - if not do_ignore: - error = "Command for {}:{} failed: {}".format(source, command, e) - logger.warning(error) - return make_response(error, 500) + else: + try: + execute() + except CommandFailed as exc: + return make_response(exc.error, 500) + + except Exception as e: + if not do_ignore: + error = "Command for {}:{} failed: {}".format(source, command, e) + logger.warning(error) + return make_response(error, 500) + + return NO_CONTENT - return NO_CONTENT def _to_client_specs(specs): - result = list() - for spec in specs.values(): - if not "action" in spec or not "source" in spec: - continue - copied = dict((k, v) for k, v in spec.items() if k in ("source", "action", "name", "confirm")) - copied["resource"] = url_for(".executeSystemCommand", - source=spec["source"], - command=spec["action"], - _external=True) - result.append(copied) - return result + result = list() + for spec in specs.values(): + if not "action" in spec or not "source" in spec: + continue + copied = dict( + (k, v) + for k, v in spec.items() + if k in ("source", "action", "name", "confirm") + ) + copied["resource"] = url_for( + ".executeSystemCommand", + source=spec["source"], + command=spec["action"], + _external=True, + ) + result.append(copied) + return result def _get_command_spec(source, action): - if source == "core": - return _get_core_command_spec(action) - elif source == "custom": - return _get_custom_command_spec(action) - else: - return None + if source == "core": + return _get_core_command_spec(action) + elif source == "custom": + return _get_custom_command_spec(action) + else: + return None def _get_core_command_specs(): - def enable_safe_mode(): - s().set(["server", "startOnceInSafeMode"], True) - s().save() + def enable_safe_mode(): + s().set(["server", "startOnceInSafeMode"], True) + s().save() - commands = collections.OrderedDict( - shutdown={"command": s().get(["server", "commands", "systemShutdownCommand"]), - "name": gettext("Shutdown system"), - "confirm": gettext(u"You are about to shutdown the system.

This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).")}, - reboot={"command": s().get(["server", "commands", "systemRestartCommand"]), - "name": gettext("Reboot system"), - "confirm": gettext(u"You are about to reboot the system.

This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).")}, - restart={"command": s().get(["server", "commands", "serverRestartCommand"]), - "name": gettext("Restart OctoPrint"), - "confirm": gettext(u"You are about to restart the OctoPrint server.

This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).")}, - restart_safe={"command": s().get(["server", "commands", "serverRestartCommand"]), - "name": gettext("Restart OctoPrint in safe mode"), - "confirm": gettext(u"You are about to restart the OctoPrint server in safe mode.

This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."), - "before": enable_safe_mode} - ) + commands = collections.OrderedDict( + shutdown={ + "command": s().get(["server", "commands", "systemShutdownCommand"]), + "name": gettext("Shutdown system"), + "confirm": gettext( + "You are about to shutdown the system.

This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)." + ), + }, + reboot={ + "command": s().get(["server", "commands", "systemRestartCommand"]), + "name": gettext("Reboot system"), + "confirm": gettext( + "You are about to reboot the system.

This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)." + ), + }, + restart={ + "command": s().get(["server", "commands", "serverRestartCommand"]), + "name": gettext("Restart OctoPrint"), + "confirm": gettext( + "You are about to restart the OctoPrint server.

This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)." + ), + }, + restart_safe={ + "command": s().get(["server", "commands", "serverRestartCommand"]), + "name": gettext("Restart OctoPrint in safe mode"), + "confirm": gettext( + "You are about to restart the OctoPrint server in safe mode.

This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)." + ), + "before": enable_safe_mode, + }, + ) - available_commands = collections.OrderedDict() - for action, spec in commands.items(): - if not spec["command"]: - continue - spec.update({'action': action, 'source': 'core', 'async': True, 'debug': True}) - available_commands[action] = spec - return available_commands + available_commands = collections.OrderedDict() + for action, spec in commands.items(): + if not spec["command"]: + continue + spec.update({"action": action, "source": "core", "async": True, "debug": True}) + available_commands[action] = spec + return available_commands def _get_core_command_spec(action): - available_actions = _get_core_command_specs() - if not action in available_actions: - logging.getLogger(__name__).warning(u"Command for core action {} is not configured, you need to configure the command before it can be used".format(action)) - return None + available_actions = _get_core_command_specs() + if not action in available_actions: + logging.getLogger(__name__).warning( + "Command for core action {} is not configured, you need to configure the command before it can be used".format( + action + ) + ) + return None - return available_actions[action] + return available_actions[action] def _get_custom_command_specs(): - specs = collections.OrderedDict() - dividers = 0 - for spec in s().get(["system", "actions"]): - if not "action" in spec: - continue - copied = dict(spec) - copied["source"] = "custom" + specs = collections.OrderedDict() + dividers = 0 + for spec in s().get(["system", "actions"]): + if not "action" in spec: + continue + copied = dict(spec) + copied["source"] = "custom" - action = spec["action"] - if action == "divider": - dividers += 1 - action = "divider_{}".format(dividers) - specs[action] = copied - return specs + action = spec["action"] + if action == "divider": + dividers += 1 + action = "divider_{}".format(dividers) + specs[action] = copied + return specs def _get_custom_command_spec(action): - available_actions = _get_custom_command_specs() - if not action in available_actions: - return None + available_actions = _get_custom_command_specs() + if not action in available_actions: + return None - return available_actions[action] + return available_actions[action] class CommandFailed(Exception): - def __init__(self, error): - self.error = error + def __init__(self, error): + self.error = error diff --git a/src/octoprint/server/api/timelapse.py b/src/octoprint/server/api/timelapse.py index f08f03322..e66636a31 100644 --- a/src/octoprint/server/api/timelapse.py +++ b/src/octoprint/server/api/timelapse.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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 os @@ -16,7 +16,12 @@ import octoprint.util as util from octoprint.settings import settings, valid_boolean_trues from octoprint.server import admin_permission, printer -from octoprint.server.util.flask import redirect_to_tornado, no_firstrun_access, get_json_command_from_request, with_revalidation_checking +from octoprint.server.util.flask import ( + redirect_to_tornado, + no_firstrun_access, + get_json_command_from_request, + with_revalidation_checking, +) from octoprint.server.api import api from octoprint.server import NO_CONTENT @@ -24,7 +29,7 @@ from octoprint.access.permissions import Permissions _DATA_FORMAT_VERSION = "v2" -#~~ timelapse handling +# ~~ timelapse handling _timelapse_cache_finished = [] _timelapse_cache_finished_lastmodified = None @@ -32,229 +37,273 @@ _timelapse_cache_unrendered = [] _timelapse_cache_unrendered_lastmodified = None _timelapse_cache_mutex = threading.RLock() + def _config_for_timelapse(timelapse): - if timelapse is not None and isinstance(timelapse, octoprint.timelapse.ZTimelapse): - return {"type": "zchange", - "postRoll": timelapse.post_roll, - "fps": timelapse.fps, - "retractionZHop": timelapse.retraction_zhop, - "minDelay": timelapse.min_delay} - elif timelapse is not None and isinstance(timelapse, octoprint.timelapse.TimedTimelapse): - return {"type": "timed", - "postRoll": timelapse.post_roll, - "fps": timelapse.fps, - "interval": timelapse.interval} - else: - return {"type": "off"} + if timelapse is not None and isinstance(timelapse, octoprint.timelapse.ZTimelapse): + return { + "type": "zchange", + "postRoll": timelapse.post_roll, + "fps": timelapse.fps, + "retractionZHop": timelapse.retraction_zhop, + "minDelay": timelapse.min_delay, + } + elif timelapse is not None and isinstance( + timelapse, octoprint.timelapse.TimedTimelapse + ): + return { + "type": "timed", + "postRoll": timelapse.post_roll, + "fps": timelapse.fps, + "interval": timelapse.interval, + } + else: + return {"type": "off"} + def _lastmodified(unrendered): - lm_finished = octoprint.timelapse.last_modified_finished() - if unrendered: - lm_unrendered = octoprint.timelapse.last_modified_unrendered() + lm_finished = octoprint.timelapse.last_modified_finished() + if unrendered: + lm_unrendered = octoprint.timelapse.last_modified_unrendered() + + if lm_finished is None or lm_unrendered is None: + return None + return max(lm_finished, lm_unrendered) + return lm_finished - if lm_finished is None or lm_unrendered is None: - return None - return max(lm_finished, lm_unrendered) - return lm_finished def _etag(unrendered, lm=None): - if lm is None: - lm = _lastmodified(unrendered) + if lm is None: + lm = _lastmodified(unrendered) - timelapse = octoprint.timelapse.current - config = _config_for_timelapse(timelapse) + timelapse = octoprint.timelapse.current + config = _config_for_timelapse(timelapse) - import hashlib - hash = hashlib.sha1() - def hash_update(value): - value = value.encode('utf-8') - hash.update(value) - hash_update(str(lm)) - hash_update(repr(config)) - hash_update(repr(_DATA_FORMAT_VERSION)) + import hashlib + + hash = hashlib.sha1() + + def hash_update(value): + value = value.encode("utf-8") + hash.update(value) + + hash_update(str(lm)) + hash_update(repr(config)) + hash_update(repr(_DATA_FORMAT_VERSION)) + + return hash.hexdigest() - return hash.hexdigest() @api.route("/timelapse", methods=["GET"]) -@with_revalidation_checking(etag_factory=lambda lm=None: _etag(request.values.get("unrendered", "false") in valid_boolean_trues, lm=lm), - lastmodified_factory=lambda: _lastmodified(request.values.get("unrendered", "false") in valid_boolean_trues), - unless=lambda: request.values.get("force", "false") in valid_boolean_trues) +@with_revalidation_checking( + etag_factory=lambda lm=None: _etag( + request.values.get("unrendered", "false") in valid_boolean_trues, lm=lm + ), + lastmodified_factory=lambda: _lastmodified( + request.values.get("unrendered", "false") in valid_boolean_trues + ), + unless=lambda: request.values.get("force", "false") in valid_boolean_trues, +) @no_firstrun_access @Permissions.TIMELAPSE_LIST.require(403) def getTimelapseData(): - timelapse = octoprint.timelapse.current - config = _config_for_timelapse(timelapse) + timelapse = octoprint.timelapse.current + config = _config_for_timelapse(timelapse) - force = request.values.get("force", "false") in valid_boolean_trues - unrendered = request.values.get("unrendered", "false") in valid_boolean_trues + force = request.values.get("force", "false") in valid_boolean_trues + unrendered = request.values.get("unrendered", "false") in valid_boolean_trues - global _timelapse_cache_finished_lastmodified, _timelapse_cache_finished, _timelapse_cache_unrendered_lastmodified, _timelapse_cache_unrendered - with _timelapse_cache_mutex: - current_lastmodified_finished = octoprint.timelapse.last_modified_finished() - current_lastmodified_unrendered = octoprint.timelapse.last_modified_unrendered() + global _timelapse_cache_finished_lastmodified, _timelapse_cache_finished, _timelapse_cache_unrendered_lastmodified, _timelapse_cache_unrendered + with _timelapse_cache_mutex: + current_lastmodified_finished = octoprint.timelapse.last_modified_finished() + current_lastmodified_unrendered = octoprint.timelapse.last_modified_unrendered() - if not force and _timelapse_cache_finished_lastmodified == current_lastmodified_finished: - files = _timelapse_cache_finished - else: - files = octoprint.timelapse.get_finished_timelapses() - _timelapse_cache_finished = files - _timelapse_cache_finished_lastmodified = current_lastmodified_finished + if ( + not force + and _timelapse_cache_finished_lastmodified == current_lastmodified_finished + ): + files = _timelapse_cache_finished + else: + files = octoprint.timelapse.get_finished_timelapses() + _timelapse_cache_finished = files + _timelapse_cache_finished_lastmodified = current_lastmodified_finished - unrendered_files = [] - if unrendered: - if not force and _timelapse_cache_unrendered_lastmodified == current_lastmodified_unrendered: - unrendered_files = _timelapse_cache_unrendered - else: - unrendered_files = octoprint.timelapse.get_unrendered_timelapses() - _timelapse_cache_unrendered = unrendered_files - _timelapse_cache_unrendered_lastmodified = current_lastmodified_unrendered + unrendered_files = [] + if unrendered: + if ( + not force + and _timelapse_cache_unrendered_lastmodified + == current_lastmodified_unrendered + ): + unrendered_files = _timelapse_cache_unrendered + else: + unrendered_files = octoprint.timelapse.get_unrendered_timelapses() + _timelapse_cache_unrendered = unrendered_files + _timelapse_cache_unrendered_lastmodified = current_lastmodified_unrendered - finished_list = [] - for f in files: - output = dict(f) - output["url"] = url_for("index") + "downloads/timelapse/" + f["name"] - finished_list.append(output) + finished_list = [] + for f in files: + output = dict(f) + output["url"] = url_for("index") + "downloads/timelapse/" + f["name"] + finished_list.append(output) - result = {"config": config, - "enabled": settings().getBoolean(["webcam", "timelapseEnabled"]), - "files": finished_list} + result = { + "config": config, + "enabled": settings().getBoolean(["webcam", "timelapseEnabled"]), + "files": finished_list, + } - if unrendered: - result.update(unrendered=unrendered_files) + if unrendered: + result.update(unrendered=unrendered_files) - return jsonify(result) + return jsonify(result) @api.route("/timelapse/", methods=["GET"]) @no_firstrun_access @Permissions.TIMELAPSE_DOWNLOAD.require(403) def downloadTimelapse(filename): - return redirect_to_tornado(request, url_for("index") + "downloads/timelapse/" + filename) + return redirect_to_tornado( + request, url_for("index") + "downloads/timelapse/" + filename + ) @api.route("/timelapse/", methods=["DELETE"]) @no_firstrun_access @Permissions.TIMELAPSE_DELETE.require(403) def deleteTimelapse(filename): - timelapse_folder = settings().getBaseFolder("timelapse") - full_path = os.path.realpath(os.path.join(timelapse_folder, filename)) - if octoprint.timelapse.valid_timelapse(full_path) \ - and full_path.startswith(timelapse_folder) \ - and os.path.exists(full_path) \ - and not util.is_hidden_path(full_path): - try: - os.remove(full_path) - except Exception as ex: - logging.getLogger(__file__).exception("Error deleting timelapse file {}".format(full_path)) - return make_response("Unexpected error: {}".format(ex), 500) + timelapse_folder = settings().getBaseFolder("timelapse") + full_path = os.path.realpath(os.path.join(timelapse_folder, filename)) + if ( + octoprint.timelapse.valid_timelapse(full_path) + and full_path.startswith(timelapse_folder) + and os.path.exists(full_path) + and not util.is_hidden_path(full_path) + ): + try: + os.remove(full_path) + except Exception as ex: + logging.getLogger(__file__).exception( + "Error deleting timelapse file {}".format(full_path) + ) + return make_response("Unexpected error: {}".format(ex), 500) - return getTimelapseData() + return getTimelapseData() @api.route("/timelapse/unrendered/", methods=["DELETE"]) @no_firstrun_access @Permissions.TIMELAPSE_DELETE.require(403) def deleteUnrenderedTimelapse(name): - octoprint.timelapse.delete_unrendered_timelapse(name) - return NO_CONTENT + octoprint.timelapse.delete_unrendered_timelapse(name) + return NO_CONTENT @api.route("/timelapse/unrendered/", methods=["POST"]) @no_firstrun_access @Permissions.TIMELAPSE_ADMIN.require(403) def processUnrenderedTimelapseCommand(name): - # valid file commands, dict mapping command name to mandatory parameters - valid_commands = { - "render": [] - } + # valid file commands, dict mapping command name to mandatory parameters + valid_commands = {"render": []} - command, data, response = get_json_command_from_request(request, valid_commands) - if response is not None: - return response + command, data, response = get_json_command_from_request(request, valid_commands) + if response is not None: + return response - if command == "render": - if printer.is_printing() or printer.is_paused(): - return make_response("Printer is currently printing, cannot render timelapse", 409) - octoprint.timelapse.render_unrendered_timelapse(name) + if command == "render": + if printer.is_printing() or printer.is_paused(): + return make_response( + "Printer is currently printing, cannot render timelapse", 409 + ) + octoprint.timelapse.render_unrendered_timelapse(name) - return NO_CONTENT + return NO_CONTENT @api.route("/timelapse", methods=["POST"]) @no_firstrun_access @Permissions.TIMELAPSE_ADMIN.require(403) def setTimelapseConfig(): - data = request.get_json(silent=True) - if data is None: - data = request.values + data = request.get_json(silent=True) + if data is None: + data = request.values - if "type" in data: - config = { - "type": data["type"], - "postRoll": 0, - "fps": 25, - "options": {} - } + if "type" in data: + config = {"type": data["type"], "postRoll": 0, "fps": 25, "options": {}} - if "postRoll" in data: - try: - postRoll = int(data["postRoll"]) - except ValueError: - return make_response("Invalid value for postRoll: %r" % data["postRoll"], 400) - else: - if postRoll >= 0: - config["postRoll"] = postRoll - else: - return make_response("Invalid value for postRoll: %d" % postRoll, 400) + if "postRoll" in data: + try: + postRoll = int(data["postRoll"]) + except ValueError: + return make_response( + "Invalid value for postRoll: %r" % data["postRoll"], 400 + ) + else: + if postRoll >= 0: + config["postRoll"] = postRoll + else: + return make_response("Invalid value for postRoll: %d" % postRoll, 400) - if "fps" in data: - try: - fps = int(data["fps"]) - except ValueError: - return make_response("Invalid value for fps: %r" % data["fps"], 400) - else: - if fps > 0: - config["fps"] = fps - else: - return make_response("Invalid value for fps: %d" % fps, 400) + if "fps" in data: + try: + fps = int(data["fps"]) + except ValueError: + return make_response("Invalid value for fps: %r" % data["fps"], 400) + else: + if fps > 0: + config["fps"] = fps + else: + return make_response("Invalid value for fps: %d" % fps, 400) - if "interval" in data: - try: - interval = int(data["interval"]) - except ValueError: - return make_response("Invalid value for interval: %r" % data["interval"], 400) - else: - if interval > 0: - config["options"]["interval"] = interval - else: - return make_response("Invalid value for interval: %d" % interval, 400) + if "interval" in data: + try: + interval = int(data["interval"]) + except ValueError: + return make_response( + "Invalid value for interval: %r" % data["interval"], 400 + ) + else: + if interval > 0: + config["options"]["interval"] = interval + else: + return make_response("Invalid value for interval: %d" % interval, 400) - if "retractionZHop" in data: - try: - retractionZHop = float(data["retractionZHop"]) - except ValueError: - return make_response("Invalid value for retraction Z-Hop: %r" % data["retractionZHop"], 400) - else: - if retractionZHop >= 0: - config["options"]["retractionZHop"] = retractionZHop - else: - return make_response("Invalid value for retraction Z-Hop: %f" % retractionZHop, 400) + if "retractionZHop" in data: + try: + retractionZHop = float(data["retractionZHop"]) + except ValueError: + return make_response( + "Invalid value for retraction Z-Hop: %r" % data["retractionZHop"], 400 + ) + else: + if retractionZHop >= 0: + config["options"]["retractionZHop"] = retractionZHop + else: + return make_response( + "Invalid value for retraction Z-Hop: %f" % retractionZHop, 400 + ) - if "minDelay" in data: - try: - minDelay = float(data["minDelay"]) - except ValueError: - return make_response("Invalid value for minimum delay: %r" % data["minDelay"], 400) - else: - if minDelay > 0: - config["options"]["minDelay"] = minDelay - else: - return make_response("Invalid value for minimum delay: %f" % minDelay, 400) + if "minDelay" in data: + try: + minDelay = float(data["minDelay"]) + except ValueError: + return make_response( + "Invalid value for minimum delay: %r" % data["minDelay"], 400 + ) + else: + if minDelay > 0: + config["options"]["minDelay"] = minDelay + else: + return make_response( + "Invalid value for minimum delay: %f" % minDelay, 400 + ) - if admin_permission.can() and "save" in data and data["save"] in valid_boolean_trues: - octoprint.timelapse.configure_timelapse(config, True) - else: - octoprint.timelapse.configure_timelapse(config) - - return getTimelapseData() + if ( + admin_permission.can() + and "save" in data + and data["save"] in valid_boolean_trues + ): + octoprint.timelapse.configure_timelapse(config, True) + else: + octoprint.timelapse.configure_timelapse(config) + return getTimelapseData() diff --git a/src/octoprint/server/api/users.py b/src/octoprint/server/api/users.py index e13978538..0a99b861a 100644 --- a/src/octoprint/server/api/users.py +++ b/src/octoprint/server/api/users.py @@ -1,7 +1,7 @@ # -*- 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' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" from octoprint.server.api import api @@ -11,51 +11,52 @@ from flask import redirect, url_for # by all browsers yet. So we stick to 307 TEMPORARY REDIRECT as defined in RFC7231 although it's definitely not a # temporary redirect we have here. + @api.route("/users", methods=["GET"]) def deprecated_get_users(): - return redirect(url_for("api.get_users"), code=307) + return redirect(url_for("api.get_users"), code=307) @api.route("/users", methods=["POST"]) def addUser(): - return redirect(url_for("api.add_user"), code=307) + return redirect(url_for("api.add_user"), code=307) @api.route("/users/", methods=["GET"]) def getUser(username): - return redirect(url_for("api.get_user", username=username), code=307) + return redirect(url_for("api.get_user", username=username), code=307) @api.route("/users/", methods=["PUT"]) def updateUser(username): - return redirect(url_for("api.update_user", username=username), code=307) + return redirect(url_for("api.update_user", username=username), code=307) @api.route("/users/", methods=["DELETE"]) def removeUser(username): - return redirect(url_for("api.remove_user", username=username), code=307) + return redirect(url_for("api.remove_user", username=username), code=307) @api.route("/users//password", methods=["PUT"]) def changePasswordForUser(username): - return redirect(url_for("api.change_password_for_user", username=username), code=307) + return redirect(url_for("api.change_password_for_user", username=username), code=307) @api.route("/users//settings", methods=["GET"]) def getSettingsForUser(username): - return redirect(url_for("api.get_settings_for_user", username=username), code=307) + return redirect(url_for("api.get_settings_for_user", username=username), code=307) @api.route("/users//settings", methods=["PATCH"]) def changeSettingsForUser(username): - return redirect(url_for("api.change_settings_for_user", username=username), code=307) + return redirect(url_for("api.change_settings_for_user", username=username), code=307) @api.route("/users//apikey", methods=["DELETE"]) def deleteApikeyForUser(username): - return redirect(url_for("api.delete_apikey_for_user", username=username), code=307) + return redirect(url_for("api.delete_apikey_for_user", username=username), code=307) @api.route("/users//apikey", methods=["POST"]) def generateApikeyForUser(username): - return redirect(url_for("api.generate_apikey_for_user", username=username), code=307) + return redirect(url_for("api.generate_apikey_for_user", username=username), code=307) diff --git a/src/octoprint/server/util/__init__.py b/src/octoprint/server/util/__init__.py index 0bfd06fe3..2c4ad26ac 100644 --- a/src/octoprint/server/util/__init__.py +++ b/src/octoprint/server/util/__init__.py @@ -2,11 +2,12 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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 base64 import sys + PY3 = sys.version_info[0] == 3 from octoprint.settings import settings @@ -27,277 +28,320 @@ from . import tornado from . import watchdog -@deprecated("API keys are no longer needed for anonymous access and thus this is now obsolete") +@deprecated( + "API keys are no longer needed for anonymous access and thus this is now obsolete" +) def enforceApiKeyRequestHandler(): - pass + pass -apiKeyRequestHandler = deprecated("apiKeyRequestHandler has been renamed to enforceApiKeyRequestHandler")(enforceApiKeyRequestHandler) + +apiKeyRequestHandler = deprecated( + "apiKeyRequestHandler has been renamed to enforceApiKeyRequestHandler" +)(enforceApiKeyRequestHandler) def loginFromApiKeyRequestHandler(): - """ - ``before_request`` handler for blueprints which creates a login session for the provided api key (if available) + """ + ``before_request`` handler for blueprints which creates a login session for the provided api key (if available) - App session keys are handled as anonymous keys here and ignored. - """ - try: - if loginUserFromApiKey(): - _flask.g.login_via_apikey = True - except InvalidApiKeyException: - return _flask.make_response("Invalid API key", 403) + App session keys are handled as anonymous keys here and ignored. + """ + try: + if loginUserFromApiKey(): + _flask.g.login_via_apikey = True + except InvalidApiKeyException: + return _flask.make_response("Invalid API key", 403) def loginFromAuthorizationHeaderRequestHandler(): - """ - ``before_request`` handler for creating login sessions based on the Authorization header. - """ - try: - if loginUserFromAuthorizationHeader(): - _flask.g.login_via_header = True - except InvalidApiKeyException: - return _flask.make_response("Invalid API key", 403) + """ + ``before_request`` handler for creating login sessions based on the Authorization header. + """ + try: + if loginUserFromAuthorizationHeader(): + _flask.g.login_via_header = True + except InvalidApiKeyException: + return _flask.make_response("Invalid API key", 403) -class InvalidApiKeyException(Exception): pass +class InvalidApiKeyException(Exception): + pass def loginUserFromApiKey(): - apikey = get_api_key(_flask.request) - if not apikey: - return False + apikey = get_api_key(_flask.request) + if not apikey: + return False - user = get_user_for_apikey(apikey) - if user is None: - # invalid API key = no API key - return False + user = get_user_for_apikey(apikey) + if user is None: + # invalid API key = no API key + return False - return loginUser(user, login_mechanism="apikey") + return loginUser(user, login_mechanism="apikey") def loginUserFromAuthorizationHeader(): - authorization_header = get_authorization_header(_flask.request) - user = get_user_for_authorization_header(authorization_header) - return loginUser(user, login_mechanism="authheader") + authorization_header = get_authorization_header(_flask.request) + user = get_user_for_authorization_header(authorization_header) + return loginUser(user, login_mechanism="authheader") def loginUser(user, remember=False, login_mechanism=None): - """ - Logs the provided ``user`` into Flask Login and Principal if not None and active + """ + Logs the provided ``user`` into Flask Login and Principal if not None and active - Args: - user: the User to login. May be None in which case the login will fail - remember: Whether to set the ``remember`` flag on the Flask Login operation + Args: + user: the User to login. May be None in which case the login will fail + remember: Whether to set the ``remember`` flag on the Flask Login operation - Returns: (bool) True if the login succeeded, False otherwise + Returns: (bool) True if the login succeeded, False otherwise - """ - if user is not None and user.is_active and flask_login.login_user(user, remember=remember): - flask_principal.identity_changed.send(_flask.current_app._get_current_object(), - identity=flask_principal.Identity(user.get_id())) - if login_mechanism: - _flask.session["login_mechanism"] = login_mechanism - return True - return False + """ + if ( + user is not None + and user.is_active + and flask_login.login_user(user, remember=remember) + ): + flask_principal.identity_changed.send( + _flask.current_app._get_current_object(), + identity=flask_principal.Identity(user.get_id()), + ) + if login_mechanism: + _flask.session["login_mechanism"] = login_mechanism + return True + return False def requireLoginRequestHandler(): - if _flask.request.endpoint.endswith(".static"): - return + if _flask.request.endpoint.endswith(".static"): + return - if not (octoprint.server.userManager.enabled and octoprint.server.userManager.has_been_customized()): - return + if not ( + octoprint.server.userManager.enabled + and octoprint.server.userManager.has_been_customized() + ): + return - user = flask_login.current_user - if user is None or user.is_anonymous or not user.is_active: - return flask.make_response("Forbidden", 403) + user = flask_login.current_user + if user is None or user.is_anonymous or not user.is_active: + return flask.make_response("Forbidden", 403) def corsRequestHandler(): - """ - ``before_request`` handler for blueprints which sets CORS headers for OPTIONS requests if enabled - """ - if _flask.request.method == 'OPTIONS' and settings().getBoolean(["api", "allowCrossOrigin"]): - # reply to OPTIONS request for CORS headers - return optionsAllowOrigin(_flask.request) + """ + ``before_request`` handler for blueprints which sets CORS headers for OPTIONS requests if enabled + """ + if _flask.request.method == "OPTIONS" and settings().getBoolean( + ["api", "allowCrossOrigin"] + ): + # reply to OPTIONS request for CORS headers + return optionsAllowOrigin(_flask.request) def corsResponseHandler(resp): - """ - ``after_request`` handler for blueprints for which CORS is supported. + """ + ``after_request`` handler for blueprints for which CORS is supported. - Sets ``Access-Control-Allow-Origin`` headers for ``Origin`` request header on response. - """ + Sets ``Access-Control-Allow-Origin`` headers for ``Origin`` request header on response. + """ - # Allow crossdomain - allowCrossOrigin = settings().getBoolean(["api", "allowCrossOrigin"]) - if _flask.request.method != 'OPTIONS' and 'Origin' in _flask.request.headers and allowCrossOrigin: - resp.headers['Access-Control-Allow-Origin'] = _flask.request.headers['Origin'] + # Allow crossdomain + allowCrossOrigin = settings().getBoolean(["api", "allowCrossOrigin"]) + if ( + _flask.request.method != "OPTIONS" + and "Origin" in _flask.request.headers + and allowCrossOrigin + ): + resp.headers["Access-Control-Allow-Origin"] = _flask.request.headers["Origin"] - return resp + return resp def noCachingResponseHandler(resp): - """ - ``after_request`` handler for blueprints which shall set no caching headers - on their responses. + """ + ``after_request`` handler for blueprints which shall set no caching headers + on their responses. - Sets ``Cache-Control``, ``Pragma`` and ``Expires`` headers accordingly - to prevent all client side caching from taking place. - """ + Sets ``Cache-Control``, ``Pragma`` and ``Expires`` headers accordingly + to prevent all client side caching from taking place. + """ - return flask.add_non_caching_response_headers(resp) + return flask.add_non_caching_response_headers(resp) def noCachingExceptGetResponseHandler(resp): - """ - ``after_request`` handler for blueprints which shall set no caching headers - on their responses to any requests that are not sent with method ``GET``. + """ + ``after_request`` handler for blueprints which shall set no caching headers + on their responses to any requests that are not sent with method ``GET``. - See :func:`noCachingResponseHandler`. - """ + See :func:`noCachingResponseHandler`. + """ - if _flask.request.method == "GET": - return flask.add_no_max_age_response_headers(resp) - else: - return flask.add_non_caching_response_headers(resp) + if _flask.request.method == "GET": + return flask.add_no_max_age_response_headers(resp) + else: + return flask.add_non_caching_response_headers(resp) def optionsAllowOrigin(request): - """ - Shortcut for request handling for CORS OPTIONS requests to set CORS headers. - """ + """ + Shortcut for request handling for CORS OPTIONS requests to set CORS headers. + """ - resp = _flask.current_app.make_default_options_response() + resp = _flask.current_app.make_default_options_response() - # Allow the origin which made the XHR - resp.headers['Access-Control-Allow-Origin'] = request.headers['Origin'] - # Allow the actual method - resp.headers['Access-Control-Allow-Methods'] = request.headers['Access-Control-Request-Method'] - # Allow for 10 seconds - resp.headers['Access-Control-Max-Age'] = "10" + # Allow the origin which made the XHR + resp.headers["Access-Control-Allow-Origin"] = request.headers["Origin"] + # Allow the actual method + resp.headers["Access-Control-Allow-Methods"] = request.headers[ + "Access-Control-Request-Method" + ] + # Allow for 10 seconds + resp.headers["Access-Control-Max-Age"] = "10" - # 'preflight' request contains the non-standard headers the real request will have (like X-Api-Key) - customRequestHeaders = request.headers.get('Access-Control-Request-Headers', None) - if customRequestHeaders is not None: - # If present => allow them all - resp.headers['Access-Control-Allow-Headers'] = customRequestHeaders + # 'preflight' request contains the non-standard headers the real request will have (like X-Api-Key) + customRequestHeaders = request.headers.get("Access-Control-Request-Headers", None) + if customRequestHeaders is not None: + # If present => allow them all + resp.headers["Access-Control-Allow-Headers"] = customRequestHeaders - return resp + return resp def get_user_for_apikey(apikey): - if apikey is not None: - if apikey == settings().get(["api", "key"]): - # master key was used - return octoprint.server.userManager.api_user_factory() + if apikey is not None: + if apikey == settings().get(["api", "key"]): + # master key was used + return octoprint.server.userManager.api_user_factory() - if octoprint.server.userManager.enabled: - user = octoprint.server.userManager.find_user(apikey=apikey) - if user is not None: - # user key was used - return user + if octoprint.server.userManager.enabled: + user = octoprint.server.userManager.find_user(apikey=apikey) + if user is not None: + # user key was used + return user - apikey_hooks = plugin_manager().get_hooks("octoprint.accesscontrol.keyvalidator") - for name, hook in apikey_hooks.items(): - try: - user = hook(apikey) - if user is not None: - return user - except Exception: - logging.getLogger(__name__).exception("Error running api key validator " - "for plugin {} and key {}".format(name, apikey), - extra={"plugin": name}) - return None + apikey_hooks = plugin_manager().get_hooks("octoprint.accesscontrol.keyvalidator") + for name, hook in apikey_hooks.items(): + try: + user = hook(apikey) + if user is not None: + return user + except Exception: + logging.getLogger(__name__).exception( + "Error running api key validator " + "for plugin {} and key {}".format(name, apikey), + extra={"plugin": name}, + ) + return None def get_user_for_remote_user_header(request): - if not octoprint.server.userManager.enabled: - return None + if not octoprint.server.userManager.enabled: + return None - if not settings().getBoolean(["accessControl", "trustRemoteUser"]): - return None + if not settings().getBoolean(["accessControl", "trustRemoteUser"]): + return None - header = request.headers.get(settings().get(["accessControl", "remoteUserHeader"])) - if header is None: - return None + header = request.headers.get(settings().get(["accessControl", "remoteUserHeader"])) + if header is None: + return None - user = octoprint.server.userManager.findUser(userid=header) + user = octoprint.server.userManager.findUser(userid=header) - if user is None and settings().getBoolean(["accessControl", "addRemoteUsers"]): - octoprint.server.userManager.addUser(header, settings().generateApiKey(), active=True) - user = octoprint.server.userManager.findUser(userid=header) + if user is None and settings().getBoolean(["accessControl", "addRemoteUsers"]): + octoprint.server.userManager.addUser( + header, settings().generateApiKey(), active=True + ) + user = octoprint.server.userManager.findUser(userid=header) - return user + return user def get_user_for_authorization_header(header): - if not settings().getBoolean(["accessControl", "trustBasicAuthentication"]): - return None + if not settings().getBoolean(["accessControl", "trustBasicAuthentication"]): + return None - if header is None: - return None + if header is None: + return None - if not header.startswith("Basic "): - # we currently only support Basic Authentication - return None + if not header.startswith("Basic "): + # we currently only support Basic Authentication + return None - header = header.replace('Basic ', '', 1) - try: - header = to_unicode(base64.b64decode(header)) - except TypeError: - return None + header = header.replace("Basic ", "", 1) + try: + header = to_unicode(base64.b64decode(header)) + except TypeError: + return None - name, password = header.split(':', 1) - if not octoprint.server.userManager.enabled: - return None + name, password = header.split(":", 1) + if not octoprint.server.userManager.enabled: + return None - user = octoprint.server.userManager.find_user(userid=name) - if settings().getBoolean(["accessControl", "checkBasicAuthenticationPassword"]) \ - and not octoprint.server.userManager.check_password(name, password): - # password check enabled and password don't match - return None + user = octoprint.server.userManager.find_user(userid=name) + if settings().getBoolean( + ["accessControl", "checkBasicAuthenticationPassword"] + ) and not octoprint.server.userManager.check_password(name, password): + # password check enabled and password don't match + return None - return user + return user def get_api_key(request): - # Check Flask GET/POST arguments - if hasattr(request, "values") and "apikey" in request.values: - return request.values["apikey"] + # Check Flask GET/POST arguments + if hasattr(request, "values") and "apikey" in request.values: + return request.values["apikey"] - # Check Tornado GET/POST arguments - if hasattr(request, "arguments") and "apikey" in request.arguments \ - and len(request.arguments["apikey"]) > 0 and len(request.arguments["apikey"].strip()) > 0: - return request.arguments["apikey"] + # Check Tornado GET/POST arguments + if ( + hasattr(request, "arguments") + and "apikey" in request.arguments + and len(request.arguments["apikey"]) > 0 + and len(request.arguments["apikey"].strip()) > 0 + ): + return request.arguments["apikey"] - # Check Tornado and Flask headers - if "X-Api-Key" in request.headers: - return request.headers.get("X-Api-Key") + # Check Tornado and Flask headers + if "X-Api-Key" in request.headers: + return request.headers.get("X-Api-Key") - # Check Tornado and Flask headers - if "Authorization" in request.headers: - header = request.headers.get("Authorization") - if header.startswith("Bearer "): - token = header.replace("Bearer ", "", 1) - return token + # Check Tornado and Flask headers + if "Authorization" in request.headers: + header = request.headers.get("Authorization") + if header.startswith("Bearer "): + token = header.replace("Bearer ", "", 1) + return token - return None + return None def get_authorization_header(request): - # Tornado and Flask headers - return request.headers.get("Authorization") + # Tornado and Flask headers + return request.headers.get("Authorization") def get_plugin_hash(): - from octoprint.plugin import plugin_manager + from octoprint.plugin import plugin_manager - plugin_signature = lambda impl: "{}:{}".format(impl._identifier, impl._plugin_version) - template_plugins = list(map(plugin_signature, plugin_manager().get_implementations(octoprint.plugin.TemplatePlugin))) - asset_plugins = list(map(plugin_signature, plugin_manager().get_implementations(octoprint.plugin.AssetPlugin))) - ui_plugins = sorted(set(template_plugins + asset_plugins)) + plugin_signature = lambda impl: "{}:{}".format(impl._identifier, impl._plugin_version) + template_plugins = list( + map( + plugin_signature, + plugin_manager().get_implementations(octoprint.plugin.TemplatePlugin), + ) + ) + asset_plugins = list( + map( + plugin_signature, + plugin_manager().get_implementations(octoprint.plugin.AssetPlugin), + ) + ) + ui_plugins = sorted(set(template_plugins + asset_plugins)) - import hashlib - plugin_hash = hashlib.sha1() - plugin_hash.update(",".join(ui_plugins).encode('utf-8')) - return plugin_hash.hexdigest() + import hashlib + + plugin_hash = hashlib.sha1() + plugin_hash.update(",".join(ui_plugins).encode("utf-8")) + return plugin_hash.hexdigest() diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index 1cd854412..a50889de7 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -4,7 +4,7 @@ from __future__ import absolute_import, division, print_function, unicode_litera from flask import make_response __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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 tornado.web @@ -44,1537 +44,1807 @@ from cachelib import BaseCache from past.builtins import basestring, long try: - from os import scandir, walk + from os import scandir, walk except ImportError: - from scandir import scandir, walk + from scandir import scandir, walk + +# ~~ monkey patching -#~~ monkey patching def enable_additional_translations(default_locale="en", additional_folders=None): - import os - from flask import _request_ctx_stack - from babel import support, Locale - import flask_babel + import os + from flask import _request_ctx_stack + from babel import support, Locale + import flask_babel - if additional_folders is None: - additional_folders = [] + if additional_folders is None: + additional_folders = [] - logger = logging.getLogger(__name__) + logger = logging.getLogger(__name__) - def fixed_list_translations(self): - """Returns a list of all the locales translations exist for. The - list returned will be filled with actual locale objects and not just - strings. - """ - def list_translations(dirname): - if not os.path.isdir(dirname): - return [] - result = [] - for entry in scandir(dirname): - locale_dir = os.path.join(entry.path, 'LC_MESSAGES') - if not os.path.isdir(locale_dir): - continue - if any(filter(lambda x: x.name.endswith('.mo'), scandir(locale_dir))): - result.append(Locale.parse(entry.name)) - return result + def fixed_list_translations(self): + """Returns a list of all the locales translations exist for. The + list returned will be filled with actual locale objects and not just + strings. + """ - dirs = additional_folders + [os.path.join(self.app.root_path, 'translations')] + def list_translations(dirname): + if not os.path.isdir(dirname): + return [] + result = [] + for entry in scandir(dirname): + locale_dir = os.path.join(entry.path, "LC_MESSAGES") + if not os.path.isdir(locale_dir): + continue + if any(filter(lambda x: x.name.endswith(".mo"), scandir(locale_dir))): + result.append(Locale.parse(entry.name)) + return result - # translations from plugins - plugins = octoprint.plugin.plugin_manager().enabled_plugins - for name, plugin in plugins.items(): - plugin_translation_dir = os.path.join(plugin.location, 'translations') - if not os.path.isdir(plugin_translation_dir): - continue - dirs.append(plugin_translation_dir) + dirs = additional_folders + [os.path.join(self.app.root_path, "translations")] - result = [Locale.parse(default_locale)] + # translations from plugins + plugins = octoprint.plugin.plugin_manager().enabled_plugins + for name, plugin in plugins.items(): + plugin_translation_dir = os.path.join(plugin.location, "translations") + if not os.path.isdir(plugin_translation_dir): + continue + dirs.append(plugin_translation_dir) - for dir in dirs: - result += list_translations(dir) - return result + result = [Locale.parse(default_locale)] - def fixed_get_translations(): - """Returns the correct gettext translations that should be used for - this request. This will never fail and return a dummy translation - object if used outside of the request or if a translation cannot be - found. - """ - ctx = _request_ctx_stack.top - if ctx is None: - return None - translations = getattr(ctx, 'babel_translations', None) - if translations is None: - locale = flask_babel.get_locale() - translations = support.Translations() + for dir in dirs: + result += list_translations(dir) + return result - if str(locale) != default_locale: - # plugin translations - plugins = octoprint.plugin.plugin_manager().enabled_plugins - for name, plugin in plugins.items(): - dirs = list(map(lambda x: os.path.join(x, "_plugins", name), additional_folders)) + [os.path.join(plugin.location, 'translations')] - for dirname in dirs: - if not os.path.isdir(dirname): - continue + def fixed_get_translations(): + """Returns the correct gettext translations that should be used for + this request. This will never fail and return a dummy translation + object if used outside of the request or if a translation cannot be + found. + """ + ctx = _request_ctx_stack.top + if ctx is None: + return None + translations = getattr(ctx, "babel_translations", None) + if translations is None: + locale = flask_babel.get_locale() + translations = support.Translations() - try: - plugin_translations = support.Translations.load(dirname, [locale]) - except Exception: - logger.exception("Error while trying to load translations for plugin {name}".format(**locals())) - else: - if isinstance(plugin_translations, support.Translations): - translations = translations.merge(plugin_translations) - logger.debug("Using translation plugin folder {dirname} from plugin {name} for locale {locale}".format(**locals())) - break - else: - logger.debug("No translations for locale {locale} from plugin {name}".format(**locals())) + if str(locale) != default_locale: + # plugin translations + plugins = octoprint.plugin.plugin_manager().enabled_plugins + for name, plugin in plugins.items(): + dirs = ( + list( + map( + lambda x: os.path.join(x, "_plugins", name), + additional_folders, + ) + ) + + [os.path.join(plugin.location, "translations")] + ) + for dirname in dirs: + if not os.path.isdir(dirname): + continue - # core translations - dirs = additional_folders + [os.path.join(ctx.app.root_path, 'translations')] - for dirname in dirs: - core_translations = support.Translations.load(dirname, [locale]) - if isinstance(core_translations, support.Translations): - logger.debug("Using translation core folder {dirname} for locale {locale}".format(**locals())) - break - else: - logger.debug("No translations for locale {} in core folders".format(locale)) - translations = translations.merge(core_translations) + try: + plugin_translations = support.Translations.load( + dirname, [locale] + ) + except Exception: + logger.exception( + "Error while trying to load translations for plugin {name}".format( + **locals() + ) + ) + else: + if isinstance(plugin_translations, support.Translations): + translations = translations.merge(plugin_translations) + logger.debug( + "Using translation plugin folder {dirname} from plugin {name} for locale {locale}".format( + **locals() + ) + ) + break + else: + logger.debug( + "No translations for locale {locale} from plugin {name}".format( + **locals() + ) + ) - ctx.babel_translations = translations - return translations + # core translations + dirs = additional_folders + [ + os.path.join(ctx.app.root_path, "translations") + ] + for dirname in dirs: + core_translations = support.Translations.load(dirname, [locale]) + if isinstance(core_translations, support.Translations): + logger.debug( + "Using translation core folder {dirname} for locale {locale}".format( + **locals() + ) + ) + break + else: + logger.debug( + "No translations for locale {} in core folders".format(locale) + ) + translations = translations.merge(core_translations) + + ctx.babel_translations = translations + return translations + + flask_babel.Babel.list_translations = fixed_list_translations + flask_babel.get_translations = fixed_get_translations - flask_babel.Babel.list_translations = fixed_list_translations - flask_babel.get_translations = fixed_get_translations def fix_webassets_cache(): - from webassets import cache + from webassets import cache - error_logger = logging.getLogger(__name__ + ".fix_webassets_cache") + error_logger = logging.getLogger(__name__ + ".fix_webassets_cache") - def fixed_set(self, key, data): - import os - import tempfile - import pickle - import shutil + def fixed_set(self, key, data): + import os + import tempfile + import pickle + import shutil - 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)) + 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 + 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 os - import errno - import warnings - from webassets.cache import make_md5 + def fixed_get(self, key): + import os + import errno + 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 + 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 + 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() + 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 + 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 - cache.FilesystemCache.set = fixed_set - cache.FilesystemCache.get = fixed_get def fix_webassets_filtertool(): - from webassets.merge import FilterTool, log, MemoryHunk + from webassets.merge import FilterTool, log, MemoryHunk - error_logger = logging.getLogger(__name__ + ".fix_webassets_filtertool") + error_logger = logging.getLogger(__name__ + ".fix_webassets_filtertool") - def fixed_wrap_cache(self, key, func): - """Return cache value ``key``, or run ``func``. - """ - if self.cache: - if not self.no_cache_read: - log.debug('Checking cache for key %s', key) - content = self.cache.get(key) - if not content in (False, None): - log.debug('Using cached result for %s', key) - return MemoryHunk(content) + def fixed_wrap_cache(self, key, func): + """Return cache value ``key``, or run ``func``.""" + if self.cache: + if not self.no_cache_read: + log.debug("Checking cache for key %s", key) + content = self.cache.get(key) + if not content in (False, None): + log.debug("Using cached result for %s", key) + return MemoryHunk(content) - try: - content = func().getvalue() - if self.cache: - try: - log.debug('Storing result in cache with key %s', key,) - self.cache.set(key, content) - except Exception: - error_logger.exception("Got an exception while trying to save file to cache, not caching") - return MemoryHunk(content) - except Exception: - error_logger.exception("Got an exception while trying to apply filter, ignoring file") - return MemoryHunk("") + try: + content = func().getvalue() + if self.cache: + try: + log.debug( + "Storing result in cache with key %s", + key, + ) + self.cache.set(key, content) + except Exception: + error_logger.exception( + "Got an exception while trying to save file to cache, not caching" + ) + return MemoryHunk(content) + except Exception: + error_logger.exception( + "Got an exception while trying to apply filter, ignoring file" + ) + return MemoryHunk("") + + FilterTool._wrap_cache = fixed_wrap_cache - FilterTool._wrap_cache = fixed_wrap_cache 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 + 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 = (',', ':') + indent = None + separators = (",", ":") - if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] or current_app.debug: - indent = 2 - 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 + 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' - ) + return current_app.response_class( + dumps(data, indent=indent, separators=separators, allow_nan=False) + "\n", + mimetype="application/json", + ) - flask.jsonify = fixed_jsonify + flask.jsonify = fixed_jsonify + + +# ~~ WSGI environment wrapper for reverse proxying -#~~ WSGI environment wrapper for reverse proxying class ReverseProxiedEnvironment(object): + @staticmethod + def to_header_candidates(values): + if values is None: + return [] + if not isinstance(values, (list, tuple)): + values = [values] + to_wsgi_format = lambda header: "HTTP_" + header.upper().replace("-", "_") + return list(map(to_wsgi_format, values)) - @staticmethod - def to_header_candidates(values): - if values is None: - return [] - if not isinstance(values, (list, tuple)): - values = [values] - to_wsgi_format = lambda header: "HTTP_" + header.upper().replace("-", "_") - return list(map(to_wsgi_format, values)) + @staticmethod + def valid_ip(address): + import netaddr - @staticmethod - def valid_ip(address): - import netaddr - try: - netaddr.IPAddress(address) - return True - except Exception: - return False + try: + netaddr.IPAddress(address) + return True + except Exception: + return False - def __init__(self, - header_prefix=None, - header_scheme=None, - header_host=None, - header_server=None, - header_port=None, - prefix=None, - scheme=None, - host=None, - server=None, - port=None): + def __init__( + self, + header_prefix=None, + header_scheme=None, + header_host=None, + header_server=None, + header_port=None, + prefix=None, + scheme=None, + host=None, + server=None, + port=None, + ): - # sensible defaults - if header_prefix is None: - header_prefix = ["x-script-name"] - if header_scheme is None: - header_scheme = ["x-forwarded-proto", "x-scheme"] - if header_host is None: - header_host = ["x-forwarded-host"] - if header_server is None: - header_server = ["x-forwarded-server"] - if header_port is None: - header_port = ["x-forwarded-port"] + # sensible defaults + if header_prefix is None: + header_prefix = ["x-script-name"] + if header_scheme is None: + header_scheme = ["x-forwarded-proto", "x-scheme"] + if header_host is None: + header_host = ["x-forwarded-host"] + if header_server is None: + header_server = ["x-forwarded-server"] + if header_port is None: + header_port = ["x-forwarded-port"] - # header candidates - self._headers_prefix = self.to_header_candidates(header_prefix) - self._headers_scheme = self.to_header_candidates(header_scheme) - self._headers_host = self.to_header_candidates(header_host) - self._headers_server = self.to_header_candidates(header_server) - self._headers_port = self.to_header_candidates(header_port) + # header candidates + self._headers_prefix = self.to_header_candidates(header_prefix) + self._headers_scheme = self.to_header_candidates(header_scheme) + self._headers_host = self.to_header_candidates(header_host) + self._headers_server = self.to_header_candidates(header_server) + self._headers_port = self.to_header_candidates(header_port) - # fallback prefix & scheme & host from config - self._fallback_prefix = prefix - self._fallback_scheme = scheme - self._fallback_host = host - self._fallback_server = server - self._fallback_port = port + # fallback prefix & scheme & host from config + self._fallback_prefix = prefix + self._fallback_scheme = scheme + self._fallback_host = host + self._fallback_server = server + self._fallback_port = port - def __call__(self, environ): - def retrieve_header(header_type): - candidates = getattr(self, "_headers_" + header_type, []) - fallback = getattr(self, "_fallback_" + header_type, None) + def __call__(self, environ): + def retrieve_header(header_type): + candidates = getattr(self, "_headers_" + header_type, []) + fallback = getattr(self, "_fallback_" + header_type, None) - for candidate in candidates: - value = environ.get(candidate, None) - if value is not None: - return value - else: - return fallback + for candidate in candidates: + value = environ.get(candidate, None) + if value is not None: + return value + else: + return fallback - def host_to_server_and_port(host, scheme): - if host is None: - return None, None + def host_to_server_and_port(host, scheme): + if host is None: + return None, None - default_port = "443" if scheme == "https" else "80" - host = host.strip() + default_port = "443" if scheme == "https" else "80" + host = host.strip() - if ":" in host: - # we might have an ipv6 address here, or a port, or both + if ":" in host: + # we might have an ipv6 address here, or a port, or both - if host[0] == "[": - # that looks like an ipv6 address with port, e.g. [fec1::1]:80 - address_end = host.find("]") - if address_end == -1: - # no ], that looks like a seriously broken address - return None, None + if host[0] == "[": + # that looks like an ipv6 address with port, e.g. [fec1::1]:80 + address_end = host.find("]") + if address_end == -1: + # no ], that looks like a seriously broken address + return None, None - # extract server ip, skip enclosing [ and ] - server = host[1:address_end] - tail = host[address_end + 1:] + # extract server ip, skip enclosing [ and ] + server = host[1:address_end] + tail = host[address_end + 1 :] - # now check if there's also a port - if len(tail) and tail[0] == ":": - # port included as well - port = tail[1:] - else: - # no port, use default one - port = default_port + # now check if there's also a port + if len(tail) and tail[0] == ":": + # port included as well + port = tail[1:] + else: + # no port, use default one + port = default_port - elif self.__class__.valid_ip(host): - # ipv6 address without port - server = host - port = default_port + elif self.__class__.valid_ip(host): + # ipv6 address without port + server = host + port = default_port - else: - # ipv4 address with port - server, port = host.rsplit(":", 1) + else: + # ipv4 address with port + server, port = host.rsplit(":", 1) - else: - server = host - port = default_port + else: + server = host + port = default_port - return server, port + return server, port - # determine prefix - prefix = retrieve_header("prefix") - if prefix is not None: - environ["SCRIPT_NAME"] = prefix - path_info = environ["PATH_INFO"] - if path_info.startswith(prefix): - environ["PATH_INFO"] = path_info[len(prefix):] + # determine prefix + prefix = retrieve_header("prefix") + if prefix is not None: + environ["SCRIPT_NAME"] = prefix + path_info = environ["PATH_INFO"] + if path_info.startswith(prefix): + environ["PATH_INFO"] = path_info[len(prefix) :] - # determine scheme - scheme = retrieve_header("scheme") - if scheme is not None and "," in scheme: - # Scheme might be something like "https,https" if doubly-reverse-proxied - # without stripping original scheme header first, make sure to only use - # the first entry in such a case. See #1391. - scheme, _ = map(lambda x: x.strip(), scheme.split(",", 1)) - if scheme is not None: - environ["wsgi.url_scheme"] = scheme + # determine scheme + scheme = retrieve_header("scheme") + if scheme is not None and "," in scheme: + # Scheme might be something like "https,https" if doubly-reverse-proxied + # without stripping original scheme header first, make sure to only use + # the first entry in such a case. See #1391. + scheme, _ = map(lambda x: x.strip(), scheme.split(",", 1)) + if scheme is not None: + environ["wsgi.url_scheme"] = scheme - # determine host - url_scheme = environ["wsgi.url_scheme"] - host = retrieve_header("host") - if host is not None: - # if we have a host, we take server_name and server_port from it - server, port = host_to_server_and_port(host, url_scheme) - environ["HTTP_HOST"] = host - environ["SERVER_NAME"] = server - environ["SERVER_PORT"] = port + # determine host + url_scheme = environ["wsgi.url_scheme"] + host = retrieve_header("host") + if host is not None: + # if we have a host, we take server_name and server_port from it + server, port = host_to_server_and_port(host, url_scheme) + environ["HTTP_HOST"] = host + environ["SERVER_NAME"] = server + environ["SERVER_PORT"] = port - elif environ.get("HTTP_HOST", None) is not None: - # if we have a Host header, we use that and make sure our server name and port properties match it - host = environ["HTTP_HOST"] - server, port = host_to_server_and_port(host, url_scheme) - environ["SERVER_NAME"] = server - environ["SERVER_PORT"] = port + elif environ.get("HTTP_HOST", None) is not None: + # if we have a Host header, we use that and make sure our server name and port properties match it + host = environ["HTTP_HOST"] + server, port = host_to_server_and_port(host, url_scheme) + environ["SERVER_NAME"] = server + environ["SERVER_PORT"] = port - else: - # else we take a look at the server and port headers and if we have - # something there we derive the host from it + else: + # else we take a look at the server and port headers and if we have + # something there we derive the host from it - # determine server - should usually not be used - server = retrieve_header("server") - if server is not None: - environ["SERVER_NAME"] = server + # determine server - should usually not be used + server = retrieve_header("server") + if server is not None: + environ["SERVER_NAME"] = server - # determine port - should usually not be used - port = retrieve_header("port") - if port is not None: - environ["SERVER_PORT"] = port + # determine port - should usually not be used + port = retrieve_header("port") + if port is not None: + environ["SERVER_PORT"] = port - # reconstruct host header - if url_scheme == "http" and environ["SERVER_PORT"] == "80" or url_scheme == "https" and environ["SERVER_PORT"] == "443": - # default port for scheme, can be skipped - environ["HTTP_HOST"] = environ["SERVER_NAME"] - else: - server_name_component = environ["SERVER_NAME"] - if ":" in server_name_component and self.__class__.valid_ip(server_name_component): - # this is an ipv6 address, we need to wrap that in [ and ] before appending the port - server_name_component = "[" + server_name_component + "]" + # reconstruct host header + if ( + url_scheme == "http" + and environ["SERVER_PORT"] == "80" + or url_scheme == "https" + and environ["SERVER_PORT"] == "443" + ): + # default port for scheme, can be skipped + environ["HTTP_HOST"] = environ["SERVER_NAME"] + else: + server_name_component = environ["SERVER_NAME"] + if ":" in server_name_component and self.__class__.valid_ip( + server_name_component + ): + # this is an ipv6 address, we need to wrap that in [ and ] before appending the port + server_name_component = "[" + server_name_component + "]" - environ["HTTP_HOST"] = server_name_component + ":" + environ["SERVER_PORT"] + environ["HTTP_HOST"] = ( + server_name_component + ":" + environ["SERVER_PORT"] + ) - # call wrapped app with rewritten environment - return environ + # call wrapped app with rewritten environment + return environ -#~~ request and response versions + +# ~~ request and response versions from werkzeug.utils import cached_property + class OctoPrintFlaskRequest(flask.Request): - environment_wrapper = staticmethod(lambda x: x) + environment_wrapper = staticmethod(lambda x: x) - def __init__(self, environ, *args, **kwargs): - # apply environment wrapper to provided WSGI environment - flask.Request.__init__(self, self.environment_wrapper(environ), *args, **kwargs) + def __init__(self, environ, *args, **kwargs): + # apply environment wrapper to provided WSGI environment + flask.Request.__init__(self, self.environment_wrapper(environ), *args, **kwargs) - @cached_property - def cookies(self): - # strip cookie_suffix from all cookies in the request, return result - cookies = flask.Request.cookies.__get__(self) + @cached_property + def cookies(self): + # strip cookie_suffix from all cookies in the request, return result + cookies = flask.Request.cookies.__get__(self) - result = {} - desuffixed = {} - for key, value in cookies.items(): - if key.endswith(self.cookie_suffix): - desuffixed[key[:-len(self.cookie_suffix)]] = value - else: - result[key] = value + result = {} + desuffixed = {} + for key, value in cookies.items(): + if key.endswith(self.cookie_suffix): + desuffixed[key[: -len(self.cookie_suffix)]] = value + else: + result[key] = value - result.update(desuffixed) - return result + result.update(desuffixed) + return result - @cached_property - def server_name(self): - """Short cut to the request's server name header""" - return self.environ.get("SERVER_NAME") + @cached_property + def server_name(self): + """Short cut to the request's server name header""" + return self.environ.get("SERVER_NAME") - @cached_property - def server_port(self): - """Short cut to the request's server port header""" - return self.environ.get("SERVER_PORT") + @cached_property + def server_port(self): + """Short cut to the request's server port header""" + return self.environ.get("SERVER_PORT") - @cached_property - def cookie_suffix(self): - """ - Request specific suffix for set and read cookies + @cached_property + def cookie_suffix(self): + """ + Request specific suffix for set and read cookies - We need this because cookies are not port-specific and we don't want to overwrite our - session and other cookies from one OctoPrint instance on our machine with those of another - one who happens to listen on the same address albeit a different port or script root. - """ - result = "_P" + self.server_port - if self.script_root: - return result + "_R" + self.script_root.replace("/", "|") - return result + We need this because cookies are not port-specific and we don't want to overwrite our + session and other cookies from one OctoPrint instance on our machine with those of another + one who happens to listen on the same address albeit a different port or script root. + """ + result = "_P" + self.server_port + if self.script_root: + return result + "_R" + self.script_root.replace("/", "|") + return result class OctoPrintFlaskResponse(flask.Response): - def set_cookie(self, key, *args, **kwargs): - # restrict cookie path to script root - kwargs["path"] = flask.request.script_root + kwargs.get("path", "/") + def set_cookie(self, key, *args, **kwargs): + # restrict cookie path to script root + kwargs["path"] = flask.request.script_root + kwargs.get("path", "/") - # set same-site header - samesite = settings().get(["server", "cookies", "samesite"]) - if samesite is not None: - samesite = samesite.lower() - if samesite == "none": - samesite = None - if samesite not in (None, "strict", "lax"): - samesite = None - kwargs["samesite"] = samesite + # set same-site header + samesite = settings().get(["server", "cookies", "samesite"]) + if samesite is not None: + samesite = samesite.lower() + if samesite == "none": + samesite = None + if samesite not in (None, "strict", "lax"): + samesite = None + kwargs["samesite"] = samesite - # set secure if necessary - kwargs["secure"] = settings().getBoolean(["server", "cookies", "secure"]) + # set secure if necessary + kwargs["secure"] = settings().getBoolean(["server", "cookies", "secure"]) - # add request specific cookie suffix to name - flask.Response.set_cookie(self, key + flask.request.cookie_suffix, *args, **kwargs) + # add request specific cookie suffix to name + flask.Response.set_cookie( + self, key + flask.request.cookie_suffix, *args, **kwargs + ) - def delete_cookie(self, key, path='/', domain=None): - flask.Response.delete_cookie(self, key, path=path, domain=domain) + def delete_cookie(self, key, path="/", domain=None): + flask.Response.delete_cookie(self, key, path=path, domain=domain) - # we also still might have a cookie left over from before we started prefixing, delete that manually - # without any pre processing (no path prefix, no key suffix) - flask.Response.set_cookie(self, key, expires=0, max_age=0, path=path, domain=domain) + # we also still might have a cookie left over from before we started prefixing, delete that manually + # without any pre processing (no path prefix, no key suffix) + flask.Response.set_cookie( + self, key, expires=0, max_age=0, path=path, domain=domain + ) class OctoPrintSessionInterface(flask.sessions.SecureCookieSessionInterface): + def should_set_cookie(self, app, session): + return flask.request.endpoint != "static" - def should_set_cookie(self, app, session): - return flask.request.endpoint != "static" - - def save_session(self, app, session, response): - if flask.g.get("login_via_apikey", False): - return - return super(OctoPrintSessionInterface, self).save_session(app, session, response) + def save_session(self, app, session, response): + if flask.g.get("login_via_apikey", False): + return + return super(OctoPrintSessionInterface, self).save_session(app, session, response) -#~~ passive login helper +# ~~ passive login helper _cached_local_networks = None + + def _local_networks(): - global _cached_local_networks + global _cached_local_networks - if _cached_local_networks is None: - logger = logging.getLogger(__name__) - local_networks = netaddr.IPSet([]) - for entry in settings().get(["accessControl", "localNetworks"]): - network = netaddr.IPNetwork(entry) - local_networks.add(network) - logger.debug("Added network {} to localNetworks".format(network)) + if _cached_local_networks is None: + logger = logging.getLogger(__name__) + local_networks = netaddr.IPSet([]) + for entry in settings().get(["accessControl", "localNetworks"]): + network = netaddr.IPNetwork(entry) + local_networks.add(network) + logger.debug("Added network {} to localNetworks".format(network)) - if network.version == 4: - network_v6 = network.ipv6() - local_networks.add(network_v6) - logger.debug("Also added v6 representation of v4 network {} = {} to localNetworks".format(network, network_v6)) + if network.version == 4: + network_v6 = network.ipv6() + local_networks.add(network_v6) + logger.debug( + "Also added v6 representation of v4 network {} = {} to localNetworks".format( + network, network_v6 + ) + ) - _cached_local_networks = local_networks + _cached_local_networks = local_networks - return _cached_local_networks + return _cached_local_networks def passive_login(): - logger = logging.getLogger(__name__) + logger = logging.getLogger(__name__) - user = flask_login.current_user + user = flask_login.current_user - remote_address = get_remote_address(flask.request) - ip_check_enabled = settings().getBoolean(["server", "ipCheck", "enabled"]) - ip_check_trusted = settings().get(["server", "ipCheck", "trustedSubnets"]) + remote_address = get_remote_address(flask.request) + ip_check_enabled = settings().getBoolean(["server", "ipCheck", "enabled"]) + ip_check_trusted = settings().get(["server", "ipCheck", "trustedSubnets"]) - if isinstance(user, LocalProxy): - # noinspection PyProtectedMember - user = user._get_current_object() + if isinstance(user, LocalProxy): + # noinspection PyProtectedMember + user = user._get_current_object() - def login(u): - # login known user - if not u.is_anonymous: - u = octoprint.server.userManager.login_user(u) - flask_login.login_user(u) - flask_principal.identity_changed.send(flask.current_app._get_current_object(), - identity=flask_principal.Identity(u.get_id())) - if hasattr(u, "session"): - flask.session["usersession.id"] = u.session - flask.g.user = u + def login(u): + # login known user + if not u.is_anonymous: + u = octoprint.server.userManager.login_user(u) + flask_login.login_user(u) + flask_principal.identity_changed.send( + flask.current_app._get_current_object(), + identity=flask_principal.Identity(u.get_id()), + ) + if hasattr(u, "session"): + flask.session["usersession.id"] = u.session + flask.g.user = u - eventManager().fire(Events.USER_LOGGED_IN, payload={"username": u.get_id()}) + eventManager().fire(Events.USER_LOGGED_IN, payload={"username": u.get_id()}) - return u + return u - def determine_user(u): - if not u.is_anonymous and u.is_active: - # known active user - logger.info("Passively logging in user {} from {}".format(u.get_id(), remote_address)) + def determine_user(u): + if not u.is_anonymous and u.is_active: + # known active user + logger.info( + "Passively logging in user {} from {}".format(u.get_id(), remote_address) + ) - elif settings().getBoolean(["accessControl", "autologinLocal"]) \ - and settings().get(["accessControl", "autologinAs"]) is not None \ - and settings().get(["accessControl", "localNetworks"]) is not None \ - and not "active_logout" in flask.request.cookies \ - and remote_address: - # attempt local autologin - autologin_as = settings().get(["accessControl", "autologinAs"]) - local_networks = _local_networks() - logger.debug("Checking if remote address {} is in localNetworks ({!r})".format(remote_address, local_networks)) + elif ( + settings().getBoolean(["accessControl", "autologinLocal"]) + and settings().get(["accessControl", "autologinAs"]) is not None + and settings().get(["accessControl", "localNetworks"]) is not None + and not "active_logout" in flask.request.cookies + and remote_address + ): + # attempt local autologin + autologin_as = settings().get(["accessControl", "autologinAs"]) + local_networks = _local_networks() + logger.debug( + "Checking if remote address {} is in localNetworks ({!r})".format( + remote_address, local_networks + ) + ) - try: - if netaddr.IPAddress(remote_address) in local_networks: - autologin_user = octoprint.server.userManager.find_user(autologin_as) - if autologin_user is not None and autologin_user.is_active: - logger.info("Passively logging in user {} from {} via autologin".format(autologin_as, remote_address)) - flask.session["login_mechanism"] = "autologin" - return autologin_user - except Exception: - logger.exception("Could not autologin user {} from {} for networks {}".format(autologin_as, remote_address, local_networks)) + try: + if netaddr.IPAddress(remote_address) in local_networks: + autologin_user = octoprint.server.userManager.find_user(autologin_as) + if autologin_user is not None and autologin_user.is_active: + logger.info( + "Passively logging in user {} from {} via autologin".format( + autologin_as, remote_address + ) + ) + flask.session["login_mechanism"] = "autologin" + return autologin_user + except Exception: + logger.exception( + "Could not autologin user {} from {} for networks {}".format( + autologin_as, remote_address, local_networks + ) + ) - if not u.is_active: - # inactive user, switch to anonymous - u = octoprint.server.userManager.anonymous_user_factory() + if not u.is_active: + # inactive user, switch to anonymous + u = octoprint.server.userManager.anonymous_user_factory() - return u + return u - user = login(determine_user(user)) - response = user.as_dict() - response["_is_external_client"] = ip_check_enabled and not is_lan_address(remote_address, - additional_private=ip_check_trusted) - if flask.session.get("login_mechanism") is not None: - response["_login_mechanism"] = flask.session.get("login_mechanism") - return flask.jsonify(response) + user = login(determine_user(user)) + response = user.as_dict() + response["_is_external_client"] = ip_check_enabled and not is_lan_address( + remote_address, additional_private=ip_check_trusted + ) + if flask.session.get("login_mechanism") is not None: + response["_login_mechanism"] = flask.session.get("login_mechanism") + return flask.jsonify(response) -#~~ cache decorator for cacheable views +# ~~ cache decorator for cacheable views + class LessSimpleCache(BaseCache): - """ - Slightly improved version of :class:`SimpleCache`. + """ + Slightly improved version of :class:`SimpleCache`. - Setting ``default_timeout`` or ``timeout`` to ``-1`` will have no timeout be applied at all. - """ + Setting ``default_timeout`` or ``timeout`` to ``-1`` will have no timeout be applied at all. + """ - def __init__(self, threshold=500, default_timeout=300): - BaseCache.__init__(self, default_timeout=default_timeout) - self._mutex = threading.RLock() - self._cache = {} - self._bypassed = set() - self.clear = self._cache.clear - self._threshold = threshold + def __init__(self, threshold=500, default_timeout=300): + BaseCache.__init__(self, default_timeout=default_timeout) + self._mutex = threading.RLock() + self._cache = {} + self._bypassed = set() + self.clear = self._cache.clear + self._threshold = threshold - def _prune(self): - if self.over_threshold(): - now = time.time() - for idx, (key, (expires, _)) in enumerate(self._cache.items()): - if expires is not None and expires <= now or idx % 3 == 0: - with self._mutex: - self._cache.pop(key, None) + def _prune(self): + if self.over_threshold(): + now = time.time() + for idx, (key, (expires, _)) in enumerate(self._cache.items()): + if expires is not None and expires <= now or idx % 3 == 0: + with self._mutex: + self._cache.pop(key, None) - def get(self, key): - import pickle - now = time.time() - with self._mutex: - expires, value = self._cache.get(key, (0, None)) - if expires is None or expires > now: - return pickle.loads(value) + def get(self, key): + import pickle - def set(self, key, value, timeout=None): - import pickle + now = time.time() + with self._mutex: + expires, value = self._cache.get(key, (0, None)) + if expires is None or expires > now: + return pickle.loads(value) - with self._mutex: - self._prune() - self._cache[key] = (self.calculate_timeout(timeout=timeout), - pickle.dumps(value, pickle.HIGHEST_PROTOCOL)) - if key in self._bypassed: - self._bypassed.remove(key) + def set(self, key, value, timeout=None): + import pickle - def add(self, key, value, timeout=None): - with self._mutex: - self.set(key, value, timeout=None) - self._cache.setdefault(key, self._cache[key]) + with self._mutex: + self._prune() + self._cache[key] = ( + self.calculate_timeout(timeout=timeout), + pickle.dumps(value, pickle.HIGHEST_PROTOCOL), + ) + if key in self._bypassed: + self._bypassed.remove(key) - def delete(self, key): - with self._mutex: - self._cache.pop(key, None) + def add(self, key, value, timeout=None): + with self._mutex: + self.set(key, value, timeout=None) + self._cache.setdefault(key, self._cache[key]) - def calculate_timeout(self, timeout=None): - if timeout is None: - timeout = self.default_timeout - if timeout == -1: - return None - return time.time() + timeout + def delete(self, key): + with self._mutex: + self._cache.pop(key, None) - def over_threshold(self): - if self._threshold is None: - return False - with self._mutex: - return len(self._cache) > self._threshold + def calculate_timeout(self, timeout=None): + if timeout is None: + timeout = self.default_timeout + if timeout == -1: + return None + return time.time() + timeout - def __getitem__(self, key): - return self.get(key) + def over_threshold(self): + if self._threshold is None: + return False + with self._mutex: + return len(self._cache) > self._threshold - def __setitem__(self, key, value): - return self.set(key, value) + def __getitem__(self, key): + return self.get(key) - def __delitem__(self, key): - return self.delete(key) + def __setitem__(self, key, value): + return self.set(key, value) - def __contains__(self, key): - with self._mutex: - return key in self._cache + def __delitem__(self, key): + return self.delete(key) - def set_bypassed(self, key): - with self._mutex: - self._bypassed.add(key) + def __contains__(self, key): + with self._mutex: + return key in self._cache + + def set_bypassed(self, key): + with self._mutex: + self._bypassed.add(key) + + def is_bypassed(self, key): + with self._mutex: + return key in self._bypassed - def is_bypassed(self, key): - with self._mutex: - return key in self._bypassed _cache = LessSimpleCache() -def cached(timeout=5 * 60, key=lambda: "view:%s" % flask.request.path, unless=None, refreshif=None, unless_response=None): - def decorator(f): - @functools.wraps(f) - def decorated_function(*args, **kwargs): - logger = logging.getLogger(__name__) - cache_key = key() +def cached( + timeout=5 * 60, + key=lambda: "view:%s" % flask.request.path, + unless=None, + refreshif=None, + unless_response=None, +): + def decorator(f): + @functools.wraps(f) + def decorated_function(*args, **kwargs): + logger = logging.getLogger(__name__) - def f_with_duration(*args, **kwargs): - start_time = time.time() - try: - return f(*args, **kwargs) - finally: - elapsed = time.time() - start_time - logger.debug( - "Needed {elapsed:.2f}s to render {path} (key: {key})".format(elapsed=elapsed, - path=flask.request.path, - key=cache_key)) + cache_key = key() - # bypass the cache if "unless" condition is true - if callable(unless) and unless(): - logger.debug("Cache for {path} bypassed, calling wrapped function".format(path=flask.request.path)) - _cache.set_bypassed(cache_key) - return f_with_duration(*args, **kwargs) + def f_with_duration(*args, **kwargs): + start_time = time.time() + try: + return f(*args, **kwargs) + finally: + elapsed = time.time() - start_time + logger.debug( + "Needed {elapsed:.2f}s to render {path} (key: {key})".format( + elapsed=elapsed, path=flask.request.path, key=cache_key + ) + ) - # also bypass the cache if it's disabled completely - if not settings().getBoolean(["devel", "cache", "enabled"]): - logger.debug("Cache for {path} disabled, calling wrapped function".format(path=flask.request.path)) - _cache.set_bypassed(cache_key) - return f_with_duration(*args, **kwargs) + # bypass the cache if "unless" condition is true + if callable(unless) and unless(): + logger.debug( + "Cache for {path} bypassed, calling wrapped function".format( + path=flask.request.path + ) + ) + _cache.set_bypassed(cache_key) + return f_with_duration(*args, **kwargs) - rv = _cache.get(cache_key) + # also bypass the cache if it's disabled completely + if not settings().getBoolean(["devel", "cache", "enabled"]): + logger.debug( + "Cache for {path} disabled, calling wrapped function".format( + path=flask.request.path + ) + ) + _cache.set_bypassed(cache_key) + return f_with_duration(*args, **kwargs) - # only take the value from the cache if we are not required to refresh it from the wrapped function - if rv is not None and (not callable(refreshif) or not refreshif(rv)): - logger.debug("Serving entry for {path} from cache (key: {key})".format(path=flask.request.path, key=cache_key)) - if not "X-From-Cache" in rv.headers: - rv.headers["X-From-Cache"] = "true" - return rv + rv = _cache.get(cache_key) - # get value from wrapped function - logger.debug("No cache entry or refreshing cache for {path} (key: {key}), calling wrapped function".format(path=flask.request.path, key=cache_key)) - rv = f_with_duration(*args, **kwargs) + # only take the value from the cache if we are not required to refresh it from the wrapped function + if rv is not None and (not callable(refreshif) or not refreshif(rv)): + logger.debug( + "Serving entry for {path} from cache (key: {key})".format( + path=flask.request.path, key=cache_key + ) + ) + if not "X-From-Cache" in rv.headers: + rv.headers["X-From-Cache"] = "true" + return rv - # do not store if the "unless_response" condition is true - if callable(unless_response) and unless_response(rv): - logger.debug("Not caching result for {path} (key: {key}), bypassed".format(path=flask.request.path, key=cache_key)) - _cache.set_bypassed(cache_key) - return rv + # get value from wrapped function + logger.debug( + "No cache entry or refreshing cache for {path} (key: {key}), calling wrapped function".format( + path=flask.request.path, key=cache_key + ) + ) + rv = f_with_duration(*args, **kwargs) - # store it in the cache - _cache.set(cache_key, rv, timeout=timeout) + # do not store if the "unless_response" condition is true + if callable(unless_response) and unless_response(rv): + logger.debug( + "Not caching result for {path} (key: {key}), bypassed".format( + path=flask.request.path, key=cache_key + ) + ) + _cache.set_bypassed(cache_key) + return rv - return rv + # store it in the cache + _cache.set(cache_key, rv, timeout=timeout) - return decorated_function + return rv + + return decorated_function + + return decorator - return decorator def is_in_cache(key=lambda: "view:%s" % flask.request.path): - if callable(key): - key = key() - return key in _cache + if callable(key): + key = key() + return key in _cache + def is_cache_bypassed(key=lambda: "view:%s" % flask.request.path): - if callable(key): - key = key() - return _cache.is_bypassed(key) + if callable(key): + key = key() + return _cache.is_bypassed(key) + def cache_check_headers(): - return "no-cache" in flask.request.cache_control or "no-cache" in flask.request.pragma + return "no-cache" in flask.request.cache_control or "no-cache" in flask.request.pragma + def cache_check_response_headers(response): - if not isinstance(response, flask.Response): - return False + if not isinstance(response, flask.Response): + return False - headers = response.headers + headers = response.headers - if "Cache-Control" in headers and ("no-cache" in headers["Cache-Control"] or "no-store" in headers["Cache-Control"]): - return True + if "Cache-Control" in headers and ( + "no-cache" in headers["Cache-Control"] or "no-store" in headers["Cache-Control"] + ): + return True - if "Pragma" in headers and "no-cache" in headers["Pragma"]: - return True + if "Pragma" in headers and "no-cache" in headers["Pragma"]: + return True - if "Expires" in headers and headers["Expires"] in ("0", "-1"): - return True + if "Expires" in headers and headers["Expires"] in ("0", "-1"): + return True + + return False - return False def cache_check_status_code(response, valid): - if not isinstance(response, flask.Response): - return False + if not isinstance(response, flask.Response): + return False + + if callable(valid): + return not valid(response.status_code) + else: + return response.status_code not in valid - if callable(valid): - return not valid(response.status_code) - else: - return response.status_code not in valid class PreemptiveCache(object): + def __init__(self, cachefile): + self.cachefile = cachefile + self.environment = None - def __init__(self, cachefile): - self.cachefile = cachefile - self.environment = None + self._logger = logging.getLogger(__name__ + "." + self.__class__.__name__) - self._logger = logging.getLogger(__name__ + "." + self.__class__.__name__) + self._lock = threading.RLock() - self._lock = threading.RLock() + def record(self, data, unless=None, root=None): + if callable(unless) and unless(): + return - def record(self, data, unless=None, root=None): - if callable(unless) and unless(): - return + entry_data = data + if callable(entry_data): + entry_data = entry_data() - entry_data = data - if callable(entry_data): - entry_data = entry_data() + if entry_data is not None: + if root is None: + from flask import request - if entry_data is not None: - if root is None: - from flask import request - root = request.path - self.add_data(root, entry_data) + root = request.path + self.add_data(root, entry_data) - def has_record(self, data, root=None): - if callable(data): - data = data() + def has_record(self, data, root=None): + if callable(data): + data = data() - if data is None: - return False + if data is None: + return False - if root is None: - from flask import request - root = request.path + if root is None: + from flask import request - all_data = self.get_data(root) - for existing in all_data: - if self._compare_data(data, existing): - return True + root = request.path - return False + all_data = self.get_data(root) + for existing in all_data: + if self._compare_data(data, existing): + return True - def clean_all_data(self, cleanup_function): - assert callable(cleanup_function) + return False - with self._lock: - all_data = self.get_all_data() - for root, entries in list(all_data.items()): - old_count = len(entries) - entries = cleanup_function(root, entries) - if not entries: - del all_data[root] - self._logger.debug("Removed root {} from preemptive cache".format(root)) - elif len(entries) < old_count: - all_data[root] = entries - self._logger.debug("Removed {} entries from preemptive cache for root {}".format(old_count - len(entries), root)) - self.set_all_data(all_data) + def clean_all_data(self, cleanup_function): + assert callable(cleanup_function) - return all_data + with self._lock: + all_data = self.get_all_data() + for root, entries in list(all_data.items()): + old_count = len(entries) + entries = cleanup_function(root, entries) + if not entries: + del all_data[root] + self._logger.debug( + "Removed root {} from preemptive cache".format(root) + ) + elif len(entries) < old_count: + all_data[root] = entries + self._logger.debug( + "Removed {} entries from preemptive cache for root {}".format( + old_count - len(entries), root + ) + ) + self.set_all_data(all_data) - def get_all_data(self): - import yaml + return all_data - cache_data = None - with self._lock: - try: - with io.open(self.cachefile, 'rt') as f: - cache_data = yaml.safe_load(f) - except IOError as e: - import errno - if e.errno != errno.ENOENT: - raise - except Exception: - self._logger.exception("Error while reading {}".format(self.cachefile)) + def get_all_data(self): + import yaml - if cache_data is None: - cache_data = {} + cache_data = None + with self._lock: + try: + with io.open(self.cachefile, "rt") as f: + cache_data = yaml.safe_load(f) + except IOError as e: + import errno - if not self._validate_data(cache_data): - self._logger.warning("Preemptive cache data was invalid, ignoring it") - cache_data = {} + if e.errno != errno.ENOENT: + raise + except Exception: + self._logger.exception("Error while reading {}".format(self.cachefile)) - return cache_data + if cache_data is None: + cache_data = {} - def get_data(self, root): - cache_data = self.get_all_data() - return cache_data.get(root, list()) + if not self._validate_data(cache_data): + self._logger.warning("Preemptive cache data was invalid, ignoring it") + cache_data = {} - def set_all_data(self, data): - from octoprint.util import atomic_write - import yaml + return cache_data - 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=4, allow_unicode=True) - except Exception: - self._logger.exception("Error while writing {}".format(self.cachefile)) + def get_data(self, root): + cache_data = self.get_all_data() + return cache_data.get(root, list()) - def set_data(self, root, data): - with self._lock: - all_data = self.get_all_data() - all_data[root] = data - self.set_all_data(all_data) + def set_all_data(self, data): + from octoprint.util import atomic_write + import yaml - def add_data(self, root, data): - def split_matched_and_unmatched(entry, entries): - matched = [] - unmatched = [] + 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=4, + allow_unicode=True, + ) + except Exception: + self._logger.exception("Error while writing {}".format(self.cachefile)) - for e in entries: - if self._compare_data(e, entry): - matched.append(e) - else: - unmatched.append(e) + def set_data(self, root, data): + with self._lock: + all_data = self.get_all_data() + all_data[root] = data + self.set_all_data(all_data) - return matched, unmatched + def add_data(self, root, data): + def split_matched_and_unmatched(entry, entries): + matched = [] + unmatched = [] - with self._lock: - cache_data = self.get_all_data() + for e in entries: + if self._compare_data(e, entry): + matched.append(e) + else: + unmatched.append(e) - if not root in cache_data: - cache_data[root] = [] + return matched, unmatched - existing, other = split_matched_and_unmatched(data, cache_data[root]) + with self._lock: + cache_data = self.get_all_data() - def get_newest(entries): - result = None - for entry in entries: - if "_timestamp" in entry and (result is None or ("_timestamp" in result and result["_timestamp"] < entry["_timestamp"])): - result = entry - return result + if not root in cache_data: + cache_data[root] = [] - to_persist = get_newest(existing) - if not to_persist: - import copy - to_persist = copy.deepcopy(data) - to_persist["_timestamp"] = time.time() - to_persist["_count"] = 1 - self._logger.info("Adding entry for {} and {!r}".format(root, to_persist)) - else: - to_persist["_timestamp"] = time.time() - to_persist["_count"] = to_persist.get("_count", 0) + 1 - self._logger.debug("Updating timestamp and counter for {} and {!r}".format(root, data)) + existing, other = split_matched_and_unmatched(data, cache_data[root]) - self.set_data(root, [to_persist] + other) + def get_newest(entries): + result = None + for entry in entries: + if "_timestamp" in entry and ( + result is None + or ( + "_timestamp" in result + and result["_timestamp"] < entry["_timestamp"] + ) + ): + result = entry + return result - def _compare_data(self, a, b): - from octoprint.util import dict_filter + to_persist = get_newest(existing) + if not to_persist: + import copy - def strip_ignored(d): - return dict_filter(d, lambda k, v: not k.startswith("_")) + to_persist = copy.deepcopy(data) + to_persist["_timestamp"] = time.time() + to_persist["_count"] = 1 + self._logger.info("Adding entry for {} and {!r}".format(root, to_persist)) + else: + to_persist["_timestamp"] = time.time() + to_persist["_count"] = to_persist.get("_count", 0) + 1 + self._logger.debug( + "Updating timestamp and counter for {} and {!r}".format(root, data) + ) - return set(strip_ignored(a).items()) == set(strip_ignored(b).items()) + self.set_data(root, [to_persist] + other) - def _validate_data(self, data): - if not isinstance(data, dict): - return False + def _compare_data(self, a, b): + from octoprint.util import dict_filter - for root, entries in data.items(): - if not isinstance(entries, list): - return False + def strip_ignored(d): + return dict_filter(d, lambda k, v: not k.startswith("_")) - for entry in entries: - if not self._validate_entry(entry): - return False + return set(strip_ignored(a).items()) == set(strip_ignored(b).items()) - return True + def _validate_data(self, data): + if not isinstance(data, dict): + return False - def _validate_entry(self, entry): - return isinstance(entry, dict) and "_timestamp" in entry and "_count" in entry + for root, entries in data.items(): + if not isinstance(entries, list): + return False + + for entry in entries: + if not self._validate_entry(entry): + return False + + return True + + def _validate_entry(self, entry): + return isinstance(entry, dict) and "_timestamp" in entry and "_count" in entry def preemptively_cached(cache, data, unless=None): - def decorator(f): - @functools.wraps(f) - def decorated_function(*args, **kwargs): - try: - cache.record(data, unless=unless) - except Exception: - logging.getLogger(__name__).exception("Error while recording preemptive cache entry: {!r}".format(data)) - return f(*args, **kwargs) - return decorated_function - return decorator + def decorator(f): + @functools.wraps(f) + def decorated_function(*args, **kwargs): + try: + cache.record(data, unless=unless) + except Exception: + logging.getLogger(__name__).exception( + "Error while recording preemptive cache entry: {!r}".format(data) + ) + return f(*args, **kwargs) + + return decorated_function + + return decorator def etagged(etag): - def decorator(f): - @functools.wraps(f) - def decorated_function(*args, **kwargs): - rv = f(*args, **kwargs) - if isinstance(rv, flask.Response): - try: - result = etag - if callable(result): - result = result(rv) - if result: - rv.set_etag(result) - except Exception: - logging.getLogger(__name__).exception("Error while calculating the etag value for response {!r}".format(rv)) - return rv - return decorated_function - return decorator + def decorator(f): + @functools.wraps(f) + def decorated_function(*args, **kwargs): + rv = f(*args, **kwargs) + if isinstance(rv, flask.Response): + try: + result = etag + if callable(result): + result = result(rv) + if result: + rv.set_etag(result) + except Exception: + logging.getLogger(__name__).exception( + "Error while calculating the etag value for response {!r}".format( + rv + ) + ) + return rv + + return decorated_function + + return decorator def lastmodified(date): - def decorator(f): - @functools.wraps(f) - def decorated_function(*args, **kwargs): - rv = f(*args, **kwargs) - if not "Last-Modified" in rv.headers: - try: - result = date - if callable(result): - result = result(rv) + def decorator(f): + @functools.wraps(f) + def decorated_function(*args, **kwargs): + rv = f(*args, **kwargs) + if not "Last-Modified" in rv.headers: + try: + result = date + if callable(result): + result = result(rv) - if not isinstance(result, basestring): - from werkzeug.http import http_date - result = http_date(result) + if not isinstance(result, basestring): + from werkzeug.http import http_date - if result: - rv.headers["Last-Modified"] = result - except Exception: - logging.getLogger(__name__).exception("Error while calculating the lastmodified value for response {!r}".format(rv)) - return rv - return decorated_function - return decorator + result = http_date(result) + + if result: + rv.headers["Last-Modified"] = result + except Exception: + logging.getLogger(__name__).exception( + "Error while calculating the lastmodified value for response {!r}".format( + rv + ) + ) + return rv + + return decorated_function + + return decorator def conditional(condition, met): - def decorator(f): - @functools.wraps(f) - def decorated_function(*args, **kwargs): - try: - if callable(condition) and condition(): - # condition has been met, return met-response - rv = met - if callable(met): - rv = met() - return rv - except Exception: - logging.getLogger(__name__).exception("Error while evaluating conditional {!r} or met {!r}".format(condition, met)) + def decorator(f): + @functools.wraps(f) + def decorated_function(*args, **kwargs): + try: + if callable(condition) and condition(): + # condition has been met, return met-response + rv = met + if callable(met): + rv = met() + return rv + except Exception: + logging.getLogger(__name__).exception( + "Error while evaluating conditional {!r} or met {!r}".format( + condition, met + ) + ) - # condition hasn't been met, call decorated function - return f(*args, **kwargs) - return decorated_function - return decorator + # condition hasn't been met, call decorated function + return f(*args, **kwargs) + + return decorated_function + + return decorator def with_client_revalidation(f): - @functools.wraps(f) - def decorated_function(*args, **kwargs): - r = f(*args, **kwargs) + @functools.wraps(f) + def decorated_function(*args, **kwargs): + r = f(*args, **kwargs) - if isinstance(r, flask.Response): - r = add_revalidation_response_headers(r) + if isinstance(r, flask.Response): + r = add_revalidation_response_headers(r) - return r - return decorated_function + return r + + return decorated_function -def with_revalidation_checking(etag_factory=None, - lastmodified_factory=None, - condition=None, - unless=None): - if etag_factory is None: - def etag_factory(lm=None): - return None +def with_revalidation_checking( + etag_factory=None, lastmodified_factory=None, condition=None, unless=None +): + if etag_factory is None: - if lastmodified_factory is None: - def lastmodified_factory(): - return None + def etag_factory(lm=None): + return None - if condition is None: - def condition(lm=None, etag=None): - if lm is None: - lm = lastmodified_factory() + if lastmodified_factory is None: - if etag is None: - etag = etag_factory(lm=lm) + def lastmodified_factory(): + return None - if flask.request.if_none_match and flask.request.if_modified_since: - # use both - return check_lastmodified(lm) and check_etag(etag) - elif flask.request.if_none_match: - # use only ETag - return check_etag(etag) - elif flask.request.if_modified_since: - # use only Last-Modified - return check_lastmodified(lm) - else: - # assume stale cache - return False + if condition is None: - if unless is None: - def unless(): - return False + def condition(lm=None, etag=None): + if lm is None: + lm = lastmodified_factory() - def decorator(f): - @functools.wraps(f) - def decorated_function(*args, **kwargs): - lm = lastmodified_factory() - etag = etag_factory(lm) + if etag is None: + etag = etag_factory(lm=lm) - if condition(lm, etag) and not unless(): - return make_response("Not Modified", 304) + if flask.request.if_none_match and flask.request.if_modified_since: + # use both + return check_lastmodified(lm) and check_etag(etag) + elif flask.request.if_none_match: + # use only ETag + return check_etag(etag) + elif flask.request.if_modified_since: + # use only Last-Modified + return check_lastmodified(lm) + else: + # assume stale cache + return False - # generate response - response = f(*args, **kwargs) + if unless is None: - # set etag header if not already set - if etag and response.get_etag()[0] is None: - response.set_etag(etag) + def unless(): + return False - # set last modified header if not already set - if lm and response.headers.get("Last-Modified", None) is None: - if not isinstance(lm, basestring): - from werkzeug.http import http_date - lm = http_date(lm) - response.headers["Last-Modified"] = lm + def decorator(f): + @functools.wraps(f) + def decorated_function(*args, **kwargs): + lm = lastmodified_factory() + etag = etag_factory(lm) - response = add_no_max_age_response_headers(response) - return response - return decorated_function - return decorator + if condition(lm, etag) and not unless(): + return make_response("Not Modified", 304) + + # generate response + response = f(*args, **kwargs) + + # set etag header if not already set + if etag and response.get_etag()[0] is None: + response.set_etag(etag) + + # set last modified header if not already set + if lm and response.headers.get("Last-Modified", None) is None: + if not isinstance(lm, basestring): + from werkzeug.http import http_date + + lm = http_date(lm) + response.headers["Last-Modified"] = lm + + response = add_no_max_age_response_headers(response) + return response + + return decorated_function + + return decorator def check_etag(etag): - if etag is None: - return False + if etag is None: + return False - return flask.request.method in ("GET", "HEAD") and \ - flask.request.if_none_match is not None and \ - etag in flask.request.if_none_match + return ( + flask.request.method in ("GET", "HEAD") + and flask.request.if_none_match is not None + and etag in flask.request.if_none_match + ) def check_lastmodified(lastmodified): - if lastmodified is None: - return False + if lastmodified is None: + return False - from datetime import datetime - if isinstance(lastmodified, (int, long, float)): - # max(86400, lastmodified) is workaround for https://bugs.python.org/issue29097, - # present in CPython 3.6.x up to 3.7.1. - # - # I think it's fair to say that we'll never encounter lastmodified values older than - # 1970-01-02 so this is a safe workaround. - lastmodified = datetime.fromtimestamp(max(86400, lastmodified)).replace(microsecond=0) + from datetime import datetime - if not isinstance(lastmodified, datetime): - raise ValueError("lastmodified must be a datetime or float or int instance but, got {} instead".format(lastmodified.__class__)) + if isinstance(lastmodified, (int, long, float)): + # max(86400, lastmodified) is workaround for https://bugs.python.org/issue29097, + # present in CPython 3.6.x up to 3.7.1. + # + # I think it's fair to say that we'll never encounter lastmodified values older than + # 1970-01-02 so this is a safe workaround. + lastmodified = datetime.fromtimestamp(max(86400, lastmodified)).replace( + microsecond=0 + ) - return flask.request.method in ("GET", "HEAD") and \ - flask.request.if_modified_since is not None and \ - lastmodified <= flask.request.if_modified_since + if not isinstance(lastmodified, datetime): + raise ValueError( + "lastmodified must be a datetime or float or int instance but, got {} instead".format( + lastmodified.__class__ + ) + ) + + return ( + flask.request.method in ("GET", "HEAD") + and flask.request.if_modified_since is not None + and lastmodified <= flask.request.if_modified_since + ) def add_revalidation_response_headers(response): - import werkzeug.http + import werkzeug.http - cache_control = werkzeug.http.parse_dict_header(response.headers.get("Cache-Control", "")) - if "no-cache" not in cache_control: - cache_control["no-cache"] = None - if "must-revalidate" not in cache_control: - cache_control["must-revalidate"] = None - response.headers["Cache-Control"] = werkzeug.http.dump_header(cache_control) + cache_control = werkzeug.http.parse_dict_header( + response.headers.get("Cache-Control", "") + ) + if "no-cache" not in cache_control: + cache_control["no-cache"] = None + if "must-revalidate" not in cache_control: + cache_control["must-revalidate"] = None + response.headers["Cache-Control"] = werkzeug.http.dump_header(cache_control) - return response + return response def add_non_caching_response_headers(response): - import werkzeug.http + import werkzeug.http - cache_control = werkzeug.http.parse_dict_header(response.headers.get("Cache-Control", "")) - if "no-store" not in cache_control: - cache_control["no-store"] = None - if "no-cache" not in cache_control: - cache_control["no-cache"] = None - if "must-revalidate" not in cache_control: - cache_control["must-revalidate"] = None - if "post-check" not in cache_control or cache_control["post-check"] != "0": - cache_control["post-check"] = "0" - if "pre-check" not in cache_control or cache_control["pre-check"] != "0": - cache_control["pre-check"] = "0" - if "max-age" not in cache_control or cache_control["max-age"] != "0": - cache_control["max-age"] = "0" - response.headers["Cache-Control"] = werkzeug.http.dump_header(cache_control) + cache_control = werkzeug.http.parse_dict_header( + response.headers.get("Cache-Control", "") + ) + if "no-store" not in cache_control: + cache_control["no-store"] = None + if "no-cache" not in cache_control: + cache_control["no-cache"] = None + if "must-revalidate" not in cache_control: + cache_control["must-revalidate"] = None + if "post-check" not in cache_control or cache_control["post-check"] != "0": + cache_control["post-check"] = "0" + if "pre-check" not in cache_control or cache_control["pre-check"] != "0": + cache_control["pre-check"] = "0" + if "max-age" not in cache_control or cache_control["max-age"] != "0": + cache_control["max-age"] = "0" + response.headers["Cache-Control"] = werkzeug.http.dump_header(cache_control) - response.headers["Pragma"] = "no-cache" - response.headers["Expires"] = "-1" - return response + response.headers["Pragma"] = "no-cache" + response.headers["Expires"] = "-1" + return response def add_no_max_age_response_headers(response): - import werkzeug.http + import werkzeug.http - cache_control = werkzeug.http.parse_dict_header(response.headers.get("Cache-Control", "")) - if "max-age" not in cache_control or cache_control["max-age"] != "0": - cache_control["max-age"] = "0" - response.headers["Cache-Control"] = werkzeug.http.dump_header(cache_control) + cache_control = werkzeug.http.parse_dict_header( + response.headers.get("Cache-Control", "") + ) + if "max-age" not in cache_control or cache_control["max-age"] != "0": + cache_control["max-age"] = "0" + response.headers["Cache-Control"] = werkzeug.http.dump_header(cache_control) - return response + return response -#~~ access validators for use with tornado +# ~~ access validators for use with tornado + def permission_validator(request, permission): - """ - Validates that the given request is made by an authorized user, identified either by API key or existing Flask - session. + """ + Validates that the given request is made by an authorized user, identified either by API key or existing Flask + session. - Must be executed in an existing Flask request context! + Must be executed in an existing Flask request context! - :param request: The Flask request object - :param request: The required permission - """ + :param request: The Flask request object + :param request: The required permission + """ - user = get_flask_user_from_request(request) - if not user.has_permission(permission): - raise tornado.web.HTTPError(403) + user = get_flask_user_from_request(request) + if not user.has_permission(permission): + raise tornado.web.HTTPError(403) -@deprecated("admin_validator is deprecated, please use new permission_validator", since="") + +@deprecated( + "admin_validator is deprecated, please use new permission_validator", since="" +) def admin_validator(request): - from octoprint.access.permissions import Permissions - return permission_validator(request, Permissions.ADMIN) + from octoprint.access.permissions import Permissions + + return permission_validator(request, Permissions.ADMIN) + @deprecated("user_validator is deprecated, please use new permission_validator", since="") def user_validator(request): - return True + return True + def get_flask_user_from_request(request): - """ - Retrieves the current flask user from the request context. Uses API key if available, otherwise the current - user session if available. + """ + Retrieves the current flask user from the request context. Uses API key if available, otherwise the current + user session if available. - :param request: flask request from which to retrieve the current user - :return: the user (might be an anonymous user) - """ - import octoprint.server.util - import flask_login + :param request: flask request from which to retrieve the current user + :return: the user (might be an anonymous user) + """ + import octoprint.server.util + import flask_login - user = None + user = None - apikey = octoprint.server.util.get_api_key(request) - if apikey is not None: - # user from api key? - user = octoprint.server.util.get_user_for_apikey(apikey) + apikey = octoprint.server.util.get_api_key(request) + if apikey is not None: + # user from api key? + user = octoprint.server.util.get_user_for_apikey(apikey) - if user is None: - # user still None -> current session user - user = flask_login.current_user + if user is None: + # user still None -> current session user + user = flask_login.current_user - if user is None: - # user still None -> anonymous - from octoprint.server import userManager - user = userManager.anonymous_user_factory() + if user is None: + # user still None -> anonymous + from octoprint.server import userManager - return user + user = userManager.anonymous_user_factory() + + return user def redirect_to_tornado(request, target, code=302): - """ - Redirects from flask to tornado, flask request context must exist. + """ + Redirects from flask to tornado, flask request context must exist. - :param request: - :param target: - :param code: - :return: - """ + :param request: + :param target: + :param code: + :return: + """ - import flask + import flask - requestUrl = request.url - appBaseUrl = requestUrl[:requestUrl.find(flask.url_for("index") + "api")] + requestUrl = request.url + appBaseUrl = requestUrl[: requestUrl.find(flask.url_for("index") + "api")] - redirectUrl = appBaseUrl + target - if "?" in requestUrl: - fragment = requestUrl[requestUrl.rfind("?"):] - redirectUrl += fragment - return flask.redirect(redirectUrl, code=code) + redirectUrl = appBaseUrl + target + if "?" in requestUrl: + fragment = requestUrl[requestUrl.rfind("?") :] + redirectUrl += fragment + return flask.redirect(redirectUrl, code=code) def restricted_access(func): - """ - This combines :py:func:`no_firstrun_access` and ``login_required``. - """ - @functools.wraps(func) - def decorated_view(*args, **kwargs): - return no_firstrun_access(flask_login.login_required(func))(*args, **kwargs) - return decorated_view + """ + This combines :py:func:`no_firstrun_access` and ``login_required``. + """ + + @functools.wraps(func) + def decorated_view(*args, **kwargs): + return no_firstrun_access(flask_login.login_required(func))(*args, **kwargs) + + return decorated_view def no_firstrun_access(func): - """ - If you decorate a view with this, it will ensure that first setup has been - done for OctoPrint's Access Control. + """ + If you decorate a view with this, it will ensure that first setup has been + done for OctoPrint's Access Control. - If OctoPrint's Access Control has not been setup yet (indicated by the "firstRun" - flag from the settings being set to True and the userManager not indicating - that it's user database has been customized from default), the decorator - will cause a HTTP 403 status code to be returned by the decorated resource. - """ - @functools.wraps(func) - def decorated_view(*args, **kwargs): - # if OctoPrint hasn't been set up yet, abort - if settings().getBoolean(["server", "firstRun"]) and settings().getBoolean(["accessControl", "enabled"]) and (octoprint.server.userManager is None or not octoprint.server.userManager.has_been_customized()): - return flask.make_response("OctoPrint isn't setup yet", 403) - return func(*args, **kwargs) + If OctoPrint's Access Control has not been setup yet (indicated by the "firstRun" + flag from the settings being set to True and the userManager not indicating + that it's user database has been customized from default), the decorator + will cause a HTTP 403 status code to be returned by the decorated resource. + """ - return decorated_view + @functools.wraps(func) + def decorated_view(*args, **kwargs): + # if OctoPrint hasn't been set up yet, abort + if ( + settings().getBoolean(["server", "firstRun"]) + and settings().getBoolean(["accessControl", "enabled"]) + and ( + octoprint.server.userManager is None + or not octoprint.server.userManager.has_been_customized() + ) + ): + return flask.make_response("OctoPrint isn't setup yet", 403) + return func(*args, **kwargs) + + return decorated_view def firstrun_only_access(func): - """ - If you decorate a view with this, it will ensure that first setup has _not_ been - done for OctoPrint's Access Control. Otherwise it - will cause a HTTP 403 status code to be returned by the decorated resource. - """ - @functools.wraps(func) - def decorated_view(*args, **kwargs): - # if OctoPrint has been set up yet, abort - if settings().getBoolean(["server", "firstRun"]) and (octoprint.server.userManager is None or not octoprint.server.userManager.has_been_customized()): - return func(*args, **kwargs) - else: - return flask.make_response("OctoPrint is already setup, this resource is not longer available.", 403) + """ + If you decorate a view with this, it will ensure that first setup has _not_ been + done for OctoPrint's Access Control. Otherwise it + will cause a HTTP 403 status code to be returned by the decorated resource. + """ - return decorated_view + @functools.wraps(func) + def decorated_view(*args, **kwargs): + # if OctoPrint has been set up yet, abort + if settings().getBoolean(["server", "firstRun"]) and ( + octoprint.server.userManager is None + or not octoprint.server.userManager.has_been_customized() + ): + return func(*args, **kwargs) + else: + return flask.make_response( + "OctoPrint is already setup, this resource is not longer available.", 403 + ) + + return decorated_view def get_remote_address(request): - forwardedFor = request.headers.get("X-Forwarded-For", None) - if forwardedFor is not None: - return forwardedFor.split(",")[0] - return request.remote_addr + forwardedFor = request.headers.get("X-Forwarded-For", None) + if forwardedFor is not None: + return forwardedFor.split(",")[0] + return request.remote_addr def get_json_command_from_request(request, valid_commands): - content_type = request.headers.get("Content-Type", None) - if content_type is None or not "application/json" in content_type: - return None, None, make_response("Expected content-type JSON", 400) + content_type = request.headers.get("Content-Type", None) + if content_type is None or not "application/json" in content_type: + return None, None, make_response("Expected content-type JSON", 400) - data = request.get_json() - if data is None: - return None, None, make_response("Malformed JSON body or wrong content-type in request", 400) - if not "command" in data or not data["command"] in valid_commands: - return None, None, make_response("Expected valid command", 400) + data = request.get_json() + if data is None: + return ( + None, + None, + make_response("Malformed JSON body or wrong content-type in request", 400), + ) + if not "command" in data or not data["command"] in valid_commands: + return None, None, make_response("Expected valid command", 400) - command = data["command"] - for parameter in valid_commands[command]: - if not parameter in data: - return None, None, make_response("Mandatory parameter %s missing for command %s" % (parameter, command), 400) + command = data["command"] + for parameter in valid_commands[command]: + if not parameter in data: + return ( + None, + None, + make_response( + "Mandatory parameter %s missing for command %s" + % (parameter, command), + 400, + ), + ) + + return command, data, None - return command, data, None ##~~ Flask-Assets resolver with plugin asset support + class PluginAssetResolver(flask_assets.FlaskResolver): + def split_prefix(self, ctx, item): + app = ctx.environment._app + if item.startswith("plugin/"): + try: + prefix, plugin, name = item.split("/", 2) + blueprint = prefix + "." + plugin - def split_prefix(self, ctx, item): - app = ctx.environment._app - if item.startswith("plugin/"): - try: - prefix, plugin, name = item.split("/", 2) - blueprint = prefix + "." + plugin + directory = flask_assets.get_static_folder(app.blueprints[blueprint]) + item = name + endpoint = blueprint + ".static" + return directory, item, endpoint + except (ValueError, KeyError): + pass - directory = flask_assets.get_static_folder(app.blueprints[blueprint]) - item = name - endpoint = blueprint + ".static" - return directory, item, endpoint - except (ValueError, KeyError): - pass + return flask_assets.FlaskResolver.split_prefix(self, ctx, item) - return flask_assets.FlaskResolver.split_prefix(self, ctx, item) + def resolve_output_to_path(self, ctx, target, bundle): + import os + + return os.path.normpath(os.path.join(ctx.environment.directory, target)) - def resolve_output_to_path(self, ctx, target, bundle): - import os - return os.path.normpath(os.path.join(ctx.environment.directory, target)) ##~~ Webassets updater that takes changes in the configuration into account + class SettingsCheckUpdater(webassets.updater.BaseUpdater): - updater = "always" + updater = "always" - def __init__(self): - self._delegate = webassets.updater.get_updater(self.__class__.updater) + def __init__(self): + self._delegate = webassets.updater.get_updater(self.__class__.updater) - def needs_rebuild(self, bundle, ctx): - return self._delegate.needs_rebuild(bundle, ctx) or self.changed_settings(ctx) + def needs_rebuild(self, bundle, ctx): + return self._delegate.needs_rebuild(bundle, ctx) or self.changed_settings(ctx) - def changed_settings(self, ctx): - import json + def changed_settings(self, ctx): + import json - if not ctx.cache: - return False + if not ctx.cache: + return False - cache_key = ('octo', 'settings') - current_hash = settings().effective_hash - cached_hash = ctx.cache.get(cache_key) - # This may seem counter-intuitive, but if no cache entry is found - # then we actually return "no update needed". This is because - # otherwise if no cache / a dummy cache is used, then we would be - # rebuilding every single time. - if not cached_hash is None: - return cached_hash != current_hash - return False + cache_key = ("octo", "settings") + current_hash = settings().effective_hash + cached_hash = ctx.cache.get(cache_key) + # This may seem counter-intuitive, but if no cache entry is found + # then we actually return "no update needed". This is because + # otherwise if no cache / a dummy cache is used, then we would be + # rebuilding every single time. + if not cached_hash is None: + return cached_hash != current_hash + return False - def build_done(self, bundle, ctx): - import json + def build_done(self, bundle, ctx): + import json - self._delegate.build_done(bundle, ctx) - if not ctx.cache: - return + self._delegate.build_done(bundle, ctx) + if not ctx.cache: + return + + cache_key = ("octo", "settings") + ctx.cache.set(cache_key, settings().effective_hash) - cache_key = ('octo', 'settings') - ctx.cache.set(cache_key, settings().effective_hash) ##~~ core assets collector def collect_core_assets(preferred_stylesheet="css"): - assets = {"js": [], - "clientjs": [], - "css": [], - "less": []} - assets["js"] = [ - 'js/app/bindings/allowbindings.js', - 'js/app/bindings/contextmenu.js', - 'js/app/bindings/copywidth.js', - 'js/app/bindings/invisible.js', - 'js/app/bindings/popover.js', - 'js/app/bindings/qrcode.js', - 'js/app/bindings/slimscrolledforeach.js', - 'js/app/bindings/toggle.js', - 'js/app/bindings/togglecontent.js', - 'js/app/bindings/valuewithinit.js', - 'js/app/viewmodels/access.js', - 'js/app/viewmodels/appearance.js', - 'js/app/viewmodels/connection.js', - 'js/app/viewmodels/control.js', - 'js/app/viewmodels/files.js', - 'js/app/viewmodels/loginstate.js', - 'js/app/viewmodels/loginui.js', - 'js/app/viewmodels/navigation.js', - 'js/app/viewmodels/printerstate.js', - 'js/app/viewmodels/printerprofiles.js', - 'js/app/viewmodels/settings.js', - 'js/app/viewmodels/slicing.js', - 'js/app/viewmodels/system.js', - 'js/app/viewmodels/temperature.js', - 'js/app/viewmodels/terminal.js', - 'js/app/viewmodels/timelapse.js', - 'js/app/viewmodels/uistate.js', - 'js/app/viewmodels/users.js', - 'js/app/viewmodels/usersettings.js', - 'js/app/viewmodels/wizard.js', - 'js/app/viewmodels/about.js' - ] + assets = {"js": [], "clientjs": [], "css": [], "less": []} + assets["js"] = [ + "js/app/bindings/allowbindings.js", + "js/app/bindings/contextmenu.js", + "js/app/bindings/copywidth.js", + "js/app/bindings/invisible.js", + "js/app/bindings/popover.js", + "js/app/bindings/qrcode.js", + "js/app/bindings/slimscrolledforeach.js", + "js/app/bindings/toggle.js", + "js/app/bindings/togglecontent.js", + "js/app/bindings/valuewithinit.js", + "js/app/viewmodels/access.js", + "js/app/viewmodels/appearance.js", + "js/app/viewmodels/connection.js", + "js/app/viewmodels/control.js", + "js/app/viewmodels/files.js", + "js/app/viewmodels/loginstate.js", + "js/app/viewmodels/loginui.js", + "js/app/viewmodels/navigation.js", + "js/app/viewmodels/printerstate.js", + "js/app/viewmodels/printerprofiles.js", + "js/app/viewmodels/settings.js", + "js/app/viewmodels/slicing.js", + "js/app/viewmodels/system.js", + "js/app/viewmodels/temperature.js", + "js/app/viewmodels/terminal.js", + "js/app/viewmodels/timelapse.js", + "js/app/viewmodels/uistate.js", + "js/app/viewmodels/users.js", + "js/app/viewmodels/usersettings.js", + "js/app/viewmodels/wizard.js", + "js/app/viewmodels/about.js", + ] - assets["clientjs"] = [ - "js/app/client/base.js", - "js/app/client/socket.js", - "js/app/client/access.js", - "js/app/client/browser.js", - "js/app/client/connection.js", - "js/app/client/control.js", - "js/app/client/files.js", - "js/app/client/job.js", - "js/app/client/languages.js", - "js/app/client/printer.js", - "js/app/client/printerprofiles.js", - "js/app/client/settings.js", - "js/app/client/slicing.js", - "js/app/client/system.js", - "js/app/client/timelapse.js", - "js/app/client/users.js", - "js/app/client/util.js", - "js/app/client/wizard.js" - ] + assets["clientjs"] = [ + "js/app/client/base.js", + "js/app/client/socket.js", + "js/app/client/access.js", + "js/app/client/browser.js", + "js/app/client/connection.js", + "js/app/client/control.js", + "js/app/client/files.js", + "js/app/client/job.js", + "js/app/client/languages.js", + "js/app/client/printer.js", + "js/app/client/printerprofiles.js", + "js/app/client/settings.js", + "js/app/client/slicing.js", + "js/app/client/system.js", + "js/app/client/timelapse.js", + "js/app/client/users.js", + "js/app/client/util.js", + "js/app/client/wizard.js", + ] - if preferred_stylesheet == "less": - assets["less"].append('less/octoprint.less') - elif preferred_stylesheet == "css": - assets["css"].append('css/octoprint.css') + if preferred_stylesheet == "less": + assets["less"].append("less/octoprint.less") + elif preferred_stylesheet == "css": + assets["css"].append("css/octoprint.css") + + return assets - return assets ##~~ plugin assets collector + def collect_plugin_assets(preferred_stylesheet="css"): - logger = logging.getLogger(__name__ + ".collect_plugin_assets") + logger = logging.getLogger(__name__ + ".collect_plugin_assets") - supported_stylesheets = ("css", "less") - assets = {"bundled": {"js": DefaultOrderedDict(list), - "clientjs": DefaultOrderedDict(list), - "css": DefaultOrderedDict(list), - "less": DefaultOrderedDict(list)}, - "external": {"js": DefaultOrderedDict(list), - "clientjs": DefaultOrderedDict(list), - "css": DefaultOrderedDict(list), - "less": DefaultOrderedDict(list)}} + supported_stylesheets = ("css", "less") + assets = { + "bundled": { + "js": DefaultOrderedDict(list), + "clientjs": DefaultOrderedDict(list), + "css": DefaultOrderedDict(list), + "less": DefaultOrderedDict(list), + }, + "external": { + "js": DefaultOrderedDict(list), + "clientjs": DefaultOrderedDict(list), + "css": DefaultOrderedDict(list), + "less": DefaultOrderedDict(list), + }, + } - asset_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.AssetPlugin) - for implementation in asset_plugins: - name = implementation._identifier - is_bundled = implementation._plugin_info.bundled + asset_plugins = octoprint.plugin.plugin_manager().get_implementations( + octoprint.plugin.AssetPlugin + ) + for implementation in asset_plugins: + name = implementation._identifier + is_bundled = implementation._plugin_info.bundled - asset_key = "bundled" if is_bundled else "external" + asset_key = "bundled" if is_bundled else "external" - try: - all_assets = implementation.get_assets() - basefolder = implementation.get_asset_folder() - except Exception: - logger.exception("Got an error while trying to collect assets from {}, ignoring assets from the plugin".format(name), - extra={"plugin": name}) - continue + try: + all_assets = implementation.get_assets() + basefolder = implementation.get_asset_folder() + except Exception: + logger.exception( + "Got an error while trying to collect assets from {}, ignoring assets from the plugin".format( + name + ), + extra={"plugin": name}, + ) + continue - def asset_exists(category, asset): - exists = os.path.exists(os.path.join(basefolder, asset)) - if not exists: - logger.warning("Plugin {} is referring to non existing {} asset {}".format(name, category, asset)) - return exists + def asset_exists(category, asset): + exists = os.path.exists(os.path.join(basefolder, asset)) + if not exists: + logger.warning( + "Plugin {} is referring to non existing {} asset {}".format( + name, category, asset + ) + ) + return exists - if "js" in all_assets: - for asset in all_assets["js"]: - if not asset_exists("js", asset): - continue - assets[asset_key]["js"][name].append('plugin/{name}/{asset}'.format(**locals())) + if "js" in all_assets: + for asset in all_assets["js"]: + if not asset_exists("js", asset): + continue + assets[asset_key]["js"][name].append( + "plugin/{name}/{asset}".format(**locals()) + ) - if "clientjs" in all_assets: - for asset in all_assets["clientjs"]: - if not asset_exists("clientjs", asset): - continue - assets[asset_key]["clientjs"][name].append("plugin/{name}/{asset}".format(**locals())) + if "clientjs" in all_assets: + for asset in all_assets["clientjs"]: + if not asset_exists("clientjs", asset): + continue + assets[asset_key]["clientjs"][name].append( + "plugin/{name}/{asset}".format(**locals()) + ) - if preferred_stylesheet in all_assets: - for asset in all_assets[preferred_stylesheet]: - if not asset_exists(preferred_stylesheet, asset): - continue - assets[asset_key][preferred_stylesheet][name].append('plugin/{name}/{asset}'.format(**locals())) - else: - for stylesheet in supported_stylesheets: - if not stylesheet in all_assets: - continue + if preferred_stylesheet in all_assets: + for asset in all_assets[preferred_stylesheet]: + if not asset_exists(preferred_stylesheet, asset): + continue + assets[asset_key][preferred_stylesheet][name].append( + "plugin/{name}/{asset}".format(**locals()) + ) + else: + for stylesheet in supported_stylesheets: + if not stylesheet in all_assets: + continue - for asset in all_assets[stylesheet]: - if not asset_exists(stylesheet, asset): - continue - assets[asset_key][stylesheet][name].append('plugin/{name}/{asset}'.format(**locals())) - break + for asset in all_assets[stylesheet]: + if not asset_exists(stylesheet, asset): + continue + assets[asset_key][stylesheet][name].append( + "plugin/{name}/{asset}".format(**locals()) + ) + break + + return assets - return assets ##~~ JSON encoding + class OctoPrintJsonEncoder(flask.json.JSONEncoder): - def default(self, obj): - try: - return JsonEncoding.encode(obj) - except TypeError: - return flask.json.JSONEncoder.default(self, obj) + def default(self, obj): + try: + return JsonEncoding.encode(obj) + except TypeError: + return flask.json.JSONEncoder.default(self, obj) diff --git a/src/octoprint/server/util/sockjs.py b/src/octoprint/server/util/sockjs.py index dcbd073a0..820a610c8 100644 --- a/src/octoprint/server/util/sockjs.py +++ b/src/octoprint/server/util/sockjs.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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 logging @@ -33,464 +33,624 @@ import json class ThreadSafeSession(octoprint.vendor.sockjs.tornado.session.Session): - def __init__(self, conn, server, session_id, expiry=None): - octoprint.vendor.sockjs.tornado.session.Session.__init__(self, conn, server, session_id, expiry=expiry) + def __init__(self, conn, server, session_id, expiry=None): + octoprint.vendor.sockjs.tornado.session.Session.__init__( + self, conn, server, session_id, expiry=expiry + ) - def set_handler(self, handler, start_heartbeat=True): - if getattr(handler, "__orig_send_pack", None) is None: - orig_send_pack = handler.send_pack - mutex = threading.RLock() + def set_handler(self, handler, start_heartbeat=True): + if getattr(handler, "__orig_send_pack", None) is None: + orig_send_pack = handler.send_pack + mutex = threading.RLock() - def send_pack(*args, **kwargs): - with mutex: - return orig_send_pack(*args, **kwargs) + def send_pack(*args, **kwargs): + with mutex: + return orig_send_pack(*args, **kwargs) - handler.send_pack = send_pack - setattr(handler, "__orig_send_pack", orig_send_pack) + handler.send_pack = send_pack + setattr(handler, "__orig_send_pack", orig_send_pack) - return octoprint.vendor.sockjs.tornado.session.Session.set_handler(self, handler, start_heartbeat=start_heartbeat) + return octoprint.vendor.sockjs.tornado.session.Session.set_handler( + self, handler, start_heartbeat=start_heartbeat + ) - def remove_handler(self, handler): - result = octoprint.vendor.sockjs.tornado.session.Session.remove_handler(self, handler) + def remove_handler(self, handler): + result = octoprint.vendor.sockjs.tornado.session.Session.remove_handler( + self, handler + ) - if getattr(handler, "__orig_send_pack", None) is not None: - handler.send_pack = getattr(handler, "__orig_send_pack") - delattr(handler, "__orig_send_pack") + if getattr(handler, "__orig_send_pack", None) is not None: + handler.send_pack = getattr(handler, "__orig_send_pack") + delattr(handler, "__orig_send_pack") - return result + return result class JsonEncodingSessionWrapper(wrapt.ObjectProxy): - def send_message(self, msg, stats=True, binary=False): - self.send_jsonified(json.dumps(octoprint.vendor.sockjs.tornado.util.bytes_to_str(msg), - separators=(',', ':'), - default=JsonEncoding.encode), - stats) - - -class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, - octoprint.printer.PrinterCallback, - LoginStatusListener, - GroupChangeListener): - - _event_permissions = {Events.USER_LOGGED_IN: [Permissions.ADMIN], - Events.USER_LOGGED_OUT: [Permissions.ADMIN], - "*": []} - - _event_payload_processors = {Events.CLIENT_OPENED: [lambda user, payload: payload if user.has_permission(Permissions.ADMIN) else {}], - Events.CLIENT_AUTHED: [lambda user, payload: payload if user.has_permission(Permissions.ADMIN) else {}], - "*": []} - - _emit_permissions = {"connected": [], - "reauthRequired": [], - "plugin": lambda payload: [] if payload.get("plugin") == "backup" and settings().getBoolean(["server", "firstRun"]) else [Permissions.STATUS], - "*": [Permissions.STATUS]} - - _unauthed_backlog_max = 100 - - def __init__(self, printer, fileManager, analysisQueue, userManager, groupManager, eventManager, pluginManager, session): - if isinstance(session, octoprint.vendor.sockjs.tornado.session.Session): - session = JsonEncodingSessionWrapper(session) - - octoprint.vendor.sockjs.tornado.SockJSConnection.__init__(self, session) - - self._logger = logging.getLogger(__name__) - - self._temperatureBacklog = [] - self._temperatureBacklogMutex = threading.Lock() - self._logBacklog = [] - self._logBacklogMutex = threading.Lock() - self._messageBacklog = [] - self._messageBacklogMutex = threading.Lock() - - self._unauthed_backlog = [] - self._unauthed_backlog_mutex = threading.RLock() - - self._printer = printer - self._fileManager = fileManager - self._analysisQueue = analysisQueue - self._userManager = userManager - self._groupManager = groupManager - self._eventManager = eventManager - self._pluginManager = pluginManager - - self._remoteAddress = None - self._user = self._userManager.anonymous_user_factory() - - self._throttle_factor = 1 - self._last_current = 0 - self._base_rate_limit = 0.5 - - self._held_back_current = None - self._held_back_mutex = threading.RLock() - - self._register_hooks = self._pluginManager.get_hooks("octoprint.server.sockjs.register") - self._authed_hooks = self._pluginManager.get_hooks("octoprint.server.sockjs.authed") - self._emit_hooks = self._pluginManager.get_hooks("octoprint.server.sockjs.emit") - - self._registered = False - self._authed = False - - @staticmethod - def _get_remote_address(info): - forwarded_for = info.headers.get("X-Forwarded-For") - if forwarded_for is not None: - return forwarded_for.split(",")[0] - return info.ip - - def __str__(self): - if self._remoteAddress: - return "{!r} connected to {}".format(self, self._remoteAddress) - else: - return "Unconnected {!r}".format(self) - - def on_open(self, info): - self._pluginManager.register_message_receiver(self.on_plugin_message) - self._remoteAddress = self._get_remote_address(info) - self._logger.info("New connection from client: %s" % self._remoteAddress) - - self._userManager.register_login_status_listener(self) - self._groupManager.register_listener(self) - - plugin_signature = lambda impl: "{}:{}".format(impl._identifier, impl._plugin_version) - template_plugins = list(map(plugin_signature, self._pluginManager.get_implementations(octoprint.plugin.TemplatePlugin))) - asset_plugins = list(map(plugin_signature, self._pluginManager.get_implementations(octoprint.plugin.AssetPlugin))) - ui_plugins = sorted(set(template_plugins + asset_plugins)) - - import hashlib - plugin_hash = hashlib.md5() - plugin_hash.update(",".join(ui_plugins).encode('utf-8')) - - config_hash = settings().config_hash - - # connected => update the API key, might be necessary if the client was left open while the server restarted - self._emit("connected", {"version": octoprint.server.VERSION, - "display_version": octoprint.server.DISPLAY_VERSION, - "branch": octoprint.server.BRANCH, - "plugin_hash": plugin_hash.hexdigest(), - "config_hash": config_hash, - "debug": octoprint.server.debug, - "safe_mode": octoprint.server.safe_mode, - "permissions": [permission.as_dict() for permission in Permissions.all()]}) - - self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": self._remoteAddress}) - self._register() - - def on_close(self): - self._user = self._userManager.anonymous_user_factory() - self._groupManager.unregister_listener(self) - self._userManager.unregister_login_status_listener(self) - - self._unregister() - self._eventManager.fire(Events.CLIENT_CLOSED, {"remoteAddress": self._remoteAddress}) - - self._logger.info("Client connection closed: %s" % self._remoteAddress) - - self._on_logout() - self._remoteAddress = None - self._pluginManager.unregister_message_receiver(self.on_plugin_message) - - def on_message(self, message): - try: - import json - message = json.loads(message) - except Exception: - self._logger.warning("Invalid JSON received from client {}, ignoring: {!r}".format(self._remoteAddress, message)) - return - - if "auth" in message: - try: - parts = message["auth"].split(":") - if not len(parts) == 2: - raise ValueError() - except ValueError: - self._logger.warning("Got invalid auth message from client {}, ignoring: {!r}".format(self._remoteAddress, message["auth"])) - else: - user_id, user_session = parts - - if self._userManager.validate_user_session(user_id, user_session): - user = self._userManager.find_user(userid=user_id, session=user_session) - self._on_login(user) - else: - self._logger.warning("Unknown user/session combo: {}:{}".format(user_id, user_session)) - self._on_logout() - - self._register() - - elif "throttle" in message: - try: - throttle = int(message["throttle"]) - if throttle < 1: - raise ValueError() - except ValueError: - self._logger.warning("Got invalid throttle factor from client {}, ignoring: {!r}".format(self._remoteAddress, message["throttle"])) - else: - self._throttle_factor = throttle - self._logger.debug("Set throttle factor for client {} to {}".format(self._remoteAddress, self._throttle_factor)) - - def on_printer_send_current_data(self, data): - if not self._user.has_permission(Permissions.STATUS): - return - - # make sure we rate limit the updates according to our throttle factor - with self._held_back_mutex: - if self._held_back_current is not None: - self._held_back_current.cancel() - self._held_back_current = None - - now = time.time() - delta = self._last_current + self._base_rate_limit * self._throttle_factor - now - if delta > 0: - self._held_back_current = threading.Timer(delta, lambda: self.on_printer_send_current_data(data)) - self._held_back_current.start() - return - - self._last_current = now - - # add current temperature, log and message backlogs to sent data - with self._temperatureBacklogMutex: - temperatures = self._temperatureBacklog - self._temperatureBacklog = [] - - with self._logBacklogMutex: - logs = self._logBacklog - self._logBacklog = [] - - with self._messageBacklogMutex: - messages = self._messageBacklog - self._messageBacklog = [] - - busy_files = [{"origin": v[0], "path": v[1]} for v in self._fileManager.get_busy_files()] - if "job" in data and data["job"] is not None \ - and "file" in data["job"] and "path" in data["job"]["file"] and "origin" in data["job"]["file"] \ - and data["job"]["file"]["path"] is not None and data["job"]["file"]["origin"] is not None \ - and (self._printer.is_printing() or self._printer.is_paused()): - busy_files.append({"origin": data["job"]["file"]["origin"], "path": data["job"]["file"]["path"]}) - - data.update({ - "serverTime": time.time(), - "temps": temperatures, - "logs": logs, - "messages": messages, - "busyFiles": busy_files, - }) - self._emit("current", payload=data) - - def on_printer_send_initial_data(self, data): - data_to_send = dict(data) - data_to_send["serverTime"] = time.time() - self._emit("history", payload=data_to_send) - - def sendEvent(self, type, payload=None): - permissions = self._event_permissions.get(type, self._event_permissions["*"]) - permissions = [x(self._user) if callable(x) else x for x in permissions] - if not self._user or not all(map(lambda p: self._user.has_permission(p), permissions)): - return - - processors = self._event_payload_processors.get(type, self._event_payload_processors["*"]) - for processor in processors: - payload = processor(self._user, payload) - - self._emit("event", payload={"type": type, "payload": payload}) - - def sendTimelapseConfig(self, timelapseConfig): - self._emit("timelapse", payload=timelapseConfig) - - def sendSlicingProgress(self, slicer, source_location, source_path, dest_location, dest_path, progress): - self._emit("slicingProgress", payload={"slicer": slicer, - "source_location": source_location, - "source_path": source_path, - "dest_location": dest_location, - "dest_path": dest_path, - "progress": progress}) - - def sendRenderProgress(self, progress): - self._emit("renderProgress", - {"progress": progress} - ) - - def on_plugin_message(self, plugin, data, permissions=None): - self._emit("plugin", payload={"plugin": plugin, "data": data}, permissions=permissions) - - def on_printer_add_log(self, data): - with self._logBacklogMutex: - self._logBacklog.append(data) - - def on_printer_add_message(self, data): - with self._messageBacklogMutex: - self._messageBacklog.append(data) - - def on_printer_add_temperature(self, data): - with self._temperatureBacklogMutex: - self._temperatureBacklog.append(data) - - def on_user_logged_out(self, user, stale=False): - if user.get_id() == self._user.get_id() and hasattr(user, "session") and hasattr(self._user, "session") and user.session == self._user.session: - self._logger.info("User {} logged out, logging out on socket".format(user.get_id())) - self._on_logout() - - if stale: - self._sendReauthRequired("stale") - else: - self._sendReauthRequired("logout") - - def on_user_modified(self, user): - if user.get_id() == self._user.get_id(): - self._sendReauthRequired("modified") - - def on_user_removed(self, userid): - if self._user.get_id() == userid: - self._logger.info("User {} deleted, logging out on socket".format(userid)) - self._on_logout() - self._sendReauthRequired("removed") - - def on_group_permissions_changed(self, group, added=None, removed=None): - if self._user.is_anonymous and group == self._groupManager.guest_group: - self._sendReauthRequired("modified") - - def on_group_subgroups_changed(self, group, added=None, removed=None): - if self._user.is_anonymous and group == self._groupManager.guest_group: - self._sendReauthRequired("modified") - - def _onEvent(self, event, payload): - self.sendEvent(event, payload) - - def _register(self): - """Register this socket with the system if STATUS permission is available.""" - - proceed = True - for name, hook in self._register_hooks.items(): - try: - proceed = proceed and hook(self, self._user) - except Exception: - self._logger.exception("Error processing register hook handler for plugin {}".format(name), - extra={"plugin": name}) - - if not proceed: - return - - if self._registered: - return - - if not self._user.has_permission(Permissions.STATUS): - return - - # printer - self._printer.register_callback(self) - self._printer.send_initial_callback(self) - - # files - self._fileManager.register_slicingprogress_callback(self) - - # events - for event in octoprint.events.all_events(): - self._eventManager.subscribe(event, self._onEvent) - - # timelapse - octoprint.timelapse.register_callback(self) - octoprint.timelapse.notify_callback(self, timelapse=octoprint.timelapse.current) - if octoprint.timelapse.current_render_job is not None: - # This is a horrible hack for now to allow displaying a notification that a render job is still - # active in the backend on a fresh connect of a client. This needs to be substituted with a proper - # job management for timelapse rendering, analysis stuff etc that also gets cancelled when prints - # start and so on. - # - # For now this is the easiest way though to at least inform the user that a timelapse is still ongoing. - # - # TODO remove when central job management becomes available and takes care of this for us - self.sendEvent(Events.MOVIE_RENDERING, payload=octoprint.timelapse.current_render_job) - self._registered = True - - def _unregister(self): - """Unregister this socket from the system""" - - self._printer.unregister_callback(self) - self._fileManager.unregister_slicingprogress_callback(self) - octoprint.timelapse.unregister_callback(self) - for event in octoprint.events.all_events(): - self._eventManager.unsubscribe(event, self._onEvent) - - def _reregister(self): - """Unregister and register again""" - self._unregister() - self._register() - - def _sendReauthRequired(self, reason): - self._emit("reauthRequired", payload={"reason": reason}) - - def _emit(self, type, payload=None, permissions=None): - proceed = True - for name, hook in self._emit_hooks.items(): - try: - proceed = proceed and hook(self, self._user, type, payload) - except Exception: - self._logger.exception("Error processing emit hook handler from plugin {}".format(name), - extra={"plugin": name}) - - if not proceed: - return - - if permissions is None: - permissions = self._emit_permissions.get(type, self._emit_permissions["*"]) - permissions = permissions(payload) if callable(permissions) else [x for x in permissions] - - if not self._user or not all(map(lambda p: self._user.has_permission(p), permissions)): - if not self._authed: - with self._unauthed_backlog_mutex: - if len(self._unauthed_backlog) < self._unauthed_backlog_max: - self._unauthed_backlog.append((type, payload)) - self._logger.debug("Socket message held back until permissions cleared, added to backlog: {}".format(type)) - else: - self._logger.debug("Socket message held back, but backlog full. Throwing message away: {}".format(type)) - return - - self._do_emit(type, payload) - - def _do_emit(self, type, payload): - try: - self.send({type: payload}) - except Exception as e: - if self._logger.isEnabledFor(logging.DEBUG): - self._logger.exception("Could not send message to client {}".format(self._remoteAddress)) - else: - self._logger.warning("Could not send message to client {}: {}".format(self._remoteAddress, e)) - - def _on_login(self, user): - self._user = user - self._logger.info("User {} logged in on the socket from client {}".format(user.get_name(), - self._remoteAddress)) - self._authed = True - - for name, hook in self._authed_hooks.items(): - try: - hook(self, self._user) - except Exception: - self._logger.exception("Error processing authed hook handler for plugin {}".format(name), - extra={"plugin": name}) - - # if we have a backlog from being unauthed, process that now - with self._unauthed_backlog_mutex: - backlog = self._unauthed_backlog - self._unauthed_backlog = [] - - if len(backlog): - self._logger.debug("Sending {} messages on the socket that were held back".format(len(backlog))) - for message, payload in backlog: - self._do_emit(message, payload) - - # trigger ClientAuthed event - octoprint.events.eventManager().fire(octoprint.events.Events.CLIENT_AUTHED, - payload={"username": user.get_name(), - "remoteAddress": self._remoteAddress}) - - def _on_logout(self): - self._user = self._userManager.anonymous_user_factory() - self._authed = False - - for name, hook in self._authed_hooks.items(): - try: - hook(self, self._user) - except Exception: - self._logger.exception("Error processing authed hook handler for plugin {}".format(name), - extra={"plugin": name}) - + def send_message(self, msg, stats=True, binary=False): + self.send_jsonified( + json.dumps( + octoprint.vendor.sockjs.tornado.util.bytes_to_str(msg), + separators=(",", ":"), + default=JsonEncoding.encode, + ), + stats, + ) + + +class PrinterStateConnection( + octoprint.vendor.sockjs.tornado.SockJSConnection, + octoprint.printer.PrinterCallback, + LoginStatusListener, + GroupChangeListener, +): + + _event_permissions = { + Events.USER_LOGGED_IN: [Permissions.ADMIN], + Events.USER_LOGGED_OUT: [Permissions.ADMIN], + "*": [], + } + + _event_payload_processors = { + Events.CLIENT_OPENED: [ + lambda user, payload: payload + if user.has_permission(Permissions.ADMIN) + else {} + ], + Events.CLIENT_AUTHED: [ + lambda user, payload: payload + if user.has_permission(Permissions.ADMIN) + else {} + ], + "*": [], + } + + _emit_permissions = { + "connected": [], + "reauthRequired": [], + "plugin": lambda payload: [] + if payload.get("plugin") == "backup" + and settings().getBoolean(["server", "firstRun"]) + else [Permissions.STATUS], + "*": [Permissions.STATUS], + } + + _unauthed_backlog_max = 100 + + def __init__( + self, + printer, + fileManager, + analysisQueue, + userManager, + groupManager, + eventManager, + pluginManager, + session, + ): + if isinstance(session, octoprint.vendor.sockjs.tornado.session.Session): + session = JsonEncodingSessionWrapper(session) + + octoprint.vendor.sockjs.tornado.SockJSConnection.__init__(self, session) + + self._logger = logging.getLogger(__name__) + + self._temperatureBacklog = [] + self._temperatureBacklogMutex = threading.Lock() + self._logBacklog = [] + self._logBacklogMutex = threading.Lock() + self._messageBacklog = [] + self._messageBacklogMutex = threading.Lock() + + self._unauthed_backlog = [] + self._unauthed_backlog_mutex = threading.RLock() + + self._printer = printer + self._fileManager = fileManager + self._analysisQueue = analysisQueue + self._userManager = userManager + self._groupManager = groupManager + self._eventManager = eventManager + self._pluginManager = pluginManager + + self._remoteAddress = None + self._user = self._userManager.anonymous_user_factory() + + self._throttle_factor = 1 + self._last_current = 0 + self._base_rate_limit = 0.5 + + self._held_back_current = None + self._held_back_mutex = threading.RLock() + + self._register_hooks = self._pluginManager.get_hooks( + "octoprint.server.sockjs.register" + ) + self._authed_hooks = self._pluginManager.get_hooks( + "octoprint.server.sockjs.authed" + ) + self._emit_hooks = self._pluginManager.get_hooks("octoprint.server.sockjs.emit") + + self._registered = False + self._authed = False + + @staticmethod + def _get_remote_address(info): + forwarded_for = info.headers.get("X-Forwarded-For") + if forwarded_for is not None: + return forwarded_for.split(",")[0] + return info.ip + + def __str__(self): + if self._remoteAddress: + return "{!r} connected to {}".format(self, self._remoteAddress) + else: + return "Unconnected {!r}".format(self) + + def on_open(self, info): + self._pluginManager.register_message_receiver(self.on_plugin_message) + self._remoteAddress = self._get_remote_address(info) + self._logger.info("New connection from client: %s" % self._remoteAddress) + + self._userManager.register_login_status_listener(self) + self._groupManager.register_listener(self) + + plugin_signature = lambda impl: "{}:{}".format( + impl._identifier, impl._plugin_version + ) + template_plugins = list( + map( + plugin_signature, + self._pluginManager.get_implementations(octoprint.plugin.TemplatePlugin), + ) + ) + asset_plugins = list( + map( + plugin_signature, + self._pluginManager.get_implementations(octoprint.plugin.AssetPlugin), + ) + ) + ui_plugins = sorted(set(template_plugins + asset_plugins)) + + import hashlib + + plugin_hash = hashlib.md5() + plugin_hash.update(",".join(ui_plugins).encode("utf-8")) + + config_hash = settings().config_hash + + # connected => update the API key, might be necessary if the client was left open while the server restarted + self._emit( + "connected", + { + "version": octoprint.server.VERSION, + "display_version": octoprint.server.DISPLAY_VERSION, + "branch": octoprint.server.BRANCH, + "plugin_hash": plugin_hash.hexdigest(), + "config_hash": config_hash, + "debug": octoprint.server.debug, + "safe_mode": octoprint.server.safe_mode, + "permissions": [permission.as_dict() for permission in Permissions.all()], + }, + ) + + self._eventManager.fire( + Events.CLIENT_OPENED, {"remoteAddress": self._remoteAddress} + ) + self._register() + + def on_close(self): + self._user = self._userManager.anonymous_user_factory() + self._groupManager.unregister_listener(self) + self._userManager.unregister_login_status_listener(self) + + self._unregister() + self._eventManager.fire( + Events.CLIENT_CLOSED, {"remoteAddress": self._remoteAddress} + ) + + self._logger.info("Client connection closed: %s" % self._remoteAddress) + + self._on_logout() + self._remoteAddress = None + self._pluginManager.unregister_message_receiver(self.on_plugin_message) + + def on_message(self, message): + try: + import json + + message = json.loads(message) + except Exception: + self._logger.warning( + "Invalid JSON received from client {}, ignoring: {!r}".format( + self._remoteAddress, message + ) + ) + return + + if "auth" in message: + try: + parts = message["auth"].split(":") + if not len(parts) == 2: + raise ValueError() + except ValueError: + self._logger.warning( + "Got invalid auth message from client {}, ignoring: {!r}".format( + self._remoteAddress, message["auth"] + ) + ) + else: + user_id, user_session = parts + + if self._userManager.validate_user_session(user_id, user_session): + user = self._userManager.find_user( + userid=user_id, session=user_session + ) + self._on_login(user) + else: + self._logger.warning( + "Unknown user/session combo: {}:{}".format(user_id, user_session) + ) + self._on_logout() + + self._register() + + elif "throttle" in message: + try: + throttle = int(message["throttle"]) + if throttle < 1: + raise ValueError() + except ValueError: + self._logger.warning( + "Got invalid throttle factor from client {}, ignoring: {!r}".format( + self._remoteAddress, message["throttle"] + ) + ) + else: + self._throttle_factor = throttle + self._logger.debug( + "Set throttle factor for client {} to {}".format( + self._remoteAddress, self._throttle_factor + ) + ) + + def on_printer_send_current_data(self, data): + if not self._user.has_permission(Permissions.STATUS): + return + + # make sure we rate limit the updates according to our throttle factor + with self._held_back_mutex: + if self._held_back_current is not None: + self._held_back_current.cancel() + self._held_back_current = None + + now = time.time() + delta = ( + self._last_current + self._base_rate_limit * self._throttle_factor - now + ) + if delta > 0: + self._held_back_current = threading.Timer( + delta, lambda: self.on_printer_send_current_data(data) + ) + self._held_back_current.start() + return + + self._last_current = now + + # add current temperature, log and message backlogs to sent data + with self._temperatureBacklogMutex: + temperatures = self._temperatureBacklog + self._temperatureBacklog = [] + + with self._logBacklogMutex: + logs = self._logBacklog + self._logBacklog = [] + + with self._messageBacklogMutex: + messages = self._messageBacklog + self._messageBacklog = [] + + busy_files = [ + {"origin": v[0], "path": v[1]} for v in self._fileManager.get_busy_files() + ] + if ( + "job" in data + and data["job"] is not None + and "file" in data["job"] + and "path" in data["job"]["file"] + and "origin" in data["job"]["file"] + and data["job"]["file"]["path"] is not None + and data["job"]["file"]["origin"] is not None + and (self._printer.is_printing() or self._printer.is_paused()) + ): + busy_files.append( + { + "origin": data["job"]["file"]["origin"], + "path": data["job"]["file"]["path"], + } + ) + + data.update( + { + "serverTime": time.time(), + "temps": temperatures, + "logs": logs, + "messages": messages, + "busyFiles": busy_files, + } + ) + self._emit("current", payload=data) + + def on_printer_send_initial_data(self, data): + data_to_send = dict(data) + data_to_send["serverTime"] = time.time() + self._emit("history", payload=data_to_send) + + def sendEvent(self, type, payload=None): + permissions = self._event_permissions.get(type, self._event_permissions["*"]) + permissions = [x(self._user) if callable(x) else x for x in permissions] + if not self._user or not all( + map(lambda p: self._user.has_permission(p), permissions) + ): + return + + processors = self._event_payload_processors.get( + type, self._event_payload_processors["*"] + ) + for processor in processors: + payload = processor(self._user, payload) + + self._emit("event", payload={"type": type, "payload": payload}) + + def sendTimelapseConfig(self, timelapseConfig): + self._emit("timelapse", payload=timelapseConfig) + + def sendSlicingProgress( + self, slicer, source_location, source_path, dest_location, dest_path, progress + ): + self._emit( + "slicingProgress", + payload={ + "slicer": slicer, + "source_location": source_location, + "source_path": source_path, + "dest_location": dest_location, + "dest_path": dest_path, + "progress": progress, + }, + ) + + def sendRenderProgress(self, progress): + self._emit("renderProgress", {"progress": progress}) + + def on_plugin_message(self, plugin, data, permissions=None): + self._emit( + "plugin", payload={"plugin": plugin, "data": data}, permissions=permissions + ) + + def on_printer_add_log(self, data): + with self._logBacklogMutex: + self._logBacklog.append(data) + + def on_printer_add_message(self, data): + with self._messageBacklogMutex: + self._messageBacklog.append(data) + + def on_printer_add_temperature(self, data): + with self._temperatureBacklogMutex: + self._temperatureBacklog.append(data) + + def on_user_logged_out(self, user, stale=False): + if ( + user.get_id() == self._user.get_id() + and hasattr(user, "session") + and hasattr(self._user, "session") + and user.session == self._user.session + ): + self._logger.info( + "User {} logged out, logging out on socket".format(user.get_id()) + ) + self._on_logout() + + if stale: + self._sendReauthRequired("stale") + else: + self._sendReauthRequired("logout") + + def on_user_modified(self, user): + if user.get_id() == self._user.get_id(): + self._sendReauthRequired("modified") + + def on_user_removed(self, userid): + if self._user.get_id() == userid: + self._logger.info("User {} deleted, logging out on socket".format(userid)) + self._on_logout() + self._sendReauthRequired("removed") + + def on_group_permissions_changed(self, group, added=None, removed=None): + if self._user.is_anonymous and group == self._groupManager.guest_group: + self._sendReauthRequired("modified") + + def on_group_subgroups_changed(self, group, added=None, removed=None): + if self._user.is_anonymous and group == self._groupManager.guest_group: + self._sendReauthRequired("modified") + + def _onEvent(self, event, payload): + self.sendEvent(event, payload) + + def _register(self): + """Register this socket with the system if STATUS permission is available.""" + + proceed = True + for name, hook in self._register_hooks.items(): + try: + proceed = proceed and hook(self, self._user) + except Exception: + self._logger.exception( + "Error processing register hook handler for plugin {}".format(name), + extra={"plugin": name}, + ) + + if not proceed: + return + + if self._registered: + return + + if not self._user.has_permission(Permissions.STATUS): + return + + # printer + self._printer.register_callback(self) + self._printer.send_initial_callback(self) + + # files + self._fileManager.register_slicingprogress_callback(self) + + # events + for event in octoprint.events.all_events(): + self._eventManager.subscribe(event, self._onEvent) + + # timelapse + octoprint.timelapse.register_callback(self) + octoprint.timelapse.notify_callback(self, timelapse=octoprint.timelapse.current) + if octoprint.timelapse.current_render_job is not None: + # This is a horrible hack for now to allow displaying a notification that a render job is still + # active in the backend on a fresh connect of a client. This needs to be substituted with a proper + # job management for timelapse rendering, analysis stuff etc that also gets cancelled when prints + # start and so on. + # + # For now this is the easiest way though to at least inform the user that a timelapse is still ongoing. + # + # TODO remove when central job management becomes available and takes care of this for us + self.sendEvent( + Events.MOVIE_RENDERING, payload=octoprint.timelapse.current_render_job + ) + self._registered = True + + def _unregister(self): + """Unregister this socket from the system""" + + self._printer.unregister_callback(self) + self._fileManager.unregister_slicingprogress_callback(self) + octoprint.timelapse.unregister_callback(self) + for event in octoprint.events.all_events(): + self._eventManager.unsubscribe(event, self._onEvent) + + def _reregister(self): + """Unregister and register again""" + self._unregister() + self._register() + + def _sendReauthRequired(self, reason): + self._emit("reauthRequired", payload={"reason": reason}) + + def _emit(self, type, payload=None, permissions=None): + proceed = True + for name, hook in self._emit_hooks.items(): + try: + proceed = proceed and hook(self, self._user, type, payload) + except Exception: + self._logger.exception( + "Error processing emit hook handler from plugin {}".format(name), + extra={"plugin": name}, + ) + + if not proceed: + return + + if permissions is None: + permissions = self._emit_permissions.get(type, self._emit_permissions["*"]) + permissions = ( + permissions(payload) + if callable(permissions) + else [x for x in permissions] + ) + + if not self._user or not all( + map(lambda p: self._user.has_permission(p), permissions) + ): + if not self._authed: + with self._unauthed_backlog_mutex: + if len(self._unauthed_backlog) < self._unauthed_backlog_max: + self._unauthed_backlog.append((type, payload)) + self._logger.debug( + "Socket message held back until permissions cleared, added to backlog: {}".format( + type + ) + ) + else: + self._logger.debug( + "Socket message held back, but backlog full. Throwing message away: {}".format( + type + ) + ) + return + + self._do_emit(type, payload) + + def _do_emit(self, type, payload): + try: + self.send({type: payload}) + except Exception as e: + if self._logger.isEnabledFor(logging.DEBUG): + self._logger.exception( + "Could not send message to client {}".format(self._remoteAddress) + ) + else: + self._logger.warning( + "Could not send message to client {}: {}".format( + self._remoteAddress, e + ) + ) + + def _on_login(self, user): + self._user = user + self._logger.info( + "User {} logged in on the socket from client {}".format( + user.get_name(), self._remoteAddress + ) + ) + self._authed = True + + for name, hook in self._authed_hooks.items(): + try: + hook(self, self._user) + except Exception: + self._logger.exception( + "Error processing authed hook handler for plugin {}".format(name), + extra={"plugin": name}, + ) + + # if we have a backlog from being unauthed, process that now + with self._unauthed_backlog_mutex: + backlog = self._unauthed_backlog + self._unauthed_backlog = [] + + if len(backlog): + self._logger.debug( + "Sending {} messages on the socket that were held back".format( + len(backlog) + ) + ) + for message, payload in backlog: + self._do_emit(message, payload) + + # trigger ClientAuthed event + octoprint.events.eventManager().fire( + octoprint.events.Events.CLIENT_AUTHED, + payload={"username": user.get_name(), "remoteAddress": self._remoteAddress}, + ) + + def _on_logout(self): + self._user = self._userManager.anonymous_user_factory() + self._authed = False + + for name, hook in self._authed_hooks.items(): + try: + hook(self, self._user) + except Exception: + self._logger.exception( + "Error processing authed hook handler for plugin {}".format(name), + extra={"plugin": name}, + ) diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py index 3be1f0011..8920b39dc 100644 --- a/src/octoprint/server/util/tornado.py +++ b/src/octoprint/server/util/tornado.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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 logging @@ -28,1330 +28,1477 @@ import octoprint.util from past.builtins import unicode try: - from urllib.parse import urlparse # py3 + from urllib.parse import urlparse # py3 except ImportError: - from urlparse import urlparse # py2 + from urlparse import urlparse # py2 from . import PY3 + def fix_json_encode(): - """ - This makes tornado.escape.json_encode use octoprint.util.JsonEncoding.encode as fallback in order to allow - serialization of globally registered types like frozendict and others. - """ + """ + This makes tornado.escape.json_encode use octoprint.util.JsonEncoding.encode as fallback in order to allow + serialization of globally registered types like frozendict and others. + """ - from octoprint.util.json import JsonEncoding - import json + from octoprint.util.json import JsonEncoding + import json - def fixed_json_encode(value): - return json.dumps(value, default=JsonEncoding.encode, allow_nan=False).replace("`_ mixin that - makes sure to set CORS headers similarly to the Flask backed API endpoints. - """ + """ + `tornado.web.RequestHandler `_ mixin that + makes sure to set CORS headers similarly to the Flask backed API endpoints. + """ - ENABLE_CORS = False + ENABLE_CORS = False - def set_default_headers(self): - origin = self.request.headers.get("Origin") - if self.request.method != "OPTIONS" and origin and self.ENABLE_CORS: - self.set_header("Access-Control-Allow-Origin", origin) + def set_default_headers(self): + origin = self.request.headers.get("Origin") + if self.request.method != "OPTIONS" and origin and self.ENABLE_CORS: + self.set_header("Access-Control-Allow-Origin", origin) - @tornado.gen.coroutine - def options(self, *args, **kwargs): - if self.ENABLE_CORS: - origin = self.request.headers.get("Origin") - method = self.request.headers.get("Access-Control-Request-Method") + @tornado.gen.coroutine + def options(self, *args, **kwargs): + if self.ENABLE_CORS: + origin = self.request.headers.get("Origin") + method = self.request.headers.get("Access-Control-Request-Method") - # Allow the origin which made the XHR - self.set_header("Access-Control-Allow-Origin", origin) - # Allow the actual method - self.set_header("Access-Control-Allow-Methods", method) - # Allow for 10 seconds - self.set_header("Access-Control-Max-Age", "10") + # Allow the origin which made the XHR + self.set_header("Access-Control-Allow-Origin", origin) + # Allow the actual method + self.set_header("Access-Control-Allow-Methods", method) + # Allow for 10 seconds + self.set_header("Access-Control-Max-Age", "10") - # 'preflight' request contains the non-standard headers the real request will have (like X-Api-Key) - custom_headers = self.request.headers.get("Access-Control-Request-Headers") - if custom_headers is not None: - self.set_header("Access-Control-Allow-Headers", custom_headers) + # 'preflight' request contains the non-standard headers the real request will have (like X-Api-Key) + custom_headers = self.request.headers.get("Access-Control-Request-Headers") + if custom_headers is not None: + self.set_header("Access-Control-Allow-Headers", custom_headers) - self.set_status(204) - self.finish() + self.set_status(204) + self.finish() -#~~ WSGI middleware +# ~~ WSGI middleware @tornado.web.stream_request_body -class UploadStorageFallbackHandler(RequestlessExceptionLoggingMixin, - CorsSupportMixin): - """ - A ``RequestHandler`` similar to ``tornado.web.FallbackHandler`` which fetches any files contained in the request bodies - of content type ``multipart``, stores them in temporary files and supplies the ``fallback`` with the file's ``name``, - ``content_type``, ``path`` and ``size`` instead via a rewritten body. +class UploadStorageFallbackHandler(RequestlessExceptionLoggingMixin, CorsSupportMixin): + """ + A ``RequestHandler`` similar to ``tornado.web.FallbackHandler`` which fetches any files contained in the request bodies + of content type ``multipart``, stores them in temporary files and supplies the ``fallback`` with the file's ``name``, + ``content_type``, ``path`` and ``size`` instead via a rewritten body. - Basically similar to what the nginx upload module does. + Basically similar to what the nginx upload module does. - Basic request body example: + Basic request body example: - .. code-block:: none + .. code-block:: none - ------WebKitFormBoundarypYiSUx63abAmhT5C - Content-Disposition: form-data; name="file"; filename="test.gcode" - Content-Type: application/octet-stream + ------WebKitFormBoundarypYiSUx63abAmhT5C + Content-Disposition: form-data; name="file"; filename="test.gcode" + Content-Type: application/octet-stream - ... - ------WebKitFormBoundarypYiSUx63abAmhT5C - Content-Disposition: form-data; name="apikey" + ... + ------WebKitFormBoundarypYiSUx63abAmhT5C + Content-Disposition: form-data; name="apikey" - my_funny_apikey - ------WebKitFormBoundarypYiSUx63abAmhT5C - Content-Disposition: form-data; name="select" + my_funny_apikey + ------WebKitFormBoundarypYiSUx63abAmhT5C + Content-Disposition: form-data; name="select" - true - ------WebKitFormBoundarypYiSUx63abAmhT5C-- + true + ------WebKitFormBoundarypYiSUx63abAmhT5C-- - That would get turned into: + That would get turned into: - .. code-block:: none - - ------WebKitFormBoundarypYiSUx63abAmhT5C - Content-Disposition: form-data; name="apikey" - - my_funny_apikey - ------WebKitFormBoundarypYiSUx63abAmhT5C - Content-Disposition: form-data; name="select" - - true - ------WebKitFormBoundarypYiSUx63abAmhT5C - Content-Disposition: form-data; name="file.path" - Content-Type: text/plain; charset=utf-8 - - /tmp/tmpzupkro - ------WebKitFormBoundarypYiSUx63abAmhT5C - Content-Disposition: form-data; name="file.name" - Content-Type: text/plain; charset=utf-8 - - test.gcode - ------WebKitFormBoundarypYiSUx63abAmhT5C - Content-Disposition: form-data; name="file.content_type" - Content-Type: text/plain; charset=utf-8 - - application/octet-stream - ------WebKitFormBoundarypYiSUx63abAmhT5C - Content-Disposition: form-data; name="file.size" - Content-Type: text/plain; charset=utf-8 - - 349182 - ------WebKitFormBoundarypYiSUx63abAmhT5C-- - - The underlying application can then access the contained files via their respective paths and just move them - where necessary. - """ - - BODY_METHODS = ("POST", "PATCH", "PUT") - """ The request methods that may contain a request body. """ - - def initialize(self, fallback, file_prefix="tmp", file_suffix="", path=None, suffixes=None): - if not suffixes: - suffixes = {} - - self._fallback = fallback - self._file_prefix = file_prefix - self._file_suffix = file_suffix - self._path = path - - self._suffixes = dict((key, key) for key in ("name", "path", "content_type", "size")) - for suffix_type, suffix in suffixes.items(): - if suffix_type in self._suffixes and suffix is not None: - self._suffixes[suffix_type] = suffix - - # multipart boundary - self._multipart_boundary = None - - # Parts, files and values will be stored here - self._parts = {} - self._files = [] - - # Part currently being processed - self._current_part = None - - # content type of request body - self._content_type = None - - # bytes left to read according to content_length of request body - self._bytes_left = 0 - - # buffer needed for identifying form data parts - self._buffer = b"" - - # buffer for new body - self._new_body = b"" - - # logger - self._logger = logging.getLogger(__name__) - - def prepare(self): - """ - Prepares the processing of the request. If it's a request that may contain a request body (as defined in - :attr:`UploadStorageFallbackHandler.BODY_METHODS`) prepares the multipart parsing if content type fits. If it's a - body-less request, just calls the ``fallback`` with an empty body and finishes the request. - """ - if self.request.method in UploadStorageFallbackHandler.BODY_METHODS: - self._bytes_left = self.request.headers.get("Content-Length", 0) - self._content_type = self.request.headers.get("Content-Type", None) - - # request might contain a body - if self.is_multipart(): - if not self._bytes_left: - # we don't support requests without a content-length - raise tornado.web.HTTPError(411, log_message="No Content-Length supplied") - - # extract the multipart boundary - fields = self._content_type.split(";") - for field in fields: - k, sep, v = field.strip().partition("=") - if k == "boundary" and v: - if v.startswith('"') and v.endswith('"'): - self._multipart_boundary = tornado.escape.utf8(v[1:-1]) - else: - self._multipart_boundary = tornado.escape.utf8(v) - break - else: - # RFC2046 section 5.1 (as referred to from RFC 7578) defines the boundary - # parameter as mandatory for multipart requests: - # - # The only mandatory global parameter for the "multipart" media type is - # the boundary parameter, which consists of 1 to 70 characters [...] - # - # So no boundary? 400 Bad Request - raise tornado.web.HTTPError(400, log_message="No multipart boundary supplied") - else: - self._fallback(self.request, b"") - self._finished = True - - def data_received(self, chunk): - """ - Called by Tornado on receiving a chunk of the request body. If request is a multipart request, takes care of - processing the multipart data structure via :func:`_process_multipart_data`. If not, just adds the chunk to - internal in-memory buffer. - - :param chunk: chunk of data received from Tornado - """ - - data = self._buffer + chunk - if self.is_multipart(): - self._process_multipart_data(data) - else: - self._buffer = data - - def is_multipart(self): - """Checks whether this request is a ``multipart`` request""" - return self._content_type is not None and self._content_type.startswith("multipart") - - def _process_multipart_data(self, data): - """ - Processes the given data, parsing it for multipart definitions and calling the appropriate methods. - - :param data: the data to process as a string - """ - - # check for boundary - delimiter = b"--%s" % self._multipart_boundary - delimiter_loc = data.find(delimiter) - delimiter_len = len(delimiter) - end_of_header = -1 - if delimiter_loc != -1: - # found the delimiter in the currently available data - delimiter_data_end = 0 if delimiter_loc == 0 else delimiter_loc - 2 - data, self._buffer = data[0:delimiter_data_end], data[delimiter_loc:] - end_of_header = self._buffer.find(b"\r\n\r\n") - else: - # make sure any boundary (with single or double ==) contained at the end of chunk does not get - # truncated by this processing round => save it to the buffer for next round - endlen = len(self._multipart_boundary) + 4 - data, self._buffer = data[0:-endlen], data[-endlen:] - - # stream data to part handler - if data and self._current_part: - self._on_part_data(self._current_part, data) - - if end_of_header >= 0: - self._on_part_header(self._buffer[delimiter_len+2:end_of_header]) - self._buffer = self._buffer[end_of_header + 4:] - - if delimiter_loc != -1 and self._buffer.strip() == delimiter + b"--": - # we saw the last boundary and are at the end of our request - if self._current_part: - self._on_part_finish(self._current_part) - self._current_part = None - self._buffer = b"" - self._on_request_body_finish() - - def _on_part_header(self, header): - """ - Called for a new multipart header, takes care of parsing the header and calling :func:`_on_part` with the - relevant data, setting the current part in the process. - - :param header: header to parse - """ - - # close any open parts - if self._current_part: - self._on_part_finish(self._current_part) - self._current_part = None - - header_check = header.find(self._multipart_boundary) - if header_check != -1: - self._logger.warning("Header still contained multipart boundary, stripping it...") - header = header[header_check:] - - # convert to dict - try: - header = tornado.httputil.HTTPHeaders.parse(header.decode("utf-8")) - except UnicodeDecodeError: - try: - header = tornado.httputil.HTTPHeaders.parse(header.decode("iso-8859-1")) - except Exception: - # looks like we couldn't decode something here neither as UTF-8 nor ISO-8859-1 - self._logger.warning("Could not decode multipart headers in request, should be either UTF-8 or ISO-8859-1") - self.send_error(400) - return - - disp_header = header.get("Content-Disposition", "") - disposition, disp_params = _parse_header(disp_header, strip_quotes=False) - - if disposition != "form-data": - self._logger.warning("Got a multipart header without form-data content disposition, ignoring that one") - return - if not disp_params.get("name"): - self._logger.warning("Got a multipart header without name, ignoring that one") - return - - filename = disp_params.get("filename*", None) # RFC 5987 header present? - if filename is not None: - try: - filename = _extended_header_value(filename) - except Exception: - # parse error, this is not RFC 5987 compliant after all - self._logger.warning("extended filename* value {!r} is not RFC 5987 compliant".format(filename)) - self.send_error(400) - return - else: - # no filename* header, just strip quotes from filename header then and be done - filename = _strip_value_quotes(disp_params.get("filename", None)) - - self._current_part = self._on_part_start(_strip_value_quotes(disp_params["name"]), - header.get("Content-Type", None), - filename=filename) - - def _on_part_start(self, name, content_type, filename=None): - """ - Called for new parts in the multipart stream. If ``filename`` is given creates new ``file`` part (which leads - to storage of the data as temporary file on disk), if not creates a new ``data`` part (which stores - incoming data in memory). - - Structure of ``file`` parts: - - * ``name``: name of the part - * ``filename``: filename associated with the part - * ``path``: path to the temporary file storing the file's data - * ``content_type``: content type of the part - * ``file``: file handle for the temporary file (mode "wb", not deleted on close, will be deleted however after - handling of the request has finished in :func:`_handle_method`) - - Structure of ``data`` parts: - - * ``name``: name of the part - * ``content_type``: content type of the part - * ``data``: bytes of the part (initialized to an empty string) - - :param name: name of the part - :param content_type: content type of the part - :param filename: filename associated with the part. - :return: dict describing the new part - """ - if filename is not None: - # this is a file - import tempfile - handle = tempfile.NamedTemporaryFile(mode="wb", prefix=self._file_prefix, suffix=self._file_suffix, dir=self._path, delete=False) - return {"name": tornado.escape.utf8(name), - "filename": tornado.escape.utf8(filename), - "path": tornado.escape.utf8(handle.name), - "content_type": tornado.escape.utf8(content_type), - "file": handle} - - else: - return {"name": tornado.escape.utf8(name), "content_type": tornado.escape.utf8(content_type), "data": b""} - - def _on_part_data(self, part, data): - """ - Called when new bytes are received for the given ``part``, takes care of writing them to their storage. - - :param part: part for which data was received - :param data: data chunk which was received - """ - if "file" in part: - part["file"].write(data) - else: - part["data"] += data - - def _on_part_finish(self, part): - """ - Called when a part gets closed, takes care of storing the finished part in the internal parts storage and for - ``file`` parts closing the temporary file and storing the part in the internal files storage. - - :param part: part which was closed - """ - name = part["name"] - self._parts[name] = part - if "file" in part: - self._files.append(part["path"]) - part["file"].close() - del part["file"] - - def _on_request_body_finish(self): - """ - Called when the request body has been read completely. Takes care of creating the replacement body out of the - logged parts, turning ``file`` parts into new ``data`` parts. - """ - - self._new_body = b"" - for name, part in self._parts.items(): - if "filename" in part: - # add form fields for filename, path, size and content_type for all files contained in the request - if not "path" in part: - continue - - parameters = {"name": part["filename"], - "path": part["path"], - "size": str(os.stat(part["path"]).st_size)} - if "content_type" in part: - parameters["content_type"] = part["content_type"] - - fields = dict((self._suffixes[key], value) for (key, value) in parameters.items()) - for n, p in fields.items(): - if n is None or p is None: - continue - key = name + b"." + octoprint.util.to_bytes(n) - self._new_body += b"--%s\r\n" % self._multipart_boundary - self._new_body += b"Content-Disposition: form-data; name=\"%s\"\r\n" % key - self._new_body += b"Content-Type: text/plain; charset=utf-8\r\n" - self._new_body += b"\r\n" - self._new_body += octoprint.util.to_bytes(p) + b'\r\n' - elif "data" in part: - self._new_body += b"--%s\r\n" % self._multipart_boundary - value = part["data"] - self._new_body += b"Content-Disposition: form-data; name=\"%s\"\r\n" % name - if "content_type" in part and part["content_type"] is not None: - self._new_body += b"Content-Type: %s\r\n" % part["content_type"] - self._new_body += b"\r\n" - self._new_body += value + b"\r\n" - self._new_body += b"--%s--\r\n" % self._multipart_boundary - - def _handle_method(self, *args, **kwargs): - """ - Takes care of defining the new request body if necessary and forwarding - the current request and changed body to the ``fallback``. - """ - - # determine which body to supply - body = b"" - if self.is_multipart(): - # make sure we really processed all data in the buffer - while len(self._buffer): - self._process_multipart_data(self._buffer) - - # use rewritten body - body = self._new_body - - elif self.request.method in UploadStorageFallbackHandler.BODY_METHODS: - # directly use data from buffer - body = self._buffer - - # rewrite content length - self.request.headers["Content-Length"] = len(body) - - try: - # call the configured fallback with request and body to use - self._fallback(self.request, body) - self._headers_written = True - finally: - # make sure the temporary files are removed again - for f in self._files: - octoprint.util.silent_remove(f) - - # make all http methods trigger _handle_method - get = _handle_method - post = _handle_method - put = _handle_method - patch = _handle_method - delete = _handle_method - head = _handle_method - options = _handle_method + .. code-block:: none + + ------WebKitFormBoundarypYiSUx63abAmhT5C + Content-Disposition: form-data; name="apikey" + + my_funny_apikey + ------WebKitFormBoundarypYiSUx63abAmhT5C + Content-Disposition: form-data; name="select" + + true + ------WebKitFormBoundarypYiSUx63abAmhT5C + Content-Disposition: form-data; name="file.path" + Content-Type: text/plain; charset=utf-8 + + /tmp/tmpzupkro + ------WebKitFormBoundarypYiSUx63abAmhT5C + Content-Disposition: form-data; name="file.name" + Content-Type: text/plain; charset=utf-8 + + test.gcode + ------WebKitFormBoundarypYiSUx63abAmhT5C + Content-Disposition: form-data; name="file.content_type" + Content-Type: text/plain; charset=utf-8 + + application/octet-stream + ------WebKitFormBoundarypYiSUx63abAmhT5C + Content-Disposition: form-data; name="file.size" + Content-Type: text/plain; charset=utf-8 + + 349182 + ------WebKitFormBoundarypYiSUx63abAmhT5C-- + + The underlying application can then access the contained files via their respective paths and just move them + where necessary. + """ + + BODY_METHODS = ("POST", "PATCH", "PUT") + """ The request methods that may contain a request body. """ + + def initialize( + self, fallback, file_prefix="tmp", file_suffix="", path=None, suffixes=None + ): + if not suffixes: + suffixes = {} + + self._fallback = fallback + self._file_prefix = file_prefix + self._file_suffix = file_suffix + self._path = path + + self._suffixes = dict( + (key, key) for key in ("name", "path", "content_type", "size") + ) + for suffix_type, suffix in suffixes.items(): + if suffix_type in self._suffixes and suffix is not None: + self._suffixes[suffix_type] = suffix + + # multipart boundary + self._multipart_boundary = None + + # Parts, files and values will be stored here + self._parts = {} + self._files = [] + + # Part currently being processed + self._current_part = None + + # content type of request body + self._content_type = None + + # bytes left to read according to content_length of request body + self._bytes_left = 0 + + # buffer needed for identifying form data parts + self._buffer = b"" + + # buffer for new body + self._new_body = b"" + + # logger + self._logger = logging.getLogger(__name__) + + def prepare(self): + """ + Prepares the processing of the request. If it's a request that may contain a request body (as defined in + :attr:`UploadStorageFallbackHandler.BODY_METHODS`) prepares the multipart parsing if content type fits. If it's a + body-less request, just calls the ``fallback`` with an empty body and finishes the request. + """ + if self.request.method in UploadStorageFallbackHandler.BODY_METHODS: + self._bytes_left = self.request.headers.get("Content-Length", 0) + self._content_type = self.request.headers.get("Content-Type", None) + + # request might contain a body + if self.is_multipart(): + if not self._bytes_left: + # we don't support requests without a content-length + raise tornado.web.HTTPError( + 411, log_message="No Content-Length supplied" + ) + + # extract the multipart boundary + fields = self._content_type.split(";") + for field in fields: + k, sep, v = field.strip().partition("=") + if k == "boundary" and v: + if v.startswith('"') and v.endswith('"'): + self._multipart_boundary = tornado.escape.utf8(v[1:-1]) + else: + self._multipart_boundary = tornado.escape.utf8(v) + break + else: + # RFC2046 section 5.1 (as referred to from RFC 7578) defines the boundary + # parameter as mandatory for multipart requests: + # + # The only mandatory global parameter for the "multipart" media type is + # the boundary parameter, which consists of 1 to 70 characters [...] + # + # So no boundary? 400 Bad Request + raise tornado.web.HTTPError( + 400, log_message="No multipart boundary supplied" + ) + else: + self._fallback(self.request, b"") + self._finished = True + + def data_received(self, chunk): + """ + Called by Tornado on receiving a chunk of the request body. If request is a multipart request, takes care of + processing the multipart data structure via :func:`_process_multipart_data`. If not, just adds the chunk to + internal in-memory buffer. + + :param chunk: chunk of data received from Tornado + """ + + data = self._buffer + chunk + if self.is_multipart(): + self._process_multipart_data(data) + else: + self._buffer = data + + def is_multipart(self): + """Checks whether this request is a ``multipart`` request""" + return self._content_type is not None and self._content_type.startswith( + "multipart" + ) + + def _process_multipart_data(self, data): + """ + Processes the given data, parsing it for multipart definitions and calling the appropriate methods. + + :param data: the data to process as a string + """ + + # check for boundary + delimiter = b"--%s" % self._multipart_boundary + delimiter_loc = data.find(delimiter) + delimiter_len = len(delimiter) + end_of_header = -1 + if delimiter_loc != -1: + # found the delimiter in the currently available data + delimiter_data_end = 0 if delimiter_loc == 0 else delimiter_loc - 2 + data, self._buffer = data[0:delimiter_data_end], data[delimiter_loc:] + end_of_header = self._buffer.find(b"\r\n\r\n") + else: + # make sure any boundary (with single or double ==) contained at the end of chunk does not get + # truncated by this processing round => save it to the buffer for next round + endlen = len(self._multipart_boundary) + 4 + data, self._buffer = data[0:-endlen], data[-endlen:] + + # stream data to part handler + if data and self._current_part: + self._on_part_data(self._current_part, data) + + if end_of_header >= 0: + self._on_part_header(self._buffer[delimiter_len + 2 : end_of_header]) + self._buffer = self._buffer[end_of_header + 4 :] + + if delimiter_loc != -1 and self._buffer.strip() == delimiter + b"--": + # we saw the last boundary and are at the end of our request + if self._current_part: + self._on_part_finish(self._current_part) + self._current_part = None + self._buffer = b"" + self._on_request_body_finish() + + def _on_part_header(self, header): + """ + Called for a new multipart header, takes care of parsing the header and calling :func:`_on_part` with the + relevant data, setting the current part in the process. + + :param header: header to parse + """ + + # close any open parts + if self._current_part: + self._on_part_finish(self._current_part) + self._current_part = None + + header_check = header.find(self._multipart_boundary) + if header_check != -1: + self._logger.warning( + "Header still contained multipart boundary, stripping it..." + ) + header = header[header_check:] + + # convert to dict + try: + header = tornado.httputil.HTTPHeaders.parse(header.decode("utf-8")) + except UnicodeDecodeError: + try: + header = tornado.httputil.HTTPHeaders.parse(header.decode("iso-8859-1")) + except Exception: + # looks like we couldn't decode something here neither as UTF-8 nor ISO-8859-1 + self._logger.warning( + "Could not decode multipart headers in request, should be either UTF-8 or ISO-8859-1" + ) + self.send_error(400) + return + + disp_header = header.get("Content-Disposition", "") + disposition, disp_params = _parse_header(disp_header, strip_quotes=False) + + if disposition != "form-data": + self._logger.warning( + "Got a multipart header without form-data content disposition, ignoring that one" + ) + return + if not disp_params.get("name"): + self._logger.warning("Got a multipart header without name, ignoring that one") + return + + filename = disp_params.get("filename*", None) # RFC 5987 header present? + if filename is not None: + try: + filename = _extended_header_value(filename) + except Exception: + # parse error, this is not RFC 5987 compliant after all + self._logger.warning( + "extended filename* value {!r} is not RFC 5987 compliant".format( + filename + ) + ) + self.send_error(400) + return + else: + # no filename* header, just strip quotes from filename header then and be done + filename = _strip_value_quotes(disp_params.get("filename", None)) + + self._current_part = self._on_part_start( + _strip_value_quotes(disp_params["name"]), + header.get("Content-Type", None), + filename=filename, + ) + + def _on_part_start(self, name, content_type, filename=None): + """ + Called for new parts in the multipart stream. If ``filename`` is given creates new ``file`` part (which leads + to storage of the data as temporary file on disk), if not creates a new ``data`` part (which stores + incoming data in memory). + + Structure of ``file`` parts: + + * ``name``: name of the part + * ``filename``: filename associated with the part + * ``path``: path to the temporary file storing the file's data + * ``content_type``: content type of the part + * ``file``: file handle for the temporary file (mode "wb", not deleted on close, will be deleted however after + handling of the request has finished in :func:`_handle_method`) + + Structure of ``data`` parts: + + * ``name``: name of the part + * ``content_type``: content type of the part + * ``data``: bytes of the part (initialized to an empty string) + + :param name: name of the part + :param content_type: content type of the part + :param filename: filename associated with the part. + :return: dict describing the new part + """ + if filename is not None: + # this is a file + import tempfile + + handle = tempfile.NamedTemporaryFile( + mode="wb", + prefix=self._file_prefix, + suffix=self._file_suffix, + dir=self._path, + delete=False, + ) + return { + "name": tornado.escape.utf8(name), + "filename": tornado.escape.utf8(filename), + "path": tornado.escape.utf8(handle.name), + "content_type": tornado.escape.utf8(content_type), + "file": handle, + } + + else: + return { + "name": tornado.escape.utf8(name), + "content_type": tornado.escape.utf8(content_type), + "data": b"", + } + + def _on_part_data(self, part, data): + """ + Called when new bytes are received for the given ``part``, takes care of writing them to their storage. + + :param part: part for which data was received + :param data: data chunk which was received + """ + if "file" in part: + part["file"].write(data) + else: + part["data"] += data + + def _on_part_finish(self, part): + """ + Called when a part gets closed, takes care of storing the finished part in the internal parts storage and for + ``file`` parts closing the temporary file and storing the part in the internal files storage. + + :param part: part which was closed + """ + name = part["name"] + self._parts[name] = part + if "file" in part: + self._files.append(part["path"]) + part["file"].close() + del part["file"] + + def _on_request_body_finish(self): + """ + Called when the request body has been read completely. Takes care of creating the replacement body out of the + logged parts, turning ``file`` parts into new ``data`` parts. + """ + + self._new_body = b"" + for name, part in self._parts.items(): + if "filename" in part: + # add form fields for filename, path, size and content_type for all files contained in the request + if not "path" in part: + continue + + parameters = { + "name": part["filename"], + "path": part["path"], + "size": str(os.stat(part["path"]).st_size), + } + if "content_type" in part: + parameters["content_type"] = part["content_type"] + + fields = dict( + (self._suffixes[key], value) for (key, value) in parameters.items() + ) + for n, p in fields.items(): + if n is None or p is None: + continue + key = name + b"." + octoprint.util.to_bytes(n) + self._new_body += b"--%s\r\n" % self._multipart_boundary + self._new_body += ( + b'Content-Disposition: form-data; name="%s"\r\n' % key + ) + self._new_body += b"Content-Type: text/plain; charset=utf-8\r\n" + self._new_body += b"\r\n" + self._new_body += octoprint.util.to_bytes(p) + b"\r\n" + elif "data" in part: + self._new_body += b"--%s\r\n" % self._multipart_boundary + value = part["data"] + self._new_body += b'Content-Disposition: form-data; name="%s"\r\n' % name + if "content_type" in part and part["content_type"] is not None: + self._new_body += b"Content-Type: %s\r\n" % part["content_type"] + self._new_body += b"\r\n" + self._new_body += value + b"\r\n" + self._new_body += b"--%s--\r\n" % self._multipart_boundary + + def _handle_method(self, *args, **kwargs): + """ + Takes care of defining the new request body if necessary and forwarding + the current request and changed body to the ``fallback``. + """ + + # determine which body to supply + body = b"" + if self.is_multipart(): + # make sure we really processed all data in the buffer + while len(self._buffer): + self._process_multipart_data(self._buffer) + + # use rewritten body + body = self._new_body + + elif self.request.method in UploadStorageFallbackHandler.BODY_METHODS: + # directly use data from buffer + body = self._buffer + + # rewrite content length + self.request.headers["Content-Length"] = len(body) + + try: + # call the configured fallback with request and body to use + self._fallback(self.request, body) + self._headers_written = True + finally: + # make sure the temporary files are removed again + for f in self._files: + octoprint.util.silent_remove(f) + + # make all http methods trigger _handle_method + get = _handle_method + post = _handle_method + put = _handle_method + patch = _handle_method + delete = _handle_method + head = _handle_method + options = _handle_method def _parse_header(line, strip_quotes=True): - parts = tornado.httputil._parseparam(';' + line) - key = next(parts) - pdict = {} - for p in parts: - i = p.find('=') - if i >= 0: - name = p[:i].strip().lower() - value = p[i + 1:].strip() - if strip_quotes: - value = _strip_value_quotes(value) - pdict[name] = value - return key, pdict + parts = tornado.httputil._parseparam(";" + line) + key = next(parts) + pdict = {} + for p in parts: + i = p.find("=") + if i >= 0: + name = p[:i].strip().lower() + value = p[i + 1 :].strip() + if strip_quotes: + value = _strip_value_quotes(value) + pdict[name] = value + return key, pdict def _strip_value_quotes(value): - if not value: - return value + if not value: + return value - if len(value) >= 2 and value[0] == value[-1] == '"': - value = value[1:-1] - value = value.replace('\\\\', '\\').replace('\\"', '"') + if len(value) >= 2 and value[0] == value[-1] == '"': + value = value[1:-1] + value = value.replace("\\\\", "\\").replace('\\"', '"') - return value + return value def _extended_header_value(value): - if not value: - return value + if not value: + return value - if value.lower().startswith("iso-8859-1'") or value.lower().startswith("utf-8'"): - # RFC 5987 section 3.2 - try: - from urllib import unquote - except ImportError: - from urllib.parse import unquote - encoding, _, value = value.split("'", 2) - if PY3: - return unquote(value, encoding=encoding) - else: - return unquote(octoprint.util.to_bytes(value, encoding="iso-8859-1")).decode(encoding) - else: - # no encoding provided, strip potentially present quotes and call it a day - return octoprint.util.to_unicode(_strip_value_quotes(value), encoding="utf-8") + if value.lower().startswith("iso-8859-1'") or value.lower().startswith("utf-8'"): + # RFC 5987 section 3.2 + try: + from urllib import unquote + except ImportError: + from urllib.parse import unquote + encoding, _, value = value.split("'", 2) + if PY3: + return unquote(value, encoding=encoding) + else: + return unquote(octoprint.util.to_bytes(value, encoding="iso-8859-1")).decode( + encoding + ) + else: + # no encoding provided, strip potentially present quotes and call it a day + return octoprint.util.to_unicode(_strip_value_quotes(value), encoding="utf-8") class WsgiInputContainer(object): - """ - A WSGI container for use with Tornado that allows supplying the request body to be used for ``wsgi.input`` in the - generated WSGI environment upon call. + """ + A WSGI container for use with Tornado that allows supplying the request body to be used for ``wsgi.input`` in the + generated WSGI environment upon call. - A ``RequestHandler`` can thus provide the WSGI application with a stream for the request body, or a modified body. + A ``RequestHandler`` can thus provide the WSGI application with a stream for the request body, or a modified body. - Example usage: + Example usage: - .. code-block:: python + .. code-block:: python - wsgi_app = octoprint.server.util.WsgiInputContainer(octoprint_app) - application = tornado.web.Application([ - (r".*", UploadStorageFallbackHandler, dict(fallback=wsgi_app), - ]) + wsgi_app = octoprint.server.util.WsgiInputContainer(octoprint_app) + application = tornado.web.Application([ + (r".*", UploadStorageFallbackHandler, dict(fallback=wsgi_app), + ]) - The implementation logic is basically the same as ``tornado.wsgi.WSGIContainer`` but the ``__call__`` and ``environ`` - methods have been adjusted to allow for an optionally supplied ``body`` argument which is then used for ``wsgi.input``. - """ + The implementation logic is basically the same as ``tornado.wsgi.WSGIContainer`` but the ``__call__`` and ``environ`` + methods have been adjusted to allow for an optionally supplied ``body`` argument which is then used for ``wsgi.input``. + """ - def __init__(self, wsgi_application, headers=None, forced_headers=None, removed_headers=None): - self.wsgi_application = wsgi_application + def __init__( + self, wsgi_application, headers=None, forced_headers=None, removed_headers=None + ): + self.wsgi_application = wsgi_application - if headers is None: - headers = {} - if forced_headers is None: - forced_headers = {} - if removed_headers is None: - removed_headers = [] + if headers is None: + headers = {} + if forced_headers is None: + forced_headers = {} + if removed_headers is None: + removed_headers = [] - self.headers = headers - self.forced_headers = forced_headers - self.removed_headers = removed_headers + self.headers = headers + self.forced_headers = forced_headers + self.removed_headers = removed_headers - def __call__(self, request, body=None): - """ - Wraps the call against the WSGI app, deriving the WSGI environment from the supplied Tornado ``HTTPServerRequest``. + def __call__(self, request, body=None): + """ + Wraps the call against the WSGI app, deriving the WSGI environment from the supplied Tornado ``HTTPServerRequest``. - :param request: the ``tornado.httpserver.HTTPServerRequest`` to derive the WSGI environment from - :param body: an optional body to use as ``wsgi.input`` instead of ``request.body``, can be a string or a stream - """ + :param request: the ``tornado.httpserver.HTTPServerRequest`` to derive the WSGI environment from + :param body: an optional body to use as ``wsgi.input`` instead of ``request.body``, can be a string or a stream + """ - data = {} - response = [] + data = {} + response = [] - def start_response(status, response_headers, exc_info=None): - data["status"] = status - data["headers"] = response_headers - return response.append - app_response = self.wsgi_application( - WsgiInputContainer.environ(request, body), start_response) - try: - response.extend(app_response) - body = b"".join(response) - finally: - if hasattr(app_response, "close"): - app_response.close() - if not data: - raise Exception("WSGI app did not call start_response") + def start_response(status, response_headers, exc_info=None): + data["status"] = status + data["headers"] = response_headers + return response.append - status_code, reason = data["status"].split(" ", 1) - status_code = int(status_code) - headers = data["headers"] - header_set = {k.lower() for (k, v) in headers} - body = tornado.escape.utf8(body) - if status_code != 304: - if "content-length" not in header_set: - headers.append(("Content-Length", str(len(body)))) - if "content-type" not in header_set: - headers.append(("Content-Type", "text/html; charset=UTF-8")) + app_response = self.wsgi_application( + WsgiInputContainer.environ(request, body), start_response + ) + try: + response.extend(app_response) + body = b"".join(response) + finally: + if hasattr(app_response, "close"): + app_response.close() + if not data: + raise Exception("WSGI app did not call start_response") - header_set = {k.lower() for (k, v) in headers} - for header, value in self.headers.items(): - if header.lower() not in header_set: - headers.append((header, value)) - for header, value in self.forced_headers.items(): - headers.append((header, value)) - headers = [(header, value) for header, value in headers if not header.lower() in self.removed_headers] + status_code, reason = data["status"].split(" ", 1) + status_code = int(status_code) + headers = data["headers"] + header_set = {k.lower() for (k, v) in headers} + body = tornado.escape.utf8(body) + if status_code != 304: + if "content-length" not in header_set: + headers.append(("Content-Length", str(len(body)))) + if "content-type" not in header_set: + headers.append(("Content-Type", "text/html; charset=UTF-8")) - start_line = tornado.httputil.ResponseStartLine("HTTP/1.1", status_code, reason) - header_obj = tornado.httputil.HTTPHeaders() - for key, value in headers: - header_obj.add(key, value) - request.connection.write_headers(start_line, header_obj, chunk=body) - request.connection.finish() - self._log(status_code, request) + header_set = {k.lower() for (k, v) in headers} + for header, value in self.headers.items(): + if header.lower() not in header_set: + headers.append((header, value)) + for header, value in self.forced_headers.items(): + headers.append((header, value)) + headers = [ + (header, value) + for header, value in headers + if not header.lower() in self.removed_headers + ] - @staticmethod - def environ(request, body=None): - """ - Converts a ``tornado.httputil.HTTPServerRequest`` to a WSGI environment. + start_line = tornado.httputil.ResponseStartLine("HTTP/1.1", status_code, reason) + header_obj = tornado.httputil.HTTPHeaders() + for key, value in headers: + header_obj.add(key, value) + request.connection.write_headers(start_line, header_obj, chunk=body) + request.connection.finish() + self._log(status_code, request) - An optional ``body`` to be used for populating ``wsgi.input`` can be supplied (either a string or a stream). If not - supplied, ``request.body`` will be wrapped into a ``io.BytesIO`` stream and used instead. + @staticmethod + def environ(request, body=None): + """ + Converts a ``tornado.httputil.HTTPServerRequest`` to a WSGI environment. - :param request: the ``tornado.httpserver.HTTPServerRequest`` to derive the WSGI environment from - :param body: an optional body to use as ``wsgi.input`` instead of ``request.body``, can be a string or a stream - """ - from tornado.wsgi import to_wsgi_str - import io + An optional ``body`` to be used for populating ``wsgi.input`` can be supplied (either a string or a stream). If not + supplied, ``request.body`` will be wrapped into a ``io.BytesIO`` stream and used instead. - # determine the request_body to supply as wsgi.input - if body is not None: - if isinstance(body, (bytes, str, unicode)): - request_body = io.BytesIO(tornado.escape.utf8(body)) - else: - request_body = body - else: - request_body = io.BytesIO(tornado.escape.utf8(request.body)) + :param request: the ``tornado.httpserver.HTTPServerRequest`` to derive the WSGI environment from + :param body: an optional body to use as ``wsgi.input`` instead of ``request.body``, can be a string or a stream + """ + from tornado.wsgi import to_wsgi_str + import io - hostport = request.host.split(":") - if len(hostport) == 2: - host = hostport[0] - port = int(hostport[1]) - else: - host = request.host - port = 443 if request.protocol == "https" else 80 - environ = { - "REQUEST_METHOD": request.method, - "SCRIPT_NAME": "", - "PATH_INFO": to_wsgi_str(tornado.escape.url_unescape( - request.path, encoding=None, plus=False)), - "QUERY_STRING": request.query, - "REMOTE_ADDR": request.remote_ip, - "SERVER_NAME": host, - "SERVER_PORT": str(port), - "SERVER_PROTOCOL": request.version, - "wsgi.version": (1, 0), - "wsgi.url_scheme": request.protocol, - "wsgi.input": request_body, - "wsgi.errors": sys.stderr, - "wsgi.multithread": False, - "wsgi.multiprocess": True, - "wsgi.run_once": False, - } - if "Content-Type" in request.headers: - environ["CONTENT_TYPE"] = request.headers.pop("Content-Type") - if "Content-Length" in request.headers: - environ["CONTENT_LENGTH"] = request.headers.pop("Content-Length") - for key, value in request.headers.items(): - environ["HTTP_" + key.replace("-", "_").upper()] = value - return environ + # determine the request_body to supply as wsgi.input + if body is not None: + if isinstance(body, (bytes, str, unicode)): + request_body = io.BytesIO(tornado.escape.utf8(body)) + else: + request_body = body + else: + request_body = io.BytesIO(tornado.escape.utf8(request.body)) - def _log(self, status_code, request): - access_log = logging.getLogger("tornado.access") + hostport = request.host.split(":") + if len(hostport) == 2: + host = hostport[0] + port = int(hostport[1]) + else: + host = request.host + port = 443 if request.protocol == "https" else 80 + environ = { + "REQUEST_METHOD": request.method, + "SCRIPT_NAME": "", + "PATH_INFO": to_wsgi_str( + tornado.escape.url_unescape(request.path, encoding=None, plus=False) + ), + "QUERY_STRING": request.query, + "REMOTE_ADDR": request.remote_ip, + "SERVER_NAME": host, + "SERVER_PORT": str(port), + "SERVER_PROTOCOL": request.version, + "wsgi.version": (1, 0), + "wsgi.url_scheme": request.protocol, + "wsgi.input": request_body, + "wsgi.errors": sys.stderr, + "wsgi.multithread": False, + "wsgi.multiprocess": True, + "wsgi.run_once": False, + } + if "Content-Type" in request.headers: + environ["CONTENT_TYPE"] = request.headers.pop("Content-Type") + if "Content-Length" in request.headers: + environ["CONTENT_LENGTH"] = request.headers.pop("Content-Length") + for key, value in request.headers.items(): + environ["HTTP_" + key.replace("-", "_").upper()] = value + return environ - if status_code < 400: - log_method = access_log.info - elif status_code < 500: - log_method = access_log.warning - else: - log_method = access_log.error - request_time = 1000.0 * request.request_time() - summary = request.method + " " + request.uri + " (" + \ - request.remote_ip + ")" - log_method("%d %s %.2fms", status_code, summary, request_time) + def _log(self, status_code, request): + access_log = logging.getLogger("tornado.access") + + if status_code < 400: + log_method = access_log.info + elif status_code < 500: + log_method = access_log.warning + else: + log_method = access_log.error + request_time = 1000.0 * request.request_time() + summary = request.method + " " + request.uri + " (" + request.remote_ip + ")" + log_method("%d %s %.2fms", status_code, summary, request_time) -#~~ customized HTTP1Connection implementation +# ~~ customized HTTP1Connection implementation class CustomHTTPServer(tornado.httpserver.HTTPServer): - """ - Custom implementation of ``tornado.httpserver.HTTPServer`` that allows defining max body sizes depending on path and - method. + """ + Custom implementation of ``tornado.httpserver.HTTPServer`` that allows defining max body sizes depending on path and + method. - The implementation is mostly taken from ``tornado.httpserver.HTTPServer``, the only difference is the creation - of a ``CustomHTTP1ConnectionParameters`` instance instead of ``tornado.http1connection.HTTP1ConnectionParameters`` - which is supplied with the two new constructor arguments ``max_body_sizes`` and ``max_default_body_size`` and the - creation of a ``CustomHTTP1ServerConnection`` instead of a ``tornado.http1connection.HTTP1ServerConnection`` upon - connection by a client. + The implementation is mostly taken from ``tornado.httpserver.HTTPServer``, the only difference is the creation + of a ``CustomHTTP1ConnectionParameters`` instance instead of ``tornado.http1connection.HTTP1ConnectionParameters`` + which is supplied with the two new constructor arguments ``max_body_sizes`` and ``max_default_body_size`` and the + creation of a ``CustomHTTP1ServerConnection`` instead of a ``tornado.http1connection.HTTP1ServerConnection`` upon + connection by a client. - ``max_body_sizes`` is expected to be an iterable containing tuples of the form (method, path regex, maximum body size), - with method and path regex having to match in order for maximum body size to take affect. + ``max_body_sizes`` is expected to be an iterable containing tuples of the form (method, path regex, maximum body size), + with method and path regex having to match in order for maximum body size to take affect. - ``default_max_body_size`` is the default maximum body size to apply if no specific one from ``max_body_sizes`` matches. - """ - def __init__(self, *args, **kwargs): - pass + ``default_max_body_size`` is the default maximum body size to apply if no specific one from ``max_body_sizes`` matches. + """ - def initialize(self, *args, **kwargs): - default_max_body_size = kwargs.pop("default_max_body_size", None) - max_body_sizes = kwargs.pop("max_body_sizes", None) + def __init__(self, *args, **kwargs): + pass - tornado.httpserver.HTTPServer.initialize(self, *args, **kwargs) + def initialize(self, *args, **kwargs): + default_max_body_size = kwargs.pop("default_max_body_size", None) + max_body_sizes = kwargs.pop("max_body_sizes", None) - additional = {"default_max_body_size": default_max_body_size, - "max_body_sizes": max_body_sizes} - self.conn_params = CustomHTTP1ConnectionParameters.from_stock_params(self.conn_params, **additional) + tornado.httpserver.HTTPServer.initialize(self, *args, **kwargs) + additional = { + "default_max_body_size": default_max_body_size, + "max_body_sizes": max_body_sizes, + } + self.conn_params = CustomHTTP1ConnectionParameters.from_stock_params( + self.conn_params, **additional + ) - def handle_stream(self, stream, address): - context = tornado.httpserver._HTTPRequestContext(stream, address, - self.protocol, - self.trusted_downstream) - conn = CustomHTTP1ServerConnection(stream, self.conn_params, context) - self._connections.add(conn) - conn.start_serving(self) + def handle_stream(self, stream, address): + context = tornado.httpserver._HTTPRequestContext( + stream, address, self.protocol, self.trusted_downstream + ) + conn = CustomHTTP1ServerConnection(stream, self.conn_params, context) + self._connections.add(conn) + conn.start_serving(self) class CustomHTTP1ServerConnection(tornado.http1connection.HTTP1ServerConnection): - """ - A custom implementation of ``tornado.http1connection.HTTP1ServerConnection`` which utilizes a ``CustomHTTP1Connection`` - instead of a ``tornado.http1connection.HTTP1Connection`` in ``_server_request_loop``. The implementation logic is - otherwise the same as ``tornado.http1connection.HTTP1ServerConnection``. - """ + """ + A custom implementation of ``tornado.http1connection.HTTP1ServerConnection`` which utilizes a ``CustomHTTP1Connection`` + instead of a ``tornado.http1connection.HTTP1Connection`` in ``_server_request_loop``. The implementation logic is + otherwise the same as ``tornado.http1connection.HTTP1ServerConnection``. + """ - @tornado.gen.coroutine - def _server_request_loop(self, delegate): - try: - while True: - conn = CustomHTTP1Connection(self.stream, False, - self.params, self.context) - request_delegate = delegate.start_request(self, conn) - try: - ret = yield conn.read_response(request_delegate) - except (tornado.iostream.StreamClosedError, - tornado.iostream.UnsatisfiableReadError): - return - except tornado.http1connection._QuietException: - # This exception was already logged. - conn.close() - return - except Exception: - tornado.http1connection.gen_log.error("Uncaught exception", exc_info=True) - conn.close() - return - if not ret: - return - yield tornado.gen.moment - finally: - delegate.on_close(self) + @tornado.gen.coroutine + def _server_request_loop(self, delegate): + try: + while True: + conn = CustomHTTP1Connection( + self.stream, False, self.params, self.context + ) + request_delegate = delegate.start_request(self, conn) + try: + ret = yield conn.read_response(request_delegate) + except ( + tornado.iostream.StreamClosedError, + tornado.iostream.UnsatisfiableReadError, + ): + return + except tornado.http1connection._QuietException: + # This exception was already logged. + conn.close() + return + except Exception: + tornado.http1connection.gen_log.error( + "Uncaught exception", exc_info=True + ) + conn.close() + return + if not ret: + return + yield tornado.gen.moment + finally: + delegate.on_close(self) class CustomHTTP1Connection(tornado.http1connection.HTTP1Connection): - """ - A custom implementation of ``tornado.http1connection.HTTP1Connection`` which upon checking the ``Content-Length`` of - the request against the configured maximum utilizes ``max_body_sizes`` and ``default_max_body_size`` as a fallback. - """ + """ + A custom implementation of ``tornado.http1connection.HTTP1Connection`` which upon checking the ``Content-Length`` of + the request against the configured maximum utilizes ``max_body_sizes`` and ``default_max_body_size`` as a fallback. + """ - def __init__(self, stream, is_client, params=None, context=None): - if params is None: - params = CustomHTTP1ConnectionParameters() + def __init__(self, stream, is_client, params=None, context=None): + if params is None: + params = CustomHTTP1ConnectionParameters() - tornado.http1connection.HTTP1Connection.__init__(self, stream, is_client, params=params, context=context) + tornado.http1connection.HTTP1Connection.__init__( + self, stream, is_client, params=params, context=context + ) - import re - self._max_body_sizes = list(map(lambda x: (x[0], re.compile(x[1]), x[2]), self.params.max_body_sizes or list())) - self._default_max_body_size = self.params.default_max_body_size or self.stream.max_buffer_size + import re - def _read_body(self, code, headers, delegate): - """ - Basically the same as ``tornado.http1connection.HTTP1Connection._read_body``, but determines the maximum - content length individually for the request (utilizing ``._get_max_content_length``). + self._max_body_sizes = list( + map( + lambda x: (x[0], re.compile(x[1]), x[2]), + self.params.max_body_sizes or list(), + ) + ) + self._default_max_body_size = ( + self.params.default_max_body_size or self.stream.max_buffer_size + ) - If the individual max content length is 0 or smaller no content length is checked. If the content length of the - current request exceeds the individual max content length, the request processing is aborted and an - ``HTTPInputError`` is raised. - """ - if "Content-Length" in headers: - if "Transfer-Encoding" in headers: - # Response cannot contain both Content-Length and - # Transfer-Encoding headers. - # http://tools.ietf.org/html/rfc7230#section-3.3.3 - raise tornado.httputil.HTTPInputError( - "Response with both Transfer-Encoding and Content-Length") - if "," in headers["Content-Length"]: - # Proxies sometimes cause Content-Length headers to get - # duplicated. If all the values are identical then we can - # use them but if they differ it's an error. - pieces = re.split(r',\s*', headers["Content-Length"]) - if any(i != pieces[0] for i in pieces): - raise tornado.httputil.HTTPInputError( - "Multiple unequal Content-Lengths: %r" % - headers["Content-Length"]) - headers["Content-Length"] = pieces[0] + def _read_body(self, code, headers, delegate): + """ + Basically the same as ``tornado.http1connection.HTTP1Connection._read_body``, but determines the maximum + content length individually for the request (utilizing ``._get_max_content_length``). - try: - content_length = int(headers["Content-Length"]) - except ValueError: - # Handles non-integer Content-Length value. - raise tornado.httputil.HTTPInputError( - "Only integer Content-Length is allowed: %s" % headers["Content-Length"]) + If the individual max content length is 0 or smaller no content length is checked. If the content length of the + current request exceeds the individual max content length, the request processing is aborted and an + ``HTTPInputError`` is raised. + """ + if "Content-Length" in headers: + if "Transfer-Encoding" in headers: + # Response cannot contain both Content-Length and + # Transfer-Encoding headers. + # http://tools.ietf.org/html/rfc7230#section-3.3.3 + raise tornado.httputil.HTTPInputError( + "Response with both Transfer-Encoding and Content-Length" + ) + if "," in headers["Content-Length"]: + # Proxies sometimes cause Content-Length headers to get + # duplicated. If all the values are identical then we can + # use them but if they differ it's an error. + pieces = re.split(r",\s*", headers["Content-Length"]) + if any(i != pieces[0] for i in pieces): + raise tornado.httputil.HTTPInputError( + "Multiple unequal Content-Lengths: %r" % headers["Content-Length"] + ) + headers["Content-Length"] = pieces[0] - max_content_length = self._get_max_content_length(self._request_start_line.method, self._request_start_line.path) - if max_content_length is not None and 0 <= max_content_length < content_length: - raise tornado.httputil.HTTPInputError("Content-Length too long") - else: - content_length = None + try: + content_length = int(headers["Content-Length"]) + except ValueError: + # Handles non-integer Content-Length value. + raise tornado.httputil.HTTPInputError( + "Only integer Content-Length is allowed: %s" + % headers["Content-Length"] + ) - if code == 204: - # This response code is not allowed to have a non-empty body, - # and has an implicit length of zero instead of read-until-close. - # http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3 - if ("Transfer-Encoding" in headers or - content_length not in (None, 0)): - raise tornado.httputil.HTTPInputError( - "Response with code %d should not have body" % code) - content_length = 0 + max_content_length = self._get_max_content_length( + self._request_start_line.method, self._request_start_line.path + ) + if ( + max_content_length is not None + and 0 <= max_content_length < content_length + ): + raise tornado.httputil.HTTPInputError("Content-Length too long") + else: + content_length = None - if content_length is not None: - return self._read_fixed_body(content_length, delegate) - if headers.get("Transfer-Encoding") == "chunked": - return self._read_chunked_body(delegate) - if self.is_client: - return self._read_body_until_close(delegate) - return None + if code == 204: + # This response code is not allowed to have a non-empty body, + # and has an implicit length of zero instead of read-until-close. + # http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3 + if "Transfer-Encoding" in headers or content_length not in (None, 0): + raise tornado.httputil.HTTPInputError( + "Response with code %d should not have body" % code + ) + content_length = 0 - def _get_max_content_length(self, method, path): - """ - Gets the max content length for the given method and path. Checks whether method and path match against any - of the specific maximum content lengths supplied in ``max_body_sizes`` and returns that as the maximum content - length if available, otherwise returns ``default_max_body_size``. + if content_length is not None: + return self._read_fixed_body(content_length, delegate) + if headers.get("Transfer-Encoding") == "chunked": + return self._read_chunked_body(delegate) + if self.is_client: + return self._read_body_until_close(delegate) + return None - :param method: method of the request to match against - :param path: path of the request to match against - :return: determine maximum content length to apply to this request, max return 0 for unlimited allowed content - length - """ + def _get_max_content_length(self, method, path): + """ + Gets the max content length for the given method and path. Checks whether method and path match against any + of the specific maximum content lengths supplied in ``max_body_sizes`` and returns that as the maximum content + length if available, otherwise returns ``default_max_body_size``. - for m, p, s in self._max_body_sizes: - if method == m and p.match(path): - return s - return self._default_max_body_size + :param method: method of the request to match against + :param path: path of the request to match against + :return: determine maximum content length to apply to this request, max return 0 for unlimited allowed content + length + """ + + for m, p, s in self._max_body_sizes: + if method == m and p.match(path): + return s + return self._default_max_body_size class CustomHTTP1ConnectionParameters(tornado.http1connection.HTTP1ConnectionParameters): - """ - An implementation of ``tornado.http1connection.HTTP1ConnectionParameters`` that adds two new parameters - ``max_body_sizes`` and ``default_max_body_size``. + """ + An implementation of ``tornado.http1connection.HTTP1ConnectionParameters`` that adds two new parameters + ``max_body_sizes`` and ``default_max_body_size``. - For a description of these please see the documentation of ``CustomHTTPServer`` above. - """ + For a description of these please see the documentation of ``CustomHTTPServer`` above. + """ - def __init__(self, *args, **kwargs): - max_body_sizes = kwargs.pop("max_body_sizes", list()) - default_max_body_size = kwargs.pop("default_max_body_size", None) + def __init__(self, *args, **kwargs): + max_body_sizes = kwargs.pop("max_body_sizes", list()) + default_max_body_size = kwargs.pop("default_max_body_size", None) - tornado.http1connection.HTTP1ConnectionParameters.__init__(self, *args, **kwargs) + tornado.http1connection.HTTP1ConnectionParameters.__init__(self, *args, **kwargs) - self.max_body_sizes = max_body_sizes - self.default_max_body_size = default_max_body_size + self.max_body_sizes = max_body_sizes + self.default_max_body_size = default_max_body_size - @classmethod - def from_stock_params(cls, other, **additional): - kwargs = dict(other.__dict__) - for key, value in additional.items(): - kwargs[key] = value - return cls(**kwargs) - -#~~ customized large response handler + @classmethod + def from_stock_params(cls, other, **additional): + kwargs = dict(other.__dict__) + for key, value in additional.items(): + kwargs[key] = value + return cls(**kwargs) -class LargeResponseHandler(RequestlessExceptionLoggingMixin, - CorsSupportMixin, - tornado.web.StaticFileHandler): - """ - Customized `tornado.web.StaticFileHandler `_ - that allows delivery of the requested resource as attachment and access and request path validation through - optional callbacks. Note that access validation takes place before path validation. +# ~~ customized large response handler - Arguments: - path (str): The system path from which to serve files (this will be forwarded to the ``initialize`` method of - :class:``~tornado.web.StaticFileHandler``) - default_filename (str): The default filename to serve if none is explicitly specified and the request references - a subdirectory of the served path (this will be forwarded to the ``initialize`` method of - :class:``~tornado.web.StaticFileHandler`` as the ``default_filename`` keyword parameter). Defaults to ``None``. - as_attachment (bool): Whether to serve requested files with ``Content-Disposition: attachment`` header (``True``) - or not. Defaults to ``False``. - allow_client_caching (bool): Whether to allow the client to cache (by not setting any ``Cache-Control`` or - ``Expires`` headers on the response) or not. - access_validation (function): Callback to call in the ``get`` method to validate access to the resource. Will - be called with ``self.request`` as parameter which contains the full tornado request object. Should raise - a ``tornado.web.HTTPError`` if access is not allowed in which case the request will not be further processed. - Defaults to ``None`` and hence no access validation being performed. - path_validation (function): Callback to call in the ``get`` method to validate the requested path. Will be called - with the requested path as parameter. Should raise a ``tornado.web.HTTPError`` (e.g. an 404) if the requested - path does not pass validation in which case the request will not be further processed. - Defaults to ``None`` and hence no path validation being performed. - etag_generator (function): Callback to call for generating the value of the ETag response header. Will be - called with the response handler as parameter. May return ``None`` to prevent the ETag response header - from being set. If not provided the last modified time of the file in question will be used as returned - by ``get_content_version``. - name_generator (function): Callback to call for generating the value of the attachment file name header. Will be - called with the requested path as parameter. - mime_type_guesser (function): Callback to guess the mime type to use for the content type encoding of the - response. Will be called with the requested path on disk as parameter. - is_pre_compressed (bool): if the file is expected to be pre-compressed, i.e, if there is a file in the same - directory with the same name, but with '.gz' appended and gzip-encoded - """ - def initialize(self, path, default_filename=None, as_attachment=False, allow_client_caching=True, - access_validation=None, path_validation=None, etag_generator=None, name_generator=None, - mime_type_guesser=None, is_pre_compressed=False, stream_body=False): - tornado.web.StaticFileHandler.initialize(self, os.path.abspath(path), default_filename) - self._as_attachment = as_attachment - self._allow_client_caching = allow_client_caching - self._access_validation = access_validation - self._path_validation = path_validation - self._etag_generator = etag_generator - self._name_generator = name_generator - self._mime_type_guesser = mime_type_guesser - self._is_pre_compressed = is_pre_compressed - self._stream_body = stream_body +class LargeResponseHandler( + RequestlessExceptionLoggingMixin, CorsSupportMixin, tornado.web.StaticFileHandler +): + """ + Customized `tornado.web.StaticFileHandler `_ + that allows delivery of the requested resource as attachment and access and request path validation through + optional callbacks. Note that access validation takes place before path validation. - def should_use_precompressed(self): - return (self._is_pre_compressed - and "gzip" in self.request.headers.get("Accept-Encoding", "")) + Arguments: + path (str): The system path from which to serve files (this will be forwarded to the ``initialize`` method of + :class:``~tornado.web.StaticFileHandler``) + default_filename (str): The default filename to serve if none is explicitly specified and the request references + a subdirectory of the served path (this will be forwarded to the ``initialize`` method of + :class:``~tornado.web.StaticFileHandler`` as the ``default_filename`` keyword parameter). Defaults to ``None``. + as_attachment (bool): Whether to serve requested files with ``Content-Disposition: attachment`` header (``True``) + or not. Defaults to ``False``. + allow_client_caching (bool): Whether to allow the client to cache (by not setting any ``Cache-Control`` or + ``Expires`` headers on the response) or not. + access_validation (function): Callback to call in the ``get`` method to validate access to the resource. Will + be called with ``self.request`` as parameter which contains the full tornado request object. Should raise + a ``tornado.web.HTTPError`` if access is not allowed in which case the request will not be further processed. + Defaults to ``None`` and hence no access validation being performed. + path_validation (function): Callback to call in the ``get`` method to validate the requested path. Will be called + with the requested path as parameter. Should raise a ``tornado.web.HTTPError`` (e.g. an 404) if the requested + path does not pass validation in which case the request will not be further processed. + Defaults to ``None`` and hence no path validation being performed. + etag_generator (function): Callback to call for generating the value of the ETag response header. Will be + called with the response handler as parameter. May return ``None`` to prevent the ETag response header + from being set. If not provided the last modified time of the file in question will be used as returned + by ``get_content_version``. + name_generator (function): Callback to call for generating the value of the attachment file name header. Will be + called with the requested path as parameter. + mime_type_guesser (function): Callback to guess the mime type to use for the content type encoding of the + response. Will be called with the requested path on disk as parameter. + is_pre_compressed (bool): if the file is expected to be pre-compressed, i.e, if there is a file in the same + directory with the same name, but with '.gz' appended and gzip-encoded + """ - def get(self, path, include_body=True): - if self._access_validation is not None: - self._access_validation(self.request) - if self._path_validation is not None: - self._path_validation(path) + def initialize( + self, + path, + default_filename=None, + as_attachment=False, + allow_client_caching=True, + access_validation=None, + path_validation=None, + etag_generator=None, + name_generator=None, + mime_type_guesser=None, + is_pre_compressed=False, + stream_body=False, + ): + tornado.web.StaticFileHandler.initialize( + self, os.path.abspath(path), default_filename + ) + self._as_attachment = as_attachment + self._allow_client_caching = allow_client_caching + self._access_validation = access_validation + self._path_validation = path_validation + self._etag_generator = etag_generator + self._name_generator = name_generator + self._mime_type_guesser = mime_type_guesser + self._is_pre_compressed = is_pre_compressed + self._stream_body = stream_body - if "cookie" in self.request.arguments: - self.set_cookie(self.request.arguments["cookie"][0], "true", path="/") + def should_use_precompressed(self): + return self._is_pre_compressed and "gzip" in self.request.headers.get( + "Accept-Encoding", "" + ) - if self.should_use_precompressed(): - if os.path.exists(os.path.join(self.root, path + ".gz")): - self.set_header("Content-Encoding", "gzip") - path = path + ".gz" - else: - logging.getLogger(__name__).warning("Precompressed assets expected but {}.gz does not exist " - "in {}, using plain file instead.".format(path, self.root)) + def get(self, path, include_body=True): + if self._access_validation is not None: + self._access_validation(self.request) + if self._path_validation is not None: + self._path_validation(path) - if self._stream_body: - return self.streamed_get(path, include_body=include_body) - else: - return tornado.web.StaticFileHandler.get(self, path, include_body=include_body) + if "cookie" in self.request.arguments: + self.set_cookie(self.request.arguments["cookie"][0], "true", path="/") - @tornado.gen.coroutine - def streamed_get(self, path, include_body=True): - """ - Version of StaticFileHandler.get that doesn't support ranges or ETag but streams the content. Helpful for files - that might still change while being transmitted (e.g. log files) - """ + if self.should_use_precompressed(): + if os.path.exists(os.path.join(self.root, path + ".gz")): + self.set_header("Content-Encoding", "gzip") + path = path + ".gz" + else: + logging.getLogger(__name__).warning( + "Precompressed assets expected but {}.gz does not exist " + "in {}, using plain file instead.".format(path, self.root) + ) - # Set up our path instance variables. - self.path = self.parse_url_path(path) - del path # make sure we don't refer to path instead of self.path again - absolute_path = self.get_absolute_path(self.root, self.path) - self.absolute_path = self.validate_absolute_path(self.root, absolute_path) - if self.absolute_path is None: - return + if self._stream_body: + return self.streamed_get(path, include_body=include_body) + else: + return tornado.web.StaticFileHandler.get( + self, path, include_body=include_body + ) - content_type = self.get_content_type() - if content_type: - self.set_header("Content-Type", content_type) - self.set_extra_headers(self.path) + @tornado.gen.coroutine + def streamed_get(self, path, include_body=True): + """ + Version of StaticFileHandler.get that doesn't support ranges or ETag but streams the content. Helpful for files + that might still change while being transmitted (e.g. log files) + """ - if include_body: - content = self.get_content(self.absolute_path) - if isinstance(content, bytes): - content = [content] - for chunk in content: - try: - self.write(chunk) - yield self.flush() - except tornado.iostream.StreamClosedError: - return - else: - assert self.request.method == "HEAD" + # Set up our path instance variables. + self.path = self.parse_url_path(path) + del path # make sure we don't refer to path instead of self.path again + absolute_path = self.get_absolute_path(self.root, self.path) + self.absolute_path = self.validate_absolute_path(self.root, absolute_path) + if self.absolute_path is None: + return - def set_extra_headers(self, path): - if self._as_attachment: - filename = None - if callable(self._name_generator): - filename = self._name_generator(path) - if filename is None: - filename = os.path.basename(path) + content_type = self.get_content_type() + if content_type: + self.set_header("Content-Type", content_type) + self.set_extra_headers(self.path) - filename = tornado.escape.url_escape(filename, plus=False) - self.set_header("Content-Disposition", "attachment; filename=\"{}\"; filename*=UTF-8''{}".format(filename, - filename)) + if include_body: + content = self.get_content(self.absolute_path) + if isinstance(content, bytes): + content = [content] + for chunk in content: + try: + self.write(chunk) + yield self.flush() + except tornado.iostream.StreamClosedError: + return + else: + assert self.request.method == "HEAD" - if not self._allow_client_caching: - self.set_header("Cache-Control", "max-age=0, must-revalidate, private") - self.set_header("Expires", "-1") + def set_extra_headers(self, path): + if self._as_attachment: + filename = None + if callable(self._name_generator): + filename = self._name_generator(path) + if filename is None: + filename = os.path.basename(path) - @property - def original_absolute_path(self): - """The path of the uncompressed file corresponding to the compressed file""" - if self._is_pre_compressed: - return self.absolute_path.rstrip('.gz') - return self.absolute_path + filename = tornado.escape.url_escape(filename, plus=False) + self.set_header( + "Content-Disposition", + "attachment; filename=\"{}\"; filename*=UTF-8''{}".format( + filename, filename + ), + ) - def compute_etag(self): - if self._etag_generator is not None: - return self._etag_generator(self) - else: - return self.get_content_version(self.absolute_path) + if not self._allow_client_caching: + self.set_header("Cache-Control", "max-age=0, must-revalidate, private") + self.set_header("Expires", "-1") - # noinspection PyAttributeOutsideInit - def get_content_type(self): - if self._mime_type_guesser is not None: - type = self._mime_type_guesser(self.original_absolute_path) - if type is not None: - return type + @property + def original_absolute_path(self): + """The path of the uncompressed file corresponding to the compressed file""" + if self._is_pre_compressed: + return self.absolute_path.rstrip(".gz") + return self.absolute_path - correct_absolute_path = None - try: - # reset self.absolute_path temporarily - if self.should_use_precompressed(): - correct_absolute_path = self.absolute_path - self.absolute_path = self.original_absolute_path - return tornado.web.StaticFileHandler.get_content_type(self) - finally: - # restore self.absolute_path - if self.should_use_precompressed() and correct_absolute_path is not None: - self.absolute_path = correct_absolute_path + def compute_etag(self): + if self._etag_generator is not None: + return self._etag_generator(self) + else: + return self.get_content_version(self.absolute_path) - @classmethod - def get_content_version(cls, abspath): - import os - import stat - return os.stat(abspath)[stat.ST_MTIME] + # noinspection PyAttributeOutsideInit + def get_content_type(self): + if self._mime_type_guesser is not None: + type = self._mime_type_guesser(self.original_absolute_path) + if type is not None: + return type + + correct_absolute_path = None + try: + # reset self.absolute_path temporarily + if self.should_use_precompressed(): + correct_absolute_path = self.absolute_path + self.absolute_path = self.original_absolute_path + return tornado.web.StaticFileHandler.get_content_type(self) + finally: + # restore self.absolute_path + if self.should_use_precompressed() and correct_absolute_path is not None: + self.absolute_path = correct_absolute_path + + @classmethod + def get_content_version(cls, abspath): + import os + import stat + + return os.stat(abspath)[stat.ST_MTIME] ##~~ URL Forward Handler for forwarding requests to a preconfigured static URL -class UrlProxyHandler(RequestlessExceptionLoggingMixin, - CorsSupportMixin, - tornado.web.RequestHandler): - """ - `tornado.web.RequestHandler `_ that proxies - requests to a preconfigured url and returns the response. Allows delivery of the requested content as attachment - and access validation through an optional callback. +class UrlProxyHandler( + RequestlessExceptionLoggingMixin, CorsSupportMixin, tornado.web.RequestHandler +): + """ + `tornado.web.RequestHandler `_ that proxies + requests to a preconfigured url and returns the response. Allows delivery of the requested content as attachment + and access validation through an optional callback. - This will use `tornado.httpclient.AsyncHTTPClient `_ - for making the request to the configured endpoint and return the body of the client response with the status code - from the client response and the following headers: + This will use `tornado.httpclient.AsyncHTTPClient `_ + for making the request to the configured endpoint and return the body of the client response with the status code + from the client response and the following headers: - * ``Date``, ``Cache-Control``, ``Expires``, ``ETag``, ``Server``, ``Content-Type`` and ``Location`` will be copied over. - * If ``as_attachment`` is set to True, ``Content-Disposition`` will be set to ``attachment``. If ``basename`` is - set including the attachment's ``filename`` attribute will be set to the base name followed by the extension - guessed based on the MIME type from the ``Content-Type`` header of the response. If no extension can be guessed - no ``filename`` attribute will be set. + * ``Date``, ``Cache-Control``, ``Expires``, ``ETag``, ``Server``, ``Content-Type`` and ``Location`` will be copied over. + * If ``as_attachment`` is set to True, ``Content-Disposition`` will be set to ``attachment``. If ``basename`` is + set including the attachment's ``filename`` attribute will be set to the base name followed by the extension + guessed based on the MIME type from the ``Content-Type`` header of the response. If no extension can be guessed + no ``filename`` attribute will be set. - Arguments: - url (str): URL to forward any requests to. A 404 response will be returned if this is not set. Defaults to ``None``. - as_attachment (bool): Whether to serve files with ``Content-Disposition: attachment`` header (``True``) - or not. Defaults to ``False``. - basename (str): base name of file names to return as part of the attachment header, see above. Defaults to ``None``. - access_validation (function): Callback to call in the ``get`` method to validate access to the resource. Will - be called with ``self.request`` as parameter which contains the full tornado request object. Should raise - a ``tornado.web.HTTPError`` if access is not allowed in which case the request will not be further processed. - Defaults to ``None`` and hence no access validation being performed. - """ + Arguments: + url (str): URL to forward any requests to. A 404 response will be returned if this is not set. Defaults to ``None``. + as_attachment (bool): Whether to serve files with ``Content-Disposition: attachment`` header (``True``) + or not. Defaults to ``False``. + basename (str): base name of file names to return as part of the attachment header, see above. Defaults to ``None``. + access_validation (function): Callback to call in the ``get`` method to validate access to the resource. Will + be called with ``self.request`` as parameter which contains the full tornado request object. Should raise + a ``tornado.web.HTTPError`` if access is not allowed in which case the request will not be further processed. + Defaults to ``None`` and hence no access validation being performed. + """ - def initialize(self, url=None, as_attachment=False, basename=None, access_validation=None): - tornado.web.RequestHandler.initialize(self) - self._url = url - self._as_attachment = as_attachment - self._basename = basename - self._access_validation = access_validation + def initialize( + self, url=None, as_attachment=False, basename=None, access_validation=None + ): + tornado.web.RequestHandler.initialize(self) + self._url = url + self._as_attachment = as_attachment + self._basename = basename + self._access_validation = access_validation - @tornado.gen.coroutine - def get(self, *args, **kwargs): - if self._access_validation is not None: - self._access_validation(self.request) + @tornado.gen.coroutine + def get(self, *args, **kwargs): + if self._access_validation is not None: + self._access_validation(self.request) - if self._url is None: - raise tornado.web.HTTPError(404) + if self._url is None: + raise tornado.web.HTTPError(404) - client = tornado.httpclient.AsyncHTTPClient() - r = tornado.httpclient.HTTPRequest(url=self._url, method=self.request.method, body=self.request.body, headers=self.request.headers, follow_redirects=False, allow_nonstandard_methods=True) + client = tornado.httpclient.AsyncHTTPClient() + r = tornado.httpclient.HTTPRequest( + url=self._url, + method=self.request.method, + body=self.request.body, + headers=self.request.headers, + follow_redirects=False, + allow_nonstandard_methods=True, + ) - try: - return client.fetch(r, self.handle_response) - except tornado.web.HTTPError as e: - if hasattr(e, "response") and e.response: - self.handle_response(e.response) - else: - raise tornado.web.HTTPError(500) + try: + return client.fetch(r, self.handle_response) + except tornado.web.HTTPError as e: + if hasattr(e, "response") and e.response: + self.handle_response(e.response) + else: + raise tornado.web.HTTPError(500) - def handle_response(self, response): - if response.error and not isinstance(response.error, tornado.web.HTTPError): - raise tornado.web.HTTPError(500) + def handle_response(self, response): + if response.error and not isinstance(response.error, tornado.web.HTTPError): + raise tornado.web.HTTPError(500) - filename = None + filename = None - self.set_status(response.code) - for name in ("Date", "Cache-Control", "Server", "Content-Type", "Location", "Expires", "ETag"): - value = response.headers.get(name) - if value: - self.set_header(name, value) + self.set_status(response.code) + for name in ( + "Date", + "Cache-Control", + "Server", + "Content-Type", + "Location", + "Expires", + "ETag", + ): + value = response.headers.get(name) + if value: + self.set_header(name, value) - if name == "Content-Type": - filename = self.get_filename(value) + if name == "Content-Type": + filename = self.get_filename(value) - if self._as_attachment: - if filename is not None: - self.set_header("Content-Disposition", "attachment; filename=%s" % filename) - else: - self.set_header("Content-Disposition", "attachment") + if self._as_attachment: + if filename is not None: + self.set_header( + "Content-Disposition", "attachment; filename=%s" % filename + ) + else: + self.set_header("Content-Disposition", "attachment") - if response.body: - self.write(response.body) - self.finish() + if response.body: + self.write(response.body) + self.finish() - def get_filename(self, content_type): - if not self._basename: - return None + def get_filename(self, content_type): + if not self._basename: + return None - typeValue = list(x.strip() for x in content_type.split(";")) - if len(typeValue) == 0: - return None + typeValue = list(x.strip() for x in content_type.split(";")) + if len(typeValue) == 0: + return None - extension = mimetypes.guess_extension(typeValue[0]) - if not extension: - return None + extension = mimetypes.guess_extension(typeValue[0]) + if not extension: + return None - return "%s%s" % (self._basename, extension) + return "%s%s" % (self._basename, extension) -class StaticDataHandler(RequestlessExceptionLoggingMixin, - CorsSupportMixin, - tornado.web.RequestHandler): - """ - `tornado.web.RequestHandler `_ that returns - static ``data`` of a configured ``content_type``. +class StaticDataHandler( + RequestlessExceptionLoggingMixin, CorsSupportMixin, tornado.web.RequestHandler +): + """ + `tornado.web.RequestHandler `_ that returns + static ``data`` of a configured ``content_type``. - Arguments: - data (str): The data with which to respond - content_type (str): The content type with which to respond. Defaults to ``text/plain`` - """ + Arguments: + data (str): The data with which to respond + content_type (str): The content type with which to respond. Defaults to ``text/plain`` + """ - def initialize(self, data="", content_type="text/plain"): - self.data = data - self.content_type = content_type + def initialize(self, data="", content_type="text/plain"): + self.data = data + self.content_type = content_type - def get(self, *args, **kwargs): - self.set_status(200) - self.set_header("Content-Type", self.content_type) - self.write(self.data) - self.flush() - self.finish() + def get(self, *args, **kwargs): + self.set_status(200) + self.set_header("Content-Type", self.content_type) + self.write(self.data) + self.flush() + self.finish() -class DeprecatedEndpointHandler(CorsSupportMixin, - tornado.web.RequestHandler): - """ - `tornado.web.RequestHandler `_ that redirects - to another ``url`` and logs a deprecation warning. +class DeprecatedEndpointHandler(CorsSupportMixin, tornado.web.RequestHandler): + """ + `tornado.web.RequestHandler `_ that redirects + to another ``url`` and logs a deprecation warning. - Arguments: - url (str): URL to which to redirect - """ + Arguments: + url (str): URL to which to redirect + """ - def initialize(self, url): - self._url = url - self._logger = logging.getLogger(__name__) + def initialize(self, url): + self._url = url + self._logger = logging.getLogger(__name__) - def _handle_method(self, *args, **kwargs): - to_url = self._url.format(*args) - self._logger.info("Redirecting deprecated endpoint {} to {}".format(self.request.path, to_url)) - self.redirect(to_url, permanent=True) + def _handle_method(self, *args, **kwargs): + to_url = self._url.format(*args) + self._logger.info( + "Redirecting deprecated endpoint {} to {}".format(self.request.path, to_url) + ) + self.redirect(to_url, permanent=True) - # make all http methods trigger _handle_method - get = _handle_method - post = _handle_method - put = _handle_method - patch = _handle_method - delete = _handle_method - head = _handle_method - options = _handle_method + # make all http methods trigger _handle_method + get = _handle_method + post = _handle_method + put = _handle_method + patch = _handle_method + delete = _handle_method + head = _handle_method + options = _handle_method class GlobalHeaderTransform(tornado.web.OutputTransform): - HEADERS = {} - FORCED_HEADERS = {} - REMOVED_HEADERS = [] + HEADERS = {} + FORCED_HEADERS = {} + REMOVED_HEADERS = [] - @classmethod - def for_headers(cls, name, headers=None, forced_headers=None, removed_headers=None): - if headers is None: - headers = {} - if forced_headers is None: - forced_headers = {} - if removed_headers is None: - removed_headers = [] + @classmethod + def for_headers(cls, name, headers=None, forced_headers=None, removed_headers=None): + if headers is None: + headers = {} + if forced_headers is None: + forced_headers = {} + if removed_headers is None: + removed_headers = [] - return type(octoprint.util.to_native_str(name), (GlobalHeaderTransform,), - {"HEADERS": headers, - "FORCED_HEADERS": forced_headers, - "REMOVED_HEADERS": removed_headers}) + return type( + octoprint.util.to_native_str(name), + (GlobalHeaderTransform,), + { + "HEADERS": headers, + "FORCED_HEADERS": forced_headers, + "REMOVED_HEADERS": removed_headers, + }, + ) - def __init__(self, request): - tornado.web.OutputTransform.__init__(self, request) + def __init__(self, request): + tornado.web.OutputTransform.__init__(self, request) - def transform_first_chunk(self, status_code, headers, chunk, finishing): - for header, value in self.HEADERS.items(): - if not header in headers: - headers[header] = value - for header, value in self.FORCED_HEADERS.items(): - headers[header] = value - for header in self.REMOVED_HEADERS: - del headers[header] - return status_code, headers, chunk + def transform_first_chunk(self, status_code, headers, chunk, finishing): + for header, value in self.HEADERS.items(): + if not header in headers: + headers[header] = value + for header, value in self.FORCED_HEADERS.items(): + headers[header] = value + for header in self.REMOVED_HEADERS: + del headers[header] + return status_code, headers, chunk -#~~ Factory method for creating Flask access validation wrappers from the Tornado request context +# ~~ Factory method for creating Flask access validation wrappers from the Tornado request context def access_validation_factory(app, validator, *args): - """ - Creates an access validation wrapper using the supplied validator. + """ + Creates an access validation wrapper using the supplied validator. - :param validator: the access validator to use inside the validation wrapper - :return: an access validator taking a request as parameter and performing the request validation - """ + :param validator: the access validator to use inside the validation wrapper + :return: an access validator taking a request as parameter and performing the request validation + """ - # noinspection PyProtectedMember - def f(request): - """ - Creates a custom wsgi and Flask request context in order to be able to process user information - stored in the current session. + # noinspection PyProtectedMember + def f(request): + """ + Creates a custom wsgi and Flask request context in order to be able to process user information + stored in the current session. - :param request: The Tornado request for which to create the environment and context - """ - import flask + :param request: The Tornado request for which to create the environment and context + """ + import flask - wsgi_environ = WsgiInputContainer.environ(request) - with app.request_context(wsgi_environ): - session = app.session_interface.open_session(app, flask.request) - user_id = session.get("_user_id") - user = None + wsgi_environ = WsgiInputContainer.environ(request) + with app.request_context(wsgi_environ): + session = app.session_interface.open_session(app, flask.request) + user_id = session.get("_user_id") + user = None - # Yes, using protected methods is ugly. But these used to be publicly available in former versions - # of flask-login, there are no replacements, and seeing them renamed & hidden in a minor version release - # without any mention in the changelog means the public API ain't strictly stable either, so we might - # as well make our life easier here and just use them... - if user_id is not None and app.login_manager._user_callback is not None: - user = app.login_manager._user_callback(user_id) - app.login_manager._update_request_context_with_user(user) + # Yes, using protected methods is ugly. But these used to be publicly available in former versions + # of flask-login, there are no replacements, and seeing them renamed & hidden in a minor version release + # without any mention in the changelog means the public API ain't strictly stable either, so we might + # as well make our life easier here and just use them... + if user_id is not None and app.login_manager._user_callback is not None: + user = app.login_manager._user_callback(user_id) + app.login_manager._update_request_context_with_user(user) + + validator(flask.request, *args) + + return f - validator(flask.request, *args) - return f def path_validation_factory(path_filter, status_code=404): - """ - Creates a request path validation wrapper returning the defined status code if the supplied path_filter returns False. + """ + Creates a request path validation wrapper returning the defined status code if the supplied path_filter returns False. + + :param path_filter: the path filter to use on the requested path, should return False for requests that should + be responded with the provided error code. + :return: a request path validator taking a request path as parameter and performing the request validation + """ + + def f(path): + if not path_filter(path): + raise tornado.web.HTTPError(status_code) + + return f - :param path_filter: the path filter to use on the requested path, should return False for requests that should - be responded with the provided error code. - :return: a request path validator taking a request path as parameter and performing the request validation - """ - def f(path): - if not path_filter(path): - raise tornado.web.HTTPError(status_code) - return f def validation_chain(*validators): - def f(request): - for validator in validators: - validator(request) - return f + def f(request): + for validator in validators: + validator(request) + + return f diff --git a/src/octoprint/server/util/watchdog.py b/src/octoprint/server/util/watchdog.py index 02ad7f27c..56ed3fe7b 100644 --- a/src/octoprint/server/util/watchdog.py +++ b/src/octoprint/server/util/watchdog.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__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 logging @@ -18,174 +18,223 @@ import octoprint.util def fix_scandir(): - try: - from os import scandir - # nothing to fix, natively available, return - return + try: + from os import scandir - except ImportError: - # not natively available, use backport - from scandir import scandir + # nothing to fix, natively available, return + return - import watchdog.utils.dirsnapshot - OriginalDirectorySnapshot = watchdog.utils.dirsnapshot.DirectorySnapshot - class FixedDirectorySnapshot(OriginalDirectorySnapshot): - def __init__(self, listdir=scandir, *args, **kwargs): - OriginalDirectorySnapshot.__init__(self, listdir=listdir, *args, **kwargs) - watchdog.utils.dirsnapshot.DirectorySnapshot = FixedDirectorySnapshot + except ImportError: + # not natively available, use backport + from scandir import scandir + + import watchdog.utils.dirsnapshot + + OriginalDirectorySnapshot = watchdog.utils.dirsnapshot.DirectorySnapshot + + class FixedDirectorySnapshot(OriginalDirectorySnapshot): + def __init__(self, listdir=scandir, *args, **kwargs): + OriginalDirectorySnapshot.__init__(self, listdir=listdir, *args, **kwargs) + + watchdog.utils.dirsnapshot.DirectorySnapshot = FixedDirectorySnapshot + + import watchdog.observers.polling + + OriginalPollingEmitter = watchdog.observers.polling.PollingEmitter + + class FixedPollingEmitter(OriginalPollingEmitter): + def __init__(self, listdir=scandir, *args, **kwargs): + OriginalPollingEmitter.__init__(self, listdir=listdir, *args, **kwargs) + + watchdog.observers.polling.PollingEmitter = FixedPollingEmitter - import watchdog.observers.polling - OriginalPollingEmitter = watchdog.observers.polling.PollingEmitter - class FixedPollingEmitter(OriginalPollingEmitter): - def __init__(self, listdir=scandir, *args, **kwargs): - OriginalPollingEmitter.__init__(self, listdir=listdir, *args, **kwargs) - watchdog.observers.polling.PollingEmitter = FixedPollingEmitter class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler): - """ - Takes care of automatically "uploading" files that get added to the watched folder. - """ + """ + Takes care of automatically "uploading" files that get added to the watched folder. + """ - def __init__(self, file_manager, printer): - watchdog.events.PatternMatchingEventHandler.__init__(self, patterns=list(map(lambda x: "*.%s" % x, octoprint.filemanager.get_all_extensions()))) + def __init__(self, file_manager, printer): + watchdog.events.PatternMatchingEventHandler.__init__( + self, + patterns=list( + map(lambda x: "*.%s" % x, octoprint.filemanager.get_all_extensions()) + ), + ) - self._logger = logging.getLogger(__name__) + self._logger = logging.getLogger(__name__) - self._file_manager = file_manager - self._printer = printer + self._file_manager = file_manager + self._printer = printer - self._watched_folder = None + self._watched_folder = None - def initial_scan(self, folder): - try: - from os import scandir - except ImportError: - from scandir import scandir + def initial_scan(self, folder): + try: + from os import scandir + except ImportError: + from scandir import scandir - def _recursive_scandir(path): - """Recursively yield DirEntry objects for given directory.""" - for entry in scandir(path): - if entry.is_dir(follow_symlinks=False): - for entry in _recursive_scandir(entry.path): - yield entry - else: - yield entry + def _recursive_scandir(path): + """Recursively yield DirEntry objects for given directory.""" + for entry in scandir(path): + if entry.is_dir(follow_symlinks=False): + for entry in _recursive_scandir(entry.path): + yield entry + else: + yield entry - def run_scan(): - self._logger.info("Running initial scan on watched folder...") - self._watched_folder = folder + def run_scan(): + self._logger.info("Running initial scan on watched folder...") + self._watched_folder = folder - for entry in _recursive_scandir(folder): - path = entry.path + for entry in _recursive_scandir(folder): + path = entry.path - if not self._valid_path(path): - continue + if not self._valid_path(path): + continue - self._logger.info("Found {}, trying to add it".format(path)) - self._upload(path) - self._logger.info("... initial scan done.") + self._logger.info("Found {}, trying to add it".format(path)) + self._upload(path) + self._logger.info("... initial scan done.") - thread = threading.Thread(target=run_scan) - thread.daemon = True - thread.start() + thread = threading.Thread(target=run_scan) + thread.daemon = True + thread.start() - def on_created(self, event): - self._start_check(event.src_path) + def on_created(self, event): + self._start_check(event.src_path) - def on_moved(self, event): - # for move/rename we are only interested in the dest_path - self._start_check(event.dest_path) + def on_moved(self, event): + # for move/rename we are only interested in the dest_path + self._start_check(event.dest_path) - def _start_check(self, path): - if not self._valid_path(path): - return + def _start_check(self, path): + if not self._valid_path(path): + return - thread = threading.Thread(target=self._repeatedly_check, args=(path,)) - thread.daemon = True - thread.start() + thread = threading.Thread(target=self._repeatedly_check, args=(path,)) + thread.daemon = True + thread.start() - def _upload(self, path): - # noinspection PyBroadException - try: - file_wrapper = octoprint.filemanager.util.DiskFileWrapper(os.path.basename(path), path) - relative_path = os.path.relpath(path, self._watched_folder) + def _upload(self, path): + # noinspection PyBroadException + try: + file_wrapper = octoprint.filemanager.util.DiskFileWrapper( + os.path.basename(path), path + ) + relative_path = os.path.relpath(path, self._watched_folder) - # determine future filename of file to be uploaded, abort if it can't be uploaded - try: - futurePath, futureFilename = self._file_manager.sanitize(octoprint.filemanager.FileDestinations.LOCAL, relative_path) - except Exception: - self._logger.exception("Could not wrap %s", path) - futurePath = None - futureFilename = None + # determine future filename of file to be uploaded, abort if it can't be uploaded + try: + futurePath, futureFilename = self._file_manager.sanitize( + octoprint.filemanager.FileDestinations.LOCAL, relative_path + ) + except Exception: + self._logger.exception("Could not wrap %s", path) + futurePath = None + futureFilename = None - if futureFilename is None or (len(self._file_manager.registered_slicers) == 0 and not octoprint.filemanager.valid_file_type(futureFilename)): - return + if futureFilename is None or ( + len(self._file_manager.registered_slicers) == 0 + and not octoprint.filemanager.valid_file_type(futureFilename) + ): + return - # prohibit overwriting currently selected file while it's being printed - futureFullPath = self._file_manager.join_path(octoprint.filemanager.FileDestinations.LOCAL, futurePath, futureFilename) - futureFullPathInStorage = self._file_manager.path_in_storage(octoprint.filemanager.FileDestinations.LOCAL, futureFullPath) + # prohibit overwriting currently selected file while it's being printed + futureFullPath = self._file_manager.join_path( + octoprint.filemanager.FileDestinations.LOCAL, futurePath, futureFilename + ) + futureFullPathInStorage = self._file_manager.path_in_storage( + octoprint.filemanager.FileDestinations.LOCAL, futureFullPath + ) - if not self._printer.can_modify_file(futureFullPathInStorage, False): - return + if not self._printer.can_modify_file(futureFullPathInStorage, False): + return - reselect = self._printer.is_current_file(futureFullPathInStorage, False) + reselect = self._printer.is_current_file(futureFullPathInStorage, False) - added_file = self._file_manager.add_file(octoprint.filemanager.FileDestinations.LOCAL, - relative_path, - file_wrapper, - allow_overwrite=True) - if os.path.exists(path): - try: - os.remove(path) - except Exception: - pass + added_file = self._file_manager.add_file( + octoprint.filemanager.FileDestinations.LOCAL, + relative_path, + file_wrapper, + allow_overwrite=True, + ) + if os.path.exists(path): + try: + os.remove(path) + except Exception: + pass - if reselect: - self._printer.select_file(self._file_manager.path_on_disk(octoprint.filemanager.FileDestinations.LOCAL, - added_file), - False) - except Exception: - self._logger.exception("There was an error while processing the file {} in the watched folder".format(path)) - finally: - if os.path.exists(path): - # file is still there - that should only happen if something went wrong, so mark it as failed - # noinspection PyBroadException - try: - shutil.move(path, "{}.failed".format(path)) - except: - # something went really wrong here.... but we can't do anything about it, so just log it - self._logger.exception("There was an error while trying to mark {} as failed in the watched folder".format(path)) + if reselect: + self._printer.select_file( + self._file_manager.path_on_disk( + octoprint.filemanager.FileDestinations.LOCAL, added_file + ), + False, + ) + except Exception: + self._logger.exception( + "There was an error while processing the file {} in the watched folder".format( + path + ) + ) + finally: + if os.path.exists(path): + # file is still there - that should only happen if something went wrong, so mark it as failed + # noinspection PyBroadException + try: + shutil.move(path, "{}.failed".format(path)) + except: + # something went really wrong here.... but we can't do anything about it, so just log it + self._logger.exception( + "There was an error while trying to mark {} as failed in the watched folder".format( + path + ) + ) - def _repeatedly_check(self, path, interval=1, stable=5): - try: - last_size = os.stat(path).st_size - except Exception: - return + def _repeatedly_check(self, path, interval=1, stable=5): + try: + last_size = os.stat(path).st_size + except Exception: + return - countdown = stable + countdown = stable - while True: - try: - new_size = os.stat(path).st_size - except Exception: - return + while True: + try: + new_size = os.stat(path).st_size + except Exception: + return - if new_size == last_size: - self._logger.debug("File at {} is no longer growing, counting down: {}".format(path, countdown)) - countdown -= 1 - if countdown <= 0: - break - else: - self._logger.debug("File at {} is still growing (last: {}, new: {}), waiting...".format(path, last_size, new_size)) - countdown = stable + if new_size == last_size: + self._logger.debug( + "File at {} is no longer growing, counting down: {}".format( + path, countdown + ) + ) + countdown -= 1 + if countdown <= 0: + break + else: + self._logger.debug( + "File at {} is still growing (last: {}, new: {}), waiting...".format( + path, last_size, new_size + ) + ) + countdown = stable - last_size = new_size - time.sleep(interval) + last_size = new_size + time.sleep(interval) - self._logger.debug("File at {} is stable, moving it".format(path)) - self._upload(path) + self._logger.debug("File at {} is stable, moving it".format(path)) + self._upload(path) - def _valid_path(self, path): - _, ext = os.path.splitext(path) - return octoprint.filemanager.valid_file_type(path) and not octoprint.util.is_hidden_path(path) and ext != "failed" + def _valid_path(self, path): + _, ext = os.path.splitext(path) + return ( + octoprint.filemanager.valid_file_type(path) + and not octoprint.util.is_hidden_path(path) + and ext != "failed" + ) diff --git a/src/octoprint/server/util/webassets.py b/src/octoprint/server/util/webassets.py index 9a7f37316..12092114b 100644 --- a/src/octoprint/server/util/webassets.py +++ b/src/octoprint/server/util/webassets.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" import logging @@ -11,9 +11,9 @@ import os import re try: - from urllib import parse as urlparse + from urllib import parse as urlparse except ImportError: - import urlparse + import urlparse from webassets.bundle import Bundle from webassets.merge import MemoryHunk, BaseHunk @@ -23,162 +23,177 @@ import webassets.filter.cssrewrite.urlpath as urlpath def replace_url(source_url, output_url, url): - # If path is an absolute one, keep it - parsed = urlparse.urlparse(url) + # If path is an absolute one, keep it + parsed = urlparse.urlparse(url) - if not parsed.scheme and not parsed.path.startswith('/'): - abs_source_url = urlparse.urljoin(source_url, url) + if not parsed.scheme and not parsed.path.startswith("/"): + abs_source_url = urlparse.urljoin(source_url, url) - # relpath() will not detect this case - if urlparse.urlparse(abs_source_url).scheme: - return abs_source_url + # relpath() will not detect this case + if urlparse.urlparse(abs_source_url).scheme: + return abs_source_url - # rewritten url: relative path from new location (output) - # to location of referenced file (source + current url) - url = urlpath.relpath(output_url, abs_source_url) + # rewritten url: relative path from new location (output) + # to location of referenced file (source + current url) + url = urlpath.relpath(output_url, abs_source_url) - return url + return url class UrlRewriter(PatternRewriter): + def input(self, _in, out, **kw): + source, source_path, output, output_path = ( + kw["source"], + kw["source_path"], + kw["output"], + kw["output_path"], + ) - def input(self, _in, out, **kw): - source, source_path, output, output_path = \ - kw['source'], kw['source_path'], kw['output'], kw['output_path'] + self.source_path = source_path + self.output_path = output_path + self.source_url = self.ctx.resolver.resolve_source_to_url( + self.ctx, source_path, source + ) + self.output_url = self.ctx.resolver.resolve_output_to_url(self.ctx, output) - self.source_path = source_path - self.output_path = output_path - self.source_url = self.ctx.resolver.resolve_source_to_url( - self.ctx, source_path, source) - self.output_url = self.ctx.resolver.resolve_output_to_url( - self.ctx, output) + return super(UrlRewriter, self).input(_in, out, **kw) - return super(UrlRewriter, self).input(_in, out, **kw) - - def replace_url(self, url): - return replace_url(self.source_url, self.output_url, url) + def replace_url(self, url): + return replace_url(self.source_url, self.output_url, url) class LessImportRewrite(UrlRewriter): - name = "less_importrewrite" + name = "less_importrewrite" - patterns = { - "import_rewrite": re.compile(r"(@import(\s+\(.*\))?\s+)\"(.*)\";") - } + patterns = {"import_rewrite": re.compile(r"(@import(\s+\(.*\))?\s+)\"(.*)\";")} - def import_rewrite(self, m): - import_with_options = m.group(1) - import_url = self.replace_url(m.group(3)) - return "{import_with_options}\"{import_url}\";".format(**locals()) + def import_rewrite(self, m): + import_with_options = m.group(1) + import_url = self.replace_url(m.group(3)) + return '{import_with_options}"{import_url}";'.format(**locals()) class SourceMapRewrite(UrlRewriter): - name = "sourcemap_urlrewrite" + name = "sourcemap_urlrewrite" - patterns = { - "url_rewrite": re.compile(r"(//#\s+sourceMappingURL=)(.*)") - } + patterns = {"url_rewrite": re.compile(r"(//#\s+sourceMappingURL=)(.*)")} - def url_rewrite(self, m): - mapping = m.group(1) - source_url = self.replace_url(m.group(2)) - return "{mapping}{source_url}".format(**locals()) + def url_rewrite(self, m): + mapping = m.group(1) + source_url = self.replace_url(m.group(2)) + return "{mapping}{source_url}".format(**locals()) class SourceMapRemove(PatternRewriter): - name = "sourcemap_remove" + name = "sourcemap_remove" - patterns = { - "sourcemap_remove": re.compile(r"(//#\s+sourceMappingURL=)(.*)") - } + patterns = {"sourcemap_remove": re.compile(r"(//#\s+sourceMappingURL=)(.*)")} - def sourcemap_remove(self, m): - return "" + def sourcemap_remove(self, m): + return "" class JsDelimiterBundler(Filter): - name = "js_delimiter_bundler" - options = {} + name = "js_delimiter_bundler" + options = {} - def input(self, _in, out, **kwargs): - source = kwargs.get("source", "n/a") + def input(self, _in, out, **kwargs): + source = kwargs.get("source", "n/a") - out.write("// source: " + source + "\n") - out.write(_in.read()) - out.write("\n;\n") + out.write("// source: " + source + "\n") + out.write(_in.read()) + out.write("\n;\n") class GzipFile(Filter): - name = "gzip" - options = {} + name = "gzip" + options = {} - def output(self, _in, out, **kwargs): - data = _in.read() - out.write(data) + def output(self, _in, out, **kwargs): + data = _in.read() + out.write(data) - # webassets requires us to output a "str", but we can't do that since gzip - # provides binary outputs. - # - # We work around that by outputting the gzipped file to another path - output_path = kwargs.get("output_path", None) - if output_path: - gzipped_output_path = output_path + ".gz" - try: - with gzip.open(gzipped_output_path, "wb", 9) as f: - f.write(data.encode("utf8")) - except Exception: - logging.getLogger(__name__).exception("Error writing gzipped " - "output of {} to {}".format(output_path, - gzipped_output_path)) - try: - os.remove(gzipped_output_path) - except Exception: - logging.getLogger(__name__).exception("Error removing broken " - ".gz from {}".format(gzipped_output_path)) + # webassets requires us to output a "str", but we can't do that since gzip + # provides binary outputs. + # + # We work around that by outputting the gzipped file to another path + output_path = kwargs.get("output_path", None) + if output_path: + gzipped_output_path = output_path + ".gz" + try: + with gzip.open(gzipped_output_path, "wb", 9) as f: + f.write(data.encode("utf8")) + except Exception: + logging.getLogger(__name__).exception( + "Error writing gzipped " + "output of {} to {}".format(output_path, gzipped_output_path) + ) + try: + os.remove(gzipped_output_path) + except Exception: + logging.getLogger(__name__).exception( + "Error removing broken " ".gz from {}".format(gzipped_output_path) + ) class ChainedHunk(BaseHunk): - def __init__(self, *hunks): - self._hunks = hunks + def __init__(self, *hunks): + self._hunks = hunks - def mtime(self): - pass + def mtime(self): + pass - def data(self): - result = "" - for hunk in self._hunks: - if isinstance(hunk, tuple) and len(hunk) == 2: - hunk, f = hunk - else: - f = lambda x: x - result += f(hunk.data()) - return result + def data(self): + result = "" + for hunk in self._hunks: + if isinstance(hunk, tuple) and len(hunk) == 2: + hunk, f = hunk + else: + f = lambda x: x + result += f(hunk.data()) + return result -_PLUGIN_BUNDLE_WRAPPER_PREFIX = \ -"""// JS assets for plugin {plugin} +_PLUGIN_BUNDLE_WRAPPER_PREFIX = """// JS assets for plugin {plugin} (function () {{ try {{ """ -_PLUGIN_BUNDLE_WRAPPER_SUFFIX = \ -""" +_PLUGIN_BUNDLE_WRAPPER_SUFFIX = """ }} catch (error) {{ log.error("Error in JS assets for plugin {plugin}:", (error.stack || error)); }} }})(); """ + + class JsPluginBundle(Bundle): - def __init__(self, plugin, *args, **kwargs): - Bundle.__init__(self, *args, **kwargs) - self.plugin = plugin + def __init__(self, plugin, *args, **kwargs): + Bundle.__init__(self, *args, **kwargs) + self.plugin = plugin - def _merge_and_apply(self, ctx, output, force, parent_debug=None, - parent_filters=None, extra_filters=None, - disable_cache=None): - hunk = Bundle._merge_and_apply(self, ctx, output, force, parent_debug=parent_debug, - parent_filters=parent_filters, extra_filters=extra_filters, - disable_cache=disable_cache) + def _merge_and_apply( + self, + ctx, + output, + force, + parent_debug=None, + parent_filters=None, + extra_filters=None, + disable_cache=None, + ): + hunk = Bundle._merge_and_apply( + self, + ctx, + output, + force, + parent_debug=parent_debug, + parent_filters=parent_filters, + extra_filters=extra_filters, + disable_cache=disable_cache, + ) - return ChainedHunk(MemoryHunk(_PLUGIN_BUNDLE_WRAPPER_PREFIX.format(plugin=self.plugin)), - (hunk, lambda x: x.replace("\n", "\n ")), - MemoryHunk(_PLUGIN_BUNDLE_WRAPPER_SUFFIX.format(plugin=self.plugin))) + return ChainedHunk( + MemoryHunk(_PLUGIN_BUNDLE_WRAPPER_PREFIX.format(plugin=self.plugin)), + (hunk, lambda x: x.replace("\n", "\n ")), + MemoryHunk(_PLUGIN_BUNDLE_WRAPPER_SUFFIX.format(plugin=self.plugin)), + ) diff --git a/src/octoprint/server/views.py b/src/octoprint/server/views.py index edeec9598..97b94f23f 100644 --- a/src/octoprint/server/views.py +++ b/src/octoprint/server/views.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import os @@ -12,13 +12,34 @@ import io from past.builtins import basestring from collections import defaultdict -from flask import request, g, url_for, make_response, render_template, send_from_directory, redirect, abort, Response +from flask import ( + request, + g, + url_for, + make_response, + render_template, + send_from_directory, + redirect, + abort, + Response, +) import octoprint.plugin -from octoprint.server import app, userManager, groupManager, pluginManager, gettext, \ - debug, LOCALES, VERSION, DISPLAY_VERSION, BRANCH, preemptiveCache, \ - NOT_MODIFIED +from octoprint.server import ( + app, + userManager, + groupManager, + pluginManager, + gettext, + debug, + LOCALES, + VERSION, + DISPLAY_VERSION, + BRANCH, + preemptiveCache, + NOT_MODIFIED, +) from octoprint.access.permissions import Permissions, OctoPrintPermission from octoprint.settings import settings from octoprint.filemanager import full_extension_tree, get_all_extensions @@ -31,6 +52,7 @@ import base64 from . import util import logging + _logger = logging.getLogger(__name__) _templates = {} @@ -40,1203 +62,1658 @@ _plugin_vars = None _valid_id_re = re.compile("[a-z_]+") _valid_div_re = re.compile("[a-zA-Z_-]+") + def _preemptive_unless(base_url=None, additional_unless=None): - if base_url is None: - base_url = request.url_root + if base_url is None: + base_url = request.url_root - disabled_for_root = not settings().getBoolean(["devel", "cache", "preemptive"]) \ - or base_url in settings().get(["server", "preemptiveCache", "exceptions"]) \ - or not (base_url.startswith("http://") or base_url.startswith("https://")) + disabled_for_root = ( + not settings().getBoolean(["devel", "cache", "preemptive"]) + or base_url in settings().get(["server", "preemptiveCache", "exceptions"]) + or not (base_url.startswith("http://") or base_url.startswith("https://")) + ) - recording_disabled = request.headers.get("X-Preemptive-Recording", "no") == "yes" + recording_disabled = request.headers.get("X-Preemptive-Recording", "no") == "yes" - if callable(additional_unless): - return recording_disabled or disabled_for_root or additional_unless() - else: - return recording_disabled or disabled_for_root + if callable(additional_unless): + return recording_disabled or disabled_for_root or additional_unless() + else: + return recording_disabled or disabled_for_root -def _preemptive_data(key, path=None, base_url=None, data=None, additional_request_data=None): - if path is None: - path = request.path - if base_url is None: - base_url = request.url_root - d = {"path": path, - "base_url": base_url, - "query_string": "l10n={}".format(g.locale.language if g.locale else "en")} +def _preemptive_data( + key, path=None, base_url=None, data=None, additional_request_data=None +): + if path is None: + path = request.path + if base_url is None: + base_url = request.url_root - if key != "_default": - d["plugin"] = key + d = { + "path": path, + "base_url": base_url, + "query_string": "l10n={}".format(g.locale.language if g.locale else "en"), + } - # add data if we have any - if data is not None: - try: - if callable(data): - data = data() - if data: - if "query_string" in data: - data["query_string"] = "l10n={}&{}".format(g.locale.language, data["query_string"]) - d.update(data) - except Exception: - _logger.exception("Error collecting data for preemptive cache from plugin {}".format(key)) + if key != "_default": + d["plugin"] = key - # add additional request data if we have any - if callable(additional_request_data): - try: - ard = additional_request_data() - if ard: - d.update({"_additional_request_data": ard}) - except Exception: - _logger.exception("Error retrieving additional data for preemptive cache from plugin {}".format(key)) + # add data if we have any + if data is not None: + try: + if callable(data): + data = data() + if data: + if "query_string" in data: + data["query_string"] = "l10n={}&{}".format( + g.locale.language, data["query_string"] + ) + d.update(data) + except Exception: + _logger.exception( + "Error collecting data for preemptive cache from plugin {}".format(key) + ) + + # add additional request data if we have any + if callable(additional_request_data): + try: + ard = additional_request_data() + if ard: + d.update({"_additional_request_data": ard}) + except Exception: + _logger.exception( + "Error retrieving additional data for preemptive cache from plugin {}".format( + key + ) + ) + + return d - return d def _cache_key(ui, url=None, locale=None, additional_key_data=None): - if url is None: - url = request.base_url - if locale is None: - locale = g.locale.language if g.locale else "en" + if url is None: + url = request.base_url + if locale is None: + locale = g.locale.language if g.locale else "en" + + k = "ui:{}:{}:{}".format(ui, url, locale) + if callable(additional_key_data): + try: + ak = additional_key_data() + if ak: + # we have some additional key components, let's attach them + if not isinstance(ak, (list, tuple)): + ak = [ak] + k = "{}:{}".format(k, ":".join(ak)) + except Exception: + _logger.exception( + "Error while trying to retrieve additional cache key parts for ui {}".format( + ui + ) + ) + return k - k = "ui:{}:{}:{}".format(ui, url, locale) - if callable(additional_key_data): - try: - ak = additional_key_data() - if ak: - # we have some additional key components, let's attach them - if not isinstance(ak, (list, tuple)): - ak = [ak] - k = "{}:{}".format(k, ":".join(ak)) - except Exception: - _logger.exception("Error while trying to retrieve additional cache key parts for ui {}".format(ui)) - return k def _valid_status_for_cache(status_code): - return 200 <= status_code < 400 + return 200 <= status_code < 400 + def _add_additional_assets(hook): - result = [] - for name, hook in pluginManager.get_hooks(hook).items(): - try: - assets = hook() - if isinstance(assets, (tuple, list)): - result += assets - except: - _logger.exception("Error fetching theming CSS to include from plugin {}".format(name), - extra={"plugin": name}) - return result + result = [] + for name, hook in pluginManager.get_hooks(hook).items(): + try: + assets = hook() + if isinstance(assets, (tuple, list)): + result += assets + except: + _logger.exception( + "Error fetching theming CSS to include from plugin {}".format(name), + extra={"plugin": name}, + ) + return result + def _has_permissions(*permissions): - logged_in = False + logged_in = False - try: - if util.loginUserFromApiKey(): - logged_in = True - except util.InvalidApiKeyException: - pass # ignored + try: + if util.loginUserFromApiKey(): + logged_in = True + except util.InvalidApiKeyException: + pass # ignored - if not logged_in and util.loginUserFromAuthorizationHeader(): - logged_in = True + if not logged_in and util.loginUserFromAuthorizationHeader(): + logged_in = True + + util.flask.passive_login() + return all(map(lambda p: p.can(), permissions)) - util.flask.passive_login() - return all(map(lambda p: p.can(), permissions)) @app.route("/login") @app.route("/login/") def login(): - from flask_login import current_user + from flask_login import current_user - redirect_url = request.args.get("redirect", request.script_root + url_for("index")) - permissions = sorted(filter(lambda x: x is not None and isinstance(x, OctoPrintPermission), - map(lambda x: getattr(Permissions, x.strip()), - request.args.get("permissions", "").split(","))), - key=lambda x: x.get_name()) - if not permissions: - permissions = [Permissions.STATUS, Permissions.SETTINGS_READ] + redirect_url = request.args.get("redirect", request.script_root + url_for("index")) + permissions = sorted( + filter( + lambda x: x is not None and isinstance(x, OctoPrintPermission), + map( + lambda x: getattr(Permissions, x.strip()), + request.args.get("permissions", "").split(","), + ), + ), + key=lambda x: x.get_name(), + ) + if not permissions: + permissions = [Permissions.STATUS, Permissions.SETTINGS_READ] - if _has_permissions(*permissions): - return redirect(redirect_url) + if _has_permissions(*permissions): + return redirect(redirect_url) - render_kwargs = {"theming": [], - "redirect_url": redirect_url, - "permission_names": map(lambda x: x.get_name(), permissions), - "logged_in": not current_user.is_anonymous} + render_kwargs = { + "theming": [], + "redirect_url": redirect_url, + "permission_names": map(lambda x: x.get_name(), permissions), + "logged_in": not current_user.is_anonymous, + } - try: - additional_assets = _add_additional_assets("octoprint.theming.login") + try: + additional_assets = _add_additional_assets("octoprint.theming.login") - # backwards compatibility to forcelogin & loginui plugins which were replaced by this built-in dialog - additional_assets += _add_additional_assets("octoprint.plugin.forcelogin.theming") - additional_assets += _add_additional_assets("octoprint.plugin.loginui.theming") + # backwards compatibility to forcelogin & loginui plugins which were replaced by this built-in dialog + additional_assets += _add_additional_assets("octoprint.plugin.forcelogin.theming") + additional_assets += _add_additional_assets("octoprint.plugin.loginui.theming") - render_kwargs.update({"theming": additional_assets}) - except: - _logger.exception("Error processing theming CSS, ignoring") + render_kwargs.update({"theming": additional_assets}) + except: + _logger.exception("Error processing theming CSS, ignoring") + + return render_template("login.jinja2", **render_kwargs) - return render_template("login.jinja2", **render_kwargs) @app.route("/recovery") @app.route("/recovery/") def recovery(): - if not _has_permissions(Permissions.ADMIN): - return redirect(url_for("login", - redirect=request.script_root + request.full_path, - permissions=Permissions.ADMIN.key)) + if not _has_permissions(Permissions.ADMIN): + return redirect( + url_for( + "login", + redirect=request.script_root + request.full_path, + permissions=Permissions.ADMIN.key, + ) + ) - render_kwargs = {"theming": []} + render_kwargs = {"theming": []} - try: - additional_assets = _add_additional_assets("octoprint.theming.recovery") - render_kwargs.update({"theming": additional_assets}) - except: - _logger.exception("Error processing theming CSS, ignoring") + try: + additional_assets = _add_additional_assets("octoprint.theming.recovery") + render_kwargs.update({"theming": additional_assets}) + except: + _logger.exception("Error processing theming CSS, ignoring") + + return render_template("recovery.jinja2", **render_kwargs) - return render_template("recovery.jinja2", **render_kwargs) @app.route("/cached.gif") def in_cache(): - url = request.base_url.replace("/cached.gif", "/") - path = request.path.replace("/cached.gif", "/") - base_url = request.url_root + url = request.base_url.replace("/cached.gif", "/") + path = request.path.replace("/cached.gif", "/") + base_url = request.url_root - # select view from plugins and fall back on default view if no plugin will handle it - ui_plugins = pluginManager.get_implementations(octoprint.plugin.UiPlugin, - sorting_context="UiPlugin.on_ui_render") - for plugin in ui_plugins: - try: - if plugin.will_handle_ui(request): - ui = plugin._identifier - key = _cache_key(plugin._identifier, - url=url, - additional_key_data=plugin.get_ui_additional_key_data_for_cache) - unless = _preemptive_unless(url, additional_unless=plugin.get_ui_preemptive_caching_additional_unless) - data = _preemptive_data(plugin._identifier, - path=path, - base_url=base_url, - data=plugin.get_ui_data_for_preemptive_caching, - additional_request_data=plugin.get_ui_additional_request_data_for_preemptive_caching) - break - except Exception: - _logger.exception("Error while calling plugin {}, skipping it".format(plugin._identifier), - extra={"plugin": plugin._identifier}) - else: - ui = "_default" - key = _cache_key("_default", url=url) - unless = _preemptive_unless(url) - data = _preemptive_data("_default", path=path, base_url=base_url) + # select view from plugins and fall back on default view if no plugin will handle it + ui_plugins = pluginManager.get_implementations( + octoprint.plugin.UiPlugin, sorting_context="UiPlugin.on_ui_render" + ) + for plugin in ui_plugins: + try: + if plugin.will_handle_ui(request): + ui = plugin._identifier + key = _cache_key( + plugin._identifier, + url=url, + additional_key_data=plugin.get_ui_additional_key_data_for_cache, + ) + unless = _preemptive_unless( + url, + additional_unless=plugin.get_ui_preemptive_caching_additional_unless, + ) + data = _preemptive_data( + plugin._identifier, + path=path, + base_url=base_url, + data=plugin.get_ui_data_for_preemptive_caching, + additional_request_data=plugin.get_ui_additional_request_data_for_preemptive_caching, + ) + break + except Exception: + _logger.exception( + "Error while calling plugin {}, skipping it".format(plugin._identifier), + extra={"plugin": plugin._identifier}, + ) + else: + ui = "_default" + key = _cache_key("_default", url=url) + unless = _preemptive_unless(url) + data = _preemptive_data("_default", path=path, base_url=base_url) - response = make_response(bytes(base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"))) - response.headers["Content-Type"] = "image/gif" + response = make_response( + bytes( + base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7") + ) + ) + response.headers["Content-Type"] = "image/gif" + + if unless or not preemptiveCache.has_record(data, root=path): + _logger.info( + "Preemptive cache not active for path {}, ui {} and data {!r}, signaling as cached".format( + path, ui, data + ) + ) + return response + elif util.flask.is_in_cache(key): + _logger.info( + "Found path {} in cache (key: {}), signaling as cached".format(path, key) + ) + return response + elif util.flask.is_cache_bypassed(key): + _logger.info( + "Path {} was bypassed from cache (key: {}), signaling as cached".format( + path, key + ) + ) + return response + else: + _logger.debug( + "Path {} not yet cached (key: {}), signaling as missing".format(path, key) + ) + return abort(404) - if unless or not preemptiveCache.has_record(data, root=path): - _logger.info("Preemptive cache not active for path {}, ui {} and data {!r}, signaling as cached".format(path, ui, data)) - return response - elif util.flask.is_in_cache(key): - _logger.info("Found path {} in cache (key: {}), signaling as cached".format(path, key)) - return response - elif util.flask.is_cache_bypassed(key): - _logger.info("Path {} was bypassed from cache (key: {}), signaling as cached".format(path, key)) - return response - else: - _logger.debug("Path {} not yet cached (key: {}), signaling as missing".format(path, key)) - return abort(404) @app.route("/") def index(): - from octoprint.server import printer + from octoprint.server import printer - if request.headers.get("X-Preemptive-Recording", "no") == "no" \ - and userManager.enabled \ - and userManager.has_been_customized(): - if not _has_permissions(Permissions.STATUS, Permissions.SETTINGS_READ): - return redirect(url_for("login", - redirect=request.script_root + request.full_path, - permissions=",".join([Permissions.STATUS.key, - Permissions.SETTINGS_READ.key]))) + if ( + request.headers.get("X-Preemptive-Recording", "no") == "no" + and userManager.enabled + and userManager.has_been_customized() + ): + if not _has_permissions(Permissions.STATUS, Permissions.SETTINGS_READ): + return redirect( + url_for( + "login", + redirect=request.script_root + request.full_path, + permissions=",".join( + [Permissions.STATUS.key, Permissions.SETTINGS_READ.key] + ), + ) + ) - global _templates, _plugin_names, _plugin_vars + global _templates, _plugin_names, _plugin_vars - preemptive_cache_enabled = settings().getBoolean(["devel", "cache", "preemptive"]) + preemptive_cache_enabled = settings().getBoolean(["devel", "cache", "preemptive"]) - locale = g.locale.language if g.locale else "en" + locale = g.locale.language if g.locale else "en" - # helper to check if wizards are active - def wizard_active(templates): - return templates is not None and bool(templates["wizard"]["order"]) + # helper to check if wizards are active + def wizard_active(templates): + return templates is not None and bool(templates["wizard"]["order"]) - # we force a refresh if the client forces one and we are not printing or if we have wizards cached - client_refresh = util.flask.cache_check_headers() - request_refresh = "_refresh" in request.values - printing = printer.is_printing() - if client_refresh and printing: - logging.getLogger(__name__).warning("Client requested cache refresh via cache-control headers but we are printing. " - "Not invalidating caches due to resource limitation. Append ?_refresh=true to " - "the URL if you absolutely require a refresh now") - client_refresh = client_refresh and not printing - force_refresh = client_refresh \ - or request_refresh \ - or wizard_active(_templates.get(locale)) + # we force a refresh if the client forces one and we are not printing or if we have wizards cached + client_refresh = util.flask.cache_check_headers() + request_refresh = "_refresh" in request.values + printing = printer.is_printing() + if client_refresh and printing: + logging.getLogger(__name__).warning( + "Client requested cache refresh via cache-control headers but we are printing. " + "Not invalidating caches due to resource limitation. Append ?_refresh=true to " + "the URL if you absolutely require a refresh now" + ) + client_refresh = client_refresh and not printing + force_refresh = ( + client_refresh or request_refresh or wizard_active(_templates.get(locale)) + ) - # if we need to refresh our template cache or it's not yet set, process it - fetch_template_data(refresh=force_refresh) + # if we need to refresh our template cache or it's not yet set, process it + fetch_template_data(refresh=force_refresh) - now = datetime.datetime.utcnow() + now = datetime.datetime.utcnow() - enable_accesscontrol = userManager.enabled - enable_timelapse = settings().getBoolean(["webcam", "timelapseEnabled"]) - enable_loading_animation = settings().getBoolean(["devel", "showLoadingAnimation"]) - enable_sd_support = settings().get(["feature", "sdSupport"]) - enable_webcam = settings().getBoolean(["webcam", "webcamEnabled"]) and bool(settings().get(["webcam", "stream"])) - enable_temperature_graph = settings().get(["feature", "temperatureGraph"]) - sockjs_connect_timeout = settings().getInt(["devel", "sockJsConnectTimeout"]) + enable_accesscontrol = userManager.enabled + enable_timelapse = settings().getBoolean(["webcam", "timelapseEnabled"]) + enable_loading_animation = settings().getBoolean(["devel", "showLoadingAnimation"]) + enable_sd_support = settings().get(["feature", "sdSupport"]) + enable_webcam = settings().getBoolean(["webcam", "webcamEnabled"]) and bool( + settings().get(["webcam", "stream"]) + ) + enable_temperature_graph = settings().get(["feature", "temperatureGraph"]) + sockjs_connect_timeout = settings().getInt(["devel", "sockJsConnectTimeout"]) - def default_template_filter(template_type, template_key): - if template_type == "navbar": - return template_key != "login" or enable_accesscontrol - elif template_type == "tab": - return (template_key != "timelapse" or enable_timelapse) - elif template_type == "settings": - return template_key != "accesscontrol" or enable_accesscontrol - elif template_type == "usersettings": - return enable_accesscontrol - else: - return True + def default_template_filter(template_type, template_key): + if template_type == "navbar": + return template_key != "login" or enable_accesscontrol + elif template_type == "tab": + return template_key != "timelapse" or enable_timelapse + elif template_type == "settings": + return template_key != "accesscontrol" or enable_accesscontrol + elif template_type == "usersettings": + return enable_accesscontrol + else: + return True - default_additional_etag = [enable_accesscontrol, - enable_timelapse, - enable_loading_animation, - enable_sd_support, - enable_webcam, - enable_temperature_graph, - sockjs_connect_timeout, - wizard_active(_templates.get(locale))] + sorted(["{}:{}".format(to_unicode(k, errors="replace"), - to_unicode(v, errors="replace")) - for k, v in _plugin_vars.items()]) + default_additional_etag = [ + enable_accesscontrol, + enable_timelapse, + enable_loading_animation, + enable_sd_support, + enable_webcam, + enable_temperature_graph, + sockjs_connect_timeout, + wizard_active(_templates.get(locale)), + ] + sorted( + [ + "{}:{}".format( + to_unicode(k, errors="replace"), to_unicode(v, errors="replace") + ) + for k, v in _plugin_vars.items() + ] + ) - def get_preemptively_cached_view(key, view, data=None, additional_request_data=None, additional_unless=None): - if (data is None and additional_request_data is None) or g.locale is None: - return view + def get_preemptively_cached_view( + key, view, data=None, additional_request_data=None, additional_unless=None + ): + if (data is None and additional_request_data is None) or g.locale is None: + return view - d = _preemptive_data(key, data=data, additional_request_data=additional_request_data) + d = _preemptive_data( + key, data=data, additional_request_data=additional_request_data + ) - def unless(): - return _preemptive_unless(base_url=request.url_root, additional_unless=additional_unless) + def unless(): + return _preemptive_unless( + base_url=request.url_root, additional_unless=additional_unless + ) - # finally decorate our view - return util.flask.preemptively_cached(cache=preemptiveCache, - data=d, - unless=unless)(view) + # finally decorate our view + return util.flask.preemptively_cached( + cache=preemptiveCache, data=d, unless=unless + )(view) - def get_cached_view(key, view, additional_key_data=None, additional_files=None, additional_etag=None, custom_files=None, custom_etag=None, custom_lastmodified=None): - if additional_etag is None: - additional_etag = [] + def get_cached_view( + key, + view, + additional_key_data=None, + additional_files=None, + additional_etag=None, + custom_files=None, + custom_etag=None, + custom_lastmodified=None, + ): + if additional_etag is None: + additional_etag = [] - def cache_key(): - return _cache_key(key, additional_key_data=additional_key_data) + def cache_key(): + return _cache_key(key, additional_key_data=additional_key_data) - def collect_files(): - if callable(custom_files): - try: - files = custom_files() - if files: - return files - except Exception: - _logger.exception("Error while trying to retrieve tracked files for plugin {}".format(key)) + def collect_files(): + if callable(custom_files): + try: + files = custom_files() + if files: + return files + except Exception: + _logger.exception( + "Error while trying to retrieve tracked files for plugin {}".format( + key + ) + ) - files = _get_all_templates() - files += _get_all_assets() - files += _get_all_translationfiles(g.locale.language if g.locale else "en", - "messages") + files = _get_all_templates() + files += _get_all_assets() + files += _get_all_translationfiles( + g.locale.language if g.locale else "en", "messages" + ) - if callable(additional_files): - try: - af = additional_files() - if af: - files += af - except Exception: - _logger.exception("Error while trying to retrieve additional tracked files for plugin {}".format(key)) + if callable(additional_files): + try: + af = additional_files() + if af: + files += af + except Exception: + _logger.exception( + "Error while trying to retrieve additional tracked files for plugin {}".format( + key + ) + ) - return sorted(set(files)) + return sorted(set(files)) - def compute_lastmodified(files): - if callable(custom_lastmodified): - try: - lastmodified = custom_lastmodified() - if lastmodified: - return lastmodified - except Exception: - _logger.exception("Error while trying to retrieve custom LastModified value for plugin {}".format(key)) + def compute_lastmodified(files): + if callable(custom_lastmodified): + try: + lastmodified = custom_lastmodified() + if lastmodified: + return lastmodified + except Exception: + _logger.exception( + "Error while trying to retrieve custom LastModified value for plugin {}".format( + key + ) + ) - return _compute_date(files) + return _compute_date(files) - def compute_etag(files, lastmodified, additional=None): - if callable(custom_etag): - try: - etag = custom_etag() - if etag: - return etag - except Exception: - _logger.exception("Error while trying to retrieve custom ETag value for plugin {}".format(key)) + def compute_etag(files, lastmodified, additional=None): + if callable(custom_etag): + try: + etag = custom_etag() + if etag: + return etag + except Exception: + _logger.exception( + "Error while trying to retrieve custom ETag value for plugin {}".format( + key + ) + ) - if lastmodified and not isinstance(lastmodified, basestring): - from werkzeug.http import http_date - lastmodified = http_date(lastmodified) - if additional is None: - additional = [] + if lastmodified and not isinstance(lastmodified, basestring): + from werkzeug.http import http_date - import hashlib - hash = hashlib.sha1() - def hash_update(value): - hash.update(to_bytes(value, encoding="utf-8", errors="replace")) - hash_update(octoprint.__version__) - hash_update(get_python_version_string()) - hash_update(",".join(sorted(files))) - if lastmodified: - hash_update(lastmodified) - for add in additional: - hash_update(add) - return hash.hexdigest() + lastmodified = http_date(lastmodified) + if additional is None: + additional = [] - current_files = collect_files() - current_lastmodified = compute_lastmodified(current_files) - current_etag = compute_etag(files=current_files, lastmodified=current_lastmodified, - additional=[cache_key()] + additional_etag) + import hashlib - def check_etag_and_lastmodified(): - lastmodified_ok = util.flask.check_lastmodified(current_lastmodified) - etag_ok = util.flask.check_etag(current_etag) - return lastmodified_ok and etag_ok + hash = hashlib.sha1() - def validate_cache(cached): - return force_refresh or (current_etag != cached.get_etag()[0]) + def hash_update(value): + hash.update(to_bytes(value, encoding="utf-8", errors="replace")) - decorated_view = view - decorated_view = util.flask.lastmodified(lambda _: current_lastmodified)(decorated_view) - decorated_view = util.flask.etagged(lambda _: current_etag)(decorated_view) - decorated_view = util.flask.cached(timeout=-1, - refreshif=validate_cache, - key=cache_key, - unless_response=lambda response: util.flask.cache_check_response_headers(response) or util.flask.cache_check_status_code(response, _valid_status_for_cache))(decorated_view) - decorated_view = util.flask.with_client_revalidation(decorated_view) - decorated_view = util.flask.conditional(check_etag_and_lastmodified, NOT_MODIFIED)(decorated_view) - return decorated_view + hash_update(octoprint.__version__) + hash_update(get_python_version_string()) + hash_update(",".join(sorted(files))) + if lastmodified: + hash_update(lastmodified) + for add in additional: + hash_update(add) + return hash.hexdigest() - def plugin_view(p): - cached = get_cached_view(p._identifier, - p.on_ui_render, - additional_key_data=p.get_ui_additional_key_data_for_cache, - additional_files=p.get_ui_additional_tracked_files, - custom_files=p.get_ui_custom_tracked_files, - custom_etag=p.get_ui_custom_etag, - custom_lastmodified=p.get_ui_custom_lastmodified, - additional_etag=p.get_ui_additional_etag(default_additional_etag)) + current_files = collect_files() + current_lastmodified = compute_lastmodified(current_files) + current_etag = compute_etag( + files=current_files, + lastmodified=current_lastmodified, + additional=[cache_key()] + additional_etag, + ) - if preemptive_cache_enabled and p.get_ui_preemptive_caching_enabled(): - view = get_preemptively_cached_view(p._identifier, - cached, - p.get_ui_data_for_preemptive_caching, - p.get_ui_additional_request_data_for_preemptive_caching, - p.get_ui_preemptive_caching_additional_unless) - else: - view = cached + def check_etag_and_lastmodified(): + lastmodified_ok = util.flask.check_lastmodified(current_lastmodified) + etag_ok = util.flask.check_etag(current_etag) + return lastmodified_ok and etag_ok - template_filter = p.get_ui_custom_template_filter(default_template_filter) - if template_filter is not None and callable(template_filter): - filtered_templates = _filter_templates(_templates[locale], template_filter) - else: - filtered_templates = _templates[locale] + def validate_cache(cached): + return force_refresh or (current_etag != cached.get_etag()[0]) - render_kwargs = _get_render_kwargs(filtered_templates, - _plugin_names, - _plugin_vars, - now) + decorated_view = view + decorated_view = util.flask.lastmodified(lambda _: current_lastmodified)( + decorated_view + ) + decorated_view = util.flask.etagged(lambda _: current_etag)(decorated_view) + decorated_view = util.flask.cached( + timeout=-1, + refreshif=validate_cache, + key=cache_key, + unless_response=lambda response: util.flask.cache_check_response_headers( + response + ) + or util.flask.cache_check_status_code(response, _valid_status_for_cache), + )(decorated_view) + decorated_view = util.flask.with_client_revalidation(decorated_view) + decorated_view = util.flask.conditional( + check_etag_and_lastmodified, NOT_MODIFIED + )(decorated_view) + return decorated_view - return view(now, request, render_kwargs) + def plugin_view(p): + cached = get_cached_view( + p._identifier, + p.on_ui_render, + additional_key_data=p.get_ui_additional_key_data_for_cache, + additional_files=p.get_ui_additional_tracked_files, + custom_files=p.get_ui_custom_tracked_files, + custom_etag=p.get_ui_custom_etag, + custom_lastmodified=p.get_ui_custom_lastmodified, + additional_etag=p.get_ui_additional_etag(default_additional_etag), + ) - def default_view(): - filtered_templates = _filter_templates(_templates[locale], default_template_filter) + if preemptive_cache_enabled and p.get_ui_preemptive_caching_enabled(): + view = get_preemptively_cached_view( + p._identifier, + cached, + p.get_ui_data_for_preemptive_caching, + p.get_ui_additional_request_data_for_preemptive_caching, + p.get_ui_preemptive_caching_additional_unless, + ) + else: + view = cached - wizard = wizard_active(filtered_templates) - accesscontrol_active = enable_accesscontrol and userManager.has_been_customized() + template_filter = p.get_ui_custom_template_filter(default_template_filter) + if template_filter is not None and callable(template_filter): + filtered_templates = _filter_templates(_templates[locale], template_filter) + else: + filtered_templates = _templates[locale] - render_kwargs = _get_render_kwargs(filtered_templates, - _plugin_names, - _plugin_vars, - now) - render_kwargs.update({"enableWebcam": enable_webcam, - "enableTemperatureGraph": enable_temperature_graph, - "enableAccessControl": enable_accesscontrol, - "accessControlActive": accesscontrol_active, - "enableLoadingAnimation": enable_loading_animation, - "enableSdSupport": enable_sd_support, - "sockJsConnectTimeout": sockjs_connect_timeout * 1000, - "wizard": wizard, - "now": now,}) + render_kwargs = _get_render_kwargs( + filtered_templates, _plugin_names, _plugin_vars, now + ) - # no plugin took an interest, we'll use the default UI - def make_default_ui(): - r = make_response(render_template("index.jinja2", **render_kwargs)) - if wizard: - # if we have active wizard dialogs, set non caching headers - r = util.flask.add_non_caching_response_headers(r) - return r + return view(now, request, render_kwargs) - cached = get_cached_view("_default", - make_default_ui, - additional_etag=default_additional_etag) - preemptively_cached = get_preemptively_cached_view("_default", - cached, - {}, - {}) - return preemptively_cached() + def default_view(): + filtered_templates = _filter_templates( + _templates[locale], default_template_filter + ) - response = None + wizard = wizard_active(filtered_templates) + accesscontrol_active = enable_accesscontrol and userManager.has_been_customized() - forced_view = request.headers.get("X-Force-View", None) + render_kwargs = _get_render_kwargs( + filtered_templates, _plugin_names, _plugin_vars, now + ) + render_kwargs.update( + { + "enableWebcam": enable_webcam, + "enableTemperatureGraph": enable_temperature_graph, + "enableAccessControl": enable_accesscontrol, + "accessControlActive": accesscontrol_active, + "enableLoadingAnimation": enable_loading_animation, + "enableSdSupport": enable_sd_support, + "sockJsConnectTimeout": sockjs_connect_timeout * 1000, + "wizard": wizard, + "now": now, + } + ) - if forced_view: - # we have view forced by the preemptive cache - _logger.debug("Forcing rendering of view {}".format(forced_view)) - if forced_view != "_default": - plugin = pluginManager.get_plugin_info(forced_view, require_enabled=True) - if plugin is not None and isinstance(plugin.implementation, octoprint.plugin.UiPlugin): - response = plugin_view(plugin.implementation) - if _logger.isEnabledFor(logging.DEBUG) and isinstance(response, Response): - response.headers["X-Ui-Plugin"] = plugin._identifier - else: - response = default_view() - if _logger.isEnabledFor(logging.DEBUG) and isinstance(response, Response): - response.headers["X-Ui-Plugin"] = "_default" + # no plugin took an interest, we'll use the default UI + def make_default_ui(): + r = make_response(render_template("index.jinja2", **render_kwargs)) + if wizard: + # if we have active wizard dialogs, set non caching headers + r = util.flask.add_non_caching_response_headers(r) + return r - else: - # select view from plugins and fall back on default view if no plugin will handle it - ui_plugins = pluginManager.get_implementations(octoprint.plugin.UiPlugin, sorting_context="UiPlugin.on_ui_render") - for plugin in ui_plugins: - try: - if plugin.will_handle_ui(request): - # plugin claims responsibility, let it render the UI - response = plugin_view(plugin) - if response is not None: - if _logger.isEnabledFor(logging.DEBUG) and isinstance(response, Response): - response.headers["X-Ui-Plugin"] = plugin._identifier - break - else: - _logger.warning("UiPlugin {} returned an empty response".format(plugin._identifier)) - except Exception: - _logger.exception("Error while calling plugin {}, skipping it".format(plugin._identifier), - extra={"plugin": plugin._identifier}) - else: - response = default_view() - if _logger.isEnabledFor(logging.DEBUG) and isinstance(response, Response): - response.headers["X-Ui-Plugin"] = "_default" + cached = get_cached_view( + "_default", make_default_ui, additional_etag=default_additional_etag + ) + preemptively_cached = get_preemptively_cached_view("_default", cached, {}, {}) + return preemptively_cached() - if response is None: - return abort(404) - return response + response = None + + forced_view = request.headers.get("X-Force-View", None) + + if forced_view: + # we have view forced by the preemptive cache + _logger.debug("Forcing rendering of view {}".format(forced_view)) + if forced_view != "_default": + plugin = pluginManager.get_plugin_info(forced_view, require_enabled=True) + if plugin is not None and isinstance( + plugin.implementation, octoprint.plugin.UiPlugin + ): + response = plugin_view(plugin.implementation) + if _logger.isEnabledFor(logging.DEBUG) and isinstance(response, Response): + response.headers["X-Ui-Plugin"] = plugin._identifier + else: + response = default_view() + if _logger.isEnabledFor(logging.DEBUG) and isinstance(response, Response): + response.headers["X-Ui-Plugin"] = "_default" + + else: + # select view from plugins and fall back on default view if no plugin will handle it + ui_plugins = pluginManager.get_implementations( + octoprint.plugin.UiPlugin, sorting_context="UiPlugin.on_ui_render" + ) + for plugin in ui_plugins: + try: + if plugin.will_handle_ui(request): + # plugin claims responsibility, let it render the UI + response = plugin_view(plugin) + if response is not None: + if _logger.isEnabledFor(logging.DEBUG) and isinstance( + response, Response + ): + response.headers["X-Ui-Plugin"] = plugin._identifier + break + else: + _logger.warning( + "UiPlugin {} returned an empty response".format( + plugin._identifier + ) + ) + except Exception: + _logger.exception( + "Error while calling plugin {}, skipping it".format( + plugin._identifier + ), + extra={"plugin": plugin._identifier}, + ) + else: + response = default_view() + if _logger.isEnabledFor(logging.DEBUG) and isinstance(response, Response): + response.headers["X-Ui-Plugin"] = "_default" + + if response is None: + return abort(404) + return response def _get_render_kwargs(templates, plugin_names, plugin_vars, now): - global _logger + global _logger - #~~ a bunch of settings + # ~~ a bunch of settings - first_run = settings().getBoolean(["server", "firstRun"]) + first_run = settings().getBoolean(["server", "firstRun"]) - locales = {} - for l in LOCALES: - try: - locales[l.language] = {"language": l.language, "display": l.display_name, "english": l.english_name} - except Exception: - _logger.exception("Error while collecting available locales") + locales = {} + for l in LOCALES: + try: + locales[l.language] = { + "language": l.language, + "display": l.display_name, + "english": l.english_name, + } + except Exception: + _logger.exception("Error while collecting available locales") - permissions = [permission.as_dict() for permission in Permissions.all()] - filetypes = list(sorted(full_extension_tree().keys())) - extensions = list(map(lambda ext: ".{}".format(ext), get_all_extensions())) + permissions = [permission.as_dict() for permission in Permissions.all()] + filetypes = list(sorted(full_extension_tree().keys())) + extensions = list(map(lambda ext: ".{}".format(ext), get_all_extensions())) - #~~ prepare full set of template vars for rendering + # ~~ prepare full set of template vars for rendering - render_kwargs = {"debug": debug, - "firstRun": first_run, - "version": {"number": VERSION, "display": DISPLAY_VERSION, "branch": BRANCH}, - "python_version": get_python_version_string(), - "templates": templates, - "pluginNames": plugin_names, - "locales": locales, - "permissions": permissions, - "supportedFiletypes": filetypes, - "supportedExtensions": extensions} - render_kwargs.update(plugin_vars) + render_kwargs = { + "debug": debug, + "firstRun": first_run, + "version": {"number": VERSION, "display": DISPLAY_VERSION, "branch": BRANCH}, + "python_version": get_python_version_string(), + "templates": templates, + "pluginNames": plugin_names, + "locales": locales, + "permissions": permissions, + "supportedFiletypes": filetypes, + "supportedExtensions": extensions, + } + render_kwargs.update(plugin_vars) - return render_kwargs + return render_kwargs def fetch_template_data(refresh=False): - global _templates, _plugin_names, _plugin_vars + global _templates, _plugin_names, _plugin_vars - locale = g.locale.language if g.locale else "en" + locale = g.locale.language if g.locale else "en" - if not refresh and _templates.get(locale) is not None and _plugin_names is not None and _plugin_vars is not None: - return _templates[locale], _plugin_names, _plugin_vars + if ( + not refresh + and _templates.get(locale) is not None + and _plugin_names is not None + and _plugin_vars is not None + ): + return _templates[locale], _plugin_names, _plugin_vars - first_run = settings().getBoolean(["server", "firstRun"]) + first_run = settings().getBoolean(["server", "firstRun"]) - ##~~ prepare templates + ##~~ prepare templates - templates = defaultdict(lambda: {"order": [], "entries": {}}) + templates = defaultdict(lambda: {"order": [], "entries": {}}) - # rules for transforming template configs to template entries - template_rules = {"navbar": {"div": lambda x: "navbar_plugin_" + x, "template": lambda x: x + "_navbar.jinja2", "to_entry": lambda data: data}, - "sidebar": {"div": lambda x: "sidebar_plugin_" + x, "template": lambda x: x + "_sidebar.jinja2", "to_entry": lambda data: (data["name"], data)}, - "tab": {"div": lambda x: "tab_plugin_" + x, "template": lambda x: x + "_tab.jinja2", "to_entry": lambda data: (data["name"], data)}, - "settings": {"div": lambda x: "settings_plugin_" + x, "template": lambda x: x + "_settings.jinja2", "to_entry": lambda data: (data["name"], data)}, - "usersettings": {"div": lambda x: "usersettings_plugin_" + x, "template": lambda x: x + "_usersettings.jinja2", "to_entry": lambda data: (data["name"], data)}, - "wizard": {"div": lambda x: "wizard_plugin_" + x, "template": lambda x: x + "_wizard.jinja2", "to_entry": lambda data: (data["name"], data)}, - "about": {"div": lambda x: "about_plugin_" + x, "template": lambda x: x + "_about.jinja2", "to_entry": lambda data: (data["name"], data)}, - "generic": {"template": lambda x: x + ".jinja2", "to_entry": lambda data: data}} + # rules for transforming template configs to template entries + template_rules = { + "navbar": { + "div": lambda x: "navbar_plugin_" + x, + "template": lambda x: x + "_navbar.jinja2", + "to_entry": lambda data: data, + }, + "sidebar": { + "div": lambda x: "sidebar_plugin_" + x, + "template": lambda x: x + "_sidebar.jinja2", + "to_entry": lambda data: (data["name"], data), + }, + "tab": { + "div": lambda x: "tab_plugin_" + x, + "template": lambda x: x + "_tab.jinja2", + "to_entry": lambda data: (data["name"], data), + }, + "settings": { + "div": lambda x: "settings_plugin_" + x, + "template": lambda x: x + "_settings.jinja2", + "to_entry": lambda data: (data["name"], data), + }, + "usersettings": { + "div": lambda x: "usersettings_plugin_" + x, + "template": lambda x: x + "_usersettings.jinja2", + "to_entry": lambda data: (data["name"], data), + }, + "wizard": { + "div": lambda x: "wizard_plugin_" + x, + "template": lambda x: x + "_wizard.jinja2", + "to_entry": lambda data: (data["name"], data), + }, + "about": { + "div": lambda x: "about_plugin_" + x, + "template": lambda x: x + "_about.jinja2", + "to_entry": lambda data: (data["name"], data), + }, + "generic": {"template": lambda x: x + ".jinja2", "to_entry": lambda data: data}, + } - # sorting orders - def wizard_key_extractor(d, k): - if d[1].get("_key", None) == "plugin_corewizard_acl": - # Ultra special case - we MUST always have the ACL wizard first since otherwise any steps that follow and - # that require to access APIs to function will run into errors since those APIs won't work before ACL - # has been configured. See also #2140 - return "0:{}".format(to_unicode(d[0])) - elif d[1].get("mandatory", False): - # Other mandatory steps come before the optional ones - return "1:{}".format(to_unicode(d[0])) - else: - # Finally everything else - return "2:{}".format(to_unicode(d[0])) + # sorting orders + def wizard_key_extractor(d, k): + if d[1].get("_key", None) == "plugin_corewizard_acl": + # Ultra special case - we MUST always have the ACL wizard first since otherwise any steps that follow and + # that require to access APIs to function will run into errors since those APIs won't work before ACL + # has been configured. See also #2140 + return "0:{}".format(to_unicode(d[0])) + elif d[1].get("mandatory", False): + # Other mandatory steps come before the optional ones + return "1:{}".format(to_unicode(d[0])) + else: + # Finally everything else + return "2:{}".format(to_unicode(d[0])) - template_sorting = {"navbar": {"add": "prepend", "key": None}, - "sidebar": {"add": "append", "key": "name"}, - "tab": {"add": "append", "key": "name"}, - "settings": {"add": "custom_append", "key": "name", "custom_add_entries": lambda missing: {"section_plugins": (gettext("Plugins"), None)}, "custom_add_order": lambda missing: ["section_plugins"] + missing}, - "usersettings": {"add": "append", "key": "name"}, - "wizard": {"add": "append", "key": "name", "key_extractor": wizard_key_extractor}, - "about": {"add": "append", "key": "name"}, - "generic": {"add": "append", "key": None}} + template_sorting = { + "navbar": {"add": "prepend", "key": None}, + "sidebar": {"add": "append", "key": "name"}, + "tab": {"add": "append", "key": "name"}, + "settings": { + "add": "custom_append", + "key": "name", + "custom_add_entries": lambda missing: { + "section_plugins": (gettext("Plugins"), None) + }, + "custom_add_order": lambda missing: ["section_plugins"] + missing, + }, + "usersettings": {"add": "append", "key": "name"}, + "wizard": {"add": "append", "key": "name", "key_extractor": wizard_key_extractor}, + "about": {"add": "append", "key": "name"}, + "generic": {"add": "append", "key": None}, + } - hooks = pluginManager.get_hooks("octoprint.ui.web.templatetypes") - for name, hook in hooks.items(): - try: - result = hook(dict(template_sorting), dict(template_rules)) - except Exception: - _logger.exception("Error while retrieving custom template type " - "definitions from plugin {name}".format(**locals()), - extra={"plugin": name}) - else: - if not isinstance(result, list): - continue + hooks = pluginManager.get_hooks("octoprint.ui.web.templatetypes") + for name, hook in hooks.items(): + try: + result = hook(dict(template_sorting), dict(template_rules)) + except Exception: + _logger.exception( + "Error while retrieving custom template type " + "definitions from plugin {name}".format(**locals()), + extra={"plugin": name}, + ) + else: + if not isinstance(result, list): + continue - for entry in result: - if not isinstance(entry, tuple) or not len(entry) == 3: - continue + for entry in result: + if not isinstance(entry, tuple) or not len(entry) == 3: + continue - key, order, rule = entry + key, order, rule = entry - # order defaults - if "add" not in order: - order["add"] = "prepend" - if "key" not in order: - order["key"] = "name" + # order defaults + if "add" not in order: + order["add"] = "prepend" + if "key" not in order: + order["key"] = "name" - # rule defaults - if "div" not in rule: - # default div name: __plugin_ - div = "{name}_{key}_plugin_".format(**locals()) - rule["div"] = lambda x: div + x - if "template" not in rule: - # default template name: _plugin__