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 new file mode 100644 index 000000000..005b4260f --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,16 @@ +# refs to ignore during git blame, use with --ignore-revs-file + +# Switch to black formatting +1f93b2355a2816918e11a55e61b42010d15a6720 +5f2a95d154650366078b0d387e5b01427c4340c0 + +# 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 f5a769758..0e0ecd233 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -5,6 +5,7 @@ on: types: [opened, sychronize, reopened] release: types: [published, prereleased] + workflow_dispatch: jobs: build: @@ -30,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: @@ -49,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 @@ -123,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 @@ -143,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/.gitignore b/.gitignore index 4aa025b88..f330dc36c 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ src/octoprint/templates/_data/AUTHORS.md src/octoprint/templates/_data/CHANGELOG.md src/octoprint/templates/_data/SUPPORTERS.md src/octoprint/templates/_data/THIRDPARTYLICENSES.md +src/octoprint/plugins/pi_support/.local_debug docs/_build devtools @@ -35,6 +36,7 @@ pypy .eggs .mypy_cache .pytest_cache +.python-version .tox venv* diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 000000000..ea54569cb --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,44 @@ +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-case-conflict + - id: check-json + - id: check-yaml + - id: check-toml + - id: check-merge-conflict + - id: fix-encoding-pragma + - repo: https://github.com/OctoPrint/codemods + rev: devel + 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: 20.8b1 + hooks: + - id: black + args: ["--config", "black.toml"] + - repo: https://gitlab.com/pycqa/flake8 + rev: 3.8.1 + hooks: + - id: flake8 + additional_dependencies: + - flake8-bugbear + - repo: https://github.com/pre-commit/mirrors-prettier + rev: v2.1.2 + 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/.versioneer-lookup b/.versioneer-lookup index cdea36dc7..2ca573de6 100644 --- a/.versioneer-lookup +++ b/.versioneer-lookup @@ -18,19 +18,19 @@ prerelease HEAD \(detached.* -# maintenance is currently the branch for preparation of maintenance release 1.4.3 +# maintenance is currently the branch for preparation of maintenance release 1.5.0 # so are any fix/... and improve/... branches -maintenance 1.4.3 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev -fix/.* 1.4.3 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev -improve/.* 1.4.3 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev +maintenance 1.5.0 42769dad7dda3bc0c6c94e0e8ce832af9b14a565 pep440-dev +fix/.* 1.5.0 42769dad7dda3bc0c6c94e0e8ce832af9b14a565 pep440-dev +improve/.* 1.5.0 42769dad7dda3bc0c6c94e0e8ce832af9b14a565 pep440-dev # staging/hotfix is the branch for preparation of the 1.4.2 hotfix release staging/hotfix 1.4.2 3ab84ed7e4c3aaaf71fe0f184b465f25d689f929 pep440-dev -# staging/maintenance is currently the branch for preparation of 1.4.1rc5 +# staging/maintenance is currently the branch for preparation of 1.5.0rc4 # so is regressionfix/... -staging/maintenance 1.4.1rc5 458ab91f915307857941f839a1b743430b8786a4 pep440-dev -regressionfix/.* 1.4.1rc5 458ab91f915307857941f839a1b743430b8786a4 pep440-dev +staging/maintenance 1.5.0rc4 5e7ea35239908f9ed91895751d8a8202aa76ed4b pep440-dev +regressionfix/.* 1.5.0rc4 5e7ea35239908f9ed91895751d8a8202aa76ed4b pep440-dev # staging/devel is currently inactive (but has the 1.4.1rc4 namespace) staging/devel 1.4.1rc4 650d54d1885409fa1d411eb54b9e8c7ff428910f pep440-dev diff --git a/AUTHORS.md b/AUTHORS.md index 94d6e6dc5..a50ec706b 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -121,8 +121,15 @@ date of first contribution): * [Josh Friend](https://github.com/joshfriend) * [Lachlan Cresswell](https://github.com/lachyc) * [Khoi Pham](https://github.com/osubuu) + * [Timofei Korostelev](https://github.com/chudsaviet) * [Federico Nembrini](https://github.com/FedericoNembrini) + * [Uri Shaked](https://github.com/urish) * [Brian Vanderbusch](https://github.com/LongLiveCHIEF) + * [Charlie Powell](https://github.com/cp2004) + * [Ollis Git](https://github.com/OllisGit) + * [Sophist](https://github.com/Sophist-UK) + * [Manuel McLure](https://github.com/ManuelMcLure) + * ["j7126"](https://github.com/j7126) OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by [Daid Braam](https://github.com/daid). Parts of its communication layer and diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 068ea1c0a..68c62a498 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -360,8 +360,7 @@ and branching strategy. 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 + scenarios you don't normally use. 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 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..c7d1ab3fd 100644 --- a/SUPPORTERS.md +++ b/SUPPORTERS.md @@ -21,45 +21,51 @@ thanks to everyone who contributed! * Eric Betts * Ernesto Martinez * Franziska Kunsmann - * GadgetAngel * George Robles * Greg Holloway * Hog Duske + * Hopewell Medical Acupuncture Center * Hugh Blemings * jean-claude migneault + * Jefferson Hunt * Jeremy Cole * Joe Pasqua - * John Robinson + * John Gregory Robinson * Joshua Wills * Justin Kaufman * Kaile Riser * Kale Stedman * Kazuhiro Ogura + * Kelly C McNiece * Kenneth Jiang * Kurt Wubbels * Kyle Menigoz * LA 3D Printer Repair * Lee Dohm + * Loyal Moses * Makespace Madrid * Mark Walker * Michael Aumock + * Michael Begala * Miles Flavel * Mosaic Manufacturing * Neil R. Goldberg + * Patrick Glyré * Patrick McGinnis * Prof Yuh Wen Chen * Raise3D * Randy C. Will * Ranjib Dey + * Richard McGuire * Richard Michaud + * Rigid3D * Robert Gusek * Ronald Griehsler * Sacha Telgenhof * Sebastien Andrivet * Stefan Krister * Steve Thompson - * Stewart Danos * 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 2116 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/THIRDPARTYLICENSES.md b/THIRDPARTYLICENSES.md index 594251edb..f3c0cb7f9 100644 --- a/THIRDPARTYLICENSES.md +++ b/THIRDPARTYLICENSES.md @@ -12,6 +12,7 @@ * [css-element-queries](https://github.com/marcj/css-element-queries): MIT * [Detect Mobile Browser](http://detectmobilebrowsers.com/): Public Domain * [Flot](http://www.flotcharts.org/): MIT + * [HLS.js](https://github.com/video-dev/hls.js): Apache License 2.0 * [JavaScript MD5](https://github.com/blueimp/JavaScript-MD5): MIT * [JQuery](http://jquery.com/): MIT * [JQuery Bootstrap Wizard](http://github.com/VinceG/twitter-bootstrap-wizard): MIT, GPL (dual licensed) 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/api/datamodel.rst b/docs/api/datamodel.rst index 4f9803e73..bbca4519f 100644 --- a/docs/api/datamodel.rst +++ b/docs/api/datamodel.rst @@ -145,6 +145,31 @@ Temperature offset - Number - Temperature offset for the printer's heated bed. +.. _sec-api-datamodel-printer-resends: + +Resend stats +------------ + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``count`` + - 1 + - int + - Number of resend requests received since connecting. + * - ``transmitted`` + - 1 + - int + - Number of transmitted lines since connecting. + * - ``ratio`` + - 1 + - int + - Percentage of resend requests vs transmitted lines. Value between 0 and 100. .. _sec-api-datamodel-jobs: diff --git a/docs/api/general.rst b/docs/api/general.rst index e47991938..0dacead1d 100644 --- a/docs/api/general.rst +++ b/docs/api/general.rst @@ -18,7 +18,7 @@ authorization workflow implemented by the bundled :ref:`Application Keys Plugin Clients are advised to implement the :ref:`Application Keys Plugin workflow ` first and fallback on directing the user to manually supply the the user specific API key. The global key should rarely be used. -The API key must be supplied in the custom HTTP header ``X-Api-Key``, e.g. +The API key must either be supplied in the custom HTTP header ``X-Api-Key``, e.g. .. sourcecode:: http @@ -26,6 +26,14 @@ The API key must be supplied in the custom HTTP header ``X-Api-Key``, e.g. Host: example.com X-Api-Key: abcdef... +or as a ``Bearer`` token in the ``Authorization`` header, e.g. + +.. sourcecode:: http + + GET /api/files HTTP/1.1 + Host: example.com + Authorization: Bearer abcdef... + For testing purposes it is also possible to supply the API key via a query parameter ``apikey``, e.g. .. sourcecode:: http diff --git a/docs/api/index.rst b/docs/api/index.rst index 9d49f2428..f6e953b38 100644 --- a/docs/api/index.rst +++ b/docs/api/index.rst @@ -9,6 +9,7 @@ REST API general.rst version.rst + server.rst connection.rst files.rst job.rst diff --git a/docs/api/push.rst b/docs/api/push.rst index 59bed82d0..c9c6a4b04 100644 --- a/docs/api/push.rst +++ b/docs/api/push.rst @@ -177,6 +177,15 @@ Data model - 0..* - List of String - Lines for the serial communication log (special messages) + * - ``resends`` + - 1 + - :ref:`Resend stats ` + - Current resend statistics for the connection + * - ``plugins`` + - 0..1 + - Map of plugin identifiers to additional data + - Additional data injected by plugins via the :ref:`octoprint.printer.additional_state_data hook `, + indexed by plugin identifier. Structure of additional data is determined by the plugin. .. _sec-api-push-datamodel-event: diff --git a/docs/api/server.rst b/docs/api/server.rst new file mode 100644 index 000000000..50849e301 --- /dev/null +++ b/docs/api/server.rst @@ -0,0 +1,36 @@ +.. _sec-api-server: + +****************** +Server information +****************** + +.. http:get:: /api/server + + .. versionadded:: 1.5.0 + + Retrieve information regarding server status. Returns a JSON object with two keys, ``version`` containing + the server version and ``safemode`` containing one of ``settings``, ``incomplete_startup`` or ``flag`` + to indicate the reason the server is running in safe mode, or the boolean value of ``false`` if it's not + running in safe mode. + + **Example Request** + + .. sourcecode:: http + + GET /api/server HTTP/1.1 + Host: example.com + X-Api-Key: abcdef... + + **Example Response** + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + { + "server": "1.5.0", + "safemode": "incomplete_startup" + } + + :statuscode 200: No error diff --git a/docs/api/util.rst b/docs/api/util.rst index 3dde7f6ca..bb1271240 100644 --- a/docs/api/util.rst +++ b/docs/api/util.rst @@ -6,8 +6,8 @@ Util .. _sec-api-util-test: -Test paths or URLs -================== +Various tests +============= .. http:post:: /api/util/test @@ -107,6 +107,15 @@ Test paths or URLs The ``resolution`` command returns :http:statuscode:`200` with a :ref:`Resolution test result ` when the test could be performed. The status code of the response does NOT reflect the test result! + address + Tests whether a provided address (or, if none is provided, the client's remote address) is + a LAN address and if so returns the subnet specifier in CIDR format. + + * ``address``: the address to test. If not set, the client's remote address will be used + + The ``address`` command return :http:statuscode:`200` with a :ref:`Address test result ` + when the test could be performed. The status code of the response does NOT reflect the test result! + Requires the ``ADMIN`` permission. **Example 1** @@ -320,6 +329,58 @@ Test paths or URLs "result": true } + **Example 8** + + Test whether the client's address is a LAN address. + + .. sourcecode:: http + + POST /api/util/test HTTP/1.1 + Host: example.com + X-Api-Key: abcdef... + Content-Type: application/json + + { + "command": "address" + } + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + { + "address": "192.168.1.3", + "is_lan_address": true, + "subnet": "192.168.0.0/16" + } + + **Example 9** + + Test whether ``8.8.8.8`` is a LAN address. + + .. sourcecode:: http + + POST /api/util/test HTTP/1.1 + Host: example.com + X-Api-Key: abcdef... + Content-Type: application/json + + { + "command": "address", + "address": "8.8.8.8" + } + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + { + "address": "8.8.8.8", + "is_lan_address": false + } + :json command: The command to execute, currently either ``path`` or ``url`` :json path: ``path`` command only: the path to test :json check_type: ``path`` command only: the type of path to test for, either ``file`` or ``dir`` @@ -337,6 +398,7 @@ Test paths or URLs :json port: ``server`` command only: the port to test :json protocol: ``server`` command only: the protocol to test :json name: ``resolution`` command only: the host name to test + :json address: ``address`` command only: the address to test :statuscode 200: No error occurred .. _sec-api-util-datamodel: @@ -466,3 +528,29 @@ Resolution test result - 1 - bool - ``true`` if the check passed. + +.. _sec-api-util-datamodel-addresstestresult: + +Address test result +------------------- + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``address`` + - 1 + - string + - The address that was tested. + * - ``is_lan_address`` + - 1 + - bool + - ``true`` if the address is a LAN address, false otherwise. + * - ``subnet`` + - 0..1 + - string + - The detected subnet, if address is a LAN address. diff --git a/docs/api/version.rst b/docs/api/version.rst index 9716139c4..61154cced 100644 --- a/docs/api/version.rst +++ b/docs/api/version.rst @@ -6,7 +6,7 @@ Version information .. http:get:: /api/version - Retrieve information regarding server and API version. Returns a JSON object with two keys, ``api`` containing + Retrieve information regarding server and API version. Returns a JSON object with three keys, ``api`` containing the API version, ``server`` containing the server version, ``text`` containing the server version including the prefix ``OctoPrint `` (to determine that this is indeed a genuine OctoPrint instance). diff --git a/docs/bundledplugins/action_command_notification.rst b/docs/bundledplugins/action_command_notification.rst index aff4d75be..fb3b50277 100644 --- a/docs/bundledplugins/action_command_notification.rst +++ b/docs/bundledplugins/action_command_notification.rst @@ -3,7 +3,9 @@ Action Command Notification support =================================== -The OctoPrint Action Command Notification Support Plugin comes bundled with OctoPrint (starting with 1.4.1). +.. versionadded:: 1.4.1 + +The OctoPrint Action Command Notification Support Plugin comes bundled with OctoPrint. It allows firmware to trigger notifications users with the ``PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW`` permission using :ref:`action commands ` about relevant events. These notifications will be shown diff --git a/docs/bundledplugins/action_command_prompt.rst b/docs/bundledplugins/action_command_prompt.rst index 247f741ff..b4e09d623 100644 --- a/docs/bundledplugins/action_command_prompt.rst +++ b/docs/bundledplugins/action_command_prompt.rst @@ -3,7 +3,9 @@ Action Command Prompt support ============================= -The OctoPrint Action Command Prompt Support Plugin comes bundled with OctoPrint (starting with 1.3.9). +.. versionadded:: 1.3.9 + +The OctoPrint Action Command Prompt Support Plugin comes bundled with OctoPrint. It allows firmware to trigger dialog prompts for logged in users using :ref:`action commands `, e.g. to wait for user acknowledgement or allow the user to choose between options, and also to close the dialog again @@ -72,8 +74,7 @@ To display the :ref:`above dialog `_ - can be automatically restored. If you have plugins installed that are not available on there you'll get their - names and - if available - homepage URL displayed after restore in order to be able to manually reinstall them. +.. [#1] Note that restore is currently unavailable on OctoPrint servers running on Windows. Additionally they may be + disabled through a config flag or an environment variable as documented :ref:`here `. +.. [#2] Note that only those plugins that are available on `OctoPrint's official plugin repository `_ + can be automatically restored. If you have plugins installed that are not available on there you'll get their + names and - if available - homepage URL displayed after restore in order to be able to manually reinstall them. diff --git a/docs/bundledplugins/discovery.rst b/docs/bundledplugins/discovery.rst index 52314cb5f..1bc8fac22 100644 --- a/docs/bundledplugins/discovery.rst +++ b/docs/bundledplugins/discovery.rst @@ -3,11 +3,12 @@ Discovery Plugin ================ -The OctoPrint Discovery Plugin comes bundled with OctoPrint (starting with 1.2.0). +.. versionadded:: 1.2.0 -It allows discovery of the OctoPrint instances via SSDP/UPNP. If -`pybonjour `_ is installed OctoPrint -will additionally support discovery via ZeroConf, also known as Bonjour or Avahi. +The OctoPrint Discovery Plugin comes bundled with OctoPrint. + +It allows discovery of the OctoPrint instances via SSDP/UPNP and ZeroConf +(also known as Bonjour or Avahi). The SSDP/UPNP support allows OctoPrint to announce itself to machines on the same network running Microsoft Windows. You will be able to just double click on the @@ -28,45 +29,6 @@ line) to scan for available instances. Various discovered OctoPrint instances in Windows Explorer -.. _sec-bundledplugins-discovery-firststeps: - -First Steps ------------ - -.. _sec-bundledplugins-discovery-firststeps-pybonjour: - -Installing pybonjour -++++++++++++++++++++ - -.. note:: - - OctoPi versions 0.12.0 and later already come with pybonjour installed and ready to go, - you don't need to perform these steps there. - -.. note:: - - Currently there are no releases for pybonjour available on the Python Package Index PyPI. The latest pybonjour - release is still available in the `Google Code Archive `_. - Since that URL is hilariously long though, a shortened version is provided with https://goo.gl/SxQZ06 and - used in the installation instructions below. - -In order for the Zeroconf discovery to work, the -`pybonjour package `_ needs to be available -to the Python installation running OctoPrint. - -It can be installed via ``pip``. Let's assume you installed OctoPrint manually -into some folder ``~/OctoPrint``. You executed ``python setup.py install`` within a -virtualenv in the same folder called ``venv``. In order to install ``pybonjour`` -so it will be available to OctoPrint you'll need to do the following:: - - venv/bin/pip install https://goo.gl/SxQZ06 - -**Linux users:** You'll need to install an additional dependency for this to work, the -libdnssd compatibility layer for libavahi. On Debian/Ubuntu that can be achieved with:: - - sudo apt-get install libavahi-compat-libdnssd-dev - - .. _sec-bundledplugins-discovery-configuration: Configuring the plugin @@ -74,6 +36,10 @@ Configuring the plugin The plugin supports the following configuration keys: + * ``addresses``: List of IP addresses for which to enable discovery, if unset all + addresses available on the host will be used + * ``interfaces``: List of network interfaces for which to enable discovery, if unset + all interfaces on the host will be used * ``publicPort``: Public port number OctoPrint is reachable under, optional, if not set the port OctoPrint itself was started under will be used * ``pathPrefix``: Path prefix OctoPrint is running under, optional, if not @@ -128,6 +94,8 @@ The following snippet is a valid configuration example for the discovery plugin plugins: discovery: + interfaces: + - eth0 publicPort: 443 useSsl: true zeroConf: diff --git a/docs/bundledplugins/errortracking.rst b/docs/bundledplugins/errortracking.rst index f87e7e8b2..71f423430 100644 --- a/docs/bundledplugins/errortracking.rst +++ b/docs/bundledplugins/errortracking.rst @@ -3,6 +3,8 @@ Error Tracking Plugin ===================== +.. versionadded:: 1.3.11 + The Error Tracking plugin will cause any logged exceptions in the server and the browser interface to be sent to OctoPrint's `Sentry instance `_. diff --git a/docs/bundledplugins/file_check.rst b/docs/bundledplugins/file_check.rst index 814066697..7be2b3baf 100644 --- a/docs/bundledplugins/file_check.rst +++ b/docs/bundledplugins/file_check.rst @@ -3,5 +3,7 @@ File Check ========== +.. versionadded:: 1.4.1 + The file check plugin - while considered bundled with OctoPrint - is a separate project on its own release cycle and documented on `its Github repository `_. diff --git a/docs/bundledplugins/firmware_check.rst b/docs/bundledplugins/firmware_check.rst index c7e95facc..e73a3b9ab 100644 --- a/docs/bundledplugins/firmware_check.rst +++ b/docs/bundledplugins/firmware_check.rst @@ -3,5 +3,9 @@ Firmware Check ============== +.. versionadded:: 1.3.7 + The firmware check plugin - while considered bundled with OctoPrint - is a separate project on its own release cycle and documented on `its Github repository `_. + +It was formerly called "Printer Safety Check" and directly bundled with OctoPrint. diff --git a/docs/bundledplugins/gcodeviewer.rst b/docs/bundledplugins/gcodeviewer.rst index 2531f7533..704d04213 100644 --- a/docs/bundledplugins/gcodeviewer.rst +++ b/docs/bundledplugins/gcodeviewer.rst @@ -3,6 +3,8 @@ GCode Viewer Plugin =================== +.. versionchanged:: 1.4.1 + The GCode Viewer plugin provides a GCode viewer based on `Alex Ustyantsev's work `_. .. _fig-bundledplugins-gcodeviewer-example: diff --git a/docs/bundledplugins/index.rst b/docs/bundledplugins/index.rst index 2a802a0b8..a1d858616 100644 --- a/docs/bundledplugins/index.rst +++ b/docs/bundledplugins/index.rst @@ -19,7 +19,6 @@ Bundled Plugins firmware_check.rst gcodeviewer.rst logging.rst - loginui.rst pluginmanager.rst printer_safety_check.rst softwareupdate.rst diff --git a/docs/bundledplugins/logging.rst b/docs/bundledplugins/logging.rst index d06d7915c..86d925fb6 100644 --- a/docs/bundledplugins/logging.rst +++ b/docs/bundledplugins/logging.rst @@ -3,9 +3,9 @@ Logging ======= -The OctoPrint Logging plugin comes bundled with OctoPrint starting with version 1.3.7. +.. versionadded:: 1.3.7 -It implements the log management functionality that was formerly part of the core application and adds features to +The OctoPrint Logging plugin implements the log management functionality that was formerly part of the core application and adds features to configure logging levels for sub modules through the included settings dialog. .. _fig-bundledplugins-logging-settings: diff --git a/docs/bundledplugins/loginui.rst b/docs/bundledplugins/loginui.rst index 1da03ce31..4697cd7d3 100644 --- a/docs/bundledplugins/loginui.rst +++ b/docs/bundledplugins/loginui.rst @@ -3,64 +3,4 @@ Login UI ======== -The Login UI plugin has been bundled since OctoPrint 1.4.0 and replaces the ForceLogin plugin bundled with prior -versions since 1.3.10. - -If anonymous read-only access is disabled in the :ref:`Access Control settings ` -it provides a stand alone login dialog that gets displayed instead of OctoPrint's regular UI. - -.. _fig-bundledplugins-loginui: -.. figure:: ../images/bundledplugins-loginui-dialog.png - :align: center - :alt: Login dialog - - OctoPrint's login dialog. - -The plugin allows theming of the dialog through :ref:`a plugin hook `. - -.. warning:: - - Since the plugin is absolutely required for the case of anonymous read-only access because in this case the - UI itself could not even fully initialize due to a lack of permissions required to do so, it is hidden in the plugin - manager and cannot be disabled through that. - -.. _sec-bundledplugins-loginui-hooks: - -Hooks ------ - -.. _sec-bundledplugins-loginui-hooks-theming: - -octoprint.plugin.loginui.theming -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. py:function:: loginui_theming_hook(*args, **kwargs) - - Support theming of the login dialog, just in case the core UI is themed as well. Use to return a list of additional - CSS file URLs to inject into the login dialog HTML. - - Example usage by a plugin: - - .. code-block:: python - - def loginui_theming(): - from flask import url_for - return [url_for("plugin.myplugin.static", filename="css/loginui_theme.css")] - - __plugin_hooks__ = { - "octoprint.plugin.loginui.theming": loginui_theming - } - - Only a list of ready-made URLs to CSS files is supported, neither LESS nor JS. Best use - url_for like in the example above to be prepared for any configured prefix URLs. - - :return: A list of additional CSS URLs to inject into the login dialog. - :rtype: A list of strings. - -.. _sec-bundledplugins-loginui-sourcecode: - -Source Code ------------ - -The source of the Anonymous Usage Tracking plugin is bundled with OctoPrint and can be -found in its source repository under ``src/octoprint/plugins/loginui``. +The Login UI plugin's functionality has been merged into OctoPrint's core as of OctoPrint 1.4.2. diff --git a/docs/bundledplugins/pluginmanager.rst b/docs/bundledplugins/pluginmanager.rst index 2ec1babbb..82eb6f393 100644 --- a/docs/bundledplugins/pluginmanager.rst +++ b/docs/bundledplugins/pluginmanager.rst @@ -3,8 +3,9 @@ Plugin Manager ============== -The OctoPrint Plugin Manager comes bundled with OctoPrint starting with -version 1.2.0. +.. versionadded:: 1.2.0 + +The OctoPrint Plugin Manager comes bundled with OctoPrint. It allows management of installed plugins (listing, enabling, disabling and uninstalling) and installing new plugins from the official diff --git a/docs/bundledplugins/softwareupdate.rst b/docs/bundledplugins/softwareupdate.rst index 0106839e5..f18a3807b 100644 --- a/docs/bundledplugins/softwareupdate.rst +++ b/docs/bundledplugins/softwareupdate.rst @@ -3,10 +3,14 @@ Software Update Plugin ====================== +.. versionadded:: 1.2.0 + The Software Update Plugin allows receiving notifications about new releases of OctoPrint or installed plugins which registered with it and -- if properly configured -- also applying the found updates. +It comes bundled with OctoPrint. + .. _sec-bundledplugins-softwareupdate-firststeps: First Steps @@ -24,7 +28,7 @@ Settings Dialog, navigate to the Software Update section therein and once you ar wrench icon in the upper right corner. .. _fig-bundledplugins-softwareupdate-plugin-configuration: -.. figure:: ../images/bundledplugins-softwareupdate-plugin-configuration.png +.. figure:: ../images/bundledplugins-softwareupdate-configuration.png :align: center :alt: Software Update plugin configuration dialog @@ -34,21 +38,25 @@ There you can adjust the following settings: * **OctoPrint version tracking**: Whether you want to track OctoPrint *releases* or every *commit*. Usually you want to select "Release" here which is also the default, unless you are a developer. - * **OctoPrint Release Channel** (if tracking releases): The release channel of OctoPrint to track for updates. If you only want stable versions, - select "Stable" here which is also the default. "Maintenance RCs" will also allow you to update to maintenance release - candidates, "Devel RCs" will also allow you to update to development release candidates. If in doubt, leave it at - "Stable". `Read more about Release Channels here `_. - * **OctoPrint checkout folder** (if tracking git commits): This must be the path to OctoPrint's git checkout folder + * **Tracked branch** (if tracking is set to "Github Commit"): The branch that will be tracked if you set version tracking to "Github Commit". + * **OctoPrint ``pip`` target** (if tracking is set to "Release" or "Github Commit"): The argument that will be provided to ``pip`` when updating OctoPrint. + Usually you don't want to change this from its default value of ``https://github.com/OctoPrint/OctoPrint/archive/{target_version}.zip``. + * **OctoPrint checkout folder** (if tracking is set to "Local checkout"): This must be the path to OctoPrint's git checkout folder (``/home/pi/OctoPrint`` for OctoPi or `manual installs following the Raspberry Pi setup guide `_). Note that since OctoPrint 1.3.6 you will no longer need to set this to be able to update to releases, only if you want to be able to update against some bleeding edge git branch. + * **Enable ``pip`` update checks**: Whether to have OctoPrint automatically check for updates of + the ``pip`` tool that is used for updating most components. * **Version cache TTL**: The "time to live" of the cache OctoPrint will use to temporarily persist the version information for the various components registered with the plugin, so that they don't have to be queried from the internet every time you load the page. Defaults to 24h, you usually shouldn't need to change that value. + * **Show notifications to users**: Whether to display update notifications (without "Update now" button) to users that cannot + apply updates. + * **Minimum free disk space**: The minimum amount of free disk space needed in order to allow software updates to be run. More settings are available by :ref:`editing the corresponding section in config.yaml `. -That restart commands for OctoPrint and the whole server can be configured under Settings > Server. +Restart commands for OctoPrint and the whole server can be configured under Settings > Server. .. _sec-bundledplugins-softwareupdate-cli: @@ -119,9 +127,6 @@ Configuring the Plugin plugins: softwareupdate: - # the time-to-live of the version cache, in minutes - cache_ttl: 60 - # configured version check and update methods checks: # "octoprint" is reserved for OctoPrint @@ -141,6 +146,41 @@ Configuring the Plugin # used - should normally NOT be necessary and hence set pip_command: /path/to/pip + # the time-to-live of the version cache, in minutes, defaults to 24h + cache_ttl: 1440 + + # whether to show update notifications to users that cannot apply updates + notify_users: true + + # whether to ignore the system throttled state reported by the pisupport plugin and + # allow updating even when the system is not running stable - really not recommended + ignore_throttled: false + + # minimum free storage in MB for updates to be enabled + minimum_free_storage: 150 + + # URL from which to fetch check overlays + check_overlay_url: https://plugins.octoprint.org/update_check_overlay.json + + # time to live of the overlay cache, defaults to 6h + check_overlay_ttl: 360 + + # global credentials to provide to version checks + credentials: + + # GitHub API token to use for the github_release and github_commit version checks. + # Helpful if you regularly run into rate limit issues with the GitHub API using + # the default anonymous access. Use a personal access token: + # https://docs.github.com/en/free-pro-team@latest/github/authenticating-to-github/creating-a-personal-access-token + # Unset by default + github: + + # Bitbucket user name and password, used by the bitbucket_commit version check if + # provided, but only if the check doesn't specify credentials on its own. + # Unset by default + bitbucket_user: + bitbucket_password: + .. _sec-bundledplugins-softwareupdate-configuration-versionchecks: Version checks @@ -163,6 +203,7 @@ types are currently recognized: field in Github release data - release will only be included if the values match. Defaults to being unset, in which case the ``branch`` will be matched. + .. versionadded:: 1.2.16 * ``stable_branch``: Stable channel definition, optional. Structure: * ``branch``: Branch associated with the channel, acts as ID * ``name``: Human readable name of the release channel @@ -170,11 +211,13 @@ types are currently recognized: field in Github release data - release will only be included if the values match. Defaults to being unset, in which case the ``branch`` will be matched. + .. versionadded:: 1.2.16 * ``prerelease_channel``: Release channel to limit updates to. If set only those releases will be included if their ``target_comittish`` matches the ones associated with the release channel identified by this, either included in ``prerelease_channels`` or the ``stable_channel``. Only taken into account if ``prerelease`` is ``true``. + .. versionadded:: 1.2.16 * ``release_compare``: Method to use to compare between current version information and release versions on Github. One of ``python`` (version comparison using ``pkg_resources.parse_version``, newer version detected @@ -208,6 +251,8 @@ types are currently recognized: ``api_user`` to be set. **Important**: Never use your actual Bitbucket login password. Generate a new app password. App passwords are user specific on Bitbucket. + .. versionadded:: 1.3.5 + * ``git_commit``: Checks a local git repository for new commits on its configured remote. Additional config parameters: @@ -219,6 +264,8 @@ types are currently recognized: * ``package``: (mandatory) Name of the package which to check. + .. versionadded:: 1.4.0 + * ``httpheader``: Checks an HTTP header on a defined URL for changes. This can be used for easy checks against things like ``ETag`` or ``Last-Modified`` headers. Additional config parameters: @@ -230,12 +277,16 @@ types are currently recognized: * ``header_prefix``: Prefix to use for the obtained value in the version display. If not provided ``header_name`` will be used. If set to an empty string, no prefix will be added. + .. versionadded:: 1.4.1 + * ``jsondata``: Checks the provided JSON endpoint for changes. The JSON endpoint must return an object with the property ``version``, which should contain the latest version, e.g. ``{"version":"1.2.3"}``. Additional config parameters: * ``jsondata``: (mandatory) URL from which to fetch the JSON data + .. versionadded:: 1.4.1 + * ``command_line``: Uses a provided script to determine whether an update is available. Additional config parameters: @@ -258,12 +309,16 @@ types are currently recognized: * ``current_version``: Version to report for both local and remote version. + .. versionadded:: 1.3.7 + * ``never_current``: Always reports that an update is necessary. Useful for debugging software update mechanisms during development. Additional config parameters: * ``local_version``: Current local version. Defaults to ``1.0.0``. * ``remote_version``: Remote version to offer update to. Defaults to ``1.0.1``. + .. versionadded:: 1.3.7 + .. _sec-bundledplugins-softwareupdate-configuration-updatemethods: Update methods @@ -309,6 +364,8 @@ supported: a countdown in the meantime. Useful for debugging software update mechanisms during development. + .. versionadded:: 1.3.7 + .. note:: To allow default configurations for multiple update methods, if more than one of @@ -480,6 +537,28 @@ commit identifier. E.g. ``https://gist.githubusercontent.com///raw ``https://gist.githubusercontent.com///raw//my_plugin.py``. Note that these URLs will be cached by Github for a bit, so an update will not be immediately picked up. +.. _sec-bundledplugins-softwareupdate-configuration-credentials: + +Global credentials +++++++++++++++++++ + +.. versionadded:: 1.5.0 + +Starting with OctoPrint 1.5.0, the Software Update Plugin supports supplyting a GitHub +API token to use for the ``github_release`` and ``github_commit`` version check types, +to work around possible rate limit problems if a lot of checks are to be made from a single +external IP. You may create a `personal access token `_ +and configure that as ``plugins.softwareupdate.credentials.github`` via +:ref:`config.yaml ` in order to get a higher rate limit than with purely anonymous access. + +Additionally, the username and password to use with the ``bitbucket_commit`` version check +type may also be configured via ``plugins.softwareupdate.credentials.bitbucket_user`` and +``plugins.softwareupdate.credentials.bitbucket_password`` respectively. + +None of these configuration options are currently exposed on the UI and can only be used +via :ref:`config.yaml ` or the +:ref:`config command line interface `. + .. _sec-bundledplugins-softwareupdate-events: Events diff --git a/docs/bundledplugins/tracking.rst b/docs/bundledplugins/tracking.rst index 4864deb6f..8c29a3bac 100644 --- a/docs/bundledplugins/tracking.rst +++ b/docs/bundledplugins/tracking.rst @@ -3,6 +3,8 @@ Anonymous Usage Tracking Plugin =============================== +.. versionadded:: 1.3.10 + The Anonymous Usage Tracking plugin provides valuable insights into how many instances running what versions of OctoPrint are out there, whether they are successfully completing print jobs and various other metrics. diff --git a/docs/bundledplugins/virtual_printer.rst b/docs/bundledplugins/virtual_printer.rst index e4ec0c48e..bc1ba147a 100644 --- a/docs/bundledplugins/virtual_printer.rst +++ b/docs/bundledplugins/virtual_printer.rst @@ -3,6 +3,8 @@ Virtual Printer =============== +.. versionchanged:: 1.4.1 + The Virtual Printer plugin provides a virtual printer to connect to during development. It is able to simulate various firmware quirks, communication issues and can be heavily configured through ``config.yaml``. See :ref:`the development documentation on details and usage `. 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/configuration/cli.rst b/docs/configuration/cli.rst new file mode 100644 index 000000000..b24d13865 --- /dev/null +++ b/docs/configuration/cli.rst @@ -0,0 +1,110 @@ +.. _sec-configuration-cli: + +CLI +=== + +.. versionadded:: 1.3.0 + +OctoPrint provides a basic command line interface for manipulation of :ref:`config.yaml `: + +.. code-block:: + + $ octoprint config --help + Usage: octoprint config [OPTIONS] COMMAND [ARGS]... + + Basic config manipulation. + + Options: + --help Show this message and exit. + + Commands: + append_value Appends value to list behind config path. + effective Retrieves the full effective config. + get Retrieves value from config path. + insert_value Inserts value at index of list behind config key. + remove Removes a config path. + remove_value Removes value from list at config path. + set Sets a config path to the provided value. + +.. code-block:: + + $ octoprint config append_value --help + Usage: octoprint config append_value [OPTIONS] PATH VALUE + + Appends value to list behind config path. + + Options: + --json + --help Show this message and exit. + +.. code-block:: + + $ octoprint config effective --help + Usage: octoprint config effective [OPTIONS] + + Retrieves the full effective config. + + Options: + --json Output value formatted as JSON + --yaml Output value formatted as YAML + --raw Output value as raw string representation + --help Show this message and exit. + +.. code-block:: + + $ octoprint config get --help + Usage: octoprint config get [OPTIONS] PATH + + Retrieves value from config path. + + Options: + --json Output value formatted as JSON + --yaml Output value formatted as YAML + --raw Output value as raw string representation + --help Show this message and exit. + +.. code-block:: + + $ octoprint config insert_value --help + Usage: octoprint config insert_value [OPTIONS] PATH INDEX VALUE + + Inserts value at index of list behind config key. + + Options: + --json + --help Show this message and exit. + +.. code-block:: + + $ octoprint config remove --help + Usage: octoprint config remove [OPTIONS] PATH + + Removes a config path. + + Options: + --help Show this message and exit. + +.. code-block:: + + $ octoprint config remove_value --help + Usage: octoprint config remove_value [OPTIONS] PATH VALUE + + Removes value from list at config path. + + Options: + --json + --help Show this message and exit. + +.. code-block:: + + $ octoprint config set --help + Usage: octoprint config set [OPTIONS] PATH VALUE + + Sets a config path to the provided value. + + Options: + --bool Interpret value as bool + --float Interpret value as float + --int Interpret value as int + --json Parse value from json + --help Show this message and exit. diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index 3ab20a8e6..7b8a949eb 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -10,6 +10,7 @@ you can just create it - it will only get created by OctoPrint once you save set settings. Note that many of these settings are available from the "Settings" menu in OctoPrint itself. +They can also be configured via :ref:`config command line interface `. .. contents:: @@ -23,9 +24,6 @@ Use the following settings to enable access control: .. code-block:: yaml accessControl: - # whether to enable access control or not. Defaults to true - enabled: true - # The user manager implementation to use for accessing user information. Currently only a filebased # user manager is implemented which stores configured accounts in a YAML file (Default: users.yaml # in the default configuration folder, see below) @@ -127,6 +125,10 @@ appearance or to modify the order and presence of the various UI components: # acrylic for its frame ;) colorTransparent: false + # Show the internal filename in the files sidebar, if necessary + # UI change only + showInternalFilename: true + # Configures the order and availability of the UI components components: @@ -805,6 +807,9 @@ Use the following settings to configure the serial connection to the printer: # the response skips on the ok) triggerOkForM29: true + # Percentage of resend requests among all sent lines that should be considered critical + resendRatioThreshold: 10 + capabilities: # Whether to enable temperature autoreport in the firmware if its support is detected @@ -944,6 +949,12 @@ Use the following settings to configure the server: # Command to shut down the system OctoPrint is running on, defaults to being unset systemShutdownCommand: sudo shutdown -h now + # pip command associated with OctoPrint, used for installing plugins and updates, + # if unset (default) the command will be autodetected based on the current python + # executable - unless you have a really special setup this is the right way to do + # it and there should be no need to ever even touch this setting + localPipCommand: None + # Configuration of the regular online connectivity check onlineCheck: # whether the online check is enabled, defaults to false due to valid privacy concerns @@ -1126,6 +1137,8 @@ Use `Javascript regular expressions - # False: - extendedSdFileList: false + # Settings related to the SD file list output + sdFiles: + # Whether M20 responses will include filesize or not + # + # True: + # False: + size: true + + # Whether M20 responses will include longname or not (only if size = true as well) + # + # True: + # False: + longname: false # Forced pause for retrieving from the outgoing buffer throttle: 0.01 diff --git a/docs/events/index.rst b/docs/events/index.rst index fe24e847f..7fa5e733e 100644 --- a/docs/events/index.rst +++ b/docs/events/index.rst @@ -109,6 +109,9 @@ ClientOpened **Note:** Name changed in version 1.1.0 + .. versionchanged:: 1.1.0 + .. versionchanged:: 1.4.0 + ClientAuthed A client has authenticated a user session on the push socket. @@ -118,6 +121,8 @@ ClientAuthed valid login session. * ``username``: the name of the user who authed. On the push socket only available with a valid login session. + .. versionadded:: 1.4.0 + ClientClosed A client has disconnected from the push socket. @@ -133,12 +138,16 @@ UserLoggedIn * ``username``: the name of the user who logged in + .. versionadded:: 1.4.0 + UserLoggedOut A user logged out. On the push socket only available with a valid login session with admin rights. Payload: * ``username``: the name of the user who logged out + .. versionadded:: 1.4.0 + ConnectivityChanged The server's internet connectivity changed @@ -147,6 +156,8 @@ ConnectivityChanged * ``old``: Old connectivity value (true for online, false for offline) * ``new``: New connectivity value (true for online, false for offline) + .. versionadded:: 1.3.5 + .. _sec-events-available_events-printer_commmunication: Printer communication @@ -155,6 +166,8 @@ Printer communication Connecting The server is attempting to connect to the printer. + .. versionadded:: 1.3.0 + Connected The server has connected to the printer. @@ -168,6 +181,8 @@ Disconnecting event might not always be sent when the server and printer get disconnected from each other. Do not depend on this for critical life cycle management. + .. versionadded:: 1.3.0 + Disconnected The server has disconnected from the printer @@ -191,6 +206,8 @@ PrinterStateChanged :func:`~octoprint.printer.PrinterInterface.get_state_id` for possible values. * ``state_string``: Text representation of the new state. + .. versionadded:: 1.3.0 + .. _sec-events-available_events-file_handling: File handling @@ -211,6 +228,8 @@ Upload * ``file``: the file's path within its storage location. To be removed in 1.4.0. + .. versionchanged:: 1.4.0 + FileAdded A file has been added to a storage. @@ -226,6 +245,8 @@ FileAdded A copied file triggers this for its new path. A moved file first triggers ``FileRemoved`` for its original path and then ``FileAdded`` for the new one. + .. versionadded:: 1.3.3 + FileRemoved A file has been removed from a storage. @@ -240,6 +261,8 @@ FileRemoved A moved file first triggers ``FileRemoved`` for its original path and then ``FileAdded`` for the new one. + .. versionadded:: 1.3.3 + FolderAdded A folder has been added to a storage. @@ -253,6 +276,8 @@ FolderAdded A copied folder triggers this for its new path. A moved folder first triggers ``FolderRemoved`` for its original path and then ``FolderAdded`` for the new one. + .. versionadded:: 1.3.3 + FolderRemoved A folder has been removed from a storage. @@ -265,6 +290,8 @@ FolderRemoved A moved folder first triggers ``FolderRemoved`` for its original path and then ``FolderAdded`` for the new one. + .. versionadded:: 1.3.3 + UpdatedFiles A file list was modified. @@ -279,6 +306,7 @@ UpdatedFiles reasons of backwards compatibility and will also be sent on modification of ``printables``. It will however be removed with 1.4.0. + .. versionchanged:: 1.4.0 MetadataAnalysisStarted The metadata analysis of a file has started. @@ -293,6 +321,8 @@ MetadataAnalysisStarted * ``file``: the file's path within its storage location. To be removed in 1.4.0. + .. versionchanged:: 1.4.0 + MetadataAnalysisFinished The metadata analysis of a file has finished. @@ -307,6 +337,8 @@ MetadataAnalysisFinished * ``file``: the file's path within its storage location. To be removed in 1.4.0. + .. versionchanged:: 1.4.0 + FileSelected A file has been selected for printing. @@ -321,6 +353,8 @@ FileSelected * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0. * ``filename``: the file's name. To be removed in 1.4.0. + .. versionchanged:: 1.4.0 + FileDeselected No file is selected any more for printing. @@ -334,6 +368,8 @@ TransferStarted **Note:** Name changed in version 1.1.0 + .. versionchanged:: 1.1.0 + TransferDone A file transfer to the printer's SD has finished. @@ -365,6 +401,8 @@ PrintStarted * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0. * ``filename``: the file's name. To be removed in 1.4.0. + .. versionchanged:: 1.4.0 + PrintFailed A print failed. @@ -383,6 +421,8 @@ PrintFailed * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0. * ``filename``: the file's name. To be removed in 1.4.0. + .. versionchanged:: 1.4.0 + PrintDone A print completed successfully. @@ -400,6 +440,8 @@ PrintDone * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0. * ``filename``: the file's name. To be removed in 1.4.0. + .. versionchanged:: 1.4.0 + PrintCancelling The print is about to be cancelled. @@ -413,6 +455,8 @@ PrintCancelling * ``user``: the user who cancelled the print job (if available) * ``firmwareError``: the firmware error that caused cancelling the print job, if any + .. versionadded:: 1.3.7 + PrintCancelled The print has been cancelled. @@ -443,6 +487,8 @@ PrintCancelled * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0. * ``filename``: the file's name. To be removed in 1.4.0. + .. versionchanged:: 1.4.0 + PrintPaused The print has been paused. @@ -472,6 +518,8 @@ PrintPaused * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0. * ``filename``: the file's name. To be removed in 1.4.0. + .. versionchanged:: 1.4.0 + PrintResumed The print has been resumed. @@ -489,6 +537,8 @@ PrintResumed * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0. * ``filename``: the file's name. To be removed in 1.4.0. + .. versionchanged:: 1.4.0 + .. _sec-events-available_events-gcode_processing: GCODE processing @@ -543,6 +593,8 @@ PositionUpdate * ``t``: last tool selected *through OctoPrint* * ``f``: last feedrate for move commands ``G0``, ``G1`` or ``G28`` sent *through OctoPrint* + .. versionadded:: 1.3.0 + ToolChange A tool change command was sent to the printer. The payload contains the former current tool index and the new current tool index. @@ -552,6 +604,34 @@ ToolChange * ``old``: old tool index * ``new``: new tool index + .. versionadded:: 1.3.5 + +CommandSuppressed + A command was suppressed by OctoPrint due to according configuration and will not be + sent to the printer. + + Payload: + + * ``command``: the command that was suppressed + * ``message``: a message containing an explanation of the command suppression + * ``severity``: a severity level, either ``warn`` or ``info`` - ``warn`` indicates + that the command was suppressed probably due to a misconfiguration either inside + OctoPrint or the firmware and that it should be investigated by the user + + .. versionadded:: 1.5.0 + +InvalidToolReported + The firmware reported a tool as invalid upon trying to select it. It has thus been marked + as invalid and further attempts to select said tool will result in the tool command + to get suppressed (and ``SuppressedCommand`` to be generated). + + Payload: + + * ``tool``: the tool number that was reported as invalid by the firmware + * ``fallback``: the tool number that OctoPrint will revert to + + .. versionadded:: 1.5.0 + .. _sec-events-available_events-timelapses: Timelapses @@ -577,6 +657,8 @@ CaptureFailed * ``file``: the name of the image file that should have been saved * ``error``: the error that was caught + .. versionadded:: 1.3.0 + MovieRendering The timelapse movie has started rendering. @@ -669,6 +751,8 @@ SlicingProfileAdded * ``slicer``: the slicer for which the profile was added * ``profile``: the profile that was added + .. versionadded:: 1.2.12 + SlicingProfileModified A slicing profile was modified. @@ -677,6 +761,8 @@ SlicingProfileModified * ``slicer``: the slicer for which the profile was modified * ``profile``: the profile that was modified + .. versionadded:: 1.2.12 + SlicingProfileDeleted A slicing profile was deleted. @@ -685,6 +771,8 @@ SlicingProfileDeleted * ``slicer``: the slicer for which the profile was deleted * ``profile``: the profile that was deleted + .. versionadded:: 1.2.12 + .. _sec-events-available_events-settings: Settings @@ -696,6 +784,8 @@ SettingsUpdated This event may also be triggered if calling code of :py:class:`octoprint.settings.Settings.save` or :py:class:`octoprint.plugin.PluginSettings.save` sets the ``trigger_event`` parameter to ``True``. + .. versionadded:: 1.2.0 + .. _sec-events-available_events-printer_profile: Printer Profile @@ -707,3 +797,6 @@ PrinterProfileModified Payload: * ``identifier``: the identifier of the modified printer profile + + .. versionadded:: 1.3.12 + diff --git a/docs/features/accesscontrol.rst b/docs/features/accesscontrol.rst index 4a85e65b7..ca035d699 100644 --- a/docs/features/accesscontrol.rst +++ b/docs/features/accesscontrol.rst @@ -3,6 +3,8 @@ Access Control ============== +.. versionchanged:: 1.4.0 + OctoPrint's bundled access control feature allows granular permission control over which users or user groups are allowed to access which parts of OctoPrint. diff --git a/docs/features/action_commands.rst b/docs/features/action_commands.rst index 7fcf6063e..6e5f8830a 100644 --- a/docs/features/action_commands.rst +++ b/docs/features/action_commands.rst @@ -21,8 +21,14 @@ Action commands are a feature defined for the GCODE based RepRap communication p OctoPrint out of the box supports handling of the above mentioned commands: +start + When this command is received from the printer, a job is currently selected and *not* active, OctoPrint + will start it just like if the "Start"/"Restart" button had been clicked. + + .. versionadded:: 1.5.0 + cancel - When this command is received from the printer, OctoPrint will cancel a current print job like if the + When this command is received from the printer, OctoPrint will cancel a current print job just like if the "Cancel" button had been clicked. pause diff --git a/docs/features/atcommands.rst b/docs/features/atcommands.rst index a8ead05d2..03d4b863f 100644 --- a/docs/features/atcommands.rst +++ b/docs/features/atcommands.rst @@ -3,6 +3,8 @@ @ Commands ========== +.. versionadded:: 1.3.7 + @ commands (also known as host commands elsewhere) are special commands you may include in GCODE files streamed through OctoPrint to your printer or send as part of GCODE scripts, through the Terminal Tab, the API or plugins. Contrary to other commands they will never be sent to the printer but instead trigger functions inside OctoPrint. diff --git a/docs/features/plugins.rst b/docs/features/plugins.rst index 8e8e26765..f8db01c3d 100644 --- a/docs/features/plugins.rst +++ b/docs/features/plugins.rst @@ -4,6 +4,8 @@ Plugins ******* +.. versionadded:: 1.2.0 + Starting with OctoPrint 1.2.0, there's now a plugin system in place which allows to individually extend OctoPrint's functionality. diff --git a/docs/features/safemode.rst b/docs/features/safemode.rst index 45ec3651c..625b5811e 100644 --- a/docs/features/safemode.rst +++ b/docs/features/safemode.rst @@ -4,6 +4,9 @@ Safe mode ********* +.. versionadded:: 1.3.0 +.. versionchanged:: 1.3.13 + With the advent of support for plugins in OctoPrint, it quickly became apparent that some of the bugs reported on OctoPrint's bug tracker were actually bugs with installed third party plugins or language packs instead of OctoPrint itself. diff --git a/docs/images/bundledplugins-appkeys-settings.png b/docs/images/bundledplugins-appkeys-settings.png index 61b185dac..84c7cd24b 100644 Binary files a/docs/images/bundledplugins-appkeys-settings.png and b/docs/images/bundledplugins-appkeys-settings.png differ diff --git a/docs/images/bundledplugins-softwareupdate-configuration.png b/docs/images/bundledplugins-softwareupdate-configuration.png new file mode 100644 index 000000000..e61544dcd Binary files /dev/null and b/docs/images/bundledplugins-softwareupdate-configuration.png differ diff --git a/docs/images/bundledplugins-softwareupdate-plugin-configuration.png b/docs/images/bundledplugins-softwareupdate-plugin-configuration.png deleted file mode 100644 index ba13a9973..000000000 Binary files a/docs/images/bundledplugins-softwareupdate-plugin-configuration.png and /dev/null differ diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst index ebc8859e1..5863c034b 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -207,6 +207,8 @@ octoprint.access.permissions .. py:function:: additional_permissions_hook(*args, **kwargs) + .. versionadded:: 1.4.0 + Return a list of additional permissions to register in the system on behalf of the plugin. Use this to add granular permissions to your plugin which can be configured for users and user groups in the general access control settings of OctoPrint. @@ -261,6 +263,8 @@ octoprint.access.users.factory .. py:function:: user_manager_factory_hook(components, settings, *args, **kwargs) + .. versionadded:: 1.4.0 + Return a :class:`~octoprint.access.users.UserManager` instance to use as global user manager object. This will be called only once during initial server startup. @@ -295,6 +299,8 @@ octoprint.accesscontrol.keyvalidator .. py:function:: acl_keyvalidator_hook(apikey, *args, **kwargs) + .. versionadded:: 1.3.6 + Via this hook plugins may validate their own customized API keys to be used to access OctoPrint's API. ``apikey`` will be the API key as read from the request headers. @@ -326,6 +332,8 @@ octoprint.cli.commands .. py:function:: cli_commands_hook(cli_group, pass_octoprint_ctx, *args, **kwargs) + .. versionadded:: 1.3.0 + By providing a handler for this hook plugins may register commands on OctoPrint's command line interface (CLI). Handlers are expected to return a list of callables annotated as `Click commands `_ to register with the @@ -449,6 +457,8 @@ octoprint.comm.protocol.firmware.info .. py:function:: firmware_info_hook(comm_instance, firmware_name, firmware_data, *args, **kwargs) + .. versionadded:: 1.3.9 + Be notified of firmware information received from the printer following an ``M115``. Hook handlers may use this to react/adjust behaviour based on reported firmware data. OctoPrint parses the received @@ -482,6 +492,8 @@ octoprint.comm.protocol.firmware.capabilities .. py:function:: firmware_capability_hook(comm_instance, capability, enabled, already_defined, *args, **kwargs) + .. versionadded:: 1.3.9 + Be notified of capability report entries received from the printer. Hook handlers may use this to react to custom firmware capabilities. OctoPrint parses the received capability @@ -507,7 +519,9 @@ octoprint.comm.protocol.firmware.capabilities octoprint.comm.protocol.action ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. py:function:: protocol_action_hook(comm_instance, line, action, *args, **kwargs) +.. py:function:: protocol_action_hook(comm_instance, line, action, name='', params='', *args, **kwargs) + + .. versionadded:: 1.2.0 React to a :ref:`action command ` received from the printer. @@ -534,8 +548,12 @@ octoprint.comm.protocol.action :param object comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook. :param str line: The complete line as received from the printer, format ``// action:`` - :param str action: The parsed out action command, so for a ``line`` like ``// action:some_command`` this will be + :param str action: The parsed out action command incl. parameters, so for a ``line`` like ``// action:some_command key value`` this will be + ``some_command key value`` + :param str name: The action command name, for a ``line`` like ``// action:some_command key value`` this will be ``some_command`` + :param str params: The action command's parameter, for a ``line`` like ``// action:some_command key value`` this will + be ``key value`` .. _sec-plugins-hook-comm-protocol-atcommand-phase: @@ -549,6 +567,8 @@ This describes actually two hooks: .. py:function:: protocol_atcommandphase_hook(comm_instance, phase, command, parameters, tags=None, *args, **kwargs) + .. versionadded:: 1.3.7 + Trigger on :ref:`@ commands ` as they progress through the ``queuing`` and ``sending`` phases of the comm layer. See :ref:`the gcode phase hook ` for a detailed description of each of these phases. @@ -588,7 +608,7 @@ This describes actually two hooks: octoprint.comm.protocol.gcode. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -This describes actually four hooks: +This actually describes four hooks: * ``octoprint.comm.protocol.gcode.queuing`` * ``octoprint.comm.protocol.gcode.queued`` @@ -597,6 +617,8 @@ This describes actually four hooks: .. py:function:: protocol_gcodephase_hook(comm_instance, phase, cmd, cmd_type, gcode, subcode=None, tags=None, *args, **kwargs) + .. versionadded:: 1.2.0 + Pre- and postprocess commands as they progress through the various phases of being sent to the printer. The phases are the following: @@ -750,6 +772,8 @@ octoprint.comm.protocol.gcode.received .. py:function:: gcode_received_hook(comm_instance, line, *args, **kwargs) + .. versionadded:: 1.3.0 + Get the returned lines sent by the printer. Handlers should return the received line or in any case, the modified version of it. If the handler returns None, processing will be aborted and the communication layer will get an empty string as the received line. Note that Python functions will also automatically return ``None`` if an empty @@ -783,6 +807,8 @@ octoprint.comm.protocol.gcode.error .. py:function:: gcode_error_hook(comm_instance, error_message, *args, **kwargs) + .. versionadded:: 1.3.7 + Get the messages of any errors messages sent by the printer, with the leading ``Error:`` or ``!!`` already stripped. Handlers should return True if they handled that error internally and it should not be processed by the system further. Normal processing of these kinds of errors - depending on the configuration of error @@ -820,6 +846,9 @@ octoprint.comm.protocol.scripts .. py:function:: protocol_scripts_hook(comm_instance, script_type, script_name, *args, **kwargs) + .. versionadded:: 1.2.0 + .. versionchanged:: 1.3.7 + Return a prefix to prepend, postfix to append, and optionally a dictionary of variables to provide to the script ``script_name`` of type ``type``. Handlers should make sure to only proceed with returning additional scripts if the ``script_type`` and ``script_name`` match handled scripts. If not, None should be returned directly. @@ -864,6 +893,8 @@ octoprint.comm.protocol.temperatures.received .. py:function:: protocol_temperatures_received_hook(comm_instance, parsed_temperatures, *args, **kwargs) + .. versionadded:: 1.3.6 + Get the parsed temperatures returned by the printer, allowing handlers to modify them prior to handing them off to the system. Handlers are expected to either return ``parsed_temperatures`` as-is or a modified copy thereof. @@ -897,6 +928,8 @@ octoprint.comm.transport.serial.additional_port_names .. py:function:: additional_port_names_hook(candidates, *args, **kwargs) + .. versionadded:: 1.4.1 + Return additional port names (not glob patterns!) to use as a serial connection to the printer. Expected to be ``list`` of ``string``s. @@ -916,6 +949,8 @@ octoprint.comm.transport.serial.factory .. py:function:: serial_factory_hook(comm_instance, port, baudrate, read_timeout, *args, **kwargs) + .. versionadded:: 1.2.0 + Return a serial object to use as serial connection to the printer. If a handler cannot create a serial object for the specified ``port`` (and ``baudrate``), it should just return ``None``. @@ -992,6 +1027,8 @@ octoprint.events.register_custom_events .. py:function:: register_custom_events_hook(*args, **kwargs) + .. versionadded:: 1.3.11 + Return a list of custom :ref:`events ` to register in the system for your plugin. Should return a list of strings which represent the custom events. Their name on the `octoprint.events.Events` object @@ -1020,6 +1057,8 @@ octoprint.filemanager.analysis.factory .. py:function:: analysis_queue_factory_hook(*args, **kwargs) + .. versionadded:: 1.3.9 + Return additional (or replacement) analysis queue factories used for analysing uploaded files. Should return a dictionary to merge with the existing dictionary of factories, mapping from extension tree leaf @@ -1058,6 +1097,8 @@ octoprint.filemanager.extension_tree .. py:function:: file_extension_hook(*args, **kwargs) + .. versionadded:: 1.2.0 + Return additional entries for the tree of accepted file extensions for uploading/handling by the file manager. Should return a dictionary to merge with the existing extension tree, adding additional extension groups to @@ -1094,6 +1135,8 @@ octoprint.filemanager.preprocessor .. py:function:: file_preprocessor_hook(path, file_object, links=None, printer_profile=None, allow_overwrite=False, *args, **kwargs) + .. versionadded:: 1.2.0 + Replace the ``file_object`` used for saving added files to storage by calling :func:`~octoprint.filemanager.util.AbstractFileWrapper.save`. ``path`` will be the future path of the file on the storage. The file's name is accessible via @@ -1121,11 +1164,22 @@ octoprint.filemanager.preprocessor :return: The `file_object` as passed in or None, or a replaced version to use instead for further processing. :rtype: AbstractFileWrapper or None +.. _sec-plugins-hook-plugin-backup-excludes: + +octoprint.plugin.backup.additional_excludes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. versionadded:: 1.5.0 + +See :ref:`here `. + .. _sec-plugins-hook-plugin-loginui-theming: octoprint.plugin.loginui.theming ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. versionadded:: 1.4.0 + See :ref:`here `. .. _sec-plugins-hook-plugin-pluginmanager-reconnect: @@ -1133,6 +1187,8 @@ See :ref:`here `. octoprint.plugin.pluginmanager.reconnect_hooks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. versionadded:: 1.4.0 + See :ref:`here `. .. _sec-plugins-hook-plugin-softwareupdate-check_config: @@ -1140,8 +1196,39 @@ See :ref:`here `. octoprint.plugin.softwareupdate.check_config ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. versionadded:: 1.2.0 + See :ref:`here `. +.. _sec-plugins-hooks-plugin-printer-additional_state_data + +octoprint.printer.additional_state_data +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: additional_state_data_hook(initial=False, *args, **kwargs) + + .. versionadded:: 1.5.0 + + Use this to inject additional data into the data structure returned from the printer backend to the frontend + on the push socket or other registered :ref:`~octoprint.printer.PrinterCallback`s. Anything you return here + will be located beneath ``plugins.`` in the resulting initial and current data push structure. + + The ``initial`` parameter will be ``True`` if this the additional update sent to the callback. Your handler should + return a ``dict``, or ``None`` if nothing should be included. + + .. warning:: + + Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as + you could stall the whole state monitor and thus updates being pushed to the frontend. + + This includes I/O of any kind. + + Cache your data! + + :param boolean initial: True if this is the initial update, False otherwise + :return: Additional data to include + :rtype: dict + .. _sec-plugins-hook-printer-factory: octoprint.printer.factory @@ -1149,6 +1236,8 @@ octoprint.printer.factory .. py:function:: printer_factory_hook(components, *args, **kwargs) + .. versionadded:: 1.3.0 + Return a :class:`~octoprint.printer.PrinterInstance` instance to use as global printer object. This will be called only once during initial server startup. @@ -1180,6 +1269,8 @@ octoprint.printer.estimation.factory .. py:function:: print_time_estimator_factory(*args, **kwargs) + .. versionadded:: 1.3.9 + Return a :class:`~octoprint.printer.estimation.PrintTimeEstimator` subclass (or factory) to use for print time estimation. This will be called on each start of a print or streaming job with a single parameter ``job_type`` denoting the type of job that was just started: ``local`` meaning a print of a local file through the serial connection, @@ -1226,6 +1317,8 @@ octoprint.printer.sdcardupload .. py:function:: sd_card_upload_hook(printer, filename, path, start_callback, success_callback, failure_callback, *args, **kwargs) + .. versionadded:: 1.3.11 + Via this hook plugins can change the way files are being uploaded to the sd card of the printer. Implementations **must** call the provided ``start_callback`` on start of the file transfer and either the ``success_callback`` @@ -1311,6 +1404,8 @@ octoprint.server.api.after_request .. py:function:: after_request_handlers_hook(*args, **kwargs) + .. versionadded:: 1.3.10 + Allows adding additional after-request-handlers to API endpoints defined by OctoPrint itself and installed plugins. Your plugin might need this to further restrict access to API methods. @@ -1326,6 +1421,8 @@ octoprint.server.api.before_request .. py:function:: after_request_handlers_hook(*args, **kwargs) + .. versionadded:: 1.3.10 + Allows adding additional before-request-handlers to API endpoints defined by OctoPrint itself and installed plugins. Your plugin might need this to further restrict access to API methods. @@ -1341,6 +1438,8 @@ octoprint.server.http.access_validator .. py:function:: access_validator_hook(request, *args, **kwargs) + .. versionadded:: 1.3.10 + Allows adding additional access validators to the default tornado routers. Your plugin might need to this to restrict acccess to downloads and webcam snapshots further. @@ -1356,6 +1455,8 @@ octoprint.server.http.bodysize .. py:function:: server_bodysize_hook(current_max_body_sizes, *args, **kwargs) + .. versionadded:: 1.2.0 + Allows extending the list of custom maximum body sizes on the web server per path and HTTP method with custom entries from plugins. @@ -1398,6 +1499,8 @@ octoprint.server.http.routes .. py:function:: server_route_hook(server_routes, *args, **kwargs) + .. versionadded:: 1.2.0 + Allows extending the list of routes registered on the web server. This is interesting for plugins which want to provide their own download URLs which will then be delivered statically @@ -1465,6 +1568,8 @@ octoprint.server.sockjs.authed .. py:function:: socket_authed_hook(socket, user, *args, **kwargs): + .. versionadded:: 1.3.10 + Allows plugins to be notified that a user got authenticated or deauthenticated on the socket (e.g. due to logout). :param object socket: the socket object which is about to be registered @@ -1477,6 +1582,8 @@ octoprint.server.sockjs.register .. py:function:: socket_registration_hook(socket, user, *args, **kwargs): + .. versionadded:: 1.3.10 + Allows plugins to prevent a new :ref:`push socket client ` to be registered to the system. Handlers should return either ``True`` or ``False``. ``True`` signals to proceed with normal registration. ``False`` @@ -1496,6 +1603,8 @@ octoprint.server.sockjs.emit .. py:function:: socket_emit_hook(socket, user, message, payload, *args, **kwargs): + .. versionadded:: 1.3.10 + Allows plugins to prevent any messages to be emitted on an existing :ref:`push connection `. Handlers should return either ``True`` to allow the message to be emitted, or ``False`` to prevent it. @@ -1516,6 +1625,8 @@ octoprint.timelapse.extensions .. py:function:: timelapse_extension_hook(*args, **kwargs) + .. versionadded:: 1.3.10 + Allows extending the set of supported file extensions for timelapse files. Handlers must return a list of additional file extensions. @@ -1542,6 +1653,8 @@ octoprint.ui.web.templatetypes .. py:function:: templatetype_hook(template_sorting, template_rules, *args, **kwargs) + .. versionadded:: 1.2.0 + Allows extending the set of supported template types in the web interface. This is interesting for plugins which want to offer other plugins to hook into their own offered UIs. Handlers must return a list of additional template specifications in form of 3-tuples. @@ -1648,6 +1761,42 @@ octoprint.ui.web.templatetypes :return: a list of 3-tuples (template type, rule, sorting spec) :rtype: list +.. _sec-plugins-hook-theming-dialog: + +octoprint.theming. +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This actually describes two hooks: + + * ``octoprint.theming.login`` + * ``octoprint.theming.recovery`` + +.. py:function:: ui_theming_hook(*args, **kwargs) + + .. versionadded:: 1.5.0 + + Support theming of the login or recovery dialog, just in case the core UI is themed as well. Use to return a list of additional + CSS file URLs to inject into the dialog HTML. + + Example usage by a plugin: + + .. code-block:: python + + def loginui_theming(): + from flask import url_for + return [url_for("plugin.myplugin.static", filename="css/loginui_theme.css")] + + __plugin_hooks__ = { + "octoprint.theming.login": loginui_theming + } + + Only a list of ready-made URLs to CSS files is supported, neither LESS nor JS. Best use + ``url_for`` like in the example above to be prepared for any configured prefix URLs. + + :return: A list of additional CSS URLs to inject into the login or recovery dialog. + :rtype: A list of strings. + + .. _sec-plugins-hook-timelapse-capture-pre: octoprint.timelapse.capture.pre @@ -1655,6 +1804,8 @@ octoprint.timelapse.capture.pre .. py:function:: capture_pre_hook(filename) + .. versionadded:: 1.4.0 + Perform specific actions prior to capturing a timelapse frame. ``filename`` will be the future path of the frame to be saved. @@ -1670,6 +1821,8 @@ octoprint.timelapse.capture.post .. py:function:: capture_post_hook(filename, success) + .. versionadded:: 1.4.0 + Perform specific actions after capturing a timelapse frame. ``filename`` will be the path of the frame that should have been saved. 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 208fa2fca..31efb1135 100644 --- a/setup.py +++ b/setup.py @@ -1,294 +1,307 @@ #!/usr/bin/env python2 -# coding=utf-8 +# -*- 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.09.23", + "OctoPrint-FileCheck>=2020.08.07", + # 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", + "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" + "feedparser>=5.2.1,<6", # newer versions require Python 3 + "futures>=3.3,<4", + "monotonic>=1.5,<2", + "scandir>=1.10,<2", + "chainmap>=1.0.3,<2", + "typing>=3.7.4.1,<4", + "enum34>=1.1.10,<1.2", ] +# Python 3 specific requirements +INSTALL_REQUIRES_PYTHON3 = ["feedparser>=6.0.2,<7", "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 + # 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[":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 18322aa29..de9bd4d30 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -3,23 +3,28 @@ from __future__ import absolute_import, division, print_function, unicode_literals import io -import sys import logging as log - -#~~ version +import os +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 -#~~ try to ensure a sound SSL environment +# figure out current umask - sadly only doable by setting a new one and resetting it, no query method +UMASK = os.umask(0) +os.umask(UMASK) urllib3_ssl = True """Whether requests/urllib3 and urllib3 (if installed) should be able to establish @@ -27,607 +32,912 @@ 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 = dict() +# ~~ 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: + raise FatalStartupError(str(e)) -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" - } - }, - "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 - } - }, - "loggers": { - "SERIAL": { - "level": "INFO", - "handlers": ["serialFile"], - "propagate": False - }, - "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 octoprint_plugin_inject_factory(settings, components): + import octoprint.plugin + + def f(name, implementation): + """Factory for injections for all OctoPrintPlugins""" + if not isinstance(implementation, octoprint.plugin.OctoPrintPlugin): + return None + + components_copy = dict(components) + if "printer" in components: + import functools + + import wrapt + + def tagwrap(f): + @functools.wraps(f) + def wrapper(*args, **kwargs): + tags = kwargs.get("tags", set()) | { + "source:plugin", + "plugin:{}".format(name), + } + kwargs["tags"] = tags + return f(*args, **kwargs) + + wrapper.__tagwrapped__ = True + return wrapper + + class TaggedFuncsPrinter(wrapt.ObjectProxy): + def __getattribute__(self, attr): + __wrapped__ = super(TaggedFuncsPrinter, self).__getattribute__( + "__wrapped__" + ) + if attr == "__wrapped__": + return __wrapped__ + + item = getattr(__wrapped__, attr) + if ( + callable(item) + and ( + "tags" in item.__code__.co_varnames + or "kwargs" in item.__code__.co_varnames + ) + and not getattr(item, "__tagwrapped__", False) + ): + return tagwrap(item) + else: + return item + + components_copy["printer"] = TaggedFuncsPrinter(components["printer"]) + + props = {} + props.update(components_copy) + props.update({"data_folder": os.path.join(settings.getBaseFolder("data"), name)}) + return props + + return f + + +def settings_plugin_inject_factory(settings): + import octoprint.plugin + + def f(name, implementation): + """Factory for additional injections/initializations depending on plugin type""" + if not isinstance(implementation, octoprint.plugin.SettingsPlugin): + return + + default_settings_overlay = {"plugins": {}} + default_settings_overlay["plugins"][name] = implementation.get_settings_defaults() + settings.add_overlay(default_settings_overlay, at_end=True) + + plugin_settings = octoprint.plugin.plugin_settings_for_settings_plugin( + name, implementation + ) + if plugin_settings is None: + return + + return {"settings": plugin_settings} + + return f + + +def init_settings_plugin_config_migration_and_cleanup(plugin_manager): + import logging + + import octoprint.plugin + + def settings_plugin_config_migration_and_cleanup(identifier, implementation): + """Take care of migrating and cleaning up any old settings""" + + if not isinstance(implementation, octoprint.plugin.SettingsPlugin): + return + + settings_version = implementation.get_settings_version() + settings_migrator = implementation.on_settings_migrate + + if settings_version is not None and settings_migrator is not None: + stored_version = implementation._settings.get_int( + [octoprint.plugin.SettingsPlugin.config_version_key] + ) + if stored_version is None or stored_version < settings_version: + settings_migrator(settings_version, stored_version) + implementation._settings.set_int( + [octoprint.plugin.SettingsPlugin.config_version_key], + settings_version, + force=True, + ) + + implementation.on_settings_cleanup() + implementation._settings.save() + + implementation.on_settings_initialized() + + settingsPlugins = plugin_manager.get_implementations(octoprint.plugin.SettingsPlugin) + for implementation in settingsPlugins: + try: + settings_plugin_config_migration_and_cleanup( + implementation._identifier, implementation + ) + except Exception: + logging.getLogger(__name__).exception( + "Error while trying to migrate settings for " + "plugin {}, ignoring it".format(implementation._identifier), + extra={"plugin": implementation._identifier}, + ) + + plugin_manager.implementation_post_inits = [ + settings_plugin_config_migration_and_cleanup + ] + + +def init_custom_events(plugin_manager): + import logging + + import octoprint.events + + logger = logging.getLogger(__name__) + + custom_events_hooks = plugin_manager.get_hooks( + "octoprint.events.register_custom_events" + ) + for name, hook in custom_events_hooks.items(): + try: + result = hook() + if isinstance(result, (list, tuple)): + for event in result: + constant, value = octoprint.events.Events.register_event( + event, prefix="plugin_{}_".format(name) + ) + logger.debug( + 'Registered event {} of plugin {} as Events.{} = "{}"'.format( + event, name, constant, value + ) + ) + except Exception: + logger.exception( + "Error while retrieving custom event list from plugin {}".format(name), + extra={"plugin": name}, + ) 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"): + 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 = dict() - disabled_from_overlays = dict() + 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 = 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=dict(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 5895ced6a..5c78ec1f9 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") @@ -159,11 +169,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set(r.strip() for r in refnames.strip("()").split(",")) + refs = {r.strip() for r in refnames.strip("()").split(",")} # 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 = set(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 = set(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 _ 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 70ab58d23..beee5faf5 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,604 +11,742 @@ 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: dict(name="Admins", - description="Administrators", - permissions=self.default_permissions_for_group(ADMIN_GROUP), - subgroups=[], - changeable=False, - removable=False, - default=False, - toggleable=True), - USER_GROUP: dict(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: dict(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: dict(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 = dict() - 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 = dict(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", dict()) - 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 = self._to_groups(*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, + ) - for group in self._groups.values(): - group._subgroups = self._to_groups(*group._subgroups) + if key == GUEST_GROUP and ( + len(group.permissions) != len(permissions) + or len(group.subgroups) != len(subgroups) + ): + self._logger.warning( + "Dangerous permissions and/or subgroups stripped from guests group" + ) + self._dirty = True - if self._dirty: - self._save() + self._groups[key] = group - except Exception: - self._logger.exception("Error while loading groups from file {}".format(self._groupfile)) + for group in self._groups.values(): + group._subgroups = self._to_groups(*group._subgroups) - def _save(self, force=False): - if self._groupfile is None or not self._dirty and not force: - return + if self._dirty: + self._save() - groups = dict() - for key in self._groups.keys(): - group = self._groups[key] - groups[key] = dict( - 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() + except Exception: + self._logger.exception( + "Error while loading groups from file {}".format(self._groupfile) + ) - data = dict(_version=self.FILE_VERSION, - groups=groups, - tracked=[x.key for x in Permissions.all()]) + def _save(self, force=False): + if self._groupfile is None or not self._dirty and not force: + return - 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() + 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() - @property - def groups(self): - return list(self._groups.values()) + data = { + "_version": self.FILE_VERSION, + "groups": groups, + "tracked": [x.key for x in Permissions.all()], + } - @property - def default_groups(self): - return [group for group in self._groups.values() if group.is_default()] + with atomic_write( + self._groupfile, mode="wt", permissions=0o600, max_permissions=0o666 + ) as f: + import yaml - def find_group(self, key): - if key is None: - return None - return self._groups.get(key) + yaml.safe_dump( + data, f, default_flow_style=False, indent=4, allow_unicode=True + ) + self._dirty = False + self._load() - 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) + @property + def groups(self): + return list(self._groups.values()) - if not permissions: - permissions = [] + @property + def default_groups(self): + return [group for group in self._groups.values() if group.is_default()] - permissions = self._to_permissions(*permissions) - assert(all(map(lambda p: isinstance(p, OctoPrintPermission), permissions))) + def find_group(self, key): + if key is None: + return None + return self._groups.get(key) - subgroups = self._to_groups(*subgroups) - assert(all(map(lambda g: isinstance(g, Group), subgroups))) + 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) - group = Group(key, name, - description=description, - permissions=permissions, - subgroups=subgroups, - default=default, - changeable=changeable, - removable=removable, - toggleable=toggleable) - self._groups[key] = group + if not permissions: + permissions = [] - if save: - self._dirty = True - self._save() + permissions = self._to_permissions(*permissions) + assert all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)) - if notify: - self._notify_listeners("added", group) + subgroups = self._to_groups(*subgroups) + assert all(map(lambda g: isinstance(g, Group), subgroups)) - 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) + group = Group( + key, + name, + description=description, + permissions=permissions, + subgroups=subgroups, + default=default, + changeable=changeable, + removable=removable, + toggleable=toggleable, + ) + self._groups[key] = group - if not group.is_removable(): - raise GroupUnremovable(key) + if save: + self._dirty = True + self._save() - del self._groups[key] - self._dirty = True + if notify: + self._notify_listeners("added", group) - if save: - 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("removed", group) + if not group.is_removable(): + raise GroupUnremovable(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) + del self._groups[key] + self._dirty = True - if not group.is_changeable(): - raise GroupCantBeChanged(key) + if save: + self._save() - if description is not None and description != group.get_description(): - group.change_description(description) - self._dirty = True + if notify: + self._notify_listeners("removed", group) - notifications = [] + 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 permissions is not None: - permissions = self._to_permissions(*permissions) - assert (all(map(lambda p: isinstance(p, OctoPrintPermission), permissions))) + if not group.is_changeable(): + raise GroupCantBeChanged(key) - removed_permissions = list(set(group._permissions) - set(permissions)) - added_permissions = list(set(permissions) - set(group._permissions)) + if description is not None and description != group.get_description(): + group.change_description(description) + self._dirty = True - if removed_permissions: - self._dirty |= group.remove_permissions_from_group(removed_permissions) - if added_permissions: - self._dirty |= group.add_permissions_to_group(added_permissions) + notifications = [] - notifications.append((("permissions_changed", group), - dict(added=added_permissions, removed=removed_permissions))) + if permissions is not None: + permissions = self._to_permissions(*permissions) + assert all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)) - if subgroups is not None: - subgroups = self._to_groups(*subgroups) - assert(all(map(lambda g: isinstance(g, Group), subgroups))) + removed_permissions = list(set(group._permissions) - set(permissions)) + added_permissions = list(set(permissions) - set(group._permissions)) - removed_subgroups = list(set(group._subgroups) - set(subgroups)) - added_subgroups = list(set(subgroups) - set(group._subgroups)) + 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 removed_subgroups: - self._dirty = group.remove_subgroups_from_group(removed_subgroups) - if added_subgroups: - self._dirty = group.add_subgroups_to_group(added_subgroups) + notifications.append( + ( + ("permissions_changed", group), + {"added": added_permissions, "removed": removed_permissions}, + ) + ) - notifications.append((("subgroups_changed", group), - dict(added=added_subgroups, removed=removed_subgroups))) + if subgroups is not None: + subgroups = self._to_groups(*subgroups) + assert all(map(lambda g: isinstance(g, Group), subgroups)) - if default is not None: - group.change_default(default) - self._dirty = True + removed_subgroups = list(set(group._subgroups) - set(subgroups)) + added_subgroups = list(set(subgroups) - set(group._subgroups)) - if self._dirty: - if save: - self._save() + 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 notify: - for args, kwargs in notifications: - self._notify_listeners(*args, **kwargs) + notifications.append( + ( + ("subgroups_changed", group), + {"added": added_subgroups, "removed": removed_subgroups}, + ) + ) + + if default is not None: + group.change_default(default) + self._dirty = True + + 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, + ): + if permissions is None: + permissions = [] + if subgroups is None: + subgroups = [] - def as_dict(self): - from octoprint.access.permissions import OctoPrintPermission - return dict( - 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 - ) + if key == GUEST_GROUP: + # guests may not have any dangerous permissions + permissions = list(filter(lambda p: not p.dangerous, permissions)) + subgroups = list(filter(lambda g: not g.dangerous, subgroups)) - @property - def key(self): - return self._key + 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 get_name(self): - return self._name + def as_dict(self): + from octoprint.access.permissions import OctoPrintPermission - def get_description(self): - return self._description + 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, + "dangerous": self.dangerous, + } - def is_default(self): - return self._default + @property + def key(self): + return self._key - def is_changeable(self): - return self._changeable + def get_name(self): + return self._name - def is_removable(self): - return self._removable + def get_description(self): + return self._description - def is_toggleable(self): - return self._toggleable + def is_default(self): + return self._default - 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_changeable(self): + return self._changeable - # Make sure the permissions variable is of type list - if not isinstance(permissions, list): - permissions = [permissions] + def is_removable(self): + return self._removable - assert(all(map(lambda p: isinstance(p, OctoPrintPermission), permissions))) + def is_toggleable(self): + return self._toggleable - dirty = False - for permission in permissions: - if permissions not in self.permissions: - self._permissions.append(permission) - dirty = True + @property + def dangerous(self): + return any(map(lambda p: p.dangerous, self._permissions)) or any( + map(lambda g: g.dangerous, self._subgroups) + ) - return dirty + 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 remove_permissions_from_group(self, permissions): - """Removes a list of permissions from a group""" - if not self.is_changeable(): - raise GroupCantBeChanged(self.key) + # Make sure the permissions variable is of type list + if not isinstance(permissions, list): + permissions = [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))) + if self.key == GUEST_GROUP: + # don't allow dangerous permissions on the guests group + permissions = list(filter(lambda p: not p.dangerous, 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 permissions not in self.permissions: + self._permissions.append(permission) + dirty = True - return dirty + return dirty - def add_subgroups_to_group(self, subgroups): - """Adds a list of subgroups to a group""" - if not self.is_changeable(): - raise GroupCantBeChanged(self.key) + def remove_permissions_from_group(self, permissions): + """Removes a list of permissions from a group""" + if not self.is_changeable(): + raise GroupCantBeChanged(self.key) - # Make sure the subgroups variable is of type list - if not isinstance(subgroups, list): - subgroups = [subgroups] + # Make sure the permissions variable is of type list + if not isinstance(permissions, list): + permissions = [permissions] - assert(all(map(lambda g: isinstance(g, Group), subgroups))) + assert all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)) - dirty = False - for group in subgroups: - if group.is_toggleable() and group not in self._subgroups: - self._subgroups.append(group) - dirty = True + dirty = False + for permission in permissions: + if permission in self._permissions: + self._permissions.remove(permission) + dirty = True - return dirty + return dirty - 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) + def add_subgroups_to_group(self, subgroups): + """Adds a list of subgroups to a group""" + if not self.is_changeable(): + raise GroupCantBeChanged(self.key) - # Make sure the subgroups variable is of type list - if not isinstance(subgroups, list): - subgroups = [subgroups] + # Make sure the subgroups variable is of type list + if not isinstance(subgroups, list): + subgroups = [subgroups] - assert (all(map(lambda g: isinstance(g, Group), subgroups))) + assert all(map(lambda g: isinstance(g, Group), subgroups)) - dirty = False - for group in subgroups: - if group.is_toggleable() and group in self._subgroups: - self._subgroups.remove(group) - dirty = True + if self.key == GUEST_GROUP: + # don't allow dangerous subgroups on the guests group + subgroups = list(filter(lambda g: not g.dangerous, 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 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 remove_subgroups_from_group(self, subgroups): + """Removes a list of subgroups from 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 + # Make sure the subgroups variable is of type list + if not isinstance(subgroups, list): + subgroups = [subgroups] - @property - def permissions(self): - if Permissions.ADMIN in self._permissions: - return Permissions.all() + assert all(map(lambda g: isinstance(g, Group), subgroups)) - return list(filter(lambda p: p is not None, self._permissions)) + dirty = False + for group in subgroups: + if group.is_toggleable() and group in self._subgroups: + self._subgroups.remove(group) + dirty = True - @property - def subgroups(self): - return filter(lambda g: g is not None, self._subgroups) + return dirty - @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 change_default(self, default): + """Changes the default flag of a Group""" + if not self.is_changeable(): + raise GroupCantBeChanged(self.key) - return needs + self._default = default - def has_permission(self, permission): - if Permissions.ADMIN.get_name() in self._permissions: - return True + def change_description(self, description): + """Changes the description of a group""" + self._description = description - return permission.needs.issubset(self.needs) + @property + def permissions(self): + if Permissions.ADMIN in self._permissions: + return Permissions.all() - 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 list(filter(lambda p: p is not None, self._permissions)) - def __hash__(self): - return self.key.__hash__() + @property + def subgroups(self): + return list(filter(lambda g: g is not None, self._subgroups)) - def __eq__(self, other): - return isinstance(other, Group) and other.key == self.key + @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) + + return needs + + def has_permission(self, permission): + if Permissions.ADMIN.get_name() in self._permissions: + return True + + return permission.needs.issubset(self.needs) + + 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 __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 d342efeda..601e1e365 100644 --- a/src/octoprint/access/permissions.py +++ b/src/octoprint/access/permissions.py @@ -2,391 +2,466 @@ 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 dict( - 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 dangerous(self): + return self._dangerous - def get_name(self): - return self._name + @property + def default_groups(self): + return self._default_groups - def get_description(self): - return self._description + def get_name(self): + return self._name - 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 get_description(self): + return self._description - :param identity: The identity - """ - if self.needs and len(self.needs.intersection(identity.provides)) != len(self.needs): - return False + 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. - if self.excludes and self.excludes.intersection(identity.provides): - return False + :param identity: The identity + """ + if self.needs and len(self.needs.intersection(identity.provides)) != len( + self.needs + ): + return False - return True + if self.excludes and self.excludes.intersection(identity.provides): + return False + 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, and to retrieve system and usage information" + ), + 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 a0d0f7ba9..a7340bfed 100644 --- a/src/octoprint/access/users.py +++ b/src/octoprint/access/users.py @@ -1,1284 +1,1446 @@ # -*- 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 = dict() - self._sessionids_by_userid = dict() - self._enabled = True + self._logger = logging.getLogger(__name__) + self._session_users_by_session = {} + self._sessionids_by_userid = {} - 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 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=dict(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=dict(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 dict() - - 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=dict(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=dict(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=dict(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=dict(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 unregister_login_status_listener(self, listener): + self._login_status_listeners.remove(listener) + + def anonymous_user_factory(self): + return AnonymousUser([self._group_manager.guest_group]) + + def api_user_factory(self): + return ApiUser([self._group_manager.admin_group, self._group_manager.user_group]) + + @property + def enabled(self): + return True + + 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: + 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 = dict() - 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) + + self._logger = logging.getLogger(__name__) + + 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): + # noinspection PyBroadException + with io.open(self._userfile, "rt", encoding="utf-8") as f: + data = yaml.safe_load(f) + + if not data or not isinstance(data, dict): + self._logger.fatal( + "{} does not contain a valid map of users. Fix " + "the file, or remove it, then restart OctoPrint.".format( + self._userfile + ) + ) + raise CorruptUserStorage() + + 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() + + self._customized = True + 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(set(group.key for group in groups)) - - def _from_permissions(self, *permissions): - return list(set(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) + + +class CorruptUserStorage(Exception): + pass + ##~~ 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 = dict() + 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] = dict() + 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] = dict() + 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(dict(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) - -##~~ 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, "_api", "", True, [], groups) diff --git a/src/octoprint/cli/__init__.py b/src/octoprint/cli/__init__.py index 4a2a8c38b..e12b12199 100644 --- a/src/octoprint/cli/__init__.py +++ b/src/octoprint/cli/__init__.py @@ -1,177 +1,338 @@ # -*- 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 +# ~~ Basic CLI initialization for plugins + + +def init_platform_for_cli(ctx): + """ + Performs a basic platform initialization for the CLI. + + Plugin implementations will be initialized, but only with a subset of the usual + property injections: + + * _identifier and everything else parsed from metadata + * _logger + * _connectivity_checker + * _environment_detector + * _event_bus + * _plugin_manager + * _settings + + Returns: the same list of components as returned by ``init_platform`` + """ + + from octoprint import ( + init_custom_events, + init_platform, + init_settings_plugin_config_migration_and_cleanup, + ) + from octoprint import octoprint_plugin_inject_factory as opif + from octoprint import settings_plugin_inject_factory as spif + + components = init_platform( + get_ctx_obj_option(ctx, "basedir", None), + get_ctx_obj_option(ctx, "configfile", None), + safe_mode=True, + ) + + ( + settings, + logger, + safe_mode, + event_manager, + connectivity_checker, + plugin_manager, + environment_detector, + ) = components + + init_custom_events(plugin_manager) + octoprint_plugin_inject_factory = opif( + settings, + { + "plugin_manager": plugin_manager, + "event_bus": event_manager, + "connectivity_checker": connectivity_checker, + "environment_detector": environment_detector, + }, + ) + settings_plugin_inject_factory = spif(settings) + + plugin_manager.implementation_inject_factories = [ + octoprint_plugin_inject_factory, + settings_plugin_inject_factory, + ] + plugin_manager.initialize_implementations() + + init_settings_plugin_config_migration_and_cleanup(plugin_manager) + + return components + + +# ~~ 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 .systeminfo import systeminfo_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, + systeminfo_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 01e316319..9d9b3b00a 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=dict(ignore_unknown_options=True)) +@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(str(e), 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 = dict() - 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 = dict() - 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,37 +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_heartbeat(ws): - click.echo("<3") + def on_sent(ws, data): + click.echo(">>> {}".format(json.dumps(data))) - def on_message(ws, message_type, message_payload): - click.echo("Message: {}, Payload: {}".format(message_type, json.dumps(message_payload))) + def on_heartbeat(ws): + click.echo("<3") - socket = ctx.obj.client.create_socket(on_connect=on_connect, - on_close=on_close, - on_error=on_error, - on_heartbeat=on_heartbeat, - on_message=on_message) + def on_message(ws, message_type, message_payload): + click.echo( + "<<< {}, Payload: {}".format(message_type, json.dumps(message_payload)) + ) - click.echo(">>> Waiting for client to exit") - try: - socket.wait() - finally: - click.echo(">>> Goodbye...") + 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...") diff --git a/src/octoprint/cli/config.py b/src/octoprint/cli/config.py index c6f2a4df8..fb7c960e5 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(str(e), 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(str(e), 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(str(e), 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(str(e), 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(str(e), 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 a9649cd16..048bb7805 100644 --- a/src/octoprint/cli/dev.py +++ b/src/octoprint/cli/dev.py @@ -2,238 +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 = dict() - 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 = 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 = dict(cookiecutters_dir=path) - with custom_cookiecutter_config(custom): - raw_options = dict( - 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 40c444c17..e5e283110 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 = dict() + 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, dict(root=dict(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(str(e), 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=dict(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 5a28741a9..39f7fab3b 100644 --- a/src/octoprint/cli/server.py +++ b/src/octoprint/cli/server.py @@ -1,178 +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 - logger = logging.getLogger("octoprint.startup") +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(str(e), 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") @@ -180,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/systeminfo.py b/src/octoprint/cli/systeminfo.py new file mode 100644 index 000000000..f8f6fb5af --- /dev/null +++ b/src/octoprint/cli/systeminfo.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" + + +import logging + +import click + +from octoprint.cli import init_platform_for_cli, standard_options + +click.disable_unicode_literals_warning = True + + +def get_systeminfo(environment_detector, connectivity_checker): + from octoprint import __version__ + from octoprint.util import dict_flatten + + environment_detector.run_detection(notify_plugins=False) + + systeminfo = { + "octoprint": {"version": __version__}, + "connectivity": connectivity_checker.as_dict(), + "env": environment_detector.environment, + } + + # flatten and filter + flattened = dict_flatten(systeminfo) + flattened["env.python.virtualenv"] = "env.python.virtualenv" in flattened + + return flattened + + +@click.group() +def systeminfo_commands(): + pass + + +@systeminfo_commands.command(name="systeminfo") +@standard_options() +@click.pass_context +def systeminfo_command(ctx, **kwargs): + """Retrieves and prints the system info.""" + logging.disable(logging.ERROR) + try: + ( + settings, + logger, + safe_mode, + event_manager, + connectivity_checker, + plugin_manager, + environment_detector, + ) = init_platform_for_cli(ctx) + except Exception as e: + click.echo(str(e), err=True) + click.echo("There was a fatal error initializing the platform.", err=True) + ctx.exit(-1) + else: + systeminfo = get_systeminfo(environment_detector, connectivity_checker) + + for k in sorted(systeminfo.keys()): + click.echo("{}: {}".format(k, systeminfo[k])) + ctx.exit(0) diff --git a/src/octoprint/cli/user.py b/src/octoprint/cli/user.py index 488612a43..548fd88bb 100644 --- a/src/octoprint/cli/user.py +++ b/src/octoprint/cli/user.py @@ -1,124 +1,157 @@ -# coding=utf-8 +# -*- 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.access.users import ( + CorruptUserStorage, + 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 CorruptUserStorage: + raise + except Exception: + click.echo( + "Could not instantiate user manager {}, falling back to FilebasedUserManager!".format( + name + ), + err=True, + ) + user_manager = FilebasedUserManager(group_manager, settings=settings) - 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) + ctx.exit(-1) @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 +159,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 d1fb6dc56..f8be4d4fa 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,189 @@ 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 = dict() - 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 = dict() - return self._cache + def _detect_os(self): + return { + "id": get_os(), + "platform": sys.platform, + "bits": 64 if sys.maxsize > 2 ** 32 else 32, + } - def _detect_os(self): - return dict(id=get_os(), - platform=sys.platform) + def _detect_python(self): + result = {"version": "unknown", "pip": "unknown"} - def _detect_python(self): - result = dict(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 = dict(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 = dict() + 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=dict(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..fd4847181 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -2,487 +2,542 @@ 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" + COMMAND_SUPPRESSED = "CommandSuppressed" + INVALID_TOOL_REPORTED = "InvalidToolReported" - # 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 71d8aa4eb..84ceff1c6 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 = dict( -) +extensions = {} + def full_extension_tree(): - result = dict( - # extensions for printable machine code - machinecode=dict( - 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 - result = octoprint.util.dict_merge(result, plugin_result, leaf_merger=leaf_merger) - except Exception: - logging.getLogger(__name__).exception("Exception while retrieving additional extension " - "tree entries from SlicerPlugin {name}".format(name=plugin._identifier), - extra=dict(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) - except Exception: - logging.getLogger(__name__).exception("Exception while retrieving additional extension " - "tree entries from hook {name}".format(name=name), - extra=dict(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 value in subtree.values(): + 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 value in subtree.values(): + 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 = dict() - 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 = dict() - self._slicing_jobs_mutex = threading.Lock() - - self._slicing_progress_callbacks = [] - self._last_slicing_progress = None - - self._progress_plugins = [] - self._preprocessor_hooks = dict() - - 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, dict(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, dict(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", dict(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, dict(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=dict(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=dict(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): - if not destinations: - destinations = list(self._storage_managers.keys()) - if isinstance(destinations, basestring): - destinations = [destinations] - - result = dict() - for dst in destinations: - result[dst] = self._storage_managers[dst].list_files(path=path, filter=filter, recursive=recursive) - 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=dict(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, dict(storage=destination, - path=path_in_storage, - name=name, - type=get_file_type(name))) - eventManager().fire(Events.UPDATED_FILES, dict(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, dict(storage=destination, - path=path, - name=name, - type=get_file_type(name))) - eventManager().fire(Events.UPDATED_FILES, dict(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, dict(storage=destination, - path=path_in_storage, - name=name, - type=get_file_type(name))) - eventManager().fire(Events.UPDATED_FILES, dict(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, dict(storage=destination, - path=source_path_in_storage, - name=source_name, - type=get_file_type(source_name))) - eventManager().fire(Events.FILE_ADDED, dict(storage=destination, - path=dst_path_in_storage, - name=dst_name, - type=get_file_type(dst_name))) - eventManager().fire(Events.UPDATED_FILES, dict(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, dict(storage=destination, - path=path_in_storage, - name=name)) - eventManager().fire(Events.UPDATED_FILES, dict(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, dict(storage=destination, - path=path, - name=name)) - eventManager().fire(Events.UPDATED_FILES, dict(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, dict(storage=destination, - path=path_in_storage, - name=name)) - eventManager().fire(Events.UPDATED_FILES, dict(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, dict(storage=destination, - path=source_path_in_storage, - name=source_name)) - eventManager().fire(Events.FOLDER_ADDED, dict(storage=destination, - path=dst_path_in_storage, - name=dst_name)) - eventManager().fire(Events.UPDATED_FILES, dict(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, dict(timestamp=timestamp, printTime=print_time, success=success, printerProfile=printer_profile)) - else: - self._storage(destination).add_history(path, dict(timestamp=timestamp, success=success, printerProfile=printer_profile)) - eventManager().fire(Events.METADATA_STATISTICS_UPDATED, dict(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 = dict(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, _ 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 9f04f2183..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 = dict() - 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=dict(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 = dict() - 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"] = dict() - 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 04a97765b..6428d8893 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -2,1705 +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 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): - """ - 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 = dict() - self._persisted_metadata_lock_mutex = threading.RLock() - self._persisted_metadata_locks = dict() - - self._metadata_cache = pylru.lrucache(100) - - 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 = dict() - 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): - if path: - path = self.sanitize_path(to_unicode(path)) - base = self.path_in_storage(path) - if base: - base += "/" - else: - path = self.basefolder - base = "" - return self._list_folder(path, base=base, entry_filter=filter, recursive=recursive) - - 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=dict()) - 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 = dict( - path=source_path, - name=source_name, - display=source_display, - fullpath=source_fullpath, - ) - destination_data = dict( - 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=dict()) - 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=dict()) - metadata_dirty = False - if not "hash" in metadata or metadata["hash"] != file_hash: - # hash changed -> throw away old metadata - metadata = dict(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", dict(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: - current_data = metadata[name][key] - - import octoprint.util - new_data = octoprint.util.dict_merge(current_data, data) - metadata[name][key] = new_data - 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 = dict() - last_print = dict() - - - 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 = dict(averagePrintTime=dict(), lastPrintTime=dict()) - - 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"]] = dict( - 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( - dict(rel="machinecode" if rel == "model" else "model", name=name, hash=metadata[name]["hash"]) - ) - metadata_dirty = True - - link_dict = dict( - rel=rel, - name=data["name"], - hash=hash - ) - - elif rel == "web" and "href" in data: - link_dict = 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) - - def _list_folder(self, path, base="", entry_filter=None, recursive=True, include_children=True, **kwargs): - if entry_filter is None: - entry_filter = kwargs.get("filter", None) - - metadata = self._get_metadata(path) - if not metadata: - metadata = dict() - metadata_dirty = False - - result = dict() - 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 - - # TODO extract model hash from source if possible to recreate link - - if not entry_filter or entry_filter(entry_name, entry_metadata): - # only add files passing the optional filter - extended_entry_data = dict() - 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 = dict() - - entry_data = dict( - name=entry_name, - display=entry_metadata.get("display", entry_name), - path=path_in_location, - type="folder", - typePath=["folder"] - ) - if recursive: - sub_result = self._list_folder(entry_path, base=path_in_location + "/", entry_filter=entry_filter, - recursive=recursive) - entry_data["children"] = sub_result - elif include_children: - sub_result = self._list_folder(entry_path, base=path_in_location + "/", entry_filter=entry_filter, - recursive=False, include_children=False) - entry_data["children"] = sub_result - - if not entry_filter or entry_filter(entry_name, entry_data): - # only add folders passing the optional filter - - def get_size(): - total_size = 0 - for element in entry_data["children"].values(): - if "size" in element: - total_size += element["size"] - - return total_size - - extended_entry_data = dict() - extended_entry_data.update(entry_data) - if recursive: - extended_entry_data["size"] = get_size() - - result[entry_name] = extended_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 - - # TODO recreate links if we have metadata less entries - - # save metadata - if metadata_dirty: - self._save_metadata(path, metadata) - - return result - - def _add_basic_metadata(self, path, entry, display_name=None, additional_metadata=None, save=True, metadata=None): - if additional_metadata is None: - additional_metadata = dict() - - if metadata is None: - metadata = self._get_metadata(path) - - entry_path = os.path.join(path, entry) - - if os.path.isfile(entry_path): - entry_data = dict( - 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 = dict() - - 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=dict()) - 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 dict() - - 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, dict())) - 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 7074d508a..1ab1222ed 100644 --- a/src/octoprint/filemanager/util.py +++ b/src/octoprint/filemanager/util.py @@ -2,244 +2,263 @@ 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 +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 + """ - def __init__(self, filename): - self.filename = filename + DEFAULT_PERMISSIONS = 0o664 - def save(self, path): - """ - Saves the file's content to the given absolute path. + def __init__(self, filename): + self.filename = filename - Arguments: - path (str): The absolute path to where to save the file - """ - raise NotImplementedError() + def save(self, path, permissions=None): + """ + Saves the file's content to the given absolute path. - def stream(self): - """ - Returns a Python stream object (subclass of io.IOBase) representing the file's contents. + 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. + + 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): - 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) + + 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): - """ - 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) + 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 bf7c47992..665298efa 100644 --- a/src/octoprint/logging/handlers.py +++ b/src/octoprint/logging/handlers.py @@ -1,187 +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 SerialLogHandler(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 on_open_connection(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(SerialLogHandler, 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() + + +class SerialLogHandler(TriggeredRolloverLogHandler): + pass + + +class PluginTimingsLogHandler(TriggeredRolloverLogHandler): + pass - self.cleanupFiles() - if not self.delay: - self.stream = self._open() 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 69ff0c79d..535b797bc 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -16,521 +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 = dict() + 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=dict(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. + :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) + .. 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. + 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) + .. 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. + 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) + .. method:: set_boolean(path, value, force=False) - Like :func:`set` but ensures the value is an ``boolean`` through attempted conversion before setting it. + Like :func:`set` but ensures the value is an ``boolean`` through attempted conversion before setting it. - .. method:: save(force=False, trigger_event=False) + .. 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. + 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 - """ + :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 - def __init__(self, settings, plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None): - self.settings = settings - self.plugin_key = plugin_key + .. method:: add_overlay(overlay, at_end=False, key=None) - if defaults is not None: - self.defaults = dict(plugins=dict()) - self.defaults["plugins"][plugin_key] = defaults - self.defaults["plugins"][plugin_key]["_config_version"] = None - else: - self.defaults = None + Adds a new config overlay for the plugin's settings. Will return the overlay's key in the map. - if get_preprocessors is None: - get_preprocessors = dict() - self.get_preprocessors = dict(plugins=dict()) - self.get_preprocessors["plugins"][plugin_key] = get_preprocessors + :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 - if set_preprocessors is None: - set_preprocessors = dict() - self.set_preprocessors = dict(plugins=dict()) - self.set_preprocessors["plugins"][plugin_key] = set_preprocessors + .. method:: remove_overlay(key) - 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 + Removes an overlay from the settings based on its key. Return ``True`` if the overlay could be found and was + removed, ``False`` otherwise. - 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 + :param key: The key of the overlay to remove + :type key: str + :rtype: boolean + """ - 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 __init__( + self, + settings, + plugin_key, + defaults=None, + get_preprocessors=None, + set_preprocessors=None, + ): + self.settings = settings + self.plugin_key = plugin_key - self.access_methods = dict( - 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) - ) - self.deprecated_access_methods = dict( - getInt ="get_int", - getFloat ="get_float", - getBoolean="get_boolean", - setInt ="set_int", - setFloat ="set_float", - setBoolean="set_boolean" - ) + 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 - def _prefix_path(self, path=None): - if path is None: - path = list() - return ['plugins', self.plugin_key] + path + if get_preprocessors is None: + get_preprocessors = {} + self.get_preprocessors = {"plugins": {}} + self.get_preprocessors["plugins"][plugin_key] = get_preprocessors - def global_has(self, path, **kwargs): - return self.settings.has(path, **kwargs) + if set_preprocessors is None: + set_preprocessors = {} + self.set_preprocessors = {"plugins": {}} + self.set_preprocessors["plugins"][plugin_key] = set_preprocessors - def global_remove(self, path, **kwargs): - return self.settings.remove(path, **kwargs) + 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 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. + 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 - Directly forwards to :func:`octoprint.settings.Settings.get`. - """ - return self.settings.get(path, **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 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 wrap_overlay(args): + result = list(args) + overlay = result[0] + result[0] = {"plugins": {plugin_key: overlay}} + return result - 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) + 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 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 _prefix_path(self, path=None): + if path is None: + path = list() + return ["plugins", self.plugin_key] + path - 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. + def global_has(self, path, **kwargs): + return self.settings.has(path, **kwargs) - Directly forwards to :func:`octoprint.settings.Settings.set`. - """ - self.settings.set(path, value, **kwargs) + def global_remove(self, path, **kwargs): + return self.settings.remove(path, **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_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. - 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) + Directly forwards to :func:`octoprint.settings.Settings.get`. + """ + return self.settings.get(path, **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_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_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 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 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. + 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) - 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. + 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. - 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``. + Directly forwards to :func:`octoprint.settings.Settings.set`. + """ + self.settings.set(path, value, **kwargs) - 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) + 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) - @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 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 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) + 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) - kwargs.update(dict( - merged=merged, - asdict=asdict, - defaults=defaults, - preprocessors=preprocessors - )) + 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) - return self.settings.get(self._prefix_path(), **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. - def clean_all_data(self): - self.settings.remove(self._prefix_path()) + 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. - 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 + 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``. - 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) + 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) - 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 + @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 - return _func + 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) - return getattr(self.settings, item) + 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 4c900687a..b3010b1ec 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -2,8 +2,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals """ -In this module resides the core data structures and logic of the plugin system. It is implemented in an OctoPrint-agnostic -way and could be extracted into a separate Python module in the future. +In this module resides the core data structures and logic of the plugin system. .. autoclass:: PluginManager :members: @@ -22,1880 +21,2471 @@ way and could be extracted into a separate Python module in the future. """ -__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 -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") -FolderOrigin = namedtuple("FolderOrigin", "type, folder") -ModuleOrigin = namedtuple("PackageOrigin", "type, module_name, folder") +_EntryPointOrigin = namedtuple( + "EntryPointOrigin", "type, entry_point, module_name, package_name, package_version" +) + + +class EntryPointOrigin(_EntryPointOrigin): + """ + Origin of a plugin registered via an entry point. + + .. attribute:: type + + Always ``entry_point``. + + .. attribute:: entry_point + + Name of the entry point, usually ``octoprint.plugin``. + + .. attribute:: module_name + + Module registered to the entry point. + + .. attribute:: package_name + + Python package containing the entry point. + + .. attribute:: package_version + + 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. + + .. attribute:: type + + Always `folder`. + + .. attribute:: folder + + 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. + + .. attribute:: type + + Always `module`. + + .. attribute:: module_name + + Name of the module from which the plugin was loaded. + + .. attribute:: folder + + 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_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 - self.origin = None - self.enabled = True - self.blacklisted = False - self.forced_disabled = False - self.incompatible = False - self.bundled = False - self.loaded = False - self.managable = True - self.needs_restart = False - self.invalid_syntax = False - - 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): - 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 all returned implementations need to implement. - - Returns: - object: The plugin's implementation if it matches all of the requested ``types``, None otherwise. - """ - - if not self.implementation: - return None - - for t in types: - if not isinstance(self.implementation, t): - return None - - return self.implementation - - @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): - return self._cached_parsed_metadata - - def _parse_metadata(self): - result = dict() - - 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)) + attr_enable = "__plugin_enable__" + """ Module attribute which to call when enabling the plugin. """ - return result + 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 + + 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 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. - """ - - 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 = dict() - self.disabled_plugins = dict() - self.plugin_implementations = dict() - self.plugin_implementations_by_type = defaultdict(list) - - self._plugin_hooks = defaultdict(list) - - self.implementation_injects = dict() - 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): - plugins = dict(self.enabled_plugins) - plugins.update(self.disabled_plugins) - return plugins - - @property - def plugin_hooks(self): - 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 = dict(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(dict( - 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): - 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, **kwargs): - if not name in self.plugins: - self.logger.debug("Trying to mark an unknown plugin {name}".format(**locals())) - - for key, value in kwargs.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, key): - if not name in self.plugins: - return False - - return name in self.marked_plugins[key] - - 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): - 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): - 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)) - - self.plugin_implementations[name] = plugin.implementation - - 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): - 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): - return self.has_any_of_mixins(plugin, RestartNeedingPlugin) - - def has_restart_needing_hooks(self, plugin): - return self.has_any_of_hooks(plugin, self.plugin_restart_needing_hooks) - - def has_obsolete_hooks(self, plugin): - return self.has_any_of_hooks(plugin, self.plugin_obsolete_hooks) - - def is_restart_needing_hook(self, hook): - return self.hook_matches_hooks(hook, self.plugin_restart_needing_hooks) - - def is_obsolete_hook(self, hook): - 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 = dict() - 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(dict( - 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 dict() - - result = OrderedDict() - for h in self.plugin_hooks[hook]: - result[h[0]] = 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 + 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): # noqa: B014 + # 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 a2a4bf356..6012549b9 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -19,2065 +19,2189 @@ 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 + """ - 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 dict() + 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:: - - 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. + .. note:: - 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. + 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. - The included template must be called ``_about.jinja2`` (e.g. ``myplugin_about.jinja2``) unless - overridden by the configuration supplied through :func:`get_template_configs`. + .. versionadded:: 1.3.0 - 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`. + 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. - 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 dict() - - 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") + 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`. + + .. 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. + + .. 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 `/`. + """ + 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. + 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. + 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. + ``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. + 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** + **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: + 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/__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 `_ + .. 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. + 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** + **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. + 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). + 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. - """ + See below for details on this. - # 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. + .. versionadded:: 1.3.0 + """ - 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. + # 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. - The execution order of calls to this method can be influenced via the sorting context - ``UiPlugin.will_handle_ui``. + 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. - Arguments: - request (flask.Request): A Flask `Request `_ - object. + The execution order of calls to this method can be influenced via the sorting context + ``UiPlugin.will_handle_ui``. - Returns: - bool: ``True`` if the the implementation will serve the request, - ``False`` otherwise. - """ - return False + Arguments: + request (flask.Request): A Flask `Request `_ + object. - # 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``. + Returns: + bool: ``True`` if the the implementation will serve the request, + ``False`` otherwise. + """ + return False - ``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): + # 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``. - .. list-table:: - :widths: 5 95 + ``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): - * - 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 - .. 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: - * - 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)`` + .. list-table:: + :widths: 5 95 - * - 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. + * - 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)`` - The sub structure for each key will be as follows: + * - 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. - .. list-table:: - :widths: 5 95 + The sub structure for each key will be as follows: - * - 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. + .. list-table:: + :widths: 5 95 - For the possible contents of the data ``dicts`` see the - :class:`~octoprint.plugin.TemplatePlugin` mixin. + * - 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. - * - 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. + For the possible contents of the data ``dicts`` see the + :class:`~octoprint.plugin.TemplatePlugin` mixin. - 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. + * - 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. - 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. + 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. - 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``. - """ + 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. - return None + 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``. + """ - # noinspection PyMethodMayBeStatic - def get_ui_additional_key_data_for_cache(self): - """ - Allows to return additional data to use in the cache key. + return None - 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. - """ - return None + # noinspection PyMethodMayBeStatic + def get_ui_additional_key_data_for_cache(self): + """ + Allows to return additional data to use in the cache key. - # 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, 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. - Returns: - list: A list of paths to additional files whose modification to track for (in)validating - the cache. Ignored if ``None`` is returned. - """ - return None + .. 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. + # 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 representing the only files whose modification to track for (in)validating - the cache. Ignored if ``None`` is returned. - """ - return None + Returns: + list: A list of paths to additional files whose modification to track for (in)validating + the cache. Ignored if ``None`` is returned. - # 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). + ..versionadded:: 1.3.0 + """ + return None - Returns: - str: An alternatively calculated ETag value. Ignored if ``None`` is returned (default). - """ - 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. - # noinspection PyMethodMayBeStatic - def get_ui_additional_etag(self, default_additional): - """ - Allows to provide a list of additional fields to use for ETag generation. + Returns: + list: A list of paths representing the only files whose modification to track for (in)validating + the cache. Ignored if ``None`` is returned. - By default the same list will be returned that is also used in the stock UI (and injected - via the parameter ``default_additional``). + ..versionadded:: 1.3.0 + """ + return None - Arguments: - default_additional (list): The list of default fields added to the ETag of the default UI + # 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: - (list): A list of additional fields for the ETag generation, or None - """ - return default_additional + Returns: + str: An alternatively calculated ETag value. Ignored if ``None`` is returned (default). - # 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. + ..versionadded:: 1.3.0 + """ + return None - Returns: - int: An alternatively calculated LastModified value. Ignored if ``None`` is returned (default). - """ - 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. - # 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. + By default the same list will be returned that is also used in the stock UI (and injected + via the parameter ``default_additional``). - Have this return False if you do not want your plugin's UI to ever be preemptively cached. + Arguments: + default_additional (list): The list of default fields added to the ETag of the default UI - Returns: - bool: Whether to enable preemptive caching (True, default) or not (False) - """ - return True + Returns: + (list): A list of additional fields for the ETag generation, or None - # 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. + ..versionadded:: 1.3.0 + """ + return default_additional - Returns: - dict: Additional data to persist in the preemptive cache configuration. - """ - return None + # 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. - # 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. + Returns: + int: An alternatively calculated LastModified value. Ignored if ``None`` is returned (default). - Keys and values are used as keyword arguments for creating the - `Werkzeug EnvironBuilder `_ - used for creating the fake request. + ..versionadded:: 1.3.0 + """ + return None - Returns: - dict: Additional request data to persist in the preemptive cache configuration and to - use for request environment construction. - """ - 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. - # 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. + Have this return False if you do not want your plugin's UI to ever be preemptively cached. - 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 enable preemptive caching (True, default) or not (False) + """ + return True - Returns: - bool: Whether to suppress a record (True) or not (False, default) - """ - return False + # 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. - # 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. + Returns: + dict: Additional data to persist in the preemptive cache configuration. - Only relevant for UiPlugins that actually utilize the stock templates of OctoPrint. + ..versionadded:: 1.3.0 + """ + return None - By default simply returns the provided ``default_template_filter``. + # 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. - Arguments: - default_template_filter (callable): The default template filter used by the default UI + 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) + + ..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 + + # noinspection PyMethodMayBeStatic + def get_ui_permissions(self): + """ + Determines a list of permissions that need to be on the current user session. If + these requirements are not met, OctoPrint will instead redirect to a login + screen. + + Plugins may override this with their own set of permissions. Returning an empty + list will instruct OctoPrint to never show a login dialog when this UiPlugin's + view renders, in which case it will fall to your plugin to implement its own + login logic. + + Returns: + (list) A list of permissions which to check the current user session against. + May be empty to indicate that no permission checks should be made by OctoPrint. + + ..versionadded: 1.5.0 + """ + from octoprint.access.permissions import Permissions + + return [Permissions.STATUS, Permissions.SETTINGS_READ] - 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. - """ - 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 dict() + 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. - """ - 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 + return decorator - # 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. + @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. - This method will only be called once during server initialization. + See `the documentation for flask.Blueprint.errorhandler `_ + and `the documentation for flask.Flask.errorhandler `_ for more + information. - :return: the blueprint ready to be registered with Flask - """ + ..versionadded:: 1.3.0 + """ + from collections import defaultdict - 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 + 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 - import flask - kwargs = self.get_blueprint_kwargs() - blueprint = flask.Blueprint("plugin." + self._identifier, self._identifier, **kwargs) + return decorator - # 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) + # 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. - 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) + This method will only be called once during server initialization. - 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: the blueprint ready to be registered with Flask + """ - # cache and return the blueprint object - self._blueprint = blueprint - return blueprint + 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 - def get_blueprint_kwargs(self): - """ - Override this if you want your blueprint constructed with additional options such as ``static_folder``, - ``template_folder``, etc. + import flask - 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 + kwargs = self.get_blueprint_kwargs() + blueprint = flask.Blueprint( + "plugin." + self._identifier, self._identifier, **kwargs + ) - if isinstance(self, AssetPlugin): - static_folder = self.get_asset_folder() - else: - static_folder = os.path.join(self._basefolder, "static") + # 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, TemplatePlugin): - template_folder = self.get_template_folder() - else: - template_folder = os.path.join(self._basefolder, "templates") + 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 dict( - static_folder=static_folder, - template_folder=template_folder - ) + 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) - # 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. + # cache and return the blueprint object + self._blueprint = blueprint + return blueprint - If you want your blueprint's endpoints to have specific permissions, return ``False`` for this and do your - permissions checks explicitly. - """ + def get_blueprint_kwargs(self): + """ + Override this if you want your blueprint constructed with additional options such as ``static_folder``, + ``template_folder``, etc. - return True + 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 + + 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] = dict() - elif isinstance(node[key], (list, tuple)): - node[key] = [] - else: - node[key] = None - - conditions = dict(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 = dict() - - # 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 dict() - - # 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)))) - """ - return dict() - - # 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 dict(), dict() - - # 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). - """ - 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 dict( - 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. - """ - from octoprint.filemanager import ContentTypeMapping - return dict(model=dict(stl=ContentTypeMapping(["stl"], "application/sla"))) + Returns: (dict) a dictionary containing a valid extension subtree. - def get_slicer_profiles(self, profile_path): - """ - Fetch all :class:`~octoprint.slicing.SlicingProfile` stored for this slicer. + ..versionadded:: 1.3.11 + """ + from octoprint.filemanager import ContentTypeMapping - 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. + return {"model": {"stl": ContentTypeMapping(["stl"], "application/sla")}} - Arguments: - profile_path (str): The base folder where OctoPrint stores this slicer plugin's profiles - """ + def get_slicer_profiles(self, profile_path): + """ + Fetch all :class:`~octoprint.slicing.SlicingProfile` stored for this slicer. - try: - from os import scandir - except ImportError: - from scandir import scandir + 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. - import octoprint.util + Arguments: + profile_path (str): The base folder where OctoPrint stores this slicer plugin's profiles - profiles = dict() - 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 + ..versionadded:: 1.3.7 + """ - profile_name = entry.name[:-len(".profile")] - profiles[profile_name] = self.get_slicer_profile(entry.path) - return profiles + try: + from os import scandir + except ImportError: + from scandir import scandir - # noinspection PyMethodMayBeStatic - def get_slicer_profiles_lastmodified(self, profile_path): - import os - try: - from os import scandir - except ImportError: - from scandir import scandir + import octoprint.util - 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) + 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_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. + profile_name = entry.name[: -len(".profile")] + profiles[profile_name] = self.get_slicer_profile(entry.path) + return profiles - Returns: - SlicingProfile: The :class:`~octoprint.slicing.SlicingProfile` containing the default slicing profile for - this slicer. - """ - return None + # noinspection PyMethodMayBeStatic + def get_slicer_profiles_lastmodified(self, profile_path): + """ + ..versionadded:: 1.3.0 + """ + import os - # 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``. + try: + from os import scandir + except ImportError: + from scandir import scandir - Arguments: - path (str): The absolute path from which to read the slicing profile. + 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) - Returns: - SlicingProfile: The specified slicing profile. - """ - return None + # 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. - # 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. + Returns: + SlicingProfile: The :class:`~octoprint.slicing.SlicingProfile` containing the default slicing profile for + this slicer. + """ + return None - 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 + # 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 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``. + Arguments: + path (str): The absolute path from which to read the slicing profile. - 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. + Returns: + SlicingProfile: The specified slicing profile. + """ + return None - 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 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. - ``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: + 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 - .. code-block:: python + # 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``. - 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() + 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. - on_progress_kwargs["_progress"] = your_plugins_slicing_progress - on_progress(*on_progress_args, **on_progress_kwargs) + 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. - 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. + ``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: - 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. + .. code-block:: python - 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. + 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() - For jobs that finished successfully, ``result`` should be a :class:`dict` containing additional information - about the slicing job under the following keys: + on_progress_kwargs["_progress"] = your_plugins_slicing_progress + on_progress(*on_progress_args, **on_progress_kwargs) - 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. + 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 did not finish successfully (but not due to being cancelled!), ``result`` should be a :class:`str` - containing a human readable reason for the error. + 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. - If the job gets cancelled, a :class:`~octoprint.slicing.SlicingCancelled` exception should be raised. + 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. - Returns: - tuple: A 2-tuple (boolean, object) as outlined above. + For jobs that finished successfully, ``result`` should be a :class:`dict` containing additional information + about the slicing job under the following keys: - Raises: - SlicingCancelled: The slicing job was cancelled (via :meth:`cancel_slicing`). - """ - pass + 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. - # noinspection PyMethodMayBeStatic - def cancel_slicing(self, machinecode_path): - """ - Cancels the slicing to the indicated file. + 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. - Arguments: - machinecode_path (str): The absolute path to the machine code file to which to stop slicing to. - """ - pass + If the job gets cancelled, a :class:`~octoprint.slicing.SlicingCancelled` exception should be raised. + + Returns: + tuple: A 2-tuple (boolean, object) as outlined above. + + 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 eb06109a7..e58007004 100644 --- a/src/octoprint/plugins/action_command_notification/__init__.py +++ b/src/octoprint/plugins/action_command_notification/__init__.py @@ -1,132 +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) 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 [ - dict(key="SHOW", - name="Show printer notifications", - description=gettext("Allows to see printer notifications"), - default_groups=[USER_GROUP], - roles=["show"]), - dict(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 dict(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 dict(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=[dict(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 dict(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 [ - dict(type="settings", - name=gettext("Printer Notifications"), - custom_bindings=False), - dict(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"], + "template_header": "action_command_notification_sidebar_header.jinja2", + "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, dict(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, dict()) - 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/css/action_command_notification.css b/src/octoprint/plugins/action_command_notification/static/css/action_command_notification.css index ed15d2c39..e15340a1e 100644 --- a/src/octoprint/plugins/action_command_notification/static/css/action_command_notification.css +++ b/src/octoprint/plugins/action_command_notification/static/css/action_command_notification.css @@ -3,3 +3,9 @@ line-height: 20px; border-bottom: 1px solid #ddd; } + +.sidebar_plugin_action_command_notification_scrollable { + overflow-x: hidden; + overflow-y: scroll; + max-height: 306px; +} 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..c9f092d75 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; @@ -7,41 +7,71 @@ $(function() { self.settings = parameters[2]; self.notifications = ko.observableArray([]); + self.sortDesc = ko.observable(false); + self.sortDesc.subscribe(function () { + self._toLocalStorage(); + }); - 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.notifications(response.notifications); + self.fromResponse = function (response) { + var notifications = response.notifications; + if (self.sortDesc()) { + notifications.reverse(); + } + self.notifications(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.toggleSorting = function () { + self.sortDesc(!self.sortDesc()); self.requestData(); }; - self.onDataUpdaterPluginMessage = function(plugin, data) { - if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW)) return; + 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; 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, @@ -55,6 +85,19 @@ $(function() { } }; + var optionsLocalStorageKey = "core.gcodeviewer.options"; + self._toLocalStorage = function () { + saveToLocalStorage(optionsLocalStorageKey, {sortDesc: self.sortDesc()}); + }; + + self._fromLocalStorage = function () { + var data = loadFromLocalStorage(optionsLocalStorageKey); + if (data["sortDesc"] !== undefined) { + self.sortDesc(!!data["sortDesc"]); + } + }; + + self._fromLocalStorage(); } OCTOPRINT_VIEWMODELS.push({ diff --git a/src/octoprint/plugins/action_command_notification/templates/action_command_notification_settings.jinja2 b/src/octoprint/plugins/action_command_notification/templates/action_command_notification_settings.jinja2 index 64f676176..a5d079b9b 100644 --- a/src/octoprint/plugins/action_command_notification/templates/action_command_notification_settings.jinja2 +++ b/src/octoprint/plugins/action_command_notification/templates/action_command_notification_settings.jinja2 @@ -1,6 +1,6 @@

{{ _('Action Command Notification Settings') }}

-
+