diff --git a/.editorconfig b/.editorconfig
index c67a242b4..278fd7b94 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -8,19 +8,23 @@ end_of_line = lf
charset = utf-8
insert_final_newline = true
trim_trailing_whitespace = true
+indent_style = space
+max_line_length = 90
[**.py]
-indent_style = tab
indent_size = 4
-[src/octoprint/vendor/sockjs/**.py]
-indent_style = space
-indent_size = 4
+[**.yaml]
+indent_size = 2
[src/octoprint/static/js/app/**.js]
-indent_style = space
indent_size = 4
-[.travis.yml]
-indent_style = space
+[src/octoprint/static/js/login/**.js]
+indent_size = 4
+
+[src/octoprint/static/js/recovery/**.js]
+indent_size = 4
+
+[src/octoprint/static/less/octoprint.less]
indent_size = 2
diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs
index 9f4e0c877..bf301dedb 100644
--- a/.git-blame-ignore-revs
+++ b/.git-blame-ignore-revs
@@ -1 +1,15 @@
# refs to ignore during git blame, use with --ignore-revs-file
+
+# Switch to black formatting
+1f93b2355a2816918e11a55e61b42010d15a6720
+
+# Switch to prettier formatting
+6b44909f21ee39237b7504cd31ffa6cf28275c33
+
+# EOF/trailing whitespace check
+#cae6730ea87da18bd6ebfeaf3e1e9cd354390939
+
+# dict_to_literal, set_to_literal, not_in, flake8 fixes
+#af60fd642832736966104ae71d852d745397c749
+#986312b6ae7eeadcaf620cc99d53b23794be83b6
+#b5be8f3eaec18ae2a88110a3a16c552931d493dd
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
index 7ee1a4b4c..0f76418a2 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.md
+++ b/.github/ISSUE_TEMPLATE/bug_report.md
@@ -17,7 +17,7 @@ or request features within OctoPrint (not OctoPi, not any OctoPrint
plugins and not unofficial OctoPrint versions).
Do not seek support here ("I need help with ...", "I have a
-question ..."), that belongs on the community forum at
+question ..."), that belongs on the community forum at
community.octoprint.org, NOT here.
Mark requests with a "[Request]" prefix in the title please. For bug
@@ -37,7 +37,7 @@ Thank you!
#### What were you doing?
-
diff --git a/.github/fixtures/with_acl/config.yaml b/.github/fixtures/with_acl/config.yaml
index 76cd71aad..57fadccbf 100644
--- a/.github/fixtures/with_acl/config.yaml
+++ b/.github/fixtures/with_acl/config.yaml
@@ -1,18 +1,18 @@
accessControl:
- salt: zXmvzI3uWuTLkSPOEfA2ZLwn3f3sGUNS
+ salt: zXmvzI3uWuTLkSPOEfA2ZLwn3f3sGUNS
plugins:
- virtual_printer:
- enabled: true
- tracking:
- enabled: false
+ virtual_printer:
+ enabled: true
+ tracking:
+ enabled: false
server:
- firstRun: false
- onlineCheck:
- enabled: false
- pluginBlacklist:
- enabled: false
- secretKey: rrdHjvmeGMPSdYWg2NGdiM7mpz9pjekk
- seenWizards:
- backup: null
- corewizard: 3
- tracking: null
+ firstRun: false
+ onlineCheck:
+ enabled: false
+ pluginBlacklist:
+ enabled: false
+ secretKey: rrdHjvmeGMPSdYWg2NGdiM7mpz9pjekk
+ seenWizards:
+ backup: null
+ corewizard: 3
+ tracking: null
diff --git a/.github/fixtures/with_acl/users.yaml b/.github/fixtures/with_acl/users.yaml
index fac60a9d4..7ac3a086d 100644
--- a/.github/fixtures/with_acl/users.yaml
+++ b/.github/fixtures/with_acl/users.yaml
@@ -1,22 +1,22 @@
admin:
- active: true
- apikey: null
- groups:
+ active: true
+ apikey: null
+ groups:
- admins
- users
- password: 3033587f3b040680c77ce4fb7e8d61422878ef49a2a784227689f3b44ce66ada7f6161f8b2b037267f0d37b783a5600276eb88e1d224d24915f64e187a49a89f
- permissions: []
- roles:
+ password: 3033587f3b040680c77ce4fb7e8d61422878ef49a2a784227689f3b44ce66ada7f6161f8b2b037267f0d37b783a5600276eb88e1d224d24915f64e187a49a89f
+ permissions: []
+ roles:
- user
- admin
- settings: {}
+ settings: {}
user:
- active: true
- apikey: null
- groups:
+ active: true
+ apikey: null
+ groups:
- users
- password: 3033587f3b040680c77ce4fb7e8d61422878ef49a2a784227689f3b44ce66ada7f6161f8b2b037267f0d37b783a5600276eb88e1d224d24915f64e187a49a89f
- permissions: []
- roles:
+ password: 3033587f3b040680c77ce4fb7e8d61422878ef49a2a784227689f3b44ce66ada7f6161f8b2b037267f0d37b783a5600276eb88e1d224d24915f64e187a49a89f
+ permissions: []
+ roles:
- user
- settings: {}
+ settings: {}
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index fc2e7fa71..0e0ecd233 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -31,6 +31,70 @@ jobs:
name: dist
path: dist
+ lint-black:
+ name: 🧹 black
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ - name: 🏗 Set up Python 3.7
+ uses: actions/setup-python@v1
+ with:
+ python-version: 3.7
+ - name: 🏗 Set up dev dependencies
+ run: |
+ pip install -e .[develop]
+ - name: 🚀 Run black
+ run: |
+ pre-commit run --hook-stage manual black --all-files --show-diff-on-failure
+
+ lint-prettier:
+ name: 🧹 prettier
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ - name: 🏗 Set up Python 3.7
+ uses: actions/setup-python@v1
+ with:
+ python-version: 3.7
+ - name: 🏗 Set up dev dependencies
+ run: |
+ pip install -e .[develop]
+ - name: 🚀 Run prettier
+ run: |
+ pre-commit run --hook-stage manual prettier --all-files --show-diff-on-failure
+
+ lint-isort:
+ name: 🧹 isort
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ - name: 🏗 Set up Python 3.7
+ uses: actions/setup-python@v1
+ with:
+ python-version: 3.7
+ - name: 🏗 Set up dev dependencies
+ run: |
+ pip install -e .[develop]
+ - name: 🚀 Run isort
+ run: |
+ pre-commit run --hook-stage manual isort --all-files --show-diff-on-failure
+
+ lint-flake8:
+ name: 🧹 Flake8
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ - name: 🏗 Set up Python 3.7
+ uses: actions/setup-python@v1
+ with:
+ python-version: 3.7
+ - name: 🏗 Set up dev dependencies
+ run: |
+ pip install -e .[develop]
+ - name: 🚀 Run flake8
+ run: |
+ pre-commit run --hook-stage manual flake8 --all-files
+
test-unit:
name: 🧪 Unit tests
strategy:
@@ -50,22 +114,6 @@ jobs:
run: |
pytest
- test-flake8:
- name: 🧪 Flake8
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v2
- - name: 🏗 Set up Python 3.7
- uses: actions/setup-python@v1
- with:
- python-version: 3.7
- - name: 🏗 Set up test dependencies
- run: |
- pip install -e .[develop]
- - name: 🚀 Run test suite
- run: |
- flake8 src/ tests setup.py
-
test-install:
name: 🧪 Installation tests
needs: build
@@ -124,8 +172,8 @@ jobs:
with:
working-directory: tests/cypress
browser: chrome
- start: 'octoprint -b ${{ github.workspace }}/e2econfig serve --host 127.0.0.1 --port 5000'
- wait-on: 'http://127.0.0.1:5000/online.txt'
+ start: "octoprint -b ${{ github.workspace }}/e2econfig serve --host 127.0.0.1 --port 5000"
+ wait-on: "http://127.0.0.1:5000/online.txt"
- name: ⬆ Upload screenshots
uses: actions/upload-artifact@v1
@@ -144,6 +192,10 @@ jobs:
name: 📦 Publish on TestPyPI
if: github.event_name == 'release'
needs:
+ - lint-black
+ - lint-prettier
+ - lint-isort
+ - lint-flake8
- test-unit
- test-install
- test-e2e
diff --git a/.github/workflows/lock.yml b/.github/workflows/lock.yml
index 45a57141c..b753d3fc0 100644
--- a/.github/workflows/lock.yml
+++ b/.github/workflows/lock.yml
@@ -1,8 +1,8 @@
-name: 'Lock outdated issues & PRs'
+name: "Lock outdated issues & PRs"
on:
schedule:
- - cron: '0 0 * * *'
+ - cron: "0 0 * * *"
jobs:
lock:
@@ -12,5 +12,5 @@ jobs:
uses: dessant/lock-threads@v2
with:
github-token: ${{ github.token }}
- issue-lock-comment: ''
- pr-lock-comment: ''
+ issue-lock-comment: ""
+ pr-lock-comment: ""
diff --git a/.github/workflows/test_install.yml b/.github/workflows/test_install.yml
index 7904648d2..578737033 100644
--- a/.github/workflows/test_install.yml
+++ b/.github/workflows/test_install.yml
@@ -6,7 +6,7 @@ on:
- master
workflow_dispatch:
schedule:
- - cron: '0 */12 * * *'
+ - cron: "0 */12 * * *"
jobs:
install-branch:
@@ -35,14 +35,14 @@ jobs:
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
uses: Ilshidur/action-discord@master
with:
- args: '☑️ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ matrix.branch }}` was successful'
+ args: "☑️ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ matrix.branch }}` was successful"
- name: 📧 Discord failure notification
if: failure()
env:
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
uses: Ilshidur/action-discord@master
with:
- args: '🚫 Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ matrix.branch }}` failed'
+ args: "🚫 Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ matrix.branch }}` failed"
install-latest:
name: Install latest release
@@ -69,11 +69,11 @@ jobs:
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
uses: Ilshidur/action-discord@master
with:
- args: '☑️ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ steps.latest.outputs.release }}` was successful'
+ args: "☑️ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ steps.latest.outputs.release }}` was successful"
- name: 📧 Discord failure notification
if: failure()
env:
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
uses: Ilshidur/action-discord@master
with:
- args: '🚫 Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ steps.latest.outputs.release }}` failed'
+ args: "🚫 Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ steps.latest.outputs.release }}` failed"
diff --git a/.github/workflows/trigger_docker.yml b/.github/workflows/trigger_docker.yml
index ef39f5868..92f93b44a 100644
--- a/.github/workflows/trigger_docker.yml
+++ b/.github/workflows/trigger_docker.yml
@@ -14,5 +14,5 @@ jobs:
with:
token: ${{ secrets.DOCKER_ACCESS_TOKEN }}
repository: ${{ github.repository_owner }}/octoprint-docker
- event-type: 'release'
+ event-type: "release"
client-payload: '{"tag_name": "${{ github.event.release.tag_name }}"}'
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
new file mode 100644
index 000000000..a90519e68
--- /dev/null
+++ b/.pre-commit-config.yaml
@@ -0,0 +1,38 @@
+exclude: ^(src/octoprint/vendor/|src/octoprint/static/js/lib|src/octoprint/static/vendor|tests/static/js/lib|tests/util/_files|docs/|scripts/|translations/|.*\.css|.*\.svg)
+repos:
+ - repo: https://github.com/pre-commit/pre-commit-hooks
+ rev: v2.3.0
+ hooks:
+ - id: end-of-file-fixer
+ - id: trailing-whitespace
+ - id: check-yaml
+ - id: check-toml
+ - repo: https://github.com/OctoPrint/codemods
+ rev: main
+ hooks:
+ - id: codemod_dict_to_literal
+ args: ["--ignore", "src/octoprint/vendor"]
+ stages: ["manual"]
+ - id: codemod_set_to_literal
+ args: ["--ignore", "src/octoprint/vendor"]
+ stages: ["manual"]
+ - id: codemod_not_in
+ args: ["--ignore", "src/octoprint/vendor"]
+ stages: ["manual"]
+ - repo: https://github.com/pre-commit/mirrors-isort
+ rev: v5.5.4
+ hooks:
+ - id: isort
+ - repo: https://github.com/psf/black
+ rev: stable
+ hooks:
+ - id: black
+ args: ["--config", "black.toml"]
+ - repo: https://gitlab.com/pycqa/flake8
+ rev: 3.8.1
+ hooks:
+ - id: flake8
+ - repo: https://github.com/prettier/prettier
+ rev: master
+ hooks:
+ - id: prettier
diff --git a/.prettierignore b/.prettierignore
new file mode 100644
index 000000000..5c83e9d95
--- /dev/null
+++ b/.prettierignore
@@ -0,0 +1,15 @@
+src/octoprint/static/js/lib
+src/octoprint/static/vendor
+src/octoprint/static/less/bootstrap
+src/octoprint/static/less/font-awesome.less
+*.md
+*.css
+**/package.json
+**/package-lock.json
+**/*.min.js
+docs
+build
+dist
+venv
+venv2
+venv3
diff --git a/.prettierrc.yaml b/.prettierrc.yaml
new file mode 100644
index 000000000..30baf7d8a
--- /dev/null
+++ b/.prettierrc.yaml
@@ -0,0 +1,11 @@
+printWidth: 90
+tabWidth: 4
+semi: true
+trailingComma: "none"
+singleQuote: false
+quoteProps: consistent
+bracketSpacing: false
+overrides:
+ - files: ["*.yaml", "*.yml", "*.json", "*.less"]
+ options:
+ tabWidth: 2
diff --git a/.tx/config b/.tx/config
index 33bd3437b..402bc41dd 100644
--- a/.tx/config
+++ b/.tx/config
@@ -5,4 +5,3 @@ host = https://www.transifex.com
file_filter = translations//LC_MESSAGES/messages.po
source_file = translations/messages.pot
source_lang = en
-
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 63aed2508..068ea1c0a 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -325,8 +325,7 @@ and branching strategy.
commits of your full virtual environment). Make sure your PR consists
**ideally of only one commit** (use git's rebase and squash functionality).
7. Make sure you **follow the current coding style**. This means:
- * Tabs instead of spaces in the Python files[2]
- * Spaces instead of tabs in the JavaScript sources
+ * Spaces for indenting and alignment, indentation width 4.
* English language (code, variables, comments, ...)
* Comments where necessary: Tell *why* the code does something like it does
it, structure your code
@@ -347,19 +346,32 @@ and branching strategy.
in the OctoPrint checkout folder. An [automatic build workflow](https://github.com/OctoPrint/OctoPrint/actions?query=workflow%3ABuild)
is also setup so that if the tests should fail, your PR will be marked
accordingly.
-9. **Test your changes thoroughly**. That also means testing with usage
- scenarios you don't normally use, e.g. if you only use access control, test
- without and vice versa. If you only test with your printer, test with the
- virtual printer and vice versa. State in your pull request how you tested
- your changes. Ideally **add unit tests** - OctoPrint severely lacks in that
- department, but we are trying to change that, so any new code already covered
- with a test suite helps a lot!
-10. In your pull request's description, **state what your pull request does**,
+9. Run the **pre-commit check suite** against your changes. You can run that (after
+ [initial development environment setup with "develop" dependencies](https://docs.octoprint.org/en/master/development/environment.html))
+ by running
+
+ ```
+ pre-commit run --hook-stage manual --all-files
+ ```
+
+ in the OctoPrint checkout folder. If you install the pre-commit hooks via
+ `pre-commit install` (which you really should!) this will even be taken care of for you prior to committing.
+
+ An [automatic build workflow](https://github.com/OctoPrint/OctoPrint/actions?query=workflow%3ABuild)
+ is in place that will run these checks - if they fail your PR will be marked accordingly.
+10. **Test your changes thoroughly**. That also means testing with usage
+ scenarios you don't normally use, e.g. if you only use access control, test
+ without and vice versa. If you only test with your printer, test with the
+ virtual printer and vice versa. State in your pull request how you tested
+ your changes. Ideally **add unit tests** - OctoPrint severely lacks in that
+ department, but we are trying to change that, so any new code already covered
+ with a test suite helps a lot!
+11. In your pull request's description, **state what your pull request does**,
as in, what feature does it implement, what bug does it fix. The more
thoroughly you explain your intent behind the PR here, the higher the
chances it will get merged fast. There is a template provided below
that can help you here.
-11. Don't forget to **add yourself to the [AUTHORS](./AUTHORS.md)
+12. Don't forget to **add yourself to the [AUTHORS](./AUTHORS.md)
file** :)
Template to use for Pull Request descriptions:
@@ -415,14 +427,10 @@ See [the corresponding chapter in the documentation](https://docs.octoprint.org/
new features, suggest getting in touch on the forum for larger changes
* 2020-08-10: Update versioning scheme and PR instructions
* 2020-09-23: Move branch & versioning into development docs
+ * 2020-10-07: Introduce `pre-commit`
## Footnotes
* [1] - If you are wondering why, the problem is that anything that you add
to your PR's branch will also become part of your PR, so if you create a
PR from your version of `devel` chances are high you'll add changes to the
PR that do not belong to the PR.
- * [2] - Yes, we know that this goes against PEP-8. OctoPrint started out as
- a fork of Cura and hence stuck to the coding style found therein. Changing
- it now would make the history and especially `git blame` completely
- unusable, so for now we'll have to deal with it (this decision might be
- revisited in the future).
diff --git a/README.md b/README.md
index 2aba60f76..1dc986a27 100644
--- a/README.md
+++ b/README.md
@@ -1,12 +1,16 @@
# OctoPrint
-


+[](https://pypi.python.org/pypi/octoprint/)

[](https://community.octoprint.org)
[](https://discord.octoprint.org)
[](https://twitter.com/OctoPrint3d)
+[](https://github.com/psf/black)
+[](https://github.com/prettier/prettier)
+[](https://pycqa.github.io/isort/)
+[](https://github.com/pre-commit/pre-commit)
OctoPrint provides a snappy web interface for controlling consumer 3D printers. It is Free Software
diff --git a/SECURITY.md b/SECURITY.md
index 8abfa9145..79b94cdd9 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -6,6 +6,6 @@ Always update to the latest version of OctoPrint to keep up with security patche
## Reporting a Vulnerability
-Email to security@octoprint.org.
+Email to security@octoprint.org.
For the sake of the userbase of OctoPrint please always disclose responsibly and with a 90+ day window.
diff --git a/SUPPORTERS.md b/SUPPORTERS.md
index f48c48bc0..d236c5d17 100644
--- a/SUPPORTERS.md
+++ b/SUPPORTERS.md
@@ -62,4 +62,4 @@ thanks to everyone who contributed!
* Sven Mueller
* Ulrich Kempken
-and 1943 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [Github Sponsors](https://github.com/users/foosel/sponsorship)!
\ No newline at end of file
+and 1943 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [Github Sponsors](https://github.com/users/foosel/sponsorship)!
diff --git a/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/development/environment.rst b/docs/development/environment.rst
index 1fee1e727..964169d9c 100644
--- a/docs/development/environment.rst
+++ b/docs/development/environment.rst
@@ -13,8 +13,8 @@ below.
* Prerequisites:
- * `Python 2.7 `_ including ``pip``, ``setuptools`` and ``virtualenv``
* `Python 3.7 `_ including ``pip``, ``setuptools`` and ``virtualenv``
+ * `Python 2.7 `_ including ``pip``, ``setuptools`` and ``virtualenv``
* `Git `_
* Checkout the OctoPrint sources from their Git repository:
@@ -26,8 +26,8 @@ below.
installing and running OctoPrint and its dependencies. Creating virtual environments avoids potential versioning
issues for the dependencies with system wide installed instances:
- * PY2: ``virtualenv --python=python2 venv2``
* PY3: ``virtualenv --python=python3 venv3``
+ * PY2: ``virtualenv --python=python2 venv2``
.. note::
@@ -35,10 +35,11 @@ below.
binaries cannot be found on your ``PATH`` like this you'll need to specify the full paths to them here,
e.g. ``virtualenv --python=/path/to/python2/bin/python venv2``
- * Activate one of the virtual environments:
+ * Activate one of the virtual environments (the Python 3 venv should be considered the
+ primary one at this point):
- * PY2: ``source venv2/bin/activate`` (Linux, macOS) or ``source venv2/Scripts/activate`` (Git Bash under Windows, see below)
* PY3: ``source venv3/bin/activate`` (Linux, macOS) or ``source venv3/Scripts/activate`` (Git Bash under Windows, see below)
+ * PY2: ``source venv2/bin/activate`` (Linux, macOS) or ``source venv2/Scripts/activate`` (Git Bash under Windows, see below)
* Update ``pip`` in the virtual environment:
@@ -49,10 +50,20 @@ below.
* ``pip install -e '.[develop,plugins]'``
+ * Set up the pre-commit hooks that make sure any changes you do adhere to the styling rules:
+
+ * ``pre-commit install``
+
+ * Tell ``git`` where to find the file with revisions to exclude for ``git blame``:
+
+ * ``git config blame.ignoreRevsFile .git-blame-ignore-revs``
+
When the virtual environment is activated you can then:
* run the OctoPrint server via ``octoprint serve``
* run the test suite from the checked out source folder via ``pytest``
+ * trigger the pre-commit check suite manually from the checked out source folder via
+ ``pre-commit run --hook-stage manual --all-files``
To switch the activated virtual environment, simply activate the new environment as described above.
@@ -106,6 +117,8 @@ Then:
source ./venv3/bin/activate
pip install --upgrade pip
pip install -e .[develop,plugins,docs]
+ pre-commit install
+ git config blame.ignoreRevsFile .git-blame-ignore-revs
You can then start OctoPrint via ``octoprint`` after activating one of the two virtual environments.
@@ -149,6 +162,8 @@ Open the Git Bash you just installed and in that:
source ./venv3/Scripts/activate
pip install --upgrade pip
pip install -e .[develop,plugins,docs]
+ pre-commit install
+ git config blame.ignoreRevsFile .git-blame-ignore-revs
.. _sec-development-environment-mac:
@@ -198,6 +213,8 @@ You'll need a user account with administrator privileges.
source venv/bin/activate
pip install --upgrade pip
pip install -e .[develop,plugins]
+ pre-commit install
+ git config blame.ignoreRevsFile .git-blame-ignore-revs
.. _sec-development-environment-ides:
@@ -276,6 +293,18 @@ PyCharm
Note that this requires you to also have installed the additional ``docs`` dependencies into the Python 3 venv as
described above via ``pip install -e .[develop,plugins,docs]``.
+ - Settings > Tools > File Watchers (you might have to enable this, it's a bundled plugin), add new:
+
+ * Name: pre-commit
+ * File type: Python
+ * Scope: Module 'OctoPrint'
+ * Program: ``/bin/pre-commit`` (Linux) or ``/Scripts/pre-commit`` (Windows)
+ * Arguments: ``run --hook-stage manual --files $FilePath$``
+ * Output paths to refresh: ``$FilePath$``
+ * Working directory: ``$ProjectFileDir$``
+ * disable "Auto-save edited files to trigger the watched"
+ * enable "Trigger the watched on external changes"
+
To switch between Python 2 and 3, all you need to do now is change the Project Default Interpreter and restart
OctoPrint. On current PyCharm versions you can do that right from a small selection field in the footer of the IDE.
Otherwise go through Settings.
diff --git a/docs/sphinxext/codeblockext.py b/docs/sphinxext/codeblockext.py
index f36c16a33..cfbbadbb0 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, {"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 {"version": "0.1"}
diff --git a/docs/sphinxext/onlineinclude.py b/docs/sphinxext/onlineinclude.py
index ed4a1742a..5344e3473 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 = {}
-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..8646c57a3 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
+import octoprint # noqa: E402
+
if len(sys.argv) == 1:
sys.argv.append("serve")
octoprint.main()
diff --git a/setup.cfg b/setup.cfg
index 6f5421829..4b5d8f589 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -14,11 +14,22 @@ parentdir_prefix =
lookupfile = .versioneer-lookup
[flake8]
-ignore =
- D
- E
- W
- F401
- F523
+max-line-length = 90
+extend-ignore = E203, E231, E265, E266, E402, E501, E731
+select = B,C,E,F,W,T4,B9
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..dbfbc8158 100644
--- a/setup.py
+++ b/setup.py
@@ -1,302 +1,306 @@
#!/usr/bin/env python2
# coding=utf-8
-from distutils.command.build_py import build_py as _build_py
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
+from distutils.command.build_py import build_py as _build_py
-#-----------------------------------------------------------------------------------------------------------------------
+import versioneer # noqa: F401
+
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "src"))
+import setuptools # noqa: F401,E402
+
+import octoprint_setuptools # noqa: F401,E402
+
+# ----------------------------------------------------------------------------------------
# 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"
- ],
-)
+EXTRA_REQUIRES = {
+ "develop": [
+ # Testing dependencies
+ "mock>=3.0.5,<4",
+ "pytest==4.6.10",
+ "pytest-doctest-custom>=1.0.0,<2",
+ "ddt",
+ # 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
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 = {}
- 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,), {"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(
+ {
+ "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..6b0a1bb78 100644
--- a/src/octoprint/__init__.py
+++ b/src/octoprint/__init__.py
@@ -3,19 +3,21 @@
from __future__ import absolute_import, division, print_function, unicode_literals
import io
-import sys
import logging as log
import os
-
-#~~ version
+import sys
from ._version import get_versions
+
+# ~~ version
+
+
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 +32,757 @@ 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 InvalidSettings, settings
+
+ 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 # noqa: F401
- 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 name not 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 addon not in already_processed and addon not 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 os
+ import time
- from octoprint.util import bom_aware_open
- from octoprint.util.version import is_octoprint_compatible
+ import requests
+ import yaml
- logger = log.getLogger(__name__ + ".startup")
+ from octoprint.util import bom_aware_open
+ from octoprint.util.version import is_octoprint_compatible
- 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 []
+ logger = log.getLogger(__name__ + ".startup")
- 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))
+ 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 process_blacklist(entries):
- result = []
+ 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))
- if not isinstance(entries, list):
- return result
+ def process_blacklist(entries):
+ result = []
- for entry in entries:
- if not "plugin" in entry:
- continue
+ if not isinstance(entries, list):
+ return result
- if "octoversions" in entry and not is_octoprint_compatible(*entry["octoversions"]):
- continue
+ for entry in entries:
+ if "plugin" not in entry:
+ 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 "octoversions" in entry and not is_octoprint_compatible(
+ *entry["octoversions"]
+ ):
+ continue
- return result
+ 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"])
- def fetch_blacklist_from_cache(path, ttl):
- if not os.path.isfile(path):
- return None
+ return result
- if os.stat(path).st_mtime + ttl < time.time():
- return None
+ def fetch_blacklist_from_cache(path, ttl):
+ if not os.path.isfile(path):
+ return None
- with bom_aware_open(path, encoding="utf-8", mode='rt') as f:
- result = yaml.safe_load(f)
+ if os.stat(path).st_mtime + ttl < time.time():
+ return None
- if isinstance(result, list):
- return result
+ with bom_aware_open(path, encoding="utf-8", mode="rt") as f:
+ result = yaml.safe_load(f)
- def fetch_blacklist_from_url(url, timeout=3, cache=None):
- result = []
- try:
- r = requests.get(url, timeout=timeout)
- result = process_blacklist(r.json())
+ if isinstance(result, list):
+ 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
+ def fetch_blacklist_from_url(url, timeout=3, cache=None):
+ result = []
+ try:
+ r = requests.get(url, timeout=timeout)
+ result = process_blacklist(r.json())
- 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 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 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)
+ 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:
- # still now result, so no blacklist
- blacklist = []
+ 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:
- logger.info("Blacklist processing done, "
- "adding {} blacklisted plugin versions: {}".format(len(blacklist),
- format_blacklist(blacklist)))
- else:
- logger.info("Blacklist processing done")
+ if blacklist is None:
+ # still now result, so no blacklist
+ blacklist = []
- return blacklist
- except Exception:
- logger.exception("Something went wrong while processing the plugin blacklist. Proceeding without it.")
+ 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."
+ )
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..c9da3f17b 100644
--- a/src/octoprint/_version.py
+++ b/src/octoprint/_version.py
@@ -14,11 +14,11 @@ from __future__ import absolute_import, division, print_function, unicode_litera
import errno
import io
+import logging
import os
import re
import subprocess
import sys
-import logging
def get_keywords():
@@ -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..e121217f6 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
@@ -11,602 +11,708 @@ import os
from functools import partial
import yaml
-
from past.builtins import basestring
+from octoprint.access import ADMIN_GROUP, GUEST_GROUP, READONLY_GROUP, USER_GROUP
+from octoprint.access.permissions import OctoPrintPermission, Permissions
from octoprint.settings import settings
from octoprint.util import atomic_write
-from octoprint.access import ADMIN_GROUP, USER_GROUP, GUEST_GROUP, READONLY_GROUP
-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 "groups" not 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 (
+ permission.key not in tracked_permissions
+ and permission not 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 key not 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..78ce87e2f 100644
--- a/src/octoprint/access/permissions.py
+++ b/src/octoprint/access/permissions.py
@@ -2,389 +2,462 @@
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
-from flask import g, abort
-from flask_babel import gettext
-from octoprint.vendor.flask_principal import Permission, PermissionDenied, RoleNeed, Need
-
-from functools import wraps
from collections import OrderedDict, defaultdict
+from functools import wraps
+
+from flask import abort, g
+from flask_babel import gettext
+from future.utils import with_metaclass
# noinspection PyCompatibility
from past.builtins import basestring
-from octoprint.access import ADMIN_GROUP, USER_GROUP, READONLY_GROUP
+from octoprint.access import ADMIN_GROUP, READONLY_GROUP, USER_GROUP
+from octoprint.vendor.flask_principal import Need, Permission, PermissionDenied, RoleNeed
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
+ """
- @property
- def identity(self):
- """The identity of this principal
- """
- return g.identity
+ def __init__(self, key, http_exception=None):
+ self.key = key
+ self.http_exception = http_exception
+ """The permission of this principal
+ """
- 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)
+ @property
+ def identity(self):
+ """The identity of this principal"""
+ return g.identity
- return permission.can()
+ 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 __call__(self, f):
- @wraps(f)
- def _decorated(*args, **kw):
- with self:
- rv = f(*args, **kw)
- return rv
+ return permission.can()
- return _decorated
+ def __call__(self, f):
+ @wraps(f)
+ def _decorated(*args, **kw):
+ with self:
+ rv = f(*args, **kw)
+ return rv
- def __enter__(self):
- permission = getattr(Permissions, self.key)
- if permission is None or isinstance(permission, PluginPermissionDecorator):
- raise UnknownPermission(self.key)
+ return _decorated
- # check the permission here
- if not permission.can():
- if self.http_exception:
- abort(self.http_exception, permission)
- raise PermissionDenied(permission)
+ def __enter__(self):
+ permission = getattr(Permissions, self.key)
+ if permission is None or isinstance(permission, PluginPermissionDecorator):
+ raise UnknownPermission(self.key)
- def __exit__(self, *args):
- return False
+ # 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
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..951928384 100644
--- a/src/octoprint/access/users.py
+++ b/src/octoprint/access/users.py
@@ -1,1284 +1,1454 @@
# -*- 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
-from werkzeug.local import LocalProxy
import hashlib
import io
-import os
-import yaml
-import uuid
-import wrapt
-import time
-
import logging
+import os
+import uuid
# noinspection PyCompatibility
-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 get_fully_qualified_classname as fqcn
-
-from octoprint.access.permissions import Permissions, OctoPrintPermission
-from octoprint.access.groups import GroupChangeListener, Group
+from builtins import bytes, range
+import wrapt
+import yaml
+from flask_login import AnonymousUserMixin, UserMixin
from past.builtins import basestring
+from werkzeug.local import LocalProxy
+
+from octoprint.access.groups import Group, GroupChangeListener
+from octoprint.access.permissions import OctoPrintPermission, Permissions
+from octoprint.settings import settings as s
+from octoprint.util import atomic_write, deprecated, generate_api_key
+from octoprint.util import get_fully_qualified_classname as fqcn
+from octoprint.util import monotonic_time, to_bytes
+
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 userid not 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 "permissions" not in attributes:
+ self._logger.info(
+ "Migrating user {} to new granular permission system".format(
+ name
+ )
+ )
+
+ groups |= set(self._migrate_roles_to_groups(attributes["roles"]))
+ self._dirty = True
+
+ apikey = None
+ if "apikey" in attributes:
+ apikey = attributes["apikey"]
+ settings = {}
+ if "settings" in attributes:
+ settings = attributes["settings"]
+
+ self._users[name] = User(
+ username=name,
+ passwordHash=attributes["password"],
+ active=attributes["active"],
+ permissions=self._to_permissions(*permissions),
+ groups=self._to_groups(*groups),
+ apikey=apikey,
+ settings=settings,
+ )
+ 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 username not 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 username not 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 username not 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 username not in self._users:
+ raise UnknownUser(username)
+
+ user = self._users[username]
+ return user.get_all_settings()
+
+ def get_user_setting(self, username, key):
+ if username not in self._users:
+ raise UnknownUser(username)
+
+ user = self._users[username]
+ return user.get_setting(key)
+
+ def generate_api_key(self, username):
+ if username not 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 username not 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 username not 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..534927b9f 100644
--- a/src/octoprint/cli/__init__.py
+++ b/src/octoprint/cli/__init__.py
@@ -1,177 +1,268 @@
# -*- 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
+import click
+
+import octoprint
+
+click.disable_unicode_literals_warning = True
+
+
+# ~~ 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
- def decorator(f):
- if 'help' in attrs:
- attrs['help'] = inspect.cleandoc(attrs['help'])
- _param_memo(f, HiddenOption(param_decls, **attrs))
- return f
- return decorator
+ 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
+
+
+# ~~ 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
-from .dev import dev_commands
-from .client import client_commands
-from .config import config_commands
-from .analysis import analysis_commands
-from .user import user_commands
+from .analysis import analysis_commands # noqa: E402
+from .client import client_commands # noqa: E402
+from .config import config_commands # noqa: E402
+from .dev import dev_commands # noqa: E402
+from .plugins import plugin_commands # noqa: E402
+from .server import server_commands # noqa: E402
+from .user import user_commands # noqa: E402
-@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..3ddcd4ae8 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,75 @@ 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
- 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)
+ import yaml
- 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))
+ from octoprint.util import monotonic_time
+ from octoprint.util.gcodeInterpreter import gcode
- start_time = monotonic_time()
+ throttle_callback = None
+ if throttle:
- progress_callback = None
- if progress:
- def progress_callback(percentage):
- click.echo("PROGRESS:{}".format(percentage))
- interpreter = gcode(progress_callback=progress_callback)
+ def throttle_callback(filePos, readBytes):
+ if filePos % throttle_lines == 0:
+ # only apply throttle every $throttle_lines lines
+ time.sleep(throttle)
- interpreter.load(path,
- speedx=speedx,
- speedy=speedy,
- offsets=offsets,
- throttle=throttle_callback,
- max_extruders=maxt,
- g90_extruder=g90_extruder)
+ 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))
+
+ start_time = monotonic_time()
+
+ 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..e84c53c91 100644
--- a/src/octoprint/cli/client.py
+++ b/src/octoprint/cli/client.py
@@ -1,107 +1,125 @@
# -*- 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
import json
-import octoprint_client
-
-from octoprint.cli import get_ctx_obj_option, bulk_options
-from octoprint import init_settings, FatalStartupError
-
+import click
from past.builtins import unicode
+import octoprint_client
+from octoprint import FatalStartupError, init_settings
+from octoprint.cli import bulk_options, get_ctx_obj_option
+
+click.disable_unicode_literals_warning = True
+
+
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 +127,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 +138,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 +149,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 +268,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..2b20039a8 100644
--- a/src/octoprint/cli/config.py
+++ b/src/octoprint/cli/config.py
@@ -1,95 +1,104 @@
# -*- 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
-
-from octoprint import init_settings, FatalStartupError
-from octoprint.cli import standard_options, bulk_options, get_ctx_obj_option
-
-import yaml
import json
+import logging
import pprint
+import click
+import yaml
+
+from octoprint import FatalStartupError, init_settings
+from octoprint.cli import get_ctx_obj_option, standard_options
+
+click.disable_unicode_literals_warning = True
+
+
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 value not 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..048bb7805 100644
--- a/src/octoprint/cli/dev.py
+++ b/src/octoprint/cli/dev.py
@@ -2,236 +2,269 @@
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 functools import partial
- def log_util(f):
- def log(*lines):
- for line in lines:
- f(line)
- return log
+ from octoprint.util.commandline import CommandlineCaller
- 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 log_util(f):
+ def log(*lines):
+ for line in lines:
+ f(line)
- 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
+ return log
- 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
+ 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(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_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 list_commands(self, ctx):
- result = [name for name in self._get_commands()]
- result.sort()
- 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 get_command(self, ctx, cmd_name):
- commands = self._get_commands()
- return commands.get(cmd_name, None)
+ 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 plugin_new(self):
- try:
- import cookiecutter.main
- except ImportError:
- return None
+ def list_commands(self, ctx):
+ result = [name for name in self._get_commands()]
+ result.sort()
+ return result
- try:
- # we depend on Cookiecutter >= 1.4
- from cookiecutter.prompt import StrictEnvironment
- except ImportError:
- return None
+ def get_command(self, ctx, cmd_name):
+ commands = self._get_commands()
+ return commands.get(cmd_name, None)
- import contextlib
+ def plugin_new(self):
+ try:
+ import cookiecutter.main
+ 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
+ try:
+ # we depend on Cookiecutter >= 1.4
+ from cookiecutter.prompt import StrictEnvironment
+ except ImportError:
+ return None
- 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
+ import contextlib
- @contextlib.contextmanager
- def custom_cookiecutter_prompt(options):
- """
- Custom cookiecutter prompter for the template 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
- 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
+ original_get_user_config = cookiecutter.main.get_user_config
+ try:
- def custom_prompt_for_config(context, no_input=False):
- cookiecutter_dict = {}
+ def f(*args, **kwargs):
+ original_config = original_get_user_config(*args, **kwargs)
+ return fallback_dict(config, original_config)
- env = StrictEnvironment()
+ cookiecutter.main.get_user_config = f
+ yield
+ finally:
+ cookiecutter.main.get_user_config = original_get_user_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)
+ @contextlib.contextmanager
+ def custom_cookiecutter_prompt(options):
+ """
+ Custom cookiecutter prompter for the template config.
- if not no_input:
- val = click.prompt(key, default=val)
+ 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
- cookiecutter_dict[key] = val
- return cookiecutter_dict
+ def custom_prompt_for_config(context, no_input=False):
+ cookiecutter_dict = {}
- try:
- cookiecutter.main.prompt_for_config = custom_prompt_for_config
- yield
- finally:
- cookiecutter.main.prompt_for_config = original_prompt_for_config
+ env = StrictEnvironment()
- @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
+ 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)
- # 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
+ if not no_input:
+ val = click.prompt(key, default=val)
- if not os.access(path, os.W_OK):
- os.chmod(path, stat.S_IWUSR)
- func(path)
- else:
- raise
+ cookiecutter_dict[key] = val
+ return cookiecutter_dict
- 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)
+ try:
+ cookiecutter.main.prompt_for_config = custom_prompt_for_config
+ yield
+ finally:
+ cookiecutter.main.prompt_for_config = original_prompt_for_config
- with custom_cookiecutter_prompt(options):
- cookiecutter.main.cookiecutter("gh:OctoPrint/cookiecutter-octoprint-plugin")
+ @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
- return command
+ # 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 os
+ import stat
- 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.
+ if not os.access(path, os.W_OK):
+ os.chmod(path, stat.S_IWUSR)
+ func(path)
+ else:
+ raise
- 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 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
+ )
- import os
- import sys
+ with custom_cookiecutter_prompt(options):
+ cookiecutter.main.cookiecutter(
+ "gh:OctoPrint/cookiecutter-octoprint-plugin"
+ )
- if not path:
- path = os.getcwd()
+ return command
- # 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)
+ 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.
- self.command_caller.call([sys.executable, "-m", "pip", "install", "-e", "."], cwd=path)
+ 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.
+ """
- return command
+ import os
+ import sys
- def plugin_uninstall(self):
- @click.command("uninstall")
- @click.argument("name")
- def command(name):
- """Uninstalls the plugin with the given name."""
- import sys
+ if not path:
+ path = os.getcwd()
- 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)
+ # 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)
- call = [sys.executable, "-m", "pip", "uninstall", "--yes", name]
- self.command_caller.call(call)
+ self.command_caller.call(
+ [sys.executable, "-m", "pip", "install", "-e", "."], cwd=path
+ )
+
+ 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..7521ae28b 100644
--- a/src/octoprint/cli/plugins.py
+++ b/src/octoprint/cli/plugins.py
@@ -1,137 +1,152 @@
# -*- 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
-from octoprint.cli import pass_octoprint_ctx, OctoPrintContext, get_ctx_obj_option
+import click
+
+from octoprint.cli import OctoPrintContext, get_ctx_obj_option, pass_octoprint_ctx
from octoprint.util import dict_merge
+click.disable_unicode_literals_warning = True
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 FatalStartupError, init_pluginsystem, init_settings
- # 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..5680d9177 100644
--- a/src/octoprint/cli/server.py
+++ b/src/octoprint/cli/server.py
@@ -1,180 +1,277 @@
# -*- 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
+import click
-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.cli import (
+ bulk_options,
+ get_ctx_obj_option,
+ set_ctx_obj_option,
+ standard_options,
+)
- from octoprint import init_platform, __display_version__, FatalStartupError
+click.disable_unicode_literals_warning = True
- def log_startup(recorder=None, safe_mode=None, **kwargs):
- from octoprint.logging import get_divider_line
- from octoprint.logging.handlers import PluginTimingsLogHandler
- logger = logging.getLogger("octoprint.startup")
- PluginTimingsLogHandler.arm_rollover()
+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."""
- 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 import FatalStartupError, __display_version__, init_platform
- if recorder and len(recorder):
- logger.info(get_divider_line("-", "Logged during platform initialization:"))
+ def log_startup(recorder=None, safe_mode=None, **kwargs):
+ from octoprint.logging import get_divider_line
+ from octoprint.logging.handlers import PluginTimingsLogHandler
- from octoprint.logging.handlers import CombinedLogHandler
- handler = CombinedLogHandler(*logging.getLogger().handlers)
- recorder.setTarget(handler)
- recorder.flush()
+ logger = logging.getLogger("octoprint.startup")
+ PluginTimingsLogHandler.arm_rollover()
- logger.info(get_divider_line("-"))
+ 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 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("*"))
+ if recorder and len(recorder):
+ logger.info(get_divider_line("-", "Logged during platform initialization:"))
- 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
+ from octoprint.logging.handlers import CombinedLogHandler
- def rollover_callback():
- handler = get_handler("file")
- if handler is None:
- return
+ handler = CombinedLogHandler(*logging.getLogger().handlers)
+ recorder.setTarget(handler)
+ recorder.flush()
- logger = logging.getLogger("octoprint.server")
+ logger.info(get_divider_line("-"))
- def _log(message, level=logging.INFO):
- log_to_handler(logger, handler, level, message)
+ from octoprint import urllib3_ssl
- _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("-"))
+ 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("*"))
- OctoPrintLogHandler.registerRolloverCallback(rollover_callback)
+ def log_register_rollover(
+ safe_mode=None, plugin_manager=None, environment_detector=None, **kwargs
+ ):
+ from octoprint.logging import get_divider_line, get_handler, log_to_handler
+ from octoprint.logging.handlers import OctoPrintLogHandler
- 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 rollover_callback():
+ handler = get_handler("file")
+ if handler is None:
+ return
- except FatalStartupError as e:
- logger = logging.getLogger("octoprint.startup").fatal
- echo = lambda x: click.echo(x, err=True)
+ logger = logging.getLogger("octoprint.server")
- for method in logger, echo:
- method(str(e))
- method("There was a fatal error starting up OctoPrint.")
+ def _log(message, level=logging.INFO):
+ log_to_handler(logger, handler, level, message)
- 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()
+ _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("-"))
-#~~ server options
+ OctoPrintLogHandler.registerRolloverCallback(rollover_callback)
-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.")
-])
+ 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
+
+ except FatalStartupError as e:
+ logger = logging.getLogger("octoprint.startup").fatal
+ echo = lambda x: click.echo(x, err=True)
+
+ 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 FatalStartupError, init_settings
- 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 +279,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..466e8d243 100644
--- a/src/octoprint/cli/user.py
+++ b/src/octoprint/cli/user.py
@@ -1,124 +1,152 @@
# 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 click
import logging
+import click
+
from octoprint import init_settings
-from octoprint.cli import get_ctx_obj_option
from octoprint.access.groups import FilebasedGroupManager
from octoprint.access.users import FilebasedUserManager, UnknownUser, UserAlreadyExists
+from octoprint.cli import get_ctx_obj_option
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 +154,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..94c44ae94 100644
--- a/src/octoprint/daemon.py
+++ b/src/octoprint/daemon.py
@@ -7,170 +7,183 @@ Generic linux daemon base class
Originally from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/#c35
"""
-import io, sys, os, time, signal
+import io
+import os
+import signal
+import sys
+import time
+
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..c44f79150 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
@@ -9,165 +9,185 @@ import logging
import os
import sys
import threading
-import yaml
import psutil
+import yaml
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..2adf17db6 100644
--- a/src/octoprint/events.py
+++ b/src/octoprint/events.py
@@ -2,487 +2,540 @@
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 threading
+ import Queue as queue
+
import collections
import re
+import threading
-from octoprint.settings import settings
import octoprint.plugin
+from octoprint.settings import settings
# singleton
_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 name not 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 (
+ "event" not in subscription
+ or "command" not in subscription
+ or "type" not in subscription
+ or subscription["type"] not 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 event not 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..a96c9b6ca 100644
--- a/src/octoprint/filemanager/__init__.py
+++ b/src/octoprint/filemanager/__init__.py
@@ -2,739 +2,1067 @@
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
import io
+import logging
import os
-
-import octoprint.plugin
-import octoprint.util
-
-from octoprint.events import eventManager, Events
-
-from .destinations import FileDestinations
-from .analysis import QueueEntry, AnalysisQueue
-from .storage import LocalFileStorage
-from .util import AbstractFileWrapper, StreamWrapper, DiskFileWrapper
-from octoprint.util import get_fully_qualified_classname as fqcn
-
from collections import namedtuple
from past.builtins import basestring
+import octoprint.plugin
+import octoprint.util
+from octoprint.events import Events, eventManager
+from octoprint.util import get_fully_qualified_classname as fqcn
+
+from .analysis import AnalysisQueue, QueueEntry # noqa: F401
+from .destinations import FileDestinations # noqa: F401
+from .storage import LocalFileStorage # noqa: F401
+from .util import AbstractFileWrapper, DiskFileWrapper, StreamWrapper # noqa: F401
+
ContentTypeMapping = namedtuple("ContentTypeMapping", "extensions, content_type")
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 type not 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 destination not 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 destination not 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..67a2761ff 100644
--- a/src/octoprint/filemanager/analysis.py
+++ b/src/octoprint/filemanager/analysis.py
@@ -2,438 +2,507 @@
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 collections
import os
import threading
-import collections
import time
from octoprint.events import Events, eventManager
from octoprint.settings import settings
+from octoprint.util import dict_merge
+from octoprint.util import get_fully_qualified_classname as fqcn
from octoprint.util import monotonic_time
-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 entry.type not 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 entry.type not 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 Exception:
+ 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 sys
- if self._current.analysis and all(map(lambda x: x in self._current.analysis, ("printingArea",
- "dimensions",
- "estimatedPrintTime",
- "filament"))):
- return self._current.analysis
+ import sarge
+ import yaml
- 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"]
+ if self._current.analysis and all(
+ map(
+ lambda x: x in self._current.analysis,
+ ("printingArea", "dimensions", "estimatedPrintTime", "filament"),
+ )
+ ):
+ return self._current.analysis
- 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)
+ 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"]
- self._logger.info("Invoking analysis command: {}".format(" ".join(command)))
+ 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._aborted = False
- p = sarge.run(command, close_fds=CLOSE_FDS, async_=True, stdout=sarge.Capture())
+ self._logger.info("Invoking analysis command: {}".format(" ".join(command)))
- 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)
+ self._aborted = False
+ p = sarge.run(
+ command, close_fds=CLOSE_FDS, async_=True, stdout=sarge.Capture()
+ )
- # by now we should have a command, let's wait for its
- # process to have been prepared
- p.commands[0].process_ready.wait()
+ 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)
- 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)))
+ # by now we should have a command, let's wait for its
+ # process to have been prepared
+ p.commands[0].process_ready.wait()
- 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)
+ 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))
+ )
- # else continue
- p.commands[0].poll()
- finally:
- p.close()
+ 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)
- output = p.stdout.text
- self._logger.debug("Got output: {!r}".format(output))
+ # else continue
+ p.commands[0].poll()
+ finally:
+ p.close()
- if not "RESULTS:" in output:
- raise RuntimeError("No analysis result found")
+ output = p.stdout.text
+ self._logger.debug("Got output: {!r}".format(output))
- _, output = output.split("RESULTS:")
- analysis = yaml.safe_load(output)
+ if "RESULTS:" not in output:
+ raise RuntimeError("No analysis result found")
- 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]
- }
+ _, output = output.split("RESULTS:")
+ analysis = yaml.safe_load(output)
- if self._current.analysis and isinstance(self._current.analysis, dict):
- return dict_merge(result, self._current.analysis)
- else:
- return result
- finally:
- self._gcode = None
+ 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],
+ }
- def _do_abort(self, reenqueue=True):
- self._aborted = True
- self._reenqueue = reenqueue
+ 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
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..bf0a33c34 100644
--- a/src/octoprint/filemanager/storage.py
+++ b/src/octoprint/filemanager/storage.py
@@ -2,1713 +2,2002 @@
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 copy
import io
import logging
import os
-import shutil
import re
+import shutil
+
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
+from emoji import demojize
from past.builtins import basestring
-from emoji import demojize
+import octoprint.filemanager
+from octoprint.util import atomic_write, is_hidden_path, time_this, to_bytes, to_unicode
from octoprint.vendor.awesome_slugify import Slugify
-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 (
+ entry.name not in metadata
+ or not isinstance(metadata[entry.name], dict)
+ or "analysis" not 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 "hash" not in metadata or metadata["hash"] != file_hash:
+ # hash changed -> throw away old metadata
+ metadata = {"hash": file_hash}
+ metadata_dirty = True
+
+ if "display" not 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 name not 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 name not in metadata:
+ return
+
+ metadata = self._copied_metadata(metadata, name)
+
+ if key not 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 name not in metadata:
+ return
+
+ if key not 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 "hash" not in metadata[name]:
+ metadata[name]["hash"] = self._create_hash(os.path.join(path, name))
+
+ if "history" not 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 name not in metadata or "history" not 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 name not in metadata or "history" not 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 "history" not in metadata[name]:
+ return
+
+ # collect data from history
+ former_print_times = {}
+ last_print = {}
+
+ for history_entry in metadata[name]["history"]:
+ if (
+ "printTime" not in history_entry
+ or "success" not in history_entry
+ or not history_entry["success"]
+ or "printerProfile" not 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 printer_profile not in former_print_times:
+ former_print_times[printer_profile] = []
+ former_print_times[printer_profile].append(print_time)
+
+ if (
+ printer_profile not 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 name not in metadata:
+ return result
+
+ if "links" not in metadata[name]:
+ return result
+
+ for data in metadata[name]["links"]:
+ if "rel" not 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 "hash" not in metadata[name]:
+ metadata[name]["hash"] = self._create_hash(os.path.join(path, name))
+
+ if "links" not 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 data["name"] not 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 "links" not 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 k not 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 (
+ "display" not 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 (
+ "display" not 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 name not in metadata:
+ return
+
+ metadata = copy.copy(metadata)
+
+ if "hash" in metadata[name]:
+ hash = metadata[name]["hash"]
+ for m in metadata.values():
+ if "links" not 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 Exception:
+ 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 json
+
+ import yaml
+
+ with self._get_persisted_metadata_lock(path):
+ metadata_path_yaml = os.path.join(path, ".metadata.yaml")
+ metadata_path_json = os.path.join(path, ".metadata.json")
+
+ 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..21f0b4ab9 100644
--- a/src/octoprint/logging/__init__.py
+++ b/src/octoprint/logging/__init__.py
@@ -1,159 +1,166 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
-from past.builtins import basestring, unicode
-
-from octoprint.logging import handlers
-
from typing import Union
+from past.builtins import basestring, unicode
+
+from octoprint.logging import handlers # noqa: F401
+
+
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..665298efa 100644
--- a/src/octoprint/logging/handlers.py
+++ b/src/octoprint/logging/handlers.py
@@ -1,196 +1,196 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
+# noinspection PyCompatibility
+import concurrent.futures
import logging.handlers
import os
import re
import time
-# noinspection PyCompatibility
-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..535b797bc 100644
--- a/src/octoprint/plugin/__init__.py
+++ b/src/octoprint/plugin/__init__.py
@@ -16,545 +16,613 @@ 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
import logging
-import threading
+import os
-from octoprint.settings import settings as s
-from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin)
+from octoprint.plugin.core import Plugin, PluginInfo, PluginManager # noqa: F401
+from octoprint.plugin.types import * # noqa: F401,F403 ## used by multiple other modules
from octoprint.plugin.types import OctoPrintPlugin, SettingsPlugin
-from octoprint.plugin.types import * # noqa: F403 ## used by multiple other modules
-
+from octoprint.settings import settings as s
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 "defaults" not in kwargs and self.defaults is not None:
+ kwargs.update(defaults=self.defaults)
+ if "preprocessors" not in kwargs:
+ kwargs.update(preprocessors=self.get_preprocessors)
+ return kwargs
+
+ def add_setter_kwargs(kwargs):
+ if "defaults" not in kwargs and self.defaults is not None:
+ kwargs.update(defaults=self.defaults)
+ if "preprocessors" not 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..b46f80cef 100644
--- a/src/octoprint/plugin/core.py
+++ b/src/octoprint/plugin/core.py
@@ -21,2014 +21,2471 @@ 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"
-import os
-import io
-from collections import defaultdict, namedtuple, OrderedDict
-import logging
import fnmatch
import inspect
+import io
+import logging
+import os
import sys
+from collections import OrderedDict, defaultdict, namedtuple
import pkg_resources
import pkginfo
-
from past.builtins import unicode
-from octoprint.util import to_unicode, sv, time_this
-from octoprint.util.version import is_python_compatible, get_python_version_string
+from octoprint.util import sv, time_this, to_unicode
+from octoprint.util.version import get_python_version_string, is_python_compatible
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__'
- """
- Module attribute from which to retrieve the plugin's python compatibility string.
+ 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
- Python 2 but not Python 3.
+ If unset a default of ``>=2.7,<3`` will be assumed, meaning that the plugin will be considered compatible to
+ Python 2 but not Python 3.
- To mark a plugin as Python 3 compatible, a string of ``>=2.7,<4`` is recommended.
+ To mark a plugin as Python 3 compatible, a string of ``>=2.7,<4`` is recommended.
- Bundled plugins will automatically be assumed to be compatible.
- """
+ Bundled plugins will automatically be assumed to be compatible.
+ """
- attr_hidden = '__plugin_hidden__'
- """
- Module attribute from which to determine if the plugin's hidden or not.
+ 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.
- """
+ 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__'
- """
- Module attribute from which to retrieve the plugin's provided 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
- first entry will be evaluated.
+ This deprecated attribute will only be used if a plugin does not yet offer :attr:`attr_implementation`. Only the
+ first entry will be evaluated.
- .. deprecated:: 1.2.0-dev-694
+ .. deprecated:: 1.2.0-dev-694
- Use :attr:`attr_implementation` instead.
- """
+ 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__'
- """
- Module attribute which to call when loading the plugin.
+ 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`.
+ This deprecated attribute will only be used if a plugin does not yet offer :attr:`attr_load`.
- .. deprecated:: 1.2.0-dev-720
+ .. deprecated:: 1.2.0-dev-720
- Use :attr:`attr_load` instead.
- """
+ 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
- """
- The origin from which this plugin was loaded, either a :class:`EntryPointOrigin`, :class:`FolderOrigin`
- or :class:`ModuleOrigin` instance. Set during loading, initially ``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 hook not 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):
+ import sys
+ from distutils.command.install import install as cmd_install
+ from distutils.dist import Distribution
+
+ 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 site.USER_SITE not in working_set.entries:
+ working_set.add_entry(site.USER_SITE)
+ if site.USER_SITE not 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 k not 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 name not 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 name not 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 name not 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 name not 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 name not 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 name not 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 name not 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 name not 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 hook not 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 name not 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..d2c2661ba 100644
--- a/src/octoprint/plugin/types.py
+++ b/src/octoprint/plugin/types.py
@@ -19,2103 +19,2167 @@ 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 name not 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"])
-
- 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()))
-
- 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()
-
- 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::
-
- 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."""
-
- # 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_save(self, data):
+ old_flag = self._settings.get_boolean(["sub", "some_flag"])
+
+ 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()))
+
+ 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()
+
+ 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::
+
+ 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."""
+
+ # 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
+ """
+ import copy
+
+ from flask_login import current_user
+
+ 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 entry not 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..a91c80155 100644
--- a/src/octoprint/plugins/action_command_notification/__init__.py
+++ b/src/octoprint/plugins/action_command_notification/__init__.py
@@ -1,132 +1,151 @@
# -*- 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 octoprint.access import USER_GROUP
-from octoprint.access.permissions import Permissions
-from octoprint.events import Events
+import time
import flask
from flask_babel import gettext
-import time
+import octoprint.plugin
+from octoprint.access import USER_GROUP
+from octoprint.access.permissions import Permissions
+from octoprint.events import Events
-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_notification/static/clientjs/action_command_notification.js b/src/octoprint/plugins/action_command_notification/static/clientjs/action_command_notification.js
index 249b69704..138226dca 100644
--- a/src/octoprint/plugins/action_command_notification/static/clientjs/action_command_notification.js
+++ b/src/octoprint/plugins/action_command_notification/static/clientjs/action_command_notification.js
@@ -4,19 +4,30 @@
} else {
factory(global.OctoPrintClient);
}
-})(this, function(OctoPrintClient) {
- var OctoPrintActionCommandNotificationClient = function(base) {
+})(this, function (OctoPrintClient) {
+ var OctoPrintActionCommandNotificationClient = function (base) {
this.base = base;
};
- OctoPrintActionCommandNotificationClient.prototype.get = function(refresh, opts) {
- return this.base.get(this.base.getSimpleApiUrl("action_command_notification"), opts);
+ OctoPrintActionCommandNotificationClient.prototype.get = function (refresh, opts) {
+ return this.base.get(
+ this.base.getSimpleApiUrl("action_command_notification"),
+ opts
+ );
};
- OctoPrintActionCommandNotificationClient.prototype.clear = function(opts) {
- return this.base.simpleApiCommand("action_command_notification", "clear", {}, opts);
+ OctoPrintActionCommandNotificationClient.prototype.clear = function (opts) {
+ return this.base.simpleApiCommand(
+ "action_command_notification",
+ "clear",
+ {},
+ opts
+ );
};
- OctoPrintClient.registerPluginComponent("action_command_notification", OctoPrintActionCommandNotificationClient);
+ OctoPrintClient.registerPluginComponent(
+ "action_command_notification",
+ OctoPrintActionCommandNotificationClient
+ );
return OctoPrintActionCommandNotificationClient;
});
diff --git a/src/octoprint/plugins/action_command_notification/static/js/action_command_notification.js b/src/octoprint/plugins/action_command_notification/static/js/action_command_notification.js
index 991557caa..6410639fd 100644
--- a/src/octoprint/plugins/action_command_notification/static/js/action_command_notification.js
+++ b/src/octoprint/plugins/action_command_notification/static/js/action_command_notification.js
@@ -1,4 +1,4 @@
-$(function() {
+$(function () {
function ActionCommandNotificationViewModel(parameters) {
var self = this;
@@ -8,40 +8,57 @@ $(function() {
self.notifications = ko.observableArray([]);
- self.toDateTimeString = function(timestamp) {
+ self.toDateTimeString = function (timestamp) {
return formatDate(timestamp);
};
- self.requestData = function() {
- if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW)) return;
+ self.requestData = function () {
+ if (
+ !self.loginState.hasPermission(
+ self.access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW
+ )
+ )
+ return;
- OctoPrint.plugins.action_command_notification.get()
- .done(self.fromResponse)
+ OctoPrint.plugins.action_command_notification.get().done(self.fromResponse);
};
- self.fromResponse = function(response) {
+ self.fromResponse = function (response) {
self.notifications(response.notifications);
};
- self.clear = function() {
- if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_CLEAR)) return;
+ self.clear = function () {
+ if (
+ !self.loginState.hasPermission(
+ self.access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_CLEAR
+ )
+ )
+ return;
OctoPrint.plugins.action_command_notification.clear();
};
- self.onStartup = self.onUserLoggedIn = self.onUserLoggedOut = function() {
+ self.onStartup = self.onUserLoggedIn = self.onUserLoggedOut = function () {
self.requestData();
};
- self.onDataUpdaterPluginMessage = function(plugin, data) {
- if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW)) return;
+ self.onDataUpdaterPluginMessage = function (plugin, data) {
+ if (
+ !self.loginState.hasPermission(
+ self.access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW
+ )
+ )
+ return;
if (plugin !== "action_command_notification") {
return;
}
self.requestData();
- if (data.message && self.settings.settings.plugins.action_command_notification.enable_popups()) {
+ if (
+ data.message &&
+ self.settings.settings.plugins.action_command_notification.enable_popups()
+ ) {
new PNotify({
title: gettext("Printer Notification"),
text: data.message,
@@ -54,7 +71,6 @@ $(function() {
});
}
};
-
}
OCTOPRINT_VIEWMODELS.push({
diff --git a/src/octoprint/plugins/action_command_prompt/__init__.py b/src/octoprint/plugins/action_command_prompt/__init__.py
index 64f1f8afb..e9cd2e4bb 100644
--- a/src/octoprint/plugins/action_command_prompt/__init__.py
+++ b/src/octoprint/plugins/action_command_prompt/__init__.py
@@ -1,245 +1,305 @@
# -*- 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
-
-from octoprint.server import user_permission
-from octoprint.access import USER_GROUP
-from octoprint.access.permissions import Permissions
-from octoprint.events import Events
-
import flask
from flask_babel import gettext
+import octoprint.plugin
+from octoprint.access import USER_GROUP
+from octoprint.access.permissions import Permissions
+from octoprint.events import Events
+
+
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 "S" not 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/action_command_prompt/static/clientjs/action_command_prompt.js b/src/octoprint/plugins/action_command_prompt/static/clientjs/action_command_prompt.js
index 9ba9b4a14..a2560a078 100644
--- a/src/octoprint/plugins/action_command_prompt/static/clientjs/action_command_prompt.js
+++ b/src/octoprint/plugins/action_command_prompt/static/clientjs/action_command_prompt.js
@@ -4,22 +4,25 @@
} else {
factory(global.OctoPrintClient);
}
-})(this, function(OctoPrintClient) {
- var OctoPrintActionCommandPromptClient = function(base) {
+})(this, function (OctoPrintClient) {
+ var OctoPrintActionCommandPromptClient = function (base) {
this.base = base;
};
- OctoPrintActionCommandPromptClient.prototype.get = function(refresh, opts) {
+ OctoPrintActionCommandPromptClient.prototype.get = function (refresh, opts) {
return this.base.get(this.base.getSimpleApiUrl("action_command_prompt"), opts);
};
- OctoPrintActionCommandPromptClient.prototype.select = function(choice, opts) {
+ OctoPrintActionCommandPromptClient.prototype.select = function (choice, opts) {
var data = {
choice: choice
};
return this.base.simpleApiCommand("action_command_prompt", "select", data, opts);
};
- OctoPrintClient.registerPluginComponent("action_command_prompt", OctoPrintActionCommandPromptClient);
+ OctoPrintClient.registerPluginComponent(
+ "action_command_prompt",
+ OctoPrintActionCommandPromptClient
+ );
return OctoPrintActionCommandPromptClient;
});
diff --git a/src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js b/src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js
index c35faf7e6..d7d1f02d1 100644
--- a/src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js
+++ b/src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js
@@ -1,4 +1,4 @@
-$(function() {
+$(function () {
function ActionCommandPromptViewModel(parameters) {
var self = this;
@@ -10,21 +10,25 @@ $(function() {
self.text = ko.observable();
self.buttons = ko.observableArray([]);
- self.active = ko.pureComputed(function() {
+ self.active = ko.pureComputed(function () {
return self.text() !== undefined;
});
- self.visible = ko.pureComputed(function() {
+ self.visible = ko.pureComputed(function () {
return self.modal() !== undefined;
});
- self.requestData = function() {
- if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT)) return;
+ self.requestData = function () {
+ if (
+ !self.loginState.hasPermission(
+ self.access.permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT
+ )
+ )
+ return;
- OctoPrint.plugins.action_command_prompt.get()
- .done(self.fromResponse);
+ OctoPrint.plugins.action_command_prompt.get().done(self.fromResponse);
};
- self.fromResponse = function(data) {
+ self.fromResponse = function (data) {
if (data.hasOwnProperty("text") && data.hasOwnProperty("choices")) {
self.text(data.text);
self.buttons(data.choices);
@@ -35,7 +39,7 @@ $(function() {
}
};
- self.showPrompt = function() {
+ self.showPrompt = function () {
var text = self.text();
var buttons = self.buttons();
@@ -44,12 +48,12 @@ $(function() {
message: text,
selections: buttons,
maycancel: true, // see #3171
- onselect: function(index) {
+ onselect: function (index) {
if (index > -1) {
self._select(index);
}
},
- onclose: function() {
+ onclose: function () {
self.modal(undefined);
}
};
@@ -57,23 +61,28 @@ $(function() {
self.modal(showSelectionDialog(opts));
};
- self._select = function(index) {
+ self._select = function (index) {
OctoPrint.plugins.action_command_prompt.select(index);
};
- self._closePrompt = function() {
+ self._closePrompt = function () {
var modal = self.modal();
if (modal) {
modal.modal("hide");
}
};
- self.onStartupComplete = function() {
+ self.onStartupComplete = function () {
self.requestData();
};
- self.onDataUpdaterPluginMessage = function(plugin, data) {
- if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT)) return;
+ self.onDataUpdaterPluginMessage = function (plugin, data) {
+ if (
+ !self.loginState.hasPermission(
+ self.access.permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT
+ )
+ )
+ return;
if (plugin !== "action_command_prompt") {
return;
}
@@ -92,8 +101,7 @@ $(function() {
break;
}
}
- }
-
+ };
}
OCTOPRINT_VIEWMODELS.push({
diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py
index 74f4e115e..7f05a23f1 100644
--- a/src/octoprint/plugins/announcements/__init__.py
+++ b/src/octoprint/plugins/announcements/__init__.py
@@ -2,547 +2,642 @@
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"
-import octoprint.plugin
-
import calendar
import io
import os
import re
-import time
-import threading
import sys
-PY2 = sys.version_info[0] < 3
+import threading
+import time
+from collections import OrderedDict
import feedparser
import flask
+from flask_babel import gettext
-from collections import OrderedDict
-
+import octoprint.plugin
+from octoprint import __version__ as OCTOPRINT_VERSION
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.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)
+from octoprint.server.util.flask import (
+ check_etag,
+ no_firstrun_access,
+ with_revalidation_checking,
+)
+from octoprint.util import count, monotonic_time, utmify
+
+PY2 = sys.version_info[0] < 3
+
+
+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 "_blog" not 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 import NO_CONTENT
+ from octoprint.server.util.flask import get_json_command_from_request
+
+ 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 key not 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 key not in enabled and key not in forced:
+ continue
+
+ if "url" not 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: ") # doctest: +ALLOW_UNICODE
- "I'm a link and this is an image: "
- >>> _strip_images("One and two and three and 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: ") # doctest: +ALLOW_UNICODE
+ "I'm a link and this is an image: "
+ >>> _strip_images("One and two and three and 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: ", callback) # doctest: +ALLOW_UNICODE
- "I'm a link and this is an image: foobar"
- >>> _replace_images("One and two and three and 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: ", callback) # doctest: +ALLOW_UNICODE
+ "I'm a link and this is an image: foobar"
+ >>> _replace_images("One and two and three and 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: ") # doctest: +ALLOW_UNICODE
- 'I\\'m a link and this is an image: '
- >>> _lazy_images("I'm a link and this is an image: ", placeholder="ph.png") # doctest: +ALLOW_UNICODE
- 'I\\'m a link and this is an image: '
- >>> _lazy_images("One and two and three and four ", placeholder="ph.png") # doctest: +ALLOW_UNICODE
- 'One and two and three and 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: ") # doctest: +ALLOW_UNICODE
+ 'I\\'m a link and this is an image: '
+ >>> _lazy_images("I'm a link and this is an image: ", placeholder="ph.png") # doctest: +ALLOW_UNICODE
+ 'I\\'m a link and this is an image: '
+ >>> _lazy_images("One and two and three and four ", placeholder="ph.png") # doctest: +ALLOW_UNICODE
+ 'One and two and three and 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/announcements/static/js/announcements.js b/src/octoprint/plugins/announcements/static/js/announcements.js
index ece0a9367..2e015853f 100644
--- a/src/octoprint/plugins/announcements/static/js/announcements.js
+++ b/src/octoprint/plugins/announcements/static/js/announcements.js
@@ -1,4 +1,4 @@
-$(function() {
+$(function () {
function AnnouncementsViewModel(parameters) {
var self = this;
@@ -9,15 +9,22 @@ $(function() {
self.channels = new ItemListHelper(
"plugin.announcements.channels",
{
- "channel": function (a, b) {
+ channel: function (a, b) {
// sorts ascending
- if (a["channel"].toLocaleLowerCase() < b["channel"].toLocaleLowerCase()) return -1;
- if (a["channel"].toLocaleLowerCase() > b["channel"].toLocaleLowerCase()) return 1;
+ if (
+ a["channel"].toLocaleLowerCase() <
+ b["channel"].toLocaleLowerCase()
+ )
+ return -1;
+ if (
+ a["channel"].toLocaleLowerCase() >
+ b["channel"].toLocaleLowerCase()
+ )
+ return 1;
return 0;
}
},
- {
- },
+ {},
"name",
[],
[],
@@ -32,30 +39,34 @@ $(function() {
self.announcementDialogContent = undefined;
self.announcementDialogTabs = undefined;
- self.setupTabLink = function(item) {
+ self.setupTabLink = function (item) {
$("a[data-toggle='tab']", item).on("show", self.resetContentScroll);
};
- self.resetContentScroll = function() {
+ self.resetContentScroll = function () {
self.announcementDialogContent.scrollTop(0);
};
- self.toggleButtonCss = function(data) {
+ self.toggleButtonCss = function (data) {
var icon = data.enabled ? "fa fa-toggle-on" : "fa fa-toggle-off";
- var disabled = (self.enableToggle(data)) ? "" : " disabled";
+ var disabled = self.enableToggle(data) ? "" : " disabled";
return icon + disabled;
};
- self.toggleButtonTitle = function(data) {
- return data.forced ? gettext("Cannot be toggled") : (data.enabled ? gettext("Disable Channel") : gettext("Enable Channel"));
+ self.toggleButtonTitle = function (data) {
+ return data.forced
+ ? gettext("Cannot be toggled")
+ : data.enabled
+ ? gettext("Disable Channel")
+ : gettext("Enable Channel");
};
- self.enableToggle = function(data) {
+ self.enableToggle = function (data) {
return !data.forced;
};
- self.cleanedLink = function(data) {
+ self.cleanedLink = function (data) {
// Strips any query parameters from the link and returns it
var link = data.link;
if (!link) return link;
@@ -67,8 +78,13 @@ $(function() {
return link;
};
- self.markRead = function(channel, until, reload) {
- if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
+ self.markRead = function (channel, until, reload) {
+ if (
+ !self.loginState.hasPermission(
+ self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ
+ )
+ )
+ return;
reload = !!reload;
@@ -85,16 +101,21 @@ $(function() {
dataType: "json",
data: JSON.stringify(payload),
contentType: "application/json; charset=UTF-8",
- success: function() {
+ success: function () {
if (reload) {
- self.retrieveData()
+ self.retrieveData();
}
}
- })
+ });
};
- self.toggleChannel = function(channel) {
- if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_MANAGE)) return;
+ self.toggleChannel = function (channel) {
+ if (
+ !self.loginState.hasPermission(
+ self.access.permissions.PLUGIN_ANNOUNCEMENTS_MANAGE
+ )
+ )
+ return;
var url = PLUGIN_BASEURL + "announcements/channels/" + channel;
@@ -108,18 +129,23 @@ $(function() {
dataType: "json",
data: JSON.stringify(payload),
contentType: "application/json; charset=UTF-8",
- success: function() {
- self.retrieveData()
+ success: function () {
+ self.retrieveData();
}
- })
+ });
};
- self.refreshAnnouncements = function() {
+ self.refreshAnnouncements = function () {
self.retrieveData(true);
};
- self.retrieveData = function(force) {
- if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
+ self.retrieveData = function (force) {
+ if (
+ !self.loginState.hasPermission(
+ self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ
+ )
+ )
+ return;
var url = PLUGIN_BASEURL + "announcements/channels";
if (force) {
@@ -130,20 +156,25 @@ $(function() {
url: url,
type: "GET",
dataType: "json",
- success: function(data) {
+ success: function (data) {
self.fromResponse(data);
}
});
};
- self.fromResponse = function(data) {
- if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
+ self.fromResponse = function (data) {
+ if (
+ !self.loginState.hasPermission(
+ self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ
+ )
+ )
+ return;
var currentTab = $("li.active a", self.announcementDialogTabs).attr("href");
var unread = 0;
var channels = [];
- _.each(data.channels, function(value) {
+ _.each(data.channels, function (value) {
value.last = value.data.length ? value.data[0].published : undefined;
value.count = value.data.length;
unread += value.unread;
@@ -157,8 +188,13 @@ $(function() {
self.selectTab(currentTab);
};
- self.showAnnouncementDialog = function(channel) {
- if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
+ self.showAnnouncementDialog = function (channel) {
+ if (
+ !self.loginState.hasPermission(
+ self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ
+ )
+ )
+ return;
// lazy load images that still need lazy-loading
$("#plugin_announcements_dialog_content article img").lazyload();
@@ -166,12 +202,18 @@ $(function() {
self.announcementDialogContent.scrollTop(0);
if (!self.announcementDialog.hasClass("in")) {
- self.announcementDialog.modal({
- minHeight: function() { return Math.max($.fn.modal.defaults.maxHeight() - 80, 250); }
- }).css({
- width: 'auto',
- 'margin-left': function() { return -($(this).width() /2); }
- });
+ self.announcementDialog
+ .modal({
+ minHeight: function () {
+ return Math.max($.fn.modal.defaults.maxHeight() - 80, 250);
+ }
+ })
+ .css({
+ "width": "auto",
+ "margin-left": function () {
+ return -($(this).width() / 2);
+ }
+ });
}
var tab = undefined;
@@ -183,24 +225,29 @@ $(function() {
return false;
};
- self.selectTab = function(tab) {
+ self.selectTab = function (tab) {
if (tab != undefined) {
if (!_.startsWith(tab, "#")) {
tab = "#" + tab;
}
$('a[href="' + tab + '"]', self.announcementDialogTabs).tab("show");
} else {
- $('a:first', self.announcementDialogTabs).tab("show");
+ $("a:first", self.announcementDialogTabs).tab("show");
}
};
- self.displayAnnouncements = function(channels) {
- if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
+ self.displayAnnouncements = function (channels) {
+ if (
+ !self.loginState.hasPermission(
+ self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ
+ )
+ )
+ return;
var displayLimit = self.settings.settings.plugins.announcements.display_limit();
var maxLength = self.settings.settings.plugins.announcements.summary_limit();
- var cutAfterNewline = function(text) {
+ var cutAfterNewline = function (text) {
text = text.trim();
var firstNewlinePos = text.indexOf("\n");
@@ -211,7 +258,7 @@ $(function() {
return text;
};
- var stripParagraphs = function(text) {
+ var stripParagraphs = function (text) {
if (_.startsWith(text, "
";
}
- text += "" + gettext("You can edit your announcement subscriptions under Settings > Announcements.") + "";
+ text +=
+ "" +
+ gettext(
+ "You can edit your announcement subscriptions under Settings > Announcements."
+ ) +
+ "";
var options = {
title: channel,
@@ -272,27 +346,31 @@ $(function() {
hide: false,
confirm: {
confirm: true,
- buttons: [{
- text: gettext("Later"),
- click: function(notice) {
- notice.remove();
- self.hiddenChannels.push(key);
+ buttons: [
+ {
+ text: gettext("Later"),
+ click: function (notice) {
+ notice.remove();
+ self.hiddenChannels.push(key);
+ }
+ },
+ {
+ text: gettext("Mark read"),
+ click: function (notice) {
+ notice.remove();
+ self.markRead(key, value.last);
+ }
+ },
+ {
+ text: gettext("Read..."),
+ addClass: "btn-primary",
+ click: function (notice) {
+ notice.remove();
+ self.showAnnouncementDialog(key);
+ self.markRead(key, value.last);
+ }
}
- }, {
- text: gettext("Mark read"),
- click: function(notice) {
- notice.remove();
- self.markRead(key, value.last);
- }
- }, {
- text: gettext("Read..."),
- addClass: "btn-primary",
- click: function(notice) {
- notice.remove();
- self.showAnnouncementDialog(key);
- self.markRead(key, value.last);
- }
- }]
+ ]
},
buttons: {
sticker: false,
@@ -311,41 +389,48 @@ $(function() {
});
};
- self.hideAnnouncements = function() {
- _.each(self.channelNotifications, function(notification, key) {
+ self.hideAnnouncements = function () {
+ _.each(self.channelNotifications, function (notification, key) {
notification.remove();
});
self.channelNotifications = {};
};
- self.configureAnnouncements = function() {
+ self.configureAnnouncements = function () {
self.settings.show("settings_plugin_announcements");
};
- self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
- if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) {
+ self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
+ if (
+ !self.loginState.hasPermission(
+ self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ
+ )
+ ) {
self.hideAnnouncements();
} else {
self.retrieveData();
}
};
- self.onStartup = function() {
+ self.onStartup = function () {
self.announcementDialog = $("#plugin_announcements_dialog");
self.announcementDialogContent = $("#plugin_announcements_dialog_content");
self.announcementDialogTabs = $("#plugin_announcements_dialog_tabs");
};
- self.onEventConnectivityChanged = function(payload) {
+ self.onEventConnectivityChanged = function (payload) {
if (!payload || !payload.new) return;
self.retrieveData();
- }
-
+ };
}
OCTOPRINT_VIEWMODELS.push({
construct: AnnouncementsViewModel,
dependencies: ["loginStateViewModel", "settingsViewModel", "accessViewModel"],
- elements: ["#plugin_announcements_dialog", "#settings_plugin_announcements", "#navbar_plugin_announcements"]
+ elements: [
+ "#plugin_announcements_dialog",
+ "#settings_plugin_announcements",
+ "#navbar_plugin_announcements"
+ ]
});
});
diff --git a/src/octoprint/plugins/announcements/static/less/announcements.less b/src/octoprint/plugins/announcements/static/less/announcements.less
index 9e90b346c..42ffeb5f1 100644
--- a/src/octoprint/plugins/announcements/static/less/announcements.less
+++ b/src/octoprint/plugins/announcements/static/less/announcements.less
@@ -1,5 +1,6 @@
table {
- th, td {
+ th,
+ td {
&.settings_plugin_announcements_channels_name {
text-overflow: ellipsis;
text-align: left;
diff --git a/src/octoprint/plugins/appkeys/__init__.py b/src/octoprint/plugins/appkeys/__init__.py
index 5a393058e..e9bc9b3b5 100644
--- a/src/octoprint/plugins/appkeys/__init__.py
+++ b/src/octoprint/plugins/appkeys/__init__.py
@@ -1,447 +1,499 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
-import flask
-import threading
-import os
-import yaml
import io
-import time
-import uuid
+import os
+import threading
from collections import defaultdict
+
+import flask
+import yaml
from flask_babel import gettext
import octoprint.plugin
-from octoprint.settings import valid_boolean_trues
-from octoprint.server.util.flask import restricted_access, no_firstrun_access
-from octoprint.server import NO_CONTENT, current_user, admin_permission
-from octoprint.util import atomic_write, monotonic_time, ResettableTimer, generate_api_key
-
from octoprint.access import ADMIN_GROUP
from octoprint.access.permissions import Permissions
+from octoprint.server import NO_CONTENT, admin_permission, current_user
+from octoprint.server.util.flask import no_firstrun_access, restricted_access
+from octoprint.settings import valid_boolean_trues
+from octoprint.util import ResettableTimer, atomic_write, generate_api_key, monotonic_time
+
+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 "app" not 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 "decision" not 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/appkeys/static/clientjs/appkeys.js b/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js
index 48868d32f..b58adfca4 100644
--- a/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js
+++ b/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js
@@ -4,59 +4,80 @@
} else {
factory(global.OctoPrintClient);
}
-})(this, function(OctoPrintClient) {
- var OctoPrintAppKeysClient = function(base) {
+})(this, function (OctoPrintClient) {
+ var OctoPrintAppKeysClient = function (base) {
this.base = base;
};
- OctoPrintAppKeysClient.prototype.getKeys = function(opts) {
+ OctoPrintAppKeysClient.prototype.getKeys = function (opts) {
return this.base.simpleApiGet("appkeys", opts);
};
- OctoPrintAppKeysClient.prototype.getAllKeys = function(opts) {
- return this.base.get(OctoPrintClient.prototype.getSimpleApiUrl("appkeys") + "?all=true", opts);
+ OctoPrintAppKeysClient.prototype.getAllKeys = function (opts) {
+ return this.base.get(
+ OctoPrintClient.prototype.getSimpleApiUrl("appkeys") + "?all=true",
+ opts
+ );
};
- OctoPrintAppKeysClient.prototype.generateKey = function(app, opts) {
- return this.base.simpleApiCommand("appkeys", "generate", {"app": app}, opts);
+ OctoPrintAppKeysClient.prototype.generateKey = function (app, opts) {
+ return this.base.simpleApiCommand("appkeys", "generate", {app: app}, opts);
};
- OctoPrintAppKeysClient.prototype.generateKeyForUser = function(user, app, opts) {
- return this.base.simpleApiCommand("appkeys", "generate", {"app": app, "user": user}, opts);
+ OctoPrintAppKeysClient.prototype.generateKeyForUser = function (user, app, opts) {
+ return this.base.simpleApiCommand(
+ "appkeys",
+ "generate",
+ {app: app, user: user},
+ opts
+ );
};
- OctoPrintAppKeysClient.prototype.revokeKey = function(key, opts) {
- return this.base.simpleApiCommand("appkeys", "revoke", {"key": key}, opts);
+ OctoPrintAppKeysClient.prototype.revokeKey = function (key, opts) {
+ return this.base.simpleApiCommand("appkeys", "revoke", {key: key}, opts);
};
- OctoPrintAppKeysClient.prototype.decide = function(token, decision, opts) {
- return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "decision/" + token, {decision: !!decision}, opts);
+ OctoPrintAppKeysClient.prototype.decide = function (token, decision, opts) {
+ return this.base.postJson(
+ this.base.getBlueprintUrl("appkeys") + "decision/" + token,
+ {decision: !!decision},
+ opts
+ );
};
- OctoPrintAppKeysClient.prototype.probe = function(opts) {
+ OctoPrintAppKeysClient.prototype.probe = function (opts) {
return this.base.get(this.base.getBlueprintUrl("appkeys") + "probe", opts);
};
- OctoPrintAppKeysClient.prototype.request = function(app, opts) {
+ OctoPrintAppKeysClient.prototype.request = function (app, opts) {
return this.requestForUser(app, undefined, opts);
};
- OctoPrintAppKeysClient.prototype.requestForUser = function(app, user, opts) {
- return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "request", {app: app, user: user}, opts);
+ OctoPrintAppKeysClient.prototype.requestForUser = function (app, user, opts) {
+ return this.base.postJson(
+ this.base.getBlueprintUrl("appkeys") + "request",
+ {app: app, user: user},
+ opts
+ );
};
- OctoPrintAppKeysClient.prototype.checkDecision = function(token, opts) {
- return this.base.get(this.base.getBlueprintUrl("appkeys") + "request/" + token, opts);
+ OctoPrintAppKeysClient.prototype.checkDecision = function (token, opts) {
+ return this.base.get(
+ this.base.getBlueprintUrl("appkeys") + "request/" + token,
+ opts
+ );
};
- OctoPrintAppKeysClient.prototype.authenticate = function(app, user) {
+ OctoPrintAppKeysClient.prototype.authenticate = function (app, user) {
var deferred = $.Deferred();
var client = this;
- client.probe()
- .done(function() {
- client.requestForUser(app, user)
- .done(function(response) {
+ client
+ .probe()
+ .done(function () {
+ client
+ .requestForUser(app, user)
+ .done(function (response) {
var token = response.app_token;
if (!token) {
// no token received, something went wrong
@@ -65,9 +86,10 @@
}
var interval = 1000;
- var poll = function() {
- client.checkDecision(token)
- .done(function(response) {
+ var poll = function () {
+ client
+ .checkDecision(token)
+ .done(function (response) {
if (response.api_key) {
// got a decision, resolve the promise
deferred.resolve(response.api_key);
@@ -77,19 +99,19 @@
window.setTimeout(poll, interval);
}
})
- .fail(function() {
+ .fail(function () {
// something went wrong
deferred.reject();
});
};
window.setTimeout(poll, interval);
})
- .fail(function() {
+ .fail(function () {
// something went wrong
deferred.reject();
});
})
- .fail(function() {
+ .fail(function () {
// workflow unsupported
deferred.reject();
});
diff --git a/src/octoprint/plugins/appkeys/static/js/appkeys.js b/src/octoprint/plugins/appkeys/static/js/appkeys.js
index e26b2ae64..adfa8c3a8 100644
--- a/src/octoprint/plugins/appkeys/static/js/appkeys.js
+++ b/src/octoprint/plugins/appkeys/static/js/appkeys.js
@@ -1,14 +1,14 @@
-$(function() {
+$(function () {
function AppKeysDialogViewModel(parameters) {
var self = this;
self.dialog = undefined;
- self.onStartup = function() {
+ self.onStartup = function () {
self.dialog = $("#plugin_appkeys_keygenerated");
};
- self.showDialog = function(title, data) {
+ self.showDialog = function (title, data) {
if (self.dialog === undefined) return;
var qrcode = {
@@ -27,17 +27,19 @@ $(function() {
self.dialog.find("#plugin_appkeys_keygenerated_user").text(data.user_id);
self.dialog.find("#plugin_appkeys_keygenerated_app").text(data.app_id);
self.dialog.find("#plugin_appkeys_keygenerated_key_text").text(data.api_key);
- self.dialog.find("#plugin_appkeys_keygenerated_key_copy")
+ self.dialog
+ .find("#plugin_appkeys_keygenerated_key_copy")
.off()
- .click(function() {
+ .click(function () {
copyToClipboard(data.api_key);
});
- self.dialog.find("#plugin_appkeys_keygenerated_key_qrcode")
+ self.dialog
+ .find("#plugin_appkeys_keygenerated_key_qrcode")
.empty()
.qrcode(qrcode);
self.dialog.modal("show");
- }
+ };
}
function UserAppKeysViewModel(parameters) {
@@ -48,15 +50,14 @@ $(function() {
self.keys = new ItemListHelper(
"plugin.appkeys.userkeys",
{
- "app": function (a, b) {
+ app: function (a, b) {
// sorts ascending
if (a["app_id"].toLowerCase() < b["app_id"].toLowerCase()) return -1;
if (a["app_id"].toLowerCase() > b["app_id"].toLowerCase()) return 1;
return 0;
}
},
- {
- },
+ {},
"app",
[],
[],
@@ -67,51 +68,62 @@ $(function() {
self.editorApp = ko.observable();
- self.requestData = function() {
- OctoPrint.plugins.appkeys.getKeys()
- .done(self.fromResponse);
+ self.requestData = function () {
+ OctoPrint.plugins.appkeys.getKeys().done(self.fromResponse);
};
- self.fromResponse = function(response) {
+ self.fromResponse = function (response) {
self.keys.updateItems(response.keys);
self.pending = response.pending;
- _.each(self.pending, function(data, token) {
+ _.each(self.pending, function (data, token) {
self.openRequests[token] = self.promptForAccess(data.app_id, token);
- })
+ });
};
- self.generateKey = function() {
- return OctoPrint.plugins.appkeys.generateKey(self.editorApp())
+ self.generateKey = function () {
+ return OctoPrint.plugins.appkeys
+ .generateKey(self.editorApp())
.done(self.requestData)
- .done(function() {
+ .done(function () {
self.editorApp("");
});
};
- self.revokeKey = function(key) {
- var perform = function() {
- OctoPrint.plugins.appkeys.revokeKey(key)
- .done(self.requestData);
+ self.revokeKey = function (key) {
+ var perform = function () {
+ OctoPrint.plugins.appkeys.revokeKey(key).done(self.requestData);
};
- showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: _.escape(key)}),
- perform);
+ showConfirmationDialog(
+ _.sprintf(
+ gettext('You are about to revoke the application key "%(key)s".'),
+ {key: _.escape(key)}
+ ),
+ perform
+ );
};
- self.allowApp = function(token) {
- return OctoPrint.plugins.appkeys.decide(token, true)
- .done(self.requestData);
+ self.allowApp = function (token) {
+ return OctoPrint.plugins.appkeys.decide(token, true).done(self.requestData);
};
- self.denyApp = function(token) {
- return OctoPrint.plugins.appkeys.decide(token, false)
- .done(self.requestData);
+ self.denyApp = function (token) {
+ return OctoPrint.plugins.appkeys.decide(token, false).done(self.requestData);
};
- self.promptForAccess = function(app, token) {
- var message = gettext("\"%(app)s\" has requested access to control OctoPrint through the API.");
+ self.promptForAccess = function (app, token) {
+ var message = gettext(
+ '"%(app)s" has requested access to control OctoPrint through the API.'
+ );
message = _.sprintf(message, {app: _.escape(app)});
- message = "
" + message + "
" + gettext("Do you want to allow access to this application with your user account?") + "
";
+ message =
+ "
" +
+ message +
+ "
" +
+ gettext(
+ "Do you want to allow access to this application with your user account?"
+ ) +
+ "
";
return new PNotify({
title: gettext("Access Request"),
text: message,
@@ -119,19 +131,22 @@ $(function() {
icon: "fa fa-key",
confirm: {
confirm: true,
- buttons: [{
- text: gettext("Allow"),
- click: function(notice) {
- self.allowApp(token);
- notice.remove();
+ buttons: [
+ {
+ text: gettext("Allow"),
+ click: function (notice) {
+ self.allowApp(token);
+ notice.remove();
+ }
+ },
+ {
+ text: gettext("Deny"),
+ click: function (notice) {
+ self.denyApp(token);
+ notice.remove();
+ }
}
- }, {
- text: gettext("Deny"),
- click: function(notice) {
- self.denyApp(token);
- notice.remove();
- }
- }]
+ ]
},
buttons: {
sticker: false,
@@ -140,15 +155,15 @@ $(function() {
});
};
- self.onUserSettingsShown = function() {
+ self.onUserSettingsShown = function () {
self.requestData();
};
- self.onUserLoggedIn = function() {
+ self.onUserLoggedIn = function () {
self.requestData();
};
- self.onDataUpdaterPluginMessage = function(plugin, data) {
+ self.onDataUpdaterPluginMessage = function (plugin, data) {
if (plugin !== "appkeys") {
return;
}
@@ -169,7 +184,6 @@ $(function() {
}
self.openRequests[token] = self.promptForAccess(app, token);
-
} else if (data.type === "end_request") {
token = data.user_token;
@@ -178,7 +192,7 @@ $(function() {
if (self.openRequests[token].state !== "closed") {
self.openRequests[token].remove();
}
- delete self.openRequests[token]
+ delete self.openRequests[token];
}
}
};
@@ -193,7 +207,7 @@ $(function() {
self.keys = new ItemListHelper(
"plugin.appkeys.allkeys",
{
- "user_app": function (a, b) {
+ user_app: function (a, b) {
// sorts ascending, first by user, then by app
if (a["user_id"] > b["user_id"]) return 1;
if (a["user_id"] < b["user_id"]) return -1;
@@ -204,8 +218,7 @@ $(function() {
return 0;
}
},
- {
- },
+ {},
"user_app",
[],
[],
@@ -219,29 +232,28 @@ $(function() {
self.markedForDeletion = ko.observableArray([]);
- self.onSettingsShown = function() {
+ self.onSettingsShown = function () {
self.requestData();
self.editorUser(self.loginState.username());
self.editorApp("");
};
- self.onUserLoggedIn = function() {
+ self.onUserLoggedIn = function () {
self.requestData();
self.editorUser(self.loginState.username());
self.editorApp("");
};
- self.requestData = function() {
- OctoPrint.plugins.appkeys.getAllKeys()
- .done(self.fromResponse);
+ self.requestData = function () {
+ OctoPrint.plugins.appkeys.getAllKeys().done(self.fromResponse);
};
- self.fromResponse = function(response) {
+ self.fromResponse = function (response) {
self.keys.updateItems(response.keys);
var users = [];
var apps = [];
- _.each(response.keys, function(key) {
+ _.each(response.keys, function (key) {
users.push(key.user_id);
apps.push(key.app_id.toLowerCase());
});
@@ -255,77 +267,116 @@ $(function() {
self.apps(apps);
};
- self.generateKey = function() {
- return OctoPrint.plugins.appkeys.generateKeyForUser(self.editorUser(), self.editorApp())
+ self.generateKey = function () {
+ return OctoPrint.plugins.appkeys
+ .generateKeyForUser(self.editorUser(), self.editorApp())
.done(self.requestData)
- .done(function() {
+ .done(function () {
self.editorUser(self.loginState.username());
self.editorApp("");
})
- .done(function(data) {
+ .done(function (data) {
self.dialog.showDialog(gettext("New key generated!"), data);
});
- }
+ };
- self.revokeKey = function(key) {
- var perform = function() {
- OctoPrint.plugins.appkeys.revokeKey(key)
- .done(self.requestData);
+ self.revokeKey = function (key) {
+ var perform = function () {
+ OctoPrint.plugins.appkeys.revokeKey(key).done(self.requestData);
};
- showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: _.escape(key)}),
- perform);
+ showConfirmationDialog(
+ _.sprintf(
+ gettext('You are about to revoke the application key "%(key)s".'),
+ {key: _.escape(key)}
+ ),
+ perform
+ );
};
- self.revokeMarked = function() {
- var perform = function() {
- self._bulkRevoke(self.markedForDeletion())
- .done(function() {
- self.markedForDeletion.removeAll();
- });
+ self.revokeMarked = function () {
+ var perform = function () {
+ self._bulkRevoke(self.markedForDeletion()).done(function () {
+ self.markedForDeletion.removeAll();
+ });
};
- showConfirmationDialog(_.sprintf(gettext("You are about to revoke %(count)d application keys."), {count: self.markedForDeletion().length}),
- perform);
+ showConfirmationDialog(
+ _.sprintf(
+ gettext("You are about to revoke %(count)d application keys."),
+ {count: self.markedForDeletion().length}
+ ),
+ perform
+ );
};
- self.markAllOnPageForDeletion = function() {
- self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(self.keys.paginatedItems(), "api_key"))));
+ self.markAllOnPageForDeletion = function () {
+ self.markedForDeletion(
+ _.uniq(
+ self
+ .markedForDeletion()
+ .concat(_.map(self.keys.paginatedItems(), "api_key"))
+ )
+ );
};
- self.markAllForDeletion = function() {
+ self.markAllForDeletion = function () {
self.markedForDeletion(_.uniq(_.map(self.keys.allItems, "api_key")));
};
- self.markAllByUserForDeletion = function(user) {
- self.markAllByFilterForDeletion(function(e) { return (e.user_id === user); });
+ self.markAllByUserForDeletion = function (user) {
+ self.markAllByFilterForDeletion(function (e) {
+ return e.user_id === user;
+ });
};
- self.markAllByAppForDeletion = function(app) {
- self.markAllByFilterForDeletion(function(e) { return (e.app_id.toLowerCase() === app); })
+ self.markAllByAppForDeletion = function (app) {
+ self.markAllByFilterForDeletion(function (e) {
+ return e.app_id.toLowerCase() === app;
+ });
};
- self.markAllByFilterForDeletion = function(filter) {
- self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(_.filter(self.keys.allItems, filter), "api_key"))));
+ self.markAllByFilterForDeletion = function (filter) {
+ self.markedForDeletion(
+ _.uniq(
+ self
+ .markedForDeletion()
+ .concat(_.map(_.filter(self.keys.allItems, filter), "api_key"))
+ )
+ );
};
- self.clearMarked = function() {
+ self.clearMarked = function () {
self.markedForDeletion.removeAll();
};
- self._bulkRevoke = function(keys) {
+ self._bulkRevoke = function (keys) {
var title, message, handler;
title = gettext("Revoking application keys");
- message = _.sprintf(gettext("Revoking %(count)d application keys..."), {count: keys.length});
- handler = function(key) {
- return OctoPrint.plugins.appkeys.revokeKey(key)
- .done(function() {
- deferred.notify(_.sprintf(gettext("Revoked %(key)s..."), {key: _.escape(key)}), true);
+ message = _.sprintf(gettext("Revoking %(count)d application keys..."), {
+ count: keys.length
+ });
+ handler = function (key) {
+ return OctoPrint.plugins.appkeys
+ .revokeKey(key)
+ .done(function () {
+ deferred.notify(
+ _.sprintf(gettext("Revoked %(key)s..."), {
+ key: _.escape(key)
+ }),
+ true
+ );
})
- .fail(function(jqXHR) {
- var short = _.sprintf(gettext("Revocation of %(key)s failed, continuing..."), {key: _.escape(key)});
- var long = _.sprintf(gettext("Deletion of %(key)s failed: %(error)s"), {key: _.escape(key), error: _.escape(jqXHR.responseText)});
+ .fail(function (jqXHR) {
+ var short = _.sprintf(
+ gettext("Revocation of %(key)s failed, continuing..."),
+ {key: _.escape(key)}
+ );
+ var long = _.sprintf(
+ gettext("Deletion of %(key)s failed: %(error)s"),
+ {key: _.escape(key), error: _.escape(jqXHR.responseText)}
+ );
deferred.notify(short, long, false);
});
};
@@ -343,25 +394,20 @@ $(function() {
showProgressModal(options, promise);
var requests = [];
- _.each(keys, function(key) {
+ _.each(keys, function (key) {
var request = handler(key);
- requests.push(request)
+ requests.push(request);
+ });
+ $.when.apply($, _.map(requests, wrapPromiseWithAlways)).done(function () {
+ deferred.resolve();
+ self.requestData();
});
- $.when.apply($, _.map(requests, wrapPromiseWithAlways))
- .done(function() {
- deferred.resolve();
- self.requestData();
- });
return promise;
};
}
- OCTOPRINT_VIEWMODELS.push([
- AppKeysDialogViewModel,
- [],
- []
- ]);
+ OCTOPRINT_VIEWMODELS.push([AppKeysDialogViewModel, [], []]);
OCTOPRINT_VIEWMODELS.push([
UserAppKeysViewModel,
@@ -373,5 +419,5 @@ $(function() {
AllAppKeysViewModel,
["appKeysDialogViewModel", "loginStateViewModel", "accessViewModel"],
["#settings_plugin_appkeys"]
- ])
+ ]);
});
diff --git a/src/octoprint/plugins/appkeys/templates/appkeys.jinja2 b/src/octoprint/plugins/appkeys/templates/appkeys.jinja2
index 9c8c98be0..bf82e1953 100644
--- a/src/octoprint/plugins/appkeys/templates/appkeys.jinja2
+++ b/src/octoprint/plugins/appkeys/templates/appkeys.jinja2
@@ -36,4 +36,3 @@
-
diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py
index 7d3b04c46..248316151 100644
--- a/src/octoprint/plugins/backup/__init__.py
+++ b/src/octoprint/plugins/backup/__init__.py
@@ -1,1070 +1,1317 @@
# -*- 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
-
-from octoprint.settings import default_settings
-from octoprint.plugin.core import FolderOrigin
-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.platform import is_os_compatible
-from octoprint.util.pip import LocalPipCaller
from octoprint.access import ADMIN_GROUP
from octoprint.access.permissions import Permissions
+from octoprint.events import Events
+from octoprint.plugin.core import FolderOrigin
+from octoprint.server import NO_CONTENT
+from octoprint.server.util.flask import no_firstrun_access
+from octoprint.settings import default_settings
+from octoprint.util import is_hidden_path, to_bytes
+from octoprint.util.pip import LocalPipCaller
+from octoprint.util.platform import is_os_compatible
+from octoprint.util.version import (
+ get_comparable_version,
+ get_octoprint_version,
+ get_octoprint_version_string,
+ is_octoprint_compatible,
+)
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
-
import io
-import flask
+import json
import logging
import os
-import requests
-import sarge
import shutil
+import sys
import tempfile
import threading
import time
-import zipfile
-import json
-import sys
import traceback
+import zipfile
+
+import flask
+import requests
+import sarge
+from flask_babel import gettext
from octoprint.settings import valid_boolean_trues
-
UNKNOWN_PLUGINS_FILE = "unknown_plugins_from_restore.json"
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 import app
+ from octoprint.server.util.flask import admin_validator
+ from octoprint.server.util.tornado import (
+ LargeResponseHandler,
+ access_validation_factory,
+ path_validation_factory,
+ )
+ from octoprint.util import is_hidden_path
+
+ 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 os.environ.get("OCTOPRINT_BACKUP_RESTORE_UNSUPPORTED", False)
+ not 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/backup/static/clientjs/backup.js b/src/octoprint/plugins/backup/static/clientjs/backup.js
index 5f2ee6e62..179588a7a 100644
--- a/src/octoprint/plugins/backup/static/clientjs/backup.js
+++ b/src/octoprint/plugins/backup/static/clientjs/backup.js
@@ -4,17 +4,17 @@
} else {
factory(global.OctoPrintClient);
}
-})(this, function(OctoPrintClient) {
- var OctoPrintBackupClient = function(base) {
+})(this, function (OctoPrintClient) {
+ var OctoPrintBackupClient = function (base) {
this.base = base;
this.url = this.base.getBlueprintUrl("backup");
};
- OctoPrintBackupClient.prototype.get = function(refresh, opts) {
+ OctoPrintBackupClient.prototype.get = function (refresh, opts) {
return this.base.get(this.url, opts);
};
- OctoPrintBackupClient.prototype.createBackup = function(exclude, opts) {
+ OctoPrintBackupClient.prototype.createBackup = function (exclude, opts) {
exclude = exclude || [];
var data = {
@@ -24,11 +24,11 @@
return this.base.postJson(this.url + "backup", data, opts);
};
- OctoPrintBackupClient.prototype.deleteBackup = function(backup, opts) {
+ OctoPrintBackupClient.prototype.deleteBackup = function (backup, opts) {
return this.base.delete(this.url + "backup/" + backup, opts);
};
- OctoPrintBackupClient.prototype.restoreBackup = function(backup, opts) {
+ OctoPrintBackupClient.prototype.restoreBackup = function (backup, opts) {
var data = {
path: backup
};
diff --git a/src/octoprint/plugins/backup/static/js/backup.js b/src/octoprint/plugins/backup/static/js/backup.js
index 8bfe05e00..5f1894efd 100644
--- a/src/octoprint/plugins/backup/static/js/backup.js
+++ b/src/octoprint/plugins/backup/static/js/backup.js
@@ -1,4 +1,4 @@
-$(function() {
+$(function () {
function BackupViewModel(parameters) {
var self = this;
@@ -8,15 +8,14 @@ $(function() {
self.backups = new ItemListHelper(
"plugin.backup.backups",
{
- "date": function (a, b) {
+ date: function (a, b) {
// sorts descending
if (a["date"] > b["date"]) return -1;
if (a["date"] < b["date"]) return 1;
return 0;
}
},
- {
- },
+ {},
"date",
[],
[],
@@ -37,7 +36,7 @@ $(function() {
maxNumberOfFiles: 1,
autoUpload: false,
headers: OctoPrint.getRequestHeaders(),
- add: function(e, data) {
+ add: function (e, data) {
if (data.files.length === 0) {
// no files? ignore
return false;
@@ -46,7 +45,7 @@ $(function() {
self.backupUploadName(data.files[0].name);
self.backupUploadData = data;
},
- done: function(e, data) {
+ done: function (e, data) {
self.backupUploadName(undefined);
self.backupUploadData = undefined;
}
@@ -63,113 +62,151 @@ $(function() {
self.loglines = ko.observableArray([]);
- self.requestData = function() {
- OctoPrint.plugins.backup.get()
- .done(self.fromResponse);
+ self.requestData = function () {
+ OctoPrint.plugins.backup.get().done(self.fromResponse);
};
- self.fromResponse = function(response) {
+ self.fromResponse = function (response) {
self.backups.updateItems(response.backups);
self.unknownPlugins(response.unknown_plugins);
self.restoreSupported(response.restore_supported);
};
- self.createBackup = function() {
+ self.createBackup = function () {
var excluded = self.excludeFromBackup();
- OctoPrint.plugins.backup.createBackup(excluded)
- .done(function() {
- self.excludeFromBackup([]);
- })
+ OctoPrint.plugins.backup.createBackup(excluded).done(function () {
+ self.excludeFromBackup([]);
+ });
};
- self.removeBackup = function(backup) {
- var perform = function() {
- OctoPrint.plugins.backup.deleteBackup(backup)
- .done(function() {
- self.requestData();
- });
+ self.removeBackup = function (backup) {
+ var perform = function () {
+ OctoPrint.plugins.backup.deleteBackup(backup).done(function () {
+ self.requestData();
+ });
};
- showConfirmationDialog(_.sprintf(gettext("You are about to delete backup file \"%(name)s\"."), {name: _.escape(backup)}),
- perform);
+ showConfirmationDialog(
+ _.sprintf(gettext('You are about to delete backup file "%(name)s".'), {
+ name: _.escape(backup)
+ }),
+ perform
+ );
};
- self.restoreBackup = function(backup) {
+ self.restoreBackup = function (backup) {
if (!self.restoreSupported()) return;
- var perform = function() {
+ var perform = function () {
self.restoreInProgress(true);
self.loglines.removeAll();
self.loglines.push({line: "Preparing to restore...", stream: "message"});
self.loglines.push({line: " ", stream: "message"});
- self.restoreDialog.modal({keyboard: false, backdrop: "static", show: true});
+ self.restoreDialog.modal({
+ keyboard: false,
+ backdrop: "static",
+ show: true
+ });
OctoPrint.plugins.backup.restoreBackup(backup);
};
- showConfirmationDialog(_.sprintf(gettext("You are about to restore the backup file \"%(name)s\". This cannot be undone."), {name: _.escape(backup)}),
- perform);
+ showConfirmationDialog(
+ _.sprintf(
+ gettext(
+ 'You are about to restore the backup file "%(name)s". This cannot be undone.'
+ ),
+ {name: _.escape(backup)}
+ ),
+ perform
+ );
};
- self.performRestoreFromUpload = function() {
+ self.performRestoreFromUpload = function () {
if (self.backupUploadData === undefined) return;
- var perform = function() {
+ var perform = function () {
self.restoreInProgress(true);
self.loglines.removeAll();
- self.loglines.push({line: "Uploading backup, this can take a while. Please wait...", stream: "message"});
+ self.loglines.push({
+ line: "Uploading backup, this can take a while. Please wait...",
+ stream: "message"
+ });
self.loglines.push({line: " ", stream: "message"});
- self.restoreDialog.modal({keyboard: false, backdrop: "static", show: true});
+ self.restoreDialog.modal({
+ keyboard: false,
+ backdrop: "static",
+ show: true
+ });
self.backupUploadData.submit();
};
- showConfirmationDialog(_.sprintf(gettext("You are about to upload and restore the backup file \"%(name)s\". This cannot be undone."), {name: _.escape(self.backupUploadName())}),
- perform);
+ showConfirmationDialog(
+ _.sprintf(
+ gettext(
+ 'You are about to upload and restore the backup file "%(name)s". This cannot be undone.'
+ ),
+ {name: _.escape(self.backupUploadName())}
+ ),
+ perform
+ );
};
- self.deleteUnknownPluginRecord = function() {
- var perform = function() {
- OctoPrint.plugins.backup.deleteUnknownPlugins()
- .done(function() {
- self.requestData();
- });
+ self.deleteUnknownPluginRecord = function () {
+ var perform = function () {
+ OctoPrint.plugins.backup.deleteUnknownPlugins().done(function () {
+ self.requestData();
+ });
};
- showConfirmationDialog(gettext("You are about to delete the record of plugins unknown during the last restore."),
- perform);
+ showConfirmationDialog(
+ gettext(
+ "You are about to delete the record of plugins unknown during the last restore."
+ ),
+ perform
+ );
};
- self.markFilesOnPage = function() {
- self.markedForBackupDeletion(_.uniq(self.markedForBackupDeletion().concat(_.map(self.backups.paginatedItems(), "name"))));
+ self.markFilesOnPage = function () {
+ self.markedForBackupDeletion(
+ _.uniq(
+ self
+ .markedForBackupDeletion()
+ .concat(_.map(self.backups.paginatedItems(), "name"))
+ )
+ );
};
- self.markAllFiles = function() {
+ self.markAllFiles = function () {
self.markedForBackupDeletion(_.map(self.backups.allItems, "name"));
};
- self.clearMarkedFiles = function() {
+ self.clearMarkedFiles = function () {
self.markedForBackupDeletion.removeAll();
};
- self.removeMarkedFiles = function() {
- var perform = function() {
- self._bulkRemove(self.markedForBackupDeletion())
- .done(function() {
- self.markedForBackupDeletion.removeAll();
- });
+ self.removeMarkedFiles = function () {
+ var perform = function () {
+ self._bulkRemove(self.markedForBackupDeletion()).done(function () {
+ self.markedForBackupDeletion.removeAll();
+ });
};
- showConfirmationDialog(_.sprintf(gettext("You are about to delete %(count)d backups."), {count: self.markedForBackupDeletion().length}),
- perform);
+ showConfirmationDialog(
+ _.sprintf(gettext("You are about to delete %(count)d backups."), {
+ count: self.markedForBackupDeletion().length
+ }),
+ perform
+ );
};
- self.onStartup = function() {
+ self.onStartup = function () {
self.restoreDialog = $("#settings_plugin_backup_restoredialog");
self.restoreOutput = $("#settings_plugin_backup_restoredialog_output");
};
- self.onSettingsShown = function() {
+ self.onSettingsShown = function () {
self.requestData();
};
- self.onDataUpdaterPluginMessage = function(plugin, data) {
+ self.onDataUpdaterPluginMessage = function (plugin, data) {
if (plugin !== "backup") return;
if (data.type === "backup_done") {
@@ -186,74 +223,131 @@ $(function() {
self.backupInProgress(false);
new PNotify({
title: gettext("Creating the backup failed"),
- text: _.sprintf(gettext("OctoPrint could not create your backup. Please consult octoprint.log for details. Error: %(error)s"), {error: _.escape(data.error)}),
+ text: _.sprintf(
+ gettext(
+ "OctoPrint could not create your backup. Please consult octoprint.log for details. Error: %(error)s"
+ ),
+ {error: _.escape(data.error)}
+ ),
type: "error",
hide: false
});
} else if (data.type === "restore_started") {
- self.loglines.push({line: gettext("Restoring from backup..."), stream: "message"});
+ self.loglines.push({
+ line: gettext("Restoring from backup..."),
+ stream: "message"
+ });
self.loglines.push({line: " ", stream: "message"});
} else if (data.type === "restore_failed") {
self.loglines.push({line: " ", stream: "message"});
- self.loglines.push({line: gettext("Restore failed! Check the above output and octoprint.log for reasons as to why."), stream: "error"});
+ self.loglines.push({
+ line: gettext(
+ "Restore failed! Check the above output and octoprint.log for reasons as to why."
+ ),
+ stream: "error"
+ });
self.restoreInProgress(false);
} else if (data.type === "restore_done") {
self.loglines.push({line: " ", stream: "message"});
- self.loglines.push({line: gettext("Restore successful! The server will now be restarted!"), stream: "message"});
+ self.loglines.push({
+ line: gettext(
+ "Restore successful! The server will now be restarted!"
+ ),
+ stream: "message"
+ });
self.restoreInProgress(false);
} else if (data.type === "installing_plugin") {
self.loglines.push({line: " ", stream: "message"});
self.loglines.push({
- line: _.sprintf(gettext("Installing plugin \"%(plugin)s\"..."), {plugin: _.escape(data.plugin)}),
+ line: _.sprintf(gettext('Installing plugin "%(plugin)s"...'), {
+ plugin: _.escape(data.plugin)
+ }),
stream: "message"
});
} else if (data.type === "plugin_incompatible") {
self.loglines.push({line: " ", stream: "message"});
self.loglines.push({
- line: _.sprintf(gettext("Cannot install plugin \"%(plugin)s\" due to it being incompatible to this OctoPrint version and/or underlying operating system"), {plugin: _.escape(data.plugin.key)}),
+ line: _.sprintf(
+ gettext(
+ 'Cannot install plugin "%(plugin)s" due to it being incompatible to this OctoPrint version and/or underlying operating system'
+ ),
+ {plugin: _.escape(data.plugin.key)}
+ ),
stream: "stderr"
});
} else if (data.type === "unknown_plugins") {
if (data.plugins.length > 0) {
self.loglines.push({line: " ", stream: "message"});
- self.loglines.push({line: _.sprintf(gettext("There are %(count)d plugins you'll need to install manually since they aren't registered on the repository:"), {count: data.plugins.length}), stream: "message"});
- _.each(data.plugins, function(plugin) {
- self.loglines.push({line: plugin.name + ": " + plugin.url, stream: "message"});
+ self.loglines.push({
+ line: _.sprintf(
+ gettext(
+ "There are %(count)d plugins you'll need to install manually since they aren't registered on the repository:"
+ ),
+ {count: data.plugins.length}
+ ),
+ stream: "message"
+ });
+ _.each(data.plugins, function (plugin) {
+ self.loglines.push({
+ line: plugin.name + ": " + plugin.url,
+ stream: "message"
+ });
});
self.loglines.push({line: " ", stream: "message"});
self.unknownPlugins(data.plugins);
}
} else if (data.type === "logline") {
- self.loglines.push(self._preprocessLine({line: data.line, stream: data.stream}));
+ self.loglines.push(
+ self._preprocessLine({line: data.line, stream: data.stream})
+ );
self._scrollRestoreOutputToEnd();
}
};
- self._scrollRestoreOutputToEnd = function() {
- self.restoreOutput.scrollTop(self.restoreOutput[0].scrollHeight - self.restoreOutput.height());
+ self._scrollRestoreOutputToEnd = function () {
+ self.restoreOutput.scrollTop(
+ self.restoreOutput[0].scrollHeight - self.restoreOutput.height()
+ );
};
self._forcedStdoutLine = /You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./;
- self._preprocessLine = function(line) {
+ self._preprocessLine = function (line) {
if (line.stream === "stderr" && line.line.match(self._forcedStdoutLine)) {
line.stream = "stdout";
}
return line;
};
- self._bulkRemove = function(files) {
+ self._bulkRemove = function (files) {
var title, message, handler;
title = gettext("Deleting backups");
- message = _.sprintf(gettext("Deleting %(count)d backups..."), {count: files.length});
- handler = function(filename) {
- return OctoPrint.plugins.backup.deleteBackup(filename)
- .done(function() {
- deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: _.escape(filename)}), true);
+ message = _.sprintf(gettext("Deleting %(count)d backups..."), {
+ count: files.length
+ });
+ handler = function (filename) {
+ return OctoPrint.plugins.backup
+ .deleteBackup(filename)
+ .done(function () {
+ deferred.notify(
+ _.sprintf(gettext("Deleted %(filename)s..."), {
+ filename: _.escape(filename)
+ }),
+ true
+ );
})
- .fail(function(jqXHR) {
- var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: _.escape(filename)});
- var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: _.escape(filename), error: _.escape(jqXHR.responseText)});
+ .fail(function (jqXHR) {
+ var short = _.sprintf(
+ gettext("Deletion of %(filename)s failed, continuing..."),
+ {filename: _.escape(filename)}
+ );
+ var long = _.sprintf(
+ gettext("Deletion of %(filename)s failed: %(error)s"),
+ {
+ filename: _.escape(filename),
+ error: _.escape(jqXHR.responseText)
+ }
+ );
deferred.notify(short, long, false);
});
};
@@ -271,15 +365,14 @@ $(function() {
showProgressModal(options, promise);
var requests = [];
- _.each(files, function(filename) {
+ _.each(files, function (filename) {
var request = handler(filename);
- requests.push(request)
+ requests.push(request);
+ });
+ $.when.apply($, _.map(requests, wrapPromiseWithAlways)).done(function () {
+ deferred.resolve();
+ self.requestData();
});
- $.when.apply($, _.map(requests, wrapPromiseWithAlways))
- .done(function() {
- deferred.resolve();
- self.requestData();
- });
return promise;
};
diff --git a/src/octoprint/plugins/corewizard/__init__.py b/src/octoprint/plugins/corewizard/__init__.py
index e275b340a..d457c5879 100644
--- a/src/octoprint/plugins/corewizard/__init__.py
+++ b/src/octoprint/plugins/corewizard/__init__.py
@@ -1,125 +1,140 @@
# -*- 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"
+from flask_babel import gettext
+
import octoprint.plugin
-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 key not 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/static/js/corewizard.js b/src/octoprint/plugins/corewizard/static/js/corewizard.js
index 5f3dfa7d0..c92cb9beb 100644
--- a/src/octoprint/plugins/corewizard/static/js/corewizard.js
+++ b/src/octoprint/plugins/corewizard/static/js/corewizard.js
@@ -1,4 +1,4 @@
-$(function() {
+$(function () {
function CoreWizardAclViewModel(parameters) {
var self = this;
@@ -13,84 +13,97 @@ $(function() {
self.required = false;
- self.passwordMismatch = ko.pureComputed(function() {
+ self.passwordMismatch = ko.pureComputed(function () {
return self.password() != self.confirmedPassword();
});
- self.validUsername = ko.pureComputed(function() {
+ self.validUsername = ko.pureComputed(function () {
return self.username() && self.username().trim() != "";
});
- self.validPassword = ko.pureComputed(function() {
+ self.validPassword = ko.pureComputed(function () {
return self.password() && self.password().trim() != "";
});
- self.validData = ko.pureComputed(function() {
- return !self.passwordMismatch() && self.validUsername() && self.validPassword();
+ self.validData = ko.pureComputed(function () {
+ return (
+ !self.passwordMismatch() && self.validUsername() && self.validPassword()
+ );
});
- self.keepAccessControl = function() {
+ self.keepAccessControl = function () {
if (!self.validData()) return;
var data = {
- "ac": true,
- "user": self.username(),
- "pass1": self.password(),
- "pass2": self.confirmedPassword()
+ ac: true,
+ user: self.username(),
+ pass1: self.password(),
+ pass2: self.confirmedPassword()
};
self._sendData(data);
};
- self.disableAccessControl = function() {
- var message = gettext("If you disable Access Control and your OctoPrint installation is accessible from the internet, your printer will be accessible by everyone - that also includes the bad guys!");
+ self.disableAccessControl = function () {
+ var message = gettext(
+ "If you disable Access Control and your OctoPrint installation is accessible from the internet, your printer will be accessible by everyone - that also includes the bad guys!"
+ );
showConfirmationDialog({
message: message,
onproceed: function (e) {
var data = {
- "ac": false
+ ac: false
};
self._sendData(data);
}
});
};
- self._sendData = function(data, callback) {
- OctoPrint.postJson("plugin/corewizard/acl", data)
- .done(function() {
- self.setup(true);
- self.decision(data.ac);
- if (data.ac) {
- // we now log the user in
- var user = data.user;
- var pass = data.pass1;
- self.loginStateViewModel.login(user, pass, true)
- .done(function() {
- if (callback) callback();
- });
- } else {
+ self._sendData = function (data, callback) {
+ OctoPrint.postJson("plugin/corewizard/acl", data).done(function () {
+ self.setup(true);
+ self.decision(data.ac);
+ if (data.ac) {
+ // we now log the user in
+ var user = data.user;
+ var pass = data.pass1;
+ self.loginStateViewModel.login(user, pass, true).done(function () {
if (callback) callback();
- }
- });
+ });
+ } else {
+ if (callback) callback();
+ }
+ });
};
- self.onBeforeWizardTabChange = function(next, current) {
+ self.onBeforeWizardTabChange = function (next, current) {
if (!self.required) return true;
- if (!current || !_.startsWith(current, "wizard_plugin_corewizard_acl_") || self.setup()) {
+ if (
+ !current ||
+ !_.startsWith(current, "wizard_plugin_corewizard_acl_") ||
+ self.setup()
+ ) {
return true;
}
showMessageDialog({
title: gettext("Please set up Access Control"),
- message: gettext("You haven't yet set up access control. You need to either setup a username and password and click \"Keep Access Control Enabled\" or click \"Disable Access Control\" before continuing")
+ message: gettext(
+ 'You haven\'t yet set up access control. You need to either setup a username and password and click "Keep Access Control Enabled" or click "Disable Access Control" before continuing'
+ )
});
return false;
};
- self.onWizardDetails = function(response) {
- self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.acl && response.corewizard.details.acl.required;
+ self.onWizardDetails = function (response) {
+ self.required =
+ response &&
+ response.corewizard &&
+ response.corewizard.details &&
+ response.corewizard.details.acl &&
+ response.corewizard.details.acl.required;
};
- self.onWizardFinish = function() {
+ self.onWizardFinish = function () {
if (!self.required) return;
if (!self.decision()) {
@@ -106,17 +119,25 @@ $(function() {
self.required = false;
- self.onWizardDetails = function(response) {
- self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.webcam && response.corewizard.details.webcam.required;
+ self.onWizardDetails = function (response) {
+ self.required =
+ response &&
+ response.corewizard &&
+ response.corewizard.details &&
+ response.corewizard.details.webcam &&
+ response.corewizard.details.webcam.required;
};
- self.onWizardFinish = function() {
+ self.onWizardFinish = function () {
if (!self.required) return;
- if (self.settingsViewModel.webcam_streamUrl()
- || (self.settingsViewModel.webcam_snapshotUrl() && self.settingsViewModel.webcam_ffmpegPath())) {
+ if (
+ self.settingsViewModel.webcam_streamUrl() ||
+ (self.settingsViewModel.webcam_snapshotUrl() &&
+ self.settingsViewModel.webcam_ffmpegPath())
+ ) {
return "reload";
}
- }
+ };
}
function CoreWizardServerCommandsViewModel(parameters) {
@@ -136,22 +157,26 @@ $(function() {
self.required = false;
self.active = false;
- self.enableOnlineCheck = function() {
+ self.enableOnlineCheck = function () {
self.settingsViewModel.server_onlineCheck_enabled(true);
self.decision(true);
self._sendData();
};
- self.disableOnlineCheck = function() {
+ self.disableOnlineCheck = function () {
self.settingsViewModel.server_onlineCheck_enabled(false);
self.decision(false);
self._sendData();
};
- self.onBeforeWizardTabChange = function(next, current) {
+ self.onBeforeWizardTabChange = function (next, current) {
if (!self.required) return true;
- if (!current || !_.startsWith(current, "wizard_plugin_corewizard_onlinecheck_") || self.setup()) {
+ if (
+ !current ||
+ !_.startsWith(current, "wizard_plugin_corewizard_onlinecheck_") ||
+ self.setup()
+ ) {
return true;
}
@@ -159,7 +184,7 @@ $(function() {
return false;
};
- self.onBeforeWizardFinish = function() {
+ self.onBeforeWizardFinish = function () {
if (!self.required) return true;
if (self.setup()) {
@@ -170,18 +195,25 @@ $(function() {
return false;
};
- self.onWizardDetails = function(response) {
- self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.onlinecheck && response.corewizard.details.onlinecheck.required;
+ self.onWizardDetails = function (response) {
+ self.required =
+ response &&
+ response.corewizard &&
+ response.corewizard.details &&
+ response.corewizard.details.onlinecheck &&
+ response.corewizard.details.onlinecheck.required;
};
- self._showDecisionNeededDialog = function() {
+ self._showDecisionNeededDialog = function () {
showMessageDialog({
title: gettext("Please set up the online connectivity check"),
- message: gettext("You haven't yet decided on whether to enable or disable the online connectivity check. You need to either enable or disable it before continuing.")
+ message: gettext(
+ "You haven't yet decided on whether to enable or disable the online connectivity check. You need to either enable or disable it before continuing."
+ )
});
};
- self._sendData = function() {
+ self._sendData = function () {
var data = {
server: {
onlineCheck: {
@@ -194,13 +226,11 @@ $(function() {
};
self.active = true;
- self.settingsViewModel.saveData(data)
- .done(function() {
- self.setup(true);
- self.active = false;
- });
+ self.settingsViewModel.saveData(data).done(function () {
+ self.setup(true);
+ self.active = false;
+ });
};
-
}
function CoreWizardPluginBlacklistViewModel(parameters) {
@@ -214,22 +244,26 @@ $(function() {
self.required = false;
self.active = false;
- self.enablePluginBlacklist = function() {
+ self.enablePluginBlacklist = function () {
self.settingsViewModel.server_pluginBlacklist_enabled(true);
self.decision(true);
self._sendData();
};
- self.disablePluginBlacklist = function() {
+ self.disablePluginBlacklist = function () {
self.settingsViewModel.server_pluginBlacklist_enabled(false);
self.decision(false);
self._sendData();
};
- self.onBeforeWizardTabChange = function(next, current) {
+ self.onBeforeWizardTabChange = function (next, current) {
if (!self.required) return true;
- if (!current || !_.startsWith(current, "wizard_plugin_corewizard_pluginblacklist_") || self.setup()) {
+ if (
+ !current ||
+ !_.startsWith(current, "wizard_plugin_corewizard_pluginblacklist_") ||
+ self.setup()
+ ) {
return true;
}
@@ -237,7 +271,7 @@ $(function() {
return false;
};
- self.onBeforeWizardFinish = function() {
+ self.onBeforeWizardFinish = function () {
if (!self.required) return true;
if (self.setup()) {
@@ -248,18 +282,25 @@ $(function() {
return false;
};
- self.onWizardDetails = function(response) {
- self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.pluginblacklist && response.corewizard.details.pluginblacklist.required;
+ self.onWizardDetails = function (response) {
+ self.required =
+ response &&
+ response.corewizard &&
+ response.corewizard.details &&
+ response.corewizard.details.pluginblacklist &&
+ response.corewizard.details.pluginblacklist.required;
};
- self._showDecisionNeededDialog = function() {
+ self._showDecisionNeededDialog = function () {
showMessageDialog({
title: gettext("Please set up the plugin blacklist processing"),
- message: gettext("You haven't yet decided on whether to enable or disable the plugin blacklist processing. You need to either enable or disable it before continuing.")
+ message: gettext(
+ "You haven't yet decided on whether to enable or disable the plugin blacklist processing. You need to either enable or disable it before continuing."
+ )
});
};
- self._sendData = function() {
+ self._sendData = function () {
var data = {
server: {
pluginBlacklist: {
@@ -269,13 +310,11 @@ $(function() {
};
self.active = true;
- self.settingsViewModel.saveData(data)
- .done(function() {
- self.setup(true);
- self.active = false;
- });
+ self.settingsViewModel.saveData(data).done(function () {
+ self.setup(true);
+ self.active = false;
+ });
};
-
}
function CoreWizardPrinterProfileViewModel(parameters) {
@@ -288,54 +327,68 @@ $(function() {
self.editor = self.printerProfiles.createProfileEditor();
self.editorLoaded = ko.observable(false);
- self.onWizardDetails = function(response) {
- self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.printerprofile && response.corewizard.details.printerprofile.required;
+ self.onWizardDetails = function (response) {
+ self.required =
+ response &&
+ response.corewizard &&
+ response.corewizard.details &&
+ response.corewizard.details.printerprofile &&
+ response.corewizard.details.printerprofile.required;
if (!self.required) return;
- OctoPrint.printerprofiles.get("_default")
- .done(function(data) {
+ OctoPrint.printerprofiles
+ .get("_default")
+ .done(function (data) {
self.editor.fromProfileData(data);
self.editorLoaded(true);
})
- .fail(function() {
+ .fail(function () {
self.editor.fromProfileData();
self.editorLoaded(true);
});
};
- self.onWizardFinish = function() {
+ self.onWizardFinish = function () {
if (!self.required) return;
- OctoPrint.printerprofiles.update("_default", self.editor.toProfileData())
- .done(function() {
+ OctoPrint.printerprofiles
+ .update("_default", self.editor.toProfileData())
+ .done(function () {
self.printerProfiles.requestData();
});
};
}
- OCTOPRINT_VIEWMODELS.push({
- construct: CoreWizardAclViewModel,
- dependencies: ["loginStateViewModel"],
- elements: ["#wizard_plugin_corewizard_acl"]
- }, {
- construct: CoreWizardWebcamViewModel,
- dependencies: ["settingsViewModel"],
- elements: ["#wizard_plugin_corewizard_webcam"]
- }, {
- construct: CoreWizardServerCommandsViewModel,
- dependencies: ["settingsViewModel"],
- elements: ["#wizard_plugin_corewizard_servercommands"]
- }, {
- construct: CoreWizardOnlineCheckViewModel,
- dependencies: ["settingsViewModel"],
- elements: ["#wizard_plugin_corewizard_onlinecheck"]
- }, {
- construct: CoreWizardPluginBlacklistViewModel,
- dependencies: ["settingsViewModel"],
- elements: ["#wizard_plugin_corewizard_pluginblacklist"]
- }, {
- construct: CoreWizardPrinterProfileViewModel,
- dependencies: ["printerProfilesViewModel"],
- elements: ["#wizard_plugin_corewizard_printerprofile"]
- });
+ OCTOPRINT_VIEWMODELS.push(
+ {
+ construct: CoreWizardAclViewModel,
+ dependencies: ["loginStateViewModel"],
+ elements: ["#wizard_plugin_corewizard_acl"]
+ },
+ {
+ construct: CoreWizardWebcamViewModel,
+ dependencies: ["settingsViewModel"],
+ elements: ["#wizard_plugin_corewizard_webcam"]
+ },
+ {
+ construct: CoreWizardServerCommandsViewModel,
+ dependencies: ["settingsViewModel"],
+ elements: ["#wizard_plugin_corewizard_servercommands"]
+ },
+ {
+ construct: CoreWizardOnlineCheckViewModel,
+ dependencies: ["settingsViewModel"],
+ elements: ["#wizard_plugin_corewizard_onlinecheck"]
+ },
+ {
+ construct: CoreWizardPluginBlacklistViewModel,
+ dependencies: ["settingsViewModel"],
+ elements: ["#wizard_plugin_corewizard_pluginblacklist"]
+ },
+ {
+ construct: CoreWizardPrinterProfileViewModel,
+ dependencies: ["printerProfilesViewModel"],
+ elements: ["#wizard_plugin_corewizard_printerprofile"]
+ }
+ );
});
diff --git a/src/octoprint/plugins/corewizard/subwizards.py b/src/octoprint/plugins/corewizard/subwizards.py
index e695ea9c3..0655de0e5 100644
--- a/src/octoprint/plugins/corewizard/subwizards.py
+++ b/src/octoprint/plugins/corewizard/subwizards.py
@@ -1,152 +1,186 @@
# -*- 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
-
-import sys
import inspect
+import sys
+
from flask_babel import gettext
+
+import octoprint.plugin
from octoprint.access import ADMIN_GROUP, USER_GROUP
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 abort, request
- if not self._settings.global_get(["server", "firstRun"]) or self._user_manager.has_been_customized():
- abort(404)
+ from octoprint.server.api import NO_CONTENT, valid_boolean_trues
- data = request.get_json()
- if data is None:
- data = request.values
+ if (
+ not self._settings.global_get(["server", "firstRun"])
+ or self._user_manager.has_been_customized()
+ ):
+ abort(404)
- 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()
+ data = request.get_json()
+ if data is None:
+ data = request.values
- 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
+ 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 data["ac"] not 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..4bbf856af 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"
"""
@@ -11,690 +11,810 @@ The SSDP/UPNP implementations has been largely inspired by https://gist.github.c
For a spec see http://www.upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.0.pdf
"""
-import flask
-from flask_babel import gettext
-
# noinspection PyCompatibility
from builtins import range
+import flask
+from flask_babel import gettext
+
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
+import socket
+import time
+
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 key not 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 Exception:
+ 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 io
+ import threading
+
+ 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/discovery/templates/discovery.xml.jinja2 b/src/octoprint/plugins/discovery/templates/discovery.xml.jinja2
index 413c84f7a..f99dfee2f 100644
--- a/src/octoprint/plugins/discovery/templates/discovery.xml.jinja2
+++ b/src/octoprint/plugins/discovery/templates/discovery.xml.jinja2
@@ -19,4 +19,4 @@
{{ presentationUrl }}
-
\ No newline at end of file
+
diff --git a/src/octoprint/plugins/errortracking/__init__.py b/src/octoprint/plugins/errortracking/__init__.py
index 4ee577ad4..f73feec88 100644
--- a/src/octoprint/plugins/errortracking/__init__.py
+++ b/src/octoprint/plugins/errortracking/__init__.py
@@ -1,208 +1,253 @@
# 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 errno
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
-
+import requests.exceptions
+import serial
+import tornado.websocket
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"
+import octoprint.plugin
+from octoprint.util import get_fully_qualified_classname as fqcn # noqa: F401
+from octoprint.util.version import (
+ get_octoprint_version_string,
+ is_released_octoprint_version,
+)
-SETTINGS_DEFAULTS = {"enabled": False,
- "enabled_unreleased": False,
- "unique_id": None,
- "url_server": SENTRY_URL_SERVER,
- "url_coreui": SENTRY_URL_COREUI}
+SENTRY_URL_SERVER = (
+ "https://d479a74f172d4ac2b959a9a7d0536a82@o118517.ingest.sentry.io/1373987"
+)
+SENTRY_URL_COREUI = (
+ "https://040577fb88b241ff985e408c11775720@o118517.ingest.sentry.io/1374096"
+)
-import serial
-import requests.exceptions
-import errno
-import tornado.websocket
+SETTINGS_DEFAULTS = {
+ "enabled": False,
+ "enabled_unreleased": False,
+ "unique_id": None,
+ "url_server": SENTRY_URL_SERVER,
+ "url_coreui": SENTRY_URL_COREUI,
+}
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
- for ignore in IGNORED_EXCEPTIONS:
- if isinstance(ignore, tuple):
- ignored_exc, matcher = ignore
- else:
- ignored_exc = ignore
- matcher = lambda *args: True
+ from octoprint.plugin import plugin_manager
- 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
+ def _before_send(event, hint):
+ if "exc_info" not in hint:
+ # we only want exceptions
+ return None
- elif isinstance(ignore, type):
- if isinstance(hint["exc_info"][1], ignore):
- # exception ignored
- return None
+ handled = True
+ logger = event.get("logger", "")
+ plugin = event.get("extra", {}).get("plugin", None)
+ callback = event.get("extra", {}).get("callback", 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"]))
+ for ignore in IGNORED_EXCEPTIONS:
+ if isinstance(ignore, tuple):
+ ignored_exc, matcher = ignore
+ else:
+ ignored_exc = ignore
+ matcher = lambda *args: True
- 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
+ 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 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
+ elif isinstance(ignore, type):
+ if isinstance(hint["exc_info"][1], ignore):
+ # exception ignored
+ return None
- 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 event.get("exception") and event["exception"].get("values"):
+ handled = not any(
+ map(
+ lambda x: x.get("mechanism")
+ and not x["mechanism"].get("handled", True),
+ event["exception"]["values"],
+ )
+ )
- return event
+ 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
- sentry_sdk.init(url_server,
- release=version,
- before_send=_before_send)
+ 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
- with sentry_sdk.configure_scope() as scope:
- scope.user = {"id": unique_id}
+ 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
- logging.getLogger("octoprint.plugins.errortracking").info("Initialized error tracking")
- _enabled = True
+ return event
+
+ 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/errortracking/static/js/errortracking.js b/src/octoprint/plugins/errortracking/static/js/errortracking.js
index 32ed05e0b..651bcaa0c 100644
--- a/src/octoprint/plugins/errortracking/static/js/errortracking.js
+++ b/src/octoprint/plugins/errortracking/static/js/errortracking.js
@@ -1,4 +1,4 @@
-$(function() {
+$(function () {
function ErrorTrackingViewModel(parameters) {
var self = this;
@@ -6,7 +6,7 @@ $(function() {
self.loginState = parameters[1];
var notification = undefined;
- var performCheck = function() {
+ var performCheck = function () {
if (!self.loginState.isAdmin()) return;
// already enabled?
@@ -19,7 +19,8 @@ $(function() {
// ignored?
try {
- var ignoredString = localStorage["plugin.errortracking.notification_ignored"];
+ var ignoredString =
+ localStorage["plugin.errortracking.notification_ignored"];
var ignored = false;
if (ignoredString) {
@@ -28,50 +29,63 @@ $(function() {
if (ignored) return;
} catch (ex) {
- log.error("Error while reading plugin.errortracking.notification_ignored from local storage");
+ log.error(
+ "Error while reading plugin.errortracking.notification_ignored from local storage"
+ );
}
// show notification
notification = new PNotify({
title: gettext("Enable error reporting?"),
- text: gettext("
It looks like you are tracking an OctoPrint RC release channel. It " +
- "would be great if you would enable error reporting so that any kind of errors that occur " +
- "with an RC can be looked into more easily. Thank you!
" +
- "
You can find more information on error reporting " +
- "under Settings > Error Tracking
"),
+ text: gettext(
+ "
It looks like you are tracking an OctoPrint RC release channel. It " +
+ "would be great if you would enable error reporting so that any kind of errors that occur " +
+ "with an RC can be looked into more easily. Thank you!
" +
+ "
You can find more information on error reporting " +
+ "under Settings > Error Tracking
";
}
console.log("Initialization succeeded with warnings.", warnings);
}
return true;
};
- var setOptions = function(options) {
+ var setOptions = function (options) {
if (!options) return;
for (var opt in options) {
if (options[opt] === undefined) continue;
@@ -132,7 +134,7 @@ GCODE.ui = (function(){
return {
worker: undefined,
- init: function(options){
+ init: function (options) {
if (options) setOptions(options);
if (!options.container) {
return false;
@@ -146,7 +148,7 @@ GCODE.ui = (function(){
setProgress("", 0);
this.worker = new Worker(GCODE_WORKER);
- this.worker.addEventListener('message', processMessage, false);
+ this.worker.addEventListener("message", processMessage, false);
GCODE.renderer.setOption({
container: options.container,
@@ -161,7 +163,7 @@ GCODE.ui = (function(){
return true;
},
- clear: function() {
+ clear: function () {
GCODE.gCodeReader.clear();
GCODE.renderer.clear();
@@ -174,11 +176,11 @@ GCODE.ui = (function(){
}
},
- updateLayerInfo: function(layerNum){
+ updateLayerInfo: function (layerNum) {
switchLayer(layerNum, true);
},
- updateOptions: function(options) {
+ updateOptions: function (options) {
setOptions(options.ui);
if (options.reader) {
GCODE.gCodeReader.setOption(options.reader);
@@ -188,12 +190,12 @@ GCODE.ui = (function(){
}
},
- changeSelectedLayer: function(newLayerNum) {
+ changeSelectedLayer: function (newLayerNum) {
switchLayer(newLayerNum);
},
- changeSelectedCommands: function(layerNum, first, last) {
+ changeSelectedCommands: function (layerNum, first, last) {
switchCommands(layerNum, first, last);
}
- }
-}());
+ };
+})();
diff --git a/src/octoprint/plugins/gcodeviewer/static/js/viewer/worker.js b/src/octoprint/plugins/gcodeviewer/static/js/viewer/worker.js
index dded4b51c..350102285 100644
--- a/src/octoprint/plugins/gcodeviewer/static/js/viewer/worker.js
+++ b/src/octoprint/plugins/gcodeviewer/static/js/viewer/worker.js
@@ -6,17 +6,28 @@
var gcode;
var firstReport;
-var toolOffsets = [
- {x: 0, y: 0}
-];
+var toolOffsets = [{x: 0, y: 0}];
var g90InfluencesExtruder = false;
var z_heights = {};
var model = [];
var max = {x: undefined, y: undefined, z: undefined};
var min = {x: undefined, y: undefined, z: undefined};
-var boundingBox = {minX: undefined, maxX: undefined, minY: undefined, maxY: undefined, minZ: undefined, maxZ: undefined};
+var boundingBox = {
+ minX: undefined,
+ maxX: undefined,
+ minY: undefined,
+ maxY: undefined,
+ minZ: undefined,
+ maxZ: undefined
+};
var modelSize = {x: undefined, y: undefined, z: undefined};
-var bed = {x: undefined, y: undefined, r: undefined, circular: false, centeredOrigin: false};
+var bed = {
+ x: undefined,
+ y: undefined,
+ r: undefined,
+ circular: false,
+ centeredOrigin: false
+};
var ignoreOutsideBed = false;
var filamentByLayer = {};
var totalFilament = [0];
@@ -29,8 +40,8 @@ var speedsByLayer = {extrude: {}, retract: {}, move: {}};
var sendLayerToParent = function (layerNum, z, progress) {
self.postMessage({
- "cmd": "returnLayer",
- "msg": {
+ cmd: "returnLayer",
+ msg: {
cmds: model[layerNum],
layerNum: layerNum,
zHeightObject: {zValue: z, layer: z_heights[z]},
@@ -50,8 +61,8 @@ var sendMultiLayerToParent = function (layerNum, z, progress) {
}
self.postMessage({
- "cmd": "returnMultiLayer",
- "msg": {
+ cmd: "returnMultiLayer",
+ msg: {
model: tmpModel,
layerNum: layerNum,
zHeightObject: {zValue: z, layer: tmpZHeight},
@@ -61,11 +72,10 @@ var sendMultiLayerToParent = function (layerNum, z, progress) {
});
};
-
var sendSizeProgress = function (progress) {
self.postMessage({
- "cmd": "analyzeProgress",
- "msg": {
+ cmd: "analyzeProgress",
+ msg: {
progress: progress,
printTime: printTime
}
@@ -74,8 +84,8 @@ var sendSizeProgress = function (progress) {
var sendAnalyzeDone = function () {
self.postMessage({
- "cmd": "analyzeDone",
- "msg": {
+ cmd: "analyzeDone",
+ msg: {
max: max,
min: min,
modelSize: modelSize,
@@ -101,7 +111,7 @@ var purgeLayers = function () {
purge = true;
} else {
for (var j = 0; j < model[i].length; j++) {
- if (model[i][j].extrude)purge = false;
+ if (model[i][j].extrude) purge = false;
}
}
if (!purge) {
@@ -110,7 +120,7 @@ var purgeLayers = function () {
}
};
-var bedBounds = function() {
+var bedBounds = function () {
if (!bed) {
return {xMin: 0, xMax: 0, yMin: 0, yMax: 0};
}
@@ -119,30 +129,36 @@ var bedBounds = function() {
if (bed.circular) {
result = {xMin: -bed.r, xMax: bed.r, yMin: -bed.r, yMax: bed.r};
} else if (bed.centeredOrigin) {
- result = {xMin: -bed.x/2.0, xMax: bed.x/2.0, yMin: -bed.y/2.0, yMax: bed.y/2.0};
+ result = {
+ xMin: -bed.x / 2.0,
+ xMax: bed.x / 2.0,
+ yMin: -bed.y / 2.0,
+ yMax: bed.y / 2.0
+ };
} else {
result = {xMin: 0, xMax: bed.x, yMin: 0, yMax: bed.y};
}
return result;
};
-var withinBedBounds = function(x, y, bedBounds) {
+var withinBedBounds = function (x, y, bedBounds) {
if (!ignoreOutsideBed) return true;
var result = true;
if (x !== undefined && !isNaN(x)) {
- result = result && (x >= bedBounds.xMin && x <= bedBounds.xMax);
+ result = result && x >= bedBounds.xMin && x <= bedBounds.xMax;
}
if (y !== undefined && !isNaN(y)) {
- result = result && (y >= bedBounds.yMin && y <= bedBounds.yMax);
+ result = result && y >= bedBounds.yMin && y <= bedBounds.yMax;
}
return result;
};
var analyzeModel = function () {
- var tmp1 = 0, tmp2 = 0;
+ var tmp1 = 0,
+ tmp2 = 0;
var speedIndex = 0;
var type;
var printTimeAdd = 0;
@@ -158,38 +174,55 @@ var analyzeModel = function () {
var retract = cmds[j].retract && cmds[j].retract > 0;
var extrude = cmds[j].extrude && cmds[j].extrude > 0 && !retract;
- var move = cmds[j].x !== undefined || cmds[j].y !== undefined || cmds[j].z !== undefined;
+ var move =
+ cmds[j].x !== undefined ||
+ cmds[j].y !== undefined ||
+ cmds[j].z !== undefined;
var prevInBounds = withinBedBounds(cmds[j].prevX, cmds[j].prevY, bounds);
- var inBounds = withinBedBounds(cmds[j].x === undefined ? cmds[j].prevX : cmds[j].x,
- cmds[j].y === undefined ? cmds[j].prevY : cmds[j].y,
- bounds);
+ var inBounds = withinBedBounds(
+ cmds[j].x === undefined ? cmds[j].prevX : cmds[j].x,
+ cmds[j].y === undefined ? cmds[j].prevY : cmds[j].y,
+ bounds
+ );
- var recordX = function(x, inBounds) {
+ var recordX = function (x, inBounds) {
if (x === undefined || isNaN(x)) return;
max.x = max.x !== undefined ? Math.max(max.x, x) : x;
min.x = min.x !== undefined ? Math.min(min.x, x) : x;
if (inBounds) {
- boundingBox.minX = boundingBox.minX !== undefined ? Math.min(boundingBox.minX, x): x;
- boundingBox.maxX = boundingBox.maxX !== undefined ? Math.max(boundingBox.maxX, x): x;
+ boundingBox.minX =
+ boundingBox.minX !== undefined
+ ? Math.min(boundingBox.minX, x)
+ : x;
+ boundingBox.maxX =
+ boundingBox.maxX !== undefined
+ ? Math.max(boundingBox.maxX, x)
+ : x;
}
};
- var recordY = function(y, inBounds) {
+ var recordY = function (y, inBounds) {
if (y === undefined || isNaN(y)) return;
max.y = max.y !== undefined ? Math.max(max.y, y) : y;
min.y = min.y !== undefined ? Math.min(min.y, y) : y;
if (inBounds) {
- boundingBox.minY = boundingBox.minY !== undefined ? Math.min(boundingBox.minY, y): y;
- boundingBox.maxY = boundingBox.maxY !== undefined ? Math.max(boundingBox.maxY, y): y;
+ boundingBox.minY =
+ boundingBox.minY !== undefined
+ ? Math.min(boundingBox.minY, y)
+ : y;
+ boundingBox.maxY =
+ boundingBox.maxY !== undefined
+ ? Math.max(boundingBox.maxY, y)
+ : y;
}
};
- var recordZ = function(z) {
+ var recordZ = function (z) {
if (z === undefined || isNaN(z)) return;
max.z = max.z !== undefined ? Math.max(max.z, z) : z;
@@ -210,20 +243,27 @@ var analyzeModel = function () {
if (!totalFilament[tool]) totalFilament[tool] = 0;
if (!filamentByLayer[cmds[j].prevZ]) filamentByLayer[cmds[j].prevZ] = [0];
- if (!filamentByLayer[cmds[j].prevZ][tool]) filamentByLayer[cmds[j].prevZ][tool] = 0;
+ if (!filamentByLayer[cmds[j].prevZ][tool])
+ filamentByLayer[cmds[j].prevZ][tool] = 0;
if (cmds[j].extrusion) {
totalFilament[tool] += cmds[j].extrusion;
filamentByLayer[cmds[j].prevZ][tool] += cmds[j].extrusion;
}
- if (cmds[j].x !== undefined && !isNaN(cmds[j].x)
- && cmds[j].y !== undefined && !isNaN(cmds[j].y)) {
+ if (
+ cmds[j].x !== undefined &&
+ !isNaN(cmds[j].x) &&
+ cmds[j].y !== undefined &&
+ !isNaN(cmds[j].y)
+ ) {
var diffX = cmds[j].x - cmds[j].prevX;
var diffY = cmds[j].y - cmds[j].prevY;
if (move) {
- printTimeAdd = Math.sqrt(diffX * diffX + diffY * diffY) / (cmds[j].speed / 60);
+ printTimeAdd =
+ Math.sqrt(diffX * diffX + diffY * diffY) / (cmds[j].speed / 60);
} else if (extrude) {
- tmp1 = Math.sqrt(diffX * diffX + diffY * diffY) / (cmds[j].speed / 60);
+ tmp1 =
+ Math.sqrt(diffX * diffX + diffY * diffY) / (cmds[j].speed / 60);
tmp2 = Math.abs(cmds[j].extrusion / (cmds[j].speed / 60));
printTimeAdd = Math.max(tmp1, tmp2);
} else if (retract) {
@@ -240,14 +280,14 @@ var analyzeModel = function () {
printTimeByLayer[cmds[j].prevZ] += printTimeAdd;
if (cmds[j].extrude && cmds[j].retract === 0) {
- type = 'extrude';
+ type = "extrude";
} else if (cmds[j].retract !== 0) {
- type = 'retract';
+ type = "retract";
} else if (!cmds[j].extrude && cmds[j].retract === 0) {
- type = 'move';
+ type = "move";
} else {
- self.postMessage({cmd: 'unknown type of move'});
- type = 'unknown';
+ self.postMessage({cmd: "unknown type of move"});
+ type = "unknown";
}
speedIndex = speeds[type].indexOf(cmds[j].speed);
@@ -255,16 +295,14 @@ var analyzeModel = function () {
speeds[type].push(cmds[j].speed);
speedIndex = speeds[type].indexOf(cmds[j].speed);
}
- if (typeof(speedsByLayer[type][cmds[j].prevZ]) === 'undefined') {
+ if (typeof speedsByLayer[type][cmds[j].prevZ] === "undefined") {
speedsByLayer[type][cmds[j].prevZ] = [];
}
if (speedsByLayer[type][cmds[j].prevZ].indexOf(cmds[j].speed) === -1) {
speedsByLayer[type][cmds[j].prevZ][speedIndex] = cmds[j].speed;
}
-
}
- sendSizeProgress(i / model.length * 100);
-
+ sendSizeProgress((i / model.length) * 100);
}
purgeLayers();
@@ -285,11 +323,18 @@ var doParse = function () {
var lastSend = 0;
var layer = 0;
- var x, y, z = 0;
+ var x,
+ y,
+ z = 0;
var center_i, center_j, direction;
- var prevX = 0, prevY = 0, prevZ = 0;
- var f, lastF = 4000;
- var extrude = false, relativeE = false, retract = 0;
+ var prevX = 0,
+ prevY = 0,
+ prevZ = 0;
+ var f,
+ lastF = 4000;
+ var extrude = false,
+ relativeE = false,
+ retract = 0;
var relativeMode = false;
var zLift = false;
var zLiftZ = undefined;
@@ -339,8 +384,8 @@ var doParse = function () {
args = line.split(/\s/);
for (j = 0; j < args.length; j++) {
- switch (argChar = args[j].charAt(0).toLowerCase()) {
- case 'x':
+ switch ((argChar = args[j].charAt(0).toLowerCase())) {
+ case "x":
if (relativeMode) {
x = prevX + Number(args[j].slice(1)) + activeToolOffset.x;
} else {
@@ -349,7 +394,7 @@ var doParse = function () {
break;
- case 'y':
+ case "y":
if (relativeMode) {
y = prevY + Number(args[j].slice(1)) + activeToolOffset.y;
} else {
@@ -358,7 +403,7 @@ var doParse = function () {
break;
- case 'z':
+ case "z":
if (relativeMode) {
z = prevZ + Number(args[j].slice(1));
} else {
@@ -367,10 +412,10 @@ var doParse = function () {
break;
- case 'e':
- case 'a':
- case 'b':
- case 'c':
+ case "e":
+ case "a":
+ case "b":
+ case "c":
assumeNonDC = true;
numSlice = Number(args[j].slice(1));
@@ -379,7 +424,8 @@ var doParse = function () {
prev_extrude[tool][argChar] += numSlice;
} else {
// absolute extrusion positioning
- prev_extrude[tool]["abs"] = numSlice - prev_extrude[tool][argChar];
+ prev_extrude[tool]["abs"] =
+ numSlice - prev_extrude[tool][argChar];
prev_extrude[tool][argChar] = numSlice;
}
@@ -389,7 +435,10 @@ var doParse = function () {
retract = -1;
} else if (prev_extrude[tool]["abs"] === 0) {
retract = 0;
- } else if (prev_extrude[tool]["abs"] > 0 && prev_retract[tool] < 0) {
+ } else if (
+ prev_extrude[tool]["abs"] > 0 &&
+ prev_retract[tool] < 0
+ ) {
prev_retract[tool] = 0;
retract = 1;
} else {
@@ -398,31 +447,36 @@ var doParse = function () {
break;
- case 'f':
+ case "f":
numSlice = parseFloat(args[j].slice(1));
lastF = numSlice;
break;
- case 'i':
+ case "i":
center_i = Number(args[j].slice(1));
break;
- case 'j':
+ case "j":
center_j = Number(args[j].slice(1));
break;
- case 'g':
- if(args[j].charAt(1).toLowerCase() === '2')
- direction=-1;
- if(args[j].charAt(1).toLowerCase() === '3')
- direction=1;
+ case "g":
+ if (args[j].charAt(1).toLowerCase() === "2") direction = -1;
+ if (args[j].charAt(1).toLowerCase() === "3") direction = 1;
break;
}
}
if (dcExtrude && !assumeNonDC) {
extrude = true;
- prev_extrude[tool]["abs"] = Math.sqrt((prevX - x) * (prevX - x) + (prevY - y) * (prevY - y));
+ prev_extrude[tool]["abs"] = Math.sqrt(
+ (prevX - x) * (prevX - x) + (prevY - y) * (prevY - y)
+ );
}
- if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined' || retract !== 0) {
+ if (
+ typeof x !== "undefined" ||
+ typeof y !== "undefined" ||
+ typeof z !== "undefined" ||
+ retract !== 0
+ ) {
addToModel = true;
move = true;
}
@@ -460,24 +514,24 @@ var doParse = function () {
prev_extrude[tool]["b"] = 0;
prev_extrude[tool]["c"] = 0;
} else {
- switch (argChar = args[j].charAt(0).toLowerCase()) {
- case 'x':
+ switch ((argChar = args[j].charAt(0).toLowerCase())) {
+ case "x":
x = Number(args[j].slice(1)) + activeToolOffset.x;
break;
- case 'y':
+ case "y":
y = Number(args[j].slice(1)) + activeToolOffset.y;
break;
- case 'z':
+ case "z":
z = Number(args[j].slice(1));
prevZ = z;
break;
- case 'e':
- case 'a':
- case 'b':
- case 'c':
+ case "e":
+ case "a":
+ case "b":
+ case "c":
numSlice = Number(args[j].slice(1));
if (relativeMode || relativeE) {
prev_extrude[tool][argChar] = numSlice;
@@ -489,11 +543,14 @@ var doParse = function () {
}
}
- if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined') {
+ if (
+ typeof x !== "undefined" ||
+ typeof y !== "undefined" ||
+ typeof z !== "undefined"
+ ) {
addToModel = true;
move = false;
}
-
} else if (/^(?:G28)(\.\d+)?/i.test(line)) {
args = line.split(/\s/);
@@ -504,14 +561,14 @@ var doParse = function () {
z = 0;
} else {
for (j = 0; j < args.length; j++) {
- switch (argChar = args[j].charAt(0).toLowerCase()) {
- case 'x':
+ switch ((argChar = args[j].charAt(0).toLowerCase())) {
+ case "x":
x = 0;
break;
- case 'y':
+ case "y":
y = 0;
break;
- case 'z':
+ case "z":
z = 0;
break;
default:
@@ -521,17 +578,23 @@ var doParse = function () {
}
// if it's the first layer and G28 was without z
- if (layer === 0 && typeof(z) === 'undefined') {
+ if (layer === 0 && typeof z === "undefined") {
z = 0;
}
- if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined' || retract !== 0) {
+ if (
+ typeof x !== "undefined" ||
+ typeof y !== "undefined" ||
+ typeof z !== "undefined" ||
+ retract !== 0
+ ) {
addToModel = true;
move = true;
}
} else if (/^(?:T\d+)/i.test(line)) {
tool = Number(line.split(/\s/)[0].slice(1));
- if (!prev_extrude[tool]) prev_extrude[tool] = {a: 0, b: 0, c: 0, e: 0, abs: 0};
+ if (!prev_extrude[tool])
+ prev_extrude[tool] = {a: 0, b: 0, c: 0, e: 0, abs: 0};
if (!prev_retract[tool]) prev_retract[tool] = 0;
activeToolOffset = toolOffsets[tool];
@@ -540,7 +603,7 @@ var doParse = function () {
// If move is on a new height and it's not extruding and
// it's not currently already in a Z-lift, assume it's possibly a Z-lift
- if (typeof(z) !== 'undefined' && z !== prevZ && !extrude && !zLift) {
+ if (typeof z !== "undefined" && z !== prevZ && !extrude && !zLift) {
zLift = true;
zLiftZ = prevZ;
}
@@ -549,7 +612,7 @@ var doParse = function () {
zLift = false;
}
- if (typeof(z) !== 'undefined' && z !== prevZ) {
+ if (typeof z !== "undefined" && z !== prevZ) {
if (z_heights[z] !== undefined) {
layer = z_heights[z];
} else {
@@ -560,7 +623,7 @@ var doParse = function () {
sendLayer = layer;
sendLayerZ = z;
prevZ = z;
- } else if (typeof(z) === 'undefined' && typeof(prevZ) !== 'undefined') {
+ } else if (typeof z === "undefined" && typeof prevZ !== "undefined") {
if (z_heights.hasOwnProperty(prevZ)) {
layer = z_heights[prevZ];
} else {
@@ -581,7 +644,10 @@ var doParse = function () {
extrude: extrude,
retract: retract,
noMove: !move,
- extrusion: (extrude || retract) && prev_extrude[tool]["abs"] ? prev_extrude[tool]["abs"] : 0,
+ extrusion:
+ (extrude || retract) && prev_extrude[tool]["abs"]
+ ? prev_extrude[tool]["abs"]
+ : 0,
prevX: prevX,
prevY: prevY,
prevZ: prevZ,
@@ -601,7 +667,10 @@ var doParse = function () {
// there's something to be checked in the Z-lift cache
if (prevZ === zLiftZ) {
zLiftMoves.forEach(function (zLiftMove) {
- model[zLiftMove.layer].splice(model[layer].indexOf(zLiftMove.command), 1);
+ model[zLiftMove.layer].splice(
+ model[layer].indexOf(zLiftMove.command),
+ 1
+ );
model[z_heights[zLiftZ]].push(zLiftMove.command);
});
}
@@ -610,19 +679,22 @@ var doParse = function () {
zLiftZ = undefined;
}
-
model[layer].push(command);
}
if (move) {
- if (typeof(x) !== 'undefined') prevX = x;
- if (typeof(y) !== 'undefined') prevY = y;
+ if (typeof x !== "undefined") prevX = x;
+ if (typeof y !== "undefined") prevY = y;
}
- if (typeof(sendLayer) !== "undefined") {
+ if (typeof sendLayer !== "undefined") {
if (i - lastSend > gcode.length * 0.02 && sendMultiLayer.length !== 0) {
lastSend = i;
- sendMultiLayerToParent(sendMultiLayer, sendMultiLayerZ, i / gcode.length * 100);
+ sendMultiLayerToParent(
+ sendMultiLayer,
+ sendMultiLayerZ,
+ (i / gcode.length) * 100
+ );
sendMultiLayer = [];
sendMultiLayerZ = [];
}
@@ -632,10 +704,9 @@ var doParse = function () {
sendLayerZ = undefined;
}
}
- sendMultiLayerToParent(sendMultiLayer, sendMultiLayerZ, i / gcode.length * 100);
+ sendMultiLayerToParent(sendMultiLayer, sendMultiLayerZ, (i / gcode.length) * 100);
};
-
var parseGCode = function (message) {
gcode = message.gcode;
firstReport = message.options.firstReport;
@@ -648,8 +719,8 @@ var parseGCode = function (message) {
doParse();
gcode = [];
self.postMessage({
- "cmd": "returnModel",
- "msg": {}
+ cmd: "returnModel",
+ msg: {}
});
};
@@ -664,7 +735,14 @@ var runAnalyze = function (message) {
max = {x: undefined, y: undefined, z: undefined};
min = {x: undefined, y: undefined, z: undefined};
modelSize = {x: undefined, y: undefined, z: undefined};
- boundingBox = {minX: undefined, maxX: undefined, minY: undefined, maxY: undefined, minZ: undefined, maxZ: undefined};
+ boundingBox = {
+ minX: undefined,
+ maxX: undefined,
+ minY: undefined,
+ maxY: undefined,
+ minZ: undefined,
+ maxZ: undefined
+ };
filamentByLayer = {};
totalFilament = 0;
printTime = 0;
@@ -686,18 +764,17 @@ onmessage = function (e) {
var data = e.data;
// for some reason firefox doesn't garbage collect when something inside closures is deleted, so we delete and recreate whole object eaech time
switch (data.cmd) {
- case 'parseGCode':
+ case "parseGCode":
parseGCode(data.msg);
break;
- case 'setOption':
+ case "setOption":
setOption(data.msg);
break;
- case 'analyzeModel':
+ case "analyzeModel":
runAnalyze(data.msg);
break;
default:
- self.postMessage('Unknown command: ' + data.msg);
+ self.postMessage("Unknown command: " + data.msg);
}
-
};
diff --git a/src/octoprint/plugins/gcodeviewer/static/less/gcodeviewer.less b/src/octoprint/plugins/gcodeviewer/static/less/gcodeviewer.less
index 044cb5cce..fee4ed379 100644
--- a/src/octoprint/plugins/gcodeviewer/static/less/gcodeviewer.less
+++ b/src/octoprint/plugins/gcodeviewer/static/less/gcodeviewer.less
@@ -6,15 +6,16 @@
.bar {
-webkit-transition: width 0s linear;
- -moz-transition: width 0s linear;
- -o-transition: width 0s linear;
- transition: width 0s linear;
+ -moz-transition: width 0s linear;
+ -o-transition: width 0s linear;
+ transition: width 0s linear;
}
}
.canvas_container {
position: relative;
- &:hover, &:active {
+ &:hover,
+ &:active {
outline: 0;
}
}
diff --git a/src/octoprint/plugins/logging/__init__.py b/src/octoprint/plugins/logging/__init__.py
index df8367410..703d5c8a3 100644
--- a/src/octoprint/plugins/logging/__init__.py
+++ b/src/octoprint/plugins/logging/__init__.py
@@ -1,243 +1,284 @@
# -*- 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
-from octoprint.settings import settings
-
-from octoprint.server import NO_CONTENT
-from octoprint.server.util.flask import redirect_to_tornado, no_firstrun_access
-from octoprint.access import ADMIN_GROUP
-from octoprint.access.permissions import Permissions
-
-from flask import request, jsonify, url_for, make_response
-from flask_babel import gettext
-
-from werkzeug.utils import secure_filename
-from werkzeug.exceptions import BadRequest
-import yaml
-
import io
import os
+import yaml
+from flask import jsonify, make_response, request, url_for
+from flask_babel import gettext
+from werkzeug.exceptions import BadRequest
+from werkzeug.utils import secure_filename
+
+import octoprint.plugin
+from octoprint.access import ADMIN_GROUP
+from octoprint.access.permissions import Permissions
+from octoprint.server import NO_CONTENT
+from octoprint.server.util.flask import no_firstrun_access, redirect_to_tornado
+from octoprint.settings import settings
+
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 "application/json" not 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/logging/static/clientjs/logging.js b/src/octoprint/plugins/logging/static/clientjs/logging.js
index 23b90f85d..bccbfc216 100644
--- a/src/octoprint/plugins/logging/static/clientjs/logging.js
+++ b/src/octoprint/plugins/logging/static/clientjs/logging.js
@@ -4,9 +4,8 @@
} else {
factory(global.OctoPrintClient);
}
-})(this, function(OctoPrintClient) {
-
- var OctoPrintLoggingClient = function(base) {
+})(this, function (OctoPrintClient) {
+ var OctoPrintLoggingClient = function (base) {
this.base = base;
this.baseUrl = this.base.getBlueprintUrl("logging");
@@ -14,47 +13,53 @@
this.setupUrl = this.baseUrl + "setup";
};
- OctoPrintLoggingClient.prototype.get = function(opts) {
+ OctoPrintLoggingClient.prototype.get = function (opts) {
return this.base.get(this.baseUrl, opts);
};
- OctoPrintLoggingClient.prototype.listLogs = function(opts) {
+ OctoPrintLoggingClient.prototype.listLogs = function (opts) {
return this.base.get(this.logsUrl, opts);
};
- OctoPrintLoggingClient.prototype.deleteLog = function(file, opts) {
+ OctoPrintLoggingClient.prototype.deleteLog = function (file, opts) {
var fileUrl = this.logsUrl + "/" + file;
return this.base.delete(fileUrl, opts);
};
- OctoPrintLoggingClient.prototype.downloadLog = function(file, opts) {
+ OctoPrintLoggingClient.prototype.downloadLog = function (file, opts) {
var fileUrl = this.logsUrl + "/" + file;
return this.base.download(fileUrl, opts);
};
- OctoPrintLoggingClient.prototype.updateLevels = function(config, opts) {
+ OctoPrintLoggingClient.prototype.updateLevels = function (config, opts) {
return this.base.putJson(this.setupUrl + "/levels", config, opts);
};
//~~ wrapper for backwards compatibility
- var DeprecatedOctoPrintLogsClient = function(base) {
+ var DeprecatedOctoPrintLogsClient = function (base) {
this.base = base;
this.wrapped = this.base.plugins.logging;
};
- DeprecatedOctoPrintLogsClient.prototype.list = function(opts) {
- log.warn("OctoPrintClient.logs.list has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.listLogs instead");
+ DeprecatedOctoPrintLogsClient.prototype.list = function (opts) {
+ log.warn(
+ "OctoPrintClient.logs.list has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.listLogs instead"
+ );
return this.wrapped.listLogs(opts);
};
- DeprecatedOctoPrintLogsClient.prototype.delete = function(file, opts) {
- log.warn("OctoPrintClient.logs.delete has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.deleteLog instead");
+ DeprecatedOctoPrintLogsClient.prototype.delete = function (file, opts) {
+ log.warn(
+ "OctoPrintClient.logs.delete has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.deleteLog instead"
+ );
return this.wrapped.deleteLog(file, opts);
};
- DeprecatedOctoPrintLogsClient.prototype.download = function(file, opts) {
- log.warn("OctoPrintClient.logs.download has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.downloadLog instead");
+ DeprecatedOctoPrintLogsClient.prototype.download = function (file, opts) {
+ log.warn(
+ "OctoPrintClient.logs.download has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.downloadLog instead"
+ );
return this.wrapped.downloadLog(file, opts);
};
diff --git a/src/octoprint/plugins/logging/static/js/logging.js b/src/octoprint/plugins/logging/static/js/logging.js
index 910b6c1d5..a2ef0bd21 100644
--- a/src/octoprint/plugins/logging/static/js/logging.js
+++ b/src/octoprint/plugins/logging/static/js/logging.js
@@ -1,4 +1,4 @@
-$(function() {
+$(function () {
function LoggingViewModel(parameters) {
var self = this;
@@ -17,11 +17,11 @@ $(function() {
self.markedForDeletion = ko.observableArray([]);
- self.availableLoggersSorted = ko.computed(function() {
+ self.availableLoggersSorted = ko.computed(function () {
return _.sortBy(self.availableLoggers());
});
- self.configuredLoggersSorted = ko.computed(function() {
+ self.configuredLoggersSorted = ko.computed(function () {
return _.sortBy(self.configuredLoggers(), function (o) {
o.level();
return o.component;
@@ -32,54 +32,57 @@ $(function() {
self.listHelper = new ItemListHelper(
"logFiles",
{
- "name": function(a, b) {
+ name: function (a, b) {
// sorts ascending
- if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1;
- if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1;
+ if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase())
+ return -1;
+ if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase())
+ return 1;
return 0;
},
- "modification": function(a, b) {
+ modification: function (a, b) {
// sorts descending
if (a["date"] > b["date"]) return -1;
if (a["date"] < b["date"]) return 1;
return 0;
},
- "size": function(a, b) {
+ size: function (a, b) {
// sorts descending
if (a["size"] > b["size"]) return -1;
if (a["size"] < b["size"]) return 1;
return 0;
}
},
- {
- },
+ {},
"name",
[],
[],
CONFIG_LOGFILESPERPAGE
);
- self.requestData = function() {
- if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)) {
+ self.requestData = function () {
+ if (
+ !self.loginState.hasPermission(
+ self.access.permissions.PLUGIN_LOGGING_MANAGE
+ )
+ ) {
return;
}
- OctoPrint.plugins.logging.get()
- .done(self.fromResponse);
+ OctoPrint.plugins.logging.get().done(self.fromResponse);
};
- self.fromResponse = function(response) {
+ self.fromResponse = function (response) {
self.fromLogsResponse(response.logs);
self.fromSetupResponse(response.setup);
self.fromSerialLogResponse(response.serial_log);
self.fromPluginTimingsLogResponse(response.plugintimings_log);
};
- self.fromLogsResponse = function(response) {
+ self.fromLogsResponse = function (response) {
if (!response) return;
var files = response.files;
- if (files === undefined)
- return;
+ if (files === undefined) return;
self.listHelper.updateItems(files);
@@ -87,15 +90,15 @@ $(function() {
self.totalSpace(response.total);
};
- self.fromSetupResponse = function(response) {
+ self.fromSetupResponse = function (response) {
if (!response) return;
// levels
var levels = [];
var configuredLoggers = [];
- _.each(response.levels, function(level, logger) {
+ _.each(response.levels, function (level, logger) {
var item = {component: logger, level: ko.observable(level)};
- item.level.subscribe(function() {
+ item.level.subscribe(function () {
self.configuredLoggersHasChanged();
});
levels.push(item);
@@ -108,69 +111,92 @@ $(function() {
self.availableLoggers(availableLoggers);
};
- self.fromSerialLogResponse = function(response) {
+ self.fromSerialLogResponse = function (response) {
if (!response) return;
self.serialLogEnabled(response.enabled);
};
- self.fromPluginTimingsLogResponse = function(response) {
+ self.fromPluginTimingsLogResponse = function (response) {
if (!response) return;
self.pluginTimingsLogEnabled(response.enabled);
};
- self.serialLogPopoverContent = function() {
+ self.serialLogPopoverContent = function () {
return self.popoverContent("serial.log");
};
- self.pluginTimingsLogPopoverContent = function() {
+ self.pluginTimingsLogPopoverContent = function () {
return self.popoverContent("plugintimings.log");
};
- self.popoverContent = function(logfile) {
+ self.popoverContent = function (logfile) {
var free = self.freeSpace();
var total = self.totalSpace();
- var content = "
"
- + _.sprintf(gettext("You currently have %(logfile)s enabled. Please remember to turn it off " +
- "again once your are done debugging whatever issue prompted you to turn it on."), {logfile: logfile})
- + "
"
- + gettext("It can negatively impact print performance and also take up a lot of storage space " +
- "depending on how long you keep it enabled and thus should only be used for " +
- "debugging.")
- + "
";
+ var content =
+ "
" +
+ _.sprintf(
+ gettext(
+ "You currently have %(logfile)s enabled. Please remember to turn it off " +
+ "again once your are done debugging whatever issue prompted you to turn it on."
+ ),
+ {logfile: logfile}
+ ) +
+ "
" +
+ gettext(
+ "It can negatively impact print performance and also take up a lot of storage space " +
+ "depending on how long you keep it enabled and thus should only be used for " +
+ "debugging."
+ ) +
+ "
";
if (free !== undefined && total !== undefined) {
- content += "
- " + gettext("Undervoltage. Make sure your power supply and cabling are providing enough power to the Pi.") + "
"
- + "
- " + gettext("Frequency capping due to overheating. Improve cooling of the CPU and GPU.") + "
"
- + "
" + gettext("A blinking symbol indicates a current issue, a non blinking symbol one that was observed some time since the Pi booted up.") + "
"
- + "
" + gettext("Click the symbol in the navbar for more information.") + "
";
+ return (
+ "
- ' +
+ gettext(
+ "Undervoltage. Make sure your power supply and cabling are providing enough power to the Pi."
+ ) +
+ "
" +
+ "
- ' +
+ gettext(
+ "Frequency capping due to overheating. Improve cooling of the CPU and GPU."
+ ) +
+ "
" +
+ "
" +
+ gettext(
+ "A blinking symbol indicates a current issue, a non blinking symbol one that was observed some time since the Pi booted up."
+ ) +
+ "
" +
+ "
" +
+ gettext("Click the symbol in the navbar for more information.") +
+ "
"
+ );
});
- self.onStartup = self.onServerReconnect = self.onUserLoggedIn = self.onUserLoggedOut = function() {
+ self.onStartup = self.onServerReconnect = self.onUserLoggedIn = self.onUserLoggedOut = function () {
self.requestData();
};
- self.onDataUpdaterPluginMessage = function(plugin, data) {
+ self.onDataUpdaterPluginMessage = function (plugin, data) {
if (plugin !== "pi_support") return;
if (!data.hasOwnProperty("state") || !data.hasOwnProperty("type")) return;
if (data.type !== "throttle_state") return;
- if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PI_SUPPORT_STATUS)) return;
+ if (
+ !self.loginState.hasPermission(
+ self.access.permissions.PLUGIN_PI_SUPPORT_STATUS
+ )
+ )
+ return;
self.fromThrottleState(data.state);
- }
+ };
}
OCTOPRINT_VIEWMODELS.push({
diff --git a/src/octoprint/plugins/pi_support/templates/pi_support_about_octopi.jinja2 b/src/octoprint/plugins/pi_support/templates/pi_support_about_octopi.jinja2
index b3a43aaaa..5dcba4b65 100644
--- a/src/octoprint/plugins/pi_support/templates/pi_support_about_octopi.jinja2
+++ b/src/octoprint/plugins/pi_support/templates/pi_support_about_octopi.jinja2
@@ -29,4 +29,3 @@
For a copy of the GNU General Public License, see
www.gnu.org/licenses/gpl-3.0.en.html.
-
diff --git a/src/octoprint/plugins/pi_support/templates/pi_support_settings.jinja2 b/src/octoprint/plugins/pi_support/templates/pi_support_settings.jinja2
index a9e879380..a8abffcc0 100644
--- a/src/octoprint/plugins/pi_support/templates/pi_support_settings.jinja2
+++ b/src/octoprint/plugins/pi_support/templates/pi_support_settings.jinja2
@@ -27,5 +27,3 @@
-
-
diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py
index 2054a854f..3210be7a7 100644
--- a/src/octoprint/plugins/pluginmanager/__init__.py
+++ b/src/octoprint/plugins/pluginmanager/__init__.py
@@ -2,82 +2,102 @@
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 copy
+import io
+import logging
+import os
+import re
+import shutil
+import sys
+import tempfile
+import threading
+import time
+from datetime import datetime
+
+import filetype
+import pkg_resources
+import requests
+import sarge
+from flask import jsonify, make_response
+from flask_babel import gettext
from past.builtins import basestring
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.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.platform import get_os, is_os_compatible
-from octoprint.util.net import download_file
from octoprint.events import Events
-
-from flask import jsonify, make_response
-from flask_babel import gettext
-
-import io
-import logging
-import sarge
-import sys
-import requests
-import re
-import os
-import copy
-import time
-import threading
-import tempfile
-import shutil
-import filetype
-import pkg_resources
-
-from datetime import datetime
+from octoprint.server.util.flask import (
+ check_etag,
+ no_firstrun_access,
+ with_revalidation_checking,
+)
+from octoprint.settings import valid_boolean_trues
+from octoprint.util import TemporaryDirectory, to_bytes, to_native_str
+from octoprint.util.net import download_file
+from octoprint.util.pip import LocalPipCaller
+from octoprint.util.platform import get_os, is_os_compatible
+from octoprint.util.version import (
+ get_octoprint_version,
+ get_octoprint_version_string,
+ is_octoprint_compatible,
+ is_python_compatible,
+)
try:
- from os import scandir
-except:
- from scandir import scandir
+ from os import scandir
+except ImportError:
+ 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 "follow_dependency_links" not 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 +105,1773 @@ 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 plugin_name not 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 plugin_name not 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 Exception:
+ 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 plugin.key not 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):
+ 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):
+ 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 "plugin" not in notice or "text" not in notice or "date" not 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 key not 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 +1882,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/pluginmanager/static/clientjs/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/clientjs/pluginmanager.js
index 4d2c02abc..2197e0d45 100644
--- a/src/octoprint/plugins/pluginmanager/static/clientjs/pluginmanager.js
+++ b/src/octoprint/plugins/pluginmanager/static/clientjs/pluginmanager.js
@@ -4,12 +4,12 @@
} else {
factory(global.OctoPrintClient);
}
-})(this, function(OctoPrintClient) {
- var OctoPrintPluginManagerClient = function(base) {
+})(this, function (OctoPrintClient) {
+ var OctoPrintPluginManagerClient = function (base) {
this.base = base;
};
- OctoPrintPluginManagerClient.prototype.get = function(refresh, opts) {
+ OctoPrintPluginManagerClient.prototype.get = function (refresh, opts) {
var refresh_repo, refresh_notices, refresh_orphans;
if (_.isPlainObject(refresh)) {
refresh_repo = refresh.repo || false;
@@ -26,18 +26,26 @@
if (refresh_notices) query.push("refresh_notices=true");
if (refresh_orphans) query.push("refresh_orphans=true");
- return this.base.get(this.base.getSimpleApiUrl("pluginmanager") + ((query.length) ? "?" + query.join("&") : ""), opts);
+ return this.base.get(
+ this.base.getSimpleApiUrl("pluginmanager") +
+ (query.length ? "?" + query.join("&") : ""),
+ opts
+ );
};
- OctoPrintPluginManagerClient.prototype.getWithRefresh = function(opts) {
+ OctoPrintPluginManagerClient.prototype.getWithRefresh = function (opts) {
return this.get(true, opts);
};
- OctoPrintPluginManagerClient.prototype.getWithoutRefresh = function(opts) {
+ OctoPrintPluginManagerClient.prototype.getWithoutRefresh = function (opts) {
return this.get(false, opts);
};
- OctoPrintPluginManagerClient.prototype.install = function(pluginUrl, dependencyLinks, opts) {
+ OctoPrintPluginManagerClient.prototype.install = function (
+ pluginUrl,
+ dependencyLinks,
+ opts
+ ) {
var data = {
url: pluginUrl,
dependency_links: !!dependencyLinks
@@ -45,7 +53,12 @@
return this.base.simpleApiCommand("pluginmanager", "install", data, opts);
};
- OctoPrintPluginManagerClient.prototype.reinstall = function(plugin, pluginUrl, dependencyLinks, opts) {
+ OctoPrintPluginManagerClient.prototype.reinstall = function (
+ plugin,
+ pluginUrl,
+ dependencyLinks,
+ opts
+ ) {
var data = {
url: pluginUrl,
dependency_links: !!dependencyLinks,
@@ -55,7 +68,7 @@
return this.base.simpleApiCommand("pluginmanager", "install", data, opts);
};
- OctoPrintPluginManagerClient.prototype.uninstall = function(plugin, cleanup, opts) {
+ OctoPrintPluginManagerClient.prototype.uninstall = function (plugin, cleanup, opts) {
// backwards compatibility to former argument list (plugin, opts)
if (arguments.length === 2 && typeof cleanup === "object") {
opts = cleanup;
@@ -69,36 +82,42 @@
return this.base.simpleApiCommand("pluginmanager", "uninstall", data, opts);
};
- OctoPrintPluginManagerClient.prototype.cleanup = function(plugin, opts) {
+ OctoPrintPluginManagerClient.prototype.cleanup = function (plugin, opts) {
var data = {
plugin: plugin
};
return this.base.simpleApiCommand("pluginmanager", "cleanup", data, opts);
};
- OctoPrintPluginManagerClient.prototype.cleanupAll = function(plugin, opts) {
+ OctoPrintPluginManagerClient.prototype.cleanupAll = function (plugin, opts) {
var data = {};
return this.base.simpleApiCommand("pluginmanager", "cleanup_all", data, opts);
};
- OctoPrintPluginManagerClient.prototype.enable = function(plugin, opts) {
+ OctoPrintPluginManagerClient.prototype.enable = function (plugin, opts) {
var data = {
plugin: plugin
};
return this.base.simpleApiCommand("pluginmanager", "enable", data, opts);
};
- OctoPrintPluginManagerClient.prototype.disable = function(plugin, opts) {
+ OctoPrintPluginManagerClient.prototype.disable = function (plugin, opts) {
var data = {
plugin: plugin
};
return this.base.simpleApiCommand("pluginmanager", "disable", data, opts);
};
- OctoPrintPluginManagerClient.prototype.upload = function(file) {
- return this.base.upload(this.base.getBlueprintUrl("pluginmanager") + "upload_archive", file);
+ OctoPrintPluginManagerClient.prototype.upload = function (file) {
+ return this.base.upload(
+ this.base.getBlueprintUrl("pluginmanager") + "upload_archive",
+ file
+ );
};
- OctoPrintClient.registerPluginComponent("pluginmanager", OctoPrintPluginManagerClient);
+ OctoPrintClient.registerPluginComponent(
+ "pluginmanager",
+ OctoPrintPluginManagerClient
+ );
return OctoPrintPluginManagerClient;
});
diff --git a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js
index 3b27a9409..5b5bd9552 100644
--- a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js
+++ b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js
@@ -1,4 +1,4 @@
-$(function() {
+$(function () {
function PluginManagerViewModel(parameters) {
var self = this;
@@ -20,84 +20,103 @@ $(function() {
self.config_confirmUninstall = ko.observable();
self.config_confirmDisable = ko.observable();
- self.configurationDialog = $("#settings_plugin_pluginmanager_configurationdialog");
+ self.configurationDialog = $(
+ "#settings_plugin_pluginmanager_configurationdialog"
+ );
self.plugins = new ItemListHelper(
"plugin.pluginmanager.installedplugins",
{
- "name": function (a, b) {
+ name: function (a, b) {
// sorts ascending
- if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1;
- if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1;
+ if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase())
+ return -1;
+ if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase())
+ return 1;
return 0;
}
},
{
- "bundled": function(item) {
+ "bundled": function (item) {
return item.bundled;
},
- "3rdparty": function(item) {
+ "3rdparty": function (item) {
return !item.bundled;
},
- "enabled": function(item) {
+ "enabled": function (item) {
return item.enabled;
},
- "disabled": function(item) {
+ "disabled": function (item) {
return !item.enabled;
}
},
"name",
[],
- [["bundled", "3rdparty"], ["enabled", "disabled"]],
+ [
+ ["bundled", "3rdparty"],
+ ["enabled", "disabled"]
+ ],
0
);
self.repositoryplugins = new ItemListHelper(
"plugin.pluginmanager.repositoryplugins",
{
- "title": function (a, b) {
+ title: function (a, b) {
// sorts ascending
- if (a.title.toLocaleLowerCase() < b.title.toLocaleLowerCase()) return -1;
- if (a.title.toLocaleLowerCase() > b.title.toLocaleLowerCase()) return 1;
+ if (a.title.toLocaleLowerCase() < b.title.toLocaleLowerCase())
+ return -1;
+ if (a.title.toLocaleLowerCase() > b.title.toLocaleLowerCase())
+ return 1;
return 0;
},
- "published": function (a, b) {
+ published: function (a, b) {
// sorts descending
- if (a.published.toLocaleLowerCase() > b.published.toLocaleLowerCase()) return -1;
- if (a.published.toLocaleLowerCase() < b.published.toLocaleLowerCase()) return 1;
+ if (a.published.toLocaleLowerCase() > b.published.toLocaleLowerCase())
+ return -1;
+ if (a.published.toLocaleLowerCase() < b.published.toLocaleLowerCase())
+ return 1;
return 0;
},
- "popularity": function (a, b) {
+ popularity: function (a, b) {
// sorts descending
- var countA = (a.stats && a.stats.instances_month) ? a.stats.instances_month : 0;
- var countB = (b.stats && b.stats.instances_month) ? b.stats.instances_month : 0;
+ var countA =
+ a.stats && a.stats.instances_month ? a.stats.instances_month : 0;
+ var countB =
+ b.stats && b.stats.instances_month ? b.stats.instances_month : 0;
if (countA > countB) return -1;
if (countA < countB) return 1;
return 0;
},
- "release_date": function (a, b) {
+ release_date: function (a, b) {
// sorts descending
- var valA = (a.github && a.github.latest_release) ? a.github.latest_release.date.toLocaleLowerCase() : "";
- var valB = (b.github && b.github.latest_release) ? b.github.latest_release.date.toLocaleLowerCase() : "";
+ var valA =
+ a.github && a.github.latest_release
+ ? a.github.latest_release.date.toLocaleLowerCase()
+ : "";
+ var valB =
+ b.github && b.github.latest_release
+ ? b.github.latest_release.date.toLocaleLowerCase()
+ : "";
if (valA > valB) return -1;
if (valA < valB) return 1;
return 0;
},
- "push_date": function (a, b) {
+ push_date: function (a, b) {
// sorts descending
- var valA = (a.github) ? a.github.last_push.toLocaleLowerCase() : "";
- var valB = (b.github) ? b.github.last_push.toLocaleLowerCase() : "";
+ var valA = a.github ? a.github.last_push.toLocaleLowerCase() : "";
+ var valB = b.github ? b.github.last_push.toLocaleLowerCase() : "";
if (valA > valB) return -1;
if (valA < valB) return 1;
return 0;
},
- "stars": function (a, b) {
+ stars: function (a, b) {
// sorts descending
- var valA = (a.github) ? a.github.stars : 0;
- var valB = (b.github) ? b.github.stars : 0;
+ var valA = a.github ? a.github.stars : 0;
+ var valB = b.github ? b.github.stars : 0;
if (valA > valB) return -1;
if (valA < valB) return 1;
@@ -105,13 +124,17 @@ $(function() {
}
},
{
- "filter_installed": function(plugin) {
+ filter_installed: function (plugin) {
return !self.installed(plugin);
},
- "filter_incompatible": function(plugin) {
- return plugin.is_compatible.octoprint && plugin.is_compatible.os && plugin.is_compatible.python;
+ filter_incompatible: function (plugin) {
+ return (
+ plugin.is_compatible.octoprint &&
+ plugin.is_compatible.os &&
+ plugin.is_compatible.python
+ );
},
- "filter_abandoned": function(plugin) {
+ filter_abandoned: function (plugin) {
return !plugin.abandoned;
}
},
@@ -124,10 +147,18 @@ $(function() {
self.orphans = new ItemListHelper(
"plugin.pluginmanager.orphans",
{
- "identifier": function (a, b) {
+ identifier: function (a, b) {
// sorts ascending
- if (a["identifier"].toLocaleLowerCase() < b["identifier"].toLocaleLowerCase()) return -1;
- if (a["identifier"].toLocaleLowerCase() > b["identifier"].toLocaleLowerCase()) return 1;
+ if (
+ a["identifier"].toLocaleLowerCase() <
+ b["identifier"].toLocaleLowerCase()
+ )
+ return -1;
+ if (
+ a["identifier"].toLocaleLowerCase() >
+ b["identifier"].toLocaleLowerCase()
+ )
+ return 1;
return 0;
}
},
@@ -139,17 +170,19 @@ $(function() {
);
self.uploadElement = $("#settings_plugin_pluginmanager_repositorydialog_upload");
- self.uploadButton = $("#settings_plugin_pluginmanager_repositorydialog_upload_start");
+ self.uploadButton = $(
+ "#settings_plugin_pluginmanager_repositorydialog_upload_start"
+ );
self.repositoryAvailable = ko.observable(false);
self.repositorySearchQuery = ko.observable();
- self.repositorySearchQuery.subscribe(function() {
+ self.repositorySearchQuery.subscribe(function () {
self.performRepositorySearch();
});
self.listingSearchQuery = ko.observable();
- self.listingSearchQuery.subscribe(function() {
+ self.listingSearchQuery.subscribe(function () {
self.performListingSearch();
});
@@ -174,10 +207,10 @@ $(function() {
self.requestError = ko.observable(false);
- self.pipUseUserString = ko.pureComputed(function() {
+ self.pipUseUserString = ko.pureComputed(function () {
return self.pipUseUser() ? "yes" : "no";
});
- self.pipVirtualEnvString = ko.pureComputed(function() {
+ self.pipVirtualEnvString = ko.pureComputed(function () {
return self.pipVirtualEnv() ? "yes" : "no";
});
@@ -189,15 +222,20 @@ $(function() {
self.toggling = ko.observable(false);
self.restartCommandSpec = undefined;
- self.systemViewModel.systemActions.subscribe(function() {
+ self.systemViewModel.systemActions.subscribe(function () {
var lastResponse = self.systemViewModel.lastCommandResponse;
if (!lastResponse || !lastResponse.core) {
self.restartCommandSpec = undefined;
return;
}
- var restartSpec = _.filter(lastResponse.core, function(spec) { return spec.action == "restart" });
- self.restartCommandSpec = restartSpec != undefined && restartSpec.length > 0 ? restartSpec[0] : undefined;
+ var restartSpec = _.filter(lastResponse.core, function (spec) {
+ return spec.action == "restart";
+ });
+ self.restartCommandSpec =
+ restartSpec != undefined && restartSpec.length > 0
+ ? restartSpec[0]
+ : undefined;
});
self.noticeNotifications = [];
@@ -214,113 +252,168 @@ $(function() {
}
};
- self.noticeCountText = ko.pureComputed(function() {
+ self.noticeCountText = ko.pureComputed(function () {
var count = self.noticeCount();
if (count === 0) {
return gettext("There are no plugin notices. Great!");
} else if (count === 1) {
- return gettext("There is a plugin notice for one of your installed plugins.");
+ return gettext(
+ "There is a plugin notice for one of your installed plugins."
+ );
} else {
- return _.sprintf(gettext("There are %(count)d plugin notices for one or more of your installed plugins."), {count: count});
+ return _.sprintf(
+ gettext(
+ "There are %(count)d plugin notices for one or more of your installed plugins."
+ ),
+ {count: count}
+ );
}
});
- self.enableManagement = ko.pureComputed(function() {
+ self.enableManagement = ko.pureComputed(function () {
return !self.printerState.isBusy();
});
- self.enableToggle = function(data) {
+ self.enableToggle = function (data) {
var command = self._getToggleCommand(data);
var not_safemode_victim = !data.safe_mode_victim;
var not_blacklisted = !data.blacklisted;
var not_incompatible = !data.incompatible;
- return self.enableManagement() && !self.toggling() && (command === "disable" || (not_safemode_victim && not_blacklisted && not_incompatible)) && data.key !== 'pluginmanager';
+ return (
+ self.enableManagement() &&
+ !self.toggling() &&
+ (command === "disable" ||
+ (not_safemode_victim && not_blacklisted && not_incompatible)) &&
+ data.key !== "pluginmanager"
+ );
};
- self.enableUninstall = function(data) {
- return self.enableManagement()
- && (data.origin !== "entry_point" || self.pipAvailable())
- && data.managable
- && !data.bundled
- && data.key !== 'pluginmanager'
- && !data.pending_uninstall;
+ self.enableUninstall = function (data) {
+ return (
+ self.enableManagement() &&
+ (data.origin !== "entry_point" || self.pipAvailable()) &&
+ data.managable &&
+ !data.bundled &&
+ data.key !== "pluginmanager" &&
+ !data.pending_uninstall
+ );
};
- self.enableCleanup = function(data) {
- return self.enableManagement()
- && data.key !== 'pluginmanager'
- && !data.pending_uninstall;
+ self.enableCleanup = function (data) {
+ return (
+ self.enableManagement() &&
+ data.key !== "pluginmanager" &&
+ !data.pending_uninstall
+ );
};
- self.enableRepoInstall = function(data) {
- return self.enableManagement() && self.pipAvailable() && !self.safeMode() && !self.throttled() && self.online() && self.isCompatible(data);
+ self.enableRepoInstall = function (data) {
+ return (
+ self.enableManagement() &&
+ self.pipAvailable() &&
+ !self.safeMode() &&
+ !self.throttled() &&
+ self.online() &&
+ self.isCompatible(data)
+ );
};
- self.throttled = ko.pureComputed(function() {
- return self.piSupport && self.piSupport.currentIssue() && !self.settingsViewModel.settings.plugins.pluginmanager.ignore_throttled();
+ self.throttled = ko.pureComputed(function () {
+ return (
+ self.piSupport &&
+ self.piSupport.currentIssue() &&
+ !self.settingsViewModel.settings.plugins.pluginmanager.ignore_throttled()
+ );
});
- self.invalidUrl = ko.pureComputed(function() {
+ self.invalidUrl = ko.pureComputed(function () {
// supported pip install URL schemes, according to https://pip.pypa.io/en/stable/reference/pip_install/
- var allowedUrlSchemes = ["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", "brz+ftp", "bzr+lp"];
+ var allowedUrlSchemes = [
+ "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",
+ "brz+ftp",
+ "bzr+lp"
+ ];
var url = self.installUrl();
var lowerUrl = url !== undefined ? url.toLocaleLowerCase() : undefined;
- var lowerUrlStartsWithScheme = function(scheme) {
+ var lowerUrlStartsWithScheme = function (scheme) {
return _.startsWith(lowerUrl, scheme + "://");
};
- return url !== undefined && url.trim() !== ""
- && !(_.any(allowedUrlSchemes, lowerUrlStartsWithScheme));
+ return (
+ url !== undefined &&
+ url.trim() !== "" &&
+ !_.any(allowedUrlSchemes, lowerUrlStartsWithScheme)
+ );
});
- self.enableUrlInstall = ko.pureComputed(function() {
+ self.enableUrlInstall = ko.pureComputed(function () {
var url = self.installUrl();
- return self.enableManagement()
- && self.pipAvailable()
- && !self.safeMode()
- && !self.throttled()
- && self.online()
- && url !== undefined
- && url.trim() !== ""
- && !self.invalidUrl();
+ return (
+ self.enableManagement() &&
+ self.pipAvailable() &&
+ !self.safeMode() &&
+ !self.throttled() &&
+ self.online() &&
+ url !== undefined &&
+ url.trim() !== "" &&
+ !self.invalidUrl()
+ );
});
- self.invalidFile = ko.pureComputed(function() {
+ self.invalidFile = ko.pureComputed(function () {
var allowedFileExtensions = [".zip", ".tar.gz", ".tgz", ".tar", ".py"];
var name = self.uploadFilename();
var lowerName = name !== undefined ? name.toLocaleLowerCase() : undefined;
- var lowerNameHasExtension = function(extension) {
+ var lowerNameHasExtension = function (extension) {
return _.endsWith(lowerName, extension);
};
- return name !== undefined
- && !(_.any(allowedFileExtensions, lowerNameHasExtension));
+ return (
+ name !== undefined && !_.any(allowedFileExtensions, lowerNameHasExtension)
+ );
});
- self.enableFileInstall = ko.pureComputed(function() {
+ self.enableFileInstall = ko.pureComputed(function () {
var name = self.uploadFilename();
- return self.enableManagement()
- && self.pipAvailable()
- && !self.safeMode()
- && !self.throttled()
- && name !== undefined
- && name.trim() !== ""
- && !self.invalidFile();
+ return (
+ self.enableManagement() &&
+ self.pipAvailable() &&
+ !self.safeMode() &&
+ !self.throttled() &&
+ name !== undefined &&
+ name.trim() !== "" &&
+ !self.invalidFile()
+ );
});
self.uploadElement.fileupload({
dataType: "json",
maxNumberOfFiles: 1,
autoUpload: false,
- add: function(e, data) {
+ add: function (e, data) {
if (data.files.length === 0) {
return false;
}
@@ -328,8 +421,11 @@ $(function() {
self.uploadFilename(data.files[0].name);
self.uploadButton.unbind("click");
- self.uploadButton.bind("click", function() {
- self._markWorking(gettext("Installing plugin..."), gettext("Installing plugin from uploaded archive..."));
+ self.uploadButton.bind("click", function () {
+ self._markWorking(
+ gettext("Installing plugin..."),
+ gettext("Installing plugin from uploaded archive...")
+ );
data.formData = {
dependency_links: self.followDependencyLinks()
};
@@ -337,7 +433,7 @@ $(function() {
return false;
});
},
- done: function(e, data) {
+ done: function (e, data) {
var response = data.result;
if (response.result) {
self._markDone();
@@ -348,7 +444,7 @@ $(function() {
self.uploadButton.unbind("click");
self.uploadFilename(undefined);
},
- fail: function(e, data) {
+ fail: function (e, data) {
new PNotify({
title: gettext("Something went wrong"),
text: gettext("Please consult octoprint.log for details"),
@@ -361,24 +457,34 @@ $(function() {
}
});
- self.performListingSearch = function() {
+ self.performListingSearch = function () {
var query = self.listingSearchQuery();
if (query !== undefined && query.trim() !== "") {
query = query.toLocaleLowerCase();
self.plugins.changeSearchFunction(function (entry) {
- return entry && (entry["name"].toLocaleLowerCase().indexOf(query) > -1 || (entry.description && entry.description.toLocaleLowerCase().indexOf(query) > -1));
+ return (
+ entry &&
+ (entry["name"].toLocaleLowerCase().indexOf(query) > -1 ||
+ (entry.description &&
+ entry.description.toLocaleLowerCase().indexOf(query) >
+ -1))
+ );
});
} else {
self.plugins.resetSearch();
}
};
- self.performRepositorySearch = function() {
+ self.performRepositorySearch = function () {
var query = self.repositorySearchQuery();
if (query !== undefined && query.trim() !== "") {
query = query.toLocaleLowerCase();
- self.repositoryplugins.changeSearchFunction(function(entry) {
- return entry && (entry["title"].toLocaleLowerCase().indexOf(query) > -1 || entry["description"].toLocaleLowerCase().indexOf(query) > -1);
+ self.repositoryplugins.changeSearchFunction(function (entry) {
+ return (
+ entry &&
+ (entry["title"].toLocaleLowerCase().indexOf(query) > -1 ||
+ entry["description"].toLocaleLowerCase().indexOf(query) > -1)
+ );
});
} else {
self.repositoryplugins.resetSearch();
@@ -386,7 +492,7 @@ $(function() {
return false;
};
- self.fromResponse = function(data, options) {
+ self.fromResponse = function (data, options) {
self._fromPluginsResponse(data.plugins, options);
self._fromOrphanResponse(data.orphan_data, options);
self._fromRepositoryResponse(data.repository, options);
@@ -396,7 +502,7 @@ $(function() {
self.online(data.online !== undefined ? data.online : true);
};
- self._fromPluginsResponse = function(data, options) {
+ self._fromPluginsResponse = function (data, options) {
var evalNotices = options.eval_notices || false;
var ignoreNoticeHidden = options.ignore_notice_hidden || false;
var ignoreNoticeIgnored = options.ignore_notice_ignored || false;
@@ -405,14 +511,28 @@ $(function() {
var installedPlugins = [];
var noticeCount = 0;
- _.each(data, function(plugin) {
+ _.each(data, function (plugin) {
installedPlugins.push(plugin.key);
if (evalNotices && plugin.notifications && plugin.notifications.length) {
- _.each(plugin.notifications, function(notification) {
+ _.each(plugin.notifications, function (notification) {
noticeCount++;
- if (!ignoreNoticeIgnored && self._isNoticeNotificationIgnored(plugin.key, notification.date)) return;
- if (!ignoreNoticeHidden && self._isNoticeNotificationHidden(plugin.key, notification.date)) return;
+ if (
+ !ignoreNoticeIgnored &&
+ self._isNoticeNotificationIgnored(
+ plugin.key,
+ notification.date
+ )
+ )
+ return;
+ if (
+ !ignoreNoticeHidden &&
+ self._isNoticeNotificationHidden(
+ plugin.key,
+ notification.date
+ )
+ )
+ return;
self._showPluginNotification(plugin, notification);
});
}
@@ -422,15 +542,19 @@ $(function() {
self.plugins.updateItems(data);
};
- self._fromOrphanResponse = function(data) {
+ self._fromOrphanResponse = function (data) {
var orphans = [];
- _.each(data, function(value, key) {
- orphans.push({identifier: key, settings: value.settings, data: value.data});
+ _.each(data, function (value, key) {
+ orphans.push({
+ identifier: key,
+ settings: value.settings,
+ data: value.data
+ });
});
self.orphans.updateItems(orphans);
};
- self._fromRepositoryResponse = function(data) {
+ self._fromRepositoryResponse = function (data) {
self.repositoryAvailable(data.available);
if (data.available) {
self.repositoryplugins.updateItems(data.plugins);
@@ -439,7 +563,7 @@ $(function() {
}
};
- self._fromPipResponse = function(data) {
+ self._fromPipResponse = function (data) {
self.pipAvailable(data.available);
if (data.available) {
self.pipVersion(data.version);
@@ -458,7 +582,7 @@ $(function() {
};
self.dataDeferred = undefined;
- self.requestData = function(options) {
+ self.requestData = function (options) {
if (!_.isPlainObject(options)) {
options = {
refresh_repo: options,
@@ -473,27 +597,42 @@ $(function() {
options.refresh_notices = options.refresh_notices || false;
options.eval_notices = options.eval_notices || false;
- if (self.dataDeferred && self.dataDeferred.state() === "pending"
- && !options.refresh_repo && !options.refresh_orphans
- && !options.refresh_notices && !options.eval_notices) {
+ if (
+ self.dataDeferred &&
+ self.dataDeferred.state() === "pending" &&
+ !options.refresh_repo &&
+ !options.refresh_orphans &&
+ !options.refresh_notices &&
+ !options.eval_notices
+ ) {
return self.dataDeferred.promise();
}
var deferred = new $.Deferred();
- if (!options.refresh_repo && !options.refresh_orphans && !options.refresh_notices && !options.eval_notices) {
+ if (
+ !options.refresh_repo &&
+ !options.refresh_orphans &&
+ !options.refresh_notices &&
+ !options.eval_notices
+ ) {
self.dataDeferred = deferred;
}
- if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)) {
+ if (
+ !self.loginState.hasPermission(
+ self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE
+ )
+ ) {
deferred.fail();
return deferred.promise();
}
- OctoPrint.plugins.pluginmanager.get({
- repo: options.refresh_repo,
- notices: options.refresh_notices,
- orphans: options.refresh_orphans
- })
+ OctoPrint.plugins.pluginmanager
+ .get({
+ repo: options.refresh_repo,
+ notices: options.refresh_notices,
+ orphans: options.refresh_orphans
+ })
.fail(function () {
self.requestError(true);
deferred.reject();
@@ -507,8 +646,12 @@ $(function() {
return deferred.promise();
};
- self.togglePlugin = function(data) {
- if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)) {
+ self.togglePlugin = function (data) {
+ if (
+ !self.loginState.hasPermission(
+ self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE
+ )
+ ) {
return;
}
@@ -518,48 +661,53 @@ $(function() {
if (data.key === "pluginmanager") return;
- var onSuccess = function() {
- self.requestData()
- .always(function() {
- self.toggling(false);
- });
+ var onSuccess = function () {
+ self.requestData().always(function () {
+ self.toggling(false);
+ });
},
- onError = function() {
+ onError = function () {
self.toggling(false);
new PNotify({
title: gettext("Something went wrong"),
text: gettext("Please consult octoprint.log for details"),
type: "error",
hide: false
- })
+ });
};
- var performDisabling = function() {
+ var performDisabling = function () {
if (self.toggling()) return;
self.toggling(true);
- OctoPrint.plugins.pluginmanager.disable(data.key)
+ OctoPrint.plugins.pluginmanager
+ .disable(data.key)
.done(onSuccess)
.fail(onError);
};
- var performEnabling = function() {
+ var performEnabling = function () {
if (data.safe_mode_victim) return;
if (self.toggling()) return;
self.toggling(true);
- OctoPrint.plugins.pluginmanager.enable(data.key)
+ OctoPrint.plugins.pluginmanager
+ .enable(data.key)
.done(onSuccess)
.fail(onError);
- }
+ };
if (self._getToggleCommand(data) === "enable") {
performEnabling();
} else {
// always warn if plugin is marked "disabling discouraged"
if (data.disabling_discouraged) {
- var message = _.sprintf(gettext("You are about to disable \"%(name)s\"."), {name: _.escape(data.name)})
- + "
" + data.disabling_discouraged;
+ var message =
+ _.sprintf(gettext('You are about to disable "%(name)s".'), {
+ name: _.escape(data.name)
+ }) +
+ "
" +
+ data.disabling_discouraged;
showConfirmationDialog({
title: gettext("This is not recommended"),
message: message,
@@ -570,9 +718,14 @@ $(function() {
});
}
// warn if global "warn disabling" setting is set"
- else if (self.settingsViewModel.settings.plugins.pluginmanager.confirm_disable()) {
+ else if (
+ self.settingsViewModel.settings.plugins.pluginmanager.confirm_disable()
+ ) {
showConfirmationDialog({
- message: _.sprintf(gettext("You are about to disable \"%(name)s\""), {name: _.escape(data.name)}),
+ message: _.sprintf(
+ gettext('You are about to disable "%(name)s"'),
+ {name: _.escape(data.name)}
+ ),
cancel: gettext("Keep enabled"),
proceed: gettext("Disable plugin"),
onproceed: performDisabling,
@@ -585,19 +738,25 @@ $(function() {
}
};
- self.showRepository = function() {
+ self.showRepository = function () {
self.repositoryDialog.modal({
- minHeight: function() { return Math.max($.fn.modal.defaults.maxHeight() - 80, 250); },
+ minHeight: function () {
+ return Math.max($.fn.modal.defaults.maxHeight() - 80, 250);
+ },
show: true
});
};
- self.pluginDetails = function(data) {
+ self.pluginDetails = function (data) {
window.open(data.page);
};
- self.installFromRepository = function(data) {
- if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_INSTALL)) {
+ self.installFromRepository = function (data) {
+ if (
+ !self.loginState.hasPermission(
+ self.access.permissions.PLUGIN_PLUGINMANAGER_INSTALL
+ )
+ ) {
return;
}
@@ -605,11 +764,20 @@ $(function() {
return;
}
- self.installPlugin(data.archive, data.title, (self.installed(data) ? data.id : undefined), data.follow_dependency_links || self.followDependencyLinks());
+ self.installPlugin(
+ data.archive,
+ data.title,
+ self.installed(data) ? data.id : undefined,
+ data.follow_dependency_links || self.followDependencyLinks()
+ );
};
- self.installPlugin = function(url, name, reinstall, followDependencyLinks) {
- if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_INSTALL)) {
+ self.installPlugin = function (url, name, reinstall, followDependencyLinks) {
+ if (
+ !self.loginState.hasPermission(
+ self.access.permissions.PLUGIN_PLUGINMANAGER_INSTALL
+ )
+ ) {
return;
}
@@ -634,21 +802,31 @@ $(function() {
if (!reinstall) {
workTitle = gettext("Installing plugin...");
if (name) {
- workText = _.sprintf(gettext("Installing plugin \"%(name)s\" from %(url)s..."), {url: _.escape(url), name: _.escape(name)});
+ workText = _.sprintf(
+ gettext('Installing plugin "%(name)s" from %(url)s...'),
+ {url: _.escape(url), name: _.escape(name)}
+ );
} else {
- workText = _.sprintf(gettext("Installing plugin from %(url)s..."), {url: _.escape(url)});
+ workText = _.sprintf(gettext("Installing plugin from %(url)s..."), {
+ url: _.escape(url)
+ });
}
} else {
workTitle = gettext("Reinstalling plugin...");
- workText = _.sprintf(gettext("Reinstalling plugin \"%(name)s\" from %(url)s..."), {url: _.escape(url), name: _.escape(name)});
+ workText = _.sprintf(
+ gettext('Reinstalling plugin "%(name)s" from %(url)s...'),
+ {url: _.escape(url), name: _.escape(name)}
+ );
}
self._markWorking(workTitle, workText);
- var onSuccess = function(response) {
+ var onSuccess = function (response) {
self.installUrl("");
},
- onError = function() {
- self._markDone("Could not install plugin, unknown error, please consult octoprint.log for details");
+ onError = function () {
+ self._markDone(
+ "Could not install plugin, unknown error, please consult octoprint.log for details"
+ );
new PNotify({
title: gettext("Something went wrong"),
text: gettext("Please consult octoprint.log for details"),
@@ -658,18 +836,24 @@ $(function() {
};
if (reinstall) {
- OctoPrint.plugins.pluginmanager.reinstall(reinstall, url, followDependencyLinks)
+ OctoPrint.plugins.pluginmanager
+ .reinstall(reinstall, url, followDependencyLinks)
.done(onSuccess)
.fail(onError);
} else {
- OctoPrint.plugins.pluginmanager.install(url, followDependencyLinks)
+ OctoPrint.plugins.pluginmanager
+ .install(url, followDependencyLinks)
.done(onSuccess)
.fail(onError);
}
};
- self.uninstallPlugin = function(data) {
- if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)) {
+ self.uninstallPlugin = function (data) {
+ if (
+ !self.loginState.hasPermission(
+ self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE
+ )
+ ) {
return;
}
@@ -682,14 +866,20 @@ $(function() {
// defining actual uninstall logic as functor in order to handle
// the confirm/no-confirm logic without duplication of logic
- var performUninstall = function(cleanup) {
- self._markWorking(gettext("Uninstalling plugin..."), _.sprintf(gettext("Uninstalling plugin \"%(name)s\""), {name: _.escape(data.name)}));
+ var performUninstall = function (cleanup) {
+ self._markWorking(
+ gettext("Uninstalling plugin..."),
+ _.sprintf(gettext('Uninstalling plugin "%(name)s"'), {
+ name: _.escape(data.name)
+ })
+ );
- OctoPrint.plugins.pluginmanager.uninstall(data.key, cleanup)
- .done(function() {
+ OctoPrint.plugins.pluginmanager
+ .uninstall(data.key, cleanup)
+ .done(function () {
self.requestData();
})
- .fail(function() {
+ .fail(function () {
new PNotify({
title: gettext("Something went wrong"),
text: gettext("Please consult octoprint.log for details"),
@@ -697,27 +887,27 @@ $(function() {
hide: false
});
})
- .always(function() {
+ .always(function () {
self._markDone();
});
};
showConfirmationDialog({
- message: _.sprintf(gettext("You are about to uninstall the plugin \"%(name)s\""), {name: _.escape(data.name)}),
+ message: _.sprintf(
+ gettext('You are about to uninstall the plugin "%(name)s"'),
+ {name: _.escape(data.name)}
+ ),
cancel: gettext("Keep installed"),
- proceed: [
- gettext("Uninstall"),
- gettext("Uninstall & clean up data")
- ],
- onproceed: function(button) {
+ proceed: [gettext("Uninstall"), gettext("Uninstall & clean up data")],
+ onproceed: function (button) {
// buttons: 0=uninstall, 1=uninstall&cleanup
- performUninstall(button === 1)
+ performUninstall(button === 1);
},
nofade: true
});
};
- self.cleanupPlugin = function(data) {
+ self.cleanupPlugin = function (data) {
var key, name;
if (_.isObject(data)) {
key = data.key;
@@ -732,14 +922,20 @@ $(function() {
if (key === "pluginmanager") return;
- var performCleanup = function() {
- self._markWorking(gettext("Cleaning up plugin data..."), _.sprintf(gettext("Cleaning up data of plugin \"%(name)s\""), {name: _.escape(name)}));
+ var performCleanup = function () {
+ self._markWorking(
+ gettext("Cleaning up plugin data..."),
+ _.sprintf(gettext('Cleaning up data of plugin "%(name)s"'), {
+ name: _.escape(name)
+ })
+ );
- OctoPrint.plugins.pluginmanager.cleanup(key)
- .done(function() {
+ OctoPrint.plugins.pluginmanager
+ .cleanup(key)
+ .done(function () {
self.requestData();
})
- .fail(function() {
+ .fail(function () {
new PNotify({
title: gettext("Something went wrong"),
text: gettext("Please consult octoprint.log for details"),
@@ -747,13 +943,18 @@ $(function() {
hide: false
});
})
- .always(function() {
+ .always(function () {
self._markDone();
- })
+ });
};
showConfirmationDialog({
- message: _.sprintf(gettext("You are about to cleanup the plugin data of \"%(name)s\". This operation cannot be reversed."), {name: _.escape(name)}),
+ message: _.sprintf(
+ gettext(
+ 'You are about to cleanup the plugin data of "%(name)s". This operation cannot be reversed.'
+ ),
+ {name: _.escape(name)}
+ ),
cancel: gettext("Keep data"),
proceed: gettext("Cleanup data"),
onproceed: performCleanup,
@@ -761,17 +962,18 @@ $(function() {
});
};
- self.cleanupAll = function() {
+ self.cleanupAll = function () {
if (!self.loginState.isAdmin()) {
return;
}
- var performCleanup = function() {
+ var performCleanup = function () {
var title = gettext("Cleaning up all left over plugin data...");
self._markWorking(title, title);
- OctoPrint.plugins.pluginmanager.cleanupAll()
- .fail(function() {
+ OctoPrint.plugins.pluginmanager
+ .cleanupAll()
+ .fail(function () {
new PNotify({
title: gettext("Something went wrong"),
text: gettext("Please consult octoprint.log for details"),
@@ -779,13 +981,15 @@ $(function() {
hide: false
});
})
- .always(function() {
+ .always(function () {
self._markDone();
- })
+ });
};
showConfirmationDialog({
- message: gettext("You are about to cleanup left over plugin settings and data of plugins no longer installed. This operation cannot be reversed."),
+ message: gettext(
+ "You are about to cleanup left over plugin settings and data of plugins no longer installed. This operation cannot be reversed."
+ ),
cancel: gettext("Keep data"),
proceed: gettext("Cleanup all data"),
onproceed: performCleanup,
@@ -793,35 +997,48 @@ $(function() {
});
};
- self.refreshRepository = function() {
- if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_INSTALL)) {
+ self.refreshRepository = function () {
+ if (
+ !self.loginState.hasPermission(
+ self.access.permissions.PLUGIN_PLUGINMANAGER_INSTALL
+ )
+ ) {
return;
}
self.requestData({refresh_repo: true});
};
- self.refreshNotices = function() {
+ self.refreshNotices = function () {
if (!self.loginState.isAdmin()) {
return;
}
- self.requestData({refresh_notices: true, eval_notices: true, ignore_notice_hidden: true, ignore_notice_ignored: true});
+ self.requestData({
+ refresh_notices: true,
+ eval_notices: true,
+ ignore_notice_hidden: true,
+ ignore_notice_ignored: true
+ });
};
- self.reshowNotices = function() {
+ self.reshowNotices = function () {
if (!self.loginState.isAdmin()) {
return;
}
- self.requestData({eval_notices: true, ignore_notice_hidden: true, ignore_notice_ignored: true});
+ self.requestData({
+ eval_notices: true,
+ ignore_notice_hidden: true,
+ ignore_notice_ignored: true
+ });
};
- self.showPluginSettings = function() {
+ self.showPluginSettings = function () {
self._copyConfig();
self.configurationDialog.modal();
};
- self.savePluginSettings = function() {
+ self.savePluginSettings = function () {
var repository = self.config_repositoryUrl();
if (repository !== null && repository.trim() === "") {
repository = null;
@@ -860,54 +1077,89 @@ $(function() {
notices_ttl: noticesTtl,
pip_args: pipArgs,
pip_force_user: self.config_pipForceUser(),
- confirm_disable: self.config_confirmDisable(),
+ confirm_disable: self.config_confirmDisable()
}
}
};
- self.settingsViewModel.saveData(data, function() {
+ self.settingsViewModel.saveData(data, function () {
self.configurationDialog.modal("hide");
self._copyConfig();
- self.requestData({refresh_repo: true, refresh_notices: true, eval_notices: true});
+ self.requestData({
+ refresh_repo: true,
+ refresh_notices: true,
+ eval_notices: true
+ });
});
};
- self._copyConfig = function() {
- self.config_repositoryUrl(self.settingsViewModel.settings.plugins.pluginmanager.repository());
- self.config_repositoryTtl(self.settingsViewModel.settings.plugins.pluginmanager.repository_ttl());
- self.config_noticesUrl(self.settingsViewModel.settings.plugins.pluginmanager.notices());
- self.config_noticesTtl(self.settingsViewModel.settings.plugins.pluginmanager.notices_ttl());
- self.config_pipAdditionalArgs(self.settingsViewModel.settings.plugins.pluginmanager.pip_args());
- self.config_pipForceUser(self.settingsViewModel.settings.plugins.pluginmanager.pip_force_user());
- self.config_confirmDisable(self.settingsViewModel.settings.plugins.pluginmanager.confirm_disable());
+ self._copyConfig = function () {
+ self.config_repositoryUrl(
+ self.settingsViewModel.settings.plugins.pluginmanager.repository()
+ );
+ self.config_repositoryTtl(
+ self.settingsViewModel.settings.plugins.pluginmanager.repository_ttl()
+ );
+ self.config_noticesUrl(
+ self.settingsViewModel.settings.plugins.pluginmanager.notices()
+ );
+ self.config_noticesTtl(
+ self.settingsViewModel.settings.plugins.pluginmanager.notices_ttl()
+ );
+ self.config_pipAdditionalArgs(
+ self.settingsViewModel.settings.plugins.pluginmanager.pip_args()
+ );
+ self.config_pipForceUser(
+ self.settingsViewModel.settings.plugins.pluginmanager.pip_force_user()
+ );
+ self.config_confirmDisable(
+ self.settingsViewModel.settings.plugins.pluginmanager.confirm_disable()
+ );
};
- self.installed = function(data) {
+ self.installed = function (data) {
return _.includes(self.installedPlugins(), data.id);
};
- self.isCompatible = function(data) {
- return data.is_compatible.octoprint && data.is_compatible.os && data.is_compatible.python;
+ self.isCompatible = function (data) {
+ return (
+ data.is_compatible.octoprint &&
+ data.is_compatible.os &&
+ data.is_compatible.python
+ );
};
- self.installButtonText = function(data) {
- return self.isCompatible(data) ? (self.installed(data) ? gettext("Reinstall") : gettext("Install")) : (data.disabled ? gettext("Disabled") : gettext("Incompatible"));
+ self.installButtonText = function (data) {
+ return self.isCompatible(data)
+ ? self.installed(data)
+ ? gettext("Reinstall")
+ : gettext("Install")
+ : data.disabled
+ ? gettext("Disabled")
+ : gettext("Incompatible");
};
- self._processPluginManagementResult = function(response, action, plugin) {
+ self._processPluginManagementResult = function (response, action, plugin) {
if (response.result) {
self._markDone();
} else {
- self._markDone(response.reason)
+ self._markDone(response.reason);
}
self._displayPluginManagementNotification(response, action, plugin);
};
- self._displayPluginManagementNotification = function(response, action, plugin) {
- self.logContents.action.restart = self.logContents.action.restart || response.needs_restart;
- self.logContents.action.refresh = self.logContents.action.refresh || response.needs_refresh;
- self.logContents.action_reconnect = self.logContents.action.reconnect || response.needs_reconnect;
- self.logContents.steps.push({action: action, plugin: plugin, result: response.result});
+ self._displayPluginManagementNotification = function (response, action, plugin) {
+ self.logContents.action.restart =
+ self.logContents.action.restart || response.needs_restart;
+ self.logContents.action.refresh =
+ self.logContents.action.refresh || response.needs_refresh;
+ self.logContents.action_reconnect =
+ self.logContents.action.reconnect || response.needs_reconnect;
+ self.logContents.steps.push({
+ action: action,
+ plugin: plugin,
+ result: response.result
+ });
var title = gettext("Plugin management log");
var text = "
";
var confirm = undefined;
var type = "success";
if (self.logContents.action.restart) {
- text += "
" + gettext("A restart is needed for the changes to take effect.") + "
";
+ text +=
+ "
" +
+ gettext("A restart is needed for the changes to take effect.") +
+ "
";
type = "warning";
if (self.restartCommandSpec) {
var restartClicked = false;
confirm = {
confirm: true,
- buttons: [{
- text: gettext("Restart now"),
- click: function (notice) {
- if (restartClicked) return;
- restartClicked = true;
- showConfirmationDialog({
- message: gettext("This will restart your 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)."),
- onproceed: function() {
- OctoPrint.system.executeCommand("core", "restart")
- .done(function() {
- notice.remove();
- new PNotify({
- title: gettext("Restart in progress"),
- text: gettext("The server is now being restarted in the background")
+ buttons: [
+ {
+ text: gettext("Restart now"),
+ click: function (notice) {
+ if (restartClicked) return;
+ restartClicked = true;
+ showConfirmationDialog({
+ message: gettext(
+ "This will restart your 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)."
+ ),
+ onproceed: function () {
+ OctoPrint.system
+ .executeCommand("core", "restart")
+ .done(function () {
+ notice.remove();
+ new PNotify({
+ title: gettext(
+ "Restart in progress"
+ ),
+ text: gettext(
+ "The server is now being restarted in the background"
+ )
+ });
})
- })
- .fail(function() {
- new PNotify({
- title: gettext("Something went wrong"),
- text: gettext("Trying to restart the server produced an error, please check octoprint.log for details. You'll have to restart manually.")
- })
- });
- },
- onclose: function() {
- restartClicked = false;
- }
- });
+ .fail(function () {
+ new PNotify({
+ title: gettext(
+ "Something went wrong"
+ ),
+ text: gettext(
+ "Trying to restart the server produced an error, please check octoprint.log for details. You'll have to restart manually."
+ )
+ });
+ });
+ },
+ onclose: function () {
+ restartClicked = false;
+ }
+ });
+ }
}
- }]
- }
+ ]
+ };
}
} else if (self.logContents.action.refresh) {
- text += "
" + gettext("A refresh is needed for the changes to take effect.") + "
";
+ text +=
+ "
" +
+ gettext("A refresh is needed for the changes to take effect.") +
+ "
";
type = "warning";
var refreshClicked = false;
confirm = {
confirm: true,
- buttons: [{
- text: gettext("Reload now"),
- click: function () {
- if (refreshClicked) return;
- refreshClicked = true;
- location.reload(true);
+ buttons: [
+ {
+ text: gettext("Reload now"),
+ click: function () {
+ if (refreshClicked) return;
+ refreshClicked = true;
+ location.reload(true);
+ }
}
- }]
- }
+ ]
+ };
} else if (self.logContents.action_reconnect) {
- text += "
" + gettext("A reconnect to the printer is needed for the changes to take effect.") + "
";
+ text +=
+ "
" +
+ gettext(
+ "A reconnect to the printer is needed for the changes to take effect."
+ ) +
+ "
";
type = "warning";
}
@@ -1040,7 +1324,10 @@ $(function() {
self.logNotification = PNotify.singleButtonNotify(options);
} else {
self.logNotification.update(options);
- self.logNotification = PNotify.fixSingleButton(self.logNotification, options);
+ self.logNotification = PNotify.fixSingleButton(
+ self.logNotification,
+ options
+ );
}
} else {
if (self.logNotification === undefined) {
@@ -1051,12 +1338,15 @@ $(function() {
}
// make sure the notification is visible
- if (self.logNotification.state !== 'open' && self.logNotification.state !== 'opening') {
+ if (
+ self.logNotification.state !== "open" &&
+ self.logNotification.state !== "opening"
+ ) {
self.logNotification.open();
}
};
- self._markWorking = function(title, line) {
+ self._markWorking = function (title, line) {
self.working(true);
self.workingTitle(title);
@@ -1067,42 +1357,50 @@ $(function() {
self.workingDialog.modal({keyboard: false, backdrop: "static", show: true});
};
- self._markDone = function(error) {
+ self._markDone = function (error) {
self.working(false);
if (error) {
self.loglines.push({line: gettext("Error!"), stream: "error"});
- self.loglines.push({line: error, stream: "error"})
+ self.loglines.push({line: error, stream: "error"});
} else {
self.loglines.push({line: gettext("Done!"), stream: "message"});
}
self._scrollWorkingOutputToEnd();
};
- self._scrollWorkingOutputToEnd = function() {
- self.workingOutput.scrollTop(self.workingOutput[0].scrollHeight - self.workingOutput.height());
+ self._scrollWorkingOutputToEnd = function () {
+ self.workingOutput.scrollTop(
+ self.workingOutput[0].scrollHeight - self.workingOutput.height()
+ );
};
- self._getToggleCommand = function(data) {
- var disable = (data.enabled || (data.safe_mode_victim && !data.forced_disabled) || data.pending_enable)
- && !data.pending_disable;
+ self._getToggleCommand = function (data) {
+ var disable =
+ (data.enabled ||
+ (data.safe_mode_victim && !data.forced_disabled) ||
+ data.pending_enable) &&
+ !data.pending_disable;
return disable ? "disable" : "enable";
};
- self.toggleButtonCss = function(data) {
+ self.toggleButtonCss = function (data) {
var icon, disabled;
if (self.toggling()) {
icon = "fa fa-spin fa-spinner";
disabled = " disabled";
} else {
- icon = self._getToggleCommand(data) === "enable" ? "fa fa-toggle-off" : "fa fa-toggle-on";
- disabled = (self.enableToggle(data)) ? "" : " disabled";
+ icon =
+ self._getToggleCommand(data) === "enable"
+ ? "fa fa-toggle-off"
+ : "fa fa-toggle-on";
+ disabled = self.enableToggle(data) ? "" : " disabled";
}
return icon + disabled;
};
- self.toggleButtonTitle = function(data) {
+ self.toggleButtonTitle = function (data) {
var command = self._getToggleCommand(data);
if (command === "enable") {
if (data.blacklisted) {
@@ -1117,36 +1415,52 @@ $(function() {
}
};
- self.showPluginNotifications = function(plugin) {
+ self.showPluginNotifications = function (plugin) {
if (!plugin.notifications || plugin.notifications.length === 0) return;
self._removeAllNoticeNotificationsForPlugin(plugin.key);
- _.each(plugin.notifications, function(notification) {
+ _.each(plugin.notifications, function (notification) {
self._showPluginNotification(plugin, notification);
});
};
- self.showPluginNotificationsLinkText = function(plugins) {
+ self.showPluginNotificationsLinkText = function (plugins) {
if (!plugins.notifications || plugins.notifications.length === 0) return;
var count = plugins.notifications.length;
- var importantCount = _.filter(plugins.notifications, function(notification) { return notification.important }).length;
+ var importantCount = _.filter(plugins.notifications, function (notification) {
+ return notification.important;
+ }).length;
if (count > 1) {
if (importantCount) {
- return _.sprintf(gettext("There are %(count)d notices (%(important)d marked as important) available regarding this plugin - click to show!"), {count: count, important: importantCount});
+ return _.sprintf(
+ gettext(
+ "There are %(count)d notices (%(important)d marked as important) available regarding this plugin - click to show!"
+ ),
+ {count: count, important: importantCount}
+ );
} else {
- return _.sprintf(gettext("There are %(count)d notices available regarding this plugin - click to show!"), {count: count});
+ return _.sprintf(
+ gettext(
+ "There are %(count)d notices available regarding this plugin - click to show!"
+ ),
+ {count: count}
+ );
}
} else {
if (importantCount) {
- return gettext("There is an important notice available regarding this plugin - click to show!");
+ return gettext(
+ "There is an important notice available regarding this plugin - click to show!"
+ );
} else {
- return gettext("There is a notice available regarding this plugin - click to show!");
+ return gettext(
+ "There is a notice available regarding this plugin - click to show!"
+ );
}
}
};
- self._showPluginNotification = function(plugin, notification) {
+ self._showPluginNotification = function (plugin, notification) {
var name = plugin.name;
var version = plugin.version;
@@ -1155,53 +1469,84 @@ $(function() {
var title;
if (important) {
- title = _.sprintf(gettext("Important notice regarding plugin \"%(name)s\""), {name: _.escape(name)});
+ title = _.sprintf(
+ gettext('Important notice regarding plugin "%(name)s"'),
+ {name: _.escape(name)}
+ );
} else {
- title = _.sprintf(gettext("Notice regarding plugin \"%(name)s\""), {name: _.escape(name)});
+ title = _.sprintf(gettext('Notice regarding plugin "%(name)s"'), {
+ name: _.escape(name)
+ });
}
var text = "";
if (notification.versions && notification.versions.length > 0) {
- var versions = _.map(notification.versions, function(v) { return (v === version) ? "" + _.escape(v) + "" : _.escape(v); }).join(", ");
- text += "" + _.sprintf(gettext("Affected versions: %(versions)s"), {versions: versions}) + "";
+ var versions = _.map(notification.versions, function (v) {
+ return v === version
+ ? "" + _.escape(v) + ""
+ : _.escape(v);
+ }).join(", ");
+ text +=
+ "" +
+ _.sprintf(gettext("Affected versions: %(versions)s"), {
+ versions: versions
+ }) +
+ "";
} else {
text += "" + gettext("Affected versions: all") + "";
}
text += "
" + gettext("Be sure to read through any linked release notes, especially those for OctoPrint since they might contain important information you need to know before upgrading.") + "
"
- + "
" + gettext("This action may disrupt any ongoing print jobs.") + "
"
- + "
" + gettext("Depending on your printer's controller and general setup, restarting OctoPrint may cause your printer to be reset.") + "
"
- + "
" + gettext("Are you sure you want to proceed?") + "
";
+ html +=
+ "
" +
+ gettext(
+ "Be sure to read through any linked release notes, especially those for OctoPrint since they might contain important information you need to know before upgrading."
+ ) +
+ "
" +
+ "
" +
+ gettext("This action may disrupt any ongoing print jobs.") +
+ "
" +
+ "
" +
+ gettext(
+ "Depending on your printer's controller and general setup, restarting OctoPrint may cause your printer to be reset."
+ ) +
+ "
" +
+ "
" +
+ gettext("Are you sure you want to proceed?") +
+ "
";
showConfirmationDialog({
title: gettext("Are you sure you want to update now?"),
html: html,
proceed: gettext("Proceed"),
- onproceed: function() {
- self.performUpdate((force === true),
- _.map(items,
- function(info) { return info.key }));
+ onproceed: function () {
+ self.performUpdate(
+ force === true,
+ _.map(items, function (info) {
+ return info.key;
+ })
+ );
},
- onclose: function() {
+ onclose: function () {
self._updateClicked = false;
}
});
};
- self._showWorkingDialog = function(title) {
- if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_CHECK)) {
+ self._showWorkingDialog = function (title) {
+ if (
+ !self.loginState.hasPermission(
+ self.access.permissions.PLUGIN_SOFTWAREUPDATE_CHECK
+ )
+ ) {
return;
}
@@ -596,7 +806,7 @@ $(function() {
self.workingDialog.modal({keyboard: false, backdrop: "static", show: true});
};
- self._markWorking = function(title, line, stream) {
+ self._markWorking = function (title, line, stream) {
if (stream === undefined) {
stream = "message";
}
@@ -606,7 +816,7 @@ $(function() {
self._showWorkingDialog(title);
};
- self._markDone = function(line, stream) {
+ self._markDone = function (line, stream) {
if (stream === undefined) {
stream = "message";
}
@@ -617,11 +827,13 @@ $(function() {
self._scrollWorkingOutputToEnd();
};
- self._scrollWorkingOutputToEnd = function() {
- self.workingOutput.scrollTop(self.workingOutput[0].scrollHeight - self.workingOutput.height());
+ self._scrollWorkingOutputToEnd = function () {
+ self.workingOutput.scrollTop(
+ self.workingOutput[0].scrollHeight - self.workingOutput.height()
+ );
};
- self.onBeforeWizardTabChange = function(next, current) {
+ self.onBeforeWizardTabChange = function (next, current) {
if (next && next === "#wizard_plugin_softwareupdate") {
// switching to the plugin wizard tab
self._copyConfig();
@@ -633,30 +845,34 @@ $(function() {
return true;
};
- self.onAfterWizardFinish = function() {
+ self.onAfterWizardFinish = function () {
// we might have changed our config, so we need to refresh our check data from the server
self.performCheck();
};
- self.onStartup = function() {
+ self.onStartup = function () {
self.workingDialog = $("#settings_plugin_softwareupdate_workingdialog");
- self.workingOutput = $("#settings_plugin_softwareupdate_workingdialog_output");
- self.configurationDialog = $("#settings_plugin_softwareupdate_configurationdialog");
+ self.workingOutput = $(
+ "#settings_plugin_softwareupdate_workingdialog_output"
+ );
+ self.configurationDialog = $(
+ "#settings_plugin_softwareupdate_configurationdialog"
+ );
};
- self.onServerDisconnect = function() {
+ self.onServerDisconnect = function () {
if (self.restartTimeout !== undefined) {
clearTimeout(self.restartTimeout);
}
return true;
};
- self.onEventConnectivityChanged = function(payload) {
+ self.onEventConnectivityChanged = function (payload) {
if (!payload || !payload.new) return;
self.performCheck();
};
- self.onDataUpdaterReconnect = function() {
+ self.onDataUpdaterReconnect = function () {
if (self.waitingForRestart) {
self.waitingForRestart = false;
self.updateInProgress = false;
@@ -666,7 +882,7 @@ $(function() {
}
};
- self.onDataUpdaterPluginMessage = function(plugin, data) {
+ self.onDataUpdaterPluginMessage = function (plugin, data) {
if (plugin !== "softwareupdate") {
return;
}
@@ -680,7 +896,7 @@ $(function() {
var title = undefined;
var text = undefined;
- switch(messageType) {
+ switch (messageType) {
// make sure we are marked as working if we get any of the in-progress messages
case "loglines":
case "updating":
@@ -690,7 +906,10 @@ $(function() {
case "success":
case "error": {
if (!self.working()) {
- self._markWorking(gettext("Updating..."), gettext("Updating, please wait."));
+ self._markWorking(
+ gettext("Updating..."),
+ gettext("Updating, please wait.")
+ );
}
break;
}
@@ -698,18 +917,27 @@ $(function() {
switch (messageType) {
case "loglines": {
- _.each(messageData.loglines, function(line) {
+ _.each(messageData.loglines, function (line) {
self.loglines.push(self._preprocessLine(line));
});
self._scrollWorkingOutputToEnd();
break;
}
case "updating": {
- text = _.sprintf(gettext("Now updating %(name)s to %(version)s"), {name: _.escape(messageData.name), version: _.escape(messageData.version)});
+ text = _.sprintf(gettext("Now updating %(name)s to %(version)s"), {
+ name: _.escape(messageData.name),
+ version: _.escape(messageData.version)
+ });
self.loglines.push({line: "", stream: "separator"});
- self.loglines.push({line: _.repeat("+", text.length), stream: "separator"});
+ self.loglines.push({
+ line: _.repeat("+", text.length),
+ stream: "separator"
+ });
self.loglines.push({line: text, stream: "message"});
- self.loglines.push({line: _.repeat("+", text.length), stream: "separator"});
+ self.loglines.push({
+ line: _.repeat("+", text.length),
+ stream: "separator"
+ });
self._scrollWorkingOutputToEnd();
self._updatePopup({
text: text,
@@ -723,7 +951,9 @@ $(function() {
}
case "restarting": {
title = gettext("Update successful, restarting!");
- text = gettext("The update finished successfully and the server will now be restarted.");
+ text = gettext(
+ "The update finished successfully and the server will now be restarted."
+ );
options = {
title: title,
@@ -739,9 +969,11 @@ $(function() {
self._scrollWorkingOutputToEnd();
self.waitingForRestart = true;
- self.restartTimeout = setTimeout(function() {
+ self.restartTimeout = setTimeout(function () {
title = gettext("Restart failed");
- text = gettext("The server apparently did not restart by itself, you'll have to do it manually. Please consult octoprint.log on what went wrong.");
+ text = gettext(
+ "The server apparently did not restart by itself, you'll have to do it manually. Please consult octoprint.log on what went wrong."
+ );
self._showPopup({
title: title,
@@ -761,9 +993,13 @@ $(function() {
}
case "restart_manually": {
restartType = messageData.restart_type;
- text = gettext("The update finished successfully, please restart OctoPrint now.");
+ text = gettext(
+ "The update finished successfully, please restart OctoPrint now."
+ );
if (restartType === "environment") {
- text = gettext("The update finished successfully, please reboot the server now.");
+ text = gettext(
+ "The update finished successfully, please reboot the server now."
+ );
}
title = gettext("Update successful, restart required!");
@@ -782,9 +1018,13 @@ $(function() {
}
case "restart_failed": {
restartType = messageData.restart_type;
- text = gettext("Restarting OctoPrint failed, please restart it manually. You might also want to consult octoprint.log on what went wrong here.");
+ text = gettext(
+ "Restarting OctoPrint failed, please restart it manually. You might also want to consult octoprint.log on what went wrong here."
+ );
if (restartType === "environment") {
- text = gettext("Rebooting the server failed, please reboot it manually. You might also want to consult octoprint.log on what went wrong here.");
+ text = gettext(
+ "Rebooting the server failed, please reboot it manually. You might also want to consult octoprint.log on what went wrong here."
+ );
}
title = gettext("Restart failed");
@@ -820,7 +1060,9 @@ $(function() {
}
case "error": {
title = gettext("Update failed!");
- text = gettext("The update did not finish successfully. Please consult octoprint.log and plugin_softwareupdate_console.log for details.");
+ text = gettext(
+ "The update did not finish successfully. Please consult octoprint.log and plugin_softwareupdate_console.log for details."
+ );
self._showPopup({
title: title,
text: text,
@@ -845,22 +1087,34 @@ $(function() {
}
};
- self._forcedStdoutPatterns = ["You are using pip version .*?, however version .*? is available\.",
- "You should consider upgrading via the '.*?' command\.",
- "'.*?' does not exist -- can't clean it"];
+ self._forcedStdoutPatterns = [
+ "You are using pip version .*?, however version .*? is available.",
+ "You should consider upgrading via the '.*?' command.",
+ "'.*?' does not exist -- can't clean it"
+ ];
self._forcedStdoutLine = new RegExp(self._forcedStdoutPatterns.join("|"));
- self._preprocessLine = function(line) {
+ self._preprocessLine = function (line) {
if (line.stream === "stderr" && line.line.match(self._forcedStdoutLine)) {
line.stream = "stdout";
}
return line;
- }
+ };
}
OCTOPRINT_VIEWMODELS.push({
construct: SoftwareUpdateViewModel,
- dependencies: ["loginStateViewModel", "printerStateViewModel", "settingsViewModel", "accessViewModel", "piSupportViewModel"],
+ dependencies: [
+ "loginStateViewModel",
+ "printerStateViewModel",
+ "settingsViewModel",
+ "accessViewModel",
+ "piSupportViewModel"
+ ],
optional: ["piSupportViewModel"],
- elements: ["#settings_plugin_softwareupdate", "#softwareupdate_confirmation_dialog", "#wizard_plugin_softwareupdate"]
+ elements: [
+ "#settings_plugin_softwareupdate",
+ "#softwareupdate_confirmation_dialog",
+ "#wizard_plugin_softwareupdate"
+ ]
});
});
diff --git a/src/octoprint/plugins/softwareupdate/static/less/softwareupdate.less b/src/octoprint/plugins/softwareupdate/static/less/softwareupdate.less
index 3da4a36f6..2c4a5cd99 100644
--- a/src/octoprint/plugins/softwareupdate/static/less/softwareupdate.less
+++ b/src/octoprint/plugins/softwareupdate/static/less/softwareupdate.less
@@ -73,4 +73,3 @@ td.settings_plugin_softwareupdate_column_information {
}
}
}
-
diff --git a/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 b/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2
index c769aab1e..3f013e6a8 100644
--- a/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2
+++ b/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2
@@ -171,4 +171,3 @@
-
diff --git a/src/octoprint/plugins/softwareupdate/updaters/__init__.py b/src/octoprint/plugins/softwareupdate/updaters/__init__.py
index 6c76224bf..3a9fc471a 100644
--- a/src/octoprint/plugins/softwareupdate/updaters/__init__.py
+++ b/src/octoprint/plugins/softwareupdate/updaters/__init__.py
@@ -2,7 +2,13 @@
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
+from . import ( # noqa: F401
+ pip,
+ python_updater,
+ single_file_plugin,
+ sleep_a_bit,
+ update_script,
+)
diff --git a/src/octoprint/plugins/softwareupdate/updaters/pip.py b/src/octoprint/plugins/softwareupdate/updaters/pip.py
index c3c4362b5..adc7fddd3 100644
--- a/src/octoprint/plugins/softwareupdate/updaters/pip.py
+++ b/src/octoprint/plugins/softwareupdate/updaters/pip.py
@@ -2,19 +2,23 @@
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
+
import pkg_resources
from octoprint.util.pip import PipCaller, UnknownPip
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 +27,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 key not 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..776b891f1 100644
--- a/src/octoprint/plugins/softwareupdate/updaters/single_file_plugin.py
+++ b/src/octoprint/plugins/softwareupdate/updaters/single_file_plugin.py
@@ -1,75 +1,88 @@
# -*- 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
-import shutil
-import os
import ast
import io
+import logging
+import os
+import shutil
+from octoprint.settings import settings
from octoprint.util import TemporaryDirectory
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..9b5b47fec 100644
--- a/src/octoprint/plugins/softwareupdate/updaters/update_script.py
+++ b/src/octoprint/plugins/softwareupdate/updaters/update_script.py
@@ -2,104 +2,131 @@
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
import logging
-
-from ..exceptions import ConfigurationInvalid, UpdateError, CannotUpdateOffline
+import sys
from octoprint.util.commandline import CommandlineCaller, CommandlineError
+from ..exceptions import CannotUpdateOffline, ConfigurationInvalid, UpdateError
+
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..dbd6b1be5 100644
--- a/src/octoprint/plugins/softwareupdate/util.py
+++ b/src/octoprint/plugins/softwareupdate/util.py
@@ -2,33 +2,44 @@
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 ScriptError
-
import logging
from octoprint.util.platform import CLOSE_FDS
+from .exceptions import ScriptError
+
+
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..42d42c95e 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 ( # noqa: F401
+ always_current,
+ bitbucket_commit,
+ commandline,
+ git_commit,
+ github_commit,
+ github_release,
+ httpheader,
+ jsondata,
+ never_current,
+ pypi_release,
+ python_checker,
+)
+
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..5264848b1 100644
--- a/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py
+++ b/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py
@@ -1,70 +1,94 @@
# -*- 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
+import logging
-BRANCH_HEAD_URL = "https://api.bitbucket.org/2.0/repositories/{user}/{repo}/commit/{branch}"
+import requests
-logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.bitbucket_commit")
+BRANCH_HEAD_URL = (
+ "https://api.bitbucket.org/2.0/repositories/{user}/{repo}/commit/{branch}"
+)
+
+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 "hash" not 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..0942bc6c0 100644
--- a/src/octoprint/plugins/softwareupdate/version_checks/commandline.py
+++ b/src/octoprint/plugins/softwareupdate/version_checks/commandline.py
@@ -2,47 +2,63 @@
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
-from ..exceptions import ConfigurationInvalid, CannotCheckOffline
+from ..exceptions import CannotCheckOffline, ConfigurationInvalid
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..af697d06a 100644
--- a/src/octoprint/plugins/softwareupdate/version_checks/git_commit.py
+++ b/src/octoprint/plugins/softwareupdate/version_checks/git_commit.py
@@ -2,86 +2,106 @@
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 errno
+import logging
import subprocess
import sys
-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..e38959fdd 100644
--- a/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py
+++ b/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py
@@ -2,65 +2,89 @@
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
import logging
+import requests
+
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 "object" not in reference or "sha" not 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..9a7c31964 100644
--- a/src/octoprint/plugins/softwareupdate/version_checks/github_release.py
+++ b/src/octoprint/plugins/softwareupdate/version_checks/github_release.py
@@ -1,302 +1,347 @@
# -*- 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
import logging
+import requests
+
from octoprint.util import sv
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 (
+ compare_type
+ not 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..43a86775d 100644
--- a/src/octoprint/plugins/softwareupdate/version_checks/httpheader.py
+++ b/src/octoprint/plugins/softwareupdate/version_checks/httpheader.py
@@ -1,41 +1,57 @@
# -*- 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
import logging
-from ..exceptions import ConfigurationInvalid, NetworkError, CannotCheckOffline
+import requests
+
+from ..exceptions import CannotCheckOffline, ConfigurationInvalid, NetworkError
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..d367bcf22 100644
--- a/src/octoprint/plugins/softwareupdate/version_checks/jsondata.py
+++ b/src/octoprint/plugins/softwareupdate/version_checks/jsondata.py
@@ -1,37 +1,45 @@
# -*- 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
import logging
-from ..exceptions import ConfigurationInvalid, NetworkError, CannotCheckOffline
+import requests
+
+from ..exceptions import CannotCheckOffline, ConfigurationInvalid, NetworkError
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..282103033 100644
--- a/src/octoprint/plugins/softwareupdate/version_checks/pypi_release.py
+++ b/src/octoprint/plugins/softwareupdate/version_checks/pypi_release.py
@@ -1,108 +1,131 @@
# 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
+
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 import to_native_str # noqa: F401
+from octoprint.util.version import (
+ get_comparable_version,
+ is_prerelease,
+ is_python_compatible,
+)
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 "info" not in data or "version" not 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..f07c4d200 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
+from ..exceptions import CannotCheckOffline, ConfigurationInvalid
+
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..74ec18e71 100644
--- a/src/octoprint/plugins/tracking/__init__.py
+++ b/src/octoprint/plugins/tracking/__init__.py
@@ -1,454 +1,542 @@
# -*- 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
-
-from flask_babel import gettext
-
-import requests
import hashlib
import logging
+import requests
+from flask_babel import gettext
+
+import octoprint.plugin
+
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
+from octoprint.events import Events
from octoprint.util import RepeatedTimer, monotonic_time
from octoprint.util.version import get_octoprint_version_string
-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 "reason" not in payload or "error" not 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/tracking/static/js/usage.js b/src/octoprint/plugins/tracking/static/js/usage.js
index 2086ca707..dc44f467d 100644
--- a/src/octoprint/plugins/tracking/static/js/usage.js
+++ b/src/octoprint/plugins/tracking/static/js/usage.js
@@ -1,4 +1,4 @@
-$(function() {
+$(function () {
function UsageViewModel(parameters) {
var self = this;
@@ -10,22 +10,26 @@ $(function() {
self.active = ko.observable();
self.required = false;
- self.enableUsage = function() {
+ self.enableUsage = function () {
self.settingsViewModel.settings.plugins.tracking.enabled(true);
self.decision(true);
self._sendData();
};
- self.disableUsage = function() {
+ self.disableUsage = function () {
self.settingsViewModel.settings.plugins.tracking.enabled(false);
self.decision(false);
self._sendData();
};
- self.onBeforeWizardTabChange = function(next, current) {
+ self.onBeforeWizardTabChange = function (next, current) {
if (!self.required) return true;
- if (!current || !_.startsWith(current, "wizard_plugin_tracking") || self.setup()) {
+ if (
+ !current ||
+ !_.startsWith(current, "wizard_plugin_tracking") ||
+ self.setup()
+ ) {
return true;
}
@@ -33,7 +37,7 @@ $(function() {
return false;
};
- self.onBeforeWizardFinish = function() {
+ self.onBeforeWizardFinish = function () {
if (!self.required) return true;
if (self.setup()) {
@@ -44,18 +48,20 @@ $(function() {
return false;
};
- self.onWizardDetails = function(response) {
+ self.onWizardDetails = function (response) {
self.required = response && response.tracking && response.tracking.required;
};
- self._showDecisionNeededDialog = function() {
+ self._showDecisionNeededDialog = function () {
showMessageDialog({
title: gettext("Please set up anonymous usage tracking"),
- message: gettext("You haven't yet decided on whether to enable or disable anonymous usage tracking. You need to either enable or disable it before continuing.")
+ message: gettext(
+ "You haven't yet decided on whether to enable or disable anonymous usage tracking. You need to either enable or disable it before continuing."
+ )
});
};
- self._sendData = function() {
+ self._sendData = function () {
var data = {
plugins: {
tracking: {
@@ -65,23 +71,30 @@ $(function() {
};
self.active(true);
- self.settingsViewModel.saveData(data)
- .done(function() {
+ self.settingsViewModel
+ .saveData(data)
+ .done(function () {
self.setup(true);
self.active(false);
})
- .fail(function() {
+ .fail(function () {
self.decision(false);
self.setup(true);
self.active(false);
- var message = gettext("Please open a " +
+ var message = gettext(
+ "Please open a " +
"bug report on this. Make sure to include all requested information, including your " +
"JS console and " +
- "octoprint.log.");
+ "octoprint.log."
+ );
new PNotify({
title: gettext("Something went wrong"),
- text: _.sprintf(message, {bugreport: "https://github.com/OctoPrint/OctoPrint/blob/master/CONTRIBUTING.md#how-to-file-a-bug-report", jsconsole: "https://webmasters.stackexchange.com/a/77337"}),
+ text: _.sprintf(message, {
+ bugreport:
+ "https://github.com/OctoPrint/OctoPrint/blob/master/CONTRIBUTING.md#how-to-file-a-bug-report",
+ jsconsole: "https://webmasters.stackexchange.com/a/77337"
+ }),
type: "error",
hide: false
});
diff --git a/src/octoprint/plugins/virtual_printer/__init__.py b/src/octoprint/plugins/virtual_printer/__init__.py
index 287e94c31..40d163a18 100644
--- a/src/octoprint/plugins/virtual_printer/__init__.py
+++ b/src/octoprint/plugins/virtual_printer/__init__.py
@@ -2,135 +2,144 @@
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
- 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 octoprint.logging.handlers import CleaningTimedRotatingFileHandler
- from . import virtual
+ 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)
- serial_obj = virtual.VirtualPrinter(self._settings,
- seriallog_handler=seriallog_handler,
- read_timeout=float(read_timeout),
- faked_baudrate=baudrate)
- return serial_obj
+ from . import virtual
+
+ 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..b25b1679c 100644
--- a/src/octoprint/plugins/virtual_printer/virtual.py
+++ b/src/octoprint/plugins/virtual_printer/virtual.py
@@ -2,1713 +2,1868 @@
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 collections
import io
-import time
+import math
import os
import re
import threading
-import math
-import collections
-try:
- import queue
-except ImportError:
- import Queue as queue
+import time
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
+from typing import Any
+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 typing import Any
+from octoprint.util import (
+ RepeatedTimer,
+ get_dos_filename,
+ monotonic_time,
+ to_bytes,
+ to_unicode,
+)
# 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 = """
- OctoPrint Virtual Printer debug commands
-
- help
- ?
- | This help.
-
- # Action Triggers
-
- action_pause
- | Sends a "// action:pause" action trigger to the host.
- action_resume
- | Sends a "// action:resume" action trigger to the host.
- action_disconnect
- | Sends a "// action:disconnect" action trigger to the
- | host.
- action_custom [ ]
- | Sends a custom "// action:"
- | action trigger to the host.
-
- # Communication Errors
-
- dont_answer
- | Will not acknowledge the next command.
- go_awol
- | Will completely stop replying
- trigger_resend_lineno
- | Triggers a resend error with a line number mismatch
- trigger_resend_checksum
- | Triggers a resend error with a checksum mismatch
- trigger_missing_checksum
- | Triggers a resend error with a missing checksum
- trigger_missing_lineno
- | Triggers a "no line number with checksum" error w/o resend request
- trigger_fatal_error_marlin
- | Triggers a fatal error/simulated heater fail, Marlin style
- trigger_fatal_error_repetier
- | Triggers a fatal error/simulated heater fail, Repetier style
- drop_connection
- | Drops the serial connection
- prepare_ok
- | Will cause to be enqueued for use,
- | will be used instead of actual "ok"
- rerequest_last
- | Will cause the last line number + 1 to be rerequest add infinitum
-
- # Reply Timing / Sleeping
-
- sleep
- | Sleep s
- sleep_after
- | Sleeps s after each execution of
- sleep_after_next
- | Sleeps s after execution of next
-
- # SD printing
-
- start_sd
- | Select and start printing file from SD
- select_sd
- | Select file from SD, don't start printing it yet. Use
- | start_sd to start the print
- cancel_sd
- | Cancels an ongoing SD print
-
- # Misc
-
- send
- | Sends back
- reset
- | Simulates a reset. Internal state will be lost.
- 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))
+ 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 "M29" not 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
+ ?
+ | This help.
+
+ # Action Triggers
+
+ action_pause
+ | Sends a "// action:pause" action trigger to the host.
+ action_resume
+ | Sends a "// action:resume" action trigger to the host.
+ action_disconnect
+ | Sends a "// action:disconnect" action trigger to the
+ | host.
+ action_custom [ ]
+ | Sends a custom "// action:"
+ | action trigger to the host.
+
+ # Communication Errors
+
+ dont_answer
+ | Will not acknowledge the next command.
+ go_awol
+ | Will completely stop replying
+ trigger_resend_lineno
+ | Triggers a resend error with a line number mismatch
+ trigger_resend_checksum
+ | Triggers a resend error with a checksum mismatch
+ trigger_missing_checksum
+ | Triggers a resend error with a missing checksum
+ trigger_missing_lineno
+ | Triggers a "no line number with checksum" error w/o resend request
+ trigger_fatal_error_marlin
+ | Triggers a fatal error/simulated heater fail, Marlin style
+ trigger_fatal_error_repetier
+ | Triggers a fatal error/simulated heater fail, Repetier style
+ drop_connection
+ | Drops the serial connection
+ prepare_ok
+ | Will cause to be enqueued for use,
+ | will be used instead of actual "ok"
+ rerequest_last
+ | Will cause the last line number + 1 to be rerequest add infinitum
+
+ # Reply Timing / Sleeping
+
+ sleep
+ | Sleep s
+ sleep_after
+ | Sleeps s after each execution of
+ sleep_after_next
+ | Sleeps s after execution of next
+
+ # SD printing
+
+ start_sd
+ | Select and start printing file from SD
+ select_sd
+ | Select file from SD, don't start printing it yet. Use
+ | start_sd to start the print
+ cancel_sd
+ | Cancels an ongoing SD print
+
+ # Misc
+
+ send
+ | Sends back
+ reset
+ | Simulates a reset. Internal state will be lost.
+ 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 Exception:
+ if support_r:
+ try:
+ self.chamberTargetTemp = float(re.search("R([0-9]+)", line).group(1))
+ only_wait_if_higher = False
+ except Exception:
+ 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): # noqa: E741
+ 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..b69f04c82 100644
--- a/src/octoprint/printer/__init__.py
+++ b/src/octoprint/printer/__init__.py
@@ -18,705 +18,717 @@ 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
+from octoprint.filemanager import FileDestinations
from octoprint.settings import settings
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: