diff --git a/.editorconfig b/.editorconfig index bf65494f2..278fd7b94 100644 --- a/.editorconfig +++ b/.editorconfig @@ -8,15 +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 +[**.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/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 000000000..5311f0fa2 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,3 @@ +# someone from the docker-maintainers team will be requested for review +# whenever the trigger_docker workflow is changed in a Pull Request +.github/workflows/trigger_docker.yml @OctoPrint/docker-maintainers diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index 7ee1a4b4c..000000000 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,135 +0,0 @@ ---- -name: Bug report -about: Create a report to help improve OctoPrint - ---- - - - -#### What were you doing? - - - -1. Go to '...' -2. Click on '....' -3. Scroll down to '....' -4. See error - - - -#### What did you expect to happen? - -#### What happened instead? - -#### Did the same happen when running OctoPrint in safe mode? - - - -#### Version of OctoPrint - - - -#### Operating System running OctoPrint - - - -#### Printer model & used firmware incl. version - - - -#### Browser and version of browser, operating system running browser - - - -#### Link to octoprint.log - - - -#### Link to contents of terminal tab or serial.log - - - -#### Link to contents of Javascript console in the browser - - - -#### Screenshot(s)/video(s) showing the problem: - - - -I have read the FAQ. diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 000000000..6e56ba502 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,121 @@ +name: Bug report +about: Create a report to help improve OctoPrint +title: "" +issue_body: true +inputs: + - type: description + attributes: + value: > + **Thank you for wanting to report a bug in OctoPrint!** + + + If this is the first time you are doing this, please take a few moments to read + through the [Contribution Guidelines](https://github.com/OctoPrint/OctoPrint/blob/master/CONTRIBUTING.md). + Also check out [the FAQ](https://faq.octoprint.org) if your + problem is maybe already covered there. + + + You are about to report a bug in **OctoPrint**. Do not proceed if your issues + occurs with OctoPi, any third party OctoPrint plugins, unofficial or outdated + OctoPrint versions. If you are unsure of the difference between OctoPrint and + OctoPi, [read this FAQ entry](https://faq.octoprint.org/octoprint-vs-octopi). + + + Do also not seek support here ("I need help with ...", "I have a + question ...", "Can someone walk me through ..."), that belongs into the + [community forum at community.octoprint.org](https://community.octoprint.org) or on the [Discord server](https://discord.octoprint.org). + + + And finally, make sure any bug you want to report is still present with the **current** + OctoPrint version and that it does not vanish when you start OctoPrint + in [safe mode](https://docs.octoprint.org/en/master/features/safemode.html) either. + + + Thank you for your collaboration! + - type: textarea + attributes: + label: The problem + required: true + description: >- + Describe the issue you are experiencing here. Tell us what you were trying to do + step by step, and what happened that you did not expect. + + Provide a clear and concise description of what the problem is and include as many + details as possible. + placeholder: | + 1. ... + 2. ... + 3. ... + - type: dropdown + attributes: + label: Did the issue persist even in safe mode? + description: >- + Testing in safe mode is required to make sure the issue you are reporting is not + caused by a third party plugin. Please see [here](https://docs.octoprint.org/en/master/features/safemode.html) + on how to run OctoPrint in safe mode. + choices: + - Yes, it did persist + - No, it did not persist (it's an issue with one of your installed plugins, don't report here) + - I cannot test this issue in safe mode (state why below) + required: true + - type: description + attributes: + value: | + ## Environment + - type: input + attributes: + label: Version of OctoPrint + description: Can be found in the lower left corner of the web interface. + required: true + - type: input + attributes: + label: Operating system running OctoPrint + description: >- + OctoPi, Linux, Windows, MacOS, something else? With version please? OctoPi's + version can be found in `/etc/octopi_version` or in the lower left corner of the + web interface. + required: true + - type: input + attributes: + label: Printer model & used firmware incl. version + description: If applicable, always include if unsure + - type: input + attributes: + label: Browser and version of browser, operating system running browser + description: If applicable, always include if unsure + - type: description + attributes: + value: | + ## Logs and other files needed for analysis + - type: description + attributes: + value: >- + Please also be sure to upload the following files below: + + * `octoprint.log`: See [here](https://community.octoprint.org/t/where-can-i-find-octoprints-and-octopis-log-files/299) if you don't know where to find that. + * `serial.log` or the contents of your terminal tab, if applicable. Always + include if unsure. **Please note that you need to enable `serial.log` first**, + see [here](https://community.octoprint.org/t/where-can-i-find-octoprints-and-octopis-log-files/299) if you don't know how to do or where to find it. + * Your browser's JavaScript console, if you are reporting a problem with the + user interface. See [here](https://webmasters.stackexchange.com/questions/8525/how-to-open-the-javascript-console-in-different-browsers) on where to find that. + * If possible, screenshots or videos showing the problem, especially if you + are reporting a problem with the user interface! + * GCODE files with which to reproduce, if you are reporting an issue with + GCODE file analysis or printing behaviour. + + Please be aware that unless at least `octoprint.log` is included, your bug report + will not be processed. + - type: checkboxes + attributes: + label: Checklist of files to include below + choices: + - label: octoprint.log + required: true + - label: serial.log or contents of your terminal tab (always include in cases of issues with printer communication) + - label: Contents of the JavaScript browser console (always include in cases of issues with the user interface) + - label: Screenshots and/or videos showing the problem (always include in case of issues with the user interface) + - label: GCODE file with which to reproduce (always include in case of issues with GCODE analysis or printing behaviour) + - type: description + attributes: + value: | + ## Additional information & file uploads diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 000000000..eb9fb4bd9 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,4 @@ +contact_links: + - name: Have questions or need support? + url: https://community.octoprint.org + about: Please get in touch on the OctoPrint Community Forum! diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index 8842b0ca0..cd4966224 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -1,6 +1,7 @@ --- name: Feature request about: Suggest an idea for this project +title: '[Request]' --- diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 51764038b..9d7dce15b 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -16,15 +16,15 @@ checklist: made sure your changes don't interfere with current development by talking it through with the maintainers, e.g. through a Brainstorming ticket - * [ ] Your PR targets OctoPrint's devel branch if it's a completely + * [ ] Your PR targets OctoPrint's devel branch if it's a completely new feature, or maintenance if it's a bug fix or improvement of - existing functionality for the current stable version (no PRs + existing functionality for the current stable version (no PRs against master or anything else please) * [ ] Your PR was opened from a custom branch on your repository (no PRs from your version of master, maintenance or devel please), e.g. dev/my_new_feature or fix/my_bugfix * [ ] Your PR only contains relevant changes: no unrelated files, - no dead code, ideally only one commit - rebase and squash your PR + no dead code, ideally only one commit - rebase and squash your PR if necessary! * [ ] Your changes follow the existing coding style * [ ] If your changes include style sheets: You have modified the @@ -37,7 +37,7 @@ checklist: * [ ] You have added yourself to the AUTHORS.md file :) diff --git a/.github/fixtures/with_acl/config.yaml b/.github/fixtures/with_acl/config.yaml new file mode 100644 index 000000000..57fadccbf --- /dev/null +++ b/.github/fixtures/with_acl/config.yaml @@ -0,0 +1,18 @@ +accessControl: + salt: zXmvzI3uWuTLkSPOEfA2ZLwn3f3sGUNS +plugins: + 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 diff --git a/.github/fixtures/with_acl/users.yaml b/.github/fixtures/with_acl/users.yaml new file mode 100644 index 000000000..7ac3a086d --- /dev/null +++ b/.github/fixtures/with_acl/users.yaml @@ -0,0 +1,22 @@ +admin: + active: true + apikey: null + groups: + - admins + - users + password: 3033587f3b040680c77ce4fb7e8d61422878ef49a2a784227689f3b44ce66ada7f6161f8b2b037267f0d37b783a5600276eb88e1d224d24915f64e187a49a89f + permissions: [] + roles: + - user + - admin + settings: {} +user: + active: true + apikey: null + groups: + - users + password: 3033587f3b040680c77ce4fb7e8d61422878ef49a2a784227689f3b44ce66ada7f6161f8b2b037267f0d37b783a5600276eb88e1d224d24915f64e187a49a89f + permissions: [] + roles: + - user + settings: {} diff --git a/.github/issue-validation.yml b/.github/issue-validation.yml new file mode 100644 index 000000000..763ca73a2 --- /dev/null +++ b/.github/issue-validation.yml @@ -0,0 +1,62 @@ +approve_label: approved +problem_label: incomplete +ignored_labels: + - approved + - bug + - request + - improvement + - brainstorming + - task + - rc feedback + - awaiting information + - not octoprint + - done +ignored_authors: + - "@OctoPrint" + - "sentry-io" + - "FormerLurker" + - "bzed" + +validation_comment: > + Hi @@@AUTHOR@@, + + + it looks like there is some **information missing** from your bug report that will + be needed in order to solve the problem. Read the [Contribution Guidelines](https://github.com/OctoPrint/OctoPrint/blob/master/CONTRIBUTING.md) + which will provide you with a template to *fully fill out* here so that your bug report + is ready to be investigated (I promise I'll go away then too!). + + + If you did not intend to report a bug but wanted to **request a feature or brain + storm** about some kind of development, please take special note of the title format + to use as described in the [Contribution Guidelines](https://github.com/OctoPrint/OctoPrint/blob/master/CONTRIBUTING.md). + + + **Please do not abuse the bug tracker as a support forum** - that can be found at + [community.octoprint.org](https://community.octoprint.org). Go there for any kind + of issues with network connectivity, webcam functionality, printer detection or + any other kind of such support requests or general questions. + + + Also **make sure you are at the right place** - this is the bug tracker of the official + version of OctoPrint, not the Raspberry Pi image OctoPi nor any unbundled third + party OctoPrint plugins or unofficial versions. Make sure too that you have **read + through the [Frequently Asked Questions](http://faq.octoprint.org)** and searched + the [**existing tickets**](https://github.com/OctoPrint/OctoPrint/issues) + for your problem - try multiple search terms please. + + + I'm marking this one now as needing some more information. Please understand that + if you do not provide that information within the next two weeks + I'll close this ticket so it doesn't clutter the bug tracker. This is nothing + personal, it's needed to keep this project manageable. Please just be considerate + and help the maintainers solve this problem + quickly by following the guidelines linked above. Remember, the less time the devs + have to spend running after information on tickets, the more time they have to actually + solve problems and add awesome new features. Thank you! + + + *I'm just a bot 🤖, not a human being, so don't expect any replies + from me :) Your ticket is read by humans too, I'm just not one of them.* + +keyphrase: I have read the FAQ diff --git a/.github/labeler.yml b/.github/labeler.yml new file mode 100644 index 000000000..ed3f1c77a --- /dev/null +++ b/.github/labeler.yml @@ -0,0 +1,25 @@ +docs: + - "docs/*" + - "docs/**/*" + - "README.md" + +meta: + - "CODE_OF_CONDUCT.md" + - "CONTRIBUTING.md" + - "SECURITY.md" + - ".github/CODEOWNERS" + - ".github/FUNDING.yml" + - ".github/ISSUE_TEMPLATE/*" + - ".github/PULL_REQUEST_TEMPLATE.md" + +ci/cd: + - ".github/fixtures/**/*" + - ".github/workflows/*" + - ".github/labeler.yml" + +docker: + - ".github/workflows/trigger_docker.yml" + +tests: + - "tests/*" + - "tests/**/*" diff --git a/.github/pr-validation.yml b/.github/pr-validation.yml new file mode 100644 index 000000000..b6644f25c --- /dev/null +++ b/.github/pr-validation.yml @@ -0,0 +1,14 @@ +approve_label: "approved" +problem_label: "needs some work" + +allowed_targets: ["maintenance", "devel", "staging/maintenance", "staging/devel"] +forbidden_sources: + ["master", "maintenance", "devel", "staging/maintenance", "staging/devel"] + +labels: + docs: + additional_allowed_targets: ["master"] + meta: + additional_allowed_targets: ["master"] + ci/cd: + additional_allowed_targets: ["master"] diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 000000000..1116d1640 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,229 @@ +name: Build +on: + push: + pull_request: + release: + types: [released, prereleased] + workflow_dispatch: + +jobs: + build: + name: 🔨 Build distribution + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + with: + fetch-depth: 0 + - name: 🏗 Set up Python 3.7 + uses: actions/setup-python@v1 + with: + python-version: 3.7 + - name: 🏗 Install build dependencies + run: | + python -m pip install wheel --user + - name: 🔨 Build a binary wheel and a source tarball + run: | + python setup.py sdist bdist_wheel + - name: ⬆ Upload build result + uses: actions/upload-artifact@v1 + with: + 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: + matrix: + python: ["3.7", "3.8"] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: 🏗 Set up Python ${{ matrix.python }} + uses: actions/setup-python@v1 + with: + python-version: ${{ matrix.python }} + - name: 🏗 Set up test dependencies + run: | + pip install -e .[develop] + - name: 🚀 Run test suite + run: | + pytest + + test-install: + name: 🧪 Installation tests + needs: build + strategy: + matrix: + python: ["3.7", "3.8"] + installable: ["wheel", "sdist"] + runs-on: ubuntu-latest + steps: + - name: ⬇ Download build result + uses: actions/download-artifact@v1 + with: + name: dist + path: dist + - name: 🏗 Set up Python ${{ matrix.python }} + uses: actions/setup-python@v1 + with: + python-version: ${{ matrix.python }} + - name: 🚀 Install wheel + if: matrix.installable == 'wheel' + run: | + pip install dist/OctoPrint-*-py2.py3-none-any.whl + - name: 🚀 Install source tarball + if: matrix.installable == 'sdist' + run: | + pip install dist/OctoPrint-*.tar.gz + + test-e2e: + name: 🧪 E2E tests + needs: build + runs-on: ubuntu-16.04 + steps: + - name: ⬇ Checkout code + uses: actions/checkout@v2 + + - name: ⬇ Download build result + uses: actions/download-artifact@v1 + with: + name: dist + path: dist + - name: 🏗 Set up Python 3.7 + uses: actions/setup-python@v1 + with: + python-version: 3.7 + - name: 🚀 Install wheel + run: | + pip install dist/OctoPrint-*-py2.py3-none-any.whl + + - name: 🏗 Create base config for test server + run: | + mkdir e2econfig + cp -r .github/fixtures/with_acl/* e2econfig + + - name: 🚀 Run Cypress + uses: cypress-io/github-action@v2 + 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" + + - name: ⬆ Upload screenshots + uses: actions/upload-artifact@v1 + if: failure() + with: + name: cypress-screenshots + path: tests/cypress/screenshots + - name: ⬆ Upload videos + uses: actions/upload-artifact@v1 + if: always() + with: + name: cypress-videos + path: tests/cypress/videos + + publish-on-testpypi: + name: 📦 Publish on TestPyPI + if: github.event_name == 'release' + needs: + - lint-black + - lint-prettier + - lint-isort + - lint-flake8 + - test-unit + - test-install + - test-e2e + runs-on: ubuntu-latest + steps: + - name: ⬇ Download build result + uses: actions/download-artifact@v1 + with: + name: dist + path: dist + - name: 📦 Publish to index + uses: pypa/gh-action-pypi-publish@master + continue-on-error: true + with: + password: ${{ secrets.testpypi_password }} + repository_url: https://test.pypi.org/legacy/ + + publish-on-pypi: + name: 📦 Publish tagged releases to PyPI + if: github.event_name == 'release' + needs: publish-on-testpypi + runs-on: ubuntu-latest + steps: + - name: ⬇ Download build result + uses: actions/download-artifact@v1 + with: + name: dist + path: dist + - name: 📦 Publish to index + uses: pypa/gh-action-pypi-publish@master + with: + password: ${{ secrets.pypi_password }} diff --git a/.github/workflows/cleanup.yml b/.github/workflows/cleanup.yml new file mode 100644 index 000000000..80ff4f957 --- /dev/null +++ b/.github/workflows/cleanup.yml @@ -0,0 +1,37 @@ +name: "Cleanup issues & PRs" + +on: + schedule: + - cron: "0 0 * * *" + workflow_dispatch: + +jobs: + lock: + name: 🔒 Lock issues & PRs closed over a year + runs-on: ubuntu-latest + steps: + - uses: dessant/lock-threads@v2 + with: + github-token: ${{ github.token }} + issue-lock-comment: "" + pr-lock-comment: "" + + cleanup: + name: 🧹 Close issues marked as incomplete & older than 14 days + runs-on: ubuntu-latest + steps: + - id: date + run: | + echo "::set-output name=CUTOFF::`date --date='14 days ago' +'%Y-%m-%d'`" + - uses: OctoPrint/actions/close-by-query@main + with: + repo-token: "${{ secrets.GITHUB_TOKEN }}" + query: "is:issue is:open label:incomplete created:<${{ steps.date.outputs.CUTOFF }}" + comment: > + Since apparently some of the required information is still missing, this will be + closed now, sorry. Feel free to request a reopen of this or create a new issue + once you can provide **all** + [required information](https://github.com/OctoPrint/OctoPrint/blob/master/CONTRIBUTING.md#how-to-file-a-bug-report). + + + This is nothing personal. Thank you for your collaboration. diff --git a/.github/workflows/issue_automation.yml b/.github/workflows/issue_automation.yml new file mode 100644 index 000000000..fb59a7d97 --- /dev/null +++ b/.github/workflows/issue_automation.yml @@ -0,0 +1,69 @@ +name: "Issue Automation" +on: + issues: + types: [opened, edited, closed, reopened] + +jobs: + issue-automation: + runs-on: ubuntu-latest + steps: + - uses: actions/github-script@v2 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + let labels = []; + let setLabels = false; + context.payload.issue.labels.forEach(label => { labels.push(label.name) }); + + switch (context.payload.action) { + + case 'opened': + case 'edited': { + if (context.payload.issue.title.match(/\[request\]|feature request/i)) { + labels.push('request'); + labels = labels.filter(label => label !== 'triage'); + setLabels = true; + } + if (context.payload.issue.title.match(/\[rc feedback\]/i)) { + labels.push('rc feedback'); + labels = labels.filter(label => label !== 'triage'); + setLabels = true; + } + + if (labels.length === 0) { + labels.push('triage'); + setLabels = true; + } + break; + } + + case 'closed': { + if (labels.includes('bug') || labels.includes('request') || labels.includes('improvement')) { + labels.push('done'); + setLabels = true; + } + break; + } + + case 'reopened': { + if (labels.includes('done')) { + labels = labels.filter(label => label !== 'done'); + setLabels = true; + } + break; + } + } + + if (setLabels) { + github.issues.setLabels({ + issue_number: context.issue.number, + owner: context.repo.owner, + repo: context.repo.repo, + labels: labels + }) + } + + #- uses: OctoPrint/actions/issue-validation@main + # if: github.event_name == 'issues' && (github.event.action == 'opened' || github.event.action == 'edited') + # with: + # repo-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/linkify_bundles.yml b/.github/workflows/linkify_bundles.yml new file mode 100644 index 000000000..9e0553891 --- /dev/null +++ b/.github/workflows/linkify_bundles.yml @@ -0,0 +1,54 @@ +name: "Linkify systeminfo bundles" +on: + issue_comment: + types: [created, edited] + +jobs: + linkifyBundles: + runs-on: ubuntu-latest + steps: + - uses: actions/github-script@v2 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + let comment = context.payload.comment.body; + + const botMarker = ""; + const botWasHere = comment.indexOf(botMarker); + if (botWasHere !== -1) { + comment = comment.substring(0, botWasHere); + }; + + const bundleRegex = /\[(octoprint-systeminfo-\d{14}\.zip)\]\(([^)]+)\)/g; + + const bundles = []; + const seen = []; + const matches = comment.matchAll(bundleRegex); + for (const match of matches) { + if (!seen.includes(match[1])) { + bundles.push({filename: match[1], link: match[2], match: match[0]}); + seen.push(match[1]); + } + }; + + if (bundles.length > 0) { + let text = comment + botMarker + "\n\n---\n\n\nBundles:\n\n"; + bundles.forEach((bundle) => { + text += " * [" + bundle.filename + "](https://bundleviewer.octoprint.org/?url=" + encodeURIComponent(bundle.link) + ")\n" + }); + text += "\n*edited by @github-actions to add bundle viewer links*\n"; + + github.issues.updateComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: context.payload.comment.id, + body: text + }); + } else if (botWasHere !== -1) { + github.issues.updateComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: context.payload.comment.id, + body: comment + }); + } diff --git a/.github/workflows/pr_automation.yml b/.github/workflows/pr_automation.yml new file mode 100644 index 000000000..659733438 --- /dev/null +++ b/.github/workflows/pr_automation.yml @@ -0,0 +1,16 @@ +name: "Pull Request Automation" +on: + pull_request_target: + types: ["opened", "synchronize", "reopened", "edited", "labeled", "unlabeled"] + +jobs: + pr-automation: + runs-on: ubuntu-latest + steps: + - uses: actions/labeler@v3 + with: + repo-token: "${{ secrets.GITHUB_TOKEN }}" + + - uses: OctoPrint/actions/pr-validation@main + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/test_install.yml b/.github/workflows/test_install.yml new file mode 100644 index 000000000..b1a0bc8ec --- /dev/null +++ b/.github/workflows/test_install.yml @@ -0,0 +1,79 @@ +name: Test install of branches and latest release twice per day + +on: + push: + branches: + - master + workflow_dispatch: + schedule: + - cron: "0 */12 * * *" + +jobs: + install-branch: + name: Install branch + strategy: + matrix: + os: ["ubuntu-latest"] + python: ["3.7", "3.8"] + branch: ["master"] + runs-on: ${{ matrix.os }} + steps: + - name: 🐍 Set up Python ${{ matrix.python }} + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python }} + - name: ⬇ Checkout code + uses: actions/checkout@v2 + with: + ref: ${{ matrix.branch }} + fetch-depth: 0 + - name: 👷 Build and install checkout + run: | + pip install . + - name: 📧 Discord success notification + 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 }}` 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" + + install-latest: + name: Install latest release + strategy: + matrix: + os: ["ubuntu-latest"] + python: ["3.7", "3.8"] + runs-on: ${{ matrix.os }} + steps: + - name: 👀 Determine latest release + id: latest + uses: foosel/github-action-get-latest-release@master + with: + repository: "OctoPrint/OctoPrint" + - name: 🐍 Set up Python ${{ matrix.python }} + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python }} + - name: 👷 Build and install latest release + run: | + pip install https://github.com/OctoPrint/OctoPrint/archive/${{ steps.latest.outputs.release }}.zip + - name: 📧 Discord success notification + 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 }}` 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" diff --git a/.github/workflows/trigger_docker.yml b/.github/workflows/trigger_docker.yml new file mode 100644 index 000000000..1a86bb0c6 --- /dev/null +++ b/.github/workflows/trigger_docker.yml @@ -0,0 +1,47 @@ +name: Trigger docker build +on: + release: + types: + - released + - prereleased + push: + branches: + - maintenance + - devel + +jobs: + dispatch_releases: + runs-on: ubuntu-latest + if: github.repository == 'OctoPrint/OctoPrint' && github.event_name != 'push' + steps: + - name: 🚀 Repository Dispatch + uses: peter-evans/repository-dispatch@v1 + with: + token: ${{ secrets.DOCKER_ACCESS_TOKEN }} + repository: ${{ github.repository_owner }}/octoprint-docker + event-type: ${{ github.event.action }} + client-payload: '{"tag_name": "${{ github.event.release.tag_name }}"}' + + dispatch_canary: + runs-on: ubuntu-latest + if: github.repository == 'OctoPrint/OctoPrint' && github.event_name == 'push' && github.ref == 'refs/heads/maintenance' + steps: + - name: 🚀 Repository Dispatch + uses: peter-evans/repository-dispatch@v1 + with: + token: ${{ secrets.DOCKER_ACCESS_TOKEN }} + repository: ${{ github.repository_owner }}/octoprint-docker + event-type: "canary" + client-payload: '{"tag_name": "maintenance"}' + + dispatch_bleeding: + runs-on: ubuntu-latest + if: github.repository == 'OctoPrint/OctoPrint' && github.event_name == 'push' && github.ref == 'refs/heads/devel' + steps: + - name: 🚀 Repository Dispatch + uses: peter-evans/repository-dispatch@v1 + with: + token: ${{ secrets.DOCKER_ACCESS_TOKEN }} + repository: ${{ github.repository_owner }}/octoprint-docker + event-type: "bleeding" + client-payload: '{"tag_name": "devel"}' diff --git a/.github/workflows/trigger_docs.yml b/.github/workflows/trigger_docs.yml new file mode 100644 index 000000000..492d5ef5b --- /dev/null +++ b/.github/workflows/trigger_docs.yml @@ -0,0 +1,20 @@ +name: Trigger doc build +on: + push: + release: + types: + - released + - prereleased + +jobs: + trigger: + runs-on: ubuntu-latest + if: github.repository == 'OctoPrint/OctoPrint' + steps: + - name: 🚀 Repository Dispatch + uses: peter-evans/repository-dispatch@v1 + with: + token: ${{ secrets.DOCS_ACCESS_TOKEN }} + repository: OctoPrint/docs.octoprint.org + event-type: docs + client-payload: '{"ref": "${{ github.ref }}", "sha": "${{ github.sha }}"}' diff --git a/.gitignore b/.gitignore index 856725dd2..c988710df 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,8 @@ 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 @@ -17,26 +19,28 @@ win32-Cura-* linux-Cura-* *.iml Printrun -======= .idea +.vscode .DS_Store Cura/current_profile.ini Cura/preferences.ini build dist pypy -OctoPrint.egg-info -*.orig +*.orig *.codekit -venv -venv2 -venv3 -venv26 -venv27 -venv33 -venv34 -venv35 -venv36 -venv37 +*.egg-info +.eggs +.mypy_cache +.pytest_cache +.python-version +.tox + +venv* +testconf* + +node_modules +tests/cypress/screenshots +tests/cypress/videos diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 000000000..90d2be578 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,54 @@ +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: v3.2.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 + args: ["--remove"] + - repo: https://github.com/OctoPrint/codemods + rev: devel + hooks: + - id: codemod_remove_future_imports + args: ["--ignore", "src/octoprint/vendor"] + stages: ["manual"] + - id: codemod_remove_builtins_imports + args: ["--ignore", "src/octoprint/vendor"] + stages: ["manual"] + - id: codemod_detect_past_builtins_imports + args: ["--ignore", "src/octoprint/vendor"] + stages: ["manual"] + - 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.4 + 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/.travis.yml b/.travis.yml deleted file mode 100644 index b1f687f3e..000000000 --- a/.travis.yml +++ /dev/null @@ -1,22 +0,0 @@ ---- - -language: python -dist: xenial - -matrix: - include: - - python: '3.7' - env: RUN_FLAKE8=true - -python: -- "3.7" -- "3.6" -- "2.7" -install: -- pip install -e .[develop] -script: -- test -n "$RUN_FLAKE8" || pytest -- test -z "$RUN_FLAKE8" || flake8 --ignore=D,E,W,F401 src/ tests setup.py -sudo: false -git: - depth: 250 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 212fdecdb..6f5e25bb4 100644 --- a/.versioneer-lookup +++ b/.versioneer-lookup @@ -18,16 +18,24 @@ prerelease HEAD \(detached.* -# maintenance is currently the branch for preparation of maintenance release 1.3.13 +# maintenance is currently the branch for preparation of maintenance release 1.6.0 # so are any fix/... and improve/... branches -maintenance 1.3.13 2a42f02aecaedf2c55579984e0bc94e44402cc15 pep440-dev -fix/.* 1.3.13 2a42f02aecaedf2c55579984e0bc94e44402cc15 pep440-dev -improve/.* 1.3.13 2a42f02aecaedf2c55579984e0bc94e44402cc15 pep440-dev +maintenance 1.6.0 b7a45b79bf86339f0b28177ac1eaebb56d00ea37 pep440-dev +fix/.* 1.6.0 b7a45b79bf86339f0b28177ac1eaebb56d00ea37 pep440-dev +improve/.* 1.6.0 b7a45b79bf86339f0b28177ac1eaebb56d00ea37 pep440-dev -# staging/maintenance is currently the branch for preparation of 1.3.12rc3 +# staging/bugfix is the branch for preparation of the 1.5.3 hotfix release +# so are any bug/... branches +staging/bugfix 1.5.3 e46e8fa17a1553cd0c228a4fa4cfd93e2a9bce7b pep440-dev +bug/.* 1.5.3 e46e8fa17a1553cd0c228a4fa4cfd93e2a9bce7b pep440-dev + +# staging/maintenance is currently the branch for preparation of 1.5.0rc4 # so is regressionfix/... -staging/maintenance 1.3.12rc3 c4258c5bb0eae30595e6463281f266582096ad48 pep440-dev -regressionfix/.* 1.3.12rc3 c4258c5bb0eae30595e6463281f266582096ad48 pep440-dev +staging/maintenance 1.5.0rc4 5e7ea35239908f9ed91895751d8a8202aa76ed4b pep440-dev +regressionfix/.* 1.5.0rc4 5e7ea35239908f9ed91895751d8a8202aa76ed4b pep440-dev -# every other branch is a development branch and thus gets resolved to 1.4.0-dev for now -.* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev +# staging/devel is currently inactive (but has the 1.4.1rc4 namespace) +staging/devel 1.4.1rc4 650d54d1885409fa1d411eb54b9e8c7ff428910f pep440-dev + +# every other branch is a development branch and thus gets resolved to 2.0.0.dev for now +.* 2.0.0 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev diff --git a/AUTHORS.md b/AUTHORS.md index 8dd38e1ce..c996bc1a4 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -111,6 +111,33 @@ date of first contribution): * [Piotr Usewicz](https://github.com/pusewicz) * [Aliaksei Pilko](https://github.com/aliaksei135) * [Ben Yarmis](https://github.com/byarmis) + * [Florian Heilmann](https://github.com/FHeilmann) + * [Ludovico de Nittis](https://github.com/RyuzakiKK) + * [Dominik Paľo](https://github.com/DominikPalo) + * [Kelly Anderson](https://github.com/cbxbiker61) + * [Jim Neill](https://github.com/jneilliii) + * [Dustin Kerber](https://github.com/kerber) + * [Tobias Schürg](https://github.com/tobiasschuerg) + * [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) + * ["coliss86"](https://github.com/coliss86) + * ["MichaIng"](https://github.com/MichaIng) + * ["jasonbcox"](https://github.com/jasonbcox) + * ["shadycuz"](https://github.com/shadycuz) + * [David Rifkind](https://github.com/drifkind) + * [Nils Hofmann](https://github.com/Master92) + * [Miroslav Šedivý](https://github.com/eumiro) + * [Costas Basdekis](https://github.com/costas-basdekis) 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/CHANGELOG.md b/CHANGELOG.md index 30c647185..ece6d517e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,1279 +1,4 @@ -# OctoPrint Changelog +# Changelog -## 1.3.12rc2 (2019-09-17) - -### Improvements - - * [#3271](https://github.com/foosel/OctoPrint/issues/3271) - Extend safemode to also disable third party language packs - -### Bug fixes - - * [#3270](https://github.com/foosel/OctoPrint/issues/3270) - Properly escape translation strings in single/double quoted template locations - * [#3272](https://github.com/foosel/OctoPrint/issues/3272) (regression) - GCODE viewer: Fix out-of-sync & layer slider issue - * [#3273](https://github.com/foosel/OctoPrint/issues/3273) (regression) - Fix minimum pip version for OctoPi 0.15.1, which turns out is 9.0.3, not 10.0.1 as on OctoPi 0.15.0 due to a bug related version pin back then when. - -### Special thanks to all the contributors! - -Special thanks to everyone who contributed to this release candidate and provided full, analysable bug reports! - -### More information - - * [Commits](https://github.com/foosel/OctoPrint/compare/1.3.12rc1...1.3.12rc2) - -## 1.3.12rc1 (2019-09-10) - -### Improvements - - * [#1239](https://github.com/foosel/OctoPrint/issues/1239) & [#3227](https://github.com/foosel/OctoPrint/pull/3227) - Add command line interface for user management. Via `octoprint user [add_user|remove_user|change_password]` it is now possible to add & remove users or change their passwords right from the command line instead of just through the web interface. That should also make password recovery easier and as simple as `octoprint user change_password username`. - * [#2896](https://github.com/foosel/OctoPrint/issues/2896) - Add confirmation dialog when removing a plugin (see also [#3179](https://github.com/foosel/OctoPrint/pull/3179)). - * [#3075](https://github.com/foosel/OctoPrint/issues/3075) - Calculate filament usage for all extruders in `M605` duplicate/mirror setup (see also [#3181](https://github.com/foosel/OctoPrint/pull/3181)). - * [#3101](https://github.com/foosel/OctoPrint/issues/3101) - Support tags on GCODE script hook and add `plugin:` to script parts from plugins. - * [#2669](https://github.com/foosel/OctoPrint/issues/2669) - Add option for disabling filters on search results in the file list (see also [#3126](https://github.com/foosel/OctoPrint/pull/3126)). - * [#3131](https://github.com/foosel/OctoPrint/pull/3131) - Allow subscribing to multiple events in one yaml based event subscription. - * [#3133](https://github.com/foosel/OctoPrint/issues/3133) - Adjust wording in case of file upload errors to also hint at permission problems. - * [#3134](https://github.com/foosel/OctoPrint/pull/3134) - Add support for logging in (and creating users) through `REMOTE_USER` header supplied by a reverse proxy in front of OctoPrint. - * [#3147](https://github.com/foosel/OctoPrint/pull/3147) - Forcelogin: Add autofocus to the username - * [#3161](https://github.com/foosel/OctoPrint/issues/3161) - Plugin manager: Reduce height of plugin list. - * [#3162](https://github.com/foosel/OctoPrint/issues/3162) - Make closing behaviour of dialogs adjustable: default behaviour is to close on click outside of dialog, this can now be disabled. - * [#3167](https://github.com/foosel/OctoPrint/pull/3167) - Make it configurable whether to perform the parity double open workaround on serial needed for (some?) debian based systems. Solves issues for FreeBSD systems & Klipper. - * [#3180](https://github.com/foosel/OctoPrint/pull/3180) - Add button to terminal tab to clear the log. - * [#3188](https://github.com/foosel/OctoPrint/issues/3188) - Suppress scary `WebSocketClosedError` messages in the log simply caused by closing the browser. - * [#3171](https://github.com/foosel/OctoPrint/issues/3171) & [#3204](https://github.com/foosel/OctoPrint/issues/3204) - Action command prompts: Add close button to prompts triggered through action commands by the firmware. Wouldn't have been necessary if firmware wasn't already abusing this feature created for *interactive prompts* as non interactive fire&forget notification dialogs 🙄 - * [#3174](https://github.com/foosel/OctoPrint/issues/3174) - Include upload date & time in State panel to make file refreshs clearer. - * [#3191](https://github.com/foosel/OctoPrint/pull/3191) - Docs: Clarify that a target temperature value of 0 turns heaters off. - * [#3198](https://github.com/foosel/OctoPrint/issues/3198) - Clarify execution order of GCODE scripts. - * [#3199](https://github.com/foosel/OctoPrint/issues/3199) - Hardening against corrupt print recovery data. - * [#3203](https://github.com/foosel/OctoPrint/issues/3203) - Add documentation for `printTimeLeftOrigin` field. - * [#3206](https://github.com/foosel/OctoPrint/issues/3206) - Better resilience against garbage on the line on initial connect to the printer due to more handshake attempts. - * [#3207](https://github.com/foosel/OctoPrint/issues/3207) - Try to guess the mimetype if there is none during the webcam stream test. - * [#3218](https://github.com/foosel/OctoPrint/pull/3218) - Small refactoring in comm layer - * [#3225](https://github.com/foosel/OctoPrint/pull/3225) - Quote arguments in `pip install` to avoid issues with shells other than bash. - * [#3249](https://github.com/foosel/OctoPrint/pull/3249) & [#3263](https://github.com/foosel/OctoPrint/pull/3263) - Printer profile events are now properly triggered. - * [#3250](https://github.com/foosel/OctoPrint/issues/3250) - Add optional confirmation dialog for starting a print. - * Make emergency codes configurable. - * Detect endless resend requests of the same line. If the printer keeps requesting the same line over and over again, something is either seriously wrong with the line or with the connection. In any case, log an error and disconnect. - * Send `M112` on disconnect due to an error (configurable) to try to disable heaters and such. - * More type annotations throughout the code. - * Re-add missing `minHeight` support to modals. - * Ensure line breaks on copy of terminal contents. - * Error Tracking: Further limit events that go out, this time by fqcn of callback methods, if needed. - * GCODE viewer: Increase logging. - * Plugin Manager: Prevent plugin installs while throttled due to undervoltage or overheating. - * Software Update: Consider an empty restart command an unset one. - * Software Update: Prevent updates while throttled due to undervoltage or overheating. - * Tracking: Track plugins & versions once every 24h. This is a feature requested repeatedly by plugin developers and will also allow the compilation of something like a Top-10-list. - * Tracking: Track slicing events - -### Bug fixes - - * [#3022](https://github.com/foosel/OctoPrint/issues/3022) & [#3236](https://github.com/foosel/OctoPrint/issues/3236) - Ignore `NaN` and `Inf` values in GCODE analysis result, don't allow `NaN` on APIs. - * [#3095](https://github.com/foosel/OctoPrint/issues/3095) - Fix a small error in the frontend through bootstrap update. - * [#3096](https://github.com/foosel/OctoPrint/issues/3096) - Fix handling of `Empty` exception in send loop. - * [#3104](https://github.com/foosel/OctoPrint/issues/3104) - `M112` and other emergency codes must *always* jump the internal command queue even when printing and be sent immediately. - * [#3107](https://github.com/foosel/OctoPrint/issues/3107) - Prevent issues if `hash` field on file metadata is unset. - * [#3109](https://github.com/foosel/OctoPrint/issues/3109) - Fix some unicode issues on the API. - * [#3114](https://github.com/foosel/OctoPrint/issues/3114) - Virtual printer: Fix handling of closed connection. - * [#3137](https://github.com/foosel/OctoPrint/issues/3137) - Do not invert axes in GCODE viewer. The axis inversion is only relevant to the control panel (depends on how the print head is positioned), NOT the rendition of the GCODE. - * [#3142](https://github.com/foosel/OctoPrint/issues/3142) - Only do autologin if not actively logged out. - * [#3143](https://github.com/foosel/OctoPrint/issues/3143) - Fix layers vanishing from GCODE viewer on settings access. - * [#3153](https://github.com/foosel/OctoPrint/issues/3153) - Fix wrong variable name in an exception handler. - * [#3154](https://github.com/foosel/OctoPrint/issues/3154) - Strip interface tags from IPv6 addresses in local address check. - * [#3155](https://github.com/foosel/OctoPrint/issues/3155) - Backup: Make sure `exclude` is always a list. - * [#3156](https://github.com/foosel/OctoPrint/issues/3156) - Tracking: Fix error if tracked time is `None`. - * [#3157](https://github.com/foosel/OctoPrint/issues/3157) - Plugin manager: Better handling of unexpected repository format (e.g. in case of a misconfigured repository URL). - * [#3166](https://github.com/foosel/OctoPrint/issues/3166) & [#3211](https://github.com/foosel/OctoPrint/issues/3211) - Fix caching behaviour in case of active wizards. - * [#3171](https://github.com/foosel/OctoPrint/issues/3171) - Action command prompts: Remove prompts on disconnect from the printer. - * [#3176](https://github.com/foosel/OctoPrint/issues/3176) - Forcelogin: Don't touch static endpoints. - * [#3177](https://github.com/foosel/OctoPrint/issues/3177) - Always report all tools in shared nozzle setups to avoid inconsistencies. - * [#3190](https://github.com/foosel/OctoPrint/issues/3190) - Plugin Manager: Refresh the repository list on cache timeout, not just on server restart and/or connectivity events. - * [#3194](https://github.com/foosel/OctoPrint/issues/3194) & [#3196](https://github.com/foosel/OctoPrint/issues/3196) - Fix typo causing a `KeyError` on starting a second consecutive print of a file (see also [#3195](https://github.com/foosel/OctoPrint/pull/3195)). - * [#3217](https://github.com/foosel/OctoPrint/pull/3217) - Docs: Fix typo in chambers documentation - * [#3220](https://github.com/foosel/OctoPrint/issues/3220) - Fix `_long_running_command` flag for `M191` on comm layer. - * [#3224](https://github.com/foosel/OctoPrint/issues/3224) - Fix file selection not being cleared in the frontend on printer disconnect. - * [#3247](https://github.com/foosel/OctoPrint/issues/3247) - Fix scoping issue in JavaScript for custom commands with `javascript`/`enabled` fields. - * [#3253](https://github.com/foosel/OctoPrint/issues/3253) - Software Update: Fix error in python version detection (see also [#3256](https://github.com/foosel/OctoPrint/pull/3256)). - * [#3257](https://github.com/foosel/OctoPrint/issues/3257) - Appkeys: Ignore empty username on `request` endpoint to avoid later issues. - * Fix broken filtering of valid tools - * Properly clear out user data from user management dialogs - * Appkeys: Fix handling of empty request body, should return `400 Bad Request` instead of `500 Internal Server Error`. - * Printer safety: Anycubic 1.1.2 is already safe (off by one error, used to only detect >1.1.2 instead of >=1.1.2) - -### Special thanks to all the contributors! - -Special thanks to everyone who contributed to this release candidate and provided full, analyzable bug reports and pull requests, especially [@aliaksei135](https://github.com/aliaksei135), [@AndyQ](https://github.com/AndyQ), [@dmweis](https://github.com/dmweis), [@esver](https://github.com/esver), [@gdombiak](https://github.com/gdombiak), [@jackwilsdon](https://github.com/jackwilsdon), [@JanneMantyharju](https://github.com/JanneMantyharju), [@kevans91](https://github.com/kevans91), [@pusewicz](https://github.com/pusewicz), [@rfinnie](https://github.com/rfinnie) and [@tduehr](https://github.com/tduehr) for their PRs. - -### More information - - * [Commits](https://github.com/foosel/OctoPrint/compare/1.3.11...1.3.12rc1) - -## 1.3.11 (2019-05-14) - -### Heads-up: 1.3.11 unbundles the Cura plugin - -If you rely on the Cura Plugin for your workflow that so far was bundled with OctoPrint, be sure to install the [Cura Legacy plugin](https://github.com/OctoPrint/OctoPrint-CuraLegacy) that's now also [available on the plugin repository](https://plugins.octoprint.org/plugins/curalegacy/). - -Once installed the Cura Legacy plugin will import the settings and profiles from the former bundled Cura plugin automatically on first start. - -### Improvements - - * [#1938](https://github.com/foosel/OctoPrint/issues/1938) - Allow slicing parallel to printing on machines with more than one core. - * [#2462](https://github.com/foosel/OctoPrint/issues/2462) - Also scan and process watched folder on startup, not just during runtime. - * [#2900](https://github.com/foosel/OctoPrint/pull/2900) - Add new hook `octoprint.printer.sdcardupload` to allow plugins to override default way to upload files to the printer's SD card. - * [#2904](https://github.com/foosel/OctoPrint/issues/2904) - Added new command line switches `-4` and `-6` to restrict binding of the server to IPv4 or v6 respectively. - * [#2905](https://github.com/foosel/OctoPrint/issues/2905) - Use maximum of communication & temperature timeout as serial timeout to avoid issues if the user has set a longer temperature reporting interval than (busy) communication timeout. - * [#2945](https://github.com/foosel/OctoPrint/issues/2945) - Adjust default regex for filtering temperature requests and responses to not filter some `M115` responses as well. New regex is `(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+((P|B|N)\d+\s+)*)?(B|T\d*):\d+)`. If you modified your terminal filters you'll have to update that manually. - * [#2947](https://github.com/foosel/OctoPrint/issues/2947) - Printer safety check plugin: Disable warning for Monoprice Select Mini V2 with firmware v4.1+. - * [#2953](https://github.com/foosel/OctoPrint/issues/2953) - GCODE Viewer: Bring back the total number of printed layers. - * [#2962](https://github.com/foosel/OctoPrint/issues/2962) - Logging: deletion confirmation and bulk delete for log file management. - * [#2965](https://github.com/foosel/OctoPrint/issues/2965) - Add new hook `octoprint.events.register_custom_events` to allow plugins to cleanly add custom events by plugins. - * [#2970](https://github.com/foosel/OctoPrint/issues/2970) - Add configurable list of commands that should never be sent to the printer, and a configurable list of commands on which OctoPrint should pause the current print job. Allows more granular configuration of behaviour of `M0`, `M1` and `M25`. - * [#2974](https://github.com/foosel/OctoPrint/issues/2974) - Dedicated checkboxes to enable/disable webcam & timelapse functionality instead of relying on empty URLs. - * [#2976](https://github.com/foosel/OctoPrint/issues/2976) - Correctly identify v6 representations of v4 networks for auto login. Also correctly identify `::1` as local network. - * [#2978](https://github.com/foosel/OctoPrint/pull/2978) - Use module name instead of plugin identifier when loading plugins from entry points. Also load bundled plugins under `octoprint.plugins.*` instead of their identifier. - * [#2982](https://github.com/foosel/OctoPrint/issues/2982) - Log user activity of who started/paused/resumed/cancelled the current print. Include `owner` of a print job in event data and log. - * [#2983](https://github.com/foosel/OctoPrint/issues/2983) - Add clear button to filter box in file list. - * [#2986](https://github.com/foosel/OctoPrint/pull/2986) - Forcelogin plugin: Make login page responsive. - * [#2988](https://github.com/foosel/OctoPrint/issues/2988) - Add `--disable-pip-version-check` to pip calls to stop pip's tendency to confuse people with it's update nag messages. - * [#2997](https://github.com/foosel/OctoPrint/issues/2997) - Forcelogin plugin: Accept authentication through API key and/or authorization headers. - * [#3010](https://github.com/foosel/OctoPrint/pull/3010) - Add usage information for all folders to the API. - * [#3014](https://github.com/foosel/OctoPrint/issues/3014) - Hardening against corrupt language packs. - * [#3023](https://github.com/foosel/OctoPrint/issues/3023) - Hardening against corrupt preemptive caching configurations. - * [#3030](https://github.com/foosel/OctoPrint/issues/3030) - Backup plugin: Change name of generated backup file to have an `octoprint-` prefix. See also [#3039](https://github.com/foosel/OctoPrint/pull/3039). - * [#3033](https://github.com/foosel/OctoPrint/issues/3033) - Open serial port in exclusive mode. See also [#3036](https://github.com/foosel/OctoPrint/pull/3036). - * [#3038](https://github.com/foosel/OctoPrint/issues/3038) - Detect Klipper firmware and adjust serial communication settings accordingly. - * [#3040](https://github.com/foosel/OctoPrint/issues/3040) - Add setting to disable fuzzy estimation display in the UI. - * [#3049](https://github.com/foosel/OctoPrint/issues/3049) - Workaround for broken PEP440 non-compliant Python version numbers under Debian. See also [#3054](https://github.com/foosel/OctoPrint/pull/3054). - * [#3051](https://github.com/foosel/OctoPrint/pull/3051) - Always show unfuzzy total print time and print left in a tooltip. - * [#3055](https://github.com/foosel/OctoPrint/pull/3055) - GCODE Viewer: Add ability to preview the current layer to be drawn. - * [#3057](https://github.com/foosel/OctoPrint/issues/3057) - Performance improvements in file management operations & more aggressive cleanup of stale metadata. - * [#3066](https://github.com/foosel/OctoPrint/pull/3066) - Docs: Add missing documentation about state in `jobs` endpoint on API. - * [#3072](https://github.com/foosel/OctoPrint/pull/3072) - Hide temperature tab for machines with neither heated bed nor extruders. - * [#3073](https://github.com/foosel/OctoPrint/pull/3073) - Hide tool section in "Control" tab for machines with no extruders. - * [#3074](https://github.com/foosel/OctoPrint/issues/3074) - Updated several dependencies to newer versions. - * Add elapsed time and reason for failure to `PrintFailed` event. - * Add `trigger_event` parameter to `Settings.save` and `PluginSettings.save` to trigger `SettingsUpdated` event on save of settings. - * Simplify configuration change handling of wizards. - * Minimum Python version is now 2.7.9. - * Create a backup of working `config.yaml` after successful startup. - * Detect incomplete startups and set safe mode flag for next startup. - * Always show actual temperature as received from printer instead of "off" for very low temperatures. That way people will hopefully no longer blame OctoPrint for MINTEMP errors triggered by their firmware because it "can't handle temperatures under 10°C". - * Add full version string `OctoPrint ` to API. - * Add systemd unit file. - * Deprecate appkey API in favor of new bundled Application Keys Plugin. AFAIK was never used by anyone anyhow. - * Take bundle status into account for plugin sorting, bundled plugins should always win before not bundled plugins if no sorting key is provided. - * Load generic templates after JavaScript assets, making it possible to reference already loaded libraries in any injected generic templates. - * Hardening against callback errors in decorators on default view. - * Unbundled the Cura plugin. It lives on as "Cura Legacy" at [OctoPrint/OctoPrint-CuraLegacy](https://github.com/OctoPrint/OctoPrint-CuraLegacy) and will also be available on the plugin repository. - * Hardening against invalid SD status reports. - * Cleanup now obsolete `metadata.yaml` files. - * Use `monotonic_time` for relative times everywhere. - * Support for heated chamber firmware capabilities. - * Remove `UI_API_KEY` and API disabling. With the inclusion of the ForceLogin plugin that doesn't serve a real purpose anymore in most cases, and it was only ever more of a rate limiting feature than an actual security measure anyhow. Plus it lead to a ton of false security alarms. - * More resilience against broken configurations. - * More resilience against platform startup issues during environment detection. - * Don't confuse users with current `pip`'s "Python 2.7 is EOL" messages - * Define empty `UI_API_KEY` for backwards compatibility with third party plugins - * Add config flag `server.ignoredIncompleteStartup` to override incomplete startup detection - * Hardening against errors triggered during print time estimation - * Introduce setting to disable exclusive claim on serial port. There might be issues with this out there in the field, so having the option to disable it is a good thing. - * Docs: Improve docs of connection API to avoid issues as encountered in [#3043](https://github.com/foosel/OctoPrint/issues/3043). - * Action Command Prompt plugin: Set `M876` as default command as discussed in [MarlinFirmware/Marlin#12982](https://github.com/MarlinFirmware/Marlin/pull/12982). - * Action Command Prompt plugin: Add `M876` to `EMERGENCY_PARSER` compliant commands, if configured accordingly. See also [MarlinFirmware/Marlin#12982](https://github.com/MarlinFirmware/Marlin/pull/12982). - * Action Command Prompt plugin: Signal support for action command prompts to firmware via `M876 P1`, if configured accordingly. See also [MarlinFirmware/Marlin#12982](https://github.com/MarlinFirmware/Marlin/pull/12982). - * Action Command Prompt plugin: Properly handle `PROMPT_SUPPORT` capability report from firmware and configure action command prompt support accordingly. See also [MarlinFirmware/Marlin#12982](https://github.com/MarlinFirmware/Marlin/pull/12982). - * Error Tracking plugin: New plugin utilizing [sentry.io](https://sentry.io) to track any kind of errors thrown in either backend or the default UI. Will ship disabled by default, has to be enabled by the user. Release Candidates will prompt users to enable it in order to improve on error detection during RC phase. - * Error Tracking: Severely restrict what gets tracked: - * we are only interested in handled core exceptions or unhandled exceptions - * we are not interested at all in `SerialException` - * Error Tracking: Further restriction of what gets tracked - * Forcelogin plugin: Set sorting key to 0 to increase likelihood of coming before alternative UIs. - * Forcelogin plugin: Add favicon meta tags. - * Plugin Manager plugin, Softwareupdate plugin: Use scrollables instead of pagination. - * Printer Safety Check plugin: Add version restriction to Anycubic check. - * Tracking plugin: Add elapsed time and reason for failure to `print_failed` event. - * Tracking plugin: Add elapsed time to `print_cancelled` event. - * Tracking plugin: Track firmware/communication errors. - * Tracking plugin: Track printer safety warnings. - * Tracking plugin: Track uptime of OctoPrint in `ping` event. - -### Bug fixes - - * [#1881](https://github.com/foosel/OctoPrint/issues/1881) - Another attempt at fixing the hard to intentionally reproduce issue where all API endpoints start returning `403` responses. Caching headers have been adjusted and API key handling has been changed, which might fix things. - * [#2859](https://github.com/foosel/OctoPrint/issues/2859) - Fix for used port and baudrate to not be properly reflected on the UI. - * [#2916](https://github.com/foosel/OctoPrint/issues/2916) - Possible workaround for a rare issue with the bundled Tornado dependency when running OctoPrint under Windows. - * [#2954](https://github.com/foosel/OctoPrint/issues/2954) - Backup plugin: Fix an issue with calculation of available free space. - * [#2955](https://github.com/foosel/OctoPrint/issues/2955) - Fix handling of `action:resume` or `action:resumed` received during `PAUSING` and handling of `action:pause` or `action:paused` received during `RESUMING`. Fix `PAUSING` state not allowing a resume to proceed. See also [MarlinFirmware/Marlin#12982](https://github.com/MarlinFirmware/Marlin/pull/12982). - * [#2959](https://github.com/foosel/OctoPrint/issues/2959) - Enforce max height smaller than available viewport for notifications so that they cannot scroll out of the screen. - * [#2967](https://github.com/foosel/OctoPrint/issues/2967) - Tracking plugin: Fix exception caused on printer events when tracking is disabled and no UUID is thus set. - * [#2971](https://github.com/foosel/OctoPrint/issues/2971) - Forcelogin plugin: Fix "remember me" not working as advertised. See also [#2973](https://github.com/foosel/OctoPrint/pull/2973). - * [#2992](https://github.com/foosel/OctoPrint/issues/2992) - Backup plugin: Use `shutil.move` instead of `os.rename` and thus avoid issues with certain filesystem configurations. See also [#2993](https://github.com/foosel/OctoPrint/pull/2993). - * [#2996](https://github.com/foosel/OctoPrint/issues/2996) - Use non-blocking writes on serial communication to avoid `select` blocking issues under certain conditions. See also [#3004](https://github.com/foosel/OctoPrint/pull/3004). - * [#3001](https://github.com/foosel/OctoPrint/issues/3001) - Fix a race condition in SD printing detection. - * [#3012](https://github.com/foosel/OctoPrint/issues/3012) - Fix a unicode vs ASCII bug in translating plugins. - * [#3024](https://github.com/foosel/OctoPrint/issues/3024) - Fix inconsistent behaviour of CORS support on the API regarding static routes and the socket. - * [#3029](https://github.com/foosel/OctoPrint/issues/3029) & [#3045](https://github.com/foosel/OctoPrint/pull/3045) & [#3061](https://github.com/foosel/OctoPrint/issues/3061) - Fix issues in the German translation - * [#3053](https://github.com/foosel/OctoPrint/pull/3053) - GCODE Viewer: Fix an issue with multi extruder files where only a higher extruder index is actually used and all prior ones are undefined. - * [#3080](https://github.com/foosel/OctoPrint/issues/3080) - Virtual Printer plugin: Fix tracking of negative movements and homing. - * [#3071](https://github.com/foosel/OctoPrint/issues/3071) - Application Keys plugin: Fix appkeys not working when access control is disabled. - * [#3088](https://github.com/foosel/OctoPrint/issues/3088) (regression) - Fix 500 error on index rendering in case of plugins that use unicode in plugin vars. - * [#3089](https://github.com/foosel/OctoPrint/issues/3089) (regression) - Fix missing `_chamberTemp` definition - * [#3090](https://github.com/foosel/OctoPrint/issues/3090) (regression) - Fix missing method causing an exception on `/api/printer/tool` endpoint - * [#3091](https://github.com/foosel/OctoPrint/issues/3091) (regression) - Printer Safety Check: Fix unicode errors in certain communication scenarios. - * [#3092](https://github.com/foosel/OctoPrint/issues/3092) - Fix invalid tool parameter detection on `/api/printer/tool` endpoint. - * [#3098](https://github.com/foosel/OctoPrint/issues/3098) - Backup: Exclude temporary timelapse files as well if timelapses are excluded from backup. - * [#3105](https://github.com/foosel/OctoPrint/issues/3105) (regression) - Virtual printer: Fix an encoding issue - * [#3108](https://github.com/foosel/OctoPrint/issues/3108) (regression) - Fix bug in port detection - * [#3111](https://github.com/foosel/OctoPrint/issues/3111) (regression) - Refresh port list after disconnect to detect vanishing ports - * [#3115](https://github.com/foosel/OctoPrint/issues/3115) (regression) - Fix extra newlines in `serial.log` and empty lines on terminal - * [#3116](https://github.com/foosel/OctoPrint/issues/3116) - Fix potential division by zero - * Fix a typo in an error message during startup. - * `paused` action command must not trigger *any* local processing. See also [MarlinFirmware/Marlin#12982](https://github.com/MarlinFirmware/Marlin/pull/12982). - * Only use page size from local storage in `ItemListHelper` if configured. - * Fix caching headers on main view. - * Fix missing default value for `self._errorValue` in comm layer. - * Don't read return code on async system commands, it won't work. - * Fix wrong textual representation of `STARTING` state - * Fix some potential encoding errors in the comm layer - * Fix for the file list in the UI not getting refreshed after an SD list refresh from the printer. - * Docs: Fix documentation for firmware info & capability plugin hooks. - * Docs: Fix a formatting issue in the event docs, making it seem like events were deprecated when it was only payload entries that are deprecated. - * Forcelogin plugin: Never handle the UI if ACL is disabled. - * Tracking plugin: Fix tracking not starting fully if enabled during runtime. - * Tracking plugin: Fix handling of missing print time. See also [#3063](https://github.com/foosel/OctoPrint/issues/3063). - -### Special thanks to all the contributors! - -Special thanks to everyone who contributed to this release, especially [@agrif](https://github.com/agrif), [@akraus53](https://github.com/akraus53), [@AndyQ](https://github.com/AndyQ), [@CapnBry](https://github.com/CapnBry), [@DanielJoyce](https://github.com/DanielJoyce), [@devildant](https://github.com/devildant), [@Fabi0San](https://github.com/Fabi0San), [@fake-name](https://github.com/fake-name), [@fieldOfView](https://github.com/fieldOfView), [@gloomyandy](https://github.com/gloomyandy), [@HarlemSquirrel](https://github.com/HarlemSquirrel), [@hgross](https://github.com/hgross), [@jubaleth](https://github.com/foosel/OctoPrint/commits?author=jubaleth), [@melgish](https://github.com/melgish), [@rgriebl](https://github.com/rgriebl) and [@tedder](https://github.com/tedder) for their PRs. - -### More information - - * [Commits](https://github.com/foosel/OctoPrint/compare/1.3.10...1.3.11) - * Release Candidates: - * [1.3.11rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.11rc1) - * [1.3.11rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.11rc2) - * [1.3.11rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.11rc3) - * A big **Thank you!** to everyone who reported back on these release candidates this time: [@arhi](https://github.com/arhi), [@b-morgan](https://github.com/b-morgan), [@CRCinAU](https://github.com/CRCinAU), [@devildant](https://github.com/devildant), [@evanquinnalaska](https://github.com/evanquinnalaska), [@FormerLurker](https://github.com/FormerLurker), [@gege2b](https://github.com/gege2b), [@isbric](https://github.com/isbric), [@JohnOCFII](https://github.com/JohnOCFII), [@kazibole](https://github.com/kazibole), [@nionio6915](https://github.com/nionio6915), [@reloxx13](https://github.com/reloxx13), [@schnello](https://github.com/schnello), [@trunzoc](https://github.com/trunzoc), [@vfrdirk](https://github.com/vfrdirk) & [@zeroflow](https://github.com/zeroflow) - -## 1.3.10 (2018-12-10) - -### Heads-up for plugin authors regarding the `sarge` dependency - -OctoPrint has updated its `sarge` dependency. The new version 0.1.5 has a small breaking change - the `async` keyword -was renamed to `async_` for compatibility reasons with Python 3.7. This might also affect your plugin if you happen to -use `sarge` somewhere therein. OctoPrint has a workaround for this in place so your plugin will continue to function for -now. However, you should look into updating it to use `async_` instead of `async` if running against OctoPrint 1.3.10+. - -See also [here](https://sarge.readthedocs.io/en/latest/overview.html#id1) for the `sarge` changelog. - -### Improvements - - * [#1504](https://github.com/foosel/OctoPrint/issues/1504) - Added detection of `EMERGENCY_PARSER` firmware capability and if it's present add `M108` to the cancel procedure, to cancel blocking heatups. - * [#2674](https://github.com/foosel/OctoPrint/issues/2674) - Improved error handling when the file OctoPrint is currently printing from becomes unreadable. - * [#2698](https://github.com/foosel/OctoPrint/pull/2698) - Made favicon color match custom theme color. - * [#2717](https://github.com/foosel/OctoPrint/pull/2717) - Various speed ups of the GCODE viewer. - * [#2723](https://github.com/foosel/OctoPrint/pull/2723) - Always allow the file analysis to run, even if the slicer does provide analysis data. Allows plugins implementing the analysis hook to override behaviour in all cases. - * [#2729](https://github.com/foosel/OctoPrint/issues/2729) - Allow additional video formats to appear in the timelapse tab. - * [#2730](https://github.com/foosel/OctoPrint/pull/2730) & [#2739](https://github.com/foosel/OctoPrint/pull/2739) & [#2742](https://github.com/foosel/OctoPrint/pull/2742) - Improved GCODE analysis speed. - * [#2740](https://github.com/foosel/OctoPrint/issues/2740) & [#2859](https://github.com/foosel/OctoPrint/issues/2859) - Make the connection panel reflect the current connection parameters. - * [#2769](https://github.com/foosel/OctoPrint/issues/2769) - Cura Plugin: Improve error handling a profile import fails. - * [#2802](https://github.com/foosel/OctoPrint/pull/2802) - Updated the temperature filters to ignore more sent and received lines belonging to temperature requests/responses that so far weren't covered. - * [#2806](https://github.com/foosel/OctoPrint/pull/2806) - Refactored some unit tests. - * [#2827](https://github.com/foosel/OctoPrint/pull/2827) - Spelling fixes in the documentation. - * [#2839](https://github.com/foosel/OctoPrint/issues/2839) - Recognize position reports that include a space after the axis, as e.g. observed in the firmware of AlfaWise U20 - * [#2854](https://github.com/foosel/OctoPrint/issues/2854) - Auto detect Teacup firmware. - * [#2865](https://github.com/foosel/OctoPrint/pull/2865) - Added `speed` parameter to `extrude` command on the `/api/printer/tool` API endpoint which allows to set the feedrate to use for the extrude per request. - * Improve SD print detection - * Added the Anonymous Usage Tracking Plugin. Tracking will only take place if the plugin is enabled and you’ve decided to opt-in during initial setup (or enabled it manually afterwards, through the corresponding switch in the settings). The tracking data will give insight into how OctoPrint is used, which versions are running and on what kind of hardware OctoPrint gets installed. You can learn about what will get tracked (if you opt-in) on [tracking.octoprint.org](https://tracking.octoprint.org). Please consider helping development by participating in the anonymous usage tracking. - * The OctoPi Support Plugin is now the Pi Support Plugin: - * Always enabled when running on a Raspberry Pi, regardless of whether OctoPi is used or not. - * Now detects undervoltage/overheat issues and displays an alert on the UI if such an issue is found. - * Changed detection method of the Raspberry Pi Model to something a bit more future proof. - * Added the Application Keys Plugin: The new bundled plugin offers an authorization for third party apps that doesn't involve manually copying API keys or using QR codes. Third party client developers are strongly advised to implement this workflow in their apps. Read more [in the documentation](http://docs.octoprint.org/en/maintenance/bundledplugins/appkeys.html). - * Added the Backup & Restore Plugin: The new bundled plugin will allow you to make a backup of your OctoPrint settings, files and list of installed plugins, and to restore from such a backup on the - same or another instance. This should make migration paths from outdated installations to newer ones easier. - * Software Update Plugin: Automatic updates in outdated environments are no longer supported. After repeated issues out in the fields with ancient installations and ancient underlying Python environments, OctoPrint will no longer allow automatic updates of itself or plugins via the Software Update Plugin if a certain set of minimum versions of Python, `pip` and `setuptools` isn't detected. The current minimum versions reflect the environment found on OctoPi 0.14.0: Python 2.7.9, pip 9.0.1, setuptools 5.5.1. See also the [related FAQ entry](https://faq.octoprint.org/unsupported-python-environment). - * OctoPrint will now longer allow itself to be installed on Python versions less than 2.7.3 or higher than 2.7.x, to avoid peope running into issues in unsupported environments. - * Protect/educate against the dangers of opening up OctoPrint on the public internet: - * Detect connections to the UI from external IPs and display a warning in such cases. - * Added explicit warning to the first run wizard. - * Added explicit warning to the documentation. - * Added the ForcedLogin Plugin: Disables anonymous read-only access. To get back the old behaviour you'll have to explicitely disable this plugin. - * Removed printed/visited layer counts from the GCODE viewer since it was confusing people more than helping them. - * Added a warning to the documentation re expensive code in gcode hooks. - * Added the `no_firstrun_access` decorator. - * Only disable autoscroll in the terminal when scrolling up, not when scrolling down. - * Added a new asset type `clientjs` for JS client library components. - * Added new options for the `showConfirmationDialog` UI helper: - * `oncancel`: callback to call when the cancel button is pressed - * `noclose`: don't allow dismissing/closing the dialog without having chosen to proceed or cancel. - * Allow further access restrictions on API and Tornado routes by third party plugins. - * Support using the JS client library with an unset API key. - * Added documentation for `octoprint.util.commandline` module - * More resilience against third party plugins that happily block or kill important startup threads - * Improved backwards compatibility of the `sarge` dependency by monkey patching it to support the old `async` keyword parameter. Plugin authors are still advised to switch to the new `async_` parameter if running against `sarge>=0.1.5`, unmodified plugins should continue to work now however. For reference, OctoPrint 1.3.10 requires `sarge==0.1.5post0`. - * Better detection of ipv6 support by the underlying OS. - * Updated several dependencies to current versions where possible. - * Announcements Plugin: Add documentation. - * Anonymous Usage Tracking: Added elapsed time & reason of print failure to tracking (to be able to distinguish cancelled from errored out prints) - * Anonymous Usage Tracking: Added undervoltage/overheat detection on Pis to tracking (to correlate print failures to power issues, see also [#2878](https://github.com/foosel/OctoPrint/pull/2878)). - * Backup: Exclude `generated`, `logs` and `watched` folders from backup - * Backup: Use base version for version check on restore - * Pi Support plugin: Better wording on the "undervoltage & overheat" popover & added a link to the FAQ entry - * Printer Safety Plugin: Added Ender 3 stock firmware, Micro3D stock firmware and iME firmware to detection - -### Bug fixes - - * [#2629](https://github.com/foosel/OctoPrint/issues/2629) - Cura Plugin: Fixed wrong gcode snippet being used when slicing against a printer profile with multiple extruders. - * [#2696](https://github.com/foosel/OctoPrint/pull/2696) - Fixed a comment. - * [#2697](https://github.com/foosel/OctoPrint/pull/2697) - Fixed documentation regarding unit of `estimatedPrintTime` field in the analysis result. - * [#2705](https://github.com/foosel/OctoPrint/issues/2705) - Fixed internal server error on GET request for files on the printer's SD card. - * [#2706](https://github.com/foosel/OctoPrint/issues/2706) - Fixed a documentation error regarding HTTP status code returned on invalid API key - * [#2712](https://github.com/foosel/OctoPrint/issues/2712) - Fixed updating via commandline (`octoprint plugins softwareupdate:update`). - * [#2749](https://github.com/foosel/OctoPrint/issues/2749) - Fixed empty API key being treated as anonymous API key. - * [#2752](https://github.com/foosel/OctoPrint/issues/2752) - Only reset timeout to shorter "busy" timeout once the busy configuration command has been sent to the printer. - * [#2772](https://github.com/foosel/OctoPrint/issues/2772) & [#2764](https://github.com/foosel/OctoPrint/issues/2764) - Stop sending commands to the printer if a fatal error is reported that results in a `kill()`, even if OctoPrint is configured to keep the connection going on firmware errors. - * [#2774](https://github.com/foosel/OctoPrint/issues/2774) - Fixed autoscroll in the terminal stopping when switching browser windows or tabs. - * [#2780](https://github.com/foosel/OctoPrint/issues/2780) - Fixed error when trying to save timeout settings. - * [#2800](https://github.com/foosel/OctoPrint/pull/2800) - Fixed a conjugation error in the documentation. - * [#2805](https://github.com/foosel/OctoPrint/issues/2805) - Fixed duplicated method name in a unit test. - * [#2846](https://github.com/foosel/OctoPrint/issues/2846) - Removed requirement to have `messages.pot` exist to use `babel_extract` for translating plugins (see also [#2846](https://github.com/foosel/OctoPrint/pull/2847)). - * [#2850](https://github.com/foosel/OctoPrint/issues/2850) - Fixed a race condition in the web socket causing the push connection to fail (see also [#2858](https://github.com/foosel/OctoPrint/pull/2858)). - * [#2852](https://github.com/foosel/OctoPrint/issues/2852) - Fixed issue with zeroconf announcement failing for the second instance of OctoPrint on the same Linux host due to a name conflict. - * [#2872](https://github.com/foosel/OctoPrint/issues/2872) (regression) - Fix Timeout when connecting to printer that doesn't send `start` on connect - * [#2873](https://github.com/foosel/OctoPrint/issues/2873) (regression) - Fix GCODE viewer no longer being able to load files. - * [#2876](https://github.com/foosel/OctoPrint/issues/2876) (regression) - Fix semi functional UI when access control is disabled - * [#2879](https://github.com/foosel/OctoPrint/issues/2879) (regression) - Fix favicon in Firefox - * [#2897](https://github.com/foosel/OctoPrint/issues/2897) (regression) - Improved error resilience of `is_lan_address` so an error during its execution no longer nukes requests - * [#2898](https://github.com/foosel/OctoPrint/issues/2898) (regression) - ForceLogin plugin no longer interferes with websocket messages sent by plugins right on UI load but instead puts them into a (limited) backlog and then sends them out in received order once the user has authenticated on the socket. - * [#2903](https://github.com/foosel/OctoPrint/issues/2903) - Backup plugin: Support for ZIP64 extensions for large zip files - * [#2903](https://github.com/foosel/OctoPrint/issues/2903) - Backup plugin: Better error reporting - * [#2908](https://github.com/foosel/OctoPrint/issues/2908) (regression) - Tracking: Use the file's `path` instead of just the `name` for file name hashing. - * [#2920](https://github.com/foosel/OctoPrint/issues/2920) - Backup plugin: Fix wrong compatibility check logic in plugin install during restore - * Fixed an issue with collision free SD name detection. - * Fixed some JS warnings in the GCODE viewer. - * Fixed wrongly used `.error` instead of the correct `.fail` in the UI's logout handler. - * Fixed the `disable_hotends` snippet in case of a shared nozzle setup. - * Logout socket on UI logout - * Announcements Plugin: Fix an issue with atom feeds. - * Anonymous Usage Tracking: More error resilience for the wizard to possibly work around issues observed with the first RC (for which sadly no information was provided to reproduce and analyse). - * Anonymous Usage Tracking: Fixed homepage link in plugin manager - * Backup: Disable restore on Windows servers where it's not supported thanks to the Windows file system - * Backup: Fix reporting of restore failure due to version mismatch or other cases of an invalid backup - * Backup: Fix feedback in UI during restore, start feedback right on upload of backup - * Printer Safety: Fix localization of warning message - * Software Update Plugin: Fixed the update button being visible although the update is impossible. - * Software Update Plugin: More resilience against invalid data in config - * Software Update Plugin: Fixed version output of CLI update message - -### Special thanks to all the contributors! - -Special thanks to everyone who contributed to this release candidate, especially [@BillyBlaze](https://github.com/BillyBlaze), -[@bradcfisher](https://github.com/bradcfisher), [@eyal0](https://github.com/eyal0), [@fieldOfView](https://github.com/fieldOfView), -[@gdombiak](https://github.com/gdombiak), [@gerfderp](https://github.com/gerfderp), [@hashashin](https://github.com/hashashin) -and [@tedder](https://github.com/tedder) for their PRs. - -### More information - - * [Commits](https://github.com/foosel/OctoPrint/compare/1.3.9...1.3.10) - * Release Candidates: - * [1.3.10rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.10rc1) - * [1.3.10rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.10rc2) - * [1.3.10rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.10rc3) - * [1.3.10rc4](https://github.com/foosel/OctoPrint/releases/tag/1.3.10rc4) - * A big **Thank you!** to everyone who reported back on these release candidates this time: [@andrivet](https://github.com/andrivet), [@arminth](https://github.com/arminth), [@autonumous](https://github.com/autonumous), [@benlye](https://github.com/benlye), [@BillyBlaze](https://github.com/BillyBlaze), [@bradcfisher](https://github.com/bradcfisher), [@Charly333](https://github.com/Charly333), [@ChrisHeerschap](https://github.com/ChrisHeerschap), [@Crowlord](https://github.com/Crowlord), [@ctgreybeard](https://github.com/ctgreybeard), [@devildant](https://github.com/devildant), [@dimkin-eu](https://github.com/dimkin-eu), [@DominikPalo](https://github.com/DominikPalo), [@duncanlovett](https://github.com/duncanlovett), [@EddyMI3d](https://github.com/EddyMI3d), [@FanDjango](https://github.com/FanDjango), [@FormerLurker](https://github.com/FormerLurker), [@gdombiak](https://github.com/gdombiak), [@GhostlyCrowd](https://github.com/GhostlyCrowd), [@goeland86](https://github.com/goeland86), [@Goodeid](https://github.com/Goodeid), [@hamster65](https://github.com/hamster65), [@hashashin](https://github.com/hashashin), [@jenilliii](https://github.com/jenilliii), [@JohnOCFII](https://github.com/JohnOCFII), [@kmanley57](https://github.com/kmanley57), [@louispires](https://github.com/louispires), [@markuskruse](https://github.com/markuskruse), [@Nervemanna](https://github.com/Nervemanna), [@nionio6915](https://github.com/nionio6915), [@ntoff](https://github.com/ntoff), [@paukstelis](https://github.com/paukstelis), [@racenviper](https://github.com/racenviper), [@ramsesiden](https://github.com/ramsesiden), [@rtbon](https://github.com/rtbon), [@skohls](https://github.com/skohls), [@stough](https://github.com/stough), [@tech-rat](https://github.com/tech-rat), [@tedder](https://github.com/tedder), [@ThaliaFromPrussia](https://github.com/ThaliaFromPrussia), [@thisiskeithb](https://github.com/thisiskeithb), [@trendelkamp](https://github.com/trendelkamp), [@truglodite](https://github.com/truglodite), [@tteckenburg](https://github.com/tteckenburg), [@varazir](https://github.com/varazir), [@Webstas](https://github.com/Webstas) and [@zeroflow](https://github.com/zeroflow) - -## 1.3.9 (2018-07-25) - -### Still running OctoPrint 1.3.6? Heads-up! - -OctoPrint 1.3.9 includes a couple of dependency updates whose update during switch to 1.3.9 are known to trigger an "update failed" message within OctoPrint's update dialog: - -``` - -[...] -OSError: [Errno 2] No such file or directory: '/home/pi/oprint/local/lib/python2.7/site-packages/python_dateutil-2.6.0-py2.7.egg' -Successfully installed OctoPrint-1.3.9rc4 backports-abc-0.5 frozendict-1.2 markdown-2.6.11 pkginfo-1.4.2 pyserial-3.4 python-dateutil-2.6.1 singledispatch-3.4.0.3 tornado-4.5.3 -The update did not finish successfully. Please consult the log for details. - -``` - -The update did in fact succeed and the issue lies with a change in the underlying update mechanism concerning the dependencies. This problem has been fixed in 1.3.7/1.3.8 and versions prior to 1.3.6 aren't yet affected, so there you won't ever see this message there. If you are still running 1.3.6 though and updating from it, **simply run the update a second time through Settings > Software Update > Check for updates and clicking "Update now" in the reshown update notification**. - -### Running NGINX as reverse proxy? Be sure to configure HTTP protocol version 1.1! - -OctoPrint 1.3.9 updates the internal webserver Tornado from 4.0.2 to 4.5.3. Among many many fixes and improvements this also includes a change (actually a fix) in the websocket implementation that requires you to tell your NGINX to use HTTP 1.1 instead of the default 1.0 to talk to OctoPrint. You can do this by simply adding - -``` -proxy_http_version 1.1; -``` - -to the `location` config. The [configuration examples](https://discourse.octoprint.org/t/reverse-proxy-configuration-examples/1107) have been adjusted accordingly. See also [#2526](https://github.com/foosel/OctoPrint/issues/2526). - -### Disabled IPv6 and now there are issues with the server after the update? Bind to IPv4 addresses only! - -Starting with this release OctoPrint natively supports IPv6 and will attempt to bind to such addresses if it detects support in the underlying OS. If for whatever reason your OS doesn't support IPv6 even though Python's `socket` says otherwise, you can tell OctoPrint to bind to an IPv4 address only either via the `--host` command line parameter or `server.host` in `config.yaml`. Use `127.0.0.1` for localhost only, `0.0.0.0` for all IPv4 addresses or whatever specific IPv4 address you want to bind to. - -### Plugin author and still dependent on the legacy plugin bundling flag? Fix your plugin! - -As [announced with the release of OctoPrint 1.3.6](https://octoprint.org/blog/2017/12/12/new-release-1.3.6/), the legacy plugin bundling flag has now been removed again. [Make sure to check and if necessary fix your plugins](https://octoprint.org/blog/2017/12/01/heads-up-plugin-authors/) if you haven't done that so far! - -### Improvements - - * [#652](https://github.com/foosel/OctoPrint/issues/652) & [#1545](https://github.com/foosel/OctoPrint/issues/1545) - Added name of user who started a job to job info (see also [#2576](https://github.com/foosel/OctoPrint/pull/2576)). - * [#1203](https://github.com/foosel/OctoPrint/issues/1203) & [#1905](https://github.com/foosel/OctoPrint/issues/1905) & [#1797](https://github.com/foosel/OctoPrint/issues/1797) & [#2514](https://github.com/foosel/OctoPrint/issues/2514) - Added support for plugins to override GCODE analysis provider and live print time estimation with their own implementations through two new hooks [`octoprint.filemanager.analysis.factory`](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-filemanager-analysis-factory) and [`octoprint.printer.estimation.factory`](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-printer-estimation-factory). - * [#1217](https://github.com/foosel/OctoPrint/issues/1217) - Software Update Plugin: Block the UI in general when an update is in progress (even in browser windows that didn't start it and logged in as user) so that no prints can be accidentally started during that. - * [#1513](https://github.com/foosel/OctoPrint/issues/1513) - Option to allow sending `M0`/`M1` to the printer instead of swallowing it. - * [#2318](https://github.com/foosel/OctoPrint/issues/2318) - Gcode Viewer: Visualize "current" print head location with a marker. - * [#2351](https://github.com/foosel/OctoPrint/issues/2351) - Support for binding to IPv6 addresses. OctoPrint will now default to binding to `::` if IPv6 support is detected, and to `0.0.0.0` if not. Both the intermediary server and Tornado are instructed to bind their sockets to both IP versions. Positive IPv6 support detection relies on - * `socket.has_ipv6` being `True` - * `socket.IPPROTO_IPV6` and `socket.IPV6_V6ONLY` being available (or redefined in case of Windows) in order to ensure dual stack binding for the intermediary server) - * [#2379](https://github.com/foosel/OctoPrint/issues/2379) - File and plugin list now use the browser's native scrollbar instead of slimscroll. Slimscroll is still bundled though, in case third party plugins might depend on it. - * [#2487](https://github.com/foosel/OctoPrint/issues/2487) - Improved documentation of system command configuration (see also [#2498](https://github.com/foosel/OctoPrint/pull/2498)). - * [#2495](https://github.com/foosel/OctoPrint/pull/2495) - Removed unneeded filter from a template. - * [#2498](https://github.com/foosel/OctoPrint/pull/2498) - Improved documentation of the `async` flags of custom system commands. - * [#2512](https://github.com/foosel/OctoPrint/issues/2512) - Log files will now contain client IP as provided by first entry in X-Forwarded-For header (or more if `server.reverseProxy.trustDownstream` is configured accordingly). - * [#2518](https://github.com/foosel/OctoPrint/issues/2518) - Display absolute file upload date and time on hover (see also [#2630](https://github.com/foosel/OctoPrint/pull/2630)). - * [#2522](https://github.com/foosel/OctoPrint/issues/2522) - Perform logging to disk asynchronously to avoid slow downs caused by it. - * [#2541](https://github.com/foosel/OctoPrint/pull/2541) - Added link to instructions to reset passwords. Part of solving [#1239](https://github.com/foosel/OctoPrint/issues/1239). - * [#2543](https://github.com/foosel/OctoPrint/pull/2543) - Added `--no-cache-dir` to pip calls to work around `MemoryErrors`. See also [#2535](https://github.com/foosel/OctoPrint/pull/2535) and [pypa/pip#2984](https://github.com/pypa/pip/issues/2984) for more details. - * [#2558](https://github.com/foosel/OctoPrint/issues/2558) - Have the watched folder processor ignore hidden files. - * [#2572](https://github.com/foosel/OctoPrint/issues/2572) - More error resilience in `ItemListHelper` against empty child elements. - * [#2573](https://github.com/foosel/OctoPrint/pull/2573) - Added `M118` to commands to never automatically upper case. - * [#2583](https://github.com/foosel/OctoPrint/issues/2583) - Handle scripts that are part of a job like other lines coming from a job and thus allow them to be kept back using `job_on_hold`. - * [#2597](https://github.com/foosel/OctoPrint/issues/2597) - Disabled animation on cancel print confirmation. - * [#2463](https://github.com/foosel/OctoPrint/issues/2463) - Added documentation for `printingarea` and `dimensions` in `gcodeAnalysis` data model (see also [#2540](https://github.com/foosel/OctoPrint/pull/2540)). - * [#2615](https://github.com/foosel/OctoPrint/issues/2615) - Allowed more granular control over components to be upgraded through the software update plugin in its settings dialog. - * [#2620](https://github.com/foosel/OctoPrint/pull/2620) - Save `ItemListHelper` page sizes to local storage. - * [#2642](https://github.com/foosel/OctoPrint/pull/2642) - Added methods for adding and updating items to `ItemListHelper`. - * [#2644](https://github.com/foosel/OctoPrint/issues/2644) - Detect broken symlinks in configured folders on startup (see also further below). - * [#2648](https://github.com/foosel/OctoPrint/pull/2648) - Allowed class methods as callbacks in view models. - * A new API endpoint [`/api/settings/templates`](http://docs.octoprint.org/en/maintenance/api/settings.html#fetch-template-data) allows (admin only) access to information regarding the loaded templates and their order in the UI. That should allow plugins wishing to offer modification of ordering of tabs, sidebar components and so on to retrieve the data they need for that. - * Have the watched folder processor handle vanished files gracefully. - * Removed [`legacyPluginAssets` flag](https://octoprint.org/blog/2017/12/01/heads-up-plugin-authors/). - * Improved requirement detection in `octoprint_setuptools`, added unit tests for that. - * Bundled `sockjs-tornado` dependency. It hasn't been updated by the author in a while although there exist a number of issues plus patches for them, so we now vendor it. - * Disabled position logging on cancel by default. If you need this, please explicitly enable it, it is causing too many issues in the field with misbehaving firmware. - * Extended URL test API to allow whitelist/blacklist check for the returned content type, used that to verify that the webcam snapshot URL actually returns images. - * Added timeout for position logging on pause/cancel. This should work around firmware which doesn't provide a proper `M114` resport that might be unparseable so we won't get stuck in those cases. - * Migrated file storage metadata to json instead of YAML since it performs way way better. - * Added `missing linenumber` to recognized non-fatal error messages. - * Got rid of some Python 2 only code. - * Added sanity checks for configured folders (see also [#2644](https://github.com/foosel/OctoPrint/issues/2644)): - * on startup: check they are writable, if not revert to defaults - * on settings save: check they are writable, if not return an HTTP 400 - * in the settings dialog: allow quick check of writability via test buttons - * Never send referrers with links - * Confirmation dialog helper now supports an HTML body. - * Sort serial ports naturally (e.g. `tty1`, `tty2`, ..., `tty10` instead of `tty1`, `tty10`, ...) - * Added `paused` and `resumed` action commands, [see here for details](http://docs.octoprint.org/en/maintenance/features/action_commands.html). - * Added two new hooks for firmware information, [`octoprint.comm.firmware.info`](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-comm-firmware-info) and [`octoprint.comm.firmware.capabilities`](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-comm-firmware-capabilities). - * Added view model list to `OctoPrint.coreui` UI module. - * Improved logging of `FatalStartupError`s. - * Add sanity check for disabled plugin list (see also [#2687 (comment)](https://github.com/foosel/OctoPrint/issues/2687#issuecomment-399797596)). - * Improve logging of exceptions triggered inside the state update worker (see also [#2715](https://github.com/foosel/OctoPrint/issues/2715)). - * Workaround for a potential `pip` issue when updating components through the Software Update plugin. - * Fix resend and timeout handling during an active `job_on_hold`. - * Updated some dependencies: - * Tornado to 4.5. Version 5 sadly has issues with web socket handling when access behind `haproxy`. So far no solution has been found, so we stay at 4.5 for now. - * jQuery to 3.3.1 - * Several other Python dependencies - * Announcement Plugin: Don't reload all notifications if one is marked as read. - * Printer Safety Plugin: Added new detected firmwares: - * Anycubic Mega - * Malyan M200 - * CR-10S - * all Repetier firmware versions prior to 0.92 - * any firmware that reports the `THERMAL_PROTECTION` capability as disabled to thermal protection warning (see also [MarlinFirmware/Marlin#10465](https://github.com/MarlinFirmware/Marlin/pull/10465)) - * Software Update Plugin: Default to `force_base = False` for version checks. - * Virtual Printer Plugin: Allow defining custom `M114` response formats. - -### Bug fixes - - * [#2333](https://github.com/foosel/OctoPrint/issues/2333) (Part 3/3) - Updated to PySerial 3.4 and utilize read and write cancelling to work around disconnect delays. - * [#2355](https://github.com/foosel/OctoPrint/issues/2355) - Fixed non deterministic sorting of files with missing fields (e.g. date for SD card files) in OctoPrint's frontend. - * [#2496](https://github.com/foosel/OctoPrint/issues/2496) - Fixed files API not allowing to walk through the directory tree unless fetching the full listing recursively by making sure that first level children nodes are always provided. - * [#2502](https://github.com/foosel/OctoPrint/pull/2502) - Fixed some invalid HTML - * [#2504](https://github.com/foosel/OctoPrint/pull/2504) & [#2532](https://github.com/foosel/OctoPrint/pull/2532) & [#2552](https://github.com/foosel/OctoPrint/pull/2552) - Fixed various typos - * [#2505](https://github.com/foosel/OctoPrint/issues/2505) - Fixed user switch to `_api` user on use of the global API key inside the browser. - * [#2509](https://github.com/foosel/OctoPrint/issues/2509) - Properly handle a printer reset while printing and don't get stuck in "Cancelling" state - * [#2517](https://github.com/foosel/OctoPrint/issues/2517) - Fixed baudrate negotiation with printers that need a bit of a delay between connection establishment and probing (e.g. Prusa MK3). - * [#2520](https://github.com/foosel/OctoPrint/issues/2520) - Fixed temperature presets being saved as strings instead of numbers. - * [#2533](https://github.com/foosel/OctoPrint/pull/2533) - Fixed API key copy button being enabled and generate button being disabled when no API key is set. - * [#2534](https://github.com/foosel/OctoPrint/issues/2534) - Fixed stale data in API key/user editor. See also [#2604](https://github.com/foosel/OctoPrint/pull/2604). - * [#2539](https://github.com/foosel/OctoPrint/issues/2539) - Made serial and baud rate lists consistent between connection panel and settings (see also [#2606](https://github.com/foosel/OctoPrint/pull/2606)). - * [#2547](https://github.com/foosel/OctoPrint/issues/2547) - Fixed `PrintFailed` being triggered in case of an error while processing the `afterPrintJobDone` GCODE script through introduction of `Resuming` and `Finishing` states. - * [#2549](https://github.com/foosel/OctoPrint/issues/2549) - Fixed "uninstall plugin" icon in Plugin Manager staying clickable even if disabled. - * [#2549](https://github.com/foosel/OctoPrint/issues/2549) - Fixed issue with detection uninstallation of disabled plugins (see also [#2650](https://github.com/foosel/OctoPrint/pull/2650)). - * [#2551](https://github.com/foosel/OctoPrint/issues/2551) - Fixed `0` being allowed for various intervals and timeouts where that values doesn't make sense. - * [#2554](https://github.com/foosel/OctoPrint/pull/2554) - Fixed a JSON example in the docs. - * [#2568](https://github.com/foosel/OctoPrint/pull/2568) - Fixed a dead link in the plugin hooks documentation in the docs. - * [#2579](https://github.com/foosel/OctoPrint/issues/2579) - Fixed print time left of "a couple of seconds" even after the print job has finished. - * [#2581](https://github.com/foosel/OctoPrint/issues/2581) & [#2587](https://github.com/foosel/OctoPrint/issues/2587) - Fixed OctoPrint getting stuck in "Pausing" or "Cancelling" state due to a race condition. - * [#2589](https://github.com/foosel/OctoPrint/issues/2589) - Added missing `typePath` field on API response for files on the printer's SD card. - * [#2591](https://github.com/foosel/OctoPrint/pull/2591) - Fixed markup of some HTML labels. - * [#2595](https://github.com/foosel/OctoPrint/pull/2595) - Fixed some UI appearance issues. - * [#2601](https://github.com/foosel/OctoPrint/issues/2601) - Properly handle relative paths for selection via `printer.select_file`. - * [#2621](https://github.com/foosel/OctoPrint/issues/2621) - Fixed framerate not being read from config for rendering unrendered timelapses. - * [#2625](https://github.com/foosel/OctoPrint/issues/2625) - Fixed incompatibility of OctoPrint's plugin subsystem with Python wheels, which are the default mode of installing plugins from pip version 10.0.0 onward. - * [#2632](https://github.com/foosel/OctoPrint/issues/2632) - Fixed race condition in resend handling on missing `ok`s. - * [#2675](https://github.com/foosel/OctoPrint/issues/2675) - Fixed a possible division by zero on SD upload. - * [#2677](https://github.com/foosel/OctoPrint/issues/2677) (regression) - Fix a deadlock when `job_on_hold` is utilized (causing issues at least with Octolapse) - * [#2683](https://github.com/foosel/OctoPrint/pull/2683) - Fixed two missing spaces in the german translation. - * [#2715](https://github.com/foosel/OctoPrint/issues/2715) (regression) - Fix broken estimator initialization on SD print start and resulting crash of the state update worker. - * [#2719](https://github.com/foosel/OctoPrint/issues/2719) (regression) - Fix live print time estimation - * [#2737](https://github.com/foosel/OctoPrint/issues/2737) (regression) - Fix print button being enabled even though no file is selected. - * [#2738](https://github.com/foosel/OctoPrint/issues/2738) (regression) - Limit the use of the `--no-cache-dir` argument added to `pip` calls to such versions of `pip` that already support it (anything newer than 1.5.6). - * Properly handle absolute paths for recovery data comparison. - * Fixed snapshot test button not resetting on error. - * Fixed decoupling of metadata logs in the file manager. - * Fixed "remember me" and IPv4/IPv6 sessions. This might also solve [#1881](https://github.com/foosel/OctoPrint/issues/1881). - * Removed Repetier resend repetition detection and handling code. It was buggy and introducing issues. - * Fixed script order: `beforePrint*` should always precede any commands from the print job. - * Only perform write tests on directories where necessary. Especially avoid them on page rendition to prevent misconfigured folders from triggering an HTTP 500. (regression) - -### Special thanks to all the contributors! - -Special thanks to everyone who contributed to this release, especially [@benlye](https://github.com/benlye), [@dadosch](https://github.com/dadosch), [@dforsi](https://github.com/dforsi), [@ganey](https://github.com/ganey),[@malnvenshorn](https://github.com/malnvenshorn), [@ntoff](https://github.com/ntoff), [@tedder](https://github.com/tedder) and [@vitormhenrique](https://github.com/vitormhenrique) for their PRs. - -### More information - - * [Commits](https://github.com/foosel/OctoPrint/compare/1.3.8...1.3.9) - * Release Candidates: - * [1.3.9rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.9rc1) - * [1.3.9rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.9rc2) - * [1.3.9rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.9rc3) - * [1.3.9rc4](https://github.com/foosel/OctoPrint/releases/tag/1.3.9rc4) - * A big **Thank you!** to everyone who reported back on these release candidates this time: - [arhi](https://github.com/arhi), [b-morgan](https://github.com/b-morgan), [brandstaetter](https://github.com/brandstaetter), [buchnoun](https://github.com/buchnoun), [CapnBry](https://github.com/CapnBry), [chatrat12](https://github.com/chatrat12), [ChrisHeerschap](https://github.com/ChrisHeerschap), [christianlupus](https://github.com/christianlupus), [chrisWhyTea](https://github.com/chrisWhyTea), [Crowlord](https://github.com/Crowlord), [ctgreybeard](https://github.com/ctgreybeard), [Cyberwizzard](https://github.com/Cyberwizzard), [DrJuJu](https://github.com/DrJuJu), [ejjenkins](https://github.com/ejjenkins), [fieldOfView](https://github.com/fieldOfView), [FormerLurker](https://github.com/FormerLurker), [four-of-four](https://github.com/four-of-four), [Galfinite](https://github.com/Galfinite), [gege2b](https://github.com/gege2b), [HFMan](https://github.com/HFMan), [jjlink](https://github.com/jjlink), [jneilliii](https://github.com/jneilliii), [JohnOCFII](https://github.com/JohnOCFII), [jwg3](https://github.com/jwg3), [kazibole](https://github.com/kazibole), [larp-welt](https://github.com/larp-welt), [McFly99](https://github.com/McFly99), [mod38](https://github.com/mod38), [ntoff](https://github.com/ntoff), [OutsourcedGuru](https://github.com/OutsourcedGuru), [paukstelis](https://github.com/paukstelis), [pingywon](https://github.com/pingywon), [pscrespo](https://github.com/pscrespo), [Rapsey](https://github.com/Rapsey), [tech-rat](https://github.com/tech-rat), [tedder](https://github.com/tedder), [thess](https://github.com/thess), [Thisismydigitalself](https://github.com/Thisismydigitalself), [tibmeister](https://github.com/tibmeister) - -## 1.3.8 (2018-04-13) - -### Bug fixes - - * [#2577](https://github.com/foosel/OctoPrint/issues/2577) - Pin `psutil` dependency to version 5.4.3 since 5.4.4 as released today introduces a breaking change. - -([Commits](https://github.com/foosel/OctoPrint/compare/1.3.7...1.3.8)) - -## 1.3.7 (2018-04-09) - -### Improvements - - * [#324](https://github.com/foosel/OctoPrint/issues/324) & [#2414](https://github.com/foosel/OctoPrint/issues/2414) - Native support for the following [@ commands](http://docs.octoprint.org/en/maintenance/features/atcommands.html): `@pause` (pauses the print), `@resume` (resumes the print), `@cancel` or `@abort` (cancels the print). More commands can be added through the plugin hooks [`octoprint.comm.protocol.atcommand.*`](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-comm-protocol-atcommand-phase). - * [#1951](http://github.com/foosel/OctoPrint/issues/1951) - Fixed plugins being able to modify internal state data (e.g. progress, job), causing concurrent modification and resulting run time errors in the printer state processing. - * [#2208](https://github.com/foosel/OctoPrint/issues/2208) - New plugin hook [`octoprint.comm.protocol.gcode.error`](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-comm-protocol-gcode-error) to allow plugins to override OctoPrint's handling of `Error:`/`!!` messages reported by the firmware. Can be used to "downgrade" errors that aren't actually fatal errors that make the printer halt. - * [#2213](https://github.com/foosel/OctoPrint/issues/2213) - Made sure to prevent accidental configuration of a temperature cutoff value less than 1min for the temperature graph. - * [#2250](https://github.com/foosel/OctoPrint/pull/2250) - Added [`octoprint.util.ResettableTimer`](http://docs.octoprint.org/en/maintenance/modules/util.html#octoprint.util.ResettableTimer) helper class. - * [#2287](https://github.com/foosel/OctoPrint/issues/2287) - Added confirmation for attempting to disconnect during an ongoing print. See also [#2466](https://github.com/foosel/OctoPrint/pull/2466). - * [#2302](https://github.com/foosel/OctoPrint/issues/2302) - Detect invalid tools as reported by firmware and blacklist them for `T` commands. - * [#2317](https://github.com/foosel/OctoPrint/issues/2317) - Removed capturing of post roll images for time based timelapses, was causing too much confusion and surprise. - * [#2335](https://github.com/foosel/OctoPrint/issues/2335) - First throw at detecting if a print from the printer's SD was started outside of OctoPrint via the printer's control panel. Requires some specific requirements to be fulfilled by the printer's firmware to function properly: - * Firmware must send a "File opened: ..." message on start of the print - * Firmware must respond to an immediately sent `M27` with `SD printing byte /` - * Firmware must stay responsive during ongoing print to allow for regular M27 polls (or push those automatically) or M25 to pause/cancel the print through OctoPrint. - * Firmware must send `Done printing file` or respond to `M27` with `Not SD printing` when SD printing finishes (either due to being done or to having been cancelled by the user). - * [#2362](https://github.com/foosel/OctoPrint/issues/2362) - Added option to configure timelapse snapshot timeout. - * [#2367](https://github.com/foosel/OctoPrint/issues/2367) - Added support for `//action:cancel` action command. - * [#2378](https://github.com/foosel/OctoPrint/issues/2378) - Made GCODE viewer gracefully handle GCODE subcodes. - * [#2385](https://github.com/foosel/OctoPrint/pull/2385) - Made valid boolean trues check case insensitive. - * [#2304](https://github.com/foosel/OctoPrint/pull/2304) & [#2405](https://github.com/foosel/OctoPrint/pull/2405) - Added support to trust Basic Authentication headers for user login. Currently requires [manual configuration through `config.yaml`](http://docs.octoprint.org/en/maintenance/configuration/config_yaml.html#access-control), see the `accessControl.trustBasicAuthentication` and `accessControl.checkBasicAuthenticationPassword` settings. - * [#2338](https://github.com/foosel/OctoPrint/pull/2338) - Allowed plugins to define GCODE script variables using the `octoprint.comm.protocol.scripts` hook. - * [#2406](https://github.com/foosel/OctoPrint/pull/2406) - Extracted log management into its own bundled plugin and allow fine tuning of log levels. - * [#2409](https://github.com/foosel/OctoPrint/pull/2409) - Added `m4v` and `mkv` to the list of accepted timelapse extensions. - * [#2444](https://github.com/foosel/OctoPrint/pull/2444) - Support additional CSS classes on custom control buttons. - * [#2448](https://github.com/foosel/OctoPrint/issues/2448) - Also detect plugins in `~/.octoprint/plugins` that are provided as bytecode `pyc` instead of source `py` files. - * [#2455](https://github.com/foosel/OctoPrint/issues/2455) - Added option to configure SSL validation for snapshot URL. - * Support `M114` response format of RepRapFirmware (uses `X:... Y:... Z:... E0:... E1:...` instead of -`X:... Y:... Z:... E:...`) - * Added refresh button to connection panel for easy refresh of the available ports to connect to without having to reload the whole page. - * Increased upper bound of PySerial dependency from 2.7 to 3.4. See also [#2333](https://github.com/foosel/OctoPrint/issues/2333). - * Switch to lower communication timeouts if support of the `busy` protocol by the firmware is detected. - * Refactored serial settings dialog, now has sub tabs and more explanations. - * Allow to disable support for certain firmware capabilities, even if reported as supported by the firmware: `busy` protocol, temperature auto reporting, SD status auto reporting - * Attached tags to GCODE commands moving through the comm layer and allowed plugins to access and extend these tags through the GCODE hooks. Makes it possible for plugins to detect the origin of a command (streamed file vs. GCODE script vs. user input vs. plugin), the point where it entered the system and so on. Also added a new logger `octoprint.util.comm.command_phases` that if set to `DEBUG` will log the lifecycle of commands through the comm layer including tags to `octoprint.log`. See also [the docs here](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-comm-protocol-gcode-phase). - * Added new [`job_on_hold`](http://docs.octoprint.org/en/maintenance/modules/printer.html#octoprint.printer.PrinterInterface.job_on_hold) and [`set_job_on_hold`](http://docs.octoprint.org/en/maintenance/modules/printer.html#octoprint.printer.PrinterInterface.set_job_on_hold) methods on the printer instance, allowing plugins to quickly stall the streaming of a queue. This should be used sparingly - abuse will have significant negative effects on the print job. Read the docs if you plan to utilize this. - * Support extraction of plugin metadata even from disabled and blacklisted plugins through the AST of the module. - * Better logging of printer callback errors and utilization of `frozendict` for internal printer state propagation in an attempt to narrow down on [#1951](https://github.com/foosel/OctoPrint/issues/1951). Should `frozendict` cause issues it can be disabled through the settings in `config.yaml`, just set `devel.useFrozenDictForPrinterState` to `false` - * Log comm state changes to `octoprint.log`. - * Added a regular server heartbeat to the log (every 15min). - * Support SD status auto report by the firmware. - * Added `Not SD printing` to default "SD status" terminal filters. - * Added custom `readline` implementation for the serial port. Instead of relying on PySerial's `readline` that depending on the installed version might only read from the port one byte at the time, we now wait for one byte and then read everything available into a persistent buffer which then is used to fetch lines from. - * Ensure that `callViewModelIf` doesn't try to call null or uncallable `method`s. - * Added links to the new [Community Forum](https://discourse.octoprint.org) and the new location of the [FAQ](https://faq.octoprint.org). - * Improved pip utility logging, `LocalPipHelper` wasn't producing output, making it hard to debug such non writable install directories. - * Added a new bundled plugin "Printer Safety Check" that will try to identify printer/printer firmware with known safety issues such as missing thermal runaway protection. - * Plugin Manager: Reduce notification spam. See also [#2260](https://github.com/foosel/OctoPrint/issues/2260). - * Software Update Plugin: Better detection if an update is already running. - * Software Update Plugin: Refer to `plugin_softwareupdate_console.log` on update errors in log and notification. - -### Bugfixes - - * [#2294](https://github.com/foosel/OctoPrint/issues/2294) - Improved resilience against errors during gathering the file list (e.g. permission errors) - * [#2296](https://github.com/foosel/OctoPrint/issues/2296) - Fixed `X-Forwarded-For` handling in Flask Login through monkey patched backport. - * [#2297](https://github.com/foosel/OctoPrint/issues/2297) - Return `403` instead of `401` on missing/insufficient credentials. - * [#2311](https://github.com/foosel/OctoPrint/issues/2311) - Fixed server not auto connecting on startup if port is set to `AUTO` (see also [#2311](https://github.com/foosel/OctoPrint/pull/2337)). - * [#2316](https://github.com/foosel/OctoPrint/issues/2316) - Check for valid queue entry in file analysis queue before trying to dequeue, fix for a HTTP `500` on upload of a file not supported for analysis. - * [#2321](https://github.com/foosel/OctoPrint/issues/2321) & [#2449](https://github.com/foosel/OctoPrint/issues/2449) - Fixed wrong queuing order of cancel script & first line from printed file on quick start-cancel-start scenarios by introducing a two new states "Cancelling" and "Pausing". - * [#2324](https://github.com/foosel/OctoPrint/pull/2324) - Fixed 500 error when - * [#2333](https://github.com/foosel/OctoPrint/issues/2333) (Part 1/3) - Workaround for an update problem caused by interaction of `pip` with dependencies formerly installed as eggs through `python setup.py install`. - * [#2333](https://github.com/foosel/OctoPrint/issues/2333) (Part 2/3) - If supported by the underlying PySerial version, cancel all reads and writes on disconnect if possible for a faster connection release. Part 3 (forcing an upgrade of PySerial to 3.4 so this should work in more cases) will in OctoPrint 1.3.8. - * [#2364](https://github.com/foosel/OctoPrint/issues/2364) - Fixed firmware error reporting in case of cancelling a print due to a firmware error. - * [#2368](https://github.com/foosel/OctoPrint/issues/2368) - Fixed for incorrect handling of unicode filenames in cura slicer profiles - * [#2371](https://github.com/foosel/OctoPrint/issues/2371) - Removed "just now"/"gerade eben" label from temperature graph to work around a graph resize issue caused by that. - * [#2392](https://github.com/foosel/OctoPrint/issues/2392) - Fixed "Copy all" on terminal tab only working the first time. - * [#2406](https://github.com/foosel/OctoPrint/pull/2406) - Fixed `showTab` JS function of about dialog. - * [#2426](https://github.com/foosel/OctoPrint/issues/2426) - Made resend logging to `octoprint.log` unicode safe - * [#2442](https://github.com/foosel/OctoPrint/issues/2442) - Don't even import disabled plugins, use a dummy entry for them just like for backlisted plugins. More resilience against misbehaving plugins. - * [#2461](https://github.com/foosel/OctoPrint/issues/2461) - Fixed OctoPrint not properly disconnecting in case of a firmware error. - * [#2494](https://github.com/foosel/OctoPrint/issues/2494) - Fixed `undefined` values not saving in the settings. - * [#2499](https://github.com/foosel/OctoPrint/issues/2499) (regression) - Fixed communication error notification lacking the actual error message. - * [#2501](https://github.com/foosel/OctoPrint/issues/2501) (regression) - Fixed a bug causing log downloads to fail with an HTTP 500 error. - * [#2506](https://github.com/foosel/OctoPrint/issues/2506) (regression) - Fixed `printer.get_current_data` and `printer.get_current_job` returning `frozendict` instead of `dict` instances, causing issues with plugins relying on being able to modify the returned data (e.g. [dattas/OctoPrint-DetailedProgress#26](https://github.com/dattas/OctoPrint-DetailedProgress/issues/26)). - * [#2508](https://github.com/foosel/OctoPrint/issues/2508) (regression) - Fixed HTTP 500 error on `/api/slicing` in case of an unconfigured slicer. - * [#2524](https://github.com/foosel/OctoPrint/issues/2524) - Ignore `wait` while job is on hold. - * [#2536](https://github.com/foosel/OctoPrint/issues/2536) - Fix a wrong state tracking when starting an SD print through the controller, causing a disconnect due to a timeout. - * [#2544](https://github.com/foosel/OctoPrint/issues/2544) (regression) - Fix an exception when connecting to the raw websocket at `/sockjs/websocket` (instead of `/sockjs///websocket`). - * [#2546](https://github.com/foosel/OctoPrint/issues/2546) (regression) - Fix the `PRINT_FAILED` event getting triggered twice on print failure due to disconnect - * Use `pkg_resources` to determine pip version during environment check instead of `import pip; pip.__version__` since the latter causes issues with pip version 9.0.2. In the same spirit make `pip.main` approach of calling `pip` in the PipCaller the last resort during auto detection, only after trying `pip` or `pip.exe` inside the same folder as the Python executable. - * Use `octoprint.util.monotonic_time` instead of `monotonic.monotonic` in comm layer. - * Fixed timelapse not stopping on print failure due to firmware error due to missing `PrintFailed` event. - * Announcement Plugin: Fixed a missing line break in case of more than three announcements in a notification. - * Docs: Documentation for printer profile related bits and pieces - * Docs: Various fixes of typos and grammar. - * Have `OctoPrintJsonEncoder` fall back to regular flask JSON encoder, otherwise we might not be able to serialize some data types we need to be able to serialize. (regression) - -### Known bugs - - * [#2547](https://github.com/foosel/OctoPrint/issues/2547) - Error during processing of afterPrintJobDone script will trigger PRINT_FAILED event even though PRINT_DONE event was already triggered - -### More Information - - * [Commits](https://github.com/foosel/OctoPrint/compare/1.3.6...1.3.7) - * Release Candidates: - * [1.3.7rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.7rc1) - * [1.3.7rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.7rc2) - * [1.3.7rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.7rc3) - * [1.3.7rc4](https://github.com/foosel/OctoPrint/releases/tag/1.3.7rc4) - * A special **Thank you!** to everyone who reported back on these release candidates this time: - [aaronkeck](https://github.com/aaronkeck), [akurz42](https://github.com/akurz42), [andrivet](https://github.com/andrivet), [anthonyst91](https://github.com/anthonyst91), [arhi](https://github.com/arhi), [b-morgan](https://github.com/b-morgan), [BryanSmithDev](https://github.com/BryanSmithDev), [chippypilot](https://github.com/chippypilot), [ChrisHeerschap](https://github.com/ChrisHeerschap), [Crowlord](https://github.com/Crowlord), [dforsi](https://github.com/dforsi), [drdelaney](https://github.com/drdelaney), [FormerLurker](https://github.com/FormerLurker), [goeland86](https://github.com/goeland86), [inspiredbylife](https://github.com/inspiredbylife), [jbjones27](https://github.com/jbjones27), [jesasi](https://github.com/jesasi), [jneilliii](https://github.com/jneilliii), [JohnOCFII](https://github.com/JohnOCFII), [kantlivelong](https://github.com/kantlivelong), [lnx13](https://github.com/lnx13), [makaper](https://github.com/makaper), [markwal](https://github.com/markwal), [MiquelAdell](https://discourse.octoprint.org/u/MiquelAdell), [ml0w](https://github.com/ml0w), [mmotley999](https://github.com/mmotley999), [mrhanman](https://github.com/mrhanman), [SCiunczyk](https://github.com/SCiunczyk), [tdub415](https://github.com/tdub415), [tedder42](https://discourse.octoprint.org/u/tedder42), [thatjoshguy](https://github.com/thatjoshguy), [wescrockett](https://github.com/wescrockett) - -## 1.3.6 (2017-12-12) - -### Note for upgraders and plugin authors: Change in the bundling of JS assets can lead to issues in plugins - -A change to solve issues with plugins bundling JS assets that cause interference with other plugins (e.g. through the declaration of `"use strict"`) and in general to add better isolation and error handling might cause errors for some plugins that go beyond your run-off-the-mill view model and also implicitly declare new globals. - -If you happen to run into any such issues, you can switch back to the old way of bundling JS assets via the newly introduced "Settings > Feature > Enable legacy plugin asset bundling" toggle (check it, save the settings, restart the server). This is provided to allow for a minimally invasive adjustment period until affected plugins have been updated. - -You can find out more about the change, how to know if a plugin is even affected and what do about it [on the OctoBlog](https://octoprint.org/blog/2017/12/01/heads-up-plugin-authors/). - -### Improvements - - * [#203](https://github.com/foosel/OctoPrint/issues/203) - Allow selecting the current tab via URL hashs. Also update URL hash when switching tabs, thus adding this to the browser history and allowing quicker back and forth navigation through the browser's back and forward buttons. - * [#1026](https://github.com/foosel/OctoPrint/issues/1026) - Automatically upper case parameters in GCODE commands sent from the Terminal tab. A black list is in place that prevent upper casing of parameters for GCODE commands where it doesn't make sense (default: `M117`). See also [#2177](https://github.com/foosel/OctoPrint/pull/2177). - * [#2050](https://github.com/foosel/OctoPrint/issues/2050) - New hook [`octoprint.comm.protocol.temperatures.received`](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-comm-protocol-temperatures-received) that allows plugins to further preprocess/sanitize temperature data received from the printer. - * [#2055](https://github.com/foosel/OctoPrint/issues/2055) - Increased the size of the API key field in the settings. - * [#2056](https://github.com/foosel/OctoPrint/issues/2056) - Added a Copy button to the API key field in the settings and user settings. - * [#2094](https://github.com/foosel/OctoPrint/issues/2094) - Allow UTF-8 display names for uploaded files. The files will still get an ASCII only name on disk, but the UTF-8 name used during upload will also be persisted and shown in the file list. This also allows using emojis in your file and folder names now. - * [#2104](https://github.com/foosel/OctoPrint/issues/2104) - Allow more URL schemes for installing plugins from. Supported schemes should now mirror what `pip` itself supports: `http`, `https`, `git`, `git+http`, `git+https`, `git+ssh`, `git+git`, `hg+http`, `hg+https`, `hg+static-http`, `hg+ssh`, `svn`, `svn+svn`, `svn+http`, `svn+https`, `svn+ssh`, `bzr+http`, `bzr+https`, `bzr+ssh`, `bzr+sftp`, `bzr+ftp`, `bzr+lp`. - * [#2109](https://github.com/foosel/OctoPrint/pull/2109) - New decorator `@firstrun_only_access` for API endpoints that should only be available before first setup has been completed. - * [#2111](https://github.com/foosel/OctoPrint/issues/2111) - Made the file list's scroll bar wider. - * [#2131](https://github.com/foosel/OctoPrint/issues/2131) - Added warning to restart, shutdown, reboot and update confirmations that that may disrupt ongoing prints, even those run from the printer's internal storage/SD. See also [#2146](https://github.com/foosel/OctoPrint/pull/2146) and [#2152](https://github.com/foosel/OctoPrint/pull/2152). - * [#2138](https://github.com/foosel/OctoPrint/issues/2138) - Slightly longer timeout when attempting to read from serial during auto detection via programming mode. Might help with detection of some slower printer controllers under certain circumstances. - * [#2200](https://github.com/foosel/OctoPrint/issues/2200) - Wrap all JS assets of plugins into one anonymous function per plugin. That way plugins using `"use strict";` won't cause hard to debug and weird issues with other plugins bundled after them. The down side is that plugins currently relying on implicit declaration of global helper functions or variables (`function convert(value) { ... }`) to be available outside of their own plugin's JS assets will now run into errors. To compensate for that while affected plugins are adjusted to declare globals explicitly (`window.convert = function(value) { ... }`), a temporary feature flag was added as "Settings > Features > Enable legacy plugin asset bundling" that switches back to the old form of bundling until plugins you rely on are updated. This flag will be removed again in a later version (currently planned for 1.3.8). See also the note above and [#2246](https://github.com/foosel/OctoPrint/issues/2246). - * [#2229](https://github.com/foosel/OctoPrint/issues/2229) - Added note to printer profile dialog that the nozzle offsets for multi extruder setups are only to be configured if they are not already set in the printer's firmware. - * [#2232](https://github.com/foosel/OctoPrint/issues/2232) - Disable movement distance buttons when not connected to the printer or when printing, since they don't have any use then. - * [#2239](https://github.com/foosel/OctoPrint/pull/2239) - Improved the check summing speed, thus improving the general achievable throughput on the comm layer. - * Allow cancelling of file transfers - * Made check of how old an unrendered timelapse is more lenient buy looking at both the creation and last modification date and using the younger one. - * Made notifications in general auto-close faster. - * Make the first profile saved for a slicer the default profile for that slicer. - * New command `server` for testing server connections on the [JS test API](http://docs.octoprint.org/en/maintenance/api/util.html#post--api-util-test). - * New hook [`octoprint.accesscontrol.keyvalidator`](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-accesscontrol-keyvalidator) that allows plugins to validate their own customized API keys to be used to access OctoPrint. - * Updated `cookiecutter`, `requests` and `psutil` dependencies. - * Added safety warning to first run wizard. - * More error resilience against broken view models. - * New sub command `octoprint safemode`. Will set the `server.startOnceInSafeMode` setting in the config so that the next (re)start of the server after issuing this command will happen in safe mode. - * New sub command `octoprint config effective`. Will report the effective config. - * New centralized plugin blacklist (opt-in). Allows to prevent plugins/certain versions of plugins known to cause crippling issues with the normal operation of OctoPrint to be disabled from loading, if the user has opted to do so in the settings/wizard. - * Log how to enable `serial.log` to `serial.log` if it's disabled. That will hopefully put at least a small dent in the amount of "It's empty!" responses in tickets ;) - * Force new Pypi index URL in `requirements.txt` as an additional work around against old tooling. - * Prefer plain `pip` over `git` for updating OctoPrint. - * Added environment detection and logging on startup. That should give us more information about the environment to produce a reported bug in. - * Added OctoPi support plugin that provides information about the detected OctoPi version. Will only load if OctoPi is detected. - * More dynamic plugin mixin detection. Now using a base class instead of having to list all types manually. Should greatly reduce overhead of adding new mixin types. - * Support leaf merging for file extension tree, allowing to add new file extensions to types registered by default. - * Allow non GCODE SD file transfers if registered as `machinecode` through e.g. a plugin's file extension hook. Caution: This doesn't make streaming arbitrary files to the printer via serial work magically. It merely allows that, it's up to the firmware to actually be able to handle that. Also, the regular GCODE streaming protocol is used, so if the streamed file contains control characters from that (e.g. `M29` to signal the end of the streaming process), stuff will break! - * Added a test button for the online connectivity check. - * Announcements plugin: Added UTM Tags. - * Cura plugin: Less `not configured yet` logging. - * GCODE viewer: Added advanced options that allow configuring display of bounding boxes, sorting by layers and hiding of empty layers. - * GCODE viewer: Persist all options to local storage so they will be automatically set again the next time the GCODE viewer is used in the same browser. - * Software update: Auto-hide "Everything is up-to-date" notification. - * Easier copying of terminal contents thanks to dedicated copy button. - * Timelapse: [#2067](https://github.com/foosel/OctoPrint/issues/2067) - Added rate limiting to z-based timelapse capturing to prevent issues when accidentally leaving this mode on with vase mode prints. - * Timelapse: Refactored configuration form & added reset button to switch back to currently active settings. - * Timelapse: Sort timelapses by modification instead of creation time (creation time can be newer if a backup restore was done). - * Virtual printer: Support configurable ambient temperature for testing. - * Virtual printer: Support configurable reset lines. - * Virtual printer: Added new debug trigger `trigger_missing_lineno`. - * Virtual printer: Allow empty/`None` prepared oks, allowing to simulate lost acknowledgements right on start. - * Docs: [#2142](https://github.com/foosel/OctoPrint/pull/2142) - Added documentation for the bundled virtual printer plugin. - * Docs: [#2234](https://github.com/foosel/OctoPrint/pull/2234) - Added info on how to install under Suse Linux. - * Docs: Added example PyCharm run configuration that includes automatic dependency updates on start. - * Docs: Added information on how to run the test suite. - * Various refactorings - * Various documentation updates - * Fetch plugin blacklist (and also announcements, plugin notices and plugin repository) via https instead of http. - -### Bug fixes - - * [#2044](https://github.com/foosel/OctoPrint/pull/2044) - Fix various typos in strings and comments - * [#2048](https://github.com/foosel/OctoPrint/pull/2048) & [#2176](https://github.com/foosel/OctoPrint/pull/2176) - Fixed various warnings during documentation generation. - * [#2077](https://github.com/foosel/OctoPrint/issues/2077) - Fix an issue with shared nozzles and the temperature graph, causing temperature to not be reported properly when another tool but the first one is selected. See also [#2077](https://github.com/foosel/OctoPrint/pull/2123) - * [#2108](https://github.com/foosel/OctoPrint/issues/2108) - Added no-op default action to login form so that username + password aren't sent as GET parameters if for some reason the user tries to log in before the view models are properly bound and thus the AJAX POST submission method is attached. - * [#2111](https://github.com/foosel/OctoPrint/issues/2111) - Prevent file list's scroll bar from fading out. - * [#2146](https://github.com/foosel/OctoPrint/issues/2147) - Fix initialization of temperature graph if it's not on the first tab due to tab reordering. - * [#2166](https://github.com/foosel/OctoPrint/issues/2166) - Workaround for a Firefox bug that causes the Drag-n-Drop overlay to never go away if the file is dragged outside of the browser window. - * [#2167](https://github.com/foosel/OctoPrint/issues/2167) - Fixed grammar of print time estimation tooltip - * [#2175](https://github.com/foosel/OctoPrint/issues/2175) - Cancel printing when an external reset of the printer is detected on the serial connection. - * [#2181](https://github.com/foosel/OctoPrint/issues/2181) - More resilience against non-standard `M115` responses. - * [#2182](https://github.com/foosel/OctoPrint/pull/2182) - Don't start tracking non existing or nonfunctional tools if encountering a temperature command referencing said tool. See also [kantlivelong/OctoPrint-PSUControl#68](https://github.com/kantlivelong/OctoPrint-PSUControl/issues/68). - * [#2196](https://github.com/foosel/OctoPrint/issues/2196) - Marked API key fields as `readonly` instead of `disabled` to allow their contents to be copied in Firefox (which wasn't possible before). - * [#2203](https://github.com/foosel/OctoPrint/issues/2203) - Reset temperature offsets to 0 when disconnected from the printer. - * [#2206](https://github.com/foosel/OctoPrint/issues/2206) - Disable pre-configured timelapse if snapshot URL of ffmpeg path are unset. - * [#2214](https://github.com/foosel/OctoPrint/issues/2214) - Fixed temperature fields not selecting in MS Edge on focus. - * [#2217](https://github.com/foosel/OctoPrint/pull/2217) - Fix an issue in `octoprint.util` causing a crash when running under PyPy instead of CPython. - * [#2226](https://github.com/foosel/OctoPrint/issues/2226) - Handle `No Line Number with checksum, Last Line: ...` errors from the firmware. - * [#2233](https://github.com/foosel/OctoPrint/pull/2233) - Respond with `411 Length Required` when content length is missing on file uploads. - * [#2242](https://github.com/foosel/OctoPrint/issues/2242) - Fixed an issue where print time left could show "1 days" instead of "1 day". - * [#2262](https://github.com/foosel/OctoPrint/issues/2262) (regression) - Fixed a bug causing `Error:checksum mismatch, Last Line: ...` errors from the firmware to be handled incorrectly. - * [#2267](https://github.com/foosel/OctoPrint/issues/2267) (regression) - Fixed a bug causing the GCODE viewer to not get properly initialized due to a JS error on load if "Also show next layer" was selected. - * [#2268](https://github.com/foosel/OctoPrint/issues/2268) (regression) - Fixed a bug causing a display error with the temperature offsets. If one offset was changed, all others seemed to revert back to 0. - * Fixed cleanup of unrendered timelapses with certain names. - * Fixed a caching issue with the file list API and the slicing API. - * Fixed initial sizing of the temperature graph. - * More resilience against corrupt `.metadata.yaml` files. - * More resilience against corrupt/invalid entries for system actions. - * More resilience against invalid JSON command requests. - * More resilience against broken packages in the python environment. - * Don't evaluate `onWebcamLoaded` more than once when switching to the webcam tab. - * Fixed `octoprint config` sub command. - * Fixed deactivated user accounts being able to login (albeit without a persistent session). Show fitting error instead. - * Fixed temperature auto report after an external reset. - * Don't log full request headers in Tornado on an error. - * Fix displayed notification message for synchronous system commands. Was accidentally swapped with the one for asynchronous system commands. - * GCODE viewer: Fix error on empty layers. - * Virtual printer: Fix resend simuation. - * Docs: Fixed CSS of line numbered listings. - * Docs: Updated mermaid to fix a deprecation warning. - * Fixed ordering of plugin assets, should be alphabetical based on the plugin identifier. (regression) - * Fixed an issue causing redundant software update configuration settings to be written to `config.yaml`, in turn causing issues when downgrading to <1.3.5. (regression) - * Fixed an issue detecting whether the installed version is a release version or a development version. (regression) - -### More Information - - * [Commits](https://github.com/foosel/OctoPrint/compare/1.3.5...1.3.6) - * Release Candidates: - * [1.3.6rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.6rc1) - * [1.3.6rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.6rc2) - * [1.3.6rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.6rc3) - * A special **Thank you!** to everyone who reported back on these release candidates this time: [andrivet](https://github.com/andrivet), [b-morgan](https://github.com/b-morgan), [bjarchi](https://github.com/bjarchi), [chippypilot](https://github.com/chippypilot), [ChrisHeerschap](https://github.com/ChrisHeerschap), [cosmith71](https://github.com/cosmith71), [Crowlord](https://github.com/Crowlord), [ctgreybeard](https://github.com/ctgreybeard), [fiveangle](https://github.com/fiveangle), [goeland86](https://github.com/goeland86), [jbjones27](https://github.com/jbjones27), [jneilliii](https://github.com/jneilliii), [JohnOCFII](https://github.com/JohnOCFII), [Kunsi](https://github.com/Kunsi), [Lordxv](https://github.com/Lordxv), [malnvenshorn](https://github.com/malnvenshorn), [mcp5500](https://github.com/mcp5500), [ntoff](https://github.com/ntoff), [ripp2003](https://github.com/ripp2003) and [schorsch3000](https://github.com/schorsch3000) - -## 1.3.5 (2017-10-16) - -### Improvements - - * [#1162](https://github.com/foosel/OctoPrint/pull/1162) - Allow `octoprint.comm.protocol.gcode.queuing` hook to return a list of commands. - * [#1572](https://github.com/foosel/OctoPrint/issues/1572) & [#1881](https://github.com/foosel/OctoPrint/issues/1881) - Refactored web interface startup process to minimise risk of race conditions and speed improvements. Also added sequence diagram to the documentation showing the new processing order. - * [#1640](https://github.com/foosel/OctoPrint/issues/1640) - Mouse over temperature graph to get exact data for that time. - * [#1679](https://github.com/foosel/OctoPrint/issues/1679) - Support temperature autoreporting by the firmware instead of polling if the firmware reports to support it. For this to work with Marlin 1.1.0 to 1.1.3 you'll need to explicitly enable `EXTENDED_CAPABILITIES_REPORT` *and* `AUTO_REPORT_TEMPERATURES` in your firmware configuration, otherwise your firmware won't report that it actually supports this feature. - * [#1737](https://github.com/foosel/OctoPrint/issues/1737) - Auto-detect Anet A8 firmware and treat as Repetier Firmware (which it actually appears to be, just renamed - thanks Anet for making this even harder). - * [#1842](https://github.com/foosel/OctoPrint/issues/1842) - Update bundled FontAwesome to 4.7 (see also [#1915](https://github.com/foosel/OctoPrint/pull/1915)). - * [#1910](https://github.com/foosel/OctoPrint/issues/1910) - Make last/pause/cancel temperature available for GCODE scripts. - * [#1925](https://github.com/foosel/OctoPrint/issues/1925) - Include configured webcam stream URL in "Webcam stream not loaded" message for logged in users/admins. Slightly different wording for guests vs users vs admins. - * [#1941](https://github.com/foosel/OctoPrint/issues/1941) - Enable "block while dwelling" flag when Malyan firmware is detected since that firmware seems to handle `G4` identically to Repetier Firmware instead of Marlin (like it claims to). See also [#1762](https://github.com/foosel/OctoPrint/issues/1762). - * [#1946](https://github.com/foosel/OctoPrint/issues/1946) - Add option to disable position logging on cancel/pause. See "Log position on cancel" and "Log position on pause" under Settings > Serial > Advanced options. - * [#1971](https://github.com/foosel/OctoPrint/issues/1971) - Refactored temperature inputs. They now sport some fancy +/- buttons to increment/decrement the current temperature (which also auto submit after a couple of seconds) and easier editing by keyboard. The temperature offset was also slightly redesigned to make room for that. - * [#1975](https://github.com/foosel/OctoPrint/issues/1975) - Better error reporting when deleting timelapses. - * [#2010](https://github.com/foosel/OctoPrint/pull/2010) - Slight refactoring in the terminal tab: Full width input field, auto focus of input field when just clicking on terminal output. - * [#2011](https://github.com/foosel/OctoPrint/issues/2011) - Centralized online connectivity check (with opt-in of course). None of the bundled plugins will attempt to fetch data from the net when the connectivity check indicates that would fail anyhow. This should improve server startup times and various requests when running isolated. - * [#2025](https://github.com/foosel/OctoPrint/issues/2025) - More verbose logging of asynchronous system commands (e.g. restart/shutdown). - * Allow timelapse configuration through UI even when not connected to the printer (suggested in [#1918](https://github.com/foosel/OctoPrint/issues/1918)) - * Disable "Upload to SD" UI elements while printing (suggested in [#1914](https://github.com/foosel/OctoPrint/issues/1914)) - * Update bundled SockJS to 1.1.2 incl. source maps - * Set `X-Robots` HTTP header and remove `Server` header from all responses, also set `robots` meta tag in page. - * Don't require to enter programmer mode for printer port autodetection when there's only one possible port candidate anyhow. - * More sensible sorting of baudrates (additionally configured, then 115200, then 250000, then everything else). - * Don't show "Unhandled communication error" on autodetection failure. - * Make timeout after which to unload the webcam stream after navigating away from it configurable (as suggested in [#1937](https://github.com/foosel/OctoPrint/issues/1937)) - * Add `ToolChange` event and tool change GCODE scripts - * Support parsing GCODE subcodes. - * Add `octoprint.access.users.factory` hook, allowing plugins to extend/swap out the user manager OctoPrint uses. - * Corewizard: Disable view model and client code if it's not actually required. - * Corewizard: Disable injection of JS files into UI when it's not actually required. - * GCODE analysis: Moved into its own subprocess. That should improve performance on multi core systems. - * GCODE viewer: Ignore coordinates outside bed when zooming/centering on model. Those usually are nozzle priming routines. - * JS Client Lib: Add centralized browser detection as `OctoPrint.coreui.browser`. Available properties: `chrome`, `firefox`, `safari`, `ie`, `edge`, `opera` as well as `mobile` and `desktop`, all of which are boolean values. - * Plugin Manager plugin: Detect if a plugin requires a reconnect to the printer to become fully active/inactive. - * Software Update plugin: Force exact version when updating OctoPrint and tracking releases. - * Software Update plugin: "Devel RCs" release channel now also tracks maintenance RCs. That way people don't have to toggle between the two any more to get *all* RCs. - * Software Update plugin: `bitbucket_commit` check type now supports API credentials (see also [#1993](https://github.com/foosel/OctoPrint/pull/1993)). - * Wizard: Allow suppressing the "the settings got updated" dialog through subwizards, in case they need to update settings asynchronously as part of their workflow. - * More resilience against expected folders being files. - * More resilience against a wrong user manager class being configured. - * Some code refactoring & cleanup. - * Some HTML & CSS improvements. - -### Bug fixes - - * [#1916](https://github.com/foosel/OctoPrint/issues/1916) - Fix webcam not loading if first/initial tab is "Control" - * [#1924](https://github.com/foosel/OctoPrint/issues/1924) - Filter out source map links from bundled JS webassets. - * [#1943](https://github.com/foosel/OctoPrint/issues/1943) - Fix issue causing unnecessary creation of default printer profile on startup - * [#1946](https://github.com/foosel/OctoPrint/issues/1946) - Decouple writing of print log from everything else. Fixes delay in cancel processing. - * [#1963](https://github.com/foosel/OctoPrint/issues/1963) & [#1974](https://github.com/foosel/OctoPrint/issues/1974) - Allow empty & custom size in print job events. Also fixes an issue with timelapses when printing from SD on printers that require the GPX plugin to work. - * [#1996](https://github.com/foosel/OctoPrint/issues/1996) - Support all line ending variantes in the GCODE viewer. Solves an issue with GCODE generated for Prusa's multi material extruder since that uses only `\r` for some reason. - * [#2007](https://github.com/foosel/OctoPrint/issues/2007) - Fix issue parsing temperature lines from the printer that contain negative values. - * [#2012](https://github.com/foosel/OctoPrint/issues/2012) - Fix command line interface of Software Update plugin. - * [#2017](https://github.com/foosel/OctoPrint/issues/2017) - Fix issue in GCODE viewer with files that contain a visit to the first layer twice (e.g. brim, then nose dive from higher z for actual model), causing all but the last layer segment to not be rendered. - * [#2033](https://github.com/foosel/OctoPrint/issues/2033) (regression) - Temperature tab: Fix for legend in graph not updating with current values on mouse over. - * [#2033](https://github.com/foosel/OctoPrint/issues/2033) (regression) - Temperature tab: Fix for new temperature inputs not fitting on one line in Firefox. - * [#2033](https://github.com/foosel/OctoPrint/issues/2033) (regression) - Temperature tab & GCODE viewer: Fix for available tools (and offsets) not properly updating on change of printer profile. - * [#2033](https://github.com/foosel/OctoPrint/issues/2033) (regression) - Wizard: Fix sorting of required wizards not properly handling non-ASCII unicode. - * [#2035](https://github.com/foosel/OctoPrint/issues/2035) (regression) - Fix an issue of the server not starting up if there's a file in the analysis backlog. The reason for this is that spawning a new process while the intermediary server is active causes the server port to be blocked (this is due to how subprocessing works by default), in turn leading to an error on startup since the port cannot be bound by the actual server. Since the GCODE analysis takes now place in its own subprocess and hence triggers this problem, it had to be moved until after the actual server has already started up to avoid this problem. - * [#2059](https://github.com/foosel/OctoPrint/issues/2059) (regression) - Fix an issue causing the new temperature controls to wrap on touch enabled devices when the temperature dropdown is opened. - * [#2090](https://github.com/foosel/OctoPrint/issues/2090) (regression) - Fix an issue causing an aborted server startup under Windows if the timing is just right. - * [#2135](https://github.com/foosel/OctoPrint/issues/2135) (regression) - Fix an issue causing import errors inside the GCODE analysis tool in certain environments due to `sys.path` entries causing relative imports. - * [#2136](https://github.com/foosel/OctoPrint/issues/2136) (regression) - Fix wrong minimum version for `sockjs-tornado` dependency. - * [#2137](https://github.com/foosel/OctoPrint/issues/2137) (regression) - Fix issue with session cookies getting lost when running an OctoPrint instance on a subpath of another (e.g. `octopi.local/` and `octopi.local/octoprint2`). - * [#2140](https://github.com/foosel/OctoPrint/issues/2140) (regression) - Fix issue with locale dependent sorting of sub wizards during first time setup causing issues leading to the wizard not being able to complete. - * Fix various popup buttons allowing multiple clicks (suggested in [#1914](https://github.com/foosel/OctoPrint/issues/1914)) - * Software Update Plugin: Perform server restart asynchronously. Should reduce restart times on updates significantly. - * Don't hex-escape `\t`, `\r` or `\n` in terminal output - * Use client side default printer profile if the default profile could not be found on the server - * Use both "to" and "from" coordinates of a given move for min/max model coordinate calculation in GCODE analysis. Otherwise wrong values could be calculated under certain circumstances. - * Fix potential race condition in resend request handling. - * Fix potential race condition in web socket handling. - * Fix handling of tool offsets in GCODE analysis - diverted too far from firmware implementations, causing wrong calculations. - * Fix `FileAdded`, `FileRemoved`, `FolderAdded`, `FolderRemoved` events not being fired with the correct event name. - * Fix potential division by zero in progress reporting if the timing was just right. - * Fix sorting order for multiple tools in the "State" panel. - * Fix file position vs. line ending handling in GCODE viewer. Could lead to slightly off file position calculation and hence possibly to the wrong move being plotted when synchronizing with print progress. - * Wizard: Fix `onWizardPreventSettingsRefreshDialog` callback invocation. (regression) - * Corewizard plugin: Fix `firstrunonly` wizards (e.g. for printer profile configuration) being displayed again if _any_ of the sub wizards (e.g. for the online check opt-in and configuration) is active. (regression) - * Fix an issue causing rollover of `serial.log` to fail under Windows. (regression) - -### More Information - - * [Commits](https://github.com/foosel/OctoPrint/compare/1.3.4...1.3.5) - * Release Candidates: - * [1.3.5rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.5rc1) - * [1.3.5rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.5rc2) - * [1.3.5rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.5rc3) - * [1.3.5rc4](https://github.com/foosel/OctoPrint/releases/tag/1.3.5rc4) - * A special **Thank you!** to everyone who reported back on these release candidates this time: [alexxy](https://github.com/alexxy), [andrivet](https://github.com/andrivet), [b-morgan](https://github.com/b-morgan), [BillyBlaze](https://github.com/BillyBlaze), [CapnBry](https://github.com/CapnBry), [chippypilot](https://github.com/chippypilot), [ctgreybeard](https://github.com/ctgreybeard), [cxt666](https://github.com/cxt666), [DaSTIG](https://github.com/DaSTIG), [fhbmax](https://github.com/fhbmax), [fiveangle](https://github.com/fiveangle), [goeland86](https://github.com/goeland86), [JohnOCFII](https://github.com/JohnOCFII), [Kunsi](https://github.com/Kunsi), [mgrl](https://github.com/mgrl), [MoonshineSG](https://github.com/MoonshineSG), [nate-ubiquisoft](https://github.com/nate-ubiquisoft), [Neoolog](https://github.com/Neoolog), [ntoff](https://github.com/ntoff), [oferfrid](https://github.com/oferfrid), [roygilby](https://github.com/roygilby), [SAinc](https://github.com/SAinc), [sbts](https://github.com/sbts), [thess](https://github.com/thess), [tkurbad](https://github.com/tkurbad), [tsillini](https://github.com/tsillini) and [TylonHH](https://github.com/TylonHH). - -## 1.3.4 (2017-06-01) - -### Note for owners of Malyan M200/Monoprice Select Mini - -OctoPrint's firmware autodetection is now able to detect this printer. Currently when this printer is detected, the following firmware specific features will be enabled automatically: - - * Always assume SD card is present (`feature.sdAlwaysAvailable`) - * Send a checksum with the command: Always (`feature.alwaysSendChecksum`) - -Since the firmware is a very special kind of beast and its sources are so far unavailable, only tests with a real printer will show if those are sufficient settings for communication with this printer to fully function correctly. Thus, if you run into any issues with enabled firmware autodetection on this printer model, please add a comment in [#1762](https://github.com/foosel/OctoPrint/issues/1762) and explain what kind of communication problem you are seeing. Also make sure to include a [`serial.log`](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md#where-can-i-find-those-log-files-you-keep-talking-about)! - -### Bug fixes - - * [#1942](https://github.com/foosel/OctoPrint/issues/1942) - Fixed crash on startup in case of an invalid default printer profile combined with "auto-connect on startup" being selected and the printer available to connect to. - -### More information - - * [Commits](https://github.com/foosel/OctoPrint/compare/1.3.1...1.3.2) - * Release Candidates: - * None since this constitutes a hotfix release to fix an apparently very rare bug introduced with 1.3.3 that seems to be affecting a small number of users. - -## 1.3.3 (2017-05-31) - -### Note for owners of Malyan M200/Monoprice Select Mini - -OctoPrint's firmware autodetection is now able to detect this printer. Currently when this printer is detected, the following firmware specific features will be enabled automatically: - - * Always assume SD card is present (`feature.sdAlwaysAvailable`) - * Send a checksum with the command: Always (`feature.alwaysSendChecksum`) - -Since the firmware is a very special kind of beast and its sources are so far unavailable, only tests with a real printer will show if those are sufficient settings for communication with this printer to fully function correctly. Thus, if you run into any issues with enabled firmware autodetection on this printer model, please add a comment in [#1762](https://github.com/foosel/OctoPrint/issues/1762) and explain what kind of communication problem you are seeing. Also make sure to include a [`serial.log`](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md#where-can-i-find-those-log-files-you-keep-talking-about)! - -### Improvements - - * [#478](https://github.com/foosel/OctoPrint/issues/478) - Made webcam stream container fixed height (with selectable aspect ratio) to prevent jumps of the controls beneath it on load. - * [#748](https://github.com/foosel/OctoPrint/issues/748) - Added delete confirmation and bulk delete for timelapses. See also the discussion in brainstorming ticket [#1807](https://github.com/foosel/OctoPrint/issues/1807). - * [#1092](https://github.com/foosel/OctoPrint/issues/1092) - Added new events to the file manager: `FileAdded`, `FileRemoved`, `FolderAdded`, `FolderRemoved`. Contrary to the `Upload` event, `FileAdded` will always fire when a file was added to storage through the file manager, not only when added through the web interface. Extended documentation accordingly. - * [#1521](https://github.com/foosel/OctoPrint/issues/1521) - Software update plugin: Display timestamp of last version cache refresh in "Advanced options" area. - * [#1734](https://github.com/foosel/OctoPrint/issues/1734) - Treat default/initial printer profile like all other printer profiles, persisting it to disk instead of `config.yaml` and allowing deletion. OctoPrint will migrate the existing default profile to the new location on first start. - * [#1734](https://github.com/foosel/OctoPrint/issues/1734) - Better communication of what actions are available for printer profiles. - * [#1739](https://github.com/foosel/OctoPrint/issues/1739) - Software update plugin: Added option to hide update notification from users without admin rights, added "ignore" button and note to get in touch with an admit to update notifications for non admin users. - * [#1762](https://github.com/foosel/OctoPrint/issues/1762) - Added Malyan M200/Monoprice Select Mini to firmware autodetection. - * [#1811](https://github.com/foosel/OctoPrint/issues/1811) - Slight rewording and rearrangement in timelapse configuration, better feedback if settings have been saved. - * [#1818](https://github.com/foosel/OctoPrint/issues/1818) - Support both Marlin/Repetier and Smoothieware interpretations of `G90` after an `M83` in GCODE viewer and analysis. Select "G90/G91 overrides relative extruder mode" in Settings > Features for the Smoothieware interpretation. - * [#1858](https://github.com/foosel/OctoPrint/issues/1858) - Announcement plugin: Images from registered feeds now are lazy loading. - * [#1862](https://github.com/foosel/OctoPrint/issues/1862) - Automatically re-enable fancy terminal functionality when performance recovers. - * [#1875](https://github.com/foosel/OctoPrint/issues/1875) - Marked the command input field in the Terminal tab as not supporting autocomplete to work around an issue in Safari. Note that this is probably only a temporary workaround due to browser vendors [working on deprecating `autocomplete="off"` support](https://bugs.chromium.org/p/chromium/issues/detail?id=468153#c164) and a different solution will need to be found in the future. - * Added link to [`SerialException` FAQ entry](https://github.com/foosel/OctoPrint/wiki/FAQ#octoprint-randomly-loses-connection-to-the-printer-with-a-serialexception) to terminal output when such an error is encountered, as suggested in [#1876](https://github.com/foosel/OctoPrint/issues/1876). - * Force refresh of settings on login/logout. - * Made system wide API key management mirror user API key management. - * Make sure to always migrate and merge saved printer profiles with default profile to ensure all parameters are set. Should avoid issues with plugins trying to save outdated/incomplete profiles. - * Added note on lack of language pack repository & to use the wiki for now. - * Earlier validation of file to select for printing. - * Limit verbosity of failed system event handlers. - * Made bundled python client `octoprint_client` support multiple client instances. - * Disable "Reload" button in the "Please reload" overlay once clicked, added spinner. - * Updated pnotify to 2.1.0. - * Get rid of ridiculous float precision in temperature commands. - * Detect invalid settings data to persist (not a dict), send 400 status in such a case. - * More logging for preemptive caching, to help narrow down any performance issues that might be related to this. - * Further decoupling of some startup tasks from initial server startup thread for better parallelization and improved startup times. - * Announcement plugin: Added combined OctoBlog feed, replacing news and spotlight feed, added corresponding config migration. - * Announcement plugin: Subscribe to all registered feeds by default to ensure better communication flow (all subscriptions but the "Important" channel can however be unsubscribed easily, added corresponding note to the notifications and also a configuration button to the announcement reader). - * Announcement plugin: Auto-hide announcements on logout. - * Announcement plugin: Order channels server-side based on new order config setting. - * Plugin manager: Show warning when disabling a bundled plugin that is not recommended to be disabled, including a reason why disabling it is not recommended. Applies to the bundled announcement, core wizard, discovery and software update plugins. - * Plugin manager: Support for plugin notices for specific plugins from the plugin repository, e.g. to inform users of specific plugins about known issues with the plugin or instruct to update when the software update mechanism of the current plugin version turns out to be misconfigured. Supports matching installed plugin versions and OctoPrint versions to target only affected users. - * Plugin manager: Better visualization of plugins disabled on the repository, no longer shown as "incompatible" but "disabled", with link to the plugin repository page that contains more information. - * Plugin manager: Detect necessity to reinstall a plugin provided through archive URL or upload and immediately do that instead of reporting an "unknown error" without further information. - * Plugin manager: Added `freebsd` for compatibility check. - * Plugin manager: More general flexibility for OS compatibility check: - * Support for arbitrary values to match against - * Allow 1:1 check again `sys.platform` values (with `startswith`). - * Support black listing (`!windows`) additionally to white listing. A detected OS must match all provided white list elements (if the white list is empty that is considered to be always the case) and none of the black list elements (if the black list is empty that is also considered to be always the case). - * Software update plugin: New check type `bitbucket_commit` (see also [#1898](https://github.com/foosel/OctoPrint/pull/1898)) - * Docs: Now referring to dedicated Jinja 2.8 documentation as hosted at [jinja.octoprint.org](http://jinja.octoprint.org) for all template needs, to avoid confusion when consulting current Jinja documentation as available on its project page (2.9+, which OctoPrint can't upgrade to due to backwards incompatible changes). - * Docs: Better documentation of what kind of input the `FileManager` accepts for `select_file`. - * Docs: Specified OctoPrint version required for plugin tutorial. - -### Bug fixes - - * [#202](https://github.com/foosel/OctoPrint/issues/202) - Fixed an issue with the drag-n-drop area flickering if the mouse was moved too slow while dragging (see also [#1867](https://github.com/foosel/OctoPrint/pull/1867)). - * [#1671](https://github.com/foosel/OctoPrint/issues/1671) - Removed obsolete entry of no longer available filter for empty folders from file list options. - * [#1821](https://github.com/foosel/OctoPrint/issues/1821) - Properly reset "Capture post roll images" setting in timelapse configuration when switching from "off" to "timed" timelapse mode. - * [#1822](https://github.com/foosel/OctoPrint/issues/1822) - Properly reset file metadata when a file is overwritten with a new version. - * [#1836](https://github.com/foosel/OctoPrint/issues/1836) - Fixed order of `PrintCancelled` and `PrintFailed` events on print cancel. - * [#1837](https://github.com/foosel/OctoPrint/issues/1837) - Fixed a race condition causing OctoPrint trying to read data from the current job on job cancel that was no longer there. - * [#1838](https://github.com/foosel/OctoPrint/issues/1838) - Fixed a rare race condition causing an error right at the very start of a print. - * [#1863](https://github.com/foosel/OctoPrint/issues/1863) - Fixed an issue in the analysis of GCODE files containing coordinate offsets for X, Y or Z via `G92`, leading to a wrong calculation of the model size thanks to accumulating offsets. - * [#1882](https://github.com/foosel/OctoPrint/issues/1882) - Fixed a rare race condition occurring at the start of streaming a file to the printer's SD card, leading to endless line number mismatches. - * [#1884](https://github.com/foosel/OctoPrint/issues/1884) - CuraEngine plugin: Fixed a potential encoding issue when logging non-ASCII parameters supplied to CuraEngine - * [#1891](https://github.com/foosel/OctoPrint/issues/1891) - Fixed error when handling unicode passwords. - * [#1893](https://github.com/foosel/OctoPrint/issues/1893) - CuraEngine plugin: Fixed handling of multiple consecutive uploads of slicing profiles (see also [#1894](https://github.com/foosel/OctoPrint/issues/1894)) - * [#1897](https://github.com/foosel/OctoPrint/issues/1897) - Removed possibility to concurrently try to perform multiple tests of the configured snapshot URL. - * [#1906](https://github.com/foosel/OctoPrint/issues/1906) - Fixed interpretation of `G92` in GCODE analysis. - * [#1907](https://github.com/foosel/OctoPrint/issues/1907) - Don't send temperature commands with tool parameter when a shared nozzle is defined. - * [#1917](https://github.com/foosel/OctoPrint/issues/1917) (regression) - Fix job data resetting on print job completion. - * [#1918](https://github.com/foosel/OctoPrint/issues/1918) (regression) - Fix "save as default" checkbox not being disabled when other controls are disabled. - * [#1919](https://github.com/foosel/OctoPrint/issues/1919) (regression) - Fix call to no longer existing function in Plugin Manager UI. - * [#1934](https://github.com/foosel/OctoPrint/issues/1934) (regression) - Fix consecutive timed timelapse captures without configured post roll. - * Fixed API key QR Code being shown (for "n/a" value) when no API key was set. - * Fixed timelapse configuration API not returning 400 status code on some bad parameters. - * Fixed a typo (see also [#1826](https://github.com/foosel/OctoPrint/pull/1826)). - * Fixed `filter` and `force` parameters on `/api/files/`. - * Fixed message catchall `*` not working in the socket client library. - * Fixed analysis backlog calculation for sub folders. - * Fixed `PrinterInterface.is_ready` to behave as documented. - * Use black listing instead of white listing again to detect if the `daemon` sub command is supported or not. Should resolve issues users of FreeBSD and the like where having with `octoprint daemon`. - * Use `pip` instead of `python setup.py develop` in `octoprint dev plugin:install` command to avoid issues on Windows. - * Docs: Fixed a wrong command in the plugin tutorial (see also [#1860](https://github.com/foosel/OctoPrint/pull/1860)). - -### More information - -- [Commits](https://github.com/foosel/OctoPrint/compare/1.3.2...1.3.3) -- Release Candidates: - - [1.3.3rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.3rc1) - - [1.3.3rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.3rc2) - - [1.3.3rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.3rc3) - -## 1.3.2 (2017-03-16) - -### Note for plugin authors - -**If you maintain a plugin that extends OctoPrint's [JavaScript Client Library](http://docs.octoprint.org/en/master/jsclientlib/index.html)** like demonstrated in e.g. the bundled Software Update Plugin you'll need to update the way you register your plugin to depend on `OctoPrintClient` and registering your extension as shown [here](https://github.com/foosel/OctoPrint/blob/6e793c2/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js#L1-L84) instead of directly writing to `OctoPrint.plugins` (like it was still done [here](https://github.com/foosel/OctoPrint/blob/23744cd/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js#L1-L81)). That way your extensions will be available on all instances of `OctoPrintClient`, not just the global instance `OctoPrint` that gets created on startup of the core web interface. - -If all you plugin does with regards to JavaScript is registering a custom view model and you have no idea what I'm talking about regarding extending the client library, no action is necessary. This heads-up is really only relevant if you extended the JavaScript Client Library. - -### Improvements - -- [#732](https://github.com/foosel/OctoPrint/pull/732) - Have OctoPrint's `python setup.py clean` build on stock -`python setup.py clean` for better compatibility with packaging systems -- [#1506](https://github.com/foosel/OctoPrint/issues/1506) - Better handle really long "dwell"/`G4` commands on Repetier firmware (as for example apparently recommended to use with Wanhao D6 and similar printers for nozzle cooling) by actively stalling communication from OctoPrint's side as well. That way we no longer run into a communication timeout produced by a 5min dwell immediately happily acknowledged by the printer with an `ok`. -- [#1542](https://github.com/foosel/OctoPrint/issues/1542) - Support for multi-extruder setups with a shared single nozzle and heater (e.g. E3D Cyclops, Diamond hotend, etc). -- [#1676](https://github.com/foosel/OctoPrint/issues/1676) - Trigger line number reset when connected to printer and seeing `start` message. This should fix issues with printer communication when printer resets but reset goes otherwise undetected. -- [#1681](https://github.com/foosel/OctoPrint/issues/1681) - Support for connecting to multiple OctoPrint instances via the [JavaScript Client Library](http://docs.octoprint.org/en/master/jsclientlib/index.html). -- [#1712](https://github.com/foosel/OctoPrint/issues/1712) - Display current folder name in file list if in sub folder. -- [#1723](https://github.com/foosel/OctoPrint/issues/1723) - Ignore leading `v` or `V` on plugin version numbers for version checks in plugin manager and software updater (see also [#1724](https://github.com/foosel/OctoPrint/pull/1724)) -- [#1770](https://github.com/foosel/OctoPrint/issues/1770) - Better resilience against null bytes received from the printer for whatever reason. -- [#1770](https://github.com/foosel/OctoPrint/issues/1770) - Detect printer as connected even when only receiving a `wait` instead of `ok`. Should solve issues with initial connect where printer sends garbage over the line that eats/covers the `ok` if printer also sends regular `wait` messages when idle. -- [#1780](https://github.com/foosel/OctoPrint/issues/1780) - Work around for Safari re-opening one copy of the webcam stream after the other and eating up bandwidth unnecessarily (see also [#1786](https://github.com/foosel/OctoPrint/issues/1786)) -- [#1790](https://github.com/foosel/OctoPrint/issues/1790) - Removed unused "color" property from printer profile editor. -- [#1805](https://github.com/foosel/OctoPrint/issues/1805) - Better error resilience against invalid print history data from plugins that replace the printer communication. -- Better error resilience in Plugin Manager against wonky version data in repository file. -- Added a "Restart in safe mode" system menu entry that will always be available if the restart command is configured -- CLI: Only offer `daemon` sub command on Linux (since that it's the only OS it works on) -- Less throttling of analysis of GCODE files from the analysis backlog. Should still leave Pi and friends air to breathe but allow a slightly faster processing of the backlog. -- Added an explanation of safe mode to the docs. -- Log OctoPrint version & plugin list when detecting log rollover. -- Allow `UiPlugin`s to define additional fields for ETag generation. -- Allow `UiPlugin`s utilizing OctoPrint's stock templates to filter out what they don't need. -- Locales contained in `translations` of plugins will now be registered with the system. That way it's possible to provide translations for the full application through plugins. -- Abort file analysis if file is about to be overwritten -- Software Update Plugin: Refresh cache on startup, prevent concurrent refresh -- More solid parsing of request line number for resend requests. Should improve compatibility with Teacup firmwares. Based on issue reported via PR [#300](https://github.com/foosel/OctoPrint/pull/300) - -### Bug fixes - -- [#733](https://github.com/foosel/OctoPrint/issues/733) - Fixed multiple event handler commands running concurrently. Now they run one after the other, as expected. -- [#1317](https://github.com/foosel/OctoPrint/issues/1317) - Fixed a color distortion issue when rendering timelapses from higher resolution source snapshots that also need to be rotated by adjusting `ffmpeg` parameters to avoid an unexpected behaviour when a pixel format and a filter chain are required for processing. -- [#1560](https://github.com/foosel/OctoPrint/issues/1560) - Make sure we don't try to use an empty `logging.yaml` -- [#1631](https://github.com/foosel/OctoPrint/issues/1631) - Disable "Slice" button in slice dialog if a print is ongoing and a slicer is selected that runs on the same device as OctoPrint. The server would already deny such requests (simply due to performance reasons), but the UI didn't properly reflect that yet. -- [#1671](https://github.com/foosel/OctoPrint/issues/1671) - Removed "Hide empty folders" option from file list. Didn't really add value and caused usability issues. -- [#1771](https://github.com/foosel/OctoPrint/issues/1771) - Fixed `_config_version` in plugin settings not being properly updated. -- [#1732](https://github.com/foosel/OctoPrint/issues/1732) - Fixed a bug in the documentation for the printer profile API -- [#1760](https://github.com/foosel/OctoPrint/issues/1760) - Fixed missing reselect of selected file when updating via the watched folder, causing wrong progress percentages to be reported. -- [#1765](https://github.com/foosel/OctoPrint/issues/1765) - Fixed watched folder not waiting with file move until file stopped growing, causing wrong progress percentages to be reported. -- [#1777](https://github.com/foosel/OctoPrint/issues/1777) - Fixed z-change based timelapses with Slic3r generated z-hops not properly triggering snapshots. -- [#1792](https://github.com/foosel/OctoPrint/issues/1792) - Don't tell Safari we are "web-app-capable" because that means it will throw away all cookies and the user will have to constantly log in again when using a desktop shortcut for the OctoPrint instance. -- [#1812](https://github.com/foosel/OctoPrint/issues/1812) - Don't scroll up navigation in settings when switching between settings screens, very annoying on smaller resolutions (see also [#1814](https://github.com/foosel/OctoPrint/pull/1814)) -- Fix settings helper not allowing to delete values for keys that are present in the local config but not in the defaults. -- Fix wrong replacement value for `__progress` in registered command line or GCODE [event handlers](http://docs.octoprint.org/en/master/events/index.html). -- Various fixes in the Software Update Plugin: - - Don't remove manual software update configurations on settings migration. - - Properly delete old restart/reboot commands that are now defined globally since config version 4. An issue with the settings helper prevented us from properly deleting them during migration to version 4. - - Fixed `python_checker` version check method and `python_updater` update method. - - Fixed update configs without a restart of any kind causing an issue due to an undefined variable. - - Fixed broken doctests. -- Upgrade LESS.min.js from 2.7.1 to 2.7.2 to fix the broken contrast function -- Always create a new user session for requests with an API key -- Fixed an error when reading all user settings via the API -- Fixed a bunch of caching issues for the page, was not properly updated on change of snapshot URL presence, system menu entry presence, gcode viewer enabled/disabled, changes in access control availability. -- Fixed wrong bundling of core and plugin assets -- Software Update Plugin: Fixed wrong ETag calculation -- Disable external heatup detection until firmware is detected -- Fixed login dropdown not closing on click outside of it -- Fixed new user settings getting lost until restart -- Don't call `onUserLoggedIn`/`onUserLoggedOut` on user reload - -### More information - -- [Commits](https://github.com/foosel/OctoPrint/compare/1.3.1...1.3.2) -- Release Candidates: - - [1.3.2rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.2rc1) - -## 1.3.1 (2017-01-25) - -### Note for upgraders - -#### If you installed OctoPrint manually and used the included init script, you need to update that - -The init script so far shipped with OctoPrint contained a [bug](https://github.com/foosel/OctoPrint/issues/1657) that causes issues with OctoPrint 1.3.0 and higher. Please update your init script to the fixed version OctoPrint now ships under `scripts`: - -``` -sudo cp /path/to/OctoPrint/scripts/octoprint.init /etc/init.d/octoprint -``` - -If you are running OctoPi, this does **not** apply to you and you do not need to do anything here! - -#### Change in stock terminal filter configuration - -1.3.1 fixes an issue with the two terminal filters for suppressing temperature and SD status messages and adds a new filter for filtering out firmware `wait` messages. These changes will only be active automatically though for stock terminal filter configurations. If you have customized your terminal filters, you'll need to apply these changes manually under "Settings > Terminal filters": -- Changed "Suppress temperature messages" filter, new regex is `(Send: (N\d+\s+)?M105)|(Recv: ok (B|T\d*):)` -- Changed "Suppress SD status messages" filter, new regex is `(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)` -- New "Suppress wait responses" filter, regex is `Recv: wait` - -### Improvements -- [#1607](https://github.com/foosel/OctoPrint/issues/1607) - Way better support for password managers (e.g. browser built-in, 1Password, Lastpass, Dashlane) -- [#1638](https://github.com/foosel/OctoPrint/issues/1638) - Make confirmation dialog when cancelling a print optional. -- [#1656](https://github.com/foosel/OctoPrint/issues/1656) - Make wording of buttons on print cancel dialog less confusing. -- [#1705](https://github.com/foosel/OctoPrint/pull/1705) - Simplified install process on Mac by removing dependency on pyobjc. -- [#1706](https://github.com/foosel/OctoPrint/pull/1706) - Added a mask icon for Safari pinned tab and touchbar. -- Support extraction of filament diameter for volume calculation from GCODE files sliced through Simplify3D. -- Abort low priority jobs in the file analysis queue when a high priority job comes in - should make file analysis and hence time estimates show up faster for newly uploaded files. -- Added a terminal filter for firmware `wait` messages to the stock terminal filters. If you did modify your terminal filter configuration, you might want to add this manually: - - New "Suppress wait responses" filter: `Recv: wait` - -### Bug fixes - -- [#1344](https://github.com/foosel/OctoPrint/issues/1344) - Fix ProgressBarPlugins to not correctly be triggered for 0% (second try, this time hopefully for good). -- [#1637](https://github.com/foosel/OctoPrint/issues/1637) - Fix issue preventing a folder to be deleted that has a name which is a common prefix of the file currently being printed. -- [#1641](https://github.com/foosel/OctoPrint/issues/1641) - Fix issue with `octoprint --daemon` not working. -- [#1647](https://github.com/foosel/OctoPrint/issues/1647) - Fix issue with `octoprint` command throwing an error if an environment variable `OCTOPRINT_VERSION` was set to its version number. -- [#1648](https://github.com/foosel/OctoPrint/issues/1648) - Added missing `websocket-client` dependency of `octoprint client` to install script. -- [#1653](https://github.com/foosel/OctoPrint/issues/1653) - Fix for an issue with the included init script on the BBB (see also [#1654](https://github.com/foosel/OctoPrint/issues/1654)) -- [#1657](https://github.com/foosel/OctoPrint/issues/1657) - Fix init script regarding check for configured `CONFIGFILE` variable. -- [#1657](https://github.com/foosel/OctoPrint/issues/1657) - Don't care about ordering of common parameters (like `--basedir`, `--config`) on CLI. -- [#1660](https://github.com/foosel/OctoPrint/issues/1660) - Do not show hint regarding keyboard controls beneath webcam stream if keyboard control feature is disabled. -- [#1667](https://github.com/foosel/OctoPrint/issues/1667) - Fix for matching folders not getting listed in the results when performing a search in the file list. -- [#1675](https://github.com/foosel/OctoPrint/issues/1675) - Fix model size calculation in GCODE analysis, produced wrong values in some cases. Also adjusted calculation to match implementation in GCODE viewer, now both produce identical results. -- [#1685](https://github.com/foosel/OctoPrint/issues/1685) - Cura Plugin: Fix filament extraction from CuraEngine slicing output -- [#1692](https://github.com/foosel/OctoPrint/issues/1692) - Cura Plugin: Fix solid layer calculation (backport from [Ultimaker/CuraEngine#140](https://github.com/Ultimaker/CuraEngine/issues/140)) -- [#1693](https://github.com/foosel/OctoPrint/issues/1693) - Cura Plugin: Support `perimeter_before_infill` profile setting. Additionally added support for `solidarea_speed`, `raft_airgap_all`, `raft_surface_thickness`, `raft_surface_linewidth` profile settings and adjusted mapping for engine settings `raftAirGapLayer0`, `raftFanSpeed`, `raftSurfaceThickness`and `raftSurfaceLinewidth` according to current mapping in Cura Legacy and adjusted Mach3 GCODE flavor to substitute `S` with `P` in temperature commands of generated start code, also like in Cura Legacy. -- [#1697](https://github.com/foosel/OctoPrint/issues/1697) - Pin Jinja to versions <2.9 for now due to a backwards compatibility issue with templates for versions newer than that. Also pushed as a hotfix to 1.3.0 (as 1.3.0post1). -- [#1708](https://github.com/foosel/OctoPrint/issues/1708) - Cura Plugin: Fixed selection of `start.gcode` for sliced file -- Allow a retraction z-hop of 0 in timelapse configuration. -- Fix files in sub folders to not be processed by the initial analysis backlog check during startup of the server. -- Various fixes in the file analysis queue: - - High priority items are now really high priority - - Abort analysis for items that are to be deleted/moved to get around an issue with file access under Windows systems. -- Fix stock terminal filters for suppressing temperature messages and SD status messages to also be able to deal with line number prefixes. If you have added additional terminal filters, you will have to apply this fix manually: - - Changed "Suppress temperature messages" filter: `(Send: (N\d+\s+)?M105)|(Recv: ok (B|T\d*):)` - - Changed "Suppress SD status messages" filter: `(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)` -- Fix issue in german translation. - -### More information - -- [Commits](https://github.com/foosel/OctoPrint/compare/1.3.0...1.3.1) -- Release Candidates: - - [1.3.1rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.1rc1) - - [1.3.1rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.1rc2) - -## 1.3.0 (2016-12-08) - -### Features - - * You can now create folders in the file list, upload files into said folders and thus better manage your projects' files. - * New wizard dialog for system setups that can also be extended by plugins. Replaces the first run dialog for setting up access control and can also be triggered in other cases than only the first run, e.g. if plugins necessitate user input to function properly. Added wizards to help configuring the following components in OctoPrint on first run: access control, webcam URLs & ffmpeg path, server commands (restart, shutdown, reboot), printer profile. Also extended the bundled Cura plugin to add a wizard for its first setup to adjust path and import a slicing profile, and the bundled Software Update plugin to ask the user for details regarding the OctoPrint update configuration. Also see below. - * New command line interface (CLI). Offers the same functionality as the old one plus: - * a built-in API client (``octoprint client --help``) - * built-in development tools (``octoprint dev --help``) - * extendable through plugins implementing the ``octoprint.cli.commands`` hook (``octoprint plugins --help``) - * New features within the plugin system: - * Plugins may now give hints in which order various hooks or mixin methods should be called by optionally providing an integer value that will be used for sorting the callbacks prior to execution. - * Plugins may now define configuration overlays to be applied on top of the default configuration but before ``config.yaml``. - * New mixin `UiPlugin` for plugins that want to provide an alternative web interface delivered by the server. - * New mixin ``WizardPlugin`` for plugins that want to provide wizard components to OctoPrint's new wizard dialog. - * New hook ``octoprint.cli.commands`` for registering a command with the new OctoPrint CLI - * New hook ``octoprint.comm.protocol.gcode.received`` for receiving messages from the printer - * New hook ``octoprint.printer.factory`` for providing a custom factory to contruct the global ``PrinterInterface`` implementation. - * New ``TemplatePlugin`` template type: ``wizard`` - * New Javascript client library for utilizing the server's API, can be reused by `UiPlugin`s. - * OctoPrint will now track the current print head position on pause and cancel and provide it as new template variables ``pause_position``/``cancel_position`` for the relevant GCODE scripts. This will allow more intelligent pause codes that park the print head at a rest position during pause and move it back to the exact position it was before the pause on resume ([Example](https://gist.github.com/foosel/1c09e269b1c0bb7a471c20eef50c8d3e)). Note that this is NOT enabled by default and for now will necessitate adjusting the pause and resume GCODE scripts yourself since position tracking with multiple extruders or when printing from SD is currently not fool proof thanks to firmware limitations regarding reliable tracking of the various ``E`` values and the currently selected tool ``T``. In order to fully implement this feature, the following improvements were also done: - * New ``PositionUpdated`` event when OctoPrint receives a response to an ``M114`` position query. - * Extended ``PrintPaused`` and ``PrintCancelled`` events with position data from ``M114`` position query on print interruption/end. - * Added (optional) firmware auto detection. If enabled (which it is by default), OctoPrint will now send an ``M115`` to the printer on initial connection in order to try to figure out what kind of firmware it is. For FIRMWARE_NAME values containing "repetier" (case insensitive), all Repetier-specific flags will be set on the comm layer. For FIRMWARE_NAME values containing "reprapfirmware" (also case insensitive), all RepRapFirmware-specific flags will be set on the comm layer. For now no other handling will be performed. - * Added safe mode flag ``--safe`` and config setting ``startOnceInSafeMode`` that disables all third party plugins when active. The config setting will automatically be removed from `config.yaml` after the server has started through successfully. - * Added ``octoprint config`` CLI that allows easier manipulation of config.yaml entries from the command line. Example: ``octoprint config set --bool server.startOnceInSafeMode true`` - -### Improvements - - * [#1048](https://github.com/foosel/OctoPrint/issues/1048) - Added "Last print time" to extended file information (see also [#1522](https://github.com/foosel/OctoPrint/pull/1522)) - * [#1422](https://github.com/foosel/OctoPrint/issues/1422) - Added option for post roll for timed timelapse to duplicate last frame instead of capturing new frames. That makes for a faster render at the cost of a still frame at the end of the rendered video. See also [#1553](https://github.com/foosel/OctoPrint/pull/1553). - * [#1551](https://github.com/foosel/OctoPrint/issues/1551) - Allow to define a custom bounding box for valid printer head movements in the printer profile, to make print dimension check more flexible. - * [#1583](https://github.com/foosel/OctoPrint/pull/1583) - Strip invalid `pip` arguments from `pip uninstall` commands, if provided by the user as additional pip arguments. - * [#1593](https://github.com/foosel/OctoPrint/issues/1593) - Automatically migrate old manual system commands for restarting OctoPrint and rebooting or shutting down the server to the new system wide configuration settings. Make a backup copy of the old `config.yaml` before doing so in case a manual rollback is required. - * New central configuration option for commands to restart OctoPrint and to restart and shut down the system OctoPrint is running on. This allows plugins (like the Software Update Plugin or the Plugin Manager) and core functionality to perform these common administrative tasks without the user needing to define everything redundantly. - * `pip` helper now adjusts `pip install` parameters corresponding to detected `pip` version: - * Removes `--process-dependency-links` when it's not needed - * Adds `--no-use-wheel` when it's needed - * Detects and reports on completely broken versions - * Better tracking of printer connection state for plugins and scripts: - * Introduced three new Events `Connecting`, `Disconnecting` and `PrinterStateChanged`. - * Introduced new GCODE script `beforePrinterDisconnected` which will get sent before a (controlled) disconnect from the printer. This can be used to send some final commands to the printer before the connection goes down, e.g. `M117 Bye from OctoPrint`. - * The communication layer will now wait for the send queue to be fully processed before disconnecting from the printer for good. This way it is ensured that the `beforePrinterDisconnected` script or any further GCODE injected into it will actually get sent. - * Additional baud rates to allow for connecting can now be specified along side additional serial ports via the settings dialog and the configuration file. - * Option to never send checksums (e.g. if the printer firmware doesn't support it), see [#949](https://github.com/foosel/OctoPrint/issues/949). - * Added secondary temperature polling interval to use when printer is not printing but a target temperature is set - this way the graph should be more responsive while monitoring a manual heatup. - * Test buttons for webcam snapshot & stream URL, ffmpeg path and some other settings (see also [#183](https://github.com/foosel/OctoPrint/issues/183)). - * Temperature graph automatically adjusts its Y axis range if necessary to accomodate the plotted data (see also [#632](https://github.com/foosel/OctoPrint/issues/632)). - * "Fan on" command now always sends `S255` parameter for better compatibility across firmwares. - * Warn users with a notification if a file is selected for printing that exceeds the current print volume (if the corresponding model data is available, see also [#1254](https://github.com/foosel/OctoPrint/pull/1254)) - * Added option to also display temperatures in Fahrenheit (see also [#1258] (https://github.com/foosel/OctoPrint/pull/1258)) - * Better error message when the ``config.yaml`` file is invalid during startup - * API now also allows issuing absolute jogging commands to the printer - * Printer profile editor dialog refactored to better structure fields and explain where they are used - * Option to detect z-hops during z-based timelapses and not trigger a snapshot (see also [1148](https://github.com/foosel/OctoPrint/pull/1148)) - * File rename, move and copy functionality exposed via API, not yet utilized in stock frontend but available in [file manager plugin](https://github.com/Salandora/OctoPrint-FileManager). - * Try to assure a sound SSL environment for the process at all times - * Improved caching: - * Main page and asset files now carry proper ``ETag`` and ``Last-Modified`` headers to allow for sensible browser-side caching - * API sets ``Etag`` and/or ``Last-Modified`` headers on responses to GET requests where possible and feasible to allow for sensible browser-side caching - * Renamed ``GcodeFilesViewModel`` to ``FilesViewModel`` - plugin authors should accordingly update their dependencies from ``gcodeFilesViewModel`` to ``filesViewModel``. Using the old name still works, but will log a warning and stop working with 1.4.x. - * Make sure ``volume.depth`` for circular beds is forced to ``volume.width`` in printer profiles - * Support for `M116` - * Support ``M114`` responses without whitespace between coordinates (protocol consistency - who needs it?). - * `M600` is now marked as a long running command by default. - * Don't focus files in the file list after deleting a file - made the list too jumpy. - * Cura plugin: "Test" button to check if path to cura engine is valid. - * Cura plugin: Wizard component for configuring the path to the CuraEngine binary and for importing the first slicing profile - * GCODE viewer: Added Layer Up/Down buttons (see also [#1306] (https://github.com/foosel/OctoPrint/pull/1306)) - * GCODE viewer: Allow cycling through layer via keyboard (up, down, pgup, pgdown) - * GCODE viewer: Allow changing size thresholds via settings menu (see also [#1308](https://github.com/foosel/OctoPrint/pull/1308)) - * GCODE viewer: Added support for GCODE arc commands (see also [#1382](https://github.com/foosel/OctoPrint/pull/1382)) - * Language packs: Limit upload dialog for language pack archives to .zip, .tar.gz, .tgz and .tar extensions. - * Plugin Manager: Adjusted to utilize new `pip` helper - * Plugin Manager: Show restart button on install/uninstall notification if restart command is configured and a restart is required - * Plugin Manager: Track managable vs not managable plugins - * Plugin Manager: Allow hiding plugins from Plugin Manager via ``config.yaml``. - * Plugin Manager: Limit upload dialog for plugin archives to .zip, .tar.gz, .tgz and .tar extensions. - * Plugin Manager: Allow closing of all notifications and close them automatically on detected server disconnect. No need to keep a "Restart needed" message around if a restart is in progress. - * Software Update plugin: More verbose output for logged in administrators. Will now log the update commands and their output similar to the Plugin Manager install and uninstall dialog. - * Software Update plugin: CLI for checking for and applying updates - * Software Update plugin: Wizard component for configuring OctoPrint's update mechanism - * Software Update plugin: "busy" spinner on check buttons while already checking for updates. - * Software Update plugin: Prevent update notification when wizard is open. - * Plugin Manager / Software Update plugin: The "There's a new version of pip" message during plugin installs and software updates is no longer displayed like an error. - * Plugin Manager / Software Update plugin: The "busy" dialog can no longer be closed accidentally. - * Timelapse: Better (& earlier) reporting to the user when something's up with the snapshot URL causing issues with capturing timelapse frames and hence making it impossible to render a timelapse movie on print completion. - * Virtual printer: Usage screen for the ``!!DEBUG`` commands on ``!!DEBUG``, ``!!DEBUG:help`` or ``!!DEBUG:?`` - * Updated frontend dependencies (possibly relevant for plugin authors): - * Bootstrap to 2.3.2 - * JQuery to 2.2.4 - * Lodash to 3.10.1 - * SockJS to 1.1.1 - * Better error resilience against errors in UI components. - * Various improvements in the GCODE interpreter which performs the GCODE analysis - * Various adjustments towards Python 3 compatibility (still a work in progress though, see also [#1411](https://github.com/foosel/OctoPrint/pull/1411), [#1412](https://github.com/foosel/OctoPrint/pull/1412), [#1413](https://github.com/foosel/OctoPrint/pull/1413), [#1414](https://github.com/foosel/OctoPrint/pull/1414)) - * Various code refactorings - * Various small UI improvements - * Various documentation improvements - -### Bug fixes - - * [#1047](https://github.com/foosel/OctoPrint/issues/1047) - Fixed 90 degree webcam rotation for iOS Safari. - * [#1148](https://github.com/foosel/OctoPrint/issues/1148) - Fixed retraction z hop setting for Z-triggered timelapses. Was not correctly propagated to the backend and hence not taking effect. - * [#1567](https://github.com/foosel/OctoPrint/issues/1567) - Invalidate ``/api/settings`` cache on change of the user's login state (include user roles into ETag calculation). - * [#1586](https://github.com/foosel/OctoPrint/issues/1586) - Fixed incompatibility of update script and command line helper with non-ASCII output from called commands. - * [#1588](https://github.com/foosel/OctoPrint/issues/1588) - Fixed feedback controls again. - * [#1599](https://github.com/foosel/OctoPrint/issues/1599) - Properly handle exceptions that arise within the update script during runtime. - * It's not possible anymore to select files that are not machinecode files (e.g. GCODE) for printing on the file API. - * Changes to a user's personal settings via the UI now propagate across sessions. - * Improved compatibility of webcam rotation CSS across newer browsers (see also [#1436](https://github.com/foosel/OctoPrint/pull/1436)) - * Fix for system menu not getting properly reloaded after entries changed - * Invalidate ``/api/settings`` cache on change of the currently enabled plugins (by including plugin names into ETag calculation) and/or on change of the current effective config. - * Fix for `/api/settings` not being properly invalidated for plugin settings that do not have a representation in `config.yaml` but are only added at runtime (and hence are not captured by `config.effective`). - * Invalidate ``/api/timelapse`` cache on change of the current timelapse configuration. - * Fixed an issue causing the version number not to be properly extracted from ``sdist`` tarballs generated under Windows. - * Get rid of double scroll bar in printer profile editor. - * Fixed tracking of current byte position in file being streamed from disk. Turns out that ``self._handle.tell`` lied to us thanks to line buffering. - * Fixed select & print not working anymore for SD files thanks to a timing issue. - * Fixed ``PrintFailed`` event payload (was still missing new folder relevant data). - * Fixed premature parse stop on ``M114`` and ``M115`` responses with ``ok``-prefix. - * Make sure `?l10n` request parameter gets also propagated to API calls as `X-Locale` header in case of locale sensitive API responses. - * Fix language mixture due to cached template configs including localized strings; cache per locale. - * Only insert divider in system menu after core commands if there are custom commands. - * Fix update of webcam stream URL not being applied due to caching. - * Fixed a rare race condition causing the new "The settings changed, reload?" popup to show up even when the settings change originated in the same client instance. - * Fixed a bunch of missing translations. - * Pinned Tornado version to 4.0.2. Former version requirement was able to pull in a beta version causing issues with websockets due to a bug in `permessage-deflate` handling. The Tornado requirement needs an update, but we'll leave it at 4.0.2 for 1.3.0 since we'll need to do some migration work for compatibility with anything newer. Potentially related to [#1523](https://github.com/foosel/OctoPrint/issues/1523). - * Fix a rare race condition in the command line helper and the update script that could cause the code to hang due to waiting on an event that would never be set. - * Fix issue with handling new settings substructures when they are compared to existing settings data in order to find the structural diff. - * Fix for the temperature graph not displaying the data history on site reload. - -### More information - - * [Commits](https://github.com/foosel/OctoPrint/compare/1.2.18...1.3.0) - * Release Candidates: - * [1.3.0rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.0rc1) - * [1.3.0rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.0rc2) - * [1.3.0rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.0rc3) - ---- - -For even older changes, please refer to [the Github releases page](https://github.com/foosel/OctoPrint/releases). +See [the releases on Github](https://github.com/OctoPrint/OctoPrint/releases) for detailed changelogs for all releases +and release candidates. diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 000000000..ba199875d --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1 @@ +OctoPrint's Code of Conduct can be found at [octoprint.org/conduct/](https://octoprint.org/conduct/). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 675b60b4d..ba81eaba8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -31,7 +31,7 @@ nothing but ticket management. - **[Read the FAQ](https://faq.octoprint.org)** - If you want to report a **bug**, [read "How to file a bug report" below](#how-to-file-a-bug-report) - and *[use the provided template](#what-should-i-include-in-a-ticket)*. + and *[use the provided form](https://github.com/OctoPrint/OctoPrint/issues/new?template=bug_report.yml)*. You do not need to do anything else with your ticket. - If you want to post a **feature request** or a **documentation request**, add `[Request]` to your issue's title (e.g. `[Request] Awesome new feature`). A question on how to run/change/setup @@ -39,7 +39,7 @@ nothing but ticket management. [community forum at community.octoprint.org](https://community.octoprint.org) for such support issues. - If you are a **developer** that wants to brainstorm a pull request or possible - changes to the plugin system, please get in touch on the + changes to the plugin system, please get in touch on the [community forum at community.octoprint.org](https://community.octoprint.org/c/development). - If you need **support**, have a **question** or some **other reason** that doesn't fit any of the above categories, the issue tracker is not the right place. @@ -48,15 +48,6 @@ nothing but ticket management. No matter what kind of ticket you create, never mix two or more "ticket reasons" into one ticket: One ticket per bug, request, brainstorming thread please. -> 👉 **Note** -> -> A bot is in place that monitors new tickets, automatically -> categorizes them and checks new bug reports for usage of the provided template. -> That bot will only bother you if you open a ticket that appears to be a bug (no -> `[Request]` in the title) without the complete template, and it -> will do that only to ensure that all information needed to solve the issue is -> available for the maintainers to directly start tackling that problem. - ## How to file a bug report If you encounter an issue with OctoPrint, you are welcome to @@ -71,12 +62,12 @@ following section *completely* and also follow the instructions in the 1. **Make sure you are at the right location**. This is the bug tracker of the official version of OctoPrint, which is the 3D print server and corresponding web interface itself. - + **OctoPrint doesn't manage your network connection or your webcam nor - can it fix your printer not getting detected as a serial interface** - - if you have any kinds of problems with that, get in touch on the + can it fix your printer not getting detected as a serial interface** - + if you have any kinds of problems with that, get in touch on the [community forum](https://community.octoprint.org). - + **This is not the bug tracker of OctoPi**, which is the preconfigured Raspberry Pi image including OctoPrint among other things - that one can be found [here](https://github.com/guysoft/OctoPi). If you have any kind of specific @@ -118,160 +109,28 @@ following section *completely* and also follow the instructions in the it is the same as your's, it actually behaves the same as your's. E.g. if someone gives steps to reproduce his bug that looks like your's, reproduce the bug like that if possible, and only add a "me too" if you actually can reproduce the same - issue. Also **provide all information** as [described below](#what-should-i-include-in-a-bug-report) + issue. Also **provide all information like logs, versions, different reproduction steps** and whatever was additionally requested over the course of the ticket even if you "only" add to an existing ticket. The more information available regarding a bug, the higher the chances of reproducing and solving it. But "me too" on an actually unrelated ticket makes it more difficult due to on top of having to figure out the original problem there's now also a [red herring](https://en.wikipedia.org/wiki/Red_herring) interfering - so please be very diligent here! - -If in doubt about any of the above - get in touch on the [community forum](https://community.octoprint.org) -instead of opening a ticket here. If you are actually running into a bug, we'll figure it out together + +If in doubt about any of the above - get in touch on the [community forums](https://community.octoprint.org) +instead of opening a ticket here. If you are actually running into a bug, we'll figure it out together there. - + ### What should I include in a bug report? First of all make sure your use **a descriptive title**. "It doesn't work" and similar unspecific complaints are NOT descriptive titles. -**Always use the following template, even if only adding a "me too" to an -existing ticket**: +Always fill out the [reporting form](https://github.com/OctoPrint/OctoPrint/issues/new?template=bug_report.yml) **completely** and include as much +information as possible. -``` - - -#### What were you doing? - - - -1. ... -2. ... -3. ... - - - -#### What did you expect to happen? - -#### What happened instead? - -#### Did the same happen when running OctoPrint in safe mode? - - - -#### Version of OctoPrint - - - -#### Operating System running OctoPrint - - - -#### Printer model & used firmware incl. version - - - -#### Browser and version of browser, operating system running browser - - - -#### Link to octoprint.log - - - -#### Link to contents of terminal tab or serial.log - - - -#### Link to contents of Javascript console in the browser - - - -#### Screenshot(s)/video(s) showing the problem: - - - -I have read the FAQ. -``` - -Copy-paste this template **completely** (or use the version that gets pre-filled -into the "new issue" form). Do not skip any lines or the bot *will* complain! Provide -all requested information or your ticket will be closed. +Provide the same kind and amount of information also when you are just adding on to an +existing ticket! ### Where can I find which version and branch I'm on? @@ -287,9 +146,10 @@ See [How to open the Javascript Console in different browsers](https://webmaster ## Setting up a development environment -See [the corresponding chapter in the documentation](http://docs.octoprint.org/en/master/development/index.html#setting-up-a-development-environment). -This also includes information on how to run the test suite and how to build -the documentation. +See [the corresponding chapter in the documentation](https://docs.octoprint.org/en/master/development/environment.html). +This also includes information on how to run the test suite and how to build +the documentation, the bundled virtual printer plugin and OctoPrint's versioning +and branching strategy. ## Pull requests @@ -297,11 +157,12 @@ the documentation. consider if it wouldn't be better suited for a plugin.** As a general rule of thumb, any feature that is only of interest to a small sub group should be moved into a plugin. If the current plugin system doesn't allow you to - implement your feature as a plugin, create a "Brainstorming" ticket to get + implement your feature as a plugin, please get in touch on the + [forums](https://community.octoprint.org/c/development) to get the discussion going on how best to solve *this* in OctoPrint's plugin system - maybe that's the actual PR you have been waiting for to contribute :) 2. If you plan to make **any large or otherwise disruptive changes to the - code or appearance, please get in touch on the + code or appearance, please get in touch on the [forums](https://community.octoprint.org/c/development)** first so that we can determine if it's a good time for your specific pull request. It might be that we're currently in the process of making @@ -310,19 +171,20 @@ the documentation. just cause unnecessary work and frustration for everyone or possibly get the PR rejected. 3. Create your pull request **from a custom branch** on your end (e.g. - `dev/myNewFeature`)[1]. + `improve/myNewFeature`)[1]. 4. Create your pull request **only against the `maintenance` or `devel` branch**: - * if it's a bug fix for a bug in the current stable version, an improvement of existing functionality or a - *small* new feature (e.g. a new hook, a new config flag, ...): `maintenance` branch - * otherwise: `devel` branch + * if it's a bug fix for a bug in the current stable version, an improvement of existing functionality or a + *small* backwards compatible new feature (e.g. a new hook, a new config flag, ...): `maintenance` branch + * if it's a bigger backwards compatible new feature: please [get in touch](https://community.octoprint.org/c/development) first to avoid + wasting work that doesn't match the current direction of the project or implement as a plugin. + * if it's any breaking backwards incompatible change: `devel` branch. In case of big changes, [get in touch](https://community.octoprint.org/c/development) first. 5. Create **one pull request per feature/bug fix**. 6. Make sure there are **only relevant changes** included in your PR. No changes to unrelated files, no additional files that don't belong (e.g. commits of your full virtual environment). Make sure your PR consists **ideally of only one commit** (use git's rebase and squash functionality). 7. Make sure you **follow the current coding style**. This means: - * Tabs instead of spaces in the Python files[2] - * Spaces instead of tabs in the JavaScript sources + * Spaces for indenting and alignment, indentation width 4. * English language (code, variables, comments, ...) * Comments where necessary: Tell *why* the code does something like it does it, structure your code @@ -333,29 +195,41 @@ the documentation. from experiments). 8. Ensure your changes **pass the existing unit tests**. PRs that break those cannot be accepted. You can run the unit tests locally (after - [initial development environment setup with "develop" dependencies](http://docs.octoprint.org/en/master/development/index.html#setting-up-a-development-environment)) + [initial development environment setup with "develop" dependencies](https://docs.octoprint.org/en/master/development/environment.html)) by running - + ``` - nosetests --with-doctest + pytest ``` - - in the OctoPrint checkout folder. A [travis build](https://travis-ci.org/foosel/OctoPrint) - is also setup so that if the tests should fail, your PR will be marked + + in the OctoPrint checkout folder. An [automatic build workflow](https://github.com/OctoPrint/OctoPrint/actions?query=workflow%3ABuild) + is also setup so that if the tests should fail, your PR will be marked accordingly. -9. **Test your changes thoroughly**. That also means testing with usage - scenarios you don't normally use, e.g. if you only use access control, test - without and vice versa. If you only test with your printer, test with the - virtual printer and vice versa. State in your pull request how you tested - your changes. Ideally **add unit tests** - OctoPrint severely lacks in that - department, but we are trying to change that, so any new code already covered - with a test suite helps a lot! -10. In your pull request's description, **state what your pull request does**, +9. Run the **pre-commit check suite** against your changes. You can run that (after + [initial development environment setup with "develop" dependencies](https://docs.octoprint.org/en/master/development/environment.html)) + by running + + ``` + pre-commit run --hook-stage manual --all-files + ``` + + in the OctoPrint checkout folder. If you install the pre-commit hooks via + `pre-commit install` (which you really should!) this will even be taken care of for you prior to committing. + + An [automatic build workflow](https://github.com/OctoPrint/OctoPrint/actions?query=workflow%3ABuild) + is in place that will run these checks - if they fail your PR will be marked accordingly. +10. **Test your changes thoroughly**. That also means testing with usage + scenarios you don't normally use. If you only test with your printer, test with the + virtual printer and vice versa. State in your pull request how you tested + your changes. Ideally **add unit tests** - OctoPrint severely lacks in that + department, but we are trying to change that, so any new code already covered + with a test suite helps a lot! +11. In your pull request's description, **state what your pull request does**, as in, what feature does it implement, what bug does it fix. The more thoroughly you explain your intent behind the PR here, the higher the chances it will get merged fast. There is a template provided below that can help you here. -11. Don't forget to **add yourself to the [AUTHORS](./AUTHORS.md) +12. Don't forget to **add yourself to the [AUTHORS](./AUTHORS.md) file** :) Template to use for Pull Request descriptions: @@ -374,81 +248,13 @@ Template to use for Pull Request descriptions: #### Further notes ``` +## How is OctoPrint versioned? + +See [the corresponding chapter in the documentation](https://docs.octoprint.org/en/master/development/versioning.html). + ## What do the branches mean? -There are three main branches in OctoPrint: - - * `master`: The master branch always contains the current stable release. It - is *only* updated on new releases. Will have a version number following - the scheme `..` (e.g. `1.2.9`) or - if it's absolutely necessary to - add a commit after release to this branch - `...post` - (e.g. `1.2.9.post1`). - * `maintenance`: Improvements and fixes of the current release that make up - the next release go here. More or less continuously updated. You can consider - this a preview of the next release version. It should be very stable at all - times. Anything you spot in here helps tremendously with getting a rock solid - next stable release, so if you want to help out development, running the - `maintenance` branch and reporting back anything you find is a very good way - to do that. Will usually have a version number following the scheme - `...dev` for an OctoPrint version of `..` - (e.g. `1.2.10.dev12`). - * `devel`: Ongoing development of new features that will go into the next bigger - release (MINOR version number increases) will happen on this branch. Usually - kept stable, sometimes stuff can break though or lose backwards compatibility - temporarily. Can be considered the "bleeding edge". All PRs should target - *this* branch. Important improvements and fixes from PRs here are backported to - `maintenance` as needed. Will usually have a version number following the - scheme `..0.dev` for a current OctoPrint version - of `..` (e.g. `1.3.0.dev123`). - * `rc/maintenance`: This branch is reserved for future releases that have graduated from - the `maintenance` branch and are now being pushed on the "Maintenance" - pre release channel for further testing. Version number follows the scheme - `..rc` (e.g. `1.2.9rc1`). - * `staging/maintenance`: Any preparation for potential follow-up RCs takes place here. - Version number follows the scheme `..rc.dev` (e.g. - `1.2.9rc1.dev3`) for a current Maintenance RC of `..rc`. - * `rc/devel`: This branch is reserved for future releases that have graduated from - the `devel` branch and are now being pushed on the "Devel" pre release channel - for further testing. Version number follows the scheme `..0rc` (e.g. `1.3.0rc1`) - for a current stable OctoPrint version of `..`. - * `staging/devel`: Any preparation for potential follow-up Devel RCs takes place - here. Version number follows the scheme `..0rc.dev` (e.g. - `1.3.0rc1.dev12`) for a current Devel RC of `..0rc`. - -Additionally, from time to time you might see other branches pop up in the repository. -Those usually have one of the following prefixes: - - * `fix/...`: Fixes under development that are to be merged into the `maintenance` - and `devel` branches. - * `improve/...`: Improvements under development that are to be merged into the - `maintenance` and `devel` branches. - * `dev/...` or `feature/...`: New functionality under development that is to be merged - into the `devel` branch. - -There is also the `gh-pages` branch, which holds OctoPrint's web page, and a few -older development branches that are slowly being migrated or deleted. - -## How OctoPrint is versioned - -OctoPrint follows the [semantic versioning scheme](http://semver.org/) of **MAJOR.MINOR.PATCH**. - -The **PATCH** version number is the one increasing most often due to OctoPrint's maintenance releases. -Releases that only change the patch number indicate that they contain bug fixes and small improvements -of existing functionality. Example: 1.2.8 to 1.2.9. - -The **MINOR** version number increases with releases that add a lot of new functionality and -large features. Example: 1.2.x to 1.3.0. - -Finally, the **MAJOR** version number increases if there are breaking API changes that concern any of the -documented interfaces (REST API, plugin interfaces, ...). So far this hasn't happened. Example: 1.x.y to 2.0.0. - -OctoPrint's version numbers are automatically generated using [versioneer](https://github.com/warner/python-versioneer) -and depend on the selected git branch, nearest git tag and commits. The generated version number -should always be [PEP440](https://www.python.org/dev/peps/pep-0440/) compatible. Unless a git tag -is used for version number determination, the version number will also contain the git hash within -the local version identifier to allow for an exact determination of the active code base -(e.g. `1.2.9.dev68+g46c7a9c`). Additionally, instances with active uncommitted changes will contain -`.dirty` in the local version identifier. +See [the corresponding chapter in the documentation](https://docs.octoprint.org/en/master/development/branches.html). ## History @@ -477,14 +283,13 @@ the local version identifier to allow for an exact determination of the active c * 2018-03-29: "Where to find version numbers" is now located on the FAQ * 2018-10-18: Allow PRs against `maintenance` branch for improvements and small new features, suggest getting in touch on the forum for larger changes + * 2020-08-10: Update versioning scheme and PR instructions + * 2020-09-23: Move branch & versioning into development docs + * 2020-10-07: Introduce `pre-commit` + * 2021-02-04: Issue forms! \o/ ## Footnotes * [1] - If you are wondering why, the problem is that anything that you add to your PR's branch will also become part of your PR, so if you create a PR from your version of `devel` chances are high you'll add changes to the PR that do not belong to the PR. - * [2] - Yes, we know that this goes against PEP-8. OctoPrint started out as - a fork of Cura and hence stuck to the coding style found therein. Changing - it now would make the history and especially `git blame` completely - unusable, so for now we'll have to deal with it (this decision might be - revisited in the future). diff --git a/README.md b/README.md index 0e4ac5f3a..62cd644d9 100644 --- a/README.md +++ b/README.md @@ -1,21 +1,29 @@ -# OctoPrint +

OctoPrint's logo

+

OctoPrint

-![GitHub release](https://img.shields.io/github/release/foosel/OctoPrint.svg?colorB=brightgreen) -[![Travis build status](https://img.shields.io/travis/foosel/OctoPrint.svg)](https://travis-ci.org/foosel/OctoPrint) -[![Discourse topics](https://img.shields.io/discourse/https/community.octoprint.org/users.svg)](https://community.octoprint.org) -[![IRC](https://img.shields.io/badge/chat-on%20irc-brightgreen.svg)](https://chat.octoprint.org) -[![Twitter Follow](https://img.shields.io/twitter/follow/OctoPrint3d.svg?style=social&label=Follow)](https://twitter.com/OctoPrint3d) - +

+ GitHub release + PyPI + Build status + Community Forum + Discord + Twitter Follow + Contributor Covenant + Code style: black + Code style: prettier + Imports: isort + pre-commit +

OctoPrint provides a snappy web interface for controlling consumer 3D printers. It is Free Software and released under the [GNU Affero General Public License V3](http://www.gnu.org/licenses/agpl.html). Its website can be found at [octoprint.org](https://octoprint.org/?utm_source=github&utm_medium=readme). -The community forum is available at [community.octoprint.org](https://community.octoprint.org/?utm_source=github&utm_medium=readme). +The community forum is available at [community.octoprint.org](https://community.octoprint.org/?utm_source=github&utm_medium=readme). It also serves as central knowledge base. -The official IRC channel is [#octoprint on freenode](https://chat.octoprint.org). Its logs can be found [here](https://freenode.logbot.info/octoprint). +An invite to the Discord server can be found at [discord.octoprint.org](https://discord.octoprint.org). The FAQ can be accessed by following [faq.octoprint.org](https://faq.octoprint.org/?utm_source=github&utm_medium=readme). @@ -26,21 +34,21 @@ The official plugin repository can be reached at [plugins.octoprint.org](https:/ **OctoPrint's development wouldn't be possible without the [financial support by its community](https://octoprint.org/support-octoprint/?utm_source=github&utm_medium=readme). If you enjoy OctoPrint, please consider becoming a regular supporter!** -![Screenshot](http://i.imgur.com/dF3noFp.png) +![Screenshot](https://octoprint.org/assets/img/screenshot-readme.png) You are currently looking at the source code repository of OctoPrint. If you already installed it (e.g. by using the Raspberry Pi targeted distribution [OctoPi](https://github.com/guysoft/OctoPi)) and only -want to find out how to use it, [the documentation](http://docs.octoprint.org/) and [the public wiki](https://github.com/foosel/OctoPrint/wiki) -might be of more interest for you. You might also want to subscribe to join +want to find out how to use it, [the documentation](http://docs.octoprint.org/) might be of more interest for you. You might also want to subscribe to join [the community forum at community.octoprint.org](https://community.octoprint.org) where there are other active users who might be able to help you with any questions you might have. ## Contributing Contributions of all kinds are welcome, not only in the form of code but also with regards to the -[official documentation](http://docs.octoprint.org/) or [the public wiki](https://github.com/foosel/OctoPrint/wiki), debugging help -in the [bug tracker](https://github.com/foosel/OctoPrint/issues), support of other users on -[the community forum at community.octoprint.org](https://community.octoprint.org) +[official documentation](http://docs.octoprint.org/), debugging help +in the [bug tracker](https://github.com/OctoPrint/OctoPrint/issues), support of other users on +[the community forum at community.octoprint.org](https://community.octoprint.org) or +[the official discord at discord.octoprint.org](https://discord.octoprint.org) and also [financially](https://octoprint.org/support-octoprint/?utm_source=github&utm_medium=readme). If you think something is bad about OctoPrint or its documentation the way it is, please help @@ -48,26 +56,25 @@ in any way to make it better instead of just complaining about it -- this is an after all :) For information about how to go about submitting bug reports or pull requests, please see the project's -[Contribution Guidelines](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md). +[Contribution Guidelines](https://github.com/OctoPrint/OctoPrint/blob/master/CONTRIBUTING.md). ## Installation Installation instructions for installing from source for different operating -systems can be found [on the wiki](https://github.com/foosel/OctoPrint/wiki#assorted-guides). +systems can be found [on the forum](https://community.octoprint.org/tags/c/support/guides/15/setup). -If you want to run OctoPrint on a Raspberry Pi, you might want to take a look at [OctoPi](https://github.com/guysoft/OctoPi) +If you want to run OctoPrint on a Raspberry Pi, you really should take a look at [OctoPi](https://github.com/guysoft/OctoPi) which is a custom SD card image that includes OctoPrint plus dependencies. The generic steps that should basically be done regardless of operating system and runtime environment are the following (as *regular user*, please keep your hands *off* of the `sudo` command here!) - this assumes -you already have Python 2.7, 3.6 or 3.7, pip and virtualenv set up on your system: +you already have Python 3.6, 3.7 or 3.8, pip and virtualenv and their dependencies set up on your system: -1. Checkout OctoPrint: `git clone https://github.com/foosel/OctoPrint.git` -2. Change into the OctoPrint folder: `cd OctoPrint` -3. Create a user-owned virtual environment therein: `virtualenv venv` if your system default python version is - python 2.7, otherwise you need to specify the version explicitly, e.g. `virtualenv --python=python2.7 venv`. -4. Install OctoPrint *into that virtual environment*: `./venv/bin/pip install .` +1. Create a user-owned virtual environment therein: `virtualenv venv`. If you want to specify a specific python + to use instead of whatever version your system defaults to, you can also explicitly require that via the `--python` + parameter, e.g. `virtualenv --python=python3 venv`. +2. Install OctoPrint *into that virtual environment*: `./venv/bin/pip install OctoPrint` You may then start the OctoPrint server via `/path/to/OctoPrint/venv/bin/octoprint`, see [Usage](#usage) for details. @@ -78,19 +85,15 @@ access control as necessary. ## Dependencies OctoPrint depends on a few python modules to do its job. Those are automatically installed when installing -OctoPrint via `pip`: +OctoPrint via `pip`. - pip install . - -You should do this every time after pulling from the repository, since the dependencies may have changed. - -OctoPrint currently supports Python 2.7, 3.6 and 3.7. +OctoPrint currently supports Python 3.6, 3.7 and 3.8. ## Usage Running the pip install via - pip install . + pip install OctoPrint installs the `octoprint` script in your Python installation's scripts folder (which, depending on whether you installed OctoPrint globally or into a virtual env, will be in your `PATH` or not). The diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 000000000..79b94cdd9 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,11 @@ +# Security Policy + +## Supported Versions + +Always update to the latest version of OctoPrint to keep up with security patches. + +## Reporting a Vulnerability + +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 b80d61f31..46d0e9a1d 100644 --- a/SUPPORTERS.md +++ b/SUPPORTERS.md @@ -1,59 +1,74 @@ -# Supporters +# Supporters Development of this version of OctoPrint wouldn't have been possible without -[the financial support by the community](https://octoprint.org/support-octoprint/) - +[the financial support by the community](https://support.octoprint.org) - thanks to everyone who contributed! -## Patreon Patrons +## Patrons & Sponsors - * Andre Bubel + * 3DPrinterOS * Andrew Moorby - * ANTONIO AUGUSTO DE LIMA PONTES * Arnljot Arntsen + * Ash King + * BigTreeTech * Boris Hussein * Brad Jackson + * BRANDON ROBERTSON + * BuildBee * Christian Petropolis * Christian Wolf - * COLLE+McVOY + * Creality3D * D Brian Kimmel * DeltaMaker 3D Printers - * Dorian Gray - * E3D BigBox + * Dennis Breining + * Diana C Rodriguez * Eric Betts * Ernesto Martinez * Franziska Kunsmann * George Robles + * Greg Holloway + * Hog Duske + * Hopewell Medical Acupuncture Center * jean-claude migneault - * Jeff Renfer * Jefferson Hunt - * Jeremiah Avery + * Jeremy Cole + * Joe Pasqua * Joshua Wills * Justin Kaufman * Kaile Riser * Kale Stedman * Kazuhiro Ogura + * Kelly C McNiece + * Kenneth Jiang + * Kurt Wubbels + * Kyle Menigoz * LA 3D Printer Repair - * LulzBot® + * Lee Dohm + * Loyal Moses * Makespace Madrid * Mark Walker * Michael Aumock + * Michael Begala * Miles Flavel * Mosaic Manufacturing - * OMER MEHMET SUTAS + * Neil R. Goldberg * Patrick Glyré - * Patrick McGinnis + * Pete Barnwell * Prof Yuh Wen Chen + * Raise3D * Randy C. Will * Ranjib Dey + * Richard McGuire + * Richard Michaud + * Richard Stocks + * Rigid3D * Robert Gusek - * Samer Najia - * Shawn Lewis - * Simon Hallam + * Ronald Griehsler + * Sacha Telgenhof + * Sebastien Andrivet * Stefan Krister + * Steve Thompson * Sven Mueller - * TEVO 3D Printers - * Trent Shumay * Ulrich Kempken - * Vladislav Kuzemchik -and 1587 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)! +and 2225 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 5769b9c6d..9d5c9dbdb 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) @@ -26,10 +27,12 @@ * [lodash](https://lodash.com): MIT * [Loglevel](https://github.com/pimterry/loglevel): MIT * [Markdown-it](https://markdown-it.github.io/): MIT + * [md5.js](https://blueimp.github.io/JavaScript-MD5/): MIT * [Modernizr](http://modernizr.com): MIT * [Moment.js](http://momentjs.com/): MIT * [PNotify](http://sciactive.com/pnotify/): GPL, LGPL, MPL (triple licensed) * [pusher.color.js](http://cache.preserve.io/5g18q0pw/index.html) (original link dead): MIT + * [ResizeSensor.js](https://github.com/procurios/ResizeSensor): MIT * [SockJS](https://github.com/sockjs/sockjs-client): MIT * [sprintf-js](http://alexei.ro/): BSD @@ -41,12 +44,14 @@ * [Click](http://click.pocoo.org/): BSD * [emoji](https://github.com/carpedm20/emoji/): BSD * [feedparser](https://github.com/kurtmckee/feedparser): BSD + * [filetype](https://h2non.github.io/filetype.py/): MIT * [Flask](http://flask.pocoo.org/): BSD * [Flask-Assets](http://github.com/miracle2k/flask-assets): BSD * [Flask-Babel](http://github.com/mitsuhiko/flask-babel): BSD * [Flask-Login](https://github.com/maxcountryman/flask-login): MIT * [Flask-Markdown](http://github.com/dcolish/flask-markdown): BSD * [Flask-Principal](http://packages.python.org/Flask-Principal/): MIT + * [frozendict](https://github.com/slezica/python-frozendict): MIT * [future](https://python-future.org/): MIT * [futures](https://github.com/agronholm/pythonfutures): Python * [monotonic](https://github.com/atdt/monotonic): Apache License 2.0 @@ -60,19 +65,25 @@ * [requests](http://python-requests.org/): Apache License 2.0 * [rsa](http://stuvel.eu/rsa): Apache License 2.0 * [sarge](http://sarge.readthedocs.org/): BSD + * [sentry-sdk](https://github.com/getsentry/sentry-python): BSD * [scandir](https://github.com/benhoyt/scandir): BSD * [semantic_version](https://github.com/rbarrois/python-semanticversion): BSD * [SockJS-Tornado](http://github.com/mrjoes/sockjs-tornado/): MIT * [Tornado](http://www.tornadoweb.org/): Apache License 2.0 + * [typing](https://pypi.org/project/typing/): Python * [watchdog](http://github.com/gorakhargosh/watchdog): Apache License 2.0 * [websocket-client](https://github.com/liris/websocket-client): LGPLv3 * [wrapt](http://wrapt.readthedocs.org/): BSD ## Development (testing, documentation generation, etc) + * [cookiecutter](https://github.com/cookiecutter/cookiecutter): BSD * [ddt](https://github.com/txels/ddt): MIT + * [flake8](https://gitlab.com/pycqa/flake8): MIT * [mock](https://github.com/testing-cabal/mock): BSD - * [nose](http://pythonhosted.org/nose/): LGPL + * [pyinstrument](https://github.com/joerick/pyinstrument): BSD + * [pytest](https://docs.pytest.org/en/latest/): MIT + * [pytest-doctest-custom](http://github.com/danilobellini/pytest-doctest-custom): MIT * [Sphinx](http://sphinx-doc.org/): BSD * [sphinxcontrib-httpdomain](https://bitbucket.org/birkenfeld/sphinx-contrib/src/default/httpdomain/): BSD * [sphinxcontrib-mermad](https://github.com/mgaitan/sphinxcontrib-mermaid): BSD diff --git a/babel.cfg b/babel.cfg index 014eb25de..9117d82ce 100644 --- a/babel.cfg +++ b/babel.cfg @@ -1,8 +1,15 @@ [python: src/octoprint/**.py] + [jinja2: src/octoprint/templates/**.jinja2] +silent=false +extensions=jinja2.ext.autoescape, jinja2.ext.with_, webassets.ext.jinja2.AssetsExtension, jinja2.ext.do, octoprint.util.jinja.trycatch + [jinja2: src/octoprint/plugins/**.jinja2] -extensions=jinja2.ext.autoescape, jinja2.ext.with_, webassets.ext.jinja2.AssetsExtension +silent=false +extensions=jinja2.ext.autoescape, jinja2.ext.with_, webassets.ext.jinja2.AssetsExtension, jinja2.ext.do, octoprint.util.jinja.trycatch [javascript: src/octoprint/static/js/app/**.js] +extract_messages = gettext, ngettext + [javascript: src/octoprint/plugins/**.js] extract_messages = gettext, ngettext 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/Makefile b/docs/Makefile deleted file mode 100644 index b7ebd1e78..000000000 --- a/docs/Makefile +++ /dev/null @@ -1,177 +0,0 @@ -# Makefile for Sphinx documentation -# - -# You can set these variables from the command line. -SPHINXOPTS = -SPHINXBUILD = sphinx-build -PAPER = -BUILDDIR = _build - -# User-friendly check for sphinx-build -ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) -$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) -endif - -# Internal variables. -PAPEROPT_a4 = -D latex_paper_size=a4 -PAPEROPT_letter = -D latex_paper_size=letter -ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . -# the i18n builder cannot share the environment and doctrees with the others -I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . - -.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext - -help: - @echo "Please use \`make ' where is one of" - @echo " html to make standalone HTML files" - @echo " dirhtml to make HTML files named index.html in directories" - @echo " singlehtml to make a single large HTML file" - @echo " pickle to make pickle files" - @echo " json to make JSON files" - @echo " htmlhelp to make HTML files and a HTML help project" - @echo " qthelp to make HTML files and a qthelp project" - @echo " devhelp to make HTML files and a Devhelp project" - @echo " epub to make an epub" - @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" - @echo " latexpdf to make LaTeX files and run them through pdflatex" - @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" - @echo " text to make text files" - @echo " man to make manual pages" - @echo " texinfo to make Texinfo files" - @echo " info to make Texinfo files and run them through makeinfo" - @echo " gettext to make PO message catalogs" - @echo " changes to make an overview of all changed/added/deprecated items" - @echo " xml to make Docutils-native XML files" - @echo " pseudoxml to make pseudoxml-XML files for display purposes" - @echo " linkcheck to check all external links for integrity" - @echo " doctest to run all doctests embedded in the documentation (if enabled)" - -clean: - rm -rf $(BUILDDIR)/* - -html: - $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." - -dirhtml: - $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." - -singlehtml: - $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml - @echo - @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." - -pickle: - $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle - @echo - @echo "Build finished; now you can process the pickle files." - -json: - $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json - @echo - @echo "Build finished; now you can process the JSON files." - -htmlhelp: - $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp - @echo - @echo "Build finished; now you can run HTML Help Workshop with the" \ - ".hhp project file in $(BUILDDIR)/htmlhelp." - -qthelp: - $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp - @echo - @echo "Build finished; now you can run "qcollectiongenerator" with the" \ - ".qhcp project file in $(BUILDDIR)/qthelp, like this:" - @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/OctoPrint.qhcp" - @echo "To view the help file:" - @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/OctoPrint.qhc" - -devhelp: - $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp - @echo - @echo "Build finished." - @echo "To view the help file:" - @echo "# mkdir -p $$HOME/.local/share/devhelp/OctoPrint" - @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/OctoPrint" - @echo "# devhelp" - -epub: - $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub - @echo - @echo "Build finished. The epub file is in $(BUILDDIR)/epub." - -latex: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo - @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." - @echo "Run \`make' in that directory to run these through (pdf)latex" \ - "(use \`make latexpdf' here to do that automatically)." - -latexpdf: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo "Running LaTeX files through pdflatex..." - $(MAKE) -C $(BUILDDIR)/latex all-pdf - @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." - -latexpdfja: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo "Running LaTeX files through platex and dvipdfmx..." - $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja - @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." - -text: - $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text - @echo - @echo "Build finished. The text files are in $(BUILDDIR)/text." - -man: - $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man - @echo - @echo "Build finished. The manual pages are in $(BUILDDIR)/man." - -texinfo: - $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo - @echo - @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." - @echo "Run \`make' in that directory to run these through makeinfo" \ - "(use \`make info' here to do that automatically)." - -info: - $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo - @echo "Running Texinfo files through makeinfo..." - make -C $(BUILDDIR)/texinfo info - @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." - -gettext: - $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale - @echo - @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." - -changes: - $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes - @echo - @echo "The overview file is in $(BUILDDIR)/changes." - -linkcheck: - $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck - @echo - @echo "Link check complete; look for any errors in the above output " \ - "or in $(BUILDDIR)/linkcheck/output.txt." - -doctest: - $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest - @echo "Testing of doctests in the sources finished, look at the " \ - "results in $(BUILDDIR)/doctest/output.txt." - -xml: - $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml - @echo - @echo "Build finished. The XML files are in $(BUILDDIR)/xml." - -pseudoxml: - $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml - @echo - @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." diff --git a/docs/api/access.rst b/docs/api/access.rst new file mode 100644 index 000000000..061d9fb00 --- /dev/null +++ b/docs/api/access.rst @@ -0,0 +1,529 @@ +.. _sec-api-access: + +************** +Access control +************** + +.. contents:: + +.. _sec-api-access-permissions: + +Permissions +=========== + +.. _sec-api-access-permissions-list: + +List all permissions +-------------------- + +.. http:get:: /api/access/permissions + + Retrieves all permissions available in the system. + + Will return a :http:statuscode:`200` with a :ref:`permission list ` + as body. + + :status 200: No error + +.. _sec-api-access-groups: + +Groups +====== + +.. _sec-api-access-groups-list: + +Get group list +-------------- + +.. http:get:: /api/access/groups + + Retrieves all groups registered in the system. + + Will return a :http:statuscode:`200` with a :ref:`group list ` + as body. + + Requires the ``SETTINGS`` permission. + + :status 200: No error + +.. _sec-api-access-groups-add: + +Add a new group +--------------- + +.. http:post:: /api/access/groups + + Adds a new group to the system. + + Expects a :ref:`group registration request ` as request body. + + Will return a :ref:`group list response ` on success. + + Requires the ``SETTINGS`` permission. + + :json key: The group's identifier + :json name: The user's name + :json description: A human readable description of the group + :json permissions: The permissions to assign to the group + :json subgroups: Subgroups assigned to the group + :json default: Whether the group should be assigned to new users by default or not + :status 200: No error + :status 400: If any of the mandatory fields is missing or the request is otherwise + invalid + :status 409: A group with the provided key does already exist + +.. _sec-api-access-groups-retrieve: + +Retrieve a group +---------------- + +.. http:get:: /api/access/groups/(string:key) + + Retrieves an individual group record. + + Will return a :http:statuscode:`200` with a :ref:`group record ` + as body. + + Requires the ``SETTINGS`` permission. + + :status 200: No error + +.. _sec-api-access-groups-modify: + +Update a group +-------------- + +.. http:put:: /api/access/groups/(string:key) + + Updates an existing group. + + Expects a :ref:`group update request ` as request body. + + Will return a :ref:`group list response ` on success. + + Requires the ``SETTINGS`` permission. + + :json description: A human readable description of the group + :json permissions: The permissions to assign to the group + :json subgroups: Subgroups assigned to the group + :json default: Whether the group should be assigned to new users by default or not + :status 200: No error + :status 400: If any of the mandatory fields is missing or the request is otherwise + invalid + +.. _sec-api-access-groups-delete: + +Delete a group +-------------- + +.. http:delete:: /api/access/groups/(string:key) + + Deletes a group. + + Will return a :ref:`group list response ` on success. + + Requires the ``SETTINGS`` permission. + + :status 200: No error + +.. _sec-api-access-users: + +Users +===== + +.. _sec-api-access-users-list: + +Retrieve a list of users +======================== + +.. http:get:: /api/access/users + + Retrieves a list of all registered users in OctoPrint. + + Will return a :http:statuscode:`200` with a :ref:`user list response ` + as body. + + Requires the ``SETTINGS`` permission. + + :status 200: No error + +.. _sec-api-access-users-retrieve: + +Retrieve a user +--------------- + +.. http:get:: /api/access/users/(string:username) + + Retrieves information about a user. + + Will return a :http:statuscode:`200` with a :ref:`user record ` + as body. + + Requires either the ``SETTINGS`` permission or to be logged in as the user. + + :param username: Name of the user which to retrieve + :status 200: No error + :status 404: Unknown user + +.. _sec-api-access-users-add: + +Add a new user +-------------- + +.. http:post:: /api/access/users + + Adds a user to OctoPrint. + + Expects a :ref:`user registration request ` + as request body. + + Returns a list of registered users on success, see :ref:`Retrieve a list of users `. + + Requires the ``SETTINGS`` permission. + + :json name: The user's name + :json password: The user's password + :json active: Whether to activate the account (true) or not (false) + :json admin: Whether to give the account admin rights (true) or not (false) + :status 200: No error + :status 400: If any of the mandatory fields is missing or the request is otherwise + invalid + :status 409: A user with the provided name does already exist + +.. _sec-api-access-users-modify: + +Update a user +------------- + +.. http:put:: /api/access/users/(string:username) + + Updates a user record. + + Expects a :ref:`user update request ` + as request body. + + Returns a list of registered users on success, see :ref:`Retrieve a list of users `. + + Requires the ``SETTINGS`` permission. + + :param username: Name of the user to update + :json admin: Whether to mark the user as admin (true) or not (false), can be left out (no change) + :json active: Whether to mark the account as activated (true) or deactivated (false), can be left out (no change) + :status 200: No error + :status 404: Unknown user + +.. _sec-api-access-users-delete: + +Delete a user +------------- + +.. http:delete:: /api/access/users/(string:username) + + Delete a user record. + + Returns a list of registered users on success, see :ref:`Retrieve a list of users `. + + Requires the ``SETTINGS`` permission. + + :param username: Name of the user to delete + :status 200: No error + :status 404: Unknown user + +.. _sec-api-access-users-password: + +Change a user's password +------------------------ + +.. http:put:: /api/access/users/(string:username)/password + + Changes the password of a user. + + Expects a JSON object with a single property ``password`` as request body. + + Requires the ``SETTINGS`` permission or to be logged in as the user. + + :param username: Name of the user to change the password for + :json password: The new password to set + :status 200: No error + :status 400: If the request doesn't contain a ``password`` property or the request + is otherwise invalid + :status 403: No admin rights and not logged in as the user + :status 404: The user is unknown + +.. _sec-api-access-users-settings-get: + +Get a user's settings +--------------------- + +.. http:get:: /api/access/users/(string:username)/settings + + Retrieves a user's settings. + + Will return a :http:statuscode:`200` with a JSON object representing the user's + personal settings (if any) as body. + + Requires the ``SETTINGS`` permission or to be logged in as the user. + + :param username: Name of the user to retrieve the settings for + :status 200: No error + :status 403: No admin rights and not logged in as the user + :status 404: The user is unknown + +.. _sec-api-access-users-settings-set: + +Update a user's settings +------------------------ + +.. http:patch:: /api/access/users/(string:username)/settings + + Updates a user's settings. + + Expects a new settings JSON object to merge with the current settings as + request body. + + Requires the ``SETTINGS`` permission or to be logged in as the user. + + :param username: Name of the user to retrieve the settings for + :status 204: No error + :status 403: No admin rights and not logged in as the user + :status 404: The user is unknown + +.. _sec-api-access-users-apikey-generate: + +Regenerate a user's api key +--------------------------- + +.. http:post:: /api/access/users/(string:username)/apikey + + Generates a new API key for the user. + + Does not expect a body. Will return the generated API key as ``apikey`` + property in the JSON object contained in the response body. + + Requires the ``SETTINGS`` permission or to be logged in as the user. + + :param username: Name of the user to retrieve the settings for + :status 200: No error + :status 403: No admin rights and not logged in as the user + :status 404: The user is unknown + +.. _sec-api-access-users-apikey-delete: + +Delete a user's api key +----------------------- + +.. http:delete:: /api/access/users/(string:username)/apikey + + Deletes a user's personal API key. + + Requires the ``SETTINGS`` permission or to be logged in as the user. + + :param username: Name of the user to retrieve the settings for + :status 204: No error + :status 403: No admin rights and not logged in as the user + :status 404: The user is unknown + +.. _sec-api-access-datamodel: + +Data model +========== + +.. _sec-api-access-datamodel-permissions: + +Permissions +----------- + +.. _sec-api-access-datamodel-permissions-list: + +Permission list response +~~~~~~~~~~~~~~~~~~~~~~~~ + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``permissions`` + - 0..n + - List of :ref:`permission records ` + - The list of permissions + + +.. _sec-api-access-datamodel-groups: + +Groups +------ + +.. _sec-api-access-datamodel-groups-list: + +Group list response +~~~~~~~~~~~~~~~~~~~ + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``groups`` + - 0..n + - List of :ref:`group records ` + - The list of groups + +.. _sec-api-access-datamodel-groups-addgrouprequest: + +Group registration request +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``key`` + - 1 + - string + - The group's identifier + * - ``name`` + - 1 + - string + - The group's name + * - ``description`` + - 0..1 + - string + - The group's description. Set to empty if not provided. + * - ``permissions`` + - 1..n + - List of string + - A list of identifier's of permissions to assign to the group + * - ``subgroups`` + - 0..n + - List of string + - A list of identifier's of groups to assign to the group as subgroups + * - ``default`` + - 0..1 + - boolean + - Whether to assign the group to new users by default (true) or not (false, default value) + +.. _sec-api-access-datamodel-groups-updategrouprequest: + +Group update request +~~~~~~~~~~~~~~~~~~~~ + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``description`` + - 0..1 + - string + - The group's description. Set to empty if not provided. + * - ``permissions`` + - 1..n + - List of string + - A list of identifier's of permissions to assign to the group + * - ``subgroups`` + - 0..n + - List of string + - A list of identifier's of groups to assign to the group as subgroups + * - ``default`` + - 0..1 + - boolean + - Whether to assign the group to new users by default (true) or not (false, default value) + + +.. _sec-api-access-datamodel-users: + +Users +----- + +.. _sec-api-access-datamodel-users-userlistresponse: + +User list response +~~~~~~~~~~~~~~~~~~ + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``users`` + - 0..n + - List of :ref:`user records ` + - The list of users + +.. _sec-api-access-datamodel-users-adduserrequest: + +User registration request +~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``name`` + - 1 + - string + - The user's name + * - ``password`` + - 1 + - string + - The user's password + * - ``active`` + - 1 + - bool + - Whether to activate the account (true) or not (false) + * - ``groups`` + - 0..n + - List of string + - A list of identifiers of groups to assign to the user + * - ``permissions`` + - 0..n + - List of string + - A list of identifiers of permissions to assign to the user + +.. _sec-api-access-datamodel-users-updateuserrequest: + +User update request +~~~~~~~~~~~~~~~~~~~ + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``active`` + - 0..1 + - bool + - If present will set the user's active flag to the provided value. True for + activating the account, false for deactivating it. + * - ``groups`` + - 0..n + - List of string + - A list of identifiers of groups to assign to the user + * - ``permissions`` + - 0..n + - List of string + - A list of identifiers of permissions to assign to the user diff --git a/docs/api/connection.rst b/docs/api/connection.rst index 2a0037b9a..97655db9f 100644 --- a/docs/api/connection.rst +++ b/docs/api/connection.rst @@ -16,6 +16,8 @@ Get connection settings Retrieve the current connection settings, including information regarding the available baudrates and serial ports and the current connection state. + Requires the ``STATUS`` permission. + **Example** .. sourcecode:: http @@ -81,7 +83,7 @@ Issue a connection command for the lost acknowledgment should always be properly investigated and removed instead of depending on this "symptom solver". - Requires user rights. + Requires the ``CONNECTION`` permission. **Example Connect Request** diff --git a/docs/api/datamodel.rst b/docs/api/datamodel.rst index 2af4f727f..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: @@ -480,3 +505,173 @@ References - URL - The model from which this file was generated (e.g. an STL, currently not used). Never present for folders. + +.. _sec-api-datamodel-access: + +Access control +============== + +.. _sec-api-datamodel-access-users: + +User record +----------- + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``name`` + - 1 + - string + - The user's name + * - ``active`` + - 1 + - bool + - Whether the user's account is active (true) or not (false) + * - ``user`` + - 1 + - bool + - Whether the user has user rights. Should always be true. Deprecated as of 1.4.0, use the ``users`` group instead. + * - ``admin`` + - 1 + - bool + - Whether the user has admin rights (true) or not (false). Deprecated as of 1.4.0, use the ``admins`` group instead. + * - ``apikey`` + - 0..1 + - string + - The user's personal API key + * - ``settings`` + - 1 + - object + - The user's personal settings, might be an empty object. + * - ``groups`` + - 1..n + - List of string + - Groups assigned to the user + * - ``needs`` + - 1 + - :ref:`Needs object ` + - Effective needs of the user + * - ``permissions`` + - 0..n + - List of :ref:`Permissions ` + - The list of permissions assigned to the user (note: this does not include implicit permissions inherit from groups). + +.. _sec-api-datamodel-access-permissions: + +Permission record +----------------- + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``key`` + - 1 + - string + - The permission's identifier + * - ``name`` + - 1 + - string + - The permission's name + * - ``dangerous`` + - 1 + - boolean + - Whether the permission should be considered dangerous due to a high reponsibility (true) or not (false). + * - ``default_groups`` + - 1 + - List of string + - List of group identifiers for which this permission is enabled by default + * - ``description`` + - 1 + - string + - Human readable description of the permission + * - ``needs`` + - 1 + - :ref:`Needs object ` + - Needs assigned to the permission + +.. _sec-api-datamodel-access-groups: + +Group record +------------ + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``key`` + - 1 + - string + - The group's identifier + * - ``name`` + - 1 + - string + - The group's name + * - ``description`` + - 1 + - string + - A human readable description of the group + * - ``permissions`` + - 0..n + - List of :ref:`Permissions ` + - The list of permissions assigned to the group (note: this does not include implicit permissions inherited from + subgroups). + * - ``subgroups`` + - 0..n + - List of :ref:`Groups ` + - Subgroups assigned to the group + * - ``needs`` + - 1 + - :ref:`Needs object ` + - Effective needs of the group + * - ``default`` + - 1 + - boolean + - Whether this is a default group (true) or not (false) + * - ``removable`` + - 1 + - boolean + - Whether this group can be removed (true) or not (false) + * - ``changeable`` + - 1 + - boolean + - Whether this group can be modified (true) or not (false) + * - ``toggleable`` + - 1 + - boolean + - Whether this group can be assigned to users or other groups (true) or not (false) + +.. _sec-api-datamodel-access-needs: + +Needs +----- + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``role`` + - 0..1 + - List of string + - List of ``role`` needs + * - ``group`` + - 0..1 + - List of string + - List of ``group`` needs diff --git a/docs/api/files.rst b/docs/api/files.rst index 23583d59c..d295ee2b9 100644 --- a/docs/api/files.rst +++ b/docs/api/files.rst @@ -21,6 +21,8 @@ Retrieve all files Returns a :ref:`Retrieve response `. + Requires the ``FILES_LIST`` permission. + **Example 1**: Fetch only the files and folders from the root folder. @@ -250,6 +252,8 @@ Retrieve files from specific location Returns a :ref:`Retrieve response `. + Requires the ``FILES_LIST`` permission. + **Example**: .. sourcecode:: http @@ -315,7 +319,8 @@ Upload file or create folder Upload a file to the selected ``location`` or create a new empty folder on it. Other than most of the other requests on OctoPrint's API which are expected as JSON, this request is expected as - ``Content-Type: multipart/form-data`` due to the included file upload. + ``Content-Type: multipart/form-data`` due to the included file upload. A ``Content-Length`` header specifying + the full length of the request body is required as well. To upload a file, the request body must at least contain the ``file`` form field with the contents and file name of the file to upload. @@ -327,7 +332,7 @@ Upload file or create folder Returns a :http:statuscode:`201` response with a ``Location`` header set to the management URL of the uploaded file and an :ref:`Upload Response ` as the body upon successful completion. - Requires user rights. + Requires the ``FILES_UPLOAD`` permission. **Example for uploading a file** @@ -337,6 +342,7 @@ Upload file or create folder Host: example.com X-Api-Key: abcdef... Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryDeC2E3iWbTv1PwMC + Content-Length: 430 ------WebKitFormBoundaryDeC2E3iWbTv1PwMC Content-Disposition: form-data; name="file"; filename="whistle_v2.gcode" @@ -346,7 +352,7 @@ Upload file or create folder T0 G21 G90 - ... + ------WebKitFormBoundaryDeC2E3iWbTv1PwMC Content-Disposition: form-data; name="select" @@ -396,6 +402,7 @@ Upload file or create folder Host: example.com X-Api-Key: abcdef... Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryDeC2E3iWbTv1PwMC + Content-Length: 263 ------WebKitFormBoundaryDeC2E3iWbTv1PwMC Content-Disposition: form-data; name="file"; filename*=utf-8''20mm-%C3%BCml%C3%A4ut-b%C3%B6x.gcode @@ -405,7 +412,7 @@ Upload file or create folder T0 G21 G90 - ... + ------WebKitFormBoundaryDeC2E3iWbTv1PwMC-- .. sourcecode:: http @@ -436,6 +443,7 @@ Upload file or create folder Host: example.com X-Api-Key: abcdef... Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryDeC2E3iWbTv1PwMD + Content-Length: 246 ------WebKitFormBoundaryDeC2E3iWbTv1PwMD Content-Disposition: form-data; name="foldername" @@ -504,6 +512,8 @@ Retrieve a specific file's or folder's information On success, a :http:statuscode:`200` is returned, with a :ref:`file information item ` as the response body. + Requires the ``FILES_LIST`` permission. + **Example** .. sourcecode:: http @@ -566,7 +576,10 @@ Issue a file command is not operational when this parameter is present and set to ``true``, the request will fail with a response of ``409 Conflict``. - Upon success, a status code of :http:statuscode:`204` and an empty body is returned. + Upon success, a status code of :http:statuscode:`204` and an empty body is returned. If there already is an + active print job, a :http:statuscode:`409` is returned. + + Requires the ``FILES_SELECT`` permission. slice Slices an STL file into GCODE. Note that this is an asynchronous operation that will take place in the background @@ -598,6 +611,8 @@ Issue a file command Upon success, a status code of :http:statuscode:`202` and a :ref:`sec-api-datamodel-files-fileabridged` in the response body will be returned. + Requires the ``SLICE`` permission. + copy Copies the file or folder to a new ``destination`` on the same ``location``. Additional parameters are: @@ -609,6 +624,8 @@ Issue a file command Upon success, a status code of :http:statuscode:`201` and a :ref:`sec-api-datamodel-files-fileabridged` in the response body will be returned. + Requires the ``FILES_UPLOAD`` permission. + move Moves the file or folder to a new ``destination`` on the same ``location``. Additional parameters are: @@ -622,7 +639,7 @@ Issue a file command Upon success, a status code of :http:statuscode:`201` and a :ref:`sec-api-datamodel-files-fileabridged` in the response body will be returned. - Requires user rights. + Requires the ``FILES_UPLOAD`` permission. **Example Select Request** @@ -756,7 +773,8 @@ Issue a file command :statuscode 400: If the ``command`` is unknown or the request is otherwise invalid :statuscode 415: If a ``slice`` command was issued against something other than an STL file. :statuscode 404: If ``location`` is neither ``local`` nor ``sdcard`` or the requested file was not found - :statuscode 409: If a selected file is supposed to start printing directly but the printer is not operational or + :statuscode 409: If a selected file is supposed to start printing directly but the printer is not operational + or if a file is to be selected but the printer is already printing or if a file to be sliced is supposed to be selected or start printing directly but the printer is not operational or already printing. @@ -773,7 +791,7 @@ Delete file Returns a :http:statuscode:`204` after successful deletion. - Requires user rights. + Requires the ``FILES_DELETE`` permission. **Example Request** diff --git a/docs/api/general.rst b/docs/api/general.rst index 3c404724c..d2cbe3bd9 100644 --- a/docs/api/general.rst +++ b/docs/api/general.rst @@ -12,13 +12,13 @@ Authorization ============= If :ref:`Access Control ` is enabled OctoPrint's API expects an API key to be supplied with each request. This API -key can be either the globally configured one, a user specific one or an app and user specific one as generated by the +key can be either a user specific one or an app and user specific one as generated by the authorization workflow implemented by the bundled :ref:`Application Keys Plugin ` (since 1.3.10). 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. +fallback on directing the user to manually supply the the user specific API key. -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 @@ -45,21 +53,6 @@ will be denied with a :http:statuscode:`403`. If :ref:`Access Control ` is disabled, OctoPrint will treat any unauthenticated anonymous requests and thus also requests with an invalid or outright missing API key as requests with full admin rights! -.. note:: - - The API key requirements changed in 1.3.11. Up to that version, even if Access Control was disabled, all requests needed to - be supplied with an API Key. To make the webinterface work under these circumstances, an unauthenticated anonymous API key was injected into the - HTML page and also available on the :ref:`Push API `. The presence and ready availability of this unauthenticated - anonymous "UI API key" caused confusion and false alarm among users and didn't contribute to the security of the platform in a - meaningful way, so it was finally abandoned in 1.3.11. - -.. _fig-api-general-globalapikey: -.. figure:: ../images/settings-global-api-key.png - :align: center - :alt: Global API key in the API settings - - The global API key can be found in the "API" settings - .. _fig-api-general-userapikey: .. figure:: ../images/settings-user-api-key.png :align: center @@ -148,8 +141,14 @@ Login via the ``passive`` flag. Will return a :http:statuscode:`200` with a :ref:`login response ` on successful - login, whether active or passive. The active (username/password) login may also return a :http:statuscode:`401` in - case of a username/password mismatch or unknown user and a :http:statuscode:`403` in case of a deactivated account. + login, whether active or passive. The active (username/password) login may also return a :http:statuscode:`403` in + case of a username/password mismatch, unknown user or a deactivated account. + + .. warning:: + + Previous versions of this API endpoint did return a :http:statuscode:`401` in case of a username/password + mismatch or an unknown user. That was incompatible with basic authentication since it was a wrong use of + the :http:statuscode:`401` code and got therefore changed as part of a bug fix. :json passive: If present, performs a passive login only, returning information about the current user that's active either through an existing session or the used API key @@ -157,8 +156,7 @@ Login :json pass: (active login only) Password :json remember: (active login only) Whether to set a "remember me" cookie on the session :status 200: Successful login - :status 401: Username/password mismatch or unknown user - :status 403: Deactivated account + :status 403: Username/password mismatch, unknown user or deactivated account .. _sec-api-general-logout: @@ -175,6 +173,20 @@ Logout :status 204: No error +.. _sec-api-general-currentuser: + +Current User +============ + +.. http:get:: /api/currentuser + + Retrieves information about the current user. + + Will return a :http:statuscode:`200` with a :ref:`current user object ` + as body. + + :status 200: No error + .. _sec-api-general-datamodel: Data model @@ -185,6 +197,30 @@ Data model Login response -------------- +The Login response is a :ref:`user record ` extended by the following fields: + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``session`` + - 1 + - string + - The session key, can be used to authenticate with the ``auth`` message on the :ref:`push API `. + * - ``_is_external_client`` + - 1 + - boolean + - Whether the client that made the request got detected as external from the local network or not. + +.. _sec-api-general-datamodel-currentuser: + +Current user +------------ + .. list-table:: :widths: 15 5 10 30 :header-rows: 1 @@ -196,32 +232,12 @@ Login response * - ``name`` - 1 - string - - the user's name/id - * - ``active`` - - 1 - - boolean - - Whether the user's account is active or not - * - ``admin`` - - 1 - - boolean - - Whether the user has admin rights or not - * - ``user`` - - 1 - - boolean - - Whether the user has user rights or not (always ``true``) - * - ``apikey`` - - 1 - - string or None - - The user's API key, if set - * - ``settings`` - - 1 - - dict - - The user's settings, if any - * - ``session`` - - 1 - - string - - The session key, can be used to authenticate with the ``auth`` message on the :ref:`push API `. - * - ``_is_external_client`` - - 1 - - boolean - - Whether the client that made the request got detected as external from the local network or not. + - The id of the current user. Unset if guest. + * - ``permissions`` + - 0..n + - List of :ref:`permission records ` + - The effective list of permissions assigned to the user + * - ``groups`` + - 0..n + - List of :ref:`permission records ` + - The list of groups assigned to the user diff --git a/docs/api/index.rst b/docs/api/index.rst index 6eb090eb1..f6e953b38 100644 --- a/docs/api/index.rst +++ b/docs/api/index.rst @@ -9,7 +9,7 @@ REST API general.rst version.rst - apps.rst + server.rst connection.rst files.rst job.rst @@ -21,7 +21,7 @@ REST API slicing.rst system.rst timelapse.rst - users.rst + access.rst util.rst wizard.rst push.rst diff --git a/docs/api/job.rst b/docs/api/job.rst index 0c43e2b3b..e95729459 100644 --- a/docs/api/job.rst +++ b/docs/api/job.rst @@ -57,7 +57,7 @@ Issue a job command Upon success, a status code of :http:statuscode:`204` and an empty body is returned. - Requires user rights. + Requires the ``PRINT`` permission. **Example Start Request** @@ -180,6 +180,8 @@ Retrieve information about the current job Returns a :http:statuscode:`200` with a :ref:`sec-api-job-datamodel-response` in the body. + Requires the ``STATUS`` permission. + **Example** .. sourcecode:: http @@ -203,8 +205,10 @@ Retrieve information about the current job }, "estimatedPrintTime": 8811, "filament": { - "length": 810, - "volume": 5.36 + "tool0": { + "length": 810, + "volume": 5.36 + } } }, "progress": { @@ -247,5 +251,10 @@ Job information response * - ``state`` - 1 - String - - A textual representation of the current state of the job, i.e. "Operational", "Printing", "Pausing", "Paused", - "Cancelling", "Error" or "Offline". + - A textual representation of the current state of the job or connection, e.g. "Operational", "Printing", "Pausing", "Paused", + "Cancelling", "Error", "Offline", "Offline after error", "Opening serial connection", ... -- please note + that this list is not exhaustive! + * - ``error`` + - 0..1 + - String + - Any error message for the job or connection, only set if there has been an error. diff --git a/docs/api/languages.rst b/docs/api/languages.rst index ecb83102a..f9a580500 100644 --- a/docs/api/languages.rst +++ b/docs/api/languages.rst @@ -6,7 +6,7 @@ Languages .. note:: - All language pack management operations require admin rights. + All language pack management operations require the ``SETTINGS`` permission. .. contents:: diff --git a/docs/api/printer.rst b/docs/api/printer.rst index 3fe43aa18..70237c5eb 100644 --- a/docs/api/printer.rst +++ b/docs/api/printer.rst @@ -80,6 +80,8 @@ Retrieve the current printer state Returns a :http:statuscode:`200` with a :ref:`Full State Response ` in the body upon success. + Requires the ``STATUS`` permission. + **Example 1** Include temperature history data, but limit it to two entries. @@ -241,7 +243,7 @@ Issue a print head command Upon success, a status code of :http:statuscode:`204` and an empty body is returned. - Requires user rights. + Requires the ``CONTROL`` permission. **Example Jog Request** @@ -380,7 +382,7 @@ Issue a tool command Upon success, a status code of :http:statuscode:`204` and an empty body is returned. - Requires user rights. + Requires the ``CONTROL`` permission. **Example Target Temperature Request** @@ -555,6 +557,8 @@ Retrieve the current tool state Returns a :http:statuscode:`200` with a Temperature Response in the body upon success. + Requires the ``STATUS`` permission. + .. note:: If you want both tool and bed temperature information at the same time, take a look at :ref:`Retrieve the current printer state `. @@ -645,7 +649,7 @@ Issue a bed command If no heated bed is configured for the currently selected printer profile, the resource will return an :http:statuscode:`409`. - Requires user rights. + Requires the ``CONTROL`` permission. **Example Target Temperature Request** @@ -714,6 +718,8 @@ Retrieve the current bed state If no heated bed is configured for the currently selected printer profile, the resource will return an :http:statuscode:`409`. + Requires the ``STATUS`` permission. + .. note:: If you want tool, bed and chamber temperature information at the same time, take a look at :ref:`Retrieve the current printer state `. @@ -793,7 +799,7 @@ Issue a chamber command If no heated chamber is configured for the currently selected printer profile, the resource will return an :http:statuscode:`409`. - Requires user rights. + Requires the ``CONTROL`` permission. **Example Target Temperature Request** @@ -862,6 +868,8 @@ Retrieve the current chamber state If no heated chamber is configured for the currently selected printer profile, the resource will return an :http:statuscode:`409`. + Requires the ``STATUS`` permission. + .. note:: If you want tool, bed and chamber temperature information at the same time, take a look at :ref:`Retrieve the current printer state `. @@ -944,7 +952,7 @@ Issue an SD command Upon success, a status code of :http:statuscode:`204` and an empty body is returned. - Requires user rights. + Requires the ``CONTROL`` permission. **Example Init Request** @@ -1022,6 +1030,8 @@ Retrieve the current SD state Returns a :http:statuscode:`200` with an :ref:`SD State Response ` in the body upon success. + Requires the ``STATUS`` permission. + **Example** Read the current state of the SD card. @@ -1058,7 +1068,7 @@ Send an arbitrary command to the printer If successful returns a :http:statuscode:`204` and an empty body. - Requires user rights. + Requires the ``CONTROL`` permission. **Example for sending a single command** @@ -1101,6 +1111,26 @@ Send an arbitrary command to the printer :json string commands: List of commands to send to the printer, mutually exclusive with ``command``. :statuscode 204: No error +.. _sec-api-printer-customcontrols: + +Retrieve custom controls +======================== + +.. http:get:: /api/printer/command/custom + + Retrieves the :ref:`custom controls ` as configured in + :ref:`config.yaml `. + + Please refer to the documentation of :ref:`custom controls ` on what + data structure to expect here. + + Returns a :http:statuscode:`200` with an :ref:`Custom Controls Response ` + in the body upon success. + + Requires the ``CONTROL`` permission. + + :statuscode 200: No error + .. _sec-api-printer-datamodel: Data model @@ -1211,3 +1241,21 @@ Arbitrary Command Request - 0..1 - Map of key value pairs - (only if ``script`` is set) additional template variables to provide to the script renderer + +.. _sec-api-printer-datamodel-customcontrols: + +Custom Controls Response +------------------------ + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``controls`` + - 0..n + - List of :ref:`custom controls ` + - A list of custom control definitions as defined in ``config.yaml``. diff --git a/docs/api/printerprofiles.rst b/docs/api/printerprofiles.rst index 9f2f163e2..fc251ea73 100644 --- a/docs/api/printerprofiles.rst +++ b/docs/api/printerprofiles.rst @@ -21,6 +21,8 @@ Retrieve all printer profiles Returns a :http:statuscode:`200` with a list of :ref:`profiles `. + Requires the ``CONNECTION`` permission. + **Example** .. sourcecode:: http @@ -124,6 +126,22 @@ Retrieve all printer profiles } +.. _sec-api-printerprofiles-get: + +Retrieve a single printer profile +================================= + +.. http:get:: /api/printerprofiles/(string:identifier) + + Retrieves an existing single printer profile. + + Returns a :http:statuscode:`200` with a :ref:`profile `. + + Requires the ``CONNECTION`` permission. + + :statuscode 200: No error + :statuscode 404: The profile does not exist + .. _sec-api-printerprofiles-add: Add a new printer profile @@ -143,7 +161,7 @@ Add a new printer profile Returns a :http:statuscode:`200` with the saved profile as property ``profile`` in the JSON body upon success. - Requires admin rights. + Requires the ``SETTINGS`` permission. **Example 1** @@ -314,7 +332,7 @@ Update an existing printer profile Returns a :http:statuscode:`200` with the saved profile as property ``profile`` in the JSON body upon success. - Requires admin rights. + Requires the ``SETTINGS`` permission. **Example** @@ -400,7 +418,7 @@ Remove an existing printer profile Returns a :http:statuscode:`204` an empty body upon success. - Requires admin rights. + Requires the ``SETTINGS`` permission. **Example** diff --git a/docs/api/push.rst b/docs/api/push.rst index 87e40bf5d..c9c6a4b04 100644 --- a/docs/api/push.rst +++ b/docs/api/push.rst @@ -29,6 +29,9 @@ following message types are currently available for usage by 3rd party clients: * ``connected``: Initial connection information, sent only right after establishing the socket connection. See :ref:`the payload data model `. + * ``reauthRequired``: A reauthentication of the current login session is required. The ``reason`` parameter in the + payload defines whether a full active login is necessary (values ``logout`` and ``removed``) or a simple passive + login will suffice (all other values). * ``current``: Rate limited general state update, payload contains information about the printer's state, job progress, accumulated temperature points and log lines since last update. OctoPrint will send these updates when new information is available, but not more often than twice per second in order to not flood the client with messages (e.g. @@ -51,9 +54,8 @@ OctoPrint's SockJS socket also accepts two commands from the client to the serve * ``auth`` (since 1.3.10): With the ``auth`` message, clients may associate an existing user session with the socket. That is of special importance to receive - any kind of messages if the bundled :ref:`Forcelogin Plugin ` is enabled - (as it is by default), since it will prevent any kind of status messages to be sent to connected unauthenticated - clients. + any kind of messages, since the permission system will prevent any kind of status messages to be sent to connected + clients lacking the ``STATUS`` permission. The ``auth`` message expects the user id of the user to authenticate followed by ``:`` and a session key to be obtained from the successful payload of a :ref:`(passive or active) login via the API `. @@ -175,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/settings.rst b/docs/api/settings.rst index b4597ef94..b231f2875 100644 --- a/docs/api/settings.rst +++ b/docs/api/settings.rst @@ -21,6 +21,8 @@ Retrieve current settings The :ref:`data model ` is similar to what can be found in :ref:`config.yaml `, see below for details. + Requires the ``SETTINGS_READ`` permission. + .. _sec-api-settings-save: Save settings @@ -36,7 +38,7 @@ Save settings Returns the currently active settings on success, as part of a :http:statuscode:`200` response. - Requires admin rights. + Requires the ``SETTINGS`` permission. **Example** @@ -69,23 +71,6 @@ Save settings } } -.. _sec-api-settings-generateapikey: - -Regenerate the system wide API key -================================== - -.. http:post:: /api/settings/apikey - - Generates a new system wide API key. - - Does not expect a body. Will return the generated API key as ``apikey`` - property in the JSON object contained in the response body. - - Requires admin rights. - - :status 200: No error - :status 403: No admin rights - .. _sec-api-settings-fetchtemplaatedata: Fetch template data @@ -352,84 +337,22 @@ Data model ========== The data model on the settings API mostly reflects the contents of -:ref:`config.yaml `. The settings tree -returned by the API contains the following fields, which are directly -mapped from the same fields in ``config.yaml`` unless otherwise noted: +:ref:`config.yaml `, which are directly +mapped, with the following exceptions: .. list-table:: :header-rows: 1 * - Field - Notes - * - ``api.enabled`` - - - * - ``api.key`` - - Only maps to ``api.key`` in ``config.yaml`` if request is sent with admin rights, set to ``n/a`` otherwise. - Starting with OctoPrint 1.3.3 setting this field via :ref:`the API ` is not possible, - only :ref:`regenerating it ` is supported. Setting a custom value is only - possible through `config.yaml`. - * - ``api.allowCrossOrigin`` - - - * - ``appearance.name`` - - - * - ``appearance.color`` - - - * - ``appearance.colorTransparent`` - - - * - ``appearance.defaultLanguage`` - - - * - ``appearance.showFahrenheitAlso`` - - * - ``feature.gcodeViewer`` - Maps to ``gcodeViewer.enabled`` in ``config.yaml`` * - ``feature.sizeThreshold`` - Maps to ``gcodeViewer.sizeThreshold`` in ``config.yaml`` * - ``feature.mobileSizeThreshold`` - Maps to ``gcodeViewer.mobileSizeThreshold`` in ``config.yaml`` - * - ``feature.temperatureGraph`` - - - * - ``feature.waitForStart`` - - - * - ``feature.alwaysSendChecksum`` - - - * - ``feature.neverSendChecksum`` - - - * - ``feature.sdSupport`` - - - * - ``feature.sdRelativePath`` - - - * - ``feature.sdAlwaysAvailable`` - - - * - ``feature.swallowOkAfterResend`` - - - * - ``feature.repetierTargetTemp`` - - - * - ``feature.externalHeatupDetection`` - - - * - ``feature.keyboardControl`` - - - * - ``feature.pollWatched`` - - - * - ``feature.ignoreIdenticalResends`` - - - * - ``feature.modelSizeDetection`` - - - * - ``feature.firmwareDetection`` - - - * - ``feature.printCancelConfirmation`` - - - * - ``feature.blockWhileDwelling`` - - - * - ``folder.uploads`` - - - * - ``folder.timelapse`` - - * - ``folder.timelapseTmp`` - Maps to ``folder.timelapse_tmp`` in ``config.yaml`` - * - ``folder.logs`` - - - * - ``folder.watched`` - - * - ``plugins`` - Plugin settings as available from ``config.yaml`` and :class:`~octoprint.plugin.SettingsPlugin` implementations * - ``printer.defaultExtrusionLength`` @@ -444,8 +367,6 @@ mapped from the same fields in ``config.yaml`` unless otherwise noted: - Available serial ports * - ``serial.baudrateOptions`` - Available serial baudrates - * - ``serial.autoconnect`` - - * - ``serial.timeoutConnection`` - Maps to ``serial.timeout.connection`` in ``config.yaml`` * - ``serial.timeoutDetection`` @@ -458,50 +379,18 @@ mapped from the same fields in ``config.yaml`` unless otherwise noted: - Maps to ``serial.timeout.temperatureTargetSet`` in ``config.yaml`` * - ``serial.timeoutSdStatus`` - Maps to ``serial.timeout.sdStatus`` in ``config.yaml`` - * - ``serial.log`` - - - * - ``serial.additionalPorts`` - - - * - ``serial.additionalBaudrates`` - - - * - ``serial.longRunningCommands`` - - - * - ``serial.checksumRequiringCommands`` - - - * - ``serial.helloCommand`` - - - * - ``serial.ignoreErrorsFromFirmware`` - - - * - ``serial.disconnectOnErrors`` - - - * - ``serial.triggerOkForM29`` - - - * - ``serial.supportResendsWIthoutOk`` - - * - ``serial.maxTimeoutsIdle`` - Maps to ``serial.maxCommunicationTimeouts.idle`` in ``config.yaml`` * - ``serial.maxTimeoutsPrinting`` - Maps to ``serial.maxCommunicationTimeouts.printing`` in ``config.yaml`` * - ``serial.maxTimeoutsLong`` - Maps to ``serial.maxCommunicationTimeouts.long`` in ``config.yaml`` - * - ``server.commands.systemShutdownCommand`` - - - * - ``server.commands.systemRestartCommand`` - - - * - ``server.commands.serverRestartCommand`` - - - * - ``server.diskspace.warning`` - - - * - ``server.diskspace.critical`` - - * - ``system.actions`` - Whole subtree taken from ``config.yaml`` * - ``system.events`` - Whole subtree taken from ``config.yaml`` * - ``temperature.profiles`` - Whole subtree taken from ``config.yaml`` - * - ``temperature.cutoff`` - - * - ``terminalFilters`` - Whole subtree taken from ``config.yaml`` * - ``webcam.streamUrl`` @@ -510,17 +399,3 @@ mapped from the same fields in ``config.yaml`` unless otherwise noted: - Maps to ``webcam.snapshot`` in ``config.yaml`` * - ``webcam.ffmpegPath`` - Maps to ``webcam.ffmpeg`` in ``config.yaml`` - * - ``webcam.bitrate`` - - - * - ``webcam.ffmpegThreads`` - - - * - ``webcam.ffmpegVideoCodec`` - - - * - ``webcam.watermark`` - - - * - ``webcam.flipH`` - - - * - ``webcam.flipV`` - - - * - ``webcam.rotate90`` - - diff --git a/docs/api/slicing.rst b/docs/api/slicing.rst index c49cb4cd5..7c1ea53f0 100644 --- a/docs/api/slicing.rst +++ b/docs/api/slicing.rst @@ -28,6 +28,8 @@ List All Slicers and Slicing Profiles Returns a :http:statuscode:`200` response with a :ref:`Slicer list ` as the body upon successful completion. + Requires the ``SLICE`` permission. + **Example** .. sourcecode:: http @@ -77,6 +79,8 @@ List Slicing Profiles of a Specific Slicer Returns a :http:statuscode:`200` response with a :ref:`Profile list ` as the body upon successful completion. + Requires the ``SLICE`` permission. + **Example** .. sourcecode:: http @@ -121,6 +125,8 @@ Retrieve Specific Profile Returns a :http:statuscode:`200` response with a :ref:`full Profile ` as the body upon successful completion. + Requires the ``SLICE`` permission. + **Example** .. sourcecode:: http @@ -168,7 +174,7 @@ Add Slicing Profile Returns a :http:statuscode:`201` and an :ref:`abridged Profile ` in the body upon successful completion. - Requires admin rights. + Requires the ``SETTINGS`` permission. **Example** @@ -206,6 +212,31 @@ Add Slicing Profile :statuscode 201: No error :statuscode 404: If the ``slicer`` was unknown to the system. +.. _sec-api-slicing-patch: + +Update Slicing Profile +====================== + +.. http:patch:: /api/slicing/(string:slicer)/profiles/(string:key) + + Updates the slicing profile identified by ``key`` for the slicer ``slicer``. + + Expects a :ref:`profile update request ` as body. + + Returns a :http:statuscode:`201` and an :ref:`abridged Profile ` in the body + upon successful completion. + + Requires the ``SETTINGS`` permission. + + :param slicer: The identifying key of the slicer for which to update the profile + :param key: The identifying key of the profile to update + :json data: New profile overrides to apply + :json displayName: New display name + :json description: New description + :json default: Whether to make the profile default (true) or not (false) for the slicer + :statuscode 200: No error + :statuscode 404: Slicer or profile do not exist + .. _sec-api-slicing-delete: Delete Slicing Profile @@ -216,7 +247,7 @@ Delete Slicing Profile Delete the slicing profile identified by ``key`` for the slicer ``slicer``. If the profile doesn't exist, the request will succeed anyway. - Requires admin rights. + Requires the ``SETTINGS`` permission. :param slicer: The identifying key of the slicer for which to delete the profile :param key: The identifying key of the profile to delete @@ -340,3 +371,32 @@ Profile only the keys differing from the defaults when saving/updating a profile. The keys to be found in here a slicer specific. Will be left out for list responses. +.. _sec-api-slicing-datamodel-profileupdate: + +Profile Update Request +---------------------- + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``data`` + - 0..1 + - Object + - The profile data + * - ``displayName`` + - 0..1 + - ``string`` + - The new display name for the profile + * - ``description`` + - 0..1 + - ``string`` + - The new description for the profile + * - ``default`` + - 0..1 + - ``boolean`` + - Whether to mark the profile as default for the slicer (true) or not (false) diff --git a/docs/api/system.rst b/docs/api/system.rst index c3df02e9a..4dce5dd58 100644 --- a/docs/api/system.rst +++ b/docs/api/system.rst @@ -6,7 +6,7 @@ System .. note:: - All system operations require admin rights. + All system operations require the ``SYSTEM`` permission. .. _sec-api-system-command-list: @@ -20,6 +20,8 @@ List all registered system commands A :http:statuscode:`200` with a :ref:`List all response ` will be returned. + Requires the ``SYSTEM`` permission. + **Example** .. sourcecode:: http diff --git a/docs/api/timelapse.rst b/docs/api/timelapse.rst index 54b3668ec..000a8190f 100644 --- a/docs/api/timelapse.rst +++ b/docs/api/timelapse.rst @@ -18,6 +18,8 @@ Retrieve a list of timelapses and the current config Returns a :ref:`timelapse list ` in the response body. + Requires the ``TIMELAPSE_LIST`` permission. + :param unrendered: If provided and true, also include unrendered timelapses .. _sec-api-timelapse-delete: @@ -29,7 +31,7 @@ Delete a timelapse Delete the timelapse ``filename``. - Requires user rights. + Requires the ``TIMELAPSE_DELETE`` permission. .. _sec-api-timelapse-render: @@ -41,7 +43,7 @@ Issue a command for an unrendered timelapse Current only supports to render the unrendered timelapse ``name`` via the ``render`` command. - Requires user rights. + Requires the ``TIMELAPSE_ADMIN`` permission. :json command: The command to issue, currently only ``render`` is supported @@ -54,7 +56,7 @@ Delete an unrendered timelapse Delete the unrendered timelapse ``name``. - Requires user rights. + Requires the ``TIMELAPSE_DELETE`` permission. .. _sec-api-timelapse-saveconfig: @@ -67,7 +69,7 @@ Change current timelapse config The configuration is expected as the request body. - Requires user rights. + Requires the ``TIMELAPSE_ADMIN`` permission. .. _sec-api-timelapse-datamodel: diff --git a/docs/api/users.rst b/docs/api/users.rst index 536c955b0..495829a1f 100644 --- a/docs/api/users.rst +++ b/docs/api/users.rst @@ -4,311 +4,6 @@ User **** -.. contents:: +.. note:: -.. _sec-api-users-list: - -Retrieve a list of users -======================== - -.. http:get:: /api/users - - Retrieves a list of all registered users in OctoPrint. - - Will return a :http:statuscode:`200` with a :ref:`user list response ` - as body. - - Requires admin rights. - - :status 200: No error - -.. _sec-api-users-retrieve: - -Retrieve a user -=============== - -.. http:get:: /api/users/(string:username) - - Retrieves information about a user. - - Will return a :http:statuscode:`200` with a :ref:`user record ` - as body. - - Requires either admin rights or to be logged in as the user. - - :param username: Name of the user which to retrieve - :status 200: No error - :status 404: Unknown user - -.. _sec-api-users-add: - -Add a user -========== - -.. http:post:: /api/users - - Adds a user to OctoPrint. - - Expects a :ref:`user registration request ` - as request body. - - Returns a list of registered users on success, see :ref:`Retrieve a list of users `. - - Requires admin rights. - - :json name: The user's name - :json password: The user's password - :json active: Whether to activate the account (true) or not (false) - :json admin: Whether to give the account admin rights (true) or not (false) - :status 200: No error - :status 400: If any of the mandatory fields is missing or the request is otherwise - invalid - :status 409: A user with the provided name does already exist - -.. _sec-api-users-update: - -Update a user -============= - -.. http:put:: /api/users/(string:username) - - Updates a user record. - - Expects a :ref:`user update request ` - as request body. - - Returns a list of registered users on success, see :ref:`Retrieve a list of users `. - - Requires admin rights. - - :param username: Name of the user to update - :json admin: Whether to mark the user as admin (true) or not (false), can be left out (no change) - :json active: Whether to mark the account as activated (true) or deactivated (false), can be left out (no change) - :status 200: No error - :status 404: Unknown user - -.. _sec-api-users-delete: - -Delete a user -============= - -.. http:delete:: /api/users/(string:username) - - Delete a user record. - - Returns a list of registered users on success, see :ref:`Retrieve a list of users `. - - Requires admin rights. - - :param username: Name of the user to delete - :status 200: No error - :status 404: Unknown user - -.. _sec-api-users-resetpassword: - -Reset a user's password -======================= - -.. http:put:: /api/users/(string:username)/password - - Changes the password of a user. - - Expects a JSON object with a single property ``password`` as request body. - - Requires admin rights or to be logged in as the user. - - :param username: Name of the user to change the password for - :json password: The new password to set - :status 200: No error - :status 400: If the request doesn't contain a ``password`` property or the request - is otherwise invalid - :status 403: No admin rights and not logged in as the user - :status 404: The user is unknown - -.. _sec-api-users-getsettings: - -Retrieve a user's settings -========================== - -.. http:get:: /api/users/(string:username)/settings - - Retrieves a user's settings. - - Will return a :http:statuscode:`200` with a JSON object representing the user's - personal settings (if any) as body. - - Requires admin rights or to be logged in as the user. - - :param username: Name of the user to retrieve the settings for - :status 200: No error - :status 403: No admin rights and not logged in as the user - :status 404: The user is unknown - -.. _sec-api-users-updatesettings: - -Update a user's settings -======================== - -.. http:patch:: /api/users/(string:username)/settings - - Updates a user's settings. - - Expects a new settings JSON object to merge with the current settings as - request body. - - Requires admin rights or to be logged in as the user. - - :param username: Name of the user to retrieve the settings for - :status 204: No error - :status 403: No admin rights and not logged in as the user - :status 404: The user is unknown - -.. _sec-api-users-generateapikey: - -Regenerate a user's personal API key -==================================== - -.. http:post:: /api/users/(string:username)/apikey - - Generates a new API key for the user. - - Does not expect a body. Will return the generated API key as ``apikey`` - property in the JSON object contained in the response body. - - Requires admin rights or to be logged in as the user. - - :param username: Name of the user to retrieve the settings for - :status 200: No error - :status 403: No admin rights and not logged in as the user - :status 404: The user is unknown - -.. _sec-api-users-deleteapikey: - -Delete a user's personal API key -================================ - -.. http:delete:: /api/users/(string:username)/apikey - - Deletes a user's personal API key. - - Requires admin rights or to be logged in as the user. - - :param username: Name of the user to retrieve the settings for - :status 204: No error - :status 403: No admin rights and not logged in as the user - :status 404: The user is unknown - -.. _sec-api-users-datamodel: - -Data model -========== - -.. _sec-api-users-datamodel-userlistresponse: - -User list response ------------------- - -.. list-table:: - :widths: 15 5 10 30 - :header-rows: 1 - - * - Name - - Multiplicity - - Type - - Description - * - ``users`` - - 0..n - - List of :ref:`user records ` - - The list of registered users - -.. _sec-api-users-datamodel-userrecord: - -User record ------------ - -.. list-table:: - :widths: 15 5 10 30 - :header-rows: 1 - - * - Name - - Multiplicity - - Type - - Description - * - ``name`` - - 1 - - string - - The user's name - * - ``active`` - - 1 - - bool - - Whether the user's account is active (true) or not (false) - * - ``user`` - - 1 - - bool - - Whether the user has user rights. Should always be true. - * - ``admin`` - - 1 - - bool - - Whether the user has admin rights (true) or not (false) - * - ``apikey`` - - 0..1 - - string - - The user's personal API key - * - ``settings`` - - 1 - - object - - The user's personal settings, might be an empty object. - -.. _sec-api-users-datamodel-adduserrequest: - -User registration request -------------------------- - -.. list-table:: - :widths: 15 5 10 30 - :header-rows: 1 - - * - Name - - Multiplicity - - Type - - Description - * - ``name`` - - 1 - - string - - The user's name - * - ``password`` - - 1 - - string - - The user's password - * - ``active`` - - 1 - - bool - - Whether to activate the account (true) or not (false) - * - ``admin`` - - 0..1 - - bool - - Whether to give the user admin rights (true) or not (false or not present) - -.. _sec-api-users-datamodel-updateuserrequest: - -User update request -------------------- - -.. list-table:: - :widths: 15 5 10 30 - :header-rows: 1 - - * - Name - - Multiplicity - - Type - - Description - * - ``active`` - - 0..1 - - bool - - If present will set the user's active flag to the provided value. True for - activating the account, false for deactivating it. - * - ``admin`` - - 0..1 - - bool - - If present will set the user's admin flag to the provided value. True for - admin rights, false for no admin rights. + This API endpoint has been moved and is now part of :ref:`Access Control `. diff --git a/docs/api/util.rst b/docs/api/util.rst index 48b9e71b9..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 @@ -99,7 +99,24 @@ Test paths or URLs The ``server`` command returns :http:statuscode:`200` with a :ref:`Server test result ` when the test could be performed. The status code of the response does NOT reflect the test result! - Requires admin rights. + resolution + Tests whether a provided hostname can be resolved (via DNS lookup). Supported parameters are: + + * ``name``: The host name to test. Mandatory. + + 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** @@ -286,6 +303,84 @@ Test paths or URLs "result": true } + **Example 7** + + Test whether a host name can be resolved successfully. + + .. sourcecode:: http + + POST /api/util/test HTTP/1.1 + Host: example.com + X-Api-Key: abcdef... + Content-Type: application/json + + { + "command": "resolution", + "name": "octoprint" + } + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + { + "name": "octoprint.org", + "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`` @@ -302,6 +397,8 @@ Test paths or URLs :json host: ``server`` command only: the server to test :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: @@ -409,3 +506,51 @@ Server test result - 1 - bool - ``true`` if the check passed. + +.. _sec-api-util-datamodel-resolutiontestresult: + +Resolution test result +---------------------- + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``name`` + - 1 + - string + - The host name that was tested. + * - ``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/api/wizard.rst b/docs/api/wizard.rst index dfbb13801..6a36e3ed5 100644 --- a/docs/api/wizard.rst +++ b/docs/api/wizard.rst @@ -6,7 +6,7 @@ Wizard .. note:: - All wizard operations require either admin rights or the ``firstRun`` flag to be ``true``. + All wizard operations require either the ``ADMIN`` permission or the ``firstRun`` flag to be ``true``. .. contents:: diff --git a/docs/bundledplugins/action_command_notification.rst b/docs/bundledplugins/action_command_notification.rst new file mode 100644 index 000000000..d2b5a005c --- /dev/null +++ b/docs/bundledplugins/action_command_notification.rst @@ -0,0 +1,63 @@ +.. _sec-bundledplugins-action_command_notification: + +Action Command Notification support +=================================== + +.. 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 +in the sidebar and if configured also as popup messages. The notifications in the sidebar panel can also be cleared +by users with the ``PLUGIN_ACTION_COMMAND_NOTIFICATION_CLEAR`` permission. + +.. _fig-bundledplugins-action_command_notification-example: +.. figure:: ../images/bundledplugins-action_command_notification-example.png + :align: center + :alt: Simple notification example + + A simple notification example triggered by the firmware + +.. _sec-bundledplugins-action_command_notification-configuration: + +Configuring the plugin +---------------------- + +The plugin supports the following configuration keys: + + * ``enable``: Whether to enable the support of notifications (enabled by default). + * ``enable_popup``: Whether to enable the additional display of notifications as popups in the UI (disabled by default). + +You can modify them either through the plugin's configuration dialog under Settings, or by directly editing ``config.yaml``. + +.. _sec-bundledplugins-action_command_notification-action_commands: + +Supported action commands +------------------------- + +notification + Displays the notification ```` + +.. _sec-bundledplugins-action_command_prompt-example: + +Example communication with the firmware +--------------------------------------- + +.. _sec-bundledplugins-action_command_prompt-sourcecode: + +To display the :ref:`above notification ` the firmware sent this action command: + +.. code-block:: none + + //action:notification Hello World! + + +.. _sec-bundledplugins-action_command_notification-sourcecode: + + +Source code +----------- + +The source of the Action Command Prompt Notification plugin is bundled with OctoPrint and can be found in +its source repository under ``src/octoprint/plugins/action_command_notification``. diff --git a/docs/bundledplugins/action_command_prompt.rst b/docs/bundledplugins/action_command_prompt.rst index 2d972cac4..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 @@ -19,17 +21,6 @@ placeholder for the selected option's index. A simple dialog example triggered by the firmware -.. _sec-bundledplugins-action_command_prompt-firststeps: - -First Steps ------------ - -In order for this plugin to work, you'll need to configure it with the command your firmware uses to accept -dialog selections. You can do that in the settings dialog. - -Currently there is no agreed upon command for this since no firmware has yet made use of this feature, so OctoPrint -ships with an empty value here. - .. _sec-bundledplugins-action_command_prompt-configuration: Configuring the plugin @@ -37,7 +28,13 @@ Configuring the plugin The plugin supports the following configuration keys: - * ``selection_command``: The command to send to the firmware on choice, including the ``{choice}`` placeholder, e.g. ``M876 S{choice}``. + * ``enable``: Whether to always enable (``always``), disable (``never``) or ``detect`` support. + * ``enable_emergency_sending``: Will make the selection command be sent as an emergency command to jump the internal + send queue and even be sent to the printer if it's not signaling to be able to received. Only done if this is true + and the printer signals support for emergency command processing. Defaults to ``true``. + * ``enable_signaling``: If enabled, will send the configured command with the ``P1`` parameter to the printer to + signal prompt support of the host. Defaults to ``true``. + * ``command``: The command to send to the firmware on choice, defaults to ``M876``. You can modify them either through the plugin's configuration dialog under Settings, or by directly editing ``config.yaml``. @@ -69,8 +66,6 @@ prompt_end Example communication with the firmware --------------------------------------- -.. _sec-bundledplugins-action_command_prompt-sourcecode: - To display the :ref:`above dialog ` the firmware sent these action commands: .. code-block:: none @@ -79,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 1fa8acdd7..1bc8fac22 100644 --- a/docs/bundledplugins/discovery.rst +++ b/docs/bundledplugins/discovery.rst @@ -3,18 +3,19 @@ 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 OctoPrint instance icon in "Networks > Other Devices" in your Windows Explorer, which will take you directly to the web frontend. -The ZeroConf support allows OctoPrint to announce itself to Safari on MacOS X +The ZeroConf support allows OctoPrint to announce itself to Safari on macOS on the same network. Linux users should install `Avahi `_ and can then use one @@ -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 new file mode 100644 index 000000000..7be2b3baf --- /dev/null +++ b/docs/bundledplugins/file_check.rst @@ -0,0 +1,9 @@ +.. _sec-bundledplugins-file_check: + +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 new file mode 100644 index 000000000..e73a3b9ab --- /dev/null +++ b/docs/bundledplugins/firmware_check.rst @@ -0,0 +1,11 @@ +.. _sec-bundledplugins-firmware_check: + +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/forcelogin.rst b/docs/bundledplugins/forcelogin.rst deleted file mode 100644 index e5214f79f..000000000 --- a/docs/bundledplugins/forcelogin.rst +++ /dev/null @@ -1,35 +0,0 @@ -.. _sec-bundledplugins-forcelogin: - -ForceLogin Plugin -================= - -The ForceLogin Plugin comes bundled with OctoPrint (starting with version 1.3.10). It removes the anonymous -read-only access that up until 1.3.10 was standard when accessing OctoPrint instances without being logged in and -instead forces users to log in if they want to get any kind of information from OctoPrint. - -.. _fig-bundledplugins-forcelogin: -.. figure:: ../images/bundledplugins-forcelogin-dialog.png - :align: center - :alt: Forced login dialog - - OctoPrint's new forced login dialog. - -.. warning:: - - Keep in mind that **OctoPrint does not manage your webcam**, it merely embeds it. If you have a webcam, - it will still be accessible to users who are not logged in under its (guessable) URL. If you need to restrict - access to your webcam, you'll need to find a way to do so directly on the webcam server which - again - - is not OctoPrint itself. - -.. note:: - - If you want back the old behaviour of allowing anonymous read-only access to your OctoPrint instance, disable - the ForceLogin Plugin in OctoPrint's plugin manager. - -.. _sec-bundledplugins-forcelogin-sourcecode: - -Source code ------------ - -The source of the ForceLogin plugin is bundled with OctoPrint and can be found in -its source repository under ``src/octoprint/plugins/forcelogin``. diff --git a/docs/bundledplugins/gcodeviewer.rst b/docs/bundledplugins/gcodeviewer.rst new file mode 100644 index 000000000..704d04213 --- /dev/null +++ b/docs/bundledplugins/gcodeviewer.rst @@ -0,0 +1,37 @@ +.. _sec-bundledplugins-gcodeviewer: + +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: +.. figure:: ../images/bundledplugins-gcodeviewer-example.png + :align: center + :alt: OctoPrint GCode Viewer Plugin + + An example of the GCode Viewer in action. + +The viewer has been included in OctoPrint ever since the first releases back in 2013, however as of +OctoPrint 1.4.1 it has been extracted into its own bundled plugin. + +.. _sec-bundledplugins-gcodeviewer-configuration: + +Configuring the plugin +---------------------- + +The plugin supports the following configuration keys: + + * ``mobileSizeThreshold``: Whether to also enable tracking on unreleased OctoPrint versions (anything not stable releases + or release candidates). Defaults to ``false``. + * ``sizeThreshold``: Unique instance identifier, auto generated on first activation + +.. _sec-bundledplugins-gcodeviewer-sourcecode: + +Source Code +----------- + +The source of the GCode Viewer plugin is bundled with OctoPrint and can be +found in its source repository under ``src/octoprint/plugins/gcodeviewer``. diff --git a/docs/bundledplugins/index.rst b/docs/bundledplugins/index.rst index d82c3eb29..a1d858616 100644 --- a/docs/bundledplugins/index.rst +++ b/docs/bundledplugins/index.rst @@ -7,6 +7,7 @@ Bundled Plugins .. toctree:: :maxdepth: 2 + action_command_notification.rst action_command_prompt.rst announcements.rst tracking.rst @@ -14,8 +15,11 @@ Bundled Plugins backup.rst discovery.rst errortracking.rst - forcelogin.rst + file_check.rst + firmware_check.rst + gcodeviewer.rst logging.rst pluginmanager.rst printer_safety_check.rst softwareupdate.rst + virtual_printer.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 new file mode 100644 index 000000000..4697cd7d3 --- /dev/null +++ b/docs/bundledplugins/loginui.rst @@ -0,0 +1,6 @@ +.. _sec-bundledplugins-loginui: + +Login UI +======== + +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/printer_safety_check.rst b/docs/bundledplugins/printer_safety_check.rst deleted file mode 100644 index 320de9053..000000000 --- a/docs/bundledplugins/printer_safety_check.rst +++ /dev/null @@ -1,52 +0,0 @@ -.. _sec-bundledplugins-printer_safety_check: - -Printer Safety Check -==================== - -The Printer Safety Check plugin comes bundled with OctoPrint starting with version 1.3.7. - -It tries to identify printers or rather printer firmwares with known safety issues, such as -disabled thermal runaway protection, and displays a warning box to logged in users on -such identification. - -.. _fig-bundledplugins-printer_safety_check-example: -.. figure:: ../images/bundledplugins-printer_safety_check-example.png - :align: center - :alt: Printer Safety Check warning example - - An example of a warning generated by the Printer Safety Check - -Please refer to the `entry on the "unsafe firmware" warning in OctoPrint's FAQ `_ -for a list of currently identified printers. - -If you know of further printers/printer firmwares that need to be added here, please -`get in touch on the forum and provide their response to an M115 `_. - -.. note:: - - Feel free to disable the plugin in OctoPrint's Plugin Manager if you feel like it is unnecessary. Be advised though - that even if your printer might be running totally fine with a known unsafe configuration, that might change - unexpectedly and with `catastrophic `_ - `results `_. - -.. _sec-bundledplugins-printer_safety_check-events: - -Events ------- - -warning - A printer safety warning was triggered. - - Payload: - - * ``check_type``: type of check that was triggered (e.g. ``m115``, ``received`` or ``cap``) - * ``check_name``: name of check that was triggered (e.g. ``aneta8``) - * ``warning_type``: type of warning that was triggered (e.g. ``firmware-unsafe``) - -.. _sec-bundledplugins-printer_safety_check-source: - -Source Code ------------ - -The source of the Printer Safety Check plugin is bundled with OctoPrint and can be -found in its source repository under ``src/octoprint/plugins/printer_safety_check``. diff --git a/docs/bundledplugins/softwareupdate.rst b/docs/bundledplugins/softwareupdate.rst index 1ba0daf84..ada18d84e 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 - (``/home/pi/OctoPrint`` for OctoPi or `manual installs following the Raspberry Pi setup guide `_). + * **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 @@ -133,7 +138,7 @@ Configuring the Plugin user: foosel repo: OctoPrint method: pip - pip: 'https://github.com/foosel/OctoPrint/archive/{target_version}.zip' + pip: 'https://github.com/OctoPrint/OctoPrint/archive/{target_version}.zip' # further checks may be defined here @@ -141,11 +146,49 @@ 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 ++++++++++++++ +Version check types are configured through the ``type`` parameter. The following +types are currently recognized: + * ``github_release``: Checks against releases published on Github. Additional config parameters: @@ -153,10 +196,28 @@ Version checks * ``repo``: (mandatory) Github repository to check * ``prerelease``: ``True`` or ``False``, default ``False``, set to ``True`` to also include releases on Github marked as prerelease. - * ``release_branch``: Branch name to check against ``target_comittish`` - field in Github release data - release will only be included if the - values match. Defaults to being unset, in which case no match will - be performed. + * ``prerelease_branches``: Prerelease channel definitions, optional. List of: + * ``branch``: Branch associated with the channel, acts as ID + * ``name``: Human readable name of the release channel + * ``commitish``: List of values to check against ``target_commitish`` + 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 + * ``commitish``: List of values to check against ``target_commitish`` + 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_commitish`` 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 @@ -190,12 +251,42 @@ Version checks ``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: * ``checkout_folder``: (mandatory) The full path to the folder with a valid git repository to check. + * ``pypi_release``: Checks `pypi.org `_ for new releases of a specified package. Additional + config parameters: + + * ``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: + + * ``header_url`` or ``url``: (mandatory) URL to check. ``url`` can be used to avoid duplication in case of updater + methods such as ``single_file_plugin``. + * ``header_name``: (mandatory) HTTP header to check, case-insensitive, e.g. ``ETag`` or ``Last-Modified``. + * ``header_method``: HTTP request method to use for the check, defaults to ``HEAD``. + * ``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: @@ -218,35 +309,63 @@ Version checks * ``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 ++++++++++++++ - * ``pip``: An URL to provide to ``pip install`` in order to perform the - update. May contain a placeholder ``{target}`` which will be the most - recent version specifier as retrieved from the update check. - * ``update_script``: A script to execute in order to perform the update. May - contain placeholders ``{target}`` (for the most recent version specified - as retrieved from the update check), ``{branch}`` for the branch to switch - to to access the release, ``{folder}`` for the working directory - of the script and ``{python}`` for the python executable OctoPrint is - running under. The working directory must be specified either by an - ``update_folder`` setting or if the ``git_commit`` check is used its - ``checkout_folder`` setting. - * ``python_updater``: Can only be specified by plugins through the - :ref:`hook `. A Python callable - which performs the update, see below for details. +Update methods are specified via the ``method`` parameter. Some update methods are assigned implicitly +through the presence of their mandatory configuration parameters. The following methods are currently +supported: + + * ``pip``: Update by ``pip install``ing the supplied URL. May contain a + placeholder ``{target}`` which will be the most recent version specifier as retrieved from the update check. + Additional config parameters: + + * ``pip``: The URL to use for installing. Presence implies ``method: pip``. + + * ``single_file_plugin``: Update a single file plugin by re-downloading it from a configured URL. + Additional config parameters: + + * ``url``: (mandatory) The URL from which to install the single file plugin. Must be a single self contained + python file. + + * ``update_script``: Update by executing a script. + Additional config parameters: + + * ``update_script``: (mandatory) The path of the script to run. May + contain placeholders ``{target}`` (for the most recent version specified + as retrieved from the update check), ``{branch}`` for the branch to switch + to to access the release, ``{folder}`` for the working directory + of the script and ``{python}`` for the python executable OctoPrint is + running under. Presence implies ``method: update_script``. + * ``update_folder`` or ``checkout_folder``: (mandatory) The working directory. + ``checkout_folder`` can be used to avoid duplication in case of check + types such as ``git_commit``. + + * ``python_updater``: Update by executing a custom python callable. + Additional config parameters: + + * ``python_updater``: (mandatory) Can only be specified by plugins through the + :ref:`hook `. A Python callable + which performs the update, see below for details. Presence implies ``method: python_updater``. + * ``sleep_a_bit``: Does nothing but block for a configurable ``duration`` and log 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 @@ -269,7 +388,7 @@ Update methods user: foosel repo: OctoPrint method: pip - pip: 'https://github.com/foosel/OctoPrint/archive/{target_version}.zip' + pip: 'https://github.com/OctoPrint/OctoPrint/archive/{target_version}.zip' update_script: '{python} "/path/to/octoprint-update.py" --python="{python}" "{folder}" "{target}"' checkout_folder: /path/to/octoprint/checkout/folder @@ -310,7 +429,71 @@ tracked: repo: OctoPrint-SomePlugin pip: 'https://github.com/someUser/OctoPrint-SomePlugin/archive/{target}.zip' -The same, but tracking all commits pushed to branch ``devel`` (thus allowing +The same, but declaring three release channels "Stable", "Maintenance RCs" (tagged on ``rc/maintenance`` or ``master``, +id ``rc/maintenance``) and "Devel RCs" (tagged on ``rc/maintenance``, ``rc/devel`` or ``master``, id ``rc/devel``), +but with "Stable" active: + +.. code-block:: yaml + + plugins: + softwareupdate: + checks: + some_plugin: + type: github_release + user: someUser + repo: OctoPrint-SomePlugin + stable_branch: + name: Stable + branch: master + commitish: + - master + prerelease_branches: + - name: Maintenance RCs + branch: rc/maintenance + commitish: + - rc/maintenance + - master + - name: Devel RCs + branch: rc/devel + commitish: + - rc/devel + - rc/maintenance + - master + pip: 'https://github.com/someUser/OctoPrint-SomePlugin/archive/{target}.zip' + +And now with "Maintenance RCs" active (note the ``prerelease`` and ``prerelease_channel`` settings): + +.. code-block:: yaml + + plugins: + softwareupdate: + checks: + some_plugin: + type: github_release + user: someUser + repo: OctoPrint-SomePlugin + stable_branch: + name: Stable + branch: master + commitish: + - master + prerelease_branches: + - name: Maintenance RCs + branch: rc/maintenance + commitish: + - rc/maintenance + - master + - name: Devel RCs + branch: rc/devel + commitish: + - rc/devel + - rc/maintenance + - master + prerelease: True + prerelease_channel: rc/maintenance + pip: 'https://github.com/someUser/OctoPrint-SomePlugin/archive/{target}.zip' + +The same plugin again, but tracking all commits pushed to branch ``devel`` (thus allowing "bleeding edge" updates): .. code-block:: yaml @@ -325,6 +508,59 @@ The same, but tracking all commits pushed to branch ``devel`` (thus allowing branch: devel pip: 'https://github.com/someUser/OctoPrint-SomePlugin/archive/{target}.zip' +Single file plugin hosted in a gist ``https://gist.github.com/someUser/somegist`` and updated whenever there are changes: + +.. code-block:: yaml + + plugins: + softwareupdate: + checks: + some_plugin: + type: httpheader + header_name: ETag + url: 'https://gist.github.com/someUser/somegist/raw/some_plugin.py' + method: single_file_plugin + +The same but updated when a ``version.json`` hosted alongside gets updated with a new version can be found at + +.. code-block:: yaml + + plugins: + softwareupdate: + checks: + some_plugin: + type: jsondata + jsondata: 'https://gist.github.com/someUser/somegist/raw/version.json' + url: 'https://gist.github.com/someUser/somegist/raw/some_plugin.py' + method: single_file_plugin + +Note that for gist hosted single file plugins, you need to use the "Raw" install link but should remove the +commit identifier. E.g. ``https://gist.githubusercontent.com///raw/my_plugin.py`` instead of +``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 @@ -385,9 +621,6 @@ octoprint.plugin.softwareupdate.check_config .. code-block:: python - # -*- coding: utf-8 -*- - from __future__ import absolute_import, unicode_literals - def get_update_information(*args, **kwargs): return dict( updateplugindemo=dict( 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 new file mode 100644 index 000000000..bc1ba147a --- /dev/null +++ b/docs/bundledplugins/virtual_printer.rst @@ -0,0 +1,28 @@ +.. _sec-bundledplugins-virtual_printer: + +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 `. + +The virtual printer has been included in OctoPrint ever since the first releases back in 2013, however as of +OctoPrint 1.4.1 it has finally been fully extracted into its own bundled plugin. + +.. _sec-bundledplugins-virtual_printer-configuration: + +Configuring the plugin +---------------------- + +Please refer to :ref:`the development documentation `. + +.. _sec-bundledplugins-virtual_printer-sourcecode: + +Source Code +----------- + +The source of the Virtual Printer plugin is bundled with OctoPrint and can be +found in its source repository under ``src/octoprint/plugins/virtual_printer``. diff --git a/docs/conf.py b/docs/conf.py index 9de6f2608..144c9bd77 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,7 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -# # OctoPrint documentation build configuration file, created by # sphinx-quickstart on Mon Dec 02 17:08:50 2013. # @@ -18,8 +14,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,29 +26,43 @@ 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'] +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), + '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 @@ -65,137 +75,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 --------------------------------------------------- -# on_rtd is whether we are on readthedocs.org, this line of code grabbed from docs.readthedocs.org -on_rtd = os.environ.get('READTHEDOCS', None) == 'True' +import sphinx_rtd_theme -if not on_rtd: # only import and set the theme if we're building docs locally - import sphinx_rtd_theme - html_theme = 'sphinx_rtd_theme' - html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] +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_stylesheet("theme_overrides.css") + 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', @@ -204,47 +213,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 ------------------------------------------------ @@ -253,19 +259,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 10a59aefb..56a0a5fce 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -5,11 +5,12 @@ config.yaml If not specified via the command line, the main configuration file ``config.yaml`` for OctoPrint is expected in its settings folder, which unless defined differently via the command line is located at ``~/.octoprint`` on Linux, at -``%APPDATA%/OctoPrint`` on Windows and at ``~/Library/Application Support/OctoPrint`` on MacOS. If the file is not there, +``%APPDATA%/OctoPrint`` on Windows and at ``~/Library/Application Support/OctoPrint`` on macOS. If the file is not there, you can just create it - it will only get created by OctoPrint once you save settings that deviate from the default 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,16 +24,13 @@ 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) userManager: octoprint.access.users.FilebasedUserManager # The YAML user file to use. If left out defaults to users.yaml in the default configuration folder. - userFile: /path/to/users.yaml + userfile: /path/to/users.yaml # If set to true, will automatically log on clients originating from any of the networks defined in # "localNetworks" as the user defined in "autologinAs". Defaults to false. @@ -74,6 +72,10 @@ Use the following settings to enable access control: # If a remote user is not found, add them. Use this only if all users from the remote system can use OctoPrint. addRemoteUsers: false + # Secret salt used for password hashing, DO NOT TOUCH. If changed you will no longer be able to log in with your + # existing accounts. + salt: someSecretSalt + .. _sec-configuration-config_yaml-api: API @@ -123,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: @@ -146,10 +152,14 @@ appearance or to modify the order and presence of the various UI components: navbar: - settings - systemmenu + - plugin_announcements + - plugin_logging + - plugin_pi_support - login # order of sidebar items sidebar: + - plugin_firmware_check - connection - state - files @@ -158,7 +168,7 @@ appearance or to modify the order and presence of the various UI components: tab: - temperature - control - - gcodeviewer + - plugin_gcodeviewer - terminal - timelapse @@ -175,17 +185,40 @@ appearance or to modify the order and presence of the various UI components: - features - webcam - accesscontrol + - plugin_gcodeviewer - api + - plugin_appkeys - section_octoprint - folders - appearance - - logs + - plugin_logging + - plugin_pluginmanager + - plugin_softwareupdate + - plugin_announcements + - plugin_backup + - plugin_tracking + - plugin_errortracking # order of user settings usersettings: - access - interface + # order of wizards + wizard: + - plugin_backup + - plugin_corewizard_acl + + # order of about dialog entries + about: + - about + - plugin_pi_support + - supporters + - authors + - license + - thirdparty + - plugin_pluginmanager + # order of generic templates generic: [] @@ -222,7 +255,7 @@ appearance or to modify the order and presence of the various UI components: tab: - plugin_helloworld - OctoPrint will then display the tabs in the order ``plugin_helloworld``, ``temperature``, ``control``, ``gcodeviewer``, + OctoPrint will then display the tabs in the order ``plugin_helloworld``, ``temperature``, ``control``, ``plugin_gcodeviewer``, ``terminal``, ``timelapse`` plus any other plugins. @@ -283,180 +316,19 @@ The following settings are only relevant to you if you want to do OctoPrint deve # false, no minification will take place regardless of the minify setting below. bundle: true - # If set to true, OctoPrint will minify its viewmodels (that includes those of plugins). Note: if bundle is + # If set to true, OctoPrint will the core and library javascript assets. Note: if bundle is # set to false, no minification will take place either. minify: true + # If set to true, OctoPrint will also minify the third party plugin javascript assets. Note: if bundle or + # minify are set to false, no minification of the plugin assets will take place either. + minify_plugins: false + # Whether to delete generated web assets on server startup (forcing a regeneration) clean_on_startup: true - # Settings for the virtual printer - virtualPrinter: - - # Whether to enable the virtual printer and include it in the list of available serial connections. - # Defaults to false. - enabled: true - - # Whether to send an additional "ok" after a resend request (like Repetier) - okAfterResend: false - - # Whether to force checksums and line number in the communication (like Repetier), if set to true - # printer will only accept commands that come with linenumber and checksum and throw an error for - # lines that don't. Defaults to false - forceChecksum: false - - # Whether to send "ok" responses with the line number that gets acknowledged by the "ok". Defaults - # to false. - okWithLinenumber: false - - # Number of extruders to simulate on the virtual printer. Map from tool id (0, 1, ...) to temperature - # in °C - numExtruders: 1 - - # Allows pinning certain hotends to a fixed temperature - pinnedExtruders: null - - # Whether to include the current tool temperature in the M105 output as separate T segment or not. - # - # True: > M105 - # < ok T:23.5/0.0 T0:34.3/0.0 T1:23.5/0.0 B:43.2/0.0 - # False: > M105 - # < ok T0:34.3/0.0 T1:23.5/0.0 B:43.2/0.0 - includeCurrentToolInTemps: true - - # Whether to include the selected filename in the M23 File opened response. - # - # True: > M23 filename.gcode - # < File opened: filename.gcode Size: 27 - # False: > M23 filename.gcode - # > File opened - includeFilenameInOpened: true - - # Whether the simulated printer should also simulate a heated bed or not - hasBed: true - - # Whether the simulated printer should also simulate a heated chamber or not - hasChamber: false - - # If enabled, reports the set target temperatures as separate messages from the firmware - # - # True: > M109 S220.0 - # < TargetExtr0:220.0 - # < ok - # > M105 - # < ok T0:34.3 T1:23.5 B:43.2 - # False: > M109 S220.0 - # < ok - # > M105 - # < ok T0:34.3/220.0 T1:23.5/0.0 B:43.2/0.0 - repetierStyleTargetTemperature: false - - # If enabled, uses repetier style resends, sending multiple resends for the same line - # to make sure nothing gets lost on the line - repetierStyleResends: false - - # If enabled, ok will be sent before a commands output, otherwise after or inline (M105) - # - # True: > M20 - # < ok - # < Begin file list - # < End file list - # False: > M20 - # < Begin file list - # < End file list - # < ok - okBeforeCommandOutput: false - - # If enabled, reports the first extruder in M105 responses as T instead of T0 - # - # True: > M105 - # < ok T:34.3/0.0 T1:23.5/0.0 B:43.2/0.0 - # False: > M105 - # < ok T0:34.3/0.0 T1:23.5/0.0 B:43.2/0.0 - smoothieTemperatureReporting: false - - # Whether M20 responses will include filesize or not - # - # True: - # False: - extendedSdFileList: false - - # Forced pause for retrieving from the outgoing buffer - throttle: 0.01 - - # Whether to send "wait" responses every "waitInterval" seconds when serial rx buffer is empty - sendWait: false - - # Interval in which to send "wait" lines when rx buffer is empty - waitInterval: 1 - - # Size of the simulated RX buffer in bytes, when it's full a send from OctoPrint's - # side will block - rxBuffer: 64 - - # Size of simulated command buffer, number of commands. If full, buffered commands will block - # until a slot frees up - commandBuffer: 4 - - # Whether to support the M112 command with simulated kill - supportM112: true - - # Whether to send messages received via M117 back as "echo:" lines - echoOnM117: true - - # Whether to simulate broken M29 behaviour (missing ok after response) - brokenM29: true - - # Whether F is supported as individual command - supportF: false - - # Firmware name to report (useful for testing firmware detection) - firmwareName: Virtual Marlin 1.0 - - # Simulate a shared nozzle - sharedNozzle: false - - # Send "busy" messages if busy processing something - sendBusy: false - - # Simulate a reset on connect - simulateReset: true - - # Lines to send on simulated reset - resetLines: - - start - - "Marlin: Virtual Marlin!" - - "SD card ok" - - # Initial set of prepared oks to use instead of regular ok (e.g. to simulate - # mis-sent oks). Can also be filled at runtime via the debug command prepare_ok - preparedOks: [] - - # Format string for ok response. - # - # Placeholders: - # - lastN: last acknowledged line number - # - buffer: empty slots in internal command buffer - # - # Example format string for "extended" ok format: - # ok N{lastN} P{buffer} - okFormatString: ok - - # Format string for M115 output. - # - # Placeholders: - # - firmare_name: The firmware name as defined in firmwareName - m115FormatString: "FIRMWARE_NAME: {firmware_name} PROTOCOL_VERSION:1.0" - - # Whether to include capability report in M115 output - m115ReportCapabilites: false - - # Capabilities to report if capability report is enabled - capabilities: - AUTOREPORT_TEMP: true - - # Simulated ambient temperature in °C - ambientTemperature: 21.3 + # enable or disable the loading animation + showLoadingAnimation: true .. _sec-configuration-config_yaml-estimation: @@ -935,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 @@ -1022,6 +897,25 @@ Use the following settings to configure the server: - 192.168.1.254 - 192.168.23.42 + # Whether to allow OctoPrint to be embedded in a frame or not. Note that depending on your setup you might + # have to set SameSite to None, Secure to true and serve OctoPrint through a reverse proxy that enables https + # for cookies and thus logging in to work + allowFraming: true + + # Settings for further configuration of the cookies that OctoPrint sets (login, remember me, ...) + cookies: + # SameSite setting to use on the cookies. Possible values are None, Lax and Strict. Defaults to None but + # be advised that browsers will soon force this to Lax unless also being set as Secure and served over + # https, which will cause issues with embedding OctoPrint in frames. + # + # See also https://www.chromestatus.com/feature/5088147346030592, + # https://www.chromestatus.com/feature/5633521622188032 and issue #3482 + samesite: lax + + # Whether to set the Secure flag to true on cookies. Defaults to false. Only set to true if you are running + # OctoPrint behind a reverse proxy taking care of SSL termination. + secure: false + # Settings for file uploads to OctoPrint, such as maximum allowed file size and # header suffixes to use for streaming uploads. OctoPrint does some nifty things internally in # order to allow streaming of large file uploads to the application rather than just storing @@ -1055,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 @@ -1123,9 +1023,24 @@ Use the following settings to configure the server: * ``X-Scheme``: should contain your custom URL scheme to use (if different from ``http``), e.g. ``https`` If you use these headers OctoPrint will work both via the reverse proxy as well as when called directly. Take a look - `into OctoPrint's wiki `_ for some + `into OctoPrint's wiki `_ for some examples on how to configure this. +.. note:: + + If you want to embed OctoPrint in a frame, you'll need to set ``allowFraming`` to ``true`` or your browser will + prevent this. + + In future browser builds you will also have to make sure you frame is on the same domain as OctoPrint or that + OctoPrint is served via https through a reverse proxy and has set ``cookies.secure`` to ``true`` or your browser + will refuse to persist cookies and logging in will not work. + + See also `Cookies default to SameSite=Lax `_ and + `Reject insecure SameSite=None cookies `_ as well as + `this ticket `_, + and `this twitter thread `_ on why OctoPrint cannot + solve this on its own/ship with https that doesn't cause scary warnings in your browser. + .. _sec-configuration-config_yaml-slicing: Slicing @@ -1222,6 +1137,8 @@ Use `Javascript regular expressions `_. +You can find more information on the used logging handlers in the Python documentation on +:py:mod:`logging.handlers`. Changing logging formatters --------------------------- @@ -97,4 +97,4 @@ expressed in YAML as follows: format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s" The possible keys for the logging format can be found in the -`Python documentation on LogRecord attributes `_. +:ref:`Python documentation on LogRecord attributes `. diff --git a/docs/development/branches.rst b/docs/development/branches.rst new file mode 100644 index 000000000..57ec18158 --- /dev/null +++ b/docs/development/branches.rst @@ -0,0 +1,75 @@ +.. _sec-development-branches: + +OctoPrint's branching model +=========================== + +There are three main branches in OctoPrint: + +``master`` + The master branch always contains the current stable release plus any changes + since made to *documentation*, *CI related tests* or *Github meta files*. OctoPrint's actual + code will only be modified on new releases. Will have a version number following + the scheme ``..`` (e.g. ``1.5.1``). +``maintenance`` + Improvements and fixes of the current release that make up + the next release go here. More or less continuously updated. You can consider + this a preview of the next release version. It should be very stable at all + times. Anything you spot in here helps tremendously with getting a rock solid + next stable release, so if you want to help out development, running the + ``maintenance`` branch and reporting back anything you find is a very good way + to do that. Will usually have a version number following the scheme + ``..<0>.dev`` for an OctoPrint version of ``..`` + (e.g. ``1.5.0.dev114``). +``devel`` + Ongoing development of what will go into the next big + release (MAJOR version number increases) will happen on this branch. Usually + kept stable, sometimes stuff can break though. Backwards incompatible changes will + be encountered here. Can be considered the "bleeding edge". Will usually have a version + number following the scheme ``.<0>.0.dev`` for a current + OctoPrint version of ``..`` (e.g. ``2.0.0.dev123``). + +There are couple more RC and staging branches that see regular use: + +``staging/bugfix`` + Any preparation for potential bugfix releases takes place here. + Version number follows the scheme ``..`` (e.g. ``1.5.1``) for a current release + of ``..``. +``rc/maintenance`` + This branch is reserved for future releases that have graduated from + the ``maintenance`` branch and are now being pushed on the "Maintenance" + pre release channel for further testing. Version number follows the scheme + ``..rc`` (e.g. ``1.5.0rc1``). +``staging/maintenance`` + Any preparation for potential follow-up RCs takes place here. + Version number follows the scheme ``..rc.dev`` (e.g. + ``1.5.0rc2.dev3``) for a current Maintenance RC of ``..``. +``rc/devel`` + This branch is reserved for future releases that have graduated from + the ``devel`` branch and are now being pushed on the "Devel" pre release channel + for further testing. Version number follows the scheme ``.0.0rc`` (e.g. ``2.0.0rc1``) + for a current stable OctoPrint version of ``..``. +``staging/devel`` + Any preparation for potential follow-up Devel RCs takes place + here. Version number follows the scheme ``.0.0rc.dev`` (e.g. + ``2.0.0rc2.dev12``) for a current Devel RC of ``.0.0rc``. + +Additionally, from time to time you might see other branches pop up in the repository. +Those usually have one of the following prefixes: + +``bug/...`` + Fixes under development that are to be merged into the ``staging/bugfix`` + and later the ``master`` branch. +``fix/...`` + Fixes under development that are to be merged into the ``maintenance`` + and ``devel`` branches. +``improve/...`` + Improvements under development that are to be merged into the + ``maintenance`` and ``devel`` branches. +``dev/...`` or ``feature/...`` + New functionality under development that is to be merged + into the ``devel`` branch. + +There are also a few older development branches that are slowly being migrated or deleted. + +All these branches and branch patterns are set up to automatically get a correct :ref:`version number ` +generated through versioneer and thus should also be adhered to during development. diff --git a/docs/development/environment.rst b/docs/development/environment.rst index 2fa09aac3..e286e8010 100644 --- a/docs/development/environment.rst +++ b/docs/development/environment.rst @@ -13,71 +13,91 @@ below. * Prerequisites: - * `Python 2.7 `_ including ``pip``, ``setuptools`` and ``virtualenv`` - * `Python 3.7 `_ including ``pip``, ``setuptools`` and ``virtualenv`` + * `Python 3.8 `_ including ``pip``, ``setuptools`` and ``virtualenv`` * `Git `_ - * Checkout the OctoPrint sources from their Git repository: - * ``git clone -b devel https://github.com/foosel/OctoPrint.git`` + * Checkout the OctoPrint sources from their Git repository: + + * ``git clone https://github.com/OctoPrint/OctoPrint.git`` + * Enter the checked out source folder: ``cd OctoPrint`` - * Create virtual environments in the checked out source folder for both Python 2.7 and Python 3.7 to use for - installing and running OctoPrint and its dependencies (this avoids potential versioning issues for the dependencies - with system wide installed instances): - * PY2: ``virtualenv --python=python2 venv2`` - * PY3: ``virtualenv --python=python3 venv3`` - * Activate one of the virtual environments: - * PY2: ``source venv2/bin/activate`` (Linux, MacOS) or ``source venv2/Scripts/activate`` (Git Bash under Windows, see below) - * PY3: ``source venv3/bin/activate`` (Linux, MacOS) or ``source venv3/Scripts/activate`` (Git Bash under Windows, see below) + * Create virtual environments in the checked out source folder for both Python 2 and Python 3 to use for + installing and running OctoPrint and its dependencies. Creating virtual environments avoids potential versioning + issues for the dependencies with system wide installed instances: + + * ``virtualenv --python=python3 venv`` + + .. note:: + + This assumes that `python3` is a binary available directly on your ``PATH``. If your Python 3 + binary cannot be found on your ``PATH`` like this you'll need to specify the full path to it here, + e.g. ``virtualenv --python=/path/to/python3/bin/python venv`` + + * Activate one of the virtual environments (the Python 3 venv should be considered the + primary one at this point): + + * ``source venv/bin/activate`` (Linux, macOS) or ``source venv/Scripts/activate`` (Git Bash under Windows, see below) + * Update ``pip`` in the virtual environment: + * ``pip install --upgrade pip`` + * Install OctoPrint in `"editable" mode `_, - including its regular *and* development and plugin development dependencies: - * ``pip install -e .[develop,plugins]`` + including its regular *and* development and plugin development dependencies: + + * ``pip install -e '.[develop,plugins,docs]'`` + + * Set up the pre-commit hooks that make sure any changes you do adhere to the styling rules: + + * ``pre-commit install`` + + * Tell ``git`` where to find the file with revisions to exclude for ``git blame``: + + * ``git config blame.ignoreRevsFile .git-blame-ignore-revs`` When the virtual environment is activated you can then: * run the OctoPrint server via ``octoprint serve`` - * run the test suite from the checked out source folder via ``nosetests --with-doctest`` - * build the documentation from the ``docs`` sub folder of the checked out sources via ``sphinx-build -b html . _build`` + * run the test suite from the checked out source folder via ``pytest`` + * trigger the pre-commit check suite manually from the checked out source folder via + ``pre-commit run --hook-stage manual --all-files`` To switch the activated virtual environment, simply activate the new environment as described above. To deactivate the virtual environment and return to the system's default Python: ``deactivate``. +If you also want to be able to build the documentation that resides in the ``docs`` subfolder, you need to activate +the *Python 3* environment and install the docs dependencies as well: + + * ``source venv3/bin/activate`` (Linux, macOS) or ``source venv3/Scripts/activate`` (Git Bash under Windows, see below) + * ``pip install -e .[develop,plugins,docs]`` + +Go to the directory `docs` and you can then build the documentation: + + * ``sphinx-build -b html . _build`` + +The documentation will be available in the newly created ``_build`` directory. You can simply browse it locally by opening ``index.html`` .. _sec-development-environment-source-linux: Linux ..... -.. todo:: - - This guide is not yet adapted to the concurrent use of Python 2.7 and 3.7 environments during development. - This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different location, please substitute accordingly. -First make sure you have python including its header files, pip, setuptools, virtualenv, git and some build requirements +First make sure you have python 2 and 3 including their header files, pip, setuptools, virtualenv, git and some build requirements installed: * On apt based distributions (e.g. Debian, Ubuntu, ...): .. code-block:: none - sudo apt-get install python python-pip python-dev python-setuptools python-virtualenv git libyaml-dev build-essential - - * On zypper based distributions (example below for SLES 12 SP2): - - .. code-block:: none - - sudo zypper ar https://download.opensuse.org/repositories/devel:/languages:/python/SLE_12_SP2/ python_devel - sudo zypper ref - sudo zypper in python python-pip python-devel python-setuptools python-virtualenv git libyaml-devel - sudo zypper in -t pattern Basis-Devel + sudo apt-get install python3 python3-pip python3-dev python3-setuptools python3-virtualenv python3 python3-virtualenv python3-dev git libyaml-dev build-essential .. todo:: - Using a Linux distribution that doesn't use ``apt`` or ``zypper``? Please send a - `Pull Request `_ to get the necessary + Using a Linux distribution that doesn't use ``apt``? Please send a + `Pull Request `_ to get the necessary steps into this guide! Then: @@ -85,36 +105,35 @@ Then: .. code-block:: none cd ~/devel - git clone -b devel https://github.com/foosel/OctoPrint.git + git clone https://github.com/OctoPrint/OctoPrint.git cd OctoPrint - virtualenv venv + virtualenv --python=python3 venv source ./venv/bin/activate pip install --upgrade pip - pip install -e .[develop,plugins] + pip install -e .[develop,plugins,docs] + pre-commit install + git config blame.ignoreRevsFile .git-blame-ignore-revs -You can then start OctoPrint via ``~/devel/OctoPrint/venv/bin/octoprint`` or just ``octoprint`` if you activated the virtual -environment. +You can then start OctoPrint via ``octoprint`` after activating one of the two virtual environments. .. _sec-development-environment-windows: Windows ....... -.. todo:: - - This guide is not yet adapted to the concurrent use of Python 2.7 and 3.7 environments during development. - This assumes you'll host your OctoPrint development checkout at ``C:\Devel\OctoPrint``. If you want to use a different location, please substitute accordingly. First download & install: - * `Python 2.7.15 Windows x86 MSI installer `_ + * `The current Python 3.8 Windows x86 executable installer `_ * make sure to have the installer add Python to the ``PATH`` and have it install ``pip`` too + * it's recommended to install Python 2.7 into ``C:\Python27`` and Python 3 into ``C:\Python38`` - if you select + different install locations please substitute accordingly - * `Microsoft Visual C++ Compiler for Python 2.7 `_ - * `Git for Windows `_ + * `Build Tools for Visual Studio 2019 `_ + * `Git for Windows `_ Open the Git Bash you just installed and in that: @@ -122,12 +141,14 @@ Open the Git Bash you just installed and in that: pip install virtualenv cd /c/Devel - git clone https://github.com/foosel/OctoPrint.git + git clone https://github.com/OctoPrint/OctoPrint.git cd OctoPrint - virtualenv venv + virtualenv --python=C:\Python38\python.exe venv source ./venv/Scripts/activate pip install --upgrade pip - pip install -e .[develop,plugins] + pip install -e .[develop,plugins,docs] + pre-commit install + git config blame.ignoreRevsFile .git-blame-ignore-revs .. _sec-development-environment-mac: @@ -136,12 +157,14 @@ Mac OS X .. note:: - This guide is based on the `Setup Guide for Mac OS X on OctoPrint's wiki `_. + This guide is based on the `Setup Guide for Mac OS X on OctoPrint's Community Forum `_. Please report back if it works for you, due to lack of access to a Mac I cannot test it myself. Thanks. .. todo:: - This guide is not yet adapted to the concurrent use of Python 2.7 and 3.7 environments during development. + This guide is not yet adapted to the concurrent use of Python 2 and 3 environments during development. Please send a + `Pull Request `_ to get the necessary + steps into this guide! This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different location, please substitute accordingly. @@ -169,26 +192,24 @@ You'll need a user account with administrator privileges. .. code-block:: none cd ~/devel - git clone https://github.com/foosel/OctoPrint.git + git clone https://github.com/OctoPrint/OctoPrint.git cd OctoPrint virtualenv venv source venv/bin/activate pip install --upgrade pip pip install -e .[develop,plugins] + pre-commit install + git config blame.ignoreRevsFile .git-blame-ignore-revs .. _sec-development-environment-ides: IDE Setup --------- -.. todo:: - - This guide is not yet adapted to the concurrent use of Python 2.7 and 3.7 environments during development. - .. todo:: Using another IDE than the ones below? Please send a - `Pull Request `_ to get the necessary + `Pull Request `_ to get the necessary steps into this guide! .. _sec-development-environment-ides-pycharm: @@ -197,47 +218,80 @@ PyCharm ....... - "File" > "Open ...", select OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``) - - "File" > "Settings ..." > "Project: OctoPrint" > "Project Interpreter" > "Add local ...", select OctoPrint venv - folder (e.g. ``~/devel/OctoPrint/venv`` or ``C:\Devel\OctoPrint\venv``) + - Register virtual environments: + + - **(Linux, Windows)** "File" > "Settings ..." > "Project: OctoPrint" > "Project Interpreter" > "Add local ...", + select OctoPrint ``venv`` folder (e.g. ``~/devel/OctoPrint/venv`` or ``C:\Devel\OctoPrint\venv``). + - **(macOS)** "PyCharm" > "Preferences ..." > "Project: OctoPrint" > "Project Interpreter" > "Add ..." > + "Virtualenv Environment > "Existing Environment", select OctoPrint ``venv`` folder (e.g. ``~/devel/OctoPrint/venv``). + - Right click "src" in project tree, mark as source folder - Add Run/Debug Configuration, select "Python": * Name: OctoPrint server - * Script: path to ``run`` in the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint/run`` or ``C:\Devel\OctoPrint\run``) - * Script parameters: ``serve --debug`` + * Module name: ``octoprint`` + * Parameters: ``serve --debug`` * Project: ``OctoPrint`` - * Python interpreter: the ``venv`` local virtual environment + * Python interpreter: Project Default * Working directory: the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``) - * If you want dependencies to auto-update on run if necessary: "Before Launch" > "+" > "Run external tool" > "+" + * If you want build artifacts to be cleaned up on run (recommended): "Before Launch" > "+" > "Run external tool" > "+" - * Name: Update OctoPrint dependencies - * Program: ``$PyInterpreterDirectory$/pip`` (or ``$PyInterpreterDirectory$/pip.exe`` on Windows) - * Parameters: ``install -e .[develop,plugins]`` + * Name: Clean build directory + * Program: ``$ModuleSdkPath$`` + * Parameters: ``setup.py clean`` * Working directory: ``$ProjectFileDir$`` - - Add Run/Debug Configuration, select "Python tests" and therein "Nosetests": + * If you want dependencies to auto-update on run if necessary (recommended): "Before Launch" > "+" > "Run external tool" > "+" - * Name: OctoPrint nosetests - * Target: Path, ``.`` + * Name: Update OctoPrint dependencies + * Program: ``$ModuleSdkPath$`` + * Parameters: ``-m pip install -e .[develop,plugins]`` + * Working directory: ``$ProjectFileDir$`` + + Note that sadly that seems to cause some hiccups on current PyCharm versions due to ``$PyInterpreterDirectory$`` + being empty sometimes, so if this fails to run on your installation, you should update your dependencies manually + for now. + + - Add Run/Debug Configuration, select "Python tests" and therein "pytest": + + * Name: OctoPrint tests + * Target: Custom * Project: ``OctoPrint`` - * Python interpreter: the ``venv`` local virtual environment + * Python interpreter: Project Default * Working directory: the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``) * Just like with the run configuration for the server you can also have the dependencies auto-update on run of the tests, see above on how to set this up. - - Add Run/Debug Configuration, select "Python docs" and therein "Sphinx task" + - Add Run/Debug Configuration, select "Python": * Name: OctoPrint docs - * Command: ``html`` - * Input: the ``docs`` folder in the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint/docs`` or - ``C:\Devel\OctoPrint\docs``) - * Output: the ``docs/_build`` folder in the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint/docs/_build`` or - ``C:\Devel\OctoPrint\docs\_build``) + * Module name: ``sphinx.cmd.build`` + * Parameters: ``-v -T -E ./docs ./docs/_build -b html`` * Project: ``OctoPrint`` - * Python interpreter: the ``venv`` local virtual environment + * Python interpreter: ``venv`` environment + * Working directory: the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``) * Just like with the run configuration for the server you can also have the dependencies auto-update when building the documentation, see above on how to set this up. + Note that this requires you to also have installed the additional ``docs`` dependencies into the Python 3 venv as + described above via ``pip install -e .[develop,plugins,docs]``. + + - Settings > Tools > File Watchers (you might have to enable this, it's a bundled plugin), add new: + + * Name: pre-commit + * File type: Python + * Scope: Module 'OctoPrint' + * Program: ``$PyInterpreterDirectory$/bin/pre-commit`` (Linux) or ``$PyInterpreterDirectory$/Scripts/pre-commit`` (Windows) + * Arguments: ``run --hook-stage manual --files $FilePath$`` + * Output paths to refresh: ``$FilePath$`` + * Working directory: ``$ProjectFileDir$`` + * disable "Auto-save edited files to trigger the watched" + * enable "Trigger the watched on external changes" + +To switch between Python 2 and 3, all you need to do now is change the Project Default Interpreter and restart +OctoPrint. On current PyCharm versions you can do that right from a small selection field in the footer of the IDE. +Otherwise go through Settings. + .. note:: Make sure you are running a PyCharm version of 2016.1 or later, or manually fix diff --git a/docs/development/index.rst b/docs/development/index.rst index 8b3038592..249434d25 100644 --- a/docs/development/index.rst +++ b/docs/development/index.rst @@ -7,5 +7,11 @@ Development .. toctree:: :maxdepth: 3 + versioning.rst + branches.rst environment.rst virtual_printer.rst + request-profiling.rst + +If you are interested in contributing code to OctoPrint, first of all: Thank you! Please make sure to read the +`Contribution Guidelines `_! diff --git a/docs/development/request-profiling.rst b/docs/development/request-profiling.rst new file mode 100644 index 000000000..a60c82a68 --- /dev/null +++ b/docs/development/request-profiling.rst @@ -0,0 +1,20 @@ +.. _sec-request-profiling: + +Profiling requests +================== + +Once you have a development environment set up, you will need to launch +OctoPrint using ``serve --debug`` as parameters. + +At this point, you are able to make the exact same requests as before. To +profile a specific request, just add ``?perfprofile`` or ``&perfprofile`` to the +request parameters. The request will be rendered as usual, but you will receive +an html document with the profiling results instead of the contents of the +response. + +Errors +------ + +If you receive a ``500: Internal Server Error`` and a ``ModuleNotFoundError: No +module named 'pyinstrument'`` in the console, you didn't install development +dependencies. Do that now using ``pip install -e '.[develop]'``. diff --git a/docs/development/versioning.rst b/docs/development/versioning.rst new file mode 100644 index 000000000..2d9dab4c4 --- /dev/null +++ b/docs/development/versioning.rst @@ -0,0 +1,31 @@ +.. _sec-development-versions: + +OctoPrint's versioning strategy +=============================== + +OctoPrint's version numbers follow `PEP440 `_, with a version format of +**MAJOR.MINOR.PATCH** following the contract of `semantic versioning `_. + +The **PATCH** version number will increase in case of hotfix releases [#f1]_. +Releases that only change the patch number indicate that they only contain bug fixes, and usually +only hotfixes at that. Example: ``1.5.0`` to ``1.5.1``. + +The **MINOR** version number increases with releases that add new functionality while maintaining +backwards compatibility on the documented APIs (both internal and external). Example: ``1.4.x`` to ``1.5.0``. + +Finally, the **MAJOR** version number increases if there are breaking API changes that concern any of the +documented interfaces (REST API, plugin interfaces, ...). Example: ``1.x.y`` to ``2.0.0``. + +OctoPrint's version numbers are automatically generated using a customized version of +`versioneer `_ and depend on the selected git branch, nearest +git tag and commits. Unless a git tag is used for version number determination, the version number will +also contain the git hash within the local version identifier to allow for an exact determination of the +active code base (e.g. ``1.2.9.dev68+g46c7a9c``). Additionally, instances with active uncommitted changes +will contain ``.dirty`` in the local version identifier. + +.. rubric:: Footnotes + +.. [#f1] Up until 1.4.2, the PATCH version segment was the one increasing most often + due to OctoPrint's maintenance releases but with 1.5.0 this will *fully* adhere + to the concepts in semantic versioning mandating only bug fixes in patch releases. + Maintenance releases will henceforth increase the MINOR segment. diff --git a/docs/development/virtual_printer.rst b/docs/development/virtual_printer.rst index 85d35c50e..5e7a31e4d 100644 --- a/docs/development/virtual_printer.rst +++ b/docs/development/virtual_printer.rst @@ -3,7 +3,7 @@ Setting up the virtual printer for debugging ============================================ -OctoPrint includes, by default, a virtual printer plugin. This plugin allows you to debug OctoPrint's serial +OctoPrint includes, by default, a :ref:`virtual printer plugin `. This plugin allows you to debug OctoPrint's serial communication without connecting to an actual printer. Furthermore, it is possible to create certain edge conditions that may be hard to reproduce with a real printer. @@ -12,33 +12,219 @@ that may be hard to reproduce with a real printer. Enabling the virtual printer ---------------------------- -The virtual printer is enabled by editing OctoPrint's config.yaml file. Details on the configuration file can -be found in the full :ref:`config.yaml documentation `. - -The steps to take are as follows: - -* Find config.yaml in the OctoPrint settings folder. Usually in ``~/.octoprint`` on Linux, in ``%APPDATA%/OctoPrint`` on Windows and in ``~/Library/Application Support/OctoPrint`` on MacOS. -* Add or extend the ``devel`` section with: - -.. code-block:: yaml - - devel: - virtualPrinter: - enabled: true - -* Restart OctoPrint. -* In the connection panel, a new option will appear in the Serial Port dropdown labeled ``VIRTUAL``. -* Select this option and click ``connect``. -* The virtual printer is now active. +The virtual printer can be enabled through its Settings pane. .. _sec-development-virtual-printer-config: Virtual printer configuration options ------------------------------------- -The config.yaml file has many configuration options for the virtual printer that allow you to fine-tune its behavior. +There many configuration options via ``config.yaml`` for the virtual printer that allow you to fine-tune its behavior: -Please see the relevant :ref:`config.yaml section ` for the full details. +.. code-block:: yaml + + plugins: + + # Settings for the virtual printer + virtual_printer: + + # Whether to enable the virtual printer and include it in the list of available serial connections. + # Defaults to false. + enabled: true + + # Whether to send an additional "ok" after a resend request (like Repetier) + okAfterResend: false + + # Whether to force checksums and line number in the communication (like Repetier), if set to true + # printer will only accept commands that come with linenumber and checksum and throw an error for + # lines that don't. Defaults to false + forceChecksum: false + + # Whether to send "ok" responses with the line number that gets acknowledged by the "ok". Defaults + # to false. + okWithLinenumber: false + + # Number of extruders to simulate on the virtual printer. Map from tool id (0, 1, ...) to temperature + # in °C + numExtruders: 1 + + # Allows pinning certain hotends to a fixed temperature + pinnedExtruders: null + + # Whether to include the current tool temperature in the M105 output as separate T segment or not. + # + # True: > M105 + # < ok T:23.5/0.0 T0:34.3/0.0 T1:23.5/0.0 B:43.2/0.0 + # False: > M105 + # < ok T0:34.3/0.0 T1:23.5/0.0 B:43.2/0.0 + includeCurrentToolInTemps: true + + # Whether to include the selected filename in the M23 File opened response. + # + # True: > M23 filename.gcode + # < File opened: filename.gcode Size: 27 + # False: > M23 filename.gcode + # > File opened + includeFilenameInOpened: true + + # Whether the simulated printer should also simulate a heated bed or not + hasBed: true + + # Whether the simulated printer should also simulate a heated chamber or not + hasChamber: false + + # If enabled, reports the set target temperatures as separate messages from the firmware + # + # True: > M109 S220.0 + # < TargetExtr0:220.0 + # < ok + # > M105 + # < ok T0:34.3 T1:23.5 B:43.2 + # False: > M109 S220.0 + # < ok + # > M105 + # < ok T0:34.3/220.0 T1:23.5/0.0 B:43.2/0.0 + repetierStyleTargetTemperature: false + + # If enabled, uses repetier style resends, sending multiple resends for the same line + # to make sure nothing gets lost on the line + repetierStyleResends: false + + # If enabled, ok will be sent before a commands output, otherwise after or inline (M105) + # + # True: > M20 + # < ok + # < Begin file list + # < End file list + # False: > M20 + # < Begin file list + # < End file list + # < ok + okBeforeCommandOutput: false + + # If enabled, reports the first extruder in M105 responses as T instead of T0 + # + # True: > M105 + # < ok T:34.3/0.0 T1:23.5/0.0 B:43.2/0.0 + # False: > M105 + # < ok T0:34.3/0.0 T1:23.5/0.0 B:43.2/0.0 + smoothieTemperatureReporting: 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 + + # Whether to send "wait" responses every "waitInterval" seconds when serial rx buffer is empty + sendWait: false + + # Interval in which to send "wait" lines when rx buffer is empty + waitInterval: 1 + + # Size of the simulated RX buffer in bytes, when it's full a send from OctoPrint's + # side will block + rxBuffer: 64 + + # Size of simulated command buffer, number of commands. If full, buffered commands will block + # until a slot frees up + commandBuffer: 4 + + # Whether to support the M112 command with simulated kill + supportM112: true + + # Whether to send messages received via M117 back as "echo:" lines + echoOnM117: true + + # Whether to simulate broken M29 behaviour (missing ok after response) + brokenM29: true + + # Whether F is supported as individual command + supportF: false + + # Firmware name to report (useful for testing firmware detection) + firmwareName: Virtual Marlin 1.0 + + # Simulate a shared nozzle + sharedNozzle: false + + # Send "busy" messages if busy processing something + sendBusy: false + + # Simulate a reset on connect + simulateReset: true + + # Lines to send on simulated reset + resetLines: + - start + - "Marlin: Virtual Marlin!" + - "SD card ok" + + # Initial set of prepared oks to use instead of regular ok (e.g. to simulate + # mis-sent oks). Can also be filled at runtime via the debug command prepare_ok + preparedOks: [] + + # Format string for ok response. + # + # Placeholders: + # - lastN: last acknowledged line number + # - buffer: empty slots in internal command buffer + # + # Example format string for "extended" ok format: + # ok N{lastN} P{buffer} + okFormatString: ok + + # Format string for M115 output. + # + # Placeholders: + # - firmare_name: The firmware name as defined in firmwareName + m115FormatString: "FIRMWARE_NAME: {firmware_name} PROTOCOL_VERSION:1.0" + + # Whether to include capability report in M115 output + m115ReportCapabilites: false + + # Capabilities to report if capability report is enabled + capabilities: + AUTOREPORT_TEMP: true + + # Simulated ambient temperature in °C + ambientTemperature: 21.3 + + # Response to M105 when there is a target + # Placeholders: + # - heater: The heater id (eg. T0, T1, B) + # - actual: The actual temperature of the heater + # - target: The target temperature of heater + m105TargetFormatString: {heater}:{actual:.2f}/ {target:.2f} + + # Response to M105 when there is no target + # Placeholders: + # - heater: The heater id (eg. T0, T1, B) + # - actual: The actual temperature of the heater + m105NoTargetFormatString: {heater}:{actual:.2f} + + # Enable virtual EEPROM + # If enabled, a file `eeprom.json` will be created in the plugin data folder + # to enable settings persistence across connections. Enables M500/1/2/4 commmands + # And a selection of other settings commands. Responses modeled on Marlin 2.0 + enable_eeprom: true + + # Support M503 + support_m503: true + + # Resend ratio to simulate noise on the line + resend_ratio: 0 .. _sec-development-virtual-printer-log: @@ -46,7 +232,7 @@ Log file -------- Once activated, the virtual printer will log all serial communication in the ``plugin_virtual_printer_serial.log`` file -that can be found in the OctoPrint settings folder. +that can be found in the OctoPrint logs folder. .. _sec-development-virtual-printer-debug: diff --git a/docs/events/index.rst b/docs/events/index.rst index 791f33d0f..71a55d68e 100644 --- a/docs/events/index.rst +++ b/docs/events/index.rst @@ -100,20 +100,53 @@ Shutdown The server is shutting down. ClientOpened - A client has connected to the web server. + A client has connected to the push socket. Payload: - * ``remoteAddress``: the remote address (IP) of the client that connected + * ``remoteAddress``: the remote address (IP) of the client that connected. On the push socket only available with + a valid login session. **Note:** Name changed in version 1.1.0 -ClientClosed - A client has disconnected from the webserver + .. versionchanged:: 1.1.0 + .. versionchanged:: 1.4.0 + +ClientAuthed + A client has authenticated a user session on the push socket. Payload: - * ``remoteAddress``: the remote address (IP) of the client that disconnected + * ``remoteAddress``: the remote address (IP) of the client that authed. On the push socket only available with a + 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. + + Payload: + + * ``remoteAddress``: the remote address (IP) of the client that disconnected. On the push socket only available + with a valid login session. + +UserLoggedIn + A user logged in. On the push socket only available with a valid login session with admin rights. + + Payload: + + * ``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 @@ -123,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 @@ -131,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. @@ -144,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 @@ -151,6 +190,9 @@ Error An unrecoverable error has been encountered, either as reported by the firmware (e.g. a thermal runaway) or on the connection. + Note that this event will not fire for error messages from the firmware that are handled (and as such recovered from) + either by OctoPrint or a plugin. + Payload: * ``error``: the error string @@ -164,23 +206,30 @@ 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 ------------- Upload - A file has been uploaded through the web interface. + A file has been uploaded through the :ref:`REST API `. Payload: * ``name``: the file's name * ``path``: the file's path within its storage location * ``target``: the target storage location to which the file was uploaded, either ``local`` or ``sdcard`` + * ``select``: whether the file will immediately be selected, as requested on the API by the corresponding parameter + * ``print``: whether the file will immediately start printing, as requested on the API by the corresponding parameter + * ``userdata``: optional ``userdata`` if provided on the API, will only be present if supplied in the upload request .. deprecated:: 1.3.0 * ``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. @@ -196,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. @@ -210,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. @@ -223,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. @@ -235,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. @@ -249,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. @@ -263,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. @@ -277,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. @@ -291,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. @@ -304,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. @@ -335,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. @@ -353,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. @@ -370,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. @@ -383,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. @@ -413,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. @@ -442,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. @@ -459,6 +537,36 @@ 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 + +GcodeScript${ScriptName}Running + A custom :ref:`GCODE script ` has started running. + + Payload: + + * ``name``: the file's name + * ``path``: the file's path within its storage location + * ``origin``: the origin storage location of the file, either ``local`` or ``sdcard`` + * ``size``: the file's size in bytes (if available) + * ``owner``: the user who started the print job (if available) + * ``time``: the time needed for the print, in seconds (float) + + .. versionadded:: 1.6.0 + +GcodeScript${ScriptName}Finished + A custom :ref:`GCODE script ` has finished running. + + Payload: + + * ``name``: the file's name + * ``path``: the file's path within its storage location + * ``origin``: the origin storage location of the file, either ``local`` or ``sdcard`` + * ``size``: the file's size in bytes (if available) + * ``owner``: the user who started the print job (if available) + * ``time``: the time needed for the print, in seconds (float) + + .. versionadded:: 1.6.0 + .. _sec-events-available_events-gcode_processing: GCODE processing @@ -513,6 +621,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. @@ -522,6 +632,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 @@ -547,6 +685,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. @@ -639,6 +779,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. @@ -647,6 +789,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. @@ -655,6 +799,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 @@ -666,10 +812,12 @@ 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 --------- +--------------- PrinterProfileModified A printer profile was modified. @@ -677,3 +825,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 06bcc253e..23bf90b75 100644 --- a/docs/features/accesscontrol.rst +++ b/docs/features/accesscontrol.rst @@ -3,8 +3,31 @@ Access Control ============== -When Access Control is enabled, anonymous users (not logged in) will only see -the read-only parts of the UI which are the following: +.. versionchanged:: 1.5.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. + +The default permissions will deny any kind of access to anonymous (not logged in) +users out of the box. + +.. warning:: + + Please note that OctoPrint does *not* control the webcam and merely embeds it, and + thus also cannot limit access to it. If an anonymous user correctly guesses the + webcam URL, they will thus be able to see it. + +Upon first start a configuration wizard is provided which allows configuration +of the first administrator account to be used for OctoPrint. After initial setup, +you can then create more users and groups under Settings > Access Control for +customisation of the granular permission system. + +The predefined "Guests" group can be used to configure default permissions of anonymous +users, that is those who have not logged in. By default, no permissions are granted to +these users. + +A predefined "Read-only Access" group with no users is configured which by default grants +read-only access to the following parts of the UI to any users assigned to this group: * printer state * available gcode files and stats (upload is disabled) @@ -16,60 +39,214 @@ the read-only parts of the UI which are the following: * any components provided through plugins which are enabled for anonymous users -Logged in users will get access to everything besides the Settings and System -Commands, which are admin-only. +Another predefined "Operator" group is the default group for newly created users and +by default gives access to all aspects of OctoPrint that involve regular printer +operation. It matches the old "user" role from OctoPrint prior to 1.4.0. -If Access Control is disabled, everything is directly accessible. **That also -includes all administrative functionality as well as full control over the -printer**, and without the need for an :ref:`API key `! - -Upon first start a configuration wizard is provided which allows configuration -of the first administrator account or alternatively disabling Access Control -(which is **NOT** recommended for systems that are directly accessible via the -internet or other untrusted networks!). +Finally, the predefined "Admins" group gives full admin access to the platform. You should +be careful of who you put into that. It matches the old "admin" role from OctoPrint prior +to 1.4.0. .. hint:: If you plan to have your OctoPrint instance accessible over the internet, - **always enable Access Control** and ideally **don't make it accessible to + **please use additional security measures** and ideally **don't make it accessible to everyone over the internet but instead use a VPN** or at the very least - HTTP basic authentication on a layer above OctoPrint. + HTTP basic authentication on a layer above OctoPrint. Unless you are using a VPN + **please do not** enable any permissions for the Guest group or the auto-login feature + described below. A physical device that includes heaters and stepper motors really should not be publicly reachable by everyone with an internet connection, even with access control enabled. -.. _sec-features-access_control-rerunning_wizard: +.. _sec-features-access_control-autologin: -Rerunning the wizard --------------------- +Autologin +--------- -In case Access Control was disabled in the configuration wizard, it is -possible to re-run it by editing ``config.yaml`` [#f1]_ and setting ``firstRun`` -in the ``server`` section and ``enabled`` in the ``accessControl`` section to -``true``: +While access control cannot be disabled as of OctoPrint 1.5+, the Autologin feature can +be used to bypass authentication for hosts on the network(s) that you trust. -.. code-block-ext:: yaml +Starting with OctoPrint 1.5.0, OctoPrint makes enabled access control mandatory. This +might be an inconvience for some who run OctoPrint in an isolated setup where a login is +not required to ensure security, at a benefit for a huge number of users out there who +continue to underestimate or simply ignore the risk of keeping their OctoPrint instance +unsecured and then happily exposing it on the public internet. - accessControl: - enabled: true - # ... - server: - firstRun: true +That being said, even as far back as OctoPrint 1.0.0 (released in 2013) there has existed +a way to have OctoPrint automatically log you in, if you connect from a trusted local +network address. This functionality has not been exposed on the UI, and for now also won't +be (to make it a bit harder to once again create an insecure setup for those who simply +won't listen to common sense), but it's easy to set up with a bit of configuration +editing. -Then restart the server and connect to the web interface - the wizard should -be shown again. +When set up properly, it will make sure to automatically log you in as a configured user +whenever you connect from a device on your local network. To get back pretty much the same +behaviour as with disabled access control, you'll only need to create a single (admin) +account and then set up autologin for it. -.. note:: - If user accounts were created prior to disabling Access Control and those - user accounts are not to be used any more, remove ``.octoprint/users.yaml``. - If you don't remove this file, the above changes won't lead to the - configuration being shown again, instead Access Control will just be - enabled using the already existing login data. This is to prevent you from - resetting access control by accident. +.. warning:: -.. rubric:: Footnotes + **Do not do this if you cannot trust EVERYONE on your local network.** And that really + means mean everyone. If you ignore this and then someone takes over your OctoPrint + instance, installs malware on it and makes your printer print an endless stream of + benchies, that's on you. -.. [#f1] For Linux that will be ``~/.octoprint/config.yaml``, for Windows it will be ``%APPDATA%/OctoPrint/config.yaml`` and for - Mac ``~/Library/Application Support/OctoPrint/config.yaml`` +.. _sec-features-access_control-autologin-gather_config_info: + +Gather configuration information +................................ + +You can configure Autologin via a plugin (the easy way), or manually (the hard way), but +in either case you will need to specify which user should be automatically logged in, and +which hosts are permitted access this way. + +**Improperly setting this subnet option can lead to the compromise of your system, or even +your entire network. Proceed with extreme caution.** + +The subnet to use is usually the IP address range of your LAN, which sounds scary but +actually isn't. Just `figure out your PC's IP address and subnet mask `_ +and then combine both with a / in between. + +On OctoPi (or another Linux distribution) you can use the follwing command: + +.. code-block:: + + ip route | grep -P 'eth0|wlan0' | awk '{print $1}' + +Or, for IPv6, use this: + +.. code-block:: + + ip -6 route | grep -P 'eth0|wlan0' | awk '{print $1}' + +This will be what you set as the subnet in the plugin, or where it says +```` below on the manual configuration instructions. + +Example: Your PC has an IP address of ``192.168.23.42`` and a subnet mask of +``255.255.255.0``. Your address range is ``192.168.23.42/255.255.255.0``. + +.. _sec-features-access_control-autologin-plugin: + +The easy way: Using the OctoPrint-AutoLoginConfig plugin +........................................................ + +The easist way to configure AutoLogin is to install the +`OctoPrint-AutoLoginConfig plugin `_ +via the plugin manager. + +Open its settings and follow the instructions on the screen. + +.. _sec-features-access_control-autologin-manual: + +The hard way: Manual editing of config.yaml +........................................... + +Preparation +*********** + +First of all, read :ref:`the YAML primer `. You +will have to edit OctoPrint's main configuration file, and thus should make sure +you understand at least roughly how things work and that you should keep your +hands off the Tab key. If you don't, you might break your config file, and +while the steps include making a backup, this still can be easily avoided by +learning about the DOs and DONTs first. + +Then, take a look at :ref:`the docs on config.yaml ` +on where to find that central configuration file of OctoPrint. + +Configuration +************* + +Ready? Let's do some editing then. I'll outline what to do and where first, and then +further down there's also a dedicated list of steps for OctoPi specifically. + +1. Shutdown OctoPrint +2. Make a backup of your config.yaml +3. Open it in a text editor (e.g. nano). Right at the very top it'll say something like + this: + + .. code-block:: yaml + + accessControl: + salt: aabbccddee1234523452345 + + Edit this, adding lines so it looks like this (making absolutely sure not to touch the + salt line): + + .. code-block:: yaml + accessControl: + salt: aabbccddee1234523452345 + autologinLocal: true + autologinAs: "" + localNetworks: + - "127.0.0.0/8" + - "" + +4. Restart OctoPrint, check that everything works. + +This will automatically log you in as the user you specified whenver you connect to +OctoPrint from an address in the address range (e.g. a device on your local network). + +OctoPi specific steps +********************* + +If you are running OctoPi you will have to SSH into your Raspberry Pi. Then issue +the following commands: + +1. ``sudo service octoprint stop`` +2. ``cp ~/.octoprint/config.yaml ~/.octoprint/config.yaml.back`` +3. ``nano ~/.octoprint/config.yaml, make the edits as described above`` +4. ``sudo service octoprint start`` + +If something went wrong, you can restore the config backup with + +.. code-block:: + + cp ~/.octoprint/config.yaml.back ~/.octoprint/config.yaml + + +If you are using a VPN and your setup ABSOLUTELY REQUIRES disabling internal OctoPrint access controls +...................................................................................................... + +.. warning:: + + You probably shouldn't do this, EVER. There are usually other options. Don't even + THINK about it, unless you have a VPN layer for security. Only consider proceeding + with this configuration after exhausting ALL other possibilities, and even then, you + should think long and hard about whether this is a good idea. You almost certainly + don't need or want to do this. + +While access controls can no longer be disabled in OctoPrint 1.5+, this can be +approximated by an Autologin configuration that automatically logs in all users, that is +by using subnets that match all possible IP addresses. By specifying the ``0.0.0.0/0`` +subnet (for IPv4) and ``::/0`` for IPv6 in the AutoLogin configuration, you can achieve +this. This configuration is permitted, but highly, highly discouraged. + +Please don't do this. You will almost certainly regret it. You alone are responsible for +your actions. + +.. _sec-features-access_control-hooks: + +Available Extension Hooks +------------------------- + +There are two hooks for plugins to utilize in order to +add new configurable permissions into the system and/or adjust the styling of the +login dialog. + +.. _sec-features-access_control-hooks-permissions: + +octoprint.access.permissions +............................ + +See :ref:`here `. + +.. _sec-features-access_control-hooks-loginui: + +octoprint.theming.login +....................... + +See :ref:`here `. 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/custom_controls.rst b/docs/features/custom_controls.rst index f130596c1..977567a2c 100644 --- a/docs/features/custom_controls.rst +++ b/docs/features/custom_controls.rst @@ -24,7 +24,7 @@ The following example defines a control for enabling the cooling fan with a vari feedback evaluation for the result of the M114 "Get Position" gcode inside a section named "Reporting" and finally a GCODE script including user input. -.. code-block-ext:: yaml +.. code-block:: yaml controls: - name: Fan @@ -172,15 +172,16 @@ Controls turn the button red. * - ``enabled`` - (Optional) A JavaScript snippet returning either ``true`` or ``false`` determining whether the control - should be enabled or not. This allow to override the default logic for this (disabled if printer is offline - or currently printing). The JavaScript snippet is ``eval``'d and processed in a context where the control - it is part of is provided as local variable ``data`` and the ``ControlViewModel`` is available as ``self``. + should be enabled or not. This allows to override the default logic for the enable state + of the control (disabled if printer is offline). The JavaScript snippet is ``eval``'d and processed + in a context where the control it is part of is provided as local variable ``data`` and the + ``ControlViewModel`` is available as ``self``. * - ``input`` - (Optional) A list of definitions of input parameters for a ``command`` or ``commands``, to be rendered as additional input fields. ``command``/``commands`` may contain placeholders to be replaced by the values obtained from the user for the defined input fields: - .. code-block-ext:: yaml + .. code-block:: yaml name: Enable Fan command: M106 S%(speed)s @@ -210,20 +211,31 @@ Controls * - ``input.slider.step`` - (Optional) Step size per slider "tick", defaults to 1. * - ``regex`` - - (Optional) A `regular expression `_ to + - (Optional) A :ref:`regular expression ` to match against lines received from the printer to retrieve information from it (e.g. specific output). Together with ``template`` this allows rendition of received data from the printer within the UI. + + **Please also read the note below**. * - ``template`` - (Optional) A template to use for rendering the match of ``regex``. May contain placeholders in - `Python Format String Syntax `_ for either named + :ref:`Python Format String Syntax ` for either named groups within the regex (e.g. ``Temperature: {temperature}`` for a regex ``T:\s*(?P\d+(\.\d*)``) or positional groups within the regex (e.g. ``Position: X={0}, Y={1}, Z={2}, E={3}`` for a regex ``X:([0-9.]+) Y:([0-9.]+) Z:([0-9.]+) E:([0-9.]+)``). + + **Please also read the note below**. * - ``confirm`` - (Optional) A text to display to the user to confirm his button press. Can be used with sensitive custom controls like changing EEPROM values in order to prevent accidental clicks. The text will be displayed in a confirmation dialog like in :numref:`fig-configuration-customcontrols-confirm`. +.. note:: + + ``regex`` and ``template`` are only supported for controls that are defined through + ``config.yaml``. These control properties aren't supported for controls added only in + the frontend by the :ref:`getAdditionalControls ` + view model callback. + .. _fig-configuration-customcontrols-confirm: .. figure:: ../images/features-custom_controls-confirm.png :align: center @@ -241,7 +253,7 @@ Examples Parameterized GCODE Script .......................... -.. code-block-ext:: yaml +.. code-block:: yaml :caption: Control definition in ~/.octoprint/config.yaml :name: code-features-custom_controls-example-gcode_script-config_yaml @@ -256,7 +268,7 @@ Parameterized GCODE Script min: 1 step: 1 -.. code-block-ext:: jinja +.. code-block:: jinja :caption: ~/.octoprint/scripts/gcode/custom/dance.gco :name: code-features-custom_controls-example-gcode_script-dance_gco diff --git a/docs/features/gcode_scripts.rst b/docs/features/gcode_scripts.rst index 73d8916f8..d836d3fad 100644 --- a/docs/features/gcode_scripts.rst +++ b/docs/features/gcode_scripts.rst @@ -11,20 +11,14 @@ is clicked. Unless :ref:`configured otherwise `, OctoPrint expects scripts to be located in the ``scripts/gcode`` folder in OctoPrint configuration directory (per default ``~/.octoprint`` on Linux, ``%APPDATA%\OctoPrint`` -on Windows and ``~/Library/Application Support/OctoPrint`` on MacOS). +on Windows and ``~/Library/Application Support/OctoPrint`` on macOS). These GCODE scripts are backed by the templating engine Jinja2, allowing more than just simple "send-as-is" scripts but making use of a full blown templating language in order to create your scripts. To this end, OctoPrint injects some variables into the :ref:`template rendering context ` as described below. -You can find the docs on the Jinja templating engine as used in OctoPrint at `jinja.octoprint.org `_. - -.. note:: - - Due to backwards compatibility issues with Jinja versions 2.9+, OctoPrint currently only supports Jinja 2.8. For this - reason use the template documentation at `jinja.octoprint.org `_ instead of the - documentation of current stable Jinja versions. +You can find the docs on the Jinja templating engine as used in OctoPrint `here `_. .. _sec-features-gcode_scripts-predefined: @@ -49,6 +43,15 @@ The following GCODE scripts are sent by OctoPrint automatically: Plugins may extend these scripts through :ref:`a hook `. +.. _sec-features-gcode_scripts-events: + +Events +------ + +Every GCODE script that is executed will emit two events. The event name will start with 'GcodeScript' followed by the capitalized name +of the script. When ``afterPrintDone`` has started the event will be ``GcodeScriptAfterPrintDoneRunning`` and once it has completed the last event +will be ``GcodeScriptAfterPrintDoneFinished``. You can find more details in the :ref:`Events ` documentation. + .. _sec-features-gcode_scripts-snippets: Snippets @@ -190,7 +193,7 @@ More nifty pause and resume ........................... If you do not have a multi-extruder setup, aren't printing from SD and have "Log position on pause" enabled under -Settings > Serial > Advanced options, the following ``afterPrintPaused`` and +Settings > Serial Connection > Behaviour > Pausing, the following ``afterPrintPaused`` and ``beforePrintResumed`` scripts might be interesting for you. With something like them in place, OctoPrint will move your print head out of the way to a safe rest position (here ``G1 X0 Y0``, you might want to adjust that) on pause and move it back to the persisted pause position on resume, making sure to also reset the extruder and feedrate. @@ -250,7 +253,6 @@ to the persisted pause position on resume, making sure to also reset the extrude .. seealso:: - `Jinja Template Designer Documentation `_ + `Jinja Template Designer Documentation `_ Jinja's Template Designer Documentation describes the syntax and semantics of the template language used - also by OctoPrint's GCODE scripts. Linked here are the docs for Jinja 2.8.1, which OctoPrint still - relies on for backwards compatibility reasons. + also by OctoPrint's GCODE scripts. diff --git a/docs/features/plugins.rst b/docs/features/plugins.rst index 450074713..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. @@ -28,7 +30,7 @@ Finding Plugins The official OctoPrint Plugin Repository can be found at `plugins.octoprint.org `_. -Some plugins may also be found in the list provided in `the OctoPrint wiki `_ +Some plugins may also be found in the list provided in `the OctoPrint wiki `_ and on the `OctoPrint organization Github page `_. .. _sec-features-plugins-installing: diff --git a/docs/features/safemode.rst b/docs/features/safemode.rst index 56445e9e4..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. @@ -75,12 +78,12 @@ When OctoPrint is running in safe mode the following changes to its normal opera * OctoPrint will not enable any of the installed third party plugins. OctoPrint considers all plugins third party plugins that do not ship with OctoPrint's sources, so any plugins installed either via `pip` or into OctoPrint's plugin folder at ``~/.octoprint/plugins`` (Linux), ``%APPDATA%/OctoPrint/plugins`` (Windows) and - ``~/Library/Application Support/OctoPrint/plugins`` (MacOS). + ``~/Library/Application Support/OctoPrint/plugins`` (macOS). * OctoPrint will not enable any of the installed third party language packs. OctoPrint considers all language packs third party language packs that do not ship with OctoPrint's sources, so any language plugins installed through the language pack manager within settings and/or stored in the language pack folder at ``~/.octoprint/translations`` (Linux), ``%APPDATA%/OctoPrint/translations`` (Windows) or - ``~/Library/Application Support/OctoPrint/translations`` (MacOS). + ``~/Library/Application Support/OctoPrint/translations`` (macOS). * OctoPrint will still allow to uninstall third party plugins through the built-in Plugin Manager. * OctoPrint will still allow to disable (bundled) plugins that are still enabled. * OctoPrint will not allow to enable third party plugins. diff --git a/docs/images/bundledplugins-action_command_notification-example.png b/docs/images/bundledplugins-action_command_notification-example.png new file mode 100644 index 000000000..fc571db92 Binary files /dev/null and b/docs/images/bundledplugins-action_command_notification-example.png differ 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-gcodeviewer-example.png b/docs/images/bundledplugins-gcodeviewer-example.png new file mode 100644 index 000000000..28f54fc73 Binary files /dev/null and b/docs/images/bundledplugins-gcodeviewer-example.png differ diff --git a/docs/images/bundledplugins-forcelogin-dialog.png b/docs/images/bundledplugins-loginui-dialog.png similarity index 100% rename from docs/images/bundledplugins-forcelogin-dialog.png rename to docs/images/bundledplugins-loginui-dialog.png 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/jsclientlib/printer.rst b/docs/jsclientlib/printer.rst index d79d3d6de..e0c014bab 100644 --- a/docs/jsclientlib/printer.rst +++ b/docs/jsclientlib/printer.rst @@ -144,7 +144,7 @@ Sets the current flowrate multiplier. - ``factor`` is expected to be a integer value between 75 and 125 representing the new flowrate percentage. + ``factor`` is expected to be a integer value >0 representing the new flowrate percentage. See the ``flowrate`` command in :ref:`Issue a tool command ` for more details. @@ -325,7 +325,7 @@ Sets the feedrate multiplier to use. - ``factor`` is expected to be a integer value between 0 and 200 representing the new feedrate percentage. + ``factor`` is expected to be a integer value >0 representing the new feedrate percentage. See the ``feedrate`` command in :ref:`Issue a print head command ` for more details. diff --git a/docs/jsclientlib/socket.rst b/docs/jsclientlib/socket.rst index 6da88a1ee..925528490 100644 --- a/docs/jsclientlib/socket.rst +++ b/docs/jsclientlib/socket.rst @@ -42,7 +42,7 @@ To register for all message types, provide ``*`` as the type to register for. ``handler`` is expected to be a function accepting one object parameter ``eventObj``, consisting - of the received message as property ``key`` and the received payload (if any) as property ``data``. + of the received message as property ``event`` and the received payload (if any) as property ``data``. .. code-block:: javascript diff --git a/docs/jsclientlib/util.rst b/docs/jsclientlib/util.rst index f88062ee7..a5454b64d 100644 --- a/docs/jsclientlib/util.rst +++ b/docs/jsclientlib/util.rst @@ -187,7 +187,7 @@ .. code-block:: javascript - OctoPrint.util.testUrl("127.0.0.1", 1234, {"protocol": "udp"}) + OctoPrint.util.testServer("127.0.0.1", 1234, {"protocol": "udp"}) .done(function(response) { if (response.result) { // check passed @@ -203,6 +203,30 @@ :param object opts: Additional options for the request :returns Promise: A `jQuery Promise `_ for the request's response +.. js:function:: OctoPrintClient.util.testResolution(name, additional, opts) + + Test if a host name can be resolved. + + **Example** + + Test if ``octoprint.org`` can be resolved. + + .. code-block:: javascript + + OctoPrint.util.testResolution("octoprint.org") + .done(function(response) { + if (response.result) { + // check passed + } else { + // check failed + } + }); + + :param string name: Host name to test + :param object additional: Additional parameters for the test command + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + .. seealso:: :ref:`Util API ` diff --git a/docs/make.bat b/docs/make.bat deleted file mode 100644 index 4eea5d5bf..000000000 --- a/docs/make.bat +++ /dev/null @@ -1,242 +0,0 @@ -@ECHO OFF - -REM Command file for Sphinx documentation - -if "%SPHINXBUILD%" == "" ( - set SPHINXBUILD=sphinx-build -) -set BUILDDIR=_build -set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . -set I18NSPHINXOPTS=%SPHINXOPTS% . -if NOT "%PAPER%" == "" ( - set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% - set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% -) - -if "%1" == "" goto help - -if "%1" == "help" ( - :help - echo.Please use `make ^` where ^ is one of - echo. html to make standalone HTML files - echo. dirhtml to make HTML files named index.html in directories - echo. singlehtml to make a single large HTML file - echo. pickle to make pickle files - echo. json to make JSON files - echo. htmlhelp to make HTML files and a HTML help project - echo. qthelp to make HTML files and a qthelp project - echo. devhelp to make HTML files and a Devhelp project - echo. epub to make an epub - echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter - echo. text to make text files - echo. man to make manual pages - echo. texinfo to make Texinfo files - echo. gettext to make PO message catalogs - echo. changes to make an overview over all changed/added/deprecated items - echo. xml to make Docutils-native XML files - echo. pseudoxml to make pseudoxml-XML files for display purposes - echo. linkcheck to check all external links for integrity - echo. doctest to run all doctests embedded in the documentation if enabled - goto end -) - -if "%1" == "clean" ( - for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i - del /q /s %BUILDDIR%\* - goto end -) - - -%SPHINXBUILD% 2> nul -if errorlevel 9009 ( - echo. - echo.The 'sphinx-build' command was not found. Make sure you have Sphinx - echo.installed, then set the SPHINXBUILD environment variable to point - echo.to the full path of the 'sphinx-build' executable. Alternatively you - echo.may add the Sphinx directory to PATH. - echo. - echo.If you don't have Sphinx installed, grab it from - echo.http://sphinx-doc.org/ - exit /b 1 -) - -if "%1" == "html" ( - %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The HTML pages are in %BUILDDIR%/html. - goto end -) - -if "%1" == "dirhtml" ( - %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. - goto end -) - -if "%1" == "singlehtml" ( - %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. - goto end -) - -if "%1" == "pickle" ( - %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can process the pickle files. - goto end -) - -if "%1" == "json" ( - %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can process the JSON files. - goto end -) - -if "%1" == "htmlhelp" ( - %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can run HTML Help Workshop with the ^ -.hhp project file in %BUILDDIR%/htmlhelp. - goto end -) - -if "%1" == "qthelp" ( - %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can run "qcollectiongenerator" with the ^ -.qhcp project file in %BUILDDIR%/qthelp, like this: - echo.^> qcollectiongenerator %BUILDDIR%\qthelp\OctoPrint.qhcp - echo.To view the help file: - echo.^> assistant -collectionFile %BUILDDIR%\qthelp\OctoPrint.ghc - goto end -) - -if "%1" == "devhelp" ( - %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. - goto end -) - -if "%1" == "epub" ( - %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The epub file is in %BUILDDIR%/epub. - goto end -) - -if "%1" == "latex" ( - %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. - goto end -) - -if "%1" == "latexpdf" ( - %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex - cd %BUILDDIR%/latex - make all-pdf - cd %BUILDDIR%/.. - echo. - echo.Build finished; the PDF files are in %BUILDDIR%/latex. - goto end -) - -if "%1" == "latexpdfja" ( - %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex - cd %BUILDDIR%/latex - make all-pdf-ja - cd %BUILDDIR%/.. - echo. - echo.Build finished; the PDF files are in %BUILDDIR%/latex. - goto end -) - -if "%1" == "text" ( - %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The text files are in %BUILDDIR%/text. - goto end -) - -if "%1" == "man" ( - %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The manual pages are in %BUILDDIR%/man. - goto end -) - -if "%1" == "texinfo" ( - %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. - goto end -) - -if "%1" == "gettext" ( - %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The message catalogs are in %BUILDDIR%/locale. - goto end -) - -if "%1" == "changes" ( - %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes - if errorlevel 1 exit /b 1 - echo. - echo.The overview file is in %BUILDDIR%/changes. - goto end -) - -if "%1" == "linkcheck" ( - %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck - if errorlevel 1 exit /b 1 - echo. - echo.Link check complete; look for any errors in the above output ^ -or in %BUILDDIR%/linkcheck/output.txt. - goto end -) - -if "%1" == "doctest" ( - %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest - if errorlevel 1 exit /b 1 - echo. - echo.Testing of doctests in the sources finished, look at the ^ -results in %BUILDDIR%/doctest/output.txt. - goto end -) - -if "%1" == "xml" ( - %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The XML files are in %BUILDDIR%/xml. - goto end -) - -if "%1" == "pseudoxml" ( - %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. - goto end -) - -:end diff --git a/docs/modules/plugin.rst b/docs/modules/plugin.rst index d464b5c34..681c6c5b2 100644 --- a/docs/modules/plugin.rst +++ b/docs/modules/plugin.rst @@ -4,6 +4,7 @@ octoprint.plugin ---------------- .. automodule:: octoprint.plugin + :members: .. _sec-modules-plugin-core: @@ -11,6 +12,7 @@ octoprint.plugin.core --------------------- .. automodule:: octoprint.plugin.core + :members: .. _sec-modules-plugin-types: @@ -18,3 +20,4 @@ octoprint.plugin.types ---------------------- .. automodule:: octoprint.plugin.types + :members: diff --git a/docs/modules/printer.rst b/docs/modules/printer.rst index 5fcd54ae4..dc652ae70 100644 --- a/docs/modules/printer.rst +++ b/docs/modules/printer.rst @@ -4,6 +4,7 @@ octoprint.printer ----------------- .. automodule:: octoprint.printer + :members: .. _sec-modules-printer-profile: @@ -11,3 +12,4 @@ octoprint.printer.profile ------------------------- .. automodule:: octoprint.printer.profile + :members: diff --git a/docs/modules/settings.rst b/docs/modules/settings.rst index 80248cbb9..09582f710 100644 --- a/docs/modules/settings.rst +++ b/docs/modules/settings.rst @@ -4,3 +4,4 @@ octoprint.settings ------------------ .. automodule:: octoprint.settings + :members: diff --git a/docs/modules/slicing.rst b/docs/modules/slicing.rst index bf27d4865..ee3ac9192 100644 --- a/docs/modules/slicing.rst +++ b/docs/modules/slicing.rst @@ -4,10 +4,12 @@ octoprint.slicing ----------------- .. automodule:: octoprint.slicing + :members: .. _sec-modules-slicing-exceptions: octoprint.slicing.exceptions ---------------------------- -.. automodule:: octoprint.slicing.exceptions \ No newline at end of file +.. automodule:: octoprint.slicing.exceptions + :members: diff --git a/docs/modules/util.rst b/docs/modules/util.rst index 156a25ff3..134b9a1bf 100644 --- a/docs/modules/util.rst +++ b/docs/modules/util.rst @@ -13,3 +13,11 @@ octoprint.util.commandline .. automodule:: octoprint.util.commandline :members: + +.. _sec-modules-util-platform: + +octoprint.util.platform +----------------------- + +.. automodule:: octoprint.util.platform + :members: diff --git a/docs/plugins/distributing.rst b/docs/plugins/distributing.rst index f01bbf79b..35325d38f 100644 --- a/docs/plugins/distributing.rst +++ b/docs/plugins/distributing.rst @@ -60,3 +60,22 @@ that in the `Plugin Repository's help pages `_ when creating your plugin, you can find a prepared registration entry ``.md`` file in the ``extras`` folder of your plugin. + +Version management after the official plugin repository release +--------------------------------------------------------------- + +Once your plugin is available in the official plugin repository, you probably want to create and distribute new versions. +For "beta" users you can use the manual file distribution method, or a more elegant release channels (see below). +After you finalized a new plugin version, don't forget to actually update the version in the ``setup.py``, +and `submit a new release on github `_. + +After you published the new release, you can verify it on your installed octoprint, +with force checking the updates under the advanced options (in the software updates menu in the settings). +The new versions will appear to the plugin users in the next 24 hours (it depends on their cache refreshes). + +The `Software Update Plugin `_ has options to define multiple release channels, +and you can let the users decide if they want to test your pre-releases or not. +This can be achieved with defining ``stable_branch`` and ``prerelease_branches`` in the ``get_update_information`` function, +and creating github releases to the newly configured branches too. +For more information you can check the `Software Update Plugin documentation `_ +or read a more step-by-step writeup `here `_. diff --git a/docs/plugins/gettingstarted.rst b/docs/plugins/gettingstarted.rst index c83fbb7de..3ac2939d5 100644 --- a/docs/plugins/gettingstarted.rst +++ b/docs/plugins/gettingstarted.rst @@ -14,7 +14,7 @@ First of all let use make sure that you have OctoPrint checked out and set up fo development environment:: $ cd ~/devel - $ git clone https://github.com/foosel/OctoPrint + $ git clone https://github.com/OctoPrint/OctoPrint [...] $ cd OctoPrint $ virtualenv venv @@ -41,6 +41,9 @@ development environment:: [...] + Setting up a local development environment will most likely be less painful than developing directly + on the Pi. So do yourself the favor and do that instead where possible. + .. important:: This tutorial assumes you are running OctoPrint 1.3.0 and up. Please make sure your version of @@ -60,6 +63,7 @@ We'll start at the most basic form a plugin can take - just a few simple lines o __plugin_name__ = "Hello World" __plugin_version__ = "1.0.0" __plugin_description__ = "A quick \"Hello World\" example plugin for OctoPrint" + __plugin_pythoncompat__ = ">=2.7,<4" Saving this as ``helloworld.py`` in ``~/.octoprint/plugins`` yields you something resembling these log entries upon server startup:: @@ -75,7 +79,10 @@ Saving this as ``helloworld.py`` in ``~/.octoprint/plugins`` yields you somethin OctoPrint found that plugin in the folder and took a look into it. The name and the version it displays in that log entry it got from the ``__plugin_name__`` and ``__plugin_version__`` lines. It also read the description from -``__plugin_description__`` and stored it in an internal data structure, but we'll just ignore this for now. +``__plugin_description__`` and stored it in an internal data structure, but we'll just ignore this for now. Additionally +there is ``__plugin_pythoncompat__`` which tells OctoPrint here that your plugin can be run under any Python versions +between 2.7 and 4. That is necessary so that your plugin will be loadable in OctoPrint instances running under either +Python 2 or Python 3, and compatibility to both should be your goal. .. _sec-plugins-gettingstarted-sayinghello: @@ -86,7 +93,7 @@ Apart from being discovered by OctoPrint, our plugin does nothing yet. We want t "Hello World!" to the log upon server startup. Modify our ``helloworld.py`` like this: .. code-block:: python - :emphasize-lines: 4-8,13 + :emphasize-lines: 4-8,14 :linenos: # -*- coding: utf-8 -*- @@ -101,6 +108,7 @@ Apart from being discovered by OctoPrint, our plugin does nothing yet. We want t __plugin_name__ = "Hello World" __plugin_version__ = "1.0.0" __plugin_description__ = "A quick \"Hello World\" example plugin for OctoPrint" + __plugin_pythoncompat__ = ">=2.7,<4" __plugin_implementation__ = HelloWorldPlugin() and restart OctoPrint. You now get this output in the log:: @@ -135,7 +143,7 @@ as a simple python file following the naming convention ``.py that can be done in one file. Distributing multiple files and getting your users to install them in the right way so that OctoPrint will be able to actually find and load them is certainly not impossible, but we want to do it in the best way possible, meaning we want to make our plugin a fully installable Python module that your users will be able to -install directly via `OctoPrint's built-in Plugin Manager `_ +install directly via `OctoPrint's built-in Plugin Manager `_ or alternatively manually utilizing Python's standard package manager ``pip`` directly. So let's begin. We'll use the `cookiecutter `_ template for OctoPrint plugins @@ -284,7 +292,7 @@ of information now defined twice: The nice thing about our plugin now being a proper Python package is that OctoPrint can and will access the metadata defined within ``setup.py``! So, we don't really need to define all this data twice. Remove ``__plugin_name__``, ``__plugin_version__`` -and ``__plugin_description__`` from ``__init__.py``: +and ``__plugin_description__`` from ``__init__.py``, but leave ``__plugin_implementation__`` and ``__plugin_pythoncompat__``: .. code-block:: python :linenos: @@ -298,6 +306,7 @@ and ``__plugin_description__`` from ``__init__.py``: def on_after_startup(self): self._logger.info("Hello World!") + __plugin_pythoncompat__ = ">=2.7,<4" __plugin_implementation__ = HelloWorldPlugin() and restart OctoPrint:: @@ -324,6 +333,7 @@ Our "Hello World" Plugin still gets detected fine, but it's now listed under the self._logger.info("Hello World!") __plugin_name__ = "Hello World" + __plugin_pythoncompat__ = ">=2.7,<4" __plugin_implementation__ = HelloWorldPlugin() @@ -373,6 +383,7 @@ add the :class:`TemplatePlugin` to our ``HelloWorldPlugin`` class: self._logger.info("Hello World!") __plugin_name__ = "Hello World" + __plugin_pythoncompat__ = ">=2.7,<4" __plugin_implementation__ = HelloWorldPlugin() Next, we'll create a sub folder ``templates`` underneath our ``octoprint_helloworld`` folder, and within that a file @@ -443,6 +454,7 @@ Let's take a look at how all that would look in our plugin's ``__init__.py``: return dict(url="https://en.wikipedia.org/wiki/Hello_world") __plugin_name__ = "Hello World" + __plugin_pythoncompat__ = ">=2.7,<4" __plugin_implementation__ = HelloWorldPlugin() Restart OctoPrint. You should see something like this:: @@ -480,6 +492,7 @@ Adjust your plugin's ``__init__.py`` like this: return dict(url=self._settings.get(["url"])) __plugin_name__ = "Hello World" + __plugin_pythoncompat__ = ">=2.7,<4" __plugin_implementation__ = HelloWorldPlugin() Also adjust your plugin's ``templates/helloworld_navbar.jinja2`` like this: @@ -590,6 +603,7 @@ again since we don't use that anymore: ] __plugin_name__ = "Hello World" + __plugin_pythoncompat__ = ">=2.7,<4" __plugin_implementation__ = HelloWorldPlugin() Restart OctoPrint and shift-reload your browser. Your link in the navigation bar should still point to the URL we @@ -693,6 +707,7 @@ like so: ) __plugin_name__ = "Hello World" + __plugin_pythoncompat__ = ">=2.7,<4" __plugin_implementation__ = HelloWorldPlugin() Note how we did not add another entry to the return value of :func:`~octoprint.plugin.TemplatePlugin.get_template_configs`. @@ -875,6 +890,7 @@ a reference to our CSS file: ) __plugin_name__ = "Hello World" + __plugin_pythoncompat__ = ">=2.7,<4" __plugin_implementation__ = HelloWorldPlugin() OctoPrint by default bundles all CSS, JavaScript and LESS files to reduce the amount of requests necessary to fully @@ -961,6 +977,7 @@ Then adjust our returned assets to include our LESS file as well: ) __plugin_name__ = "Hello World" + __plugin_pythoncompat__ = ">=2.7,<4" __plugin_implementation__ = HelloWorldPlugin() @@ -1074,7 +1091,7 @@ you haven't seen yet, :ref:`take a look at the available plugin mixins `_ might be a good example to learn from. For how to -add support for a slicer, OctoPrint's own bundled `CuraEngine plugin `_ +add support for a slicer, the `CuraEngine Legacy plugin `_ might give some hints. For extending OctoPrint's interface, the `NavbarTemp plugin `_ might show what's possible with a few lines of code already. Finally, just take a look at the `official Plugin Repository `_ if you are looking for examples. diff --git a/docs/plugins/helpers.rst b/docs/plugins/helpers.rst index f8c5424f3..73b2a7935 100644 --- a/docs/plugins/helpers.rst +++ b/docs/plugins/helpers.rst @@ -7,7 +7,7 @@ Helpers are methods that plugins can expose to other plugins in order to make co system. They are registered with the OctoPrint plugin system through the use of the control property ``__plugin_helpers__``. An example for providing some helper functions to the system can be found in the -`Discovery Plugin `_, +`Discovery Plugin `_, which provides its SSDP browsing and Zeroconf browsing and publishing functions as helper methods. .. code-block:: python diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst index 8d35ea5a6..eb52fbec4 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -65,7 +65,7 @@ the general type of script for which to look for additions ("gcode") and the scr return a 2-tuple of prefix and postfix if has something for either of those, otherwise ``None``. OctoPrint will then take care to add prefix and suffix as necessary after a small round of preprocessing. -Plugins can easily add their own hooks too. For example, the `Software Update Plugin `_ +Plugins can easily add their own hooks too. For example, the `Software Update Plugin `_ declares a custom hook "octoprint.plugin.softwareupdate.check_config" which other plugins can add handlers for in order to register themselves with the Software Update Plugin by returning their own update check configuration. @@ -200,6 +200,98 @@ Available plugin hooks .. contents:: :local: +.. _sec-plugins-hook-permissions: + +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. + + Additional permissions must be modelled as ``dict``s with at least a ``key`` and ``name`` field. Possible + fields are as follows: + + * ``key``: A key for the permission to be used for referring to it from source code. This will turned uppercase + and prefixed with ``PLUGIN__`` before being made available on ``octoprint.access.permissions.Permissions``, + e.g. ``my_permission`` on the plugin with identifier ``example`` turns into ``PLUGIN_EXAMPLE_MY_PERMISSION`` and + can be accessed as ``octoprint.access.permissions.Permissions.PLUGIN_EXAMPLE_MY_PERMISSION`` on the server and + ``permissions.PLUGIN_EXAMPLE_MY_PERMISSION`` on the ``AccessViewModel`` on the client. Must only contain a-z, A-Z, 0-9 and _. + * ``name``: A human readable name for the permission. + * ``description``: A human readable description of the permission. + * ``permissions``: A list of permissions this permission includes, by key. + * ``roles``: A list of roles this permission includes. Roles are simple strings you define. Usually one role will + suffice. + * ``dangerous``: Whether this permission should be considered dangerous (``True``) or not (``False``) + * ``default_groups``: A list of standard groups this permission should be apply to by default. Standard groups + are ``admins``, ``users``, ``readonly`` and ``guests`` + + The following example is based on some actual code included in the bundled Application Keys plugin and defines + one additional permission called ``ADMIN`` with a role ``admin`` which is marked as dangerous (since it gives + access to the management to other user's application keys) and by default will only be given to the standard admin + group: + + .. code-block:: python + + def get_additional_permissions(*args, **kwargs): + return [ + dict(key="ADMIN", + name="Admin access", + description=gettext("Allows administrating all application keys"), + roles=["admin"], + dangerous=True, + default_groups=[ADMIN_GROUP]) + ] + + __plugin_hooks__ = { + "octoprint.access.permissions": get_additional_permissions + } + + Once registered it can be referenced under the key ``PLUGIN_APPKEYS_ADMIN``. + + :return: A list of additional permissions to register in the system. + :rtype: A list of dicts. + +.. _sec-plugins-hook-users-factory: + +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. + + The provided ``components`` is a dictionary containing the already initialized system components: + + * ``plugin_manager``: The :class:`~octoprint.plugin.core.PluginManager` + * ``printer_profile_manager``: The :class:`~octoprint.printer.profile.PrinterProfileManager` + * ``event_bus``: The :class:`~octoprint.events.EventManager` + * ``analysis_queue``: The :class:`~octoprint.filemanager.analysis.AnalysisQueue` + * ``slicing_manager``: The :class:`~octoprint.slicing.SlicingManager` + * ``file_manager``: The :class:`~octoprint.filemanager.FileManager` + * ``plugin_lifecycle_manager``: The :class:`~octoprint.server.LifecycleManager` + * ``preemptive_cache``: The :class:`~octoprint.server.util.flask.PreemptiveCache` + + If the factory returns anything but ``None``, it will be assigned to the global ``userManager`` instance. + + If none of the registered factories return a user manager instance, the class referenced by the ``config.yaml`` + entry ``accessControl.userManager`` will be initialized if possible, otherwise a stock + :class:`~octoprint.access.users.FilebasedUserManager` will be instantiated, linked to the default user storage + file ``~/.octoprint/users.yaml``. + + :param dict components: System components to use for user manager instance initialization + :param SettingsManager settings: The global settings manager instance to fetch configuration values from if necessary + :return: The ``userManager`` instance to use globally. + :rtype: UserManager subclass or None + + .. _sec-plugins-hook-accesscontrol-keyvalidator: octoprint.accesscontrol.keyvalidator @@ -207,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. @@ -238,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 @@ -361,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 @@ -384,16 +482,18 @@ octoprint.comm.protocol.firmware.info This includes I/O of any kind. :param object comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook. - :param str firmware_name: The name of the parsed capability + :param str firmware_name: The parsed name of the firmware :param dict firmware_data: All data contained in the ``M115`` report .. _sec-plugins-hook-comm-protocol-firmware-capabilities: -octoprint.comm.firmware.protocol.capabilities +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 @@ -419,7 +519,9 @@ octoprint.comm.firmware.protocol.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. @@ -446,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: @@ -461,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. @@ -500,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`` @@ -509,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: @@ -662,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 @@ -695,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 @@ -732,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. @@ -776,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. @@ -802,6 +921,27 @@ octoprint.comm.protocol.temperatures.received :tab-width: 4 :caption: `sanitize_temperatures.py `_ +.. _sec-plugins-hook-comm-transport-serial-additonal-port-names: + +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. + + Useful in combination with :ref:`octoprint.comm.transport.serial.factory ` + to implement custom serial-like ports through plugins. + + For an example of use see the bundled ``virtual_printer`` plugin. + + :param list candidates: The port names already found on the system available for connection. + :return: Additional port names to offer up for connection. + :rtype: list + .. _sec-plugins-hook-comm-transport-serial-factory: octoprint.comm.transport.serial.factory @@ -809,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``. @@ -819,21 +961,21 @@ octoprint.comm.transport.serial.factory closely if directly utilizing :class:`~octoprint.util.comm.MachineCom` functionality. A valid serial instance is expected to provide the following methods, analogue to PySerial's - `serial.Serial `_: + :py:class:`serial.Serial`: readline(size=None, eol='\n') - Reads a line from the serial connection, compare `serial.Filelike.readline `_. + Reads a line from the serial connection, compare :py:meth:`serial.Serial.readline`. write(data) - Writes data to the serial connection, compare `serial.Filelike.write `_. + Writes data to the serial connection, compare :py:meth:`serial.Serial.write`. close() - Closes the serial connection, compare `serial.Serial.close `_. + Closes the serial connection, compare :py:meth:`serial.Serial.close`. Additionally setting the following attributes need to be supported if baudrate detection is supposed to work: baudrate - An integer describing the baudrate to use for the serial connection, compare `serial.Serial.baudrate `_. + An integer describing the baudrate to use for the serial connection, compare :py:attr:`serial.Serial.baudrate`. timeout - An integer describing the read timeout on the serial connection, compare `serial.Serial.timeout `_. + An integer describing the read timeout on the serial connection, compare :py:attr:`serial.Serial.timeout`. **Example:** @@ -885,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 @@ -913,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 @@ -951,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 @@ -987,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 @@ -1014,6 +1164,62 @@ 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-pluginmanager-reconnect: + +octoprint.plugin.pluginmanager.reconnect_hooks +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. versionadded:: 1.4.0 + +See :ref:`here `. + +.. _sec-plugins-hook-plugin-softwareupdate-check_config: + +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 @@ -1021,6 +1227,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. @@ -1052,6 +1260,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, @@ -1098,6 +1308,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`` @@ -1183,10 +1395,11 @@ 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. See the bundled "Force Login" plugin for a - usage example. + Your plugin might need this to further restrict access to API methods. .. important:: @@ -1199,10 +1412,11 @@ 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. See the bundled "Force Login" plugin for a - usage example. + Your plugin might need this to further restrict access to API methods. .. important:: @@ -1215,10 +1429,11 @@ 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. See the bundled - "Force Login" plugin for a usage example. + Your plugin might need to this to restrict acccess to downloads and webcam snapshots further. .. important:: @@ -1231,6 +1446,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. @@ -1273,6 +1490,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 @@ -1340,9 +1559,9 @@ octoprint.server.sockjs.authed .. py:function:: socket_authed_hook(socket, user, *args, **kwargs): - Allows plugins to be notified that a user got authenticated or deauthenticated on the socket (e.g. due to logout). + .. versionadded:: 1.3.10 - See the bundled :ref:`Forcelogin Plugin ` for an example on how to utilize this. + 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 :param object user: the user that got authenticated on the socket, or None if the user got deauthenticated @@ -1354,6 +1573,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`` @@ -1373,6 +1594,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. @@ -1393,6 +1616,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. @@ -1419,6 +1644,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. @@ -1525,38 +1752,40 @@ octoprint.ui.web.templatetypes :return: a list of 3-tuples (template type, rule, sorting spec) :rtype: list -.. _sec-plugins-hook-users-factory: +.. _sec-plugins-hook-theming-dialog: -octoprint.access.users.factory -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +octoprint.theming. +~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. py:function:: user_manager_factory_hook(components, settings, *args, **kwargs) +This actually describes two hooks: - 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. + * ``octoprint.theming.login`` + * ``octoprint.theming.recovery`` - The provided ``components`` is a dictionary containing the already initialized system components: +.. py:function:: ui_theming_hook(*args, **kwargs) - * ``plugin_manager``: The :class:`~octoprint.plugin.core.PluginManager` - * ``printer_profile_manager``: The :class:`~octoprint.printer.profile.PrinterProfileManager` - * ``event_bus``: The :class:`~octoprint.events.EventManager` - * ``analysis_queue``: The :class:`~octoprint.filemanager.analysis.AnalysisQueue` - * ``slicing_manager``: The :class:`~octoprint.slicing.SlicingManager` - * ``file_manager``: The :class:`~octoprint.filemanager.FileManager` - * ``plugin_lifecycle_manager``: The :class:`~octoprint.server.LifecycleManager` - * ``preemptive_cache``: The :class:`~octoprint.server.util.flask.PreemptiveCache` + .. versionadded:: 1.5.0 - If the factory returns anything but ``None``, it will be assigned to the global ``userManager`` instance. + 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. - If none of the registered factories return a user manager instance, the class referenced by the ``config.yaml`` - entry ``accessControl.userManager`` will be initialized if possible, otherwise a stock - :class:`~octoprint.access.users.FilebasedUserManager` will be instantiated, linked to the default user storage - file ``~/.octoprint/users.yaml``. + Example usage by a plugin: - :param dict components: System components to use for user manager instance initialization - :param SettingsManager settings: The global settings manager instance to fetch configuration values from if necessary - :return: The ``userManager`` instance to use globally. - :rtype: UserManager subclass or None + .. 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: @@ -1566,6 +1795,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. @@ -1581,6 +1812,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/plugins/index.rst b/docs/plugins/index.rst index e04033b04..cf662f609 100644 --- a/docs/plugins/index.rst +++ b/docs/plugins/index.rst @@ -16,3 +16,4 @@ Developing Plugins viewmodels.rst gettingstarted.rst distributing.rst + python3_migration.rst diff --git a/docs/plugins/injectedproperties.rst b/docs/plugins/injectedproperties.rst index 15ee482d2..e531c3bca 100644 --- a/docs/plugins/injectedproperties.rst +++ b/docs/plugins/injectedproperties.rst @@ -22,7 +22,7 @@ An overview of these properties follows. data files etc). Plugins should not access this property directly but instead utilize :func:`~octoprint.plugin.types.OctoPrintPlugin.get_plugin_data_folder` which will make sure the path actually does exist and if not create it before returning it. ``self._logger`` - A `python logger instance `_ logging to the log target + A :py:class:`logging.Logger` instance logging to the log target ``octoprint.plugin.``. ``self._settings`` The plugin's personalized settings manager, injected only into plugins that include the :class:`~octoprint.plugin.SettingsPlugin` mixin. diff --git a/docs/plugins/mixins.rst b/docs/plugins/mixins.rst index 386ff3d26..105fb85e2 100644 --- a/docs/plugins/mixins.rst +++ b/docs/plugins/mixins.rst @@ -166,7 +166,7 @@ Now, the execution order of the ``on_after_startup`` method will be determined b This will result in the following messages to be generated: -.. code-block:: plain +.. code-block:: none Plugin B starting up Plugin C starting up diff --git a/docs/plugins/python3_migration.rst b/docs/plugins/python3_migration.rst new file mode 100644 index 000000000..170e039e7 --- /dev/null +++ b/docs/plugins/python3_migration.rst @@ -0,0 +1,377 @@ +.. _sec-plugins-python3: + +Migrating to Python 3 +===================== + +Python 2 is now EOL as of January 1st 2020. With the release of 1.4.0 OctoPrint will be compatible to both Python 2 and +Python 3. + +However, the same doesn't automatically hold true for all of the third party plugins for OctoPrint out there - it will +fall to their authors to ensure compatibility to both Python versions. + +This guide is supposed to help plugin authors in making sure their plugins run under Python 2 as well as Python 3, +which for now is the goal for OctoPrint's ecosystem, as we'll have to live with existing legacy Python 2 installations +for a while to come (the plan is to stay Python 2 compatible until roughly a year after the release of 1.4.0). + +.. contents:: + :local: + +.. _sec-plugins-python3-venv: + +How to get a Python 3 virtual environment with OctoPrint +-------------------------------------------------------- + +In order to test your plugins for Python 3 compatibility and also to allow for ongoing maintenance against both Python +versions, you should create a Python 3 virtual environment next to your Python 2 one. You can then quickly switch between +Python 2 and Python 3 simply by ``activate``-ing whichever one you need. + +You can create a Python 3 virtualenv next to your (existing) Python 2 virtualenv and then just activate which one you +currently want to use. + +After installing Python 3 on your development system it's as easy as supplying ``--python=/path/to/python3executable`` +to ``virtualenv``, e.g.: + +.. code-block:: none + + virtualenv --python=/usr/bin/python3 venv3 + +That will have the virtualenv be created based on Python 3, regardless of whether it's currently running under Python +2 or 3. The same works for Python 2 btw: + +.. code-block:: none + + virtualenv --python=/usr/bin/python2 venv2 + +After creating the virtual environment, make sure to activate & install OctoPrint into it: + +.. code-block:: none + + source venv3/bin/activate + pip install "OctoPrint>=1.4.0rc1" + +Then create an editable install of your plugin, start the server and start testing: + +.. code-block:: none + + pip install -e path/to/your/plugin + octoprint serve --debug + +.. note:: + + On Windows that will probably look something like this instead: + + .. code-block:: none + + virtualenv --python=C:/Python37/python.exe venv37 + venv3/Script/activate.bat + pip install "OctoPrint>=1.4.0rc1" + pip install -e path/to/your/plugin + octoprint serve --debug + +.. note:: + + If you want to migrate your existing OctoPrint install *on OctoPi 0.17.0* to Python 3, I suggest to first make a + :ref:`backup `, then move the existing venv ``/home/pi/oprint`` out of the way and + create a new one based on Python 3 (which should already be present on current OctoPi images): + + .. code-block:: none + + mv ~/oprint ~/oprint.py2 + virtualenv --python=/usr/bin/python3 oprint + source ~/oprint/bin/activate + pip install "OctoPrint>=1.4.0" + sudo service octoprint restart + +.. _sec-plugins-python3-markup: + +Telling OctoPrint your plugin is Python 3 ready +----------------------------------------------- + +In order for OctoPrint to even load your plugin when it's running under Python 3, it first needs to know your plugin is +compatible to a Python 3 environment. By default OctoPrint will assume your plugin isn't and refuse to load it when +running under Python 3 itself. + +To tell OctoPrint about this, all you need is to set the ``__plugin_pythoncompat__`` property in your plugins's ``__init__.py`` +accordingly, e.g. + +.. code-block:: python + + __plugin_pythoncompat__ = ">=2.7,<4" + +This would tell OctoPrint that your plugin is compatible to all Python versions between 2.7 and 3.x. This should be +your target compatibility range for now. + +If at a later date you want to go all-in on Python 3 and mark your plugin as no longer supporting Python 2, tell +OctoPrint about this as well: + +.. code-block:: python + + __plugin_pythoncompat__ = ">=3,<4" + +.. note:: + + You can also tell OctoPrint to ignore the Python compatibility flags for a specific plugin via `config.yaml`: + + .. code-block:: yaml + + plugins: + _forcedCompatible: + - "myplugin" + - "anotherplugin" + + Note that this should only be used temporarily during testing and migration, or to mark an important plugin + not under your own control that actually works fine under Python 3 out of the box as compatible while waiting + until the plugin author has pushed an update including the needed flags. Do not just blindly mark third party + plugins as compatible and then open support requests if that causes issues in your setup. + +Once your plugin is ensured to be compatible and you've released a new version that includes the necessary compatibility +flag and changes, is done you also need to mark up your plugin in the Official Plugin Repository (if it's registered +therein) so that OctoPrint's built-in Plugin Manager will see that your plugin is compatible as well and allow users +to install it through it. In order to do that, you need to add a new flag compatibility.python to the front matter in +your plugin registration file and file a pull request for that. Adjust the markdown file so that it contains this: + +.. code-block:: yaml + + compatibility: + python: ">=2.7,<3" + +The value here follows the same mechanism as the ``__plugin_pythoncompat__`` property, so ``>=2.7,<3`` for 2 and 3 +support and ``>=3,<4`` for 3+ support. + +.. warning:: + + Do **not** just mark your plugin as compatible without diligent testing that it actually does work as expected and + without flooding ``octoprint.log`` with warnings and errors! + +.. _sec-plugins-python3-pitfalls: + +Common pitfalls during migration +-------------------------------- + +Some of the changes in Python 3 compared to Python 2 are sadly backwards incompatible and usually cause a number of +common issues in code written for Python 2 when run under Python 3. By now they are pretty well documented and there +exist a number of helpful and comprehensive migration guides, three of which I want to mention here. + +One is the official Python 3 porting guide `Porting Python 2 Code to Python 3 `__ +which sums up all the important changes and also gives hints on how best to go about running a project which supports +both versions for now. + +The second is the `Writing Python 2-3 compatible code `__ cheat sheet +from the Python-Future project, which is a comprehensive list of idioms that are compatible to both Python 2 and 3 and +will make your code run under both, utilizing `future `__ and `six `__. +I can strongly recommend this cheat sheet, it's what primarily guided me during the migration phase as well. + +The third one is the free online book `Support Python 3: An in-depth guide `__, and +especially its chapter on `Common migration problems `__ in which you'll find +extensive descriptions of the most troublesome changes in Python 3 and how to overcome them. Please note that with +regards to the contents of this book, we are aiming for the "Python 2 and Python 3 without conversion" strategy, so +code that runs in both environments. Sadly this book is a bit outdated by now and still references some long-out versions +as "upcoming", so with regards to compatible idioms to use, best stick to the Python-Future cheat sheet. + +Looking at the issues encountered by some plugin authors and also my own experiences during the Python 3 migration of +OctoPrint's code, the most common problems for these scenarios seem to be byte vs unicode issues, trouble with absolute +imports, changes in integer division behaviour and the switch of map, filter and zip to return iterators instead of +lists and causing issues in the following code due to that. + +.. _sec-plugins-python3-pitfalls-strings: + +Bytes vs unicode +................ + +One of if not the most problematic change between Python 2 and 3 surely must be the change in string handling. Under +Python 2 your basic string was a byte string, but it could also magically turn into a unicode string depending on what +you wrote into it. That did cause some confusion, especially in APIs, and caused quite a mess, which is why the decision +was made to go for distinct text and binary types instead, and making the string literal always be a (unicode) text. + +.. note:: + + Please note that these changes in string handling also affect several Python APIs that operate on files and streams + and thus might also affect parts of OctoPrint's plugin interface that inherit from these APIs. Currently only one such + case has been reported, as OctoPrint's :py:class:`~octoprint.filemanager.util.LineProcessorStream` will return bytes + instead of str on its ``process_line`` function under Python 3 - so here's a heads-up if your plugin happens to utilize that. + +Obviously, that will lead to issues in code using "just strings" when run under Python 2 vs 3. The first step to solve +these problems would be to make your scripts behave the same under Python 2 and 3 by putting this right at the top of +all your plugin's python files: + +.. code-block:: python + + from __future__ import unicode_literals + +That will make your files behave as if they were running under Python 3, even when run under Python 2, and your string +literals will now be the text data type, which - annoyingly - is a different one under Python 2 vs 3, ``unicode`` vs ``str`` to +be exact. Heads-up here - under Python 2 there's also a ``str`` type, but that one is for binary data. Yes, I know, this +ain't fun. + +In any case, once you've done this, make sure that everything in your code that should be text is text (``unicode`` under +Python 2, ``str`` under Python 3), and everything that should be binary is binary (``str`` under Python 2, ``bytes`` under Python 3). +A good rule of thumb is that you usually want to use text as much as possible within your application and only convert +to/from bytes at the outskirts, e.g. when writing to a file, a socket or something else machine like. Note that you do +NOT need to convert to bytes when implementing API endpoints that return JSON, as that should use text with unicode +anyhow. + +OctoPrint includes two utility methods you should use to ensure your strings enter/exit your code in the right format, +under both Python versions: :py:func:`octoprint.util.to_bytes` and :py:func:`octoprint.util.to_unicode`. Use them to ensure the correct data +types and to avoid weird conversion and encoding issues during runtime. + +You can read more about this specific issue in the corresponding section of the +`Python porting guide `__ and also in the +`cheat sheet `__. + +.. _sec-plugins-python3-pitfalls-absolute-imports: + +Absolute imports +................ + +Python 3 now defaults to absolute imports, meaning that trying to import a sub package with a + +.. code-block:: python + + import my_sub_package + +will now fail with an error. You'll need to explicitly make the import a relative one: + +.. code-block:: python + + from . import my_sub_package + +To make your code behave the same in that regard unter both Python 2 and Python 3, you should add the corresponding +future import: + +.. code-block:: python + + from __future__ import absolute_imports + +You can read more about this specific issue in the +`cheat sheet `__ and also in +`the book `__. + +.. _sec-plugins-python3-pitfalls-version-specific-imports: + +Version specific imports +........................ + +Sometimes it is necessary to use an import statement that is explicitly related to a specific Python version, e.g. due to +a package change between Python 2 and 3. You can do this by first trying the Python 3 import and if that doesn't work +out trying the Python 2 import instead: + +.. code-block:: python + + try: + import queue + except ImportError: + import Queue as queue + +This should be the preferred method of handling situations like this. If you actually do need to do explicit version +specific imports that cannot be handled this way, you can check for the Python version like this: + +.. code-block:: python + + import sys + if sys.version[0] == '2': + # Python 2 specific imports + else: + # Python 3 specific imports + +.. _sec-plugins-python3-pitfalls-intdiv: + +Integer division +................ + +When you divide two integers in Python 2 you'll get back an integer, rounded down. In Python 3 however you'll now get +a float. That means you might have to revisit some places where you do integer divisions and might rely on the result +to be an integer as well (e.g. when using a calculation result as an index in an array or something like that). + +Yet again there's a future-import to apply to your files in order to at least have them behave the same in that regard +under both Python 2 and Python 3: + +.. code-block:: python + + from __future__ import division + +You can read more about this specific issue in the `Python porting guide `__ +and in the `cheat sheet `__. + +.. _sec-plugins-python3-pitfalls-iterators: + +Iterators instead of list from map, filter, zip +............................................... + +The built-in functions ``map``, ``filter`` and ``zip`` return a ``list`` with their result in Python 2. In Python 3 they have been +switched to returning iterators. That can cause trouble with code handling the result (e.g. if you try to return it as +part of a JSON response on an API endpoint). + +The easiest way to solve this is to make sure to wrap any ``map``/``filter``/``zip`` calls into a ``list`` constructor if the result is +to be used outside of the calling code (even though that comes with a small performance penalty under Python 2): + +.. code-block:: python + + result1 = filter(lambda x: x is not None, my_collection) + result2 = list(filter(lambda x: x is not None, my_collection)) + + assert(isinstance(result1, list)) # Python 2 passes, Python 3 fails + assert(isinstance(result2, list)) # Python 2 and 3 pass + +There also exist further options, take a look at the `cheat sheet `__. + +.. _sec-plugins-python3-checklist: + +Checklist +--------- + +As a summary, follow this checklist to migrate your plugin to be compatible to both Python 2 and 3: + + * Create a Python 3 virtualenv and install OctoPrint and your plugin into it for testing. + * Tell OctoPrint your plugin is Python 2 and 3 compatible by adding a new property ``__plugin_pycompat__`` to its + ``__init__.py``: + + .. code-block:: python + + __plugin_pythoncompat__ = ">=2.7,<4" + + * Add a compatibility header to all `py` files to ensure similar basic behaviour under Python 2 and Python 3: + + .. code-block:: python + + # -*- coding: utf-8 -*- + from __future__ import absolute_import, division, print_function, unicode_literals + + * Thorougly test your plugin under Python 3. Pay special attention to any kind of string handling issues, integer + division, relative imports from your plugin package and how the results of ``map``, ``filter`` and ``zip`` are + used in your code, as those have proven to be the biggest issues during past migrations. + * Once everything works under both Python versions and you've prepared a new release of your plugin (don't forget to + increment the version!), update your registration file in the Official Plugin Repository to include the correct + Python compatibility information as well: + + .. code-block:: yaml + + compatibility: + python: ">=2.7,<4" + +.. _sec-plugins-python3-furtherreading: + +Further reading +--------------- + +.. seealso:: + + `Porting Python 2 Code to Python 3 `__ + The official Python 3 porting guide which sums up all the important changes and also gives hints on how best to + go about running a project which supports both versions for now. + + `Cheat Sheet: Writing Python 2-3 compatible code `__ + A comprehensive list of idioms that are compatible to both Python 2 and 3 and will make your code run under both, + utilizing `future `__ and `six `__. Strongly recommended. + + `Supporting Python 3: An in-depth guide `__ + A free online book on the switch to Python 3. Sadly seems a bit outdated by now, so with regards to compatible + idioms to use, best stick to the cheat sheet. Gives some interesting background however. + + `Towards Python 3 and OctoPrint 1.4.0 `__ + Forum topic discussing OctoPrint 1.4.0's roadmap including Python 3 compatibility and time frame. + + `Migrating plugins to Python 2 & 3 compatibility - experiences? `__ + Forum topic collecting experiences by plugin developers in migrating their plugins to achieve Python 2 & 3 + compatibility. + + diff --git a/docs/plugins/viewmodels.rst b/docs/plugins/viewmodels.rst index a5fc5bd46..91759647f 100644 --- a/docs/plugins/viewmodels.rst +++ b/docs/plugins/viewmodels.rst @@ -238,6 +238,11 @@ getAdditionalControls() Your view model may return additional custom control definitions for inclusion on the "Control" tab of OctoPrint's interface. See :ref:`the custom control feature`. + .. note:: + + Controls injected from a view model do not support feedback controls (as defined by + ``regex`` and ``template``). + onSettingsShown() Called when the settings dialog is shown. @@ -254,6 +259,10 @@ onUserSettingsShown() onUserSettingsHidden() Called when the user settings dialog is hidden. +onUserSettingsBeforeSave() + Called just before the user settings view model is sent to the server. This is useful, for example, if your plugin + needs to compute persisted settings from a custom view model. + onWizardDetails(response) Called with the response from the wizard detail API call initiated before opening the wizard dialog. Will contain the data from all :class:`~octoprint.plugin.WizardPlugin` implementations returned by their :meth:`~octoprint.plugin.WizardPlugin.get_wizard_details` @@ -438,7 +447,7 @@ Web interface reconnect .. seealso:: - `OctoPrint's core viewmodels `_ + `OctoPrint's core viewmodels `_ OctoPrint's own view models use the same mechanisms for interacting with each other and the web application as plugins. Their source code is therefore a good point of reference on how to achieve certain things. `KnockoutJS documentation `_ diff --git a/docs/sphinxext/codeblockext.py b/docs/sphinxext/codeblockext.py index a5ed06548..645a88d55 100644 --- a/docs/sphinxext/codeblockext.py +++ b/docs/sphinxext/codeblockext.py @@ -1,18 +1,13 @@ -# -*- coding: utf-8 -*- -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 import sphinx.highlighting -from sphinx.highlighting import PygmentsBridge from sphinx.ext import doctest -from sphinx.util.texescape import tex_hl_escape_map_new -from docutils.nodes import General, FixedTextElement, literal_block, container +from docutils import nodes from docutils.parsers.rst import directives from six import text_type @@ -22,237 +17,264 @@ from pygments.filters import VisibleWhitespaceFilter, ErrorToken from pygments.lexers.python import PythonConsoleLexer from pygments.util import ClassNotFound +if False: + # 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(General, 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. - """ - @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 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. + """ + + @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): - # 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, 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, 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 - -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 - """ - - def __init__(self, bridge, whitespace): - self._bridge = bridge - self._whitespace = whitespace - - 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) - - # 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 - - 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 - - # 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() - - # 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() - - # 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 - - # MODIFIED: replaced by whitespace wrapped call - with whitespace(sphinx.highlighting.lexers["none"]) as l: - hlsource = highlight(source, l, formatter) - # /MODIFIED - if self._bridge.dest == 'html': - return hlsource - else: - if not isinstance(hlsource, text_type): # Py2 / Pygments < 1.6 - hlsource = hlsource.decode() - return hlsource.translate(tex_hl_escape_map_new) + def _wrap_literal_block(self, node): + literal = literal_block_ext.from_literal_block(node) + literal["whitespace"] = "whitespace" in self.options + return literal -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 +class PygmentsBridgeExt: + """ + Wrapper for :class:`PygmentsBridge`, delegates everything to the wrapped ``bridge`` but :method:`highlight_block`, + which calls the parent implementation for lexer selection, then + """ - self._orig_highlighter = self.translator.highlighter + def __init__(self, bridge, whitespace): + self._bridge = bridge + self._whitespace = whitespace - 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 __getattr__(self, item): + return getattr(self._bridge, item) - def __exit__(self, exc_type, exc_val, exc_tb): - self.translator.highlighter = self._orig_highlighter + 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. + + class whitespace: + 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 __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. + + 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") + + 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) + + # 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 + + +class whitespace_highlighter: + """ + 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 + + self._orig_highlighter = self.translator.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) - return dict(version="0.1") + return {"version": "0.1"} diff --git a/docs/sphinxext/onlineinclude.py b/docs/sphinxext/onlineinclude.py index 4769faa21..bcb3404cc 100644 --- a/docs/sphinxext/onlineinclude.py +++ b/docs/sphinxext/onlineinclude.py @@ -1,8 +1,5 @@ -# -*- coding: utf-8 -*- -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,105 +7,118 @@ import codecs import requests from contextlib import closing -from sphinx.directives.code import LiteralIncludeReader, LiteralInclude, dedent_lines, \ - nodes, set_source_info, 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)] - env = document.settings.env + try: + location = self.state_machine.get_source_and_line(self.lineno) + url = self.arguments[0] - # convert options['diff'] to absolute path - if 'diff' in self.options: - _, path = env.relfn2path(self.options['diff']) - self.options['diff'] = path + reader = OnlineIncludeReader(url, self.options, self.config) + text, lines = reader.read(location=location) - try: - location = self.state_machine.get_source_and_line(self.lineno) - url = self.arguments[0] + 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 - reader = OnlineIncludeReader(url, self.options, env.config) - text, lines = reader.read(location=location) + if "caption" in self.options: + caption = self.options["caption"] or self.arguments[0] + retnode = container_wrapper(self, retnode, caption) - 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 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) - 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) - - 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) diff --git a/run b/run index f67e9cbfd..fdc3699b8 100755 --- a/run +++ b/run @@ -1,7 +1,4 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - import os import sys @@ -10,17 +7,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/scripts/README.md b/scripts/README.md index 8fbc44621..14792931b 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -4,14 +4,36 @@ Assumes OctoPrint is installed under user pi at /home/pi/OctoPrint/venv/bin/octo setup you'll need to adjust octoprint.default (init) or octoprint.service (systemd) accordingly. ## init +Download the init.d files to the locations shown: ``` octoprint.default => /etc/default/octoprint octoprint.init => /etc/init.d/octoprint ``` +Next, enable and start the `octoprint` service: + +```sh +# Enable octoprint service +sudo update-rc.d octoprint defaults + +# and start it +sudo service octoprint start +``` + ## systemd +Download the systemd files to the locations shown: ``` -octoprint.service => /etc/systemd/service/octoprint.service +octoprint.service => /etc/systemd/system/octoprint.service +``` + +Next, enable and start the `octoprint` service: + +```sh +# Enable octoprint service +sudo systemctl enable octoprint + +# and start it +sudo systemctl start octoprint ``` diff --git a/scripts/octoprint.service b/scripts/octoprint.service index e71e07b53..ae5405c34 100644 --- a/scripts/octoprint.service +++ b/scripts/octoprint.service @@ -4,7 +4,9 @@ After=network-online.target Wants=network-online.target [Service] -Type=simple +Environment="LC_ALL=C.UTF-8" +Environment="LANG=C.UTF-8" +Type=exec User=pi ExecStart=/home/pi/OctoPrint/venv/bin/octoprint diff --git a/setup.cfg b/setup.cfg index 24ae4b6df..4b5d8f589 100644 --- a/setup.cfg +++ b/setup.cfg @@ -12,3 +12,24 @@ versionfile_build = octoprint/_version.py tag_prefix = parentdir_prefix = lookupfile = .versioneer-lookup + +[flake8] +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 ae4ba6a9a..c0abd505c 100644 --- a/setup.py +++ b/setup.py @@ -1,265 +1,272 @@ -#!/usr/bin/env python2 -# coding=utf-8 - -from setuptools import setup, find_packages -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" +PYTHON_REQUIRES = ">=3.7,<4" + +# Requirements for setup.py +SETUP_REQUIRES = [ + "markdown>=3.2.2,<4", +] # Requirements for our application INSTALL_REQUIRES = [ - # 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 - - "flask>=0.12,<0.13", # newer versions require newer Jinja versions - "Jinja2>=2.8.1,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't - # guarantee backwards compatibility for plugins and such with that - # version, hence we need to pin to a lower version for now. See #1697 - "tornado==4.5.3", # a memory leak was observed in tornado >= 5, see #2585 - "regex!=2018.11.6", # avoid broken 2018.11.6. See #2874 - - # anything below this should be checked on releases for new versions - - "Flask-Login>=0.4.1,<0.5", - "Flask-Principal>=0.4,<0.5", - "Flask-Babel>=0.12,<0.13", - "Flask-Assets>=0.12,<0.13", - "werkzeug>=0.15.1,<0.16", - "cachelib>=0.1,<0.2", - "PyYAML>=5.1,<6", - "markdown>=3.0,<3.1", - "pyserial>=3.4,<3.5", - "netaddr>=0.7.19,<0.8", - "watchdog>=0.9.0,<0.10", - "sarge==0.1.5post0", - "netifaces>=0.10.9,<0.11", - "pylru>=1.2,<1.3", - "rsa>=4.0,<5", - "pkginfo>=1.5.0.1,<1.6", - "requests>=2.21.0,<3", - "semantic_version>=2.6,<2.7", - "psutil>=5.6.1,<5.7", - "Click>=7,<8", - "awesome-slugify>=1.6.5,<1.7", - "feedparser>=5.2.1,<5.3", - "future>=0.17,<0.18", - "websocket-client>=0.56,<0.57", - "wrapt>=1.11.1,<1.12", - "emoji>=0.5.1,<0.6", - "frozendict>=1.2,<1.3", - "sentry-sdk==0.7.7", - "filetype>=1.0.5,<2" -] - -# Python 2 specific requirements -INSTALL_REQUIRES_PYTHON2 = [ - "futures>=3.2,<3.3", - "monotonic>=1.5,<1.6", - "scandir>=1.10,<1.11", - "chainmap>=1.0.3,<1.1", - "typing>=3.6.6,<4" + # additional OctoPrint plugins that are maintained on a different release cycle + "OctoPrint-FirmwareCheck>=2021.2.4", + "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 + "regex!=2018.11.6", # avoid broken 2018.11.6. See #2874 + # anything below this should be checked on releases for new versions + "tornado>=6.0.4,<7", + "markdown>=3.2.2,<4", + "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==1.0.0", + "sarge==0.1.5post0", + "netifaces>=0.10.9,<1", + "pylru>=1.2,<2", + "rsa>=4.0,<5", + "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>=6.0.2,<7", + "future>=0.18.2,<1", # not really needed anymore, but leaving in for py2/3 compat plugins + "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", + "zeroconf>=0.24,<0.25", + "zipstream-new>=1.1.8,<1.2", + # vendor bundled dependencies + "unidecode>=0.04.14,<0.05", # dependency of awesome-slugify + "blinker>=1.4,<2", # dependency of flask_principal ] # OSX specific requirements INSTALL_REQUIRES_OSX = [ - "appdirs>=1.4.0", + "appdirs>=1.4.4", ] # Additional requirements for optional install options -EXTRA_REQUIRES = dict( - # Dependencies for developing OctoPrint - develop=[ - # Testing dependencies - "mock>=2.0.0,<3", - "pytest>=4.2.1,<5.0", - "pytest-doctest-custom>=1.0.0,<1.1", - "ddt", - - # linter - "flake8", - - # Documentation dependencies - "sphinx>=1.6,<1.7", - "sphinxcontrib-httpdomain", - "sphinxcontrib-mermaid>=0.3", - "sphinx_rtd_theme", - "readthedocs-sphinx-ext==0.5.7" - ], - - # Dependencies for developing OctoPrint plugins - plugins=[ - "cookiecutter>=1.6,<1.7" - ] -) +EXTRA_REQUIRES = { + "develop": [ + # Testing dependencies + "pytest>=5.4.3,<6", + "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 + "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 +EXTRA_REQUIRES[":sys_platform == 'darwin'"] = INSTALL_REQUIRES_OSX - # 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 - - 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 - -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # 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 -def data_copy_build_py_factory(files, baseclass): - class data_copy_build_py(baseclass): - files = dict() + with codecs.open(path, encoding="utf-8") as f: + return f.read() - def run(self): - import shutil - if not self.dry_run: - for directory, files in self.__class__.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 - else: - source = dest = entry - shutil.copy(source, os.path.join(target_dir, dest)) +def md_to_html_build_py_factory(files, baseclass): + class md_to_html_build_py(baseclass): + files = {} - baseclass.run(self) + 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") + + print("Rendering markdown from {} to {}".format(source, dest)) + + 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(data_copy_build_py)(data_copy_build_py.__name__, - (data_copy_build_py,), - dict(files=files)) def get_cmdclass(): - cmdclass = versioneer.get_cmdclass() + # make sure these are always available, even when run by dependabot + global versioneer, octoprint_setuptools, md_to_html_build_py_factory - # add clean command - cmdclass.update(dict(clean=octoprint_setuptools.CleanCommand.for_options(source_folder="src", eggs=["OctoPrint*.egg-info"]))) + cmdclass = versioneer.get_cmdclass() - # 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 clean command + cmdclass.update( + { + "clean": octoprint_setuptools.CleanCommand.for_options( + source_folder="src", eggs=["OctoPrint*.egg-info"] + ) + } + ) - cmdclass["build_py"] = data_copy_build_py_factory({ - "octoprint/templates/_data": [ - "AUTHORS.md", - "CHANGELOG.md", - "SUPPORTERS.md", - "THIRDPARTYLICENSES.md", - ] - }, cmdclass["build_py"] if "build_py" in cmdclass else _build_py) + # 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, + ) + ) - return cmdclass + 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 def params(): - name = "OctoPrint" - version = versioneer.get_version() - cmdclass = get_cmdclass() + # 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 - 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" + name = "OctoPrint" + version = versioneer.get_version() + cmdclass = get_cmdclass() - python_requires = PYTHON_REQUIRES - install_requires = INSTALL_REQUIRES - extras_require = EXTRA_REQUIRES - dependency_links = DEPENDENCY_LINKS + 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" - 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 :: 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" + python_requires = PYTHON_REQUIRES + setup_requires = SETUP_REQUIRES + install_requires = INSTALL_REQUIRES + extras_require = EXTRA_REQUIRES + dependency_links = DEPENDENCY_LINKS - 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" - } + 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 :: 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" - packages = 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'] - } + 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", + } - include_package_data = True - zip_safe = False + 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"] + } - if os.environ.get('READTHEDOCS', None) == 'True': - # we can't tell read the docs to please perform a pip install -e .[develop], so we help - # it a bit here by explicitly adding the development dependencies, which include our - # documentation dependencies - install_requires = install_requires + extras_require['develop'] + include_package_data = True + zip_safe = False - entry_points = { - "console_scripts": [ - "octoprint = octoprint:main" - ] - } + 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"] - return locals() + entry_points = {"console_scripts": ["octoprint = octoprint:main"]} -setup(**params()) + return locals() + + +setuptools.setup(**params()) diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index dc05299d9..4e6f41be7 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -1,636 +1,937 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- -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 a sound SSL environment or not.""" 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 +if 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 - 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 + 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 - -#~~ 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() - - 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) - - 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) - - 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) - - kwargs["logger"] = logger - if callable(after_logging): - after_logging(**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) - - # 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: - event_manager = init_event_manager(settings) - except Exception as ex: - raise FatalStartupError("Could not initialize event manager", cause=ex) - - kwargs["event_manager"] = event_manager - if callable(after_event_manager): - after_event_manager(**kwargs) - - try: - connectivity_checker = init_connectivity_checker(settings, event_manager) - except Exception as ex: - raise FatalStartupError("Could not initialize connectivity checker", cause=ex) - - kwargs["connectivity_checker"] = connectivity_checker - if callable(after_connectivity_checker): - after_connectivity_checker(**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) - - kwargs["plugin_manager"] = plugin_manager - if callable(after_plugin_manager): - after_plugin_manager(**kwargs) - - 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 __str__(self): + result = Exception.__str__(self) + if self.cause: + return "{}: {}".format(result, str(self.cause)) + else: + return result -def init_settings(basedir, configfile): - """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) +# ~~ init methods to bring up platform -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 init_platform( + basedir, + configfile, + overlays=None, + 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 = {} - logger = set_logging_config(config, debug, verbosity, uncaught_logger, uncaught_handler) + logger, recorder = preinit_logging( + debug, verbosity, uncaught_logger, uncaught_handler + ) + kwargs["logger"] = logger + kwargs["recorder"] = recorder - from octoprint.logging.handlers import RecordingLogHandler - recorder = RecordingLogHandler(level=log.DEBUG) - log.getLogger().addHandler(recorder) + if callable(after_preinit_logging): + after_preinit_logging(**kwargs) - return logger, recorder + try: + settings = init_settings(basedir, configfile, overlays=overlays) + 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) + + 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) + + kwargs["logger"] = logger + if callable(after_logging): + after_logging(**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) + + # 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: + event_manager = init_event_manager(settings) + except Exception as ex: + raise FatalStartupError("Could not initialize event manager", cause=ex) + + kwargs["event_manager"] = event_manager + if callable(after_event_manager): + after_event_manager(**kwargs) + + try: + connectivity_checker = init_connectivity_checker(settings, event_manager) + except Exception as ex: + raise FatalStartupError("Could not initialize connectivity checker", cause=ex) + + kwargs["connectivity_checker"] = connectivity_checker + if callable(after_connectivity_checker): + after_connectivity_checker(**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) + + kwargs["plugin_manager"] = plugin_manager + if callable(after_plugin_manager): + after_plugin_manager(**kwargs) + + 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_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_settings(basedir, configfile, overlays=None): + """Inits the settings instance based on basedir and configfile to use.""" - import os + from octoprint.settings import InvalidSettings, settings - from octoprint.util import dict_merge + try: + return settings( + init=True, basedir=basedir, configfile=configfile, overlays=overlays + ) + except InvalidSettings as e: + raise FatalStartupError(str(e)) - # 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" - }, - "communication": { - "format": "%(asctime)s - %(name)s - %(message)s" - }, - "commdebug": { - "format": "%(asctime)s - %(threadName)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") - }, - "connectionFile": { - "class": "octoprint.logging.handlers.CommunicationLogHandler", - "level": "DEBUG", - "formatter": "communication", - "backupCount": 3, - "filename": os.path.join(settings.getBaseFolder("logs"), "connection.log"), - "delay": True - }, - "commDebugFile": { - "class": "octoprint.logging.handlers.CommunicationLogHandler", - "level": "DEBUG", - "formatter": "commdebug", - "backupCount": 3, - "filename": os.path.join(settings.getBaseFolder("logs"), "commdebug.log"), - "delay": True - } - }, - "loggers": { - "CONNECTION": { - "level": "INFO", - "handlers": ["connectionFile"], - "propagate": False - }, - "COMMDEBUG": { - "level": "INFO", - "handlers": ["commDebugFile"], - "propagate": False - }, - "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" +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"]}, + } - 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") + logger = set_logging_config( + config, debug, verbosity, uncaught_logger, uncaught_handler + ) - 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) + from octoprint.logging.handlers import RecordingLogHandler - # 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) + recorder = RecordingLogHandler(level=log.DEBUG) + log.getLogger().addHandler(recorder) - # configure logging globally - return set_logging_config(config, debug, verbosity, uncaught_logger, uncaught_handler) + 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.""" + + import os + + from octoprint.util import dict_merge + + # default logging configuration + if default_config is None: + default_config = { + "version": 1, + "formatters": { + "simple": { + "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s" + }, + "serial": {"format": "%(asctime)s - %(message)s"}, + "timings": {"format": "%(asctime)s - %(message)s"}, + "timingscsv": {"format": "%(asctime)s;%(func)s;%(timing)f"}, + "communication": {"format": "%(asctime)s - %(name)s - %(message)s"}, + "commdebug": {"format": "%(asctime)s - %(threadName)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" + ), + }, + "connectionFile": { + "class": "octoprint.logging.handlers.CommunicationLogHandler", + "level": "DEBUG", + "formatter": "communication", + "backupCount": 3, + "filename": os.path.join( + settings.getBaseFolder("logs"), "connection.log" + ), + "delay": True, + }, + "commDebugFile": { + "class": "octoprint.logging.handlers.CommunicationLogHandler", + "level": "DEBUG", + "formatter": "commdebug", + "backupCount": 3, + "filename": os.path.join( + settings.getBaseFolder("logs"), "commdebug.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": { + "CONNECTION": { + "level": "INFO", + "handlers": ["connectionFile"], + "propagate": False, + }, + "COMMDEBUG": { + "level": "INFO", + "handlers": ["commDebugFile"], + "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" + + 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) + + # 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().__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) + from octoprint.logging.filters import TornadoAccessFilter - import warnings + logconfig.dictConfig(config) - categories = (DeprecationWarning, PendingDeprecationWarning) - if verbosity > 2: - warnings.simplefilter("always") - elif debug or verbosity > 0: - for category in categories: - warnings.simplefilter("always", category=category) + # make sure we log any warnings + log.captureWarnings(True) - # make sure we also log any uncaught exceptions - if uncaught_logger is None: - logger = log.getLogger(__name__) - else: - logger = log.getLogger(uncaught_logger) + import warnings - 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)) + categories = (DeprecationWarning, PendingDeprecationWarning) + if verbosity > 2: + warnings.simplefilter("always") + elif debug or verbosity > 0: + for category in categories: + warnings.simplefilter("always", category=category) - uncaught_handler = exception_logger - sys.excepthook = uncaught_handler + # make sure we also log any uncaught exceptions + if uncaught_logger is None: + logger = log.getLogger(__name__) + else: + logger = log.getLogger(uncaught_logger) - return logger + 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)) + + uncaught_handler = exception_logger + sys.excepthook = uncaught_handler + + tornado_logger = log.getLogger("tornado.access") + tornado_logger.addFilter(TornadoAccessFilter()) + + 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 = [] - compatibility_ignored_list = settings.get(["plugins", "_forcedCompatible"]) + if safe_mode: - 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) + def safe_mode_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 - settings_overlays = dict() - disabled_from_overlays = dict() + plugin_validators.append(safe_mode_validator) - def handle_plugin_loaded(name, plugin): - if plugin.instance and hasattr(plugin.instance, "__plugin_settings_overlay__"): - plugin.needs_restart = True + compatibility_ignored_list = settings.get(["plugins", "_forcedCompatible"]) - # 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 + from octoprint.plugin import plugin_manager - overlay = settings.load_overlay(overlay_definition) + 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, + ) - 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) + settings_overlays = {} + disabled_from_overlays = {} - settings_overlays[name] = overlay - logger.debug("Found settings overlay on plugin {}".format(name)) + def handle_plugin_loaded(name, plugin): + if plugin.instance and hasattr(plugin.instance, "__plugin_settings_overlay__"): + plugin.needs_restart = True - def handle_plugins_loaded(startup=False, initialize_implementations=True, force_reload=None): - if not startup: - return + # 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 - 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, x[2], x[0])) + overlay = settings.load_overlay(overlay_definition) - 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 + 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) - if addon in already_processed: - logger.info("Plugin {} wants to disable plugin {}, but that was already processed".format(name, addon)) + settings_overlays[name] = overlay + logger.debug("Found settings overlay on plugin {}".format(name)) - if not addon in already_processed and not addon in disabled_list: - disabled_list.append(addon) - logger.info("Disabling plugin {} as defined by plugin {}".format(addon, name)) - already_processed.append(name) + def handle_plugins_loaded( + startup=False, initialize_implementations=True, force_reload=None + ): + if not startup: + return - 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)) + from octoprint.util import sv - 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 + 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])), + ) + + 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 + + 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"]) + # 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): - event_manager.fire(Events.CONNECTIVITY_CHANGED, payload=dict(old=old_value, new=new_value)) + 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, - enabled=connectivityEnabled, - on_change=on_connectivity_change) + 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.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 23e03429c..3ae1d1803 100644 --- a/src/octoprint/__main__.py +++ b/src/octoprint/__main__.py @@ -1,11 +1,5 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -#import sys -#if sys.version_info[0] >= 3: -# raise RuntimeError("Sorry, OctoPrint does not yet support Python 3") - 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..7920e56d2 100644 --- a/src/octoprint/_version.py +++ b/src/octoprint/_version.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build @@ -14,11 +11,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 +61,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,11 +80,14 @@ 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: + except OSError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue @@ -116,12 +118,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") @@ -144,7 +151,7 @@ def git_get_keywords(versionfile_abs): if mo: keywords["full"] = mo.group(1) f.close() - except EnvironmentError: + except OSError: pass return keywords @@ -159,11 +166,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 +179,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 +199,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 +241,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 +276,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 +287,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 +299,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 +315,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 +332,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 +377,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 +388,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 +430,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 +461,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 +621,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 +653,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 +675,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 +684,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 +716,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/__init__.py b/src/octoprint/access/__init__.py index 599123f9b..a90c18f32 100644 --- a/src/octoprint/access/__init__.py +++ b/src/octoprint/access/__init__.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - ADMIN_GROUP = "admins" USER_GROUP = "users" GUEST_GROUP = "guests" diff --git a/src/octoprint/access/groups.py b/src/octoprint/access/groups.py index 9694b7d28..bb8ffef27 100644 --- a/src/octoprint/access/groups.py +++ b/src/octoprint/access/groups.py @@ -1,8 +1,5 @@ -# -*- coding: utf-8 -*- -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 @@ -12,590 +9,739 @@ 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 flask_principal import Need, Permission +from octoprint.vendor.flask_principal import Need, Permission -DEFAULT_ADMIN_PERMISSIONS = [Permissions.ADMIN] -"""Default admin permissions are the legacy permissions from before 1.4.0""" - -DEFAULT_USER_PERMISSIONS = [Permissions.STATUS, - Permissions.CONNECTION, - Permissions.WEBCAM, - Permissions.FILES_UPLOAD, - Permissions.FILES_DOWNLOAD, - Permissions.FILES_DELETE, - Permissions.FILES_SELECT, - Permissions.PRINT, - Permissions.MONITOR_TERMINAL, - Permissions.CONTROL, - Permissions.SLICE, - Permissions.TIMELAPSE_LIST, - Permissions.TIMELAPSE_ADMIN] -"""Default user permissions are the legacy permissions from before 1.4.0""" - -DEFAULT_GUEST_PERMISSIONS = [Permissions.STATUS, - Permissions.WEBCAM, - Permissions.FILES_DOWNLOAD, - Permissions.TIMELAPSE_LIST, - Permissions.MONITOR_TERMINAL] -"""Default guest permissions are the legacy permissions from before 1.4.0""" - - -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().__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 +class GroupManager: + @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 = [] - self._init_defaults() + def __init__(self): + self._logger = logging.getLogger(__name__) + self._group_change_listeners = [] - @property - def groups(self): - return [] + self._default_groups = [] + self._init_defaults() - @property - def admin_group(self): - return self.find_group(ADMIN_GROUP) + @property + def groups(self): + return [] - @property - def user_group(self): - return self.find_group(USER_GROUP) + @property + def admin_group(self): + return self.find_group(ADMIN_GROUP) - @property - def guest_group(self): - return self.find_group(GUEST_GROUP) + @property + def user_group(self): + return self.find_group(USER_GROUP) - def _init_defaults(self): - self.add_group(ADMIN_GROUP, - "Admins", - "Administrators", - self.default_permissions_for_group(ADMIN_GROUP), - [], - changeable=False, - removable=False, - save=False) - self.add_group(USER_GROUP, - "Users", - "All logged in users", - self.default_permissions_for_group(USER_GROUP), - [], - default=True, - removable=False, - toggleable=False, - save=False) - self.add_group(GUEST_GROUP, - "Guests", - "Anyone who is not currently logged in", - self.default_permissions_for_group(GUEST_GROUP), - [], - removable=False, - toggleable=False, - save=False), - self.add_group(READONLY_GROUP, - "Read-only Access", - "Group to gain read-only access", - self.default_permissions_for_group(READONLY_GROUP), - [], - changeable=False, - removable=False, - save=False) + @property + def guest_group(self): + return self.find_group(GUEST_GROUP) - def register_listener(self, listener): - self._group_change_listeners.append(listener) + def _init_defaults(self): + self._default_groups = { + ADMIN_GROUP: { + "name": "Admins", + "description": "Administrators", + "permissions": self.default_permissions_for_group(ADMIN_GROUP), + "subgroups": [], + "changeable": False, + "removable": False, + "default": False, + "toggleable": True, + }, + USER_GROUP: { + "name": "Operator", + "description": "Group to gain operator access", + "permissions": self.default_permissions_for_group(USER_GROUP), + "subgroups": [], + "changeable": True, + "default": True, + "removable": False, + "toggleable": True, + }, + GUEST_GROUP: { + "name": "Guests", + "description": "Anyone who is not currently logged in", + "permissions": self.default_permissions_for_group(GUEST_GROUP), + "subgroups": [], + "changeable": True, + "default": False, + "removable": False, + "toggleable": False, + }, + READONLY_GROUP: { + "name": "Read-only Access", + "description": "Group to gain read-only access", + "permissions": self.default_permissions_for_group(READONLY_GROUP), + "subgroups": [], + "changeable": False, + "removable": False, + "default": False, + "toggleable": True, + }, + } - def unregister_listener(self, listener): - self._group_change_listeners.remove(listener) + 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 add_group(self, key, name, description, permissions, subgroups, - default=False, removable=True, changeable=True, toggleable=True, save=True, notify=True): - pass + def register_listener(self, listener): + self._group_change_listeners.append(listener) - def update_group(self, key, description=None, permissions=None, subgroups=None, default=None, save=True, notify=True): - pass + def unregister_listener(self, listener): + self._group_change_listeners.remove(listener) - def remove_group(self, key, 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 find_group(self, key): - return None + def update_group( + self, + key, + description=None, + permissions=None, + subgroups=None, + default=None, + save=True, + notify=True, + ): + pass - def _to_permissions(self, *permissions): - return list(filter(lambda x: x is not None, - [Permissions.find(permission) for permission in permissions])) + def remove_group(self, key, save=True, notify=True): + pass - def _from_permissions(self, *permissions): - return [permission.key for permission in permissions] + def find_group(self, key): + return None - def _from_groups(self, *groups): - return [group.key for group in groups] + def _to_permissions(self, *permissions): + return list( + filter( + lambda x: x is not None, + [Permissions.find(permission) for permission in permissions], + ) + ) - def _to_groups(self, *groups): - return filter(lambda x: x is not None, - [self._to_group(g) for g in groups]) + def _from_permissions(self, *permissions): + return [permission.key for permission in permissions] - 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 _from_groups(self, *groups): + return [group.key for group in groups] - 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 _to_groups(self, *groups): + return list(filter(lambda x: x is not None, [self._to_group(g) for g in groups])) -class GroupChangeListener(object): + def _to_group(self, group): + if isinstance(group, Group): + return group + elif isinstance(group, str): + return self.find_group(group) + elif isinstance(group, dict): + return self.find_group(group.get("key")) + else: + return None - def on_group_added(self, group): - pass + 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 on_group_removed(self, group): - pass - def on_group_permissions_changed(self, group, added=None, removed=None): - pass +class GroupChangeListener: + def on_group_added(self, group): + pass - def on_group_subgroups_changed(self, group, added=None, removed=None): - pass + def on_group_removed(self, group): + 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 class FilebasedGroupManager(GroupManager): - 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") + FILE_VERSION = 2 - self._groupfile = path - self._groups = dict() - self._dirty = False + 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") - GroupManager.__init__(self) + self._groupfile = path + self._groups = {} + self._dirty = False - self._load() + GroupManager.__init__(self) - 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) + self._load() - if not "groups" in data: - groups = data - data = dict(groups=groups) + 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) - groups = data.get("groups", dict()) - tracked_permissions = data.get("tracked", list()) + if "groups" not in data: + groups = data + data = {"groups": groups} - for key, attributes in groups.items(): - if key in self._groups: - # group is already there (from the defaults most likely) - if not self._groups[key].is_changeable(): - # group may not be changed -> bail - continue + 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 - removable = self._groups[key].is_removable() - changeable = self._groups[key].is_changeable() - toggleable = self._groups[key].is_toggleable() - else: - removable = True - changeable = True - toggleable = True + groups = data.get("groups", {}) + tracked_permissions = data.get("tracked", list()) - 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) + 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 - subgroups = attributes.get("subgroups", []) + 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) - group = Group(key, attributes.get("name", ""), - description=attributes.get("description", ""), - permissions=permissions, - subgroups=subgroups, - default=attributes.get("default", False), - removable=removable, - changeable=changeable, - toggleable=toggleable) - self._groups[key] = group + 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) - for group in self._groups.values(): - group._subgroups = self._to_groups(*group._subgroups) + 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) - except Exception: - self._logger.exception("Error while loading groups from file {}".format(self._groupfile)) + subgroups = self._to_groups(*attributes.get("subgroups", [])) - def _save(self, force=False): - if self._groupfile is None or not self._dirty and not force: - return + group = Group( + key, + name, + description=description, + permissions=permissions, + subgroups=subgroups, + default=set_default, + removable=removable, + changeable=changeable, + toggleable=toggleable, + ) - groups = dict() - for key in self._groups.keys(): - group = self._groups[key] - groups[key] = dict( - name=group._name, - description=group._description, - permissions=self._from_permissions(*group._permissions), - subgroups=self._from_groups(*group._subgroups), - default=group._default - ) + 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 - data = dict(groups=groups, - tracked=[x.key for x in Permissions.all()]) + self._groups[key] = group - 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() + for group in self._groups.values(): + group._subgroups = self._to_groups(*group._subgroups) - @property - def groups(self): - return list(self._groups.values()) + if self._dirty: + self._save() - @property - def default_groups(self): - return [group for group in self._groups.values() if group.is_default()] + except Exception: + self._logger.exception( + "Error while loading groups from file {}".format(self._groupfile) + ) - def find_group(self, key): - if key is None: - return None - return self._groups.get(key) + def _save(self, force=False): + if self._groupfile is None or not self._dirty and not force: + return - 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) + 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() - if not permissions: - permissions = [] + data = { + "_version": self.FILE_VERSION, + "groups": groups, + "tracked": [x.key for x in Permissions.all()], + } - permissions = self._to_permissions(*permissions) - assert(all(map(lambda p: isinstance(p, OctoPrintPermission), permissions))) + with atomic_write( + self._groupfile, mode="wt", permissions=0o600, max_permissions=0o666 + ) as f: + import yaml - subgroups = self._to_groups(*subgroups) - assert(all(map(lambda g: isinstance(g, Group), subgroups))) + yaml.safe_dump( + data, f, default_flow_style=False, indent=4, allow_unicode=True + ) + self._dirty = False + self._load() - group = Group(key, name, - description=description, - permissions=permissions, - subgroups=subgroups, - default=default, - changeable=changeable, - removable=removable, - toggleable=toggleable) - self._groups[key] = group + @property + def groups(self): + return list(self._groups.values()) - if save: - self._dirty = True - self._save() + @property + def default_groups(self): + return [group for group in self._groups.values() if group.is_default()] - if notify: - self._notify_listeners("added", group) + def find_group(self, key): + if key is None: + return None + return self._groups.get(key) - def remove_group(self, key, save=True, notify=True): - """Removes a Group by key""" - group = self._to_group(key) - if group is None: - raise UnknownGroup(key) + 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) - if not group.is_removable(): - raise GroupUnremovable(key) + if not permissions: + permissions = [] - del self._groups[key] - self._dirty = True + permissions = self._to_permissions(*permissions) + assert all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)) - if save: - self._save() + subgroups = self._to_groups(*subgroups) + assert all(map(lambda g: isinstance(g, Group), subgroups)) - if notify: - self._notify_listeners("removed", group) + group = Group( + key, + name, + description=description, + permissions=permissions, + subgroups=subgroups, + default=default, + changeable=changeable, + removable=removable, + toggleable=toggleable, + ) + self._groups[key] = group - 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 save: + self._dirty = True + self._save() - if not group.is_changeable(): - raise GroupCantBeChanged(key) + if notify: + self._notify_listeners("added", group) - if description is not None and description != group.get_description(): - group.change_description(description) - self._dirty = True + 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) - notifications = [] + if not group.is_removable(): + raise GroupUnremovable(key) - if permissions is not None: - permissions = self._to_permissions(*permissions) - assert (all(map(lambda p: isinstance(p, OctoPrintPermission), permissions))) + del self._groups[key] + self._dirty = True - removed_permissions = list(set(group._permissions) - set(permissions)) - added_permissions = list(set(permissions) - set(group._permissions)) + if save: + self._save() - 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 notify: + self._notify_listeners("removed", group) - notifications.append((("permissions_changed", group), - dict(added=added_permissions, removed=removed_permissions))) + 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 subgroups is not None: - subgroups = self._to_groups(*subgroups) - assert(all(map(lambda g: isinstance(g, Group), subgroups))) + if not group.is_changeable(): + raise GroupCantBeChanged(key) - removed_subgroups = list(set(group._subgroups) - set(subgroups)) - added_subgroups = list(set(subgroups) - set(group._subgroups)) + if description is not None and description != group.get_description(): + group.change_description(description) + self._dirty = True - 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 = [] - notifications.append((("subgroups_changed", group), - dict(added=added_subgroups, removed=removed_subgroups))) + if permissions is not None: + permissions = self._to_permissions(*permissions) + assert all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)) - if default is not None: - group.change_default(default) - self._dirty = True + removed_permissions = list(set(group._permissions) - set(permissions)) + added_permissions = list(set(permissions) - set(group._permissions)) - if self._dirty: - if save: - self._save() + 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 notify: - for args, kwargs in notifications: - self._notify_listeners(*args, **kwargs) + notifications.append( + ( + ("permissions_changed", group), + {"added": added_permissions, "removed": removed_permissions}, + ) + ) + + if subgroups is not None: + subgroups = self._to_groups(*subgroups) + assert all(map(lambda g: isinstance(g, Group), subgroups)) + + removed_subgroups = list(set(group._subgroups) - set(subgroups)) + added_subgroups = list(set(subgroups) - set(group._subgroups)) + + if removed_subgroups: + self._dirty = group.remove_subgroups_from_group(removed_subgroups) + if added_subgroups: + self._dirty = group.add_subgroups_to_group(added_subgroups) + + 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 +class Group: + 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 035814df0..d766b4b30 100644 --- a/src/octoprint/access/permissions.py +++ b/src/octoprint/access/permissions.py @@ -1,368 +1,459 @@ -# -*- coding: utf-8 -*- -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 flask_principal import Permission, PermissionDenied, RoleNeed, Need - -from functools import wraps from collections import OrderedDict, defaultdict +from functools import wraps -# noinspection PyCompatibility -from past.builtins import basestring +from flask import abort, g +from flask_babel import gettext -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: + if isinstance(need, Need): + result.append(need) + elif isinstance(need, Permission): + result += need.needs + elif isinstance(need, str): + 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 union(self, other): - """Create a new OctoPrintPermission with the requirements of the union of this - and other. + def get_description(self): + return self._description - :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 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 difference(self, other): - """Create a new OctoPrintPermission consisting of requirements in this - permission and not in the other. - """ + :param identity: The identity + """ + if self.needs and len(self.needs.intersection(identity.provides)) != len( + self.needs + ): + return False - p = self.__class__(self._name, self._description, *self.needs.difference(other.needs)) - p.excludes.update(self.excludes.difference(other.excludes)) - return p + if self.excludes and self.excludes.intersection(identity.provides): + return False - def __repr__(self): - return '{}({!r}, {!r}, {})'.format(self.__class__.__name__, - self.get_name(), - self.get_description(), - ', '.join(map(repr, self.needs))) + return True - def __hash__(self): - return self.get_name().__hash__() + def union(self, other): + """Create a new OctoPrintPermission with the requirements of the union of this + and other. - def __eq__(self, other): - return isinstance(other, OctoPrintPermission) and other.get_name() == self.get_name() + :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. + """ + + 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 __hash__(self): + return self.get_name().__hash__() + + 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 +class PluginIdentityContext: + """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, str): + 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)): +class Permissions(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 status information, e.g. job progress, " - "printer state, temperatures, ..."), - 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, 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"), - 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"), FILES_LIST, - default_groups=[USER_GROUP, READONLY_GROUP]) - FILES_DELETE = OctoPrintPermission("File Delete", - gettext("Allows users to delete files"), - RoleNeed("files_delete"), FILES_LIST, - default_groups=[USER_GROUP]) - FILES_SELECT = OctoPrintPermission("File Select", - gettext("Allows to select a file for printing"), - RoleNeed("files_select"), FILES_LIST, - 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. Includes the \"Select\" " - "permission"), - RoleNeed("print"), 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], + ) - GCODE_VIEWER = OctoPrintPermission("GCODE viewer", - gettext("Allows access to the GCODE viewer. Includes the \"File Download\"" - "permission."), - RoleNeed("gcodeviewer"), FILES_DOWNLOAD, - 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 = OctoPrintPermission("Settings", - gettext("Allows to manage 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 d309bad5b..62b61959f 100644 --- a/src/octoprint/access/users.py +++ b/src/octoprint/access/users.py @@ -1,1261 +1,1437 @@ -# -*- 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 time +import uuid -# noinspection PyCompatibility -from builtins import range, bytes +import wrapt +import yaml +from flask_login import AnonymousUserMixin, UserMixin +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, to_bytes, deprecated, monotonic_time +from octoprint.util import atomic_write, deprecated, generate_api_key from octoprint.util import get_fully_qualified_classname as fqcn +from octoprint.util import to_bytes -from octoprint.access.permissions import Permissions, OctoPrintPermission -from octoprint.access.groups import GroupChangeListener, Group -from past.builtins import basestring +class UserManager(GroupChangeListener): + def __init__(self, group_manager, settings=None): + self._group_manager = group_manager + self._group_manager.register_listener(self) -class UserManager(GroupChangeListener, object): - def __init__(self, group_manager, settings=None): - self._group_manager = group_manager - self._group_manager.register_listener(self) + self._logger = logging.getLogger(__name__) + self._session_users_by_session = {} + self._sessionids_by_userid = {} - self._logger = logging.getLogger(__name__) - self._session_users_by_session = dict() - self._sessionids_by_userid = dict() - self._enabled = True + if settings is None: + settings = s() + self._settings = settings - if settings is None: - settings = s() - self._settings = settings + self._login_status_listeners = [] - self._login_status_listeners = [] + def register_login_status_listener(self, listener): + self._login_status_listeners.append(listener) - def register_login_status_listener(self, listener): - self._login_status_listeners.append(listener) + def unregister_login_status_listener(self, listener): + self._login_status_listeners.remove(listener) - def unregister_login_status_listener(self, listener): - self._login_status_listeners.remove(listener) + def anonymous_user_factory(self): + return AnonymousUser([self._group_manager.guest_group]) - def anonymous_user_factory(self): - if self.enabled: - return AnonymousUser([self._group_manager.guest_group]) - else: - return AdminUser([self._group_manager.admin_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.debug("Logged in user: %r" % user) - - return user - - def logout_user(self, user): - 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: - del self._session_users_by_session[sessionid] - - for listener in self._login_status_listeners: - try: - listener.on_user_logged_out(user) - except Exception: - self._logger.exception("Error in on_user_logged_out on {!r}".format(listener), - extra=dict(callback=fqcn(listener))) - - self._logger.debug("Logged out user: %r" % user) - - def _cleanup_sessions(self): - for session, user in self._session_users_by_session.items(): - if not isinstance(user, SessionUser): - continue - if user.created + (24 * 60 * 60) < monotonic_time(): - self.logout_user(user) - - @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 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) - - -class LoginStatusListener(object): - - def on_user_logged_in(self, user): - pass - - def on_user_logged_out(self, user): - pass - - def on_user_modified(self, user): - pass - - def on_user_removed(self, userid): - pass + def cli_user_factory(self): + return LocalCliUser( + [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) < time.monotonic(): + 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, str): + # 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: + def on_user_logged_in(self, user): + pass + + def on_user_logged_out(self, user, stale=False): + pass + + def on_user_modified(self, user): + 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(): - permissions = [] - if "permissions" in attributes: - permissions = attributes["permissions"] - - groups = {self._group_manager.user_group} # the user group is mandatory for all logged in users - if "groups" in attributes: - groups |= set(attributes["groups"]) - - # 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 = ''.join('%02X' % z for z in bytes(uuid.uuid4().bytes)) - 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 +class MethodReplacedByBooleanProperty: + 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 - warn(DeprecationWarning(self._message.format(name=self._name)), stacklevel=2) - return self._attr + def __call__(self): + from warnings import warn - def __eq__(self, other): - return self._attr == other + warn(DeprecationWarning(self._message.format(name=self._name)), stacklevel=2) + return self._attr - def __ne__(self, other): - return self._attr != other + def __eq__(self, other): + return self._attr == other - def __bool__(self): - # Python 3 - return self._attr + def __ne__(self, other): + return self._attr != other - def __nonzero__(self): - # Python 2 - return self._attr + def __bool__(self): + 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 needs(self): - needs = set() + @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()) + ) - for permission in self.permissions: - if permission is not None: - needs = needs.union(permission.needs) + @property + def needs(self): + needs = set() - for group in self.groups: - if group is not None: - needs = needs.union(group.needs) + for permission in self.permissions: + if permission is not None: + needs = needs.union(permission.needs) - return needs + for group in self.groups: + if group is not None: + needs = needs.union(group.needs) - def has_permission(self, permission): - return self.has_needs(*permission.needs) + return needs - def has_needs(self, *needs): - if Permissions.ADMIN in self._permissions: - return True - return set(needs).issubset(self.needs) + def has_permission(self, permission): + return self.has_needs(*permission.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 has_needs(self, *needs): + return set(needs).issubset(self.needs) - # ~~ Deprecated methods & properties follow + 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, + ) + ) - # TODO: Remove deprecated methods & properties in OctoPrint 1.5.0 + # ~~ Deprecated methods & properties follow - asDict = deprecated("asDict has been renamed to as_dict", - includedoc="Replaced by :func:`as_dict`", - since="1.4.0")(as_dict) + # TODO: Remove deprecated methods & properties in OctoPrint 1.5.0 - @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) + asDict = deprecated( + "asDict has been renamed to as_dict", + includedoc="Replaced by :func:`as_dict`", + since="1.4.0", + )(as_dict) - @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_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("roles is deprecated, please use has_permission", since="1.4.0") - def roles(self): - return self._roles + @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 - 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 + @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 [] 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 = time.monotonic() + self._self_touched = time.monotonic() - @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 = time.monotonic() - @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 CLI key is used -##~~ User object to use when access control is disabled -class AdminUser(User): - def __init__(self, groups): - User.__init__(self, "_admin", "", True, [], groups) +class LocalCliUser(User): + def __init__(self, groups): + User.__init__(self, "_cli", "", True, [], groups) diff --git a/src/octoprint/cli/__init__.py b/src/octoprint/cli/__init__.py index 4a2a8c38b..bd386f202 100644 --- a/src/octoprint/cli/__init__.py +++ b/src/octoprint/cli/__init__.py @@ -1,177 +1,345 @@ -# -*- 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 -class OctoPrintContext(object): - """Custom context wrapping the standard options.""" +import octoprint + +click.disable_unicode_literals_warning = True + + +# ~~ click context + + +class OctoPrintContext: + """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), + overlays=get_ctx_obj_option(ctx, "overlays", 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. - """ + 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( + "--overlay", + "overlays", + type=click.Path(), + callback=set_ctx_obj_option, + is_eager=True, + multiple=True, + expose_value=False, + help="Specify additional config overlays 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..8b8f48a9f 100644 --- a/src/octoprint/cli/analysis.py +++ b/src/octoprint/cli/analysis.py @@ -1,22 +1,60 @@ -# -*- 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 sys + import click + click.disable_unicode_literals_warning = True -#~~ "octoprint util" commands +# ~~ "octoprint util" commands + + +def validate_result(result): + dimensions = ("depth", "height", "width") + printing_area = ("maxX", "maxY", "maxZ", "minX", "minY", "minZ") + + def validate_list(data): + return not any(map(invalid_float, data)) + + def validate_dict(data, keys): + for k in keys: + if k not in data or invalid_float(data[k]): + return False + return True + + def invalid_float(value): + return value is None or value == float("inf") or value == float("-inf") + + if "dimensions" not in result or not validate_dict(result["dimensions"], dimensions): + return False + + if "extrusion_length" not in result or not validate_list(result["extrusion_length"]): + return False + + if "extrusion_volume" not in result or not validate_list(result["extrusion_volume"]): + return False + + if "printing_area" not in result or not validate_dict( + result["printing_area"], printing_area + ): + return False + + if "total_time" not in result or invalid_float(result["total_time"]): + return False + + return True + @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 +68,83 @@ 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.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 = time.monotonic() + + 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(time.monotonic() - start_time)) + + result = interpreter.get_result() + if not validate_result(result): + click.echo( + "ERROR:Invalid analysis result, please create a bug report in OctoPrint's " + "issue tracker and be sure to also include the GCODE file with which this " + "happened" + ) + sys.exit(-1) + 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..e0d6f809f 100644 --- a/src/octoprint/cli/client.py +++ b/src/octoprint/cli/client.py @@ -1,107 +1,127 @@ -# -*- 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 os + +import click import octoprint_client +from octoprint import FatalStartupError, init_settings +from octoprint.cli import bulk_options, get_ctx_obj_option -from octoprint.cli import get_ctx_obj_option, bulk_options -from octoprint import init_settings, FatalStartupError +click.disable_unicode_literals_warning = True -from past.builtins import unicode class JsonStringParamType(click.ParamType): - name = "json" + name = "json" - def convert(self, value, param, ctx): - try: - return json.loads(value) - except Exception: - self.fail("%s is not a valid json string" % value, param, ctx) + def convert(self, value, param, ctx): + try: + return json.loads(value) + except Exception: + self.fail("%s is not a valid json string" % value, param, ctx) -def create_client(settings=None, apikey=None, host=None, port=None, httpuser=None, httppass=None, https=False, prefix=None): - assert(host is not None or settings is not None) - assert(port is not None or settings is not None) - assert(apikey is not None or settings is not None) +def create_client( + settings=None, + apikey=None, + host=None, + port=None, + httpuser=None, + httppass=None, + https=False, + prefix=None, +): + assert 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 = "127.0.0.1" + if not port: + port = settings.getInt(["server", "port"]) - if not apikey: - apikey = settings.get(["api", "key"]) + if not apikey: + cli_key_file = os.path.join(settings.getBaseFolder("generated"), "cli.key") + try: + with io.open(cli_key_file, "r", encoding="utf8") as f: + apikey = f.readline() + except Exception: + raise FatalStartupError( + "Can not authenticate with server at {}:{}, no key".format(host, port) + ) - 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 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 +129,9 @@ def log_response(response, status_code=True, body=True, headers=False): @click.option("--timeout", type=float, default=None) @click.pass_context def get(ctx, path, timeout): - """Performs a GET request against the specified server path.""" - r = ctx.obj.client.get(path, timeout=timeout) - log_response(r) + """Performs a GET request against the specified server path.""" + r = ctx.obj.client.get(path, timeout=timeout) + log_response(r) @client.command("post_json") @@ -120,9 +140,9 @@ def get(ctx, path, timeout): @click.option("--timeout", type=float, default=None) @click.pass_context def post_json(ctx, path, data, timeout): - """POSTs JSON data to the specified server path.""" - r = ctx.obj.client.post_json(path, data, timeout=timeout) - log_response(r) + """POSTs JSON data to the specified server path.""" + r = ctx.obj.client.post_json(path, data, timeout=timeout) + log_response(r) @client.command("patch_json") @@ -131,75 +151,118 @@ def post_json(ctx, path, data, timeout): @click.option("--timeout", type=float, default=None, help="Request timeout in seconds") @click.pass_context def patch_json(ctx, path, data, timeout): - """PATCHes JSON data to the specified server path.""" - r = ctx.obj.client.patch(path, data, encoding="json", timeout=timeout) - log_response(r) + """PATCHes JSON data to the specified server path.""" + r = ctx.obj.client.patch(path, data, encoding="json", timeout=timeout) + log_response(r) @client.command("post_from_file") @click.argument("path") -@click.argument("file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True)) +@click.argument( + "file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True) +) @click.option("--json", is_flag=True) @click.option("--yaml", is_flag=True) @click.option("--timeout", type=float, default=None, help="Request timeout in seconds") @click.pass_context def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout): - """POSTs JSON data to the specified server path, taking the data from the specified file.""" - if json_flag or yaml_flag: - if json_flag: - with io.open(file_path, 'rt') as fp: - data = json.load(fp) - else: - import yaml - with io.open(file_path, 'rt') as fp: - data = yaml.safe_load(fp) + """POSTs JSON data to the specified server path, taking the data from the specified file.""" + if json_flag or yaml_flag: + if json_flag: + with io.open(file_path, "rt") as fp: + data = json.load(fp) + else: + import yaml - r = ctx.obj.client.post_json(path, data, timeout=timeout) - else: - with io.open(file_path, 'rb') as fp: - data = fp.read() + with io.open(file_path, "rt") as fp: + data = yaml.safe_load(fp) - r = ctx.obj.client.post(path, data, timeout=timeout) + r = ctx.obj.client.post_json(path, data, timeout=timeout) + else: + with io.open(file_path, "rb") as fp: + data = fp.read() - log_response(r) + r = ctx.obj.client.post(path, data, timeout=timeout) + + log_response(r) @client.command("command") @click.argument("path") @click.argument("command") -@click.option("--str", "-s", "str_params", multiple=True, nargs=2, type=click.Tuple([unicode, unicode])) -@click.option("--int", "-i", "int_params", multiple=True, nargs=2, type=click.Tuple([unicode, int])) -@click.option("--float", "-f", "float_params", multiple=True, nargs=2, type=click.Tuple([unicode, float])) -@click.option("--bool", "-b", "bool_params", multiple=True, nargs=2, type=click.Tuple([unicode, bool])) +@click.option( + "--str", + "-s", + "str_params", + multiple=True, + nargs=2, + type=click.Tuple([str, str]), +) +@click.option( + "--int", "-i", "int_params", multiple=True, nargs=2, type=click.Tuple([str, int]) +) +@click.option( + "--float", + "-f", + "float_params", + multiple=True, + nargs=2, + type=click.Tuple([str, float]), +) +@click.option( + "--bool", + "-b", + "bool_params", + multiple=True, + nargs=2, + type=click.Tuple([str, 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([str, str]), +) @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 +270,45 @@ def upload(ctx, path, file_path, params, file_name, content_type, timeout): @click.option("--timeout", type=float, default=None, help="Request timeout in seconds") @click.pass_context def delete(ctx, path, timeout): - """Sends a DELETE request to the specified server path.""" - r = ctx.obj.client.delete(path, timeout=timeout) - log_response(r) + """Sends a DELETE request to the specified server path.""" + r = ctx.obj.client.delete(path, timeout=timeout) + log_response(r) @client.command("listen") @click.pass_context def listen(ctx): - def on_connect(ws): - click.echo(">>> Connected!") + def on_connect(ws): + click.echo("--- Connected!") - def on_close(ws): - click.echo(">>> Connection closed!") + def on_close(ws): + click.echo("--- Connection closed!") - def on_error(ws, error): - click.echo("!!! Error: {}".format(error)) + def on_error(ws, error): + click.echo("!!! Error: {}".format(error)) - def on_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..90349a365 100644 --- a/src/octoprint/cli/config.py +++ b/src/octoprint/cli/config.py @@ -1,95 +1,102 @@ -# -*- 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, force=True) + 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), + overlays=get_ctx_obj_option(ctx, "overlays", 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 +104,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 +115,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 +144,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 +172,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..7da5de9c6 100644 --- a/src/octoprint/cli/dev.py +++ b/src/octoprint/cli/dev.py @@ -1,239 +1,263 @@ -# -*- coding: utf-8 -*- -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, str): + 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 = {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 e628ae4c6..72d750bf1 100644 --- a/src/octoprint/cli/plugins.py +++ b/src/octoprint/cli/plugins.py @@ -1,110 +1,150 @@ -# -*- 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}, +} + +# ~~ "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() - # 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) + logging_config = dict_merge( + LOGGING_CONFIG, + { + "root": { + "level": logging.DEBUG if ctx.obj.verbosity > 0 else logging.WARNING + } + }, + ) + logging.config.dictConfig(logging_config) - # fetch registered hooks - self.hooks = self.plugin_manager.get_hooks("octoprint.cli.commands") + # initialize settings and plugin manager based on provided + # context (basedir and configfile) + from octoprint import FatalStartupError, init_pluginsystem, init_settings - logging.basicConfig(level=logging.DEBUG if ctx.obj.verbosity > 0 else logging.WARN) + try: + self.settings = init_settings( + get_ctx_obj_option(ctx, "basedir", None), + get_ctx_obj_option(ctx, "configfile", None), + overlays=get_ctx_obj_option(ctx, "overlays", 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 ab9ea5fe4..16622e2d7 100644 --- a/src/octoprint/cli/server.py +++ b/src/octoprint/cli/server.py @@ -1,178 +1,286 @@ -# -*- 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, + overlays=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")\ - .warn("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, + overlays=overlays, + 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 CannotStartServerException, 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, + ) + + try: + octoprint_server.run() + except CannotStartServerException 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.") + + +# ~~ 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), + overlays=get_ctx_obj_option(ctx, "overlays", 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 +288,163 @@ 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") + overlays = get_value("overlays") - 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, + overlays=overlays, + ) 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") + overlays = get_value("overlays") + 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, + overlays, + 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._overlays = overlays + 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, + overlays=self._overlays, + ) + octoprint_daemon = OctoPrintDaemon( + pid, + basedir, + configfile, + overlays, + 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..75fe2e773 --- /dev/null +++ b/src/octoprint/cli/systeminfo.py @@ -0,0 +1,159 @@ +__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 os + +import click +import zipstream + +from octoprint.cli import init_platform_for_cli, standard_options + +click.disable_unicode_literals_warning = True + + +def get_systeminfo(environment_detector, connectivity_checker, additional_fields=None): + from octoprint import __version__ + from octoprint.util import dict_flatten + + if additional_fields is None: + additional_fields = {} + + 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 + + for k, v in additional_fields.items(): + if k not in flattened: + flattened[k] = v + + return flattened + + +def get_systeminfo_bundle(systeminfo, logbase, printer=None): + from octoprint.util import to_bytes + + systeminfotxt = [] + for k in sorted(systeminfo.keys()): + systeminfotxt.append("{}: {}".format(k, systeminfo[k])) + + terminaltxt = None + if printer and printer.is_operational(): + firmware_info = printer.firmware_info + if firmware_info: + systeminfo["printer.firmware"] = firmware_info["name"] + + if hasattr(printer, "_log"): + terminaltxt = list(printer._log) + + try: + import zlib # noqa: F401 + + compress_type = zipstream.ZIP_DEFLATED + except ImportError: + # no zlib, no compression + compress_type = zipstream.ZIP_STORED + + z = zipstream.ZipFile() + + # add systeminfo + z.writestr( + "systeminfo.txt", to_bytes("\n".join(systeminfotxt)), compress_type=compress_type + ) + + # add terminal.txt, if available + if terminaltxt: + z.writestr( + "terminal.txt", to_bytes("\n".join(terminaltxt)), compress_type=compress_type + ) + + # add logs + for log in ( + "octoprint.log", + "serial.log", + "plugin_softwareupdate_console.log", + "plugin_pluginmanager_console.log", + ): + logpath = os.path.join(logbase, log) + if os.path.exists(logpath): + z.write(logpath, arcname=log, compress_type=compress_type) + + return z + + +def get_systeminfo_bundle_name(): + import time + + return "octoprint-systeminfo-{}.zip".format(time.strftime("%Y%m%d%H%M%S")) + + +@click.group() +def systeminfo_commands(): + pass + + +@systeminfo_commands.command(name="systeminfo") +@standard_options() +@click.argument( + "path", + nargs=1, + required=False, + type=click.Path(writable=True, dir_okay=True, resolve_path=True), +) +@click.pass_context +def systeminfo_command(ctx, path, **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, {"systeminfo.generator": "cli"} + ) + + if path: + # create zip at path + zipfilename = os.path.join(path, get_systeminfo_bundle_name()) + click.echo("Writing systeminfo bundle to {}...".format(zipfilename)) + + z = get_systeminfo_bundle(systeminfo, settings.getBaseFolder("logs")) + try: + with open(zipfilename, "wb") as f: + for data in z: + f.write(data) + except Exception as e: + click.echo(str(e), err=True) + click.echo( + "There was an error writing to {}.".format(zipfilename), err=True + ) + ctx.exit(-1) + + click.echo("Done!") + click.echo(zipfilename) + + else: + # output systeminfo to console + 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 1f1b19391..373ab1d95 100644 --- a/src/octoprint/cli/user.py +++ b/src/octoprint/cli/user.py @@ -1,124 +1,155 @@ -# 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.util import get_class +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), + overlays=get_ctx_obj_option(ctx, "overlays", 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 +157,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: 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/comm/__init__.py b/src/octoprint/comm/__init__.py index ff9d7d326..5fb8ab713 100644 --- a/src/octoprint/comm/__init__.py +++ b/src/octoprint/comm/__init__.py @@ -1,7 +1,2 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" - - diff --git a/src/octoprint/comm/connectionprofile.py b/src/octoprint/comm/connectionprofile.py index 6b7ab6b57..b066ba46b 100644 --- a/src/octoprint/comm/connectionprofile.py +++ b/src/octoprint/comm/connectionprofile.py @@ -1,215 +1,235 @@ -# -*- 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 io import logging import os -import io - -try: - from os import scandir -except ImportError: - from scandir import scandir +from os import scandir from octoprint.settings import settings from octoprint.util import is_hidden_path class ConnectionProfile(object): + def __init__( + self, + id, + name=None, + printer_profile=None, + protocol=None, + protocol_parameters=None, + transport=None, + transport_parameters=None, + **kwargs + ): + self.id = id + self.name = name if name is not None else id + self.printer_profile = printer_profile + self.protocol = protocol + self.protocol_parameters = protocol_parameters + self.transport = transport + self.transport_parameters = transport_parameters - def __init__(self, id, name=None, printer_profile=None, protocol=None, protocol_parameters=None, transport=None, transport_parameters=None, **kwargs): - self.id = id - self.name = name if name is not None else id - self.printer_profile = printer_profile - self.protocol = protocol - self.protocol_parameters = protocol_parameters - self.transport = transport - self.transport_parameters = transport_parameters + @classmethod + def from_dict(cls, data): + identifier = data.pop("id") + return ConnectionProfile(identifier, **data) - @classmethod - def from_dict(cls, data): - identifier = data.pop("id") - return ConnectionProfile(identifier, **data) - - def as_dict(self): - return dict(id=self.id, - name=self.name, - printer_profile=self.printer_profile, - protocol=self.protocol, - protocol_parameters=self.protocol_parameters, - transport=self.transport, - transport_parameters=self.transport_parameters) + def as_dict(self): + return { + "id": self.id, + "name": self.name, + "printer_profile": self.printer_profile, + "protocol": self.protocol, + "protocol_parameters": self.protocol_parameters, + "transport": self.transport, + "transport_parameters": self.transport_parameters, + } class ConnectionProfileManager(object): + @classmethod + def to_profile(cls, data): + return ConnectionProfile.from_dict(data) - @classmethod - def to_profile(cls, data): - return ConnectionProfile.from_dict(data) + def __init__(self): + self._current = None + self._folder = settings().getBaseFolder("connectionProfiles") + self._logger = logging.getLogger(__name__) - def __init__(self): - self._current = None - self._folder = settings().getBaseFolder("connectionProfiles") - self._logger = logging.getLogger(__name__) + def select(self, identifier): + self._current = self.get(identifier) + if self._current is None: + self._logger.error("Profile {} is invalid, cannot select".format(identifier)) + return False + return True - def select(self, identifier): - self._current = self.get(identifier) - if self._current is None: - self._logger.error("Profile {} is invalid, cannot select".format(identifier)) - return False - return True + def deselect(self): + self._current = None - def deselect(self): - self._current = None + @property + def current(self): + return self._current - @property - def current(self): - return self._current + def get_all(self): + return self._load_all() - def get_all(self): - return self._load_all() + def get(self, identifier): + try: + if self.exists(identifier): + return self._load_from_path(self._get_profile_path(identifier)) + else: + return None + except InvalidProfileError: + return None - def get(self, identifier): - try: - if self.exists(identifier): - return self._load_from_path(self._get_profile_path(identifier)) - else: - return None - except InvalidProfileError: - return None + def remove(self, identifier): + return self._remove_from_path(self._get_profile_path(identifier)) - def remove(self, identifier): - return self._remove_from_path(self._get_profile_path(identifier)) + def save(self, profile, allow_overwrite=False, make_default=False): + self._save_to_path( + self._get_profile_path(profile.id), profile, allow_overwrite=allow_overwrite + ) - def save(self, profile, allow_overwrite=False, make_default=False): - self._save_to_path(self._get_profile_path(profile.id), - profile, - allow_overwrite=allow_overwrite) + if make_default: + self.set_default(profile.id) - if make_default: - self.set_default(profile.id) + return self.get(profile.id) - return self.get(profile.id) + @property + def profile_count(self): + return len(self._load_all_identifiers()) - @property - def profile_count(self): - return len(self._load_all_identifiers()) + @property + def last_modified(self): + dates = [os.stat(self._folder).st_mtime] + dates += [ + entry.stat().st_mtime + for entry in scandir(self._folder) + if entry.name.endswith(".profile") + ] + return max(dates) - @property - def last_modified(self): - dates = [os.stat(self._folder).st_mtime] - dates += [entry.stat().st_mtime for entry in scandir(self._folder) if entry.name.endswith(".profile")] - return max(dates) + def get_default(self): + default = settings().get(["connection", "profiles", "default"]) + if default is not None and self.exists(default): + profile = self.get(default) + if profile is not None: + return profile + else: + self._logger.warning("Default profile {} is invalid".format(default)) - def get_default(self): - default = settings().get(["connection", "profiles", "default"]) - if default is not None and self.exists(default): - profile = self.get(default) - if profile is not None: - return profile - else: - self._logger.warning("Default profile {} is invalid".format(default)) + return None - return None + def set_default(self, identifier): + all_identifiers = self._load_all_identifiers() + if identifier is not None and identifier not in all_identifiers: + return - def set_default(self, identifier): - all_identifiers = self._load_all_identifiers() - if identifier is not None and identifier not in all_identifiers: - return + settings().set(["connection", "profiles", "default"], identifier) + settings().save() - settings().set(["connection", "profiles", "default"], identifier) - settings().save() + def get_current_or_default(self): + if self._current is not None: + return self._current + else: + return self.get_default() - def get_current_or_default(self): - if self._current is not None: - return self._current - else: - return self.get_default() + def get_current(self): + return self._current - def get_current(self): - return self._current + def exists(self, identifier): + if identifier is None: + return False - def exists(self, identifier): - if identifier is None: - return False + path = self._get_profile_path(identifier) + return os.path.exists(path) and os.path.isfile(path) - path = self._get_profile_path(identifier) - return os.path.exists(path) and os.path.isfile(path) + def _load_all(self): + all_identifiers = self._load_all_identifiers() + results = {} + for identifier, path in all_identifiers.items(): + try: + profile = self._load_from_path(path) + except InvalidProfileError: + self._logger.warning("Profile {} is invalid, skipping".format(identifier)) + continue - def _load_all(self): - all_identifiers = self._load_all_identifiers() - results = dict() - for identifier, path in all_identifiers.items(): - try: - profile = self._load_from_path(path) - except InvalidProfileError: - self._logger.warning("Profile {} is invalid, skipping".format(identifier)) - continue + if profile is None: + continue - if profile is None: - continue + results[identifier] = profile + return results - results[identifier] = profile - return results + def _load_all_identifiers(self): + results = {} + for entry in scandir(self._folder): + if is_hidden_path(entry.name) or not entry.name.endswith(".profile"): + continue - def _load_all_identifiers(self): - results = dict() - for entry in scandir(self._folder): - if is_hidden_path(entry.name) or not entry.name.endswith(".profile"): - continue + if not entry.is_file(): + continue - if not entry.is_file(): - continue + identifier = entry.name[: -len(".profile")] + results[identifier] = entry.path + return results - identifier = entry.name[:-len(".profile")] - results[identifier] = entry.path - return results + def _load_from_path(self, path): + if not os.path.exists(path) or not os.path.isfile(path): + return None - def _load_from_path(self, path): - if not os.path.exists(path) or not os.path.isfile(path): - return None + import yaml - import yaml - with io.open(path, 'rt', encoding='utf-8') as f: - data = yaml.safe_load(f) + with io.open(path, "rt", encoding="utf-8") as f: + data = yaml.safe_load(f) - if data is None or not isinstance(data, dict): - raise InvalidProfileError("Profile is None or not a dict") + if data is None or not isinstance(data, dict): + raise InvalidProfileError("Profile is None or not a dict") - return ConnectionProfile.from_dict(data) + return ConnectionProfile.from_dict(data) - def _save_to_path(self, path, profile, allow_overwrite=False): - if os.path.exists(path) and not allow_overwrite: - raise SaveError("Profile {} already exists and overwriting is not allowed".format(profile["id"])) + def _save_to_path(self, path, profile, allow_overwrite=False): + if os.path.exists(path) and not allow_overwrite: + raise SaveError( + "Profile {} already exists and overwriting is not allowed".format( + profile["id"] + ) + ) - from octoprint.util import atomic_write - import yaml - try: - with atomic_write(path, mode="wt", max_permissions=0o666) as f: - yaml.safe_dump(profile.as_dict(), f, - default_flow_style=False, - indent=2, - allow_unicode=True) - except Exception as e: - self._logger.exception("Error while trying to save profile {}".format(profile["id"])) - raise SaveError("Cannot save profile {}: {}".format(profile["id"], e)) + import yaml - def _remove_from_path(self, path): - try: - os.remove(path) - return True - except Exception: - return False + from octoprint.util import atomic_write - def _get_profile_path(self, identifier): - return os.path.join(self._folder, "{}.profile".format(identifier)) + try: + with atomic_write(path, mode="wt", max_permissions=0o666) as f: + yaml.safe_dump( + profile.as_dict(), + f, + default_flow_style=False, + indent=2, + allow_unicode=True, + ) + except Exception as e: + self._logger.exception( + "Error while trying to save profile {}".format(profile["id"]) + ) + raise SaveError("Cannot save profile {}: {}".format(profile["id"], e)) + + def _remove_from_path(self, path): + try: + os.remove(path) + return True + except Exception: + return False + + def _get_profile_path(self, identifier): + return os.path.join(self._folder, "{}.profile".format(identifier)) class InvalidProfileError(Exception): - pass + pass + class SaveError(Exception): - pass + pass diff --git a/src/octoprint/comm/job/__init__.py b/src/octoprint/comm/job/__init__.py index 16531a319..07639041f 100644 --- a/src/octoprint/comm/job/__init__.py +++ b/src/octoprint/comm/job/__init__.py @@ -1,573 +1,609 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" +import copy import logging import os -import copy - -from octoprint.comm.protocol import ProtocolListener, FileAwareProtocolListener, ProtocolState, FileManagementProtocolMixin - -from octoprint.util.listener import ListenerAware - -from abc import ABCMeta, abstractmethod, abstractproperty - -from octoprint.util import monotonic_time +from abc import ABCMeta from future.utils import with_metaclass +from octoprint.comm.protocol import ( + FileAwareProtocolListener, + FileManagementProtocolMixin, + ProtocolListener, + ProtocolState, +) +from octoprint.util import monotonic_time +from octoprint.util.listener import ListenerAware + class LastResult(object): - def __init__(self): - self.elapsed = None - self.clean_elapsed = None - self.progress = None - self.pos = None - self.success = None + def __init__(self): + self.elapsed = None + self.clean_elapsed = None + self.progress = None + self.pos = None + self.success = None - self.available = False + self.available = False class Printjob(with_metaclass(ABCMeta, ProtocolListener, ListenerAware)): - parallel = False - """Job runs parallel to regular communication.""" + parallel = False + """Job runs parallel to regular communication.""" - exclusive = False - """Job has exclusive claim to communication channel.""" + exclusive = False + """Job has exclusive claim to communication channel.""" - def __init__(self, name=None, user=None, event_data=None): - if event_data is None: - event_data = dict() + def __init__(self, name=None, user=None, event_data=None): + if event_data is None: + event_data = {} - super(Printjob, self).__init__() - self._logger = logging.getLogger(__name__) - self._start = None - self._protocol = None - self._printer_profile = None - self._name = name - self._user = user - self._event_data = event_data + super(Printjob, self).__init__() + self._logger = logging.getLogger(__name__) + self._start = None + self._protocol = None + self._printer_profile = None + self._name = name + self._user = user + self._event_data = event_data - self._lost_time = 0 - self._last_result = LastResult() + self._lost_time = 0 + self._last_result = LastResult() - @property - def name(self): - return self._name + @property + def name(self): + return self._name - @property - def user(self): - return self._user + @property + def user(self): + return self._user - @property - def size(self): - return None + @property + def size(self): + return None - @property - def pos(self): - return None + @property + def pos(self): + return None - @property - def elapsed(self): - return monotonic_time() - self._start if self._start is not None else None + @property + def elapsed(self): + return monotonic_time() - self._start if self._start is not None else None - @property - def clean_elapsed(self): - elapsed = self.elapsed - if elapsed is None: - return None - return elapsed - self._lost_time + @property + def clean_elapsed(self): + elapsed = self.elapsed + if elapsed is None: + return None + return elapsed - self._lost_time - @property - def last_result(self): - return self._last_result + @property + def last_result(self): + return self._last_result - @property - def progress(self): - size = self.size - pos = self.pos - if pos is None or size is None or size == 0: - return None + @property + def progress(self): + size = self.size + pos = self.pos + if pos is None or size is None or size == 0: + return None - return float(pos) / float(size) + return float(pos) / float(size) - @property - def active(self): - return self._start is not None + @property + def active(self): + return self._start is not None - def add_to_lost_time(self, value): - self._lost_time += value + def add_to_lost_time(self, value): + self._lost_time += value - def can_process(self, protocol): - return False + def can_process(self, protocol): + return False - def process(self, protocol, position=0, user=None, tags=None, **kwargs): - self._last_result = LastResult() - self._start = monotonic_time() - self._user = user - self._protocol = protocol - self._protocol.register_listener(self) + def process(self, protocol, position=0, user=None, tags=None, **kwargs): + self._last_result = LastResult() + self._start = monotonic_time() + self._user = user + self._protocol = protocol + self._protocol.register_listener(self) - def pause(self, user=None, tags=None, **kwargs): - self.process_job_paused(user=user, tags=tags, **kwargs) + def pause(self, user=None, tags=None, **kwargs): + self.process_job_paused(user=user, tags=tags, **kwargs) - def resume(self, user=None, tags=None, **kwargs): - self.process_job_resumed(user=user, tags=tags, **kwargs) + def resume(self, user=None, tags=None, **kwargs): + self.process_job_resumed(user=user, tags=tags, **kwargs) - def cancel(self, error=None, user=None, tags=None, **kwargs): - if error: - self.process_job_failed(**kwargs) - else: - self.process_job_cancelled(user=user, tags=tags, **kwargs) - self._protocol.unregister_listener(self) - self._protocol = None + def cancel(self, error=None, user=None, tags=None, **kwargs): + if error: + self.process_job_failed(**kwargs) + else: + self.process_job_cancelled(user=user, tags=tags, **kwargs) + self._protocol.unregister_listener(self) + self._protocol = None - def get_next(self): - return None + def get_next(self): + return None - def can_get_content(self): - return False + def can_get_content(self): + return False - def get_content_generator(self): - return None + def get_content_generator(self): + return None - def event_payload(self, incl_last=False): - payload = copy.deepcopy(self._event_data) + def event_payload(self, incl_last=False): + payload = copy.deepcopy(self._event_data) - payload["owner"] = self._user - elapsed = self.elapsed - if elapsed is None and incl_last and self.last_result.available: - elapsed = self.last_result.elapsed - if elapsed is not None: - payload["time"] = elapsed + payload["owner"] = self._user + elapsed = self.elapsed + if elapsed is None and incl_last and self.last_result.available: + elapsed = self.last_result.elapsed + if elapsed is not None: + payload["time"] = elapsed - return payload + return payload - def process_job_started(self, user=None, tags=None, **kwargs): - self.notify_listeners("on_job_started", self, user=user, tags=tags, **kwargs) + def process_job_started(self, user=None, tags=None, **kwargs): + self.notify_listeners("on_job_started", self, user=user, tags=tags, **kwargs) - def process_job_done(self, user=None, tags=None, **kwargs): - self.notify_listeners("on_job_done", self, user=user, tags=tags, **kwargs) - self.report_stats() - self.reset_job() + def process_job_done(self, user=None, tags=None, **kwargs): + self.notify_listeners("on_job_done", self, user=user, tags=tags, **kwargs) + self.report_stats() + self.reset_job() - def process_job_failed(self, **kwargs): - self.notify_listeners("on_job_failed", self, **kwargs) - self.report_stats() - self.reset_job(success=False) + def process_job_failed(self, **kwargs): + self.notify_listeners("on_job_failed", self, **kwargs) + self.report_stats() + self.reset_job(success=False) - def process_job_cancelled(self, user=None, tags=None, **kwargs): - self.notify_listeners("on_job_cancelled", self, user=user, tags=tags, **kwargs) - self.report_stats() - self.reset_job(success=False) + def process_job_cancelled(self, user=None, tags=None, **kwargs): + self.notify_listeners("on_job_cancelled", self, user=user, tags=tags, **kwargs) + self.report_stats() + self.reset_job(success=False) - def process_job_paused(self, user=None, tags=None, **kwargs): - self.notify_listeners("on_job_paused", self, user=user, tags=tags, **kwargs) + def process_job_paused(self, user=None, tags=None, **kwargs): + self.notify_listeners("on_job_paused", self, user=user, tags=tags, **kwargs) - def process_job_resumed(self, user=None, tags=None, **kwargs): - self.notify_listeners("on_job_resumed", self, user=user, tags=tags, **kwargs) + def process_job_resumed(self, user=None, tags=None, **kwargs): + self.notify_listeners("on_job_resumed", self, user=user, tags=tags, **kwargs) - def process_job_progress(self): - self.notify_listeners("on_job_progress", self) + def process_job_progress(self): + self.notify_listeners("on_job_progress", self) - def report_stats(self): - elapsed = self.elapsed - if elapsed: - self._logger.info("Job processed in {}s".format(elapsed)) + def report_stats(self): + elapsed = self.elapsed + if elapsed: + self._logger.info("Job processed in {}s".format(elapsed)) - def reset_job(self, success=True): - self._last_result.progress = 1.0 if success else self.progress - self._last_result.pos = self.size if success else self.pos - self._last_result.elapsed = self.elapsed - self._last_result.clean_elapsed = self.clean_elapsed - self._last_result.success = success - self._last_result.available = True + def reset_job(self, success=True): + self._last_result.progress = 1.0 if success else self.progress + self._last_result.pos = self.size if success else self.pos + self._last_result.elapsed = self.elapsed + self._last_result.clean_elapsed = self.clean_elapsed + self._last_result.success = success + self._last_result.available = True - self._start = None - self._lost_time = 0 + self._start = None + self._lost_time = 0 - def on_protocol_state(self, protocol, old_state, new_state, *args, **kwargs): - if new_state in (ProtocolState.DISCONNECTED, ProtocolState.DISCONNECTED_WITH_ERROR) and self.active: - self.cancel(error=True) + def on_protocol_state(self, protocol, old_state, new_state, *args, **kwargs): + if ( + new_state + in (ProtocolState.DISCONNECTED, ProtocolState.DISCONNECTED_WITH_ERROR) + and self.active + ): + self.cancel(error=True) class StoragePrintjob(Printjob): - def __init__(self, storage, path_in_storage, *args, **kwargs): - Printjob.__init__(self, *args, **kwargs) - self._storage = storage - self._path_in_storage = path_in_storage + def __init__(self, storage, path_in_storage, *args, **kwargs): + Printjob.__init__(self, *args, **kwargs) + self._storage = storage + self._path_in_storage = path_in_storage - @property - def storage(self): - return self._storage + @property + def storage(self): + return self._storage - @property - def path_in_storage(self): - return self._path_in_storage + @property + def path_in_storage(self): + return self._path_in_storage - def event_payload(self, incl_last=False): - payload = Printjob.event_payload(self, incl_last=incl_last) - payload["name"] = self.name - payload["path"] = self.path_in_storage - payload["origin"] = self.storage - return payload + def event_payload(self, incl_last=False): + payload = Printjob.event_payload(self, incl_last=incl_last) + payload["name"] = self.name + payload["path"] = self.path_in_storage + payload["origin"] = self.storage + return payload class LocalFilePrintjob(StoragePrintjob): + def __init__(self, path, *args, **kwargs): + encoding = kwargs.pop("encoding", "utf-8") - def __init__(self, path, *args, **kwargs): - encoding = kwargs.pop("encoding", "utf-8") + StoragePrintjob.__init__(self, *args, **kwargs) - StoragePrintjob.__init__(self, *args, **kwargs) + if path is None or not os.path.exists(path): + raise ValueError("path must be set to a local file path") - if path is None or not os.path.exists(path): - raise ValueError("path must be set to a local file path") + self._path = path + self._encoding = encoding + self._size = os.stat(path).st_size - self._path = path - self._encoding = encoding - self._size = os.stat(path).st_size + self._pos = 0 + self._read_lines = 0 + self._actual_lines = 0 - self._pos = 0 - self._read_lines = 0 - self._actual_lines = 0 + self._cancel_pos = None - self._cancel_pos = None + self._handle = None - self._handle = None + @property + def size(self): + return self._size - @property - def size(self): - return self._size + @property + def pos(self): + return self._pos - @property - def pos(self): - return self._pos + @property + def actual_lines(self): + return self._actual_lines - @property - def actual_lines(self): - return self._actual_lines + @property + def read_lines(self): + return self._read_lines - @property - def read_lines(self): - return self._read_lines + @property + def cancel_pos(self): + return self._cancel_pos - @property - def cancel_pos(self): - return self._cancel_pos + @property + def active(self): + return self._start is not None and self._handle is not None - @property - def active(self): - return self._start is not None and self._handle is not None + @property + def path(self): + return self._path - @property - def path(self): - return self._path + def event_payload(self, incl_last=False): + event_data = StoragePrintjob.event_payload(self, incl_last=incl_last) + event_data["size"] = self.size + return event_data - def event_payload(self, incl_last=False): - event_data = StoragePrintjob.event_payload(self, incl_last=incl_last) - event_data["size"] = self.size - return event_data + def process(self, protocol, position=0, user=None, tags=None, **kwargs): + Printjob.process( + self, protocol, position=position, user=user, tags=tags, **kwargs + ) - def process(self, protocol, position=0, user=None, tags=None, **kwargs): - Printjob.process(self, protocol, position=position, user=user, tags=tags, **kwargs) + from octoprint.util import bom_aware_open - from octoprint.util import bom_aware_open - self._handle = bom_aware_open(self._path, encoding=self._encoding, errors="replace") + self._handle = bom_aware_open( + self._path, encoding=self._encoding, errors="replace" + ) - if position > 0: - self._handle.seek(position) - self._pos = position - self.process_job_started(user=user, tags=tags) + if position > 0: + self._handle.seek(position) + self._pos = position + self.process_job_started(user=user, tags=tags) - def cancel(self, error=False, user=None, tags=None, **kwargs): - self._cancel_pos = self.pos - super(LocalFilePrintjob, self).cancel(error=error, user=user, tags=tags, **kwargs) + def cancel(self, error=False, user=None, tags=None, **kwargs): + self._cancel_pos = self.pos + super(LocalFilePrintjob, self).cancel(error=error, user=user, tags=tags, **kwargs) - def get_next(self): - from octoprint.util import to_unicode + def get_next(self): + from octoprint.util import to_unicode - if self._handle is None: - raise ValueError("File {} is not open for reading" % self._path) + if self._handle is None: + raise ValueError("File {} is not open for reading" % self._path) - try: - processed = None - while processed is None: - if self._handle is None: - # file got closed just now - self.process_job_done() - return None - line = to_unicode(self._handle.readline()) + try: + processed = None + while processed is None: + if self._handle is None: + # file got closed just now + self.process_job_done() + return None + line = to_unicode(self._handle.readline()) - # we need to manually keep track of our pos here since - # codecs' readline will make our handle's tell not - # return the actual number of bytes read, but also the - # already buffered bytes (for detecting the newlines) - self._pos += len(line) - self._actual_lines += 1 + # we need to manually keep track of our pos here since + # codecs' readline will make our handle's tell not + # return the actual number of bytes read, but also the + # already buffered bytes (for detecting the newlines) + self._pos += len(line) + self._actual_lines += 1 - if not line: - self.process_job_done() - return None - processed = self.process_line(line) + if not line: + self.process_job_done() + return None + processed = self.process_line(line) - self._read_lines += 1 - self.process_job_progress() - return processed - except Exception as e: - self.cancel(error=True) - self._logger.exception("Exception while processing line") - raise e + self._read_lines += 1 + self.process_job_progress() + return processed + except Exception as e: + self.cancel(error=True) + self._logger.exception("Exception while processing line") + raise e - def process_line(self, line): - return line + def process_line(self, line): + return line - def close(self): - if self._handle is not None: - try: - self._handle.close() - except Exception: - pass - self._handle = None + def close(self): + if self._handle is not None: + try: + self._handle.close() + except Exception: + pass + self._handle = None - def can_get_content(self): - return True + def can_get_content(self): + return True - def get_content_generator(self): - from octoprint.util import bom_aware_open - with bom_aware_open(self._path, encoding=self._encoding, error="replace") as f: - for line in f.readline(): - yield line + def get_content_generator(self): + from octoprint.util import bom_aware_open - def reset_job(self, success=True): - super(LocalFilePrintjob, self).reset_job(success=success) - self.close() - self._pos = self._read_lines = 0 + with bom_aware_open(self._path, encoding=self._encoding, error="replace") as f: + for line in f.readline(): + yield line - def report_stats(self): - elapsed = self.elapsed - lines = self._read_lines + def reset_job(self, success=True): + super(LocalFilePrintjob, self).reset_job(success=success) + self.close() + self._pos = self._read_lines = 0 - if elapsed and lines: - self._logger.info("Job processed in {:.3f}s ({} lines)".format(elapsed, lines)) + def report_stats(self): + elapsed = self.elapsed + lines = self._read_lines + + if elapsed and lines: + self._logger.info( + "Job processed in {:.3f}s ({} lines)".format(elapsed, lines) + ) class LocalGcodeFilePrintjob(LocalFilePrintjob): + def can_process(self, protocol): + return LocalGcodeFilePrintjob in protocol.supported_jobs - def can_process(self, protocol): - return LocalGcodeFilePrintjob in protocol.supported_jobs + def process_line(self, line): + # TODO no dependency on protocol module + from octoprint.comm.protocol.reprap.util import strip_comment - def process_line(self, line): - # TODO no dependency on protocol module - from octoprint.comm.protocol.reprap.util import strip_comment + # strip line + processed = line.strip() - # strip line - processed = line.strip() + # strip comments + processed = strip_comment(processed) + if not len(processed): + return None - # strip comments - processed = strip_comment(processed) - if not len(processed): - return None + # TODO apply offsets - # TODO apply offsets - - # return result - return processed + # return result + return processed class CopyJobMixin(object): - pass + pass class LocalGcodeStreamjob(LocalGcodeFilePrintjob, CopyJobMixin): - exclusive = True + exclusive = True - @classmethod - def from_job(cls, job, remote): - if not isinstance(job, LocalGcodeFilePrintjob): - raise ValueError("job must be a LocalGcodeFilePrintjob") + @classmethod + def from_job(cls, job, remote): + if not isinstance(job, LocalGcodeFilePrintjob): + raise ValueError("job must be a LocalGcodeFilePrintjob") - path = job._path - storage = job._storage - path_in_storage = job._path_in_storage - name = job._name - user = job._user - encoding = job._encoding - event_data = job._event_data + path = job._path + storage = job._storage + path_in_storage = job._path_in_storage + name = job._name + user = job._user + encoding = job._encoding + event_data = job._event_data - return cls(remote, path, storage, path_in_storage, - name=name, user=user, encoding=encoding, event_data=event_data) + return cls( + remote, + path, + storage, + path_in_storage, + name=name, + user=user, + encoding=encoding, + event_data=event_data, + ) - def __init__(self, remote, *args, **kwargs): - super(LocalGcodeStreamjob, self).__init__(*args, **kwargs) - self._remote = remote + def __init__(self, remote, *args, **kwargs): + super(LocalGcodeStreamjob, self).__init__(*args, **kwargs) + self._remote = remote - @property - def remote(self): - return self._remote + @property + def remote(self): + return self._remote - def process(self, protocol, position=0, user=None, tags=None, **kwargs): - super(LocalGcodeStreamjob, self).process(protocol, position=position, user=user, tags=tags, **kwargs) - self._protocol.record_file(self._remote) + def process(self, protocol, position=0, user=None, tags=None, **kwargs): + super(LocalGcodeStreamjob, self).process( + protocol, position=position, user=user, tags=tags, **kwargs + ) + self._protocol.record_file(self._remote) - def process_job_done(self, user=None, tags=None, **kwargs): - self._protocol.stop_recording_file() - super(LocalGcodeStreamjob, self).process_job_done(user=user, tags=tags, **kwargs) + def process_job_done(self, user=None, tags=None, **kwargs): + self._protocol.stop_recording_file() + super(LocalGcodeStreamjob, self).process_job_done(user=user, tags=tags, **kwargs) - def process_job_failed(self, **kwargs): - self._protocol.stop_recording_file() - super(LocalGcodeStreamjob, self).process_job_failed(**kwargs) + def process_job_failed(self, **kwargs): + self._protocol.stop_recording_file() + super(LocalGcodeStreamjob, self).process_job_failed(**kwargs) - def process_job_cancelled(self, user=None, tags=None, **kwargs): - self._protocol.stop_recording_file() - self._protocol.delete_file(self.remote) - super(LocalGcodeStreamjob, self).process_job_cancelled(user=user, tags=tags, **kwargs) + def process_job_cancelled(self, user=None, tags=None, **kwargs): + self._protocol.stop_recording_file() + self._protocol.delete_file(self.remote) + super(LocalGcodeStreamjob, self).process_job_cancelled( + user=user, tags=tags, **kwargs + ) - def can_process(self, protocol): - from octoprint.comm.protocol import FileStreamingProtocolMixin - return LocalGcodeStreamjob in protocol.supported_jobs and isinstance(protocol, FileStreamingProtocolMixin) and isinstance(protocol, FileManagementProtocolMixin) + def can_process(self, protocol): + from octoprint.comm.protocol import FileStreamingProtocolMixin - def report_stats(self): - elapsed = self.elapsed - lines = self._read_lines + return ( + LocalGcodeStreamjob in protocol.supported_jobs + and isinstance(protocol, FileStreamingProtocolMixin) + and isinstance(protocol, FileManagementProtocolMixin) + ) - if elapsed and lines: - self._logger.info("Job processed in {:.3f}s ({} lines). Approx. {:.3f} lines/s, {:.3f} ms/line".format(elapsed, - lines, - float(lines) / float(elapsed), - float(elapsed) * 1000.0 / float(lines))) + def report_stats(self): + elapsed = self.elapsed + lines = self._read_lines + + if elapsed and lines: + self._logger.info( + "Job processed in {:.3f}s ({} lines). Approx. {:.3f} lines/s, {:.3f} ms/line".format( + elapsed, + lines, + float(lines) / float(elapsed), + float(elapsed) * 1000.0 / float(lines), + ) + ) class SDFilePrintjob(StoragePrintjob, FileAwareProtocolListener): - parallel = True + parallel = True - def __init__(self, path, status_interval=2.0, *args, **kwargs): - name = path - if name.startswith("/"): - name = name[1:] + def __init__(self, path, status_interval=2.0, *args, **kwargs): + name = path + if name.startswith("/"): + name = name[1:] - StoragePrintjob.__init__(self, - "sdcard", - name, - name=name, - event_data=dict(name=name, - path=path, - origin="sdcard")) - self._filename = path - self._status_interval = status_interval + StoragePrintjob.__init__( + self, + "sdcard", + name, + name=name, + event_data={"name": name, "path": path, "origin": "sdcard"}, + ) + self._filename = path + self._status_interval = status_interval - self._status_timer = None - self._active = False + self._status_timer = None + self._active = False - self._size = None - self._last_pos = None + self._size = None + self._last_pos = None - @property - def size(self): - return self._size + @property + def size(self): + return self._size - @property - def pos(self): - return self._last_pos + @property + def pos(self): + return self._last_pos - @property - def active(self): - return self._start is not None and self._active + @property + def active(self): + return self._start is not None and self._active - @property - def status_interval(self): - return self._status_interval + @property + def status_interval(self): + return self._status_interval - def can_process(self, protocol): - from octoprint.comm.protocol import FileAwareProtocolMixin - return SDFilePrintjob in protocol.supported_jobs and isinstance(protocol, FileAwareProtocolMixin) + def can_process(self, protocol): + from octoprint.comm.protocol import FileAwareProtocolMixin - def process(self, protocol, position=0, user=None, tags=None, **kwargs): - Printjob.process(self, protocol, position=position, user=user, tags=tags, **kwargs) + return SDFilePrintjob in protocol.supported_jobs and isinstance( + protocol, FileAwareProtocolMixin + ) - self._protocol.register_listener(self) - self._active = True - self._last_pos = position + def process(self, protocol, position=0, user=None, tags=None, **kwargs): + Printjob.process( + self, protocol, position=position, user=user, tags=tags, **kwargs + ) - self._protocol.start_file_print(self._filename, - position=position, - user=user, - tags=tags, - part_of_job=True, - **kwargs) - self._protocol.start_file_print_status_monitor() + self._protocol.register_listener(self) + self._active = True + self._last_pos = position - def pause(self, user=None, tags=None, **kwargs): - super(SDFilePrintjob, self).pause(user=user, tags=tags, **kwargs) - self._protocol.pause_file_print(user=user, - tags=tags, - part_of_job=True, - **kwargs) + self._protocol.start_file_print( + self._filename, + position=position, + user=user, + tags=tags, + part_of_job=True, + **kwargs + ) + self._protocol.start_file_print_status_monitor() - def resume(self, user=None, tags=None, **kwargs): - super(SDFilePrintjob, self).resume(user=user, tags=tags, **kwargs) - self._protocol.resume_file_print(user=user, - tags=tags, - part_of_job=True, - **kwargs) + def pause(self, user=None, tags=None, **kwargs): + super(SDFilePrintjob, self).pause(user=user, tags=tags, **kwargs) + self._protocol.pause_file_print(user=user, tags=tags, part_of_job=True, **kwargs) - def on_protocol_sd_status(self, protocol, pos, total): - self._last_pos = pos - self._size = total - self.process_job_progress() + def resume(self, user=None, tags=None, **kwargs): + super(SDFilePrintjob, self).resume(user=user, tags=tags, **kwargs) + self._protocol.resume_file_print(user=user, tags=tags, part_of_job=True, **kwargs) - def on_protocol_file_print_started(self, protocol, name, long_name, size, *args, **kwargs): - self._size = size - self.process_job_started(**kwargs) + def on_protocol_sd_status(self, protocol, pos, total): + self._last_pos = pos + self._size = total + self.process_job_progress() - def on_protocol_file_print_done(self, protocol, *args, **kwargs): - self._protocol.stop_file_print_status_monitor(**kwargs) - self.process_job_done(**kwargs) + def on_protocol_file_print_started( + self, protocol, name, long_name, size, *args, **kwargs + ): + self._size = size + self.process_job_started(**kwargs) - def on_protocol_file_print_paused(self, protocol, *args, **kwargs): - self._protocol.pause_file_print(**kwargs) + def on_protocol_file_print_done(self, protocol, *args, **kwargs): + self._protocol.stop_file_print_status_monitor(**kwargs) + self.process_job_done(**kwargs) - def on_protocol_file_print_resumed(self, protocol, *args, **kwargs): - self._protocol.resume_file_print(**kwargs) + def on_protocol_file_print_paused(self, protocol, *args, **kwargs): + self._protocol.pause_file_print(**kwargs) - def reset_job(self, success=True): - super(SDFilePrintjob, self).reset_job(success=success) - self._active = False - self._last_pos = None - self._size = None + def on_protocol_file_print_resumed(self, protocol, *args, **kwargs): + self._protocol.resume_file_print(**kwargs) - def event_payload(self, incl_last=False): - payload = Printjob.event_payload(self, incl_last=incl_last) - payload["size"] = self.size - return payload + def reset_job(self, success=True): + super(SDFilePrintjob, self).reset_job(success=success) + self._active = False + self._last_pos = None + self._size = None + + def event_payload(self, incl_last=False): + payload = Printjob.event_payload(self, incl_last=incl_last) + payload["size"] = self.size + return payload class PrintjobListener(object): + def on_job_started(self, job, suppress_script=False, *args, **kwargs): + pass - def on_job_started(self, job, suppress_script=False, *args, **kwargs): - pass + def on_job_done(self, job, suppress_script=False, *args, **kwargs): + pass - def on_job_done(self, job, suppress_script=False, *args, **kwargs): - pass + def on_job_failed(self, job, *args, **kwargs): + pass - def on_job_failed(self, job, *args, **kwargs): - pass + def on_job_cancelling(self, job, firmware_error=None, *args, **kwargs): + pass - def on_job_cancelling(self, job, firmware_error=None, *args, **kwargs): - pass + def on_job_cancelled( + self, job, cancel_position=None, suppress_script=False, *args, **kwargs + ): + pass - def on_job_cancelled(self, job, cancel_position=None, suppress_script=False, *args, **kwargs): - pass + def on_job_paused( + self, job, pause_position=None, suppress_script=False, *args, **kwargs + ): + pass - def on_job_paused(self, job, pause_position=None, suppress_script=False, *args, **kwargs): - pass + def on_job_resumed(self, job, suppress_script=False, *args, **kwargs): + pass - def on_job_resumed(self, job, suppress_script=False, *args, **kwargs): - pass - - def on_job_progress(self, job, *args, **kwargs): - pass + def on_job_progress(self, job, *args, **kwargs): + pass diff --git a/src/octoprint/comm/protocol/__init__.py b/src/octoprint/comm/protocol/__init__.py index be30e62fb..deedfdead 100644 --- a/src/octoprint/comm/protocol/__init__.py +++ b/src/octoprint/comm/protocol/__init__.py @@ -1,569 +1,634 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" -from octoprint.comm.transport import TransportListener, TransportState -from octoprint.plugin import plugin_manager -from octoprint.util import to_unicode, CountedEvent -from octoprint.util.listener import ListenerAware -from octoprint.settings import SubSettings - import contextlib import copy import logging -_registry = dict() +from octoprint.comm.transport import TransportListener, TransportState +from octoprint.plugin import plugin_manager +from octoprint.settings import SubSettings +from octoprint.util import CountedEvent, to_unicode +from octoprint.util.listener import ListenerAware + +_registry = {} + def register_protocols(): - from .reprap import ReprapGcodeProtocol + from .reprap import ReprapGcodeProtocol - logger = logging.getLogger(__name__) + logger = logging.getLogger(__name__) - # stock protocols - register_protocol(ReprapGcodeProtocol) + # stock protocols + register_protocol(ReprapGcodeProtocol) - # more protocols provided by plugins - hooks = plugin_manager().get_hooks("octoprint.comm.protocol.register") - for name, hook in hooks.items(): - try: - protocols = hook() - for protocol in protocols: - try: - register_protocol(protocol) - except Exception: - logger.exception("Error while registering protocol class {} for plugin {}".format(protocol, name)) - except Exception: - logger.exception("Error executing octoprint.comm.protocol.register hook for plugin {}".format(name)) + # more protocols provided by plugins + hooks = plugin_manager().get_hooks("octoprint.comm.protocol.register") + for name, hook in hooks.items(): + try: + protocols = hook() + for protocol in protocols: + try: + register_protocol(protocol) + except Exception: + logger.exception( + "Error while registering protocol class {} for plugin {}".format( + protocol, name + ) + ) + except Exception: + logger.exception( + "Error executing octoprint.comm.protocol.register hook for plugin {}".format( + name + ) + ) def register_protocol(protocol_class): - if not hasattr(protocol_class, "key"): - raise ValueError("Protocol class {} is missing key".format(protocol_class)) - _registry[protocol_class.key] = protocol_class + if not hasattr(protocol_class, "key"): + raise ValueError("Protocol class {} is missing key".format(protocol_class)) + _registry[protocol_class.key] = protocol_class def lookup_protocol(key): - return _registry.get(key) + return _registry.get(key) def all_protocols(): - return _registry.values() + return _registry.values() class Protocol(ListenerAware, TransportListener): - name = None - key = None - - supported_jobs = [] - - @classmethod - def get_connection_options(cls): - return [] - - @classmethod - def get_settings_defaults(cls): - return dict() - - def __init__(self, *args, **kwargs): - super(Protocol, self).__init__() - - self._logger = logging.getLogger(__name__) - self._connection_logger = logging.getLogger("CONNECTION") - self._state = ProtocolState.DISCONNECTED - self._error = None - - self._printer_profile = kwargs.get("printer_profile") - self._plugin_manager = kwargs.get("plugin_manager") - self._event_bus = kwargs.get("event_bus") - self._settings = kwargs.get("settings") - if not isinstance(self._settings, ProtocolSettings): - self._settings = ProtocolSettings(self._settings, self) - - self._job = None - self._transport = None + name = None + key = None + + supported_jobs = [] + + @classmethod + def get_connection_options(cls): + return [] + + @classmethod + def get_settings_defaults(cls): + return {} + + def __init__(self, *args, **kwargs): + super(Protocol, self).__init__() + + self._logger = logging.getLogger(__name__) + self._connection_logger = logging.getLogger("CONNECTION") + self._state = ProtocolState.DISCONNECTED + self._error = None + + self._printer_profile = kwargs.get("printer_profile") + self._plugin_manager = kwargs.get("plugin_manager") + self._event_bus = kwargs.get("event_bus") + self._settings = kwargs.get("settings") + if not isinstance(self._settings, ProtocolSettings): + self._settings = ProtocolSettings(self._settings, self) + + self._job = None + self._transport = None + + self._job_on_hold = CountedEvent() + + self._args = {} + + def args(self): + return copy.deepcopy(self._args) + + def set_current_args(self, **value): + self._args = copy.deepcopy(value) + + @contextlib.contextmanager + def job_put_on_hold(self, blocking=True): + if not self._job_on_hold.acquire(blocking=blocking): + raise RuntimeError("Could not acquire job_on_hold lock") + + self._job_on_hold.set() + try: + yield + finally: + self._job_on_hold.clear() + if self._job_on_hold.counter == 0: + self._job_on_hold_cleared() + self._job_on_hold.release() + + @property + def job_on_hold(self): + return self._job_on_hold.counter > 0 + + def set_job_on_hold(self, value, blocking=True): + if not self._job_on_hold.acquire(blocking=blocking): + return False + + try: + if value: + self._job_on_hold.set() + else: + self._job_on_hold.clear() + if self._job_on_hold.counter == 0: + self._job_on_hold_cleared() + finally: + self._job_on_hold.release() + + return True + + @property + def transport(self): + return self._transport + + @property + def state(self): + return self._state + + @state.setter + def state(self, new_state): + old_state = self._state + if old_state == new_state: + return + + self._state = new_state + + name = "_on_switching_state_{}".format(new_state) + method = getattr(self, name, None) + if method is not None: + method(old_state) + + self.process_protocol_log( + "--- Protocol state changed from '{}' to '{}'".format(old_state, new_state) + ) + self.notify_listeners("on_protocol_state", self, old_state, new_state) + + name = "_on_switched_state_{}".format(new_state) + method = getattr(self, name, None) + if method is not None: + method(old_state) + + @property + def error(self): + return self._error + + @error.setter + def error(self, new_error): + self._error = new_error + + def connect(self, transport, transport_args=None, transport_kwargs=None): + if self.state not in ( + ProtocolState.DISCONNECTED, + ProtocolState.DISCONNECTED_WITH_ERROR, + ): + raise ProtocolAlreadyConnectedError("Already connected, disconnect first") + + self.process_protocol_log( + "--- Protocol {} connecting via transport {}...".format(self, transport) + ) + + if transport_args is None: + transport_args = [] + if transport_kwargs is None: + transport_kwargs = {} + + self._transport = transport + self._transport.register_listener(self) + + if self._transport.state == TransportState.DISCONNECTED: + self._transport.connect(*transport_args, **transport_kwargs) + self.state = ProtocolState.CONNECTING + + def disconnect(self, error=False, wait=True, timeout=10.0): + if self.state in ( + ProtocolState.DISCONNECTED, + ProtocolState.DISCONNECTED_WITH_ERROR, + ProtocolState.DISCONNECTING, + ProtocolState.DISCONNECTING_WITH_ERROR, + ): + raise ProtocolNotConnectedError("Already disconnecting or disconnected") + + if error: + self.state = ProtocolState.DISCONNECTING_WITH_ERROR + else: + self.state = ProtocolState.DISCONNECTING + + self.process_protocol_log( + "--- Protocol {} disconnecting from transport {}...".format( + self, self._transport + ) + ) + + if wait: + self.join(timeout=timeout) + + self._transport.unregister_listener(self) + if self._transport.state == TransportState.CONNECTED: + try: + self._transport.disconnect(wait=wait) + except Exception: + self._logger.exception( + "Error while disconnecting from transport {}".format(self._transport) + ) + error = True + + if error: + self.state = ProtocolState.DISCONNECTED_WITH_ERROR + else: + self.state = ProtocolState.DISCONNECTED + + def process(self, job, position=0, user=None, tags=None, **kwargs): + if not job.can_process(self): + raise ValueError( + "Job {} cannot be processed with protocol {}".format(job, self) + ) + + self._job = job + self._job.register_listener(self) + + self.state = ProtocolState.STARTING + self.notify_listeners( + "on_protocol_job_starting", self, self._job, user=user, tags=tags, **kwargs + ) + self._job.process(self, position=position, user=user, tags=tags, **kwargs) + + def pause_processing(self, user=None, tags=None, **kwargs): + if self._job is None or self.state not in ProtocolState.PROCESSING_STATES: + return + self.state = ProtocolState.PAUSING + self.notify_listeners( + "on_protocol_job_pausing", self, self._job, user=user, tags=tags, **kwargs + ) + self._job.pause(user=user, tags=tags) + + def resume_processing(self, user=None, tags=None, **kwargs): + if self._job is None or self.state not in ( + ProtocolState.PAUSING, + ProtocolState.PAUSED, + ): + return + self.state = ProtocolState.RESUMING + self.notify_listeners( + "on_protocol_job_resuming", self, self._job, user=user, tags=tags, **kwargs + ) + self._job.resume(user=user, tags=tags, **kwargs) + + def cancel_processing(self, error=False, user=None, tags=None, **kwargs): + if self._job is not None and self.state in ProtocolState.PROCESSING_STATES + ( + ProtocolState.PAUSED, + ): + self.state = ProtocolState.CANCELLING + self.notify_listeners( + "on_protocol_job_cancelling", + self, + self._job, + user=user, + tags=tags, + **kwargs + ) + self._job.cancel(error=error, user=user, tags=tags, **kwargs) + + def can_send(self): + return True + + def send_commands(self, command_type=None, tags=None, *commands): + pass + + def send_script(self, script, context=None, user=None, tags=None): + """ + Sends the specified script/the GCODE script with the specified name. + + Args: + script (GcodeScript or unicode): Script or name of the script to send + context (dict): Additional render context + user (str): The user on whose behalf the script is being sent. May be None + tags (set): And tags to send with the script commands. May be None + """ + pass + + def repair(self): + pass + + def join(self, timeout=None): + pass + + def on_job_started(self, job, *args, **kwargs): + self.notify_listeners("on_protocol_job_started", self, job, *args, **kwargs) + self.state = ProtocolState.PROCESSING + + def on_job_paused(self, job, *args, **kwargs): + self.notify_listeners("on_protocol_job_paused", self, job, *args, **kwargs) + self.state = ProtocolState.PAUSED + + def on_job_resumed(self, job, *args, **kwargs): + self.notify_listeners("on_protocol_job_resumed", self, job, *args, **kwargs) + self.state = ProtocolState.PROCESSING + + def on_job_done(self, job, *args, **kwargs): + self.notify_listeners("on_protocol_job_done", self, job, *args, **kwargs) + self._job_processed(job) + + def on_job_cancelled(self, job, *args, **kwargs): + self.notify_listeners("on_protocol_job_cancelled", self, job, *args, **kwargs) + self._job_processed(job) + + def on_job_failed(self, job, *args, **kwargs): + self.notify_listeners("on_protocol_job_failed", self, job, *args, **kwargs) + self._job_processed(job) + + def _job_processed(self, job, *args, **kwargs): + self._job.unregister_listener(self) + self.state = ProtocolState.CONNECTED + + def on_transport_disconnected(self, transport, error=None): + self.disconnect(error=error is not None) + + def on_transport_log_received_data(self, transport, data): + message = to_unicode(data, errors="replace").strip() + self.notify_listeners("on_protocol_log_received", self, message) + + message = "<<< {}".format(message) + self.process_protocol_log(message) + + def on_transport_log_sent_data(self, transport, data): + message = to_unicode(data, errors="replace").strip() + self.notify_listeners("on_protocol_log_sent", self, message) + + message = ">>> {}".format(message) + self.process_protocol_log(message) + + def on_transport_log_message(self, transport, data): + message = to_unicode(data, errors="replace").strip() + self.notify_listeners("on_protocol_log_message", self, message) + + message = "--- {}".format(message) + self.process_protocol_log(message) + + def process_protocol_log(self, message): + self._connection_logger.debug(message) + self.notify_listeners("on_protocol_log", self, message) + + def _job_on_hold_cleared(self): + pass + + def __str__(self): + return self.__class__.__name__ - self._job_on_hold = CountedEvent() - - self._args = dict() - - def args(self): - return copy.deepcopy(self._args) - - def set_current_args(self, **value): - self._args = copy.deepcopy(value) - - @contextlib.contextmanager - def job_put_on_hold(self, blocking=True): - if not self._job_on_hold.acquire(blocking=blocking): - raise RuntimeError("Could not acquire job_on_hold lock") - - self._job_on_hold.set() - try: - yield - finally: - self._job_on_hold.clear() - if self._job_on_hold.counter == 0: - self._job_on_hold_cleared() - self._job_on_hold.release() - - @property - def job_on_hold(self): - return self._job_on_hold.counter > 0 - - def set_job_on_hold(self, value, blocking=True): - if not self._job_on_hold.acquire(blocking=blocking): - return False - - try: - if value: - self._job_on_hold.set() - else: - self._job_on_hold.clear() - if self._job_on_hold.counter == 0: - self._job_on_hold_cleared() - finally: - self._job_on_hold.release() - - return True - - @property - def transport(self): - return self._transport - - @property - def state(self): - return self._state - - @state.setter - def state(self, new_state): - old_state = self._state - if old_state == new_state: - return - - self._state = new_state - - name = "_on_switching_state_{}".format(new_state) - method = getattr(self, name, None) - if method is not None: - method(old_state) - - self.process_protocol_log("--- Protocol state changed from '{}' to '{}'".format(old_state, new_state)) - self.notify_listeners("on_protocol_state", self, old_state, new_state) - - name = "_on_switched_state_{}".format(new_state) - method = getattr(self, name, None) - if method is not None: - method(old_state) - - @property - def error(self): - return self._error - - @error.setter - def error(self, new_error): - self._error = new_error - - def connect(self, transport, transport_args=None, transport_kwargs=None): - if self.state not in (ProtocolState.DISCONNECTED, ProtocolState.DISCONNECTED_WITH_ERROR): - raise ProtocolAlreadyConnectedError("Already connected, disconnect first") - - self.process_protocol_log("--- Protocol {} connecting via transport {}...".format(self, - transport)) - - if transport_args is None: - transport_args = [] - if transport_kwargs is None: - transport_kwargs = dict() - - self._transport = transport - self._transport.register_listener(self) - - if self._transport.state == TransportState.DISCONNECTED: - self._transport.connect(*transport_args, **transport_kwargs) - self.state = ProtocolState.CONNECTING - - def disconnect(self, error=False, wait=True, timeout=10.0): - if self.state in (ProtocolState.DISCONNECTED, ProtocolState.DISCONNECTED_WITH_ERROR, ProtocolState.DISCONNECTING, ProtocolState.DISCONNECTING_WITH_ERROR): - raise ProtocolNotConnectedError("Already disconnecting or disconnected") - - if error: - self.state = ProtocolState.DISCONNECTING_WITH_ERROR - else: - self.state = ProtocolState.DISCONNECTING - - self.process_protocol_log("--- Protocol {} disconnecting from transport {}...".format(self, - self._transport)) - - if wait: - self.join(timeout=timeout) - - self._transport.unregister_listener(self) - if self._transport.state == TransportState.CONNECTED: - try: - self._transport.disconnect(wait=wait) - except Exception: - self._logger.exception("Error while disconnecting from transport {}".format(self._transport)) - error = True - - if error: - self.state = ProtocolState.DISCONNECTED_WITH_ERROR - else: - self.state = ProtocolState.DISCONNECTED - - def process(self, job, position=0, user=None, tags=None, **kwargs): - if not job.can_process(self): - raise ValueError("Job {} cannot be processed with protocol {}".format(job, self)) - - self._job = job - self._job.register_listener(self) - - self.state = ProtocolState.STARTING - self.notify_listeners("on_protocol_job_starting", self, self._job, user=user, tags=tags, **kwargs) - self._job.process(self, position=position, user=user, tags=tags, **kwargs) - - def pause_processing(self, user=None, tags=None, **kwargs): - if self._job is None or self.state not in ProtocolState.PROCESSING_STATES: - return - self.state = ProtocolState.PAUSING - self.notify_listeners("on_protocol_job_pausing", self, self._job, user=user, tags=tags, **kwargs) - self._job.pause(user=user, tags=tags) - - def resume_processing(self, user=None, tags=None, **kwargs): - if self._job is None or self.state not in (ProtocolState.PAUSING, ProtocolState.PAUSED): - return - self.state = ProtocolState.RESUMING - self.notify_listeners("on_protocol_job_resuming", self, self._job, user=user, tags=tags, **kwargs) - self._job.resume(user=user, tags=tags, **kwargs) - - def cancel_processing(self, error=False, user=None, tags=None, **kwargs): - if self._job is not None and self.state in ProtocolState.PROCESSING_STATES + (ProtocolState.PAUSED,): - self.state = ProtocolState.CANCELLING - self.notify_listeners("on_protocol_job_cancelling", self, self._job, user=user, tags=tags, **kwargs) - self._job.cancel(error=error, user=user, tags=tags, **kwargs) - - def can_send(self): - return True - - def send_commands(self, command_type=None, tags=None, *commands): - pass - - def send_script(self, script, context=None, user=None, tags=None): - """ - Sends the specified script/the GCODE script with the specified name. - - Args: - script (GcodeScript or unicode): Script or name of the script to send - context (dict): Additional render context - user (str): The user on whose behalf the script is being sent. May be None - tags (set): And tags to send with the script commands. May be None - """ - pass - - def repair(self): - pass - - def join(self, timeout=None): - pass - - def on_job_started(self, job, *args, **kwargs): - self.notify_listeners("on_protocol_job_started", self, job, *args, **kwargs) - self.state = ProtocolState.PROCESSING - - def on_job_paused(self, job, *args, **kwargs): - self.notify_listeners("on_protocol_job_paused", self, job, *args, **kwargs) - self.state = ProtocolState.PAUSED - - def on_job_resumed(self, job, *args, **kwargs): - self.notify_listeners("on_protocol_job_resumed", self, job, *args, **kwargs) - self.state = ProtocolState.PROCESSING - - def on_job_done(self, job, *args, **kwargs): - self.notify_listeners("on_protocol_job_done", self, job, *args, **kwargs) - self._job_processed(job) - - def on_job_cancelled(self, job, *args, **kwargs): - self.notify_listeners("on_protocol_job_cancelled", self, job, *args, **kwargs) - self._job_processed(job) - - def on_job_failed(self, job, *args, **kwargs): - self.notify_listeners("on_protocol_job_failed", self, job, *args, **kwargs) - self._job_processed(job) - - def _job_processed(self, job, *args, **kwargs): - self._job.unregister_listener(self) - self.state = ProtocolState.CONNECTED - - def on_transport_disconnected(self, transport, error=None): - self.disconnect(error=error is not None) - - def on_transport_log_received_data(self, transport, data): - message = to_unicode(data, errors="replace").strip() - self.notify_listeners("on_protocol_log_received", self, message) - - message = "<<< {}".format(message) - self.process_protocol_log(message) - - def on_transport_log_sent_data(self, transport, data): - message = to_unicode(data, errors="replace").strip() - self.notify_listeners("on_protocol_log_sent", self, message) - - message = ">>> {}".format(message) - self.process_protocol_log(message) - - def on_transport_log_message(self, transport, data): - message = to_unicode(data, errors="replace").strip() - self.notify_listeners("on_protocol_log_message", self, message) - - message = "--- {}".format(message) - self.process_protocol_log(message) - - def process_protocol_log(self, message): - self._connection_logger.debug(message) - self.notify_listeners("on_protocol_log", self, message) - - def _job_on_hold_cleared(self): - pass - - - def __str__(self): - return self.__class__.__name__ class ProtocolState(object): - CONNECTING = "connecting" - CONNECTED = "connected" - DISCONNECTING = "disconnecting" - DISCONNECTED = "disconnected" - STARTING = "starting" - PROCESSING = "processing" - FINISHING = "finishing" - CANCELLING = "cancelling" - PAUSING = "pausing" - RESUMING = "resuming" - PAUSED = "paused" - ERROR = "error" - DISCONNECTING_WITH_ERROR = "disconnecting_with_error" - DISCONNECTED_WITH_ERROR = "disconnected_with_error" + CONNECTING = "connecting" + CONNECTED = "connected" + DISCONNECTING = "disconnecting" + DISCONNECTED = "disconnected" + STARTING = "starting" + PROCESSING = "processing" + FINISHING = "finishing" + CANCELLING = "cancelling" + PAUSING = "pausing" + RESUMING = "resuming" + PAUSED = "paused" + ERROR = "error" + DISCONNECTING_WITH_ERROR = "disconnecting_with_error" + DISCONNECTED_WITH_ERROR = "disconnected_with_error" + + PROCESSING_STATES = (STARTING, PROCESSING, CANCELLING, PAUSING, RESUMING, FINISHING) + OPERATIONAL_STATES = (CONNECTED, PAUSED) + PROCESSING_STATES - PROCESSING_STATES = (STARTING, PROCESSING, CANCELLING, PAUSING, RESUMING, FINISHING) - OPERATIONAL_STATES = (CONNECTED, PAUSED) + PROCESSING_STATES class ProtocolSettings(SubSettings): - def __init__(self, settings, protocol): - SubSettings.__init__(self, settings, ["comm", "protocol", protocol.key], - defaults=protocol.get_settings_defaults()) + def __init__(self, settings, protocol): + SubSettings.__init__( + self, + settings, + ["comm", "protocol", protocol.key], + defaults=protocol.get_settings_defaults(), + ) + class ProtocolAlreadyConnectedError(Exception): - pass + pass + class ProtocolNotConnectedError(Exception): - pass + pass class ThreeAxisProtocolMixin(object): - def move(self, x=None, y=None, z=None, feedrate=None, relative=False, *args, **kwargs): - pass + def move( + self, x=None, y=None, z=None, feedrate=None, relative=False, *args, **kwargs + ): + pass - def home(self, x=False, y=False, z=False, *args, **kwargs): - pass + def home(self, x=False, y=False, z=False, *args, **kwargs): + pass - def set_feedrate_multiplier(self, multiplier, *args, **kwargs): - pass + def set_feedrate_multiplier(self, multiplier, *args, **kwargs): + pass class HeaterProtocolMixin(object): - def set_temperature(self, heater, temperature, wait=False, *args, **kwargs): - pass + def set_temperature(self, heater, temperature, wait=False, *args, **kwargs): + pass - def set_temperature_offset(self, heater, offset, *args, **kwargs): - pass + def set_temperature_offset(self, heater, offset, *args, **kwargs): + pass - def get_temperature_offsets(self): - return dict() + def get_temperature_offsets(self): + return {} class MultiToolProtocolMixin(object): - def change_tool(self, tool, *args, **kwargs): - pass + def change_tool(self, tool, *args, **kwargs): + pass -class Fdm3dPrinterProtocolMixin(ThreeAxisProtocolMixin, HeaterProtocolMixin, MultiToolProtocolMixin): - def move(self, x=None, y=None, z=None, e=None, feedrate=None, relative=False, *args, **kwargs): - pass +class Fdm3dPrinterProtocolMixin( + ThreeAxisProtocolMixin, HeaterProtocolMixin, MultiToolProtocolMixin +): + def move( + self, + x=None, + y=None, + z=None, + e=None, + feedrate=None, + relative=False, + *args, + **kwargs + ): + pass - def set_extrusion_multiplier(self, multiplier, *args, **kwargs): - pass + def set_extrusion_multiplier(self, multiplier, *args, **kwargs): + pass class FanControlProtocolMixin(object): - def set_fan_speed(self, speed, *args, **kwargs): - pass + def set_fan_speed(self, speed, *args, **kwargs): + pass - def get_fan_speed(self, speed, *args, **kwargs): - pass + def get_fan_speed(self, speed, *args, **kwargs): + pass class MotorControlProtocolMixin(object): - def enable_motors(self, *args, **kwargs): - self.set_motor_state(True) + def enable_motors(self, *args, **kwargs): + self.set_motor_state(True) - def disable_motors(self, *args, **kwargs): - self.set_motor_state(False) + def disable_motors(self, *args, **kwargs): + self.set_motor_state(False) - def set_motor_state(self, enabled, *args, **kwargs): - pass + def set_motor_state(self, enabled, *args, **kwargs): + pass - def get_motor_state(self, *args, **kwargs): - pass + def get_motor_state(self, *args, **kwargs): + pass class PowerControlProtocolMixin(object): - def enable_power(self, *args, **kwargs): - self.set_power_state(True) + def enable_power(self, *args, **kwargs): + self.set_power_state(True) - def disable_power(self, *args, **kwargs): - self.set_power_state(False) + def disable_power(self, *args, **kwargs): + self.set_power_state(False) - def set_power_state(self, enabled, *args, **kwargs): - pass + def set_power_state(self, enabled, *args, **kwargs): + pass - def get_power_state(self, *args, **kwargs): - return None + def get_power_state(self, *args, **kwargs): + return None class FileAwareProtocolMixin(object): - def init_file_storage(self, *args, **kwargs): - pass + def init_file_storage(self, *args, **kwargs): + pass - def eject_file_storage(self, *args, **kwargs): - pass + def eject_file_storage(self, *args, **kwargs): + pass - def list_files(self, *args, **kwargs): - pass + def list_files(self, *args, **kwargs): + pass - def start_file_print(self, name, position=0, tags=None, *args, **kwargs): - pass + def start_file_print(self, name, position=0, tags=None, *args, **kwargs): + pass - def pause_file_print(self, *args, **kwargs): - pass + def pause_file_print(self, *args, **kwargs): + pass - def resume_file_print(self, *args, **kwargs): - pass + def resume_file_print(self, *args, **kwargs): + pass - def get_file_print_status(self, *args, **kwargs): - pass + def get_file_print_status(self, *args, **kwargs): + pass - def start_file_print_status_monitor(self, *args, **kwargs): - pass + def start_file_print_status_monitor(self, *args, **kwargs): + pass - def stop_file_print_status_monitor(self, *args, **kwargs): - pass + def stop_file_print_status_monitor(self, *args, **kwargs): + pass class FileManagementProtocolMixin(FileAwareProtocolMixin): - def delete_file(self, name, *args, **kwargs): - pass + def delete_file(self, name, *args, **kwargs): + pass class FileStreamingProtocolMixin(FileManagementProtocolMixin): - def record_file(self, name, *args, **kwargs): - pass + def record_file(self, name, *args, **kwargs): + pass - def stop_recording_file(self, *args, **kwargs): - pass + def stop_recording_file(self, *args, **kwargs): + pass class ProtocolListener(object): - def on_protocol_state(self, protocol, old_state, new_state, *args, **kwargs): - pass + def on_protocol_state(self, protocol, old_state, new_state, *args, **kwargs): + pass - def on_protocol_temperature(self, protocol, temperatures, *args, **kwargs): - pass + def on_protocol_temperature(self, protocol, temperatures, *args, **kwargs): + pass - def on_protocol_log(self, protocol, message, *args, **kwargs): - pass + def on_protocol_log(self, protocol, message, *args, **kwargs): + pass - def on_protocol_log_received(self, protocol, message, *args, **kwargs): - pass + def on_protocol_log_received(self, protocol, message, *args, **kwargs): + pass - def on_protocol_log_sent(self, protocol, message, *args, **kwargs): - pass + def on_protocol_log_sent(self, protocol, message, *args, **kwargs): + pass - def on_protocol_log_message(self, protocol, message, *args, **kwargs): - pass + def on_protocol_log_message(self, protocol, message, *args, **kwargs): + pass - def on_protocol_reset(self, protocol, idle, *args, **kwargs): - pass + def on_protocol_reset(self, protocol, idle, *args, **kwargs): + pass - def on_protocol_job_started(self, protocol, job, *args, **kwargs): - pass + def on_protocol_job_started(self, protocol, job, *args, **kwargs): + pass - def on_protocol_job_pausing(self, protocol, job, *args, **kwargs): - pass + def on_protocol_job_pausing(self, protocol, job, *args, **kwargs): + pass - def on_protocol_job_paused(self, protocol, job, *args, **kwargs): - pass + def on_protocol_job_paused(self, protocol, job, *args, **kwargs): + pass - def on_protocol_job_resuming(self, protocol, job, *args, **kwargs): - pass + def on_protocol_job_resuming(self, protocol, job, *args, **kwargs): + pass - def on_protocol_job_resumed(self, protocol, job, *args, **kwargs): - pass + def on_protocol_job_resumed(self, protocol, job, *args, **kwargs): + pass - def on_protocol_job_cancelling(self, protocol, job, *args, **kwargs): - pass + def on_protocol_job_cancelling(self, protocol, job, *args, **kwargs): + pass - def on_protocol_job_cancelled(self, protocol, job, *args, **kwargs): - pass + def on_protocol_job_cancelled(self, protocol, job, *args, **kwargs): + pass - def on_protocol_job_finishing(self, protocol, job, *args, **kwargs): - pass + def on_protocol_job_finishing(self, protocol, job, *args, **kwargs): + pass - def on_protocol_job_done(self, protocol, job, *args, **kwargs): - pass + def on_protocol_job_done(self, protocol, job, *args, **kwargs): + pass - def on_protocol_job_failed(self, protocol, job, *args, **kwargs): - pass + def on_protocol_job_failed(self, protocol, job, *args, **kwargs): + pass class FileAwareProtocolListener(object): - def on_protocol_file_storage_available(self, protocol, available, *args, **kwargs): - pass + def on_protocol_file_storage_available(self, protocol, available, *args, **kwargs): + pass - def on_protocol_file_list(self, protocol, files, *args, **kwargs): - pass + def on_protocol_file_list(self, protocol, files, *args, **kwargs): + pass - def on_protocol_file_status(self, protocol, pos, total, *args, **kwargs): - pass + def on_protocol_file_status(self, protocol, pos, total, *args, **kwargs): + pass - def on_protocol_file_print_started(self, protocol, name, long_name, size, *args, **kwargs): - pass + def on_protocol_file_print_started( + self, protocol, name, long_name, size, *args, **kwargs + ): + pass - def on_protocol_file_print_done(self, protocol, *args, **kwargs): - pass + def on_protocol_file_print_done(self, protocol, *args, **kwargs): + pass - def on_protocol_file_print_paused(self, protocol, *args, **kwargs): - pass + def on_protocol_file_print_paused(self, protocol, *args, **kwargs): + pass - def on_protocol_file_print_resumed(self, protocol, *args, **kwargs): - pass + def on_protocol_file_print_resumed(self, protocol, *args, **kwargs): + pass class PositionAwareProtocolListener(object): + def on_protocol_position_all_update(self, protocol, position, *args, **kwargs): + pass - def on_protocol_position_all_update(self, protocol, position, *args, **kwargs): - pass - - def on_protocol_position_z_update(self, protocol, z, *args, **kwargs): - pass + def on_protocol_position_z_update(self, protocol, z, *args, **kwargs): + pass class FirmwareDataAwareProtocolListener(object): + def on_protocol_firmware_info(self, protocol, info, *args, **kwargs): + pass - def on_protocol_firmware_info(self, protocol, info, *args, **kwargs): - pass - - def on_protocol_firmware_capability(self, protocol, capability, enabled, capabilities, *args, **kwargs): - pass + def on_protocol_firmware_capability( + self, protocol, capability, enabled, capabilities, *args, **kwargs + ): + pass diff --git a/src/octoprint/comm/protocol/reprap/__init__.py b/src/octoprint/comm/protocol/reprap/__init__.py index 41780b9da..c40285017 100644 --- a/src/octoprint/comm/protocol/reprap/__init__.py +++ b/src/octoprint/comm/protocol/reprap/__init__.py @@ -1,82 +1,97 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" -from octoprint.comm.protocol import Protocol, Fdm3dPrinterProtocolMixin, FileStreamingProtocolMixin, \ - MotorControlProtocolMixin, FanControlProtocolMixin, ProtocolState -from octoprint.comm.transport import Transport, LineAwareTransportWrapper, \ - PushingTransportWrapper, PushingTransportWrapperListener, TransportListener, TimeoutTransportException, \ - EofTransportException - -from octoprint.comm.protocol.reprap.commands import Command, to_command -from octoprint.comm.protocol.reprap.commands.atcommand import AtCommand -from octoprint.comm.protocol.reprap.commands.gcode import GcodeCommand - -from octoprint.comm.protocol.reprap.flavors import FlavorOverride, GenericFlavor, all_flavors, lookup_flavor - -from octoprint.comm.protocol.reprap.scripts import GcodeScript - -from octoprint.comm.protocol.reprap.util import normalize_command_handler_result, SendToken, LineHistory, PositionRecord, TemperatureRecord -from octoprint.comm.protocol.reprap.util.queues import ScriptQueue, JobQueue, CommandQueue, SendQueue, QueueMarker, SendQueueMarker - -from octoprint.comm.scripts import InvalidScript, UnknownScript - -from octoprint.comm.util.parameters import GroupChoiceType, Value, ParamGroup, BooleanType, FloatType, IntegerType, SmallChoiceType, SmallListType - -from octoprint.comm.job import LocalGcodeFilePrintjob, SDFilePrintjob, \ - LocalGcodeStreamjob, CopyJobMixin - -from octoprint.util import TypedQueue, TypeAlreadyInQueue, ResettableTimer, to_bytes, to_unicode, protectedkeydict, CountedEvent, monotonic_time -from octoprint.util import dummy_gettext as gettext - -from octoprint.events import Events - -try: - import queue -except ImportError: - import Queue as queue - -# noinspection PyCompatibility -from past.builtins import basestring - import collections import copy import logging +import queue import threading import time +from octoprint.comm.job import ( + CopyJobMixin, + LocalGcodeFilePrintjob, + LocalGcodeStreamjob, + SDFilePrintjob, +) +from octoprint.comm.protocol import ( + FanControlProtocolMixin, + Fdm3dPrinterProtocolMixin, + FileStreamingProtocolMixin, + MotorControlProtocolMixin, + Protocol, + ProtocolState, +) +from octoprint.comm.protocol.reprap.commands import Command, to_command +from octoprint.comm.protocol.reprap.commands.atcommand import AtCommand +from octoprint.comm.protocol.reprap.commands.gcode import GcodeCommand +from octoprint.comm.protocol.reprap.flavors import ( + GenericFlavor, + all_flavors, + lookup_flavor, +) +from octoprint.comm.protocol.reprap.scripts import GcodeScript +from octoprint.comm.protocol.reprap.util import ( + LineHistory, + PositionRecord, + SendToken, + TemperatureRecord, + normalize_command_handler_result, +) +from octoprint.comm.protocol.reprap.util.queues import ( + CommandQueue, + JobQueue, + QueueMarker, + SendQueue, + SendQueueMarker, +) +from octoprint.comm.scripts import InvalidScript, UnknownScript +from octoprint.comm.transport import ( + EofTransportException, + LineAwareTransportWrapper, + PushingTransportWrapper, + PushingTransportWrapperListener, + TimeoutTransportException, + Transport, + TransportListener, +) +from octoprint.comm.util.parameters import ( + BooleanType, + FloatType, + GroupChoiceType, + IntegerType, + ParamGroup, + SmallChoiceType, + SmallListType, + Value, +) +from octoprint.events import Events +from octoprint.util import ResettableTimer, TypeAlreadyInQueue +from octoprint.util import dummy_gettext as gettext +from octoprint.util import monotonic_time, protectedkeydict, to_bytes, to_unicode GCODE_TO_EVENT = { - # pause for user input - "M226": Events.WAITING, - "M0": Events.WAITING, - "M1": Events.WAITING, - # dwell command - "G4": Events.DWELL, - - # part cooler - "M245": Events.COOLING, - - # part conveyor - "M240": Events.CONVEYOR, - - # part ejector - "M40": Events.EJECT, - - # user alert - "M300": Events.ALERT, - - # home print head - "G28": Events.HOME, - - # emergency stop - "M112": Events.E_STOP, - - # motors on/off - "M80": Events.POWER_ON, - "M81": Events.POWER_OFF, + # pause for user input + "M226": Events.WAITING, + "M0": Events.WAITING, + "M1": Events.WAITING, + # dwell command + "G4": Events.DWELL, + # part cooler + "M245": Events.COOLING, + # part conveyor + "M240": Events.CONVEYOR, + # part ejector + "M40": Events.EJECT, + # user alert + "M300": Events.ALERT, + # home print head + "G28": Events.HOME, + # emergency stop + "M112": Events.E_STOP, + # motors on/off + "M80": Events.POWER_ON, + "M81": Events.POWER_OFF, } CAPABILITY_AUTOREPORT_TEMP = "AUTOREPORT_TEMP" @@ -87,2650 +102,3339 @@ CAPABILITY_CHAMBER_TEMP = "CHAMBER_TEMPERATURE" class FallbackValue(object): - def __init__(self, value, fallback=None, test=None): - self.value = value - self.fallback = fallback + def __init__(self, value, fallback=None, test=None): + self.value = value + self.fallback = fallback - self.test = test - if self.test is None: - self.test = lambda x: x is not None + self.test = test + if self.test is None: + self.test = lambda x: x is not None - @property - def effective(self): - if self.test(self.value): - return self.value - return self.fallback + @property + def effective(self): + if self.test(self.value): + return self.value + return self.fallback class BooleanCallbackValue(object): - def __init__(self, callback): - assert callable(callback) - self.callback = callback - - def __nonzero__(self): - return self.__bool__() - - def __bool__(self): - return bool(self.callback()) - - -class ReprapGcodeProtocol(Protocol, Fdm3dPrinterProtocolMixin, MotorControlProtocolMixin, - FanControlProtocolMixin, FileStreamingProtocolMixin, - PushingTransportWrapperListener, TransportListener): - name = "Reprap GCODE Protocol" - key = "reprap" - - supported_jobs = [LocalGcodeFilePrintjob, - LocalGcodeStreamjob, - SDFilePrintjob] - - @classmethod - def get_connection_options(cls): - return [GroupChoiceType("flavor", - "Firmware Flavor", - sorted([Value(f.key, - title=f.name) for f in all_flavors()], - key=lambda x: x.title), - ParamGroup("flavor_overrides", - "Flavor Overrides", - [SmallChoiceType("send_checksum", - gettext("Send a checksum with the command"), - [Value("printing", title=gettext("When printing")), - Value("always", title=gettext("Always")), - Value("never", title=gettext("Never"))]), - SmallChoiceType("trigger_ok_after_resend", - gettext("Trigger ok after resend"), - [Value("detect", title=gettext("If detected as necessary")), - Value("always", title=gettext("Always")), - Value("never", title=gettext("Never"))], - expert=True, - help=gettext("Some Marlin forks lack an acknowledging `ok` with their resend requests. Set this to \"Always\" or \"If detected as necessary\" if you run into communication stalls on resend requests.")), - BooleanType("unknown_requires_ack", - gettext("Unknown commands require `ok`")), - BooleanType("unknown_with_checksum", - gettext("Send unknown commands with line number & checksum")), - BooleanType("detect_external_heatups", - gettext("Try to detect externally triggered blocking heatups")), - BooleanType("block_while_dwelling", - gettext("Block all communication while a dwell command (`G4`) is active")), - BooleanType("sd_relative_path", - gettext("Select SD files by relative path")), - BooleanType("sd_always_available", - gettext("Always assume that the SD card is present")), - BooleanType("heatup_abortable", - gettext("Allow cancelling blocking heatups if the firmware supports it")), - SmallListType("blocked_commands", - gettext("Blocked commands"), - help=gettext("Use this to specify commands that should never be sent to the printer. Just the G or M code, comma separated. Defaults to `M0` and `M1` since most firmware will block until a button on the controller has been pressed if it receives either of those two commands.")), - SmallListType("checksum_requiring_commands", - gettext("Checksum requiring commands"), - help=gettext("")), - SmallListType("long_running_commands", - gettext("Long running commands"), - help=gettext("")), - SmallListType("asynchronous_commands", - gettext("Asynchronous commands"), - help=gettext(""), - expert=True), - SmallListType("pausing_commands", - gettext("Pausing commands"), - help=gettext(""), - expert=True), - SmallListType("emergency_commands", - gettext("Emergency commands"), - help=gettext(""), - expert=True) - ], - help=gettext("You can override the firmware flavor default settings here. You usually should *not* need to do that. Only change anything if the defaults don't work for your printer."), - advanced=True), - defaults=dict((f.key, f.overridable()) for f in all_flavors()), - default="generic"), - ParamGroup("error_handling", - gettext("Error handling"), - [SmallChoiceType("firmware_errors", gettext("What to do on a firmware error (`Error:` or `!!`)"), - [Value("disconnect", - title=gettext("Disconnect from the printer")), - Value("cancel", - title=gettext("Cancel any ongoing prints but stay connected to the printer"), - help=gettext("Please note that if you choose this, OctoPrint will still disconnect from the printer in case of *fatal* errors reported by your firmware (e.g. `kill() called`, `fatal:`)")), - Value("ignore", - title=gettext("Ignore"), - warning=True, - help=gettext("Only choose this if your firmware sends error messages that are not actual errors. Might mask printer issues (even fatal errors!), be careful!"))], - default="disconnect"), - # TODO: implement send_m112 flag - BooleanType("send_m112", - gettext("Send `M112` on disconnect due to error"), - default=True, - warning=False, - help=gettext("If this is checked, OctoPrint will try to send an `M112` prior to a disconnect due to a (fatal) error in order to disable heaters and motors."))], - advanced=True), - ParamGroup("pausing", - gettext("Pausing"), - [BooleanType("log_position_on_pause", - gettext("Log position on pause"), - default=True, - warning=True, - help=gettext("If you disable this, the `pause_position` placeholders in your pause/resume GCODE scripts will stay unpopulated! However, pausing speed might improve slightly."))], - advanced=True), - ParamGroup("cancelling", - gettext("Cancelling"), - [BooleanType("log_position_on_cancel", - gettext("Log position on cancel"), - default=True, - warning=True, - help=gettext("If you disable this, the `cancel_position` placeholders in your cancel GCODE script and the corresponding data in the print recovery data will stay unpopulated! However, cancelling speed might improve slightly."))], - advanced=True), - ParamGroup("intervals", - gettext("Query intervals"), - [FloatType("temperature_interval_idle", - gettext("Temperature (idle)"), - default=5, - unit="sec", - help=gettext("When printing or idle")), - FloatType("temperature_interval_target", - gettext("Temperature (target set)"), - default=2, - unit="sec", - help=gettext("When idle and a target temperature is set")), - FloatType("temperature_interval_auto", - gettext("Temperature (autoreport)"), - default=2, - unit="sec", - help=gettext("Autoreport interval to request from the firmware")), - FloatType("sdstatus_interval_normal", - gettext("SD Status"), - default=1, - unit="sec", - help=gettext("When printing from the printer's SD")), - FloatType("sdstatus_interval_auto", - gettext("SD status (autoreport)"), - default=1, - unit="sec", - help=gettext("Autoreport interval to request from the firmware"))], - advanced=True), - ParamGroup("timeouts", - gettext("Timeouts"), - [FloatType("communication_timeout_normal", - gettext("Communication"), - default=30, - unit="sec", - help=gettext("`busy` protocol support not detected")), - FloatType("communication_timeout_busy", - gettext("Communication (busy)"), - default=3, - unit="sec", - help=gettext("`busy` protocol support detected")), - FloatType("connection_timeout", - gettext("Connection timeout"), - default=10, - unit="sec"), - FloatType("detection_timeout", - gettext("Autodetection"), - default=1, - unit="sec", - help=""), - FloatType("position_log_wait", - gettext("Position query"), - default=10, - unit="sec"), - FloatType("baudrate_detection_pause", - gettext("Initial baudrate detection pause"), - expert=True, - default=1.0, - unit="sec", - help=gettext("Some controllers need a bit of a breather before baudrate detection after initial connect. If baudrate detection fails due to a hanging controller, try increasing this value.")), - FloatType("resendok_timeout", - gettext("Timeout for `ok` after resend detection"), - expert=True, - default=.5, - unit="sec", - help=gettext("Some firmwares do not send an `ok` after a resend request. This timeout configures how long OctoPrint will wait for one until it assumes this particular bug to be present and generate its own.")), - IntegerType("max_consecutive_timeouts_idle", - gettext("Max. consecutive timeouts while idle"), - expert=True, - default=2, - help=gettext("Set to 0 to disable consecutive timeout detection and handling.")), - IntegerType("max_consecutive_timeouts_printing", - gettext("Max. consecutive timeouts while printing"), - expert=True, - default=5, - help=gettext("Set to 0 to disable consecutive timeout detection and handling.")), - IntegerType("max_consecutive_timeouts_long", - gettext("Max. consecutive timeouts during long running commands"), - expert=True, - default=5, - help=gettext("Set to 0 to disable consecutive timeout detection and handling."))], - advanced=True), - ParamGroup("capabilities", - gettext("Firmware capability support"), - [BooleanType("autoreport_temp", - gettext("Enable temperature autoreporting if supported"), - default=True, - help=gettext("Uncheck this if you want to disable temperature autoreporting, even if the firmware supports it")), - BooleanType("autoreport_sd_status", - gettext("Enable sd status autoreporting if supported"), - default=True, - help=gettext("Uncheck this if you want to disable sd status autoreporting, even if the firmware supports it")), - BooleanType("emergency_parser", - gettext("Use emergency parser if supported"), - default=True, - help=gettext("Uncheck this if you want to disable force-sending emergency commands to compatible printers, even if the firmware supports it")), - BooleanType("busy_protocol", - gettext("Use `busy` protocol if supported"), - default=True, - help=gettext("Uncheck this if you want to disable use of the `busy` protocol, even if the firmware supports it")), - BooleanType("chamber_temp", - gettext("Enable chamber temperature management if supported"), - default=True, - help=gettext("Uncheck this if you want to disable chamber temperature management, even if the firmware supports it"))], - advanced=True)] - - @staticmethod - def get_flavor_attributes_starting_with(flavor, prefix): - return [x for x in dir(flavor) if x.startswith(prefix)] - - @classmethod - def get_attributes_starting_with(cls, prefix): - return dict((x, getattr(cls, x)) for x in dir(cls) if x.startswith(prefix)) - - def __init__(self, - flavor=None, - *args, - **kwargs): - super(ReprapGcodeProtocol, self).__init__(*args, **kwargs) - - self.flavor = lookup_flavor(flavor) - if self.flavor is None: - self.flavor = GenericFlavor - - self.flavor_overrides = kwargs.get("flavor_overrides", dict()) - self.flavor = self.flavor.with_overrides(self.flavor_overrides) - - self.set_current_args(flavor=self.flavor.key, - flavor_overrides=self.flavor_overrides) - - self._logger = logging.getLogger(__name__) - self._commdebug_logger = logging.getLogger("COMMDEBUG") - self._phase_logger = logging.getLogger(__name__ + ".command_phases") - - self._terminal_log = collections.deque([], 20) - - self.timeouts = dict( - connection=kwargs.get("timeouts", dict()).get("connection_timeout", 30.0), - communication=kwargs.get("timeouts", dict()).get("communication_timeout_normal", 10.0), - communication_busy=kwargs.get("timeouts", dict()).get("communication_timeout_busy", 2.0) - ) - self.interval = dict( - temperature_idle=kwargs.get("intervals", dict()).get("temperature_interval_idle", 5.0), - temperature_printing=kwargs.get("intervals", dict()).get("temperature_interval_printing", 5.0), - temperature_autoreport=kwargs.get("intervals", dict()).get("temperature_interval_autoreport", 2.0), - sd_status=kwargs.get("intervals", dict()).get("sd_status_interval_normal", 2.0), - sd_status_autoreport=kwargs.get("intervals", dict()).get("sd_status_interval_auto", 1.0) - ) - self.max_consecutive_timeouts = dict( - idle=kwargs.get("timeouts", dict()).get("max_consecutive_idle", 2), - printing=kwargs.get("timeouts", dict()).get("max_consecutive_printing", 5), - long=kwargs.get("timeouts", dict()).get("max_consecutive_long", 5), - ) - - self.firmware_errors = kwargs.get("error_handling", dict()).get("firmware_errors", "disconnect") - - flavor_comm_attrs = self.get_flavor_attributes_starting_with(self.flavor, "comm_") - flavor_message_attrs = self.get_flavor_attributes_starting_with(self.flavor, "message_") - flavor_error_attrs = self.get_flavor_attributes_starting_with(self.flavor, "error_") - - self._comm_messages = flavor_comm_attrs - self._registered_messages = flavor_comm_attrs + flavor_message_attrs - self._current_registered_messages = self._registered_messages - self._error_messages = flavor_error_attrs - - self._handlers_gcode = self.get_attributes_starting_with("_gcode_") - self._handlers_atcommand = self.get_attributes_starting_with("_atcommand_") - self._handlers_command_phase = self.get_attributes_starting_with("_command_phase_") - - self._capability_support = dict() - self._capability_support[CAPABILITY_AUTOREPORT_TEMP] = kwargs.get("capabilities", dict()).get("autoreport_temp", True) - self._capability_support[CAPABILITY_AUTOREPORT_SD_STATUS] = kwargs.get("capabilities", dict()).get("autoreport_sd_status", True) - self._capability_support[CAPABILITY_EMERGENCY_PARSER] = kwargs.get("capabilities", dict()).get("emergency_parser", True) - self._capability_support[CAPABILITY_BUSY_PROTOCOL] = kwargs.get("capabilities", dict()).get("busy_protocol", True) - self._capability_support[CAPABILITY_CHAMBER_TEMP] = kwargs.get("capabilities", dict()).get("chamber_temp", True) - - self._transport = None - - self._internal_flags = dict( - # temperature and heating related - temperatures=TemperatureRecord(), - heating_start=None, - heating_lost=0, - heating=False, - temperature_autoreporting=False, - temperature_offsets=dict(), - - # current stuff - current_tool=0, - former_tool=0, - current_f=None, - current_z=None, - - # sd status - sd_available=False, - sd_files=[], - sd_files_temp=None, - sd_status_autoreporting=False, - - # resend status - resend_requested=None, - resend_linenumber=None, - resend_count=None, - - # protocol status - long_running_command=False, - - # misc - only_from_job=BooleanCallbackValue(lambda: self.state in ProtocolState.PROCESSING_STATES - and self._job - and self._job.exclusive), - trigger_events=BooleanCallbackValue(lambda: not (self.state in ProtocolState.PROCESSING_STATES - and self._job - and self._job.exclusive)), - expect_continous_comms=BooleanCallbackValue(lambda: self.state in ProtocolState.PROCESSING_STATES - and self._job - and not self._job.parallel), - ignore_ok=0, - job_on_hold=BooleanCallbackValue(lambda: self.job_on_hold), - - # timeout - timeout = None, - timeout_consecutive=0, - ok_timeout=None, - - # dwelling - dwelling_until=None, - - # firmware info - firmware_identified=False, - firmware_name=None, - firmware_info=dict(), - firmware_capabilities=dict(), - firmware_capability_support=dict(), - - # busy protocol - busy_detected=False, - - # multiline errors - multiline_error=False, # either False or the first error line - ) - self._protected_flags = protectedkeydict(self._internal_flags) - - self._job_queue = JobQueue() - self._command_queue = CommandQueue() - self._send_queue = SendQueue() - self._clear_to_send = SendToken(max=10, - name="protocol.clear_to_send") - - self._current_linenumber = 1 - self._last_lines = LineHistory(max= 50) - self._last_communication_error = None - - # last known temperatures - self.pause_temperature = TemperatureRecord() - self.cancel_temperature = TemperatureRecord() - - # last known positions - self.last_position = PositionRecord() - self.pause_position = PositionRecord() - self.cancel_position = PositionRecord() - - # pause and cancel processing - self._record_pause_data = False - self._record_cancel_data = False - - # hooks - self._gcode_hooks = dict(queuing=self._plugin_manager.get_hooks("octoprint.comm.protocol.gcode.queuing"), - queued=self._plugin_manager.get_hooks("octoprint.comm.protocol.gcode.queued"), - sending=self._plugin_manager.get_hooks("octoprint.comm.protocol.gcode.sending"), - sent=self._plugin_manager.get_hooks("octoprint.comm.protocol.gcode.sent"), - receiving=self._plugin_manager.get_hooks("octoprint.comm.protocol.gcode.receiving")) - - self._error_hooks = self._plugin_manager.get_hooks("octoprint.comm.protocol.gcode.error") - - self._atcommand_hooks = dict(queuing=self._plugin_manager.get_hooks("octoprint.comm.protocol.atcommand.queuing"), - sending=self._plugin_manager.get_hooks("octoprint.comm.protocol.atcommand.sending")), - - self._action_hooks = self._plugin_manager.get_hooks("octoprint.comm.protocol.action") - - self._script_hooks = self._plugin_manager.get_hooks("octoprint.comm.protocol.scripts") - - self._temperature_hooks = self._plugin_manager.get_hooks("octoprint.comm.protocol.temperatures.received") - - self._firmware_info_hooks = self._plugin_manager.get_hooks("octoprint.comm.firmware.info") - - self._firmware_cap_hooks = self._plugin_manager.get_hooks("octoprint.comm.firmware.capabilities") - - - # polling - self._temperature_poller = None - self._sd_status_poller = None - - # script processing - self._suppress_scripts = set() - - # user logging - self._action_users = dict() - - # resend logging - self._log_resends = True - self._log_resends_rate_start = None - self._log_resends_rate_count = 0 - self._log_resends_rate_frame = 60 - self._log_resends_max = 5 - - # mutexes - self._line_mutex = threading.RLock() - self._send_queue_mutex = threading.RLock() - self._pause_mutex = threading.RLock() - self._cancel_mutex = threading.RLock() - self._suppress_scripts_mutex = threading.RLock() - self._action_users_mutex = threading.RLock() - - # timers - self._pause_position_timer = None - self._cancel_position_timer = None - self._resend_ok_timer = None - - # sending thread - self._send_queue_active = False - self._sending_thread = None - - @property - def _active(self): - return self._transport is not None and self._transport.active and self._send_queue_active - - def connect(self, transport, transport_args=None, transport_kwargs=None): - if not isinstance(transport, Transport): - raise ValueError("transport must be a Transport subclass but is a {} instead".format(type(transport))) - - self._internal_flags["timeout"] = self._get_timeout("connection") - - transport = PushingTransportWrapper(LineAwareTransportWrapper(transport), timeout=5.0) - - self._send_queue_active = True - self._sending_thread = threading.Thread(target=self._send_loop, name="comm.sending_thread") - self._sending_thread.daemon = True - self._sending_thread.start() - - super(ReprapGcodeProtocol, self).connect(transport, - transport_args=transport_args, - transport_kwargs=transport_kwargs) - - # cancel handling - - def _cancel_preparation_failed(self): - self.process_protocol_log("Did not receive parseable position data from printer within {}s, " - "continuing without it".format(self.timeouts.get("position_log_wait", 10.0))) - self._cancel_preparation_done() - - def _cancel_preparation_done(self, check_timer=True, suppress_script=False, user=None): - if user is None: - with self._action_users_mutex: - try: - user = self._action_users.pop("cancel") - except KeyError: - pass - - with self._cancel_mutex: - if self._cancel_position_timer is not None: - self._cancel_position_timer.cancel() - self._cancel_position_timer = None - elif check_timer: - return - - # TODO: recovery data - self.notify_listeners("on_protocol_job_cancelled", self, self._job, - position=self.cancel_position.as_dict(), - suppress_script=suppress_script, - user=user) - - def finalize(): - self.state = ProtocolState.CONNECTED - self.send_commands(SendQueueMarker(finalize), part_of_job=True) - self._continue_sending() - - def cancel_processing(self, error=None, user=None, tags=None, log_position=True): - if self.state not in ProtocolState.PROCESSING_STATES + (ProtocolState.PAUSED,): - return - - if self._job is None: - return - - if tags is None: - tags = set() - - def on_move_finish_requested(): - self._record_cancel_data = True - - with self._cancel_mutex: - if self._cancel_position_timer is not None: - self._cancel_position_timer.cancel() - self._cancel_position_timer = ResettableTimer(self.timeouts.get("position_log_wait", 10.0), - self._cancel_preparation_failed) - self._cancel_position_timer.start() - - self.send_commands(self.flavor.command_get_position(), - part_of_job=True, - tags=tags | {"trigger:comm.cancel", - "trigger:record_position"}) - self._continue_sending() - - # cancel the job - self.state = ProtocolState.CANCELLING - - if self.flavor.heatup_abortable: - self.send_commands(self.flavor.command_abort_heatup(), - part_of_job=True, - tags=tags | {"trigger:comm.cancel", - "trigger:abort_heatup"}) - - self._job.cancel(error=error, user=user, tags=tags) - self.notify_listeners("on_protocol_job_cancelling", self, self._job, - error=error, - user=user, - tags=tags) - - if log_position and not isinstance(self._job, CopyJobMixin): - with self._action_users_mutex: - self._action_users["cancel"] = user - - self.send_commands(self.flavor.command_finish_moving(), - part_of_job=True, - on_sent=on_move_finish_requested, - tags=tags | {"trigger:comm.cancel", - "trigger:record_position"}) - self._continue_sending() - else: - self._cancel_preparation_done(check_timer=False, - user=user) - - # pause handling - - def _pause_preparation_failed(self): - self.process_protocol_log("Did not receive parseable position data from printer within {}s, " - "continuing without it".format(self.timeouts.get("position_log_wait", 10.0))) - self._pause_preparation_done() - - def _pause_preparation_done(self, check_timer=True, suppress_script=False, user=None): - if user is None: - with self._action_users_mutex: - try: - user = self._action_users.pop("pause") - except KeyError: - pass - - # do we need to stop a timer? - with self._pause_mutex: - if self._pause_position_timer is not None: - self._pause_position_timer.cancel() - self._pause_position_timer = None - elif check_timer: - return - - self.notify_listeners("on_protocol_job_paused", self, self._job, - position=self.pause_position.as_dict(), - suppress_script=suppress_script, - user=user) - - # wait for current commands to be sent, then switch to paused state - def finalize(): - # only switch to PAUSED if we were still PAUSING, to avoid "swallowing" received resumes during - # pausing - if self.state == ProtocolState.PAUSING: - self.state = ProtocolState.PAUSED - self.send_commands(SendQueueMarker(finalize), part_of_job=True) - self._continue_sending() - - def pause_processing(self, user=None, tags=None, log_position=True, local_handling=True): - if self._job is None or self.state not in (ProtocolState.PROCESSING, - ProtocolState.STARTING, - ProtocolState.RESUMING): - return - - if isinstance(self._job, CopyJobMixin): - return - - if tags is None: - tags = set() - - self.state = ProtocolState.PAUSING - self._job.pause(local_handling=local_handling, - user=user, - tags=tags) - self.notify_listeners("on_protocol_job_pausing", self, self._job, - local_handling=local_handling, - user=user, - tags=tags) - - def on_move_finish_requested(): - self._record_pause_data = True - - with self._pause_mutex: - if self._pause_position_timer is not None: - self._pause_position_timer.cancel() - self._pause_position_timer = None - self._pause_position_timer = ResettableTimer(self.timeouts.get("position_log_wait", 10.0), - self._pause_preparation_failed) - self._pause_position_timer.start() - - self.send_commands(self.flavor.command_get_position(), - part_of_job=True, - tags=tags | {"trigger:comm.set_pause", - "trigger:pause", - "trigger:record_position"}) - self._continue_sending() - - if log_position and local_handling: - with self._action_users_mutex: - self._action_users["pause"] = user - - self.send_commands(self.flavor.command_finish_moving(), - part_of_job=True, - on_sent=on_move_finish_requested, - tags=tags | {"trigger:comm.set_pause", - "trigger:pause", - "trigger:record_position"}) - self._continue_sending() - else: - self._pause_preparation_done(check_timer=False, - suppress_script=not local_handling, - user=user) - - def move(self, x=None, y=None, z=None, e=None, feedrate=None, relative=False, *args, **kwargs): - tags = kwargs.pop("tags", set()) | {"trigger:protocol.move"} - - cmds = [self.flavor.command_move(x=x, y=y, z=z, e=e, f=feedrate)] - - if relative: - cmds = [self.flavor.command_set_relative_positioning()]\ - + cmds\ - + [self.flavor.command_set_absolute_positioning()] - - self.send_commands(*cmds, - tags=tags, - **kwargs) - - def home(self, x=False, y=False, z=False, *args, **kwargs): - tags = kwargs.pop("tags", set()) | {"trigger:protocol.home"} - self.send_commands(self.flavor.command_home(x=x, y=y, z=z), - tags=tags, - **kwargs) - - def change_tool(self, tool, *args, **kwargs): - tags = kwargs.pop("tags", set()) | {"trigger:protocol.change_tool"} - self.send_commands(self.flavor.command_set_tool(tool), - tags=tags, - **kwargs) - - def set_feedrate_multiplier(self, multiplier, *args, **kwargs): - tags = kwargs.pop("tags", set()) | {"trigger:protocol.set_feedrate_multiplier"} - self.send_commands(self.flavor.command_set_feedrate_multiplier(multiplier), - tags=tags, - **kwargs) - - def set_extrusion_multiplier(self, multiplier, *args, **kwargs): - tags = kwargs.pop("tags", set()) | {"trigger:protocol.set_extrusion_multiplier"} - self.send_commands(self.flavor.command_set_extrusion_multiplier(multiplier), - tags=tags, - **kwargs) - - def set_temperature(self, heater, temperature, wait=False, *args, **kwargs): - tags = kwargs.pop("tags", set()) | {"trigger:protocol.set_temperature"} - - if heater.startswith("tool"): - try: - tool = int(heater[len("tool"):]) - except ValueError: - self._logger.error("Got invalid tool heater, expected tool, got: {}".format(heater)) - return - command = self.flavor.command_set_extruder_temp(temperature, tool=tool, wait=wait) - elif heater == "bed": - command = self.flavor.command_set_bed_temp(temperature, wait=wait) - elif heater == "chamber": - command = self.flavor.command_set_chamber_temp(temperature, wait=wait) - else: - self._logger.warn("Got unknown heater identifier to set temperature on: {}".format(heater)) - return - - self.send_commands(command, tags=tags, **kwargs) - - def set_temperature_offset(self, heater, offset, *args, **kwargs): - self._internal_flags["temperature_offsets"][heater] = offset - - def get_temperature_offsets(self): - return copy.copy(self._internal_flags["temperature_offsets"]) - - ##~~ MotorControlProtocolMixin - - def set_motor_state(self, enabled, *args, **kwargs): - tags = kwargs.pop("tags", set()) | {"trigger:protocol.set_motor_state"} - self.send_commands(self.flavor.command_set_motors(enabled), - tags=tags, - **kwargs) - - ##~~ FanControlProtocolMixin - - def set_fan_speed(self, speed, *args, **kwargs): - tags = kwargs.pop("tags", set()) | {"trigger:protocol.set_fan_speed"} - self.send_commands(self.flavor.command_set_fan_speed(speed), - tags=tags, - **kwargs) - - ##~~ FileStreamingProtocolMixin - - def init_file_storage(self, *args, **kwargs): - tags = kwargs.pop("tags", set()) | {"trigger:protocol.init_file_storage"} - self.send_commands(self.flavor.command_sd_init(), - tags=tags, - **kwargs) - - def list_files(self, *args, **kwargs): - tags = kwargs.pop("tags", set()) | {"trigger:protocol.list_files"} - self.send_commands(self.flavor.command_sd_refresh(), - tags=tags, - **kwargs) - - def start_file_print(self, name, position=0, *args, **kwargs): - tags = kwargs.pop("tags", set()) | {"trigger:protocol.start_file_print"} - - self.send_commands(self.flavor.command_sd_select_file(name), - self.flavor.command_sd_set_pos(position), - self.flavor.command_sd_start(), - tags=tags, - **kwargs) - - def pause_file_print(self, *args, **kwargs): - if kwargs.get("local_handling", True): - tags = kwargs.pop("tags", set()) | {"trigger:protocol.pause_file_print"} - self.send_commands(self.flavor.command_sd_pause(), - tags=tags, - **kwargs) - - def resume_file_print(self, *args, **kwargs): - if kwargs.get("local_handling", True): - tags = kwargs.pop("tags", set()) | {"trigger:protocol.resume_file_print"} - self.send_commands(self.flavor.command_sd_resume(), - tags=tags, - **kwargs) - - def delete_file(self, name, *args, **kwargs): - tags = kwargs.pop("tags", set()) | {"trigger:protocol.delete_file"} - self.send_commands(self.flavor.command_sd_delete(name), - tags=tags, - **kwargs) - - def record_file(self, name, *args, **kwargs): - tags = kwargs.pop("tags", set()) | {"trigger:protocol.record_file"} - self.send_commands(self.flavor.command_sd_begin_write(name), - tags=tags, - **kwargs) - - def stop_recording_file(self, *args, **kwargs): - tags = kwargs.pop("tags", set()) | {"trigger:protocol.stop_recording_file"} - self.send_commands(self.flavor.command_sd_end_write(), - tags=tags, - **kwargs) - - def get_file_print_status(self, *args, **kwargs): - tags = kwargs.pop("tags", set()) | {"trigger:protocol.get_file_print_status"} - self.send_commands(self.flavor.command_sd_status(), - tags=tags, - **kwargs) - - def start_file_print_status_monitor(self): - if self._internal_flags["sd_status_autoreporting"]: - return - - from octoprint.util import RepeatedTimer - - def poll_status(): - if self.can_send() and not self._internal_flags["sd_status_autoreporting"]: - self.get_file_print_status() - self._sd_status_poller = RepeatedTimer(self.interval["sd_status"], - poll_status) - self._sd_status_poller.start() - - def stop_file_print_status_monitor(self): - if self._sd_status_poller is not None: - self._sd_status_poller.cancel() - self._sd_status_poller = None - - ##~~ - - def can_send(self): - return self._is_operational() and not self._internal_flags["long_running_command"] and not self._internal_flags["heating"] and not self._internal_flags["dwelling_until"] - - def send_commands(self, *commands, **kwargs): - command_type = kwargs.get("command_type") - on_sent = kwargs.get("on_sent") - tags = kwargs.get("tags") - force = kwargs.get("force", False) - part_of_job = kwargs.get("part_of_job", False) - - def sanitize_command(c, ct, t): - if isinstance(c, tuple): - # unwrap 2-tuples that consist of a command & additional tags - if len(c) != 2: - return None - c, at = c - - assert isinstance(at, set) - t |= at - - # noinspection PyCompatibility - if isinstance(c, Command): - return c.with_type(ct).with_tags(t) - elif isinstance(c, QueueMarker): - return c - elif isinstance(c, basestring): - return to_command(c, type=ct, tags=t) - else: - return None - - result = False - for command in commands: - sanitized = sanitize_command(command, command_type, tags) - if sanitized is None: - continue - - emergency = False - if isinstance(sanitized, GcodeCommand) and sanitized.code in self.flavor.emergency_commands: - emergency = True - - if part_of_job: - if isinstance(sanitized, Command): - sanitized = sanitized.with_tags({"source:job"}) - self._job_queue.put((sanitized, on_sent)) - result = True - - elif self.state in ProtocolState.PROCESSING_STATES and not self._job.parallel and not self.job_on_hold and not force: - try: - self._command_queue.put((sanitized, on_sent), item_type=command_type) - result = True - except TypeAlreadyInQueue as e: - self._logger.debug("Type already in queue: " + e.type) - - elif self._is_operational() or force or emergency: - result = self._send_commands(command, on_sent=on_sent, command_type=command_type, tags=tags) or result - - return result - - def send_script(self, script, context=None, *args, **kwargs): - part_of_job = kwargs.get("part_of_job", False) - - if context is None: - context = dict() - - # noinspection PyCompatibility - if isinstance(script, basestring): - script = GcodeScript(self._settings, script, context=context) - - if not isinstance(script, GcodeScript): - raise InvalidScript("Can't process this script") - - context.update(dict(printer_profile=self._printer_profile, - last_position=self.last_position, - last_temperature=self._internal_flags["temperatures"].as_script_dict())) - - if script.name == "afterPrintPaused" or script.name == "beforePrintResumed": - context.update(dict(pause_position=self.pause_position, - pause_temperature=self.pause_temperature.as_script_dict())) - elif script.name == "afterPrintCancelled": - context.update(dict(cancel_position=self.cancel_position, - cancel_temperature=self.cancel_temperature.as_script_dict())) - - lines = script.render(context=context) - - # process any hooks - prefix = [] - postfix = [] - - for name, hook in self._script_hooks.items(): - try: - retval = hook(self, "gcode", script.name) # prefix, postfix [ , variables [ , additional tags ] ] - except Exception: - self._logger.exception("Error while processing hook {}.".format(name), - extra=dict(plugin=name)) - else: - if retval is None: - continue - if not isinstance(retval, (list, tuple)) or not len(retval) in [2, 3, 4]: - continue - - def to_list(data, t): - # noinspection PyCompatibility - if isinstance(data, basestring): - data = list(x.strip() for x in data.split("\n")) - - if isinstance(data, (list, tuple)): - return list(map(lambda x: (x, t), data)) - else: - return None - - if len(retval) >= 3: - # variables are defined - variables = retval[2] - context.update(dict(plugins={name:variables})) - - additional_tags = {"plugin:{}".format(name)} - if len(retval) == 4: - # additional tags are defined - additional_tags |= set(retval[3]) - - p, s = map(lambda x: to_list(x, additional_tags), retval[0:2]) # convert prefix & postfix - if p: - prefix = list(p) + prefix - if s: - postfix += list(s) - - lines = prefix + lines + postfix - self.send_commands(tags={"trigger:protocol.send_script", - "source:script", - "script:{}".format(script.name)}, - part_of_job=part_of_job, - *lines) - - def repair(self, *args, **kwargs): - self._on_comm_ok() - - def join(self, timeout=None): - if timeout is not None: - stop = monotonic_time() + timeout - while (self._command_queue.unfinished_tasks or self._send_queue.unfinished_tasks) and monotonic_time() < stop: - time.sleep(0.1) - else: - self._command_queue.join() - self._send_queue.join() - - ##~~ State handling - - def _is_operational(self): - return self.state not in (ProtocolState.DISCONNECTED, ProtocolState.DISCONNECTED_WITH_ERROR) - - def _is_busy(self): - return self.state in (ProtocolState.PROCESSING, ProtocolState.PAUSED) - - def _is_streaming(self): - return self._is_busy() and self._job and isinstance(self._job, LocalGcodeStreamjob) - - def _on_switching_state_connecting(self, old_state): - if old_state is not ProtocolState.DISCONNECTED: - return - - hello = self.flavor.command_hello() - if hello: - self._tickle(hello) - - def _on_switching_state_connected(self, old_state): - if old_state == ProtocolState.CONNECTING: - self._internal_flags["timeout"] = self._get_timeout("communication") - - self._send_command(self.flavor.command_set_line(0)) - self._send_command(self.flavor.command_get_firmware_info()) - self._clear_to_send.set() - - def poll_temperature_interval(): - printing_default = 4.0 - target_default = 2.0 - threshold = 25 - - if self.state in ProtocolState.PROCESSING_STATES: - return self.interval.get("temperature_printing", printing_default) - - tools = self._internal_flags["temperatures"].tools - for temp in [tools[k][1] for k in tools]: - if temp > threshold: - return self.interval.get("temperature_target_set", target_default) - - bed = self._internal_flags["temperatures"].bed - if bed and len(bed) > 0 and bed[1] is not None and bed[1] > threshold: - return self.interval.get("temperature_target_set", target_default) - - return self.interval.get("temperature_idle") - - def poll_temperature(): - if self._is_operational() \ - and not self._internal_flags["temperature_autoreporting"] \ - and not self._internal_flags["only_from_job"] \ - and self.can_send(): - self._send_command(self.flavor.command_get_temp(), command_type="temperature_poll", tags={"trigger:protocol.poll_temperature"}) - - from octoprint.util import RepeatedTimer - self._temperature_poller = RepeatedTimer(poll_temperature_interval, - poll_temperature, - run_first=True) - self._temperature_poller.start() - - def _on_switched_state_starting(self, old_state): - # reset line numbers every time we start a new print job - self.send_commands(self.flavor.command_set_line(0)) - - def _on_switched_state_disconnecting(self, old_state): - self._handle_disconnecting(old_state, False) - - def _on_switched_state_disconnecting_with_error(self, old_state): - self._handle_disconnecting(old_state, True) - - def _handle_disconnecting(self, old_state, error): - if self._temperature_poller is not None: - self._temperature_poller.cancel() - self._temperature_poller = None - - if self._sd_status_poller is not None: - self._sd_status_poller.cancel() - self._sd_status_poller = None - - if not error: - try: - self.send_script("beforePrinterDisconnected") - stop = monotonic_time() + 10.0 # TODO make somehow configurable - while (self._command_queue.unfinished_tasks or self._send_queue.unfinished_tasks) and monotonic_time() < stop: - time.sleep(.1) - except UnknownScript: - pass - except Exception: - self._logger.exception("Error while trying to send beforePrinterDisconnected script") - - self._send_queue_active = False - - ##~~ Job handling - - def on_job_started(self, job, *args, **kwargs): - if job != self._job: - return - - self.notify_listeners("on_protocol_job_started", self, job, *args, **kwargs) - - def finalize(): - self.state = ProtocolState.PROCESSING - self.send_commands(SendQueueMarker(finalize), part_of_job=True) - self._continue_sending() - - def on_job_cancelled(self, job, *args, **kwargs): - if job != self._job: - return - self._job_processed(job) - - def on_job_paused(self, job, *args, **kwargs): - pass - - def on_job_resumed(self, job, *args, **kwargs): - if job != self._job: - return - - user = kwargs.get("user") - tags = kwargs.get("tags") - suppress_script = not kwargs.get("local_handling", True) - - self.notify_listeners("on_protocol_job_resumed", self, job, - suppress_script=suppress_script, - user=user, - tags=tags) - - def finalize(): - if self.state == ProtocolState.RESUMING: - self.state = ProtocolState.PROCESSING - self.send_commands(SendQueueMarker(finalize), part_of_job=True) - self._continue_sending() - - def on_job_done(self, job, *args, **kwargs): - if job != self._job: - return - - self.state = ProtocolState.FINISHING - self._job_processed(job) - self.notify_listeners("on_protocol_job_finishing", self, job, *args, **kwargs) - - def finalize(): - self.state = ProtocolState.CONNECTED - self.notify_listeners("on_protocol_job_done", self, job, *args, **kwargs) - self.send_commands(SendQueueMarker(finalize), part_of_job=True) - self._continue_sending() - - def _job_processed(self, job, *args, **kwargs): - self._job.unregister_listener(self) - - def _job_on_hold_cleared(self): - self._continue_sending() - - ##~~ Transport logging - - def on_transport_log_message(self, transport, data): - super(ReprapGcodeProtocol, self).on_transport_log_message(transport, data) - self._terminal_log.append("--- " + to_unicode(data.strip(), errors="replace")) - - def on_transport_log_received_data(self, transport, data): - super(ReprapGcodeProtocol, self).on_transport_log_received_data(transport, data) - self._terminal_log.append("<<< " + to_unicode(data.strip(), errors="replace")) - - def on_transport_log_sent_data(self, transport, data): - super(ReprapGcodeProtocol, self).on_transport_log_sent_data(transport, data) - self._terminal_log.append(">>> " + to_unicode(data.strip(), errors="replace")) - - ##~~ Receiving - - def on_transport_data_pushed(self, transport, data): - if transport != self._transport: - return - self._receive(data) - - def on_transport_data_exception(self, transport, exception): - if transport != self._transport: - return - - if isinstance(exception, TimeoutTransportException): - self._receive("") - elif isinstance(exception, EofTransportException): - self._receive(None) - - def _receive(self, data): - for name, hook in self._gcode_hooks["receiving"].items(): - try: - data = hook(self, data) - except Exception: - self._logger.exception("Error while processing hook {name}:".format(**locals()), - extra=dict(plugin=name)) - else: - if data is None: - data = "" - - if data is None: - # EOF - # TODO handle EOF - pass - - def convert_line(line): - if line is None: - return None, None - stripped_line = line.strip().strip("\0") - return stripped_line, stripped_line.lower() - - orig_line = to_unicode(data, encoding="ascii", errors="replace").strip() - line, lower_line = convert_line(orig_line) - - self._on_comm_any(line, lower_line) - - for message in self._current_registered_messages: - handler_method = getattr(self, "_on_{}".format(message), None) - if not handler_method: - # no handler, nothing to do - continue - - # match line against flavor specific matcher - matches = getattr(self.flavor, message)(line, lower_line, self._state, self._protected_flags) - if isinstance(matches, tuple) and len(matches) == 2: - matches, continue_further = matches - else: - continue_further = not matches - - if matches: - message_args = dict() - - parse_method = getattr(self.flavor, "parse_{}".format(message), None) - if parse_method: - # flavor specific parser? run it - parse_result = parse_method(line, lower_line, self._state, self._protected_flags) - if parse_result is None: - if continue_further: - continue - else: - break - - # add parser result to kwargs - message_args.update(parse_result) - - # before handler: flavor.before_comm_* or flavor.before_message_* - before_handler = getattr(self.flavor, "before_{}".format(message), None) - if before_handler: - before_handler(**message_args) - - # run handler - result = handler_method(**message_args) - - # after handler: flavor.after_comm_* or flavor.after_message_* - after_handler = getattr(self.flavor, "after_{}".format(message), None) - if after_handler: - after_handler(result, **message_args) - - if not result: - # nothing or False returned? handled -> only continue further if instructed - if continue_further: - continue - else: - break - - elif not continue_further: - break - - else: - # unknown message - pass - - def _on_comm_any(self, line, lower_line): - timeout, _ = self.flavor.comm_timeout(line, lower_line, self._state, self._protected_flags) - if not timeout: - self._internal_flags["timeout_consecutive"] = 0 - - offsets = [self.timeouts.get("communication_busy" if self._internal_flags["busy_detected"] else "communication", 0.0),] - if self._temperature_poller: - offsets.append(self._temperature_poller.interval()) - self._internal_flags["timeout"] = self._get_max_timeout(*offsets) - - if len(line): - if self._internal_flags["dwelling_until"] and monotonic_time() > self._internal_flags["dwelling_until"]: - self._internal_flags["dwelling_until"] = False - - if self.state == ProtocolState.CONNECTING and len(line): - hello = self.flavor.command_hello() - if hello: - self._tickle(hello) - - if self._resend_ok_timer and line and not getattr(self.flavor, "comm_ok", lambda *a, **kwa: True)(line, lower_line, self._state, self._protected_flags): - # we got anything but an ok after a resend request - this means the ok after the resend request - # was in fact missing and we now need to trigger the timer - self._resend_ok_timer.cancel() - self._resend_simulate_ok() - - def _on_comm_timeout(self, line, lower_line): - general_message = "Configure long running commands or increase communication timeout if that happens regularly on specific commands or long moves." - - # figure out which consecutive timeout maximum we have to use - if self._internal_flags["long_running_command"]: - consecutive_max = self.max_consecutive_timeouts["long"] - elif self.state in (ProtocolState.PROCESSING, ProtocolState.PAUSING, ProtocolState.CANCELLING): - consecutive_max = self.max_consecutive_timeouts["printing"] - else: - consecutive_max = self.max_consecutive_timeouts["idle"] - - # now increment the timeout counter - self._internal_flags["timeout_consecutive"] += 1 - self._logger.debug("Now at {} consecutive timeouts".format(self._internal_flags["timeout_consecutive"])) - - if 0 < consecutive_max < self._internal_flags["timeout_consecutive"]: - # too many consecutive timeouts, we give up - message = "No response from printer after {} consecutive communication timeouts. " \ - "Have to consider it dead.".format(consecutive_max + 1) - self._logger.info(message) - self.process_protocol_log(message) - - # TODO error handling - self.error = "Too many consecutive timeouts" - - self.disconnect(error=True) - - elif self._internal_flags["resend_requested"] is not None: - message = "Communication timeout during an active resend, resending same line again to trigger response from printer." - self._logger.info(message) - self.notify_listeners("on_protocol_log", self, message + " " + general_message) - if self._send_same_from_resend(): - self._commdebug_logger.debug("on_comm_timeout => clear_to_send.set: timeout during active resend (counter: {})".format(self._clear_to_send.counter)) - self._clear_to_send.set() - - elif self._internal_flags["heating"]: - # blocking heatup active, consider that finished - message = "Timeout while in an active heatup, considering heatup to be over" - self._logger.info(message) - self._finish_heatup() - - elif self._internal_flags["long_running_command"]: - # long running command active, ignore timeout - self._logger.debug("Ran into a communication timeout, but a command known to be a long runner is currently active") - - elif self.state in (ProtocolState.PROCESSING, ProtocolState.PAUSED): - # printing, try to tickle the printer - message = "Communication timeout while printing, trying to trigger response from printer." - self._logger.info(message) - self.notify_listeners("on_protocol_log_message", self, message + " " + general_message) - if self._send_command(GcodeCommand("M105", type="temperature")): - self._commdebug_logger.debug("on_comm_timeout => clear_to_send.set: timeout while printing (counter: {})".format(self._clear_to_send.counter)) - self._clear_to_send.set() - - elif self._clear_to_send.blocked(): - # timeout while idle and no oks left, let's try to tickle the printer - message = "Communication timeout while idle, trying to trigger response from printer." - self._logger.info(message) - self.notify_listeners("on_protocol_log_message", self, message + " " + general_message) - self._commdebug_logger.debug("on_comm_timeout => clear_to_send.set: timeout while idle (counter: {})".format(self._clear_to_send.counter)) - self._clear_to_send.set() - - self._internal_flags["ok_timeout"] = self._get_timeout("communication_busy" if self._internal_flags["busy_detected"] else "communication") - - return self.state != ProtocolState.PROCESSING and line == "" - - def _on_comm_ok(self, wait=False): - if self._internal_flags["ignore_ok"] > 0: - self._internal_flags["ignore_ok"] -= 1 - if self._internal_flags["ignore_ok"] < 0: - self._internal_flags["ignore_ok"] = 0 - self._logger.debug("Ignoring this ok, ignore counter is now {}".format(self._internal_flags["ignore_ok"])) - return - - if self.state == ProtocolState.CONNECTING: - self.state = ProtocolState.CONNECTED - return - - if self._resend_ok_timer: - self._resend_ok_timer.cancel() - self._resend_ok_timer = None - - self._internal_flags["ok_timeout"] = self._get_timeout("communication_busy" if self._internal_flags["busy_detected"] else "communication") - self._commdebug_logger.debug("on_comm_ok => clear_to_send.set: {} (counter: {})".format("wait" if wait else "ok", self._clear_to_send.counter)) - self._clear_to_send.set() - - # reset long running commands, persisted current tools and heatup counters on ok - - self._internal_flags["long_running_command"] = False - - if self._internal_flags["former_tool"]: - self._internal_flags["current_tool"] = self._internal_flags["former_tool"] - self._internal_flags["former_tool"] = None - - self._finish_heatup() - - if not self.state in ProtocolState.OPERATIONAL_STATES: - return - - # process ongoing resend requests and queues if we are operational - - if self._internal_flags["resend_requested"] is not None: - self._send_next_from_resend() - else: - self._continue_sending() - - def _on_comm_ignore_ok(self): - self._internal_flags["ignore_ok"] += 1 - self._logger.info("Ignoring next ok, counter is now at {}".format(self._internal_flags["ignore_ok"])) - - def _on_comm_wait(self): - if self.state == ProtocolState.PROCESSING and not self.job_on_hold: - self._on_comm_ok(wait=True) - - def _on_comm_resend(self, linenumber): - try: - if linenumber is None: - return False - - if self._internal_flags["resend_requested"] is None and linenumber == self._current_linenumber: - # We don't expect to have an active resend request and the printer is requesting a resend of - # a line we haven't yet sent. - # - # This means the printer got a line from us with N = self._current_linenumber - 1 but had already - # acknowledged that. This can happen if the last line was resent due to a timeout during an active - # (prior) resend request. - # - # We will ignore this resend request and just continue normally. - self._logger.debug("Ignoring resend request for line {} == current line, we haven't sent that yet so the printer got N-1 twice from us, probably due to a timeout".format(linenumber)) - self.process_protocol_log("Ignoring resend request for line {}, we haven't sent that yet".format(linenumber)) - return - - last_communication_error = self._last_communication_error - self._last_communication_error = None - - if last_communication_error is not None \ - and last_communication_error == "linenumber" \ - and linenumber == self._internal_flags["resend_requested"] \ - and self._internal_flags["resend_count"] < self._current_linenumber - linenumber - 1: - self._logger.debug("Ignoring resend request for line {}, that still originates from lines we sent before we got the first resend request".format(linenumber)) - self.process_protocol_log("Ignoring resend request for line {}, originates from lines sent earlier".format(linenumber)) - self._internal_flags["resend_count"] += 1 - return - - if not linenumber in self._last_lines: - self._logger.error("Printer requested to resend a line we don't have: {}".format(linenumber)) - if self._is_busy(): - # TODO set error state & log - self.cancel_processing(error=True) - else: - return - - self._internal_flags["resend_requested"] = linenumber - self._internal_flags["resend_linenumber"] = linenumber - self._internal_flags["resend_count"] = 0 - - # if we log resends, make sure we don't log more resends than the set rate within a window - # - # this it to prevent the log from getting flooded for extremely bad communication issues - if self._log_resends: - now = monotonic_time() - new_rate_window = self._log_resends_rate_start is None or self._log_resends_rate_start + self._log_resends_rate_frame < now - in_rate = self._log_resends_rate_count < self._log_resends_max - - if new_rate_window or in_rate: - if new_rate_window: - self._log_resends_rate_start = now - self._log_resends_rate_count = 0 - - self._to_logfile_with_terminal(u"Got a resend request from the printer: requested line = {}, " - u"current line = {}".format(linenumber, self._current_linenumber)) - self._log_resends_rate_count += 1 - - self._send_queue.resend_active = True - - finally: - if self.flavor.trigger_ok_after_resend == "always": - self._on_comm_ok() - elif self.flavor.trigger_ok_after_resend == "detect": - self._resend_ok_timer = threading.Timer(self.timeouts.get("resendOk", 1.0), self._resend_simulate_ok) - self._resend_ok_timer.start() - - def _resend_simulate_ok(self): - self._resend_ok_timer = None - self._on_comm_ok() - self._logger.info("Firmware didn't send an 'ok' with their resend request. That's a known bug " - "with some firmware variants out there. Simulating an ok to continue...") - - def _on_comm_start(self): - if self.state == ProtocolState.CONNECTING: - self.state = ProtocolState.CONNECTED - - elif self.state in ProtocolState.OPERATIONAL_STATES: - with self.job_put_on_hold(): - idle = self._state == ProtocolState.CONNECTED - if idle: - message = "Printer sent 'start' while already connected. External reset? " \ - "Resetting state to be on the safe side." - self.process_protocol_log(message) - self._logger.warn(message) - - self._on_external_reset() - - else: - message = "Printer sent 'start' while processing a job. External reset? " \ - "Aborting job since printer lost state." - self.process_protocol_log(message) - self._logger.warn(message) - - self._on_external_reset() - self.cancel_processing(log_position=False) - - self.notify_listeners("on_protocol_reset", idle) - - def _on_comm_error(self, line, lower_line, error): - for message in self._error_messages: - handler_method = getattr(self, "_on_{}".format(message), None) - if not handler_method: - continue - - if getattr(self.flavor, message)(line, lower_line, error, self._state, self._protected_flags): - message_args = dict() - - parse_method = getattr(self.flavor, "parse_{}".format(message), None) - if parse_method: - parse_result = parse_method(line, lower_line, error, self._state, self._protected_flags) - if parse_result is None: - break - - message_args.update(parse_result) - - if not handler_method(**message_args): - break - else: - for name, hook in self._error_hooks.items(): - try: - ret = hook(self, error) - except Exception: - self._logger.exception("Error while processing hook {name}:".format(**locals()), - extra=dict(plugin=name)) - else: - if ret: - # some plugin handled this, we'll return - return - - # unknown error message - self.error = line - - if self.firmware_errors != "ignore": - if self.firmware_errors == "disconnect" or self.flavor.error_sdcard(line, lower_line, error, self._state, self._protected_flags): - # disconnect - self._trigger_error(error, "firmware") - - elif self._state in ProtocolState.PROCESSING_STATES: - # cancel the print - self.cancel_processing(error=error) - self._clear_to_send.set() - - else: - message = "--- WARNING! Received an error from the printer's firmware, ignoring that as configured " \ - "but you might want to investigate what happened here! Error: {}".format(error) - self._to_logfile_with_terminal(message, level=logging.WARNING) - self.process_protocol_log(message) - self._clear_to_send.set() - - def _on_error_communication(self, error_type): - self._last_communication_error = error_type - - def _on_comm_busy(self): - self._internal_flags["ok_timeout"] = self._get_timeout("communcation_busy" if self._internal_flags["busy_detected"] else "communication") - - if not self._internal_flags["busy_detected"] and self._capability_support.get(CAPABILITY_BUSY_PROTOCOL, False): - self.process_protocol_log("Printer seems to support the busy protocol, adjusting timeouts and setting busy " - "interval accordingly") - self._internal_flags["busy_detected"] = True - - new_communication_timeout = self.timeouts.get("communication_busy", 2) - self._transport.timeout = new_communication_timeout - busy_interval = max(int(new_communication_timeout) - 1, 1) - - self._logger.info("Printer seems to support the busy protocol, telling it to set the busy " - "interval to our \"communication_busy\" timeout - 1s = {}s".format(busy_interval)) - - self._set_busy_protocol_interval(interval=busy_interval) - - def _on_comm_action_command(self, line, lower_line, action): - if action == "cancel": - self.process_protocol_log("Cancelling on request of the printer...") - self.cancel_processing() - elif action == "pause": - self.process_protocol_log("Pausing on request of the printer...") - self.pause_processing() - elif action == "paused": - self.process_protocol_log("Printer signalled that it paused, switching state...") - self.pause_processing(local_handling=False) - elif action == "resume": - self.process_protocol_log("Resuming on request of the printer...") - self.resume_processing() - elif action == "resumed": - self.process_protocol_log("Printer signalled that it resumed, switching state...") - self.resume_processing(local_handling=False) - elif action == "disconnect": - self.process_protocol_log("Disconnecting on request of the printer...") - # TODO inform printer about forced disconnect - self.disconnect() - else: - for hook in self._action_hooks: - try: - self._action_hooks[hook](self, line, action) - except Exception: - self._logger.exception("Error while calling hook {} with action command {}".format(self._action_hooks[hook], - action)) - continue - - def _on_message_temperature(self, max_tool_num, temperatures, heatup_detected): - if heatup_detected: - self._logger.debug("Externally triggered heatup detected") - self._internal_flags["heating"] = True - self._internal_flags["heatup_start"] = monotonic_time() - - shared_nozzle = self._printer_profile["extruder"]["sharedNozzle"] - current_tool_key = "T{}".format(self._internal_flags["current_tool"]) - - for name, hook in self._temperature_hooks.items(): - try: - temperatures = hook(self, temperatures) - if temperatures is None or not temperatures: - return - except Exception: - self._logger.exception("Error while processing temperatures in {}, skipping".format(name), - extra=dict(plugin=name)) - - if current_tool_key in temperatures: - for x in range(max_tool_num + 1): - tool = "T{}".format(x) - if not tool in temperatures: - if shared_nozzle: - # replicate the current temperature across all tools (see #2077) - actual, target = temperatures[current_tool_key] - else: - continue - else: - actual, target = temperatures[tool] - self._internal_flags["temperatures"].set_tool(x, actual=actual, target=target) - - if "B" in temperatures and self._printer_profile["heatedBed"]: - actual, target = temperatures["B"] - self._internal_flags["temperatures"].set_bed(actual=actual, target=target) - - if "C" in temperatures and (self._capability_support.get(CAPABILITY_CHAMBER_TEMP, False) or self._printer_profile["heatedChamber"]): - actual, target = temperatures["C"] - self._internal_flags["temperatures"].set_chamber(actual=actual, target=target) - - self.notify_listeners("on_protocol_temperature", self, self._internal_flags["temperatures"].as_dict()) - - def _on_message_position(self, position): - self.last_position.valid = True - self.last_position.x = position.get("x") - self.last_position.y = position.get("y") - self.last_position.z = position.get("z") - - t_and_f_trustworthy = self._job is None or not self._job.parallel - - if "e" in position: - self.last_position.e = position.get("e") - else: - # multiple extruder coordinates provided, find current one - self.last_position.e = position.get("e{}".format(self._internal_flags["current_tool"])) if t_and_f_trustworthy else None - - for key in [key for key in position if key.startswith("e") and len(key) > 1]: - setattr(self.last_position, key, position.get(key)) - - self.last_position.t = self._internal_flags["current_tool"] if t_and_f_trustworthy else None - self.last_position.f = self._internal_flags["current_f"] if t_and_f_trustworthy else None - - reason = None - - if self._record_pause_data: - reason = "pause" - self._record_pause_data = False - self.pause_position.copy_from(self.last_position) - self.pause_temperature.copy_from(self._internal_flags["temperatures"]) - self._pause_preparation_done() - - if self._record_cancel_data: - reason = "cancel" - self._record_cancel_data = False - self.cancel_position.copy_from(self.last_position) - self.cancel_temperature.copy_from(self._internal_flags["temperatures"]) - self._cancel_preparation_done() - - self.notify_listeners("on_protocol_position_all_update", self, position, reason=reason) - - def _on_message_firmware_info(self, firmware_name, data): - self._event_bus.fire(Events.FIRMWARE_DATA, dict(name=firmware_name, data=copy.copy(data))) - - if not self._internal_flags["firmware_identified"] and firmware_name: - self._logger.info("Printer reports firmware name \"{}\"".format(firmware_name)) - - for flavor in all_flavors(): - if flavor.identifier and callable(flavor.identifier) and flavor.identifier(firmware_name, data): - self._logger.info("Detected firmware flavor \"{}\", switching...".format(flavor.key)) - self._switch_flavor(flavor) - - self._internal_flags["firmware_identified"] = True - self._internal_flags["firmware_name"] = firmware_name - self._internal_flags["firmware_info"] = data - - # notify plugins - for name, hook in self._firmware_info_hooks.items(): - try: - hook(self, firmware_name, copy.copy(data)) - except Exception: - self._logger.exception("Error processing firmware info hook {}:".format(name), - extra=dict(plugin=name)) - - def _on_message_firmware_capability(self, cap, enabled): - self._internal_flags["firmware_capabilities"][cap] = enabled - - if self._capability_support.get(cap, False): - if cap == CAPABILITY_AUTOREPORT_TEMP and enabled: - self._logger.info("Firmware states that it supports temperature autoreporting") - self._set_autoreport_temperature_interval() - elif cap == CAPABILITY_AUTOREPORT_SD_STATUS and enabled: - self._logger.info("Firmware states that it supports sd status autoreporting") - self._set_autoreport_sdstatus_interval() - elif cap == CAPABILITY_EMERGENCY_PARSER and enabled: - self._logger.info("Firmware states that it supports emergency GCODEs to be sent without waiting for an acknowledgement first") - - # notify plugins - for name, hook in self._firmware_cap_hooks.items(): - try: - hook(self, cap, enabled, copy.copy(self._internal_flags["firmware_capabilities"])) - except Exception: - self._logger.exception("Error processing firmware capability hook {}:".format(name), - extra=dict(plugin=name)) - - def _on_message_sd_init_ok(self): - self._internal_flags["sd_available"] = True - self.list_files() - self.notify_listeners("on_protocol_file_storage_available", self, self._internal_flags["sd_available"]) - - def _on_message_sd_init_fail(self): - self._internal_flags["sd_available"] = False - self.notify_listeners("on_protocol_file_storage_available", self, self._internal_flags["sd_available"]) - - def _on_message_sd_begin_file_list(self): - self._internal_flags["sd_files_temp"] = [] - - def _on_message_sd_end_file_list(self): - self._internal_flags["sd_files"] = self._internal_flags["sd_files_temp"] - self._internal_flags["sd_files_temp"] = None - self.notify_listeners("on_protocol_file_list", self, self._internal_flags["sd_files"]) - - def _on_message_sd_entry(self, name, long_name, size): - self._internal_flags["sd_files_temp"].append((name, long_name, size)) - - def _on_message_sd_file_opened(self, name, long_name, size): - self.notify_listeners("on_protocol_file_print_started", self, name, long_name, size) - - def _on_message_sd_done_printing(self): - self.notify_listeners("on_protocol_file_print_done", self) - - def _on_message_sd_printing_byte(self, current, total): - self.notify_listeners("on_protocol_sd_status", self, current, total) - - def _finish_heatup(self): - if self._internal_flags["heating"]: - if self._internal_flags["heating_start"]: - self._internal_flags["heating_lost"] = self._internal_flags["heating_lost"] + (monotonic_time() - self._internal_flags["heating_start"]) - self._internal_flags["heating_start"] = None - self._internal_flags["heating"] = False - - def _on_external_reset(self): - with self._send_queue.blocked(): - self._clear_to_send.clear(completely=True) - with self._command_queue.blocked(): - self._command_queue.clear() - self._send_queue.clear() - - with self._line_mutex: - self._current_linenumber = 0 - self._last_lines.clear() - - self.flavor = GenericFlavor.with_overrides(self.flavor_overrides) - - self.send_commands(self.flavor.command_hello(), - self.flavor.command_set_line(0)) - - if self._internal_flags["temperature_autoreporting"]: - self._set_autoreport_temperature_interval() - if self._internal_flags["sd_status_autoreporting"]: - self._set_autoreport_sdstatus_interval() - if self._internal_flags["busy_detected"]: - self._set_busy_protocol_interval() - - ##~~ Sending - - def _tickle(self, command): - if self._send_command(command): - if self._clear_to_send.blocked(): - self._commdebug_logger.debug("tickle => clear_to_send.set (counter: {})".format(self._clear_to_send.counter)) - self._clear_to_send.set() - - def _continue_sending(self): - self._commdebug_logger.debug("continue_sending (counter: {}, line number: {})".format(self._clear_to_send.counter, self._current_linenumber)) - while self._active: - job_active = self.state in (ProtocolState.STARTING, ProtocolState.PROCESSING) and not (self._job is None or not self._job.active or isinstance(self._job, SDFilePrintjob)) - - if self._send_from_command_queue(): - # we found something in the command queue to send - return True - - elif self.job_on_hold: - # job is on hold, that means we must not send from either job or job queue - return False - - elif self._send_from_job_queue(): - # we found something in the job queue to send - return True - - elif job_active and self._send_next_from_job(): - # we sent the next line from the file - return True - - elif not job_active: - # nothing sent but also no job active, so we can just return false here - return False - - self._logger.debug("No command sent on ok while printing, doing another iteration") - - def _send_same_from_resend(self): - return self._send_next_from_resend(again=True) - - def _send_next_from_resend(self, again=False): - self._commdebug_logger.debug("send_next_from_resend (counter: {}, line number: {})".format(self._clear_to_send.counter, self._internal_flags.get("resend_linenumber"))) - self._last_communication_error = None - - # Make sure we are only handling one sending job at a time - with self._send_queue_mutex: - if again: - # If we are about to send the last line from the active resend request - # again, we first need to increment resend delta. It might already - # be set to None if the last resend line was already sent, so - # if that's the case we set it to 0. It will then be incremented, - # the last line will be sent again, and then the delta will be - # decremented and set to None again, completing the cycle. - if self._internal_flags["resend_linenumber"] is None: - self._internal_flags["resend_linenumber"] = self._current_linenumber - self._internal_flags["resend_linenumber"] -= 1 - - linenumber = self._internal_flags["resend_linenumber"] - - try: - command = self._last_lines[linenumber] - except KeyError: - # TODO what to do? - return False - - result = self._enqueue_for_sending(to_command(command), linenumber=linenumber, processed=True, resend=True) - - self._internal_flags["resend_linenumber"] += 1 - if self._internal_flags["resend_linenumber"] == self._current_linenumber: - self._internal_flags["resend_requested"] = None - self._internal_flags["resend_linenumber"] = None - self._internal_flags["resend_count"] = 0 - - self._send_queue.resend_active = False - - return result - - def _send_next_from_job(self): - with self._send_queue_mutex: - while self._active: - # we loop until we've actually enqueued a line for sending - if self.state != ProtocolState.PROCESSING: - # we are no longer printing, return False - return False - - elif self.job_on_hold: - # job is on hold, return false - return False - - line = self._job.get_next() - if line is None: - # end of job, return False - return False - - pos = self._job.pos - read_lines = self._job.read_lines - actual_lines = self._job.actual_lines - command = to_command(line, tags={"source:file", - "filepos:{}".format(pos), - "fileline:{}".format(read_lines), - "fileactualline:{}".format(actual_lines)}) - if self._send_command(command): - return True - - self._logger.debug("Command \"{}\" from job not enqueued, doing another iteration".format(line)) - - def _send_from_job_queue(self): - try: - command, on_sent = self._job_queue.get_nowait() - result = self._send_command(command, on_sent=on_sent) - if result: - return True - except queue.Empty: - pass - - return False - - def _send_from_command_queue(self): - # We loop here to make sure that if we do NOT send the first command - # from the queue, we'll send the second (if there is one). We do not - # want to get stuck here by throwing away commands. - while True: - if self._internal_flags["only_from_job"]: - # irrelevant command queue => return - return False - - try: - entry = self._command_queue.get(block=False) - except queue.Empty: - # nothing in command queue - return False - - try: - if isinstance(entry, tuple): - if not len(entry) == 2: - # something with that entry is broken, ignore it and fetch - # the next one - continue - cmd, callback = entry - else: - cmd = entry - callback = None - - if self._send_command(cmd, on_sent=callback): - # we actually did add this cmd to the send queue, so let's - # return, we are done here - return True - finally: - self._command_queue.task_done() - - def _send_commands(self, *commands, **kwargs): - command_type = kwargs.pop("command_type", None) - result = False - for command in commands: - if len(commands) > 1: - command_type = None - result = self._send_command(command, command_type=command_type, **kwargs) or result - return result - - def _send_command(self, command, command_type=None, tags=None, on_sent=None): - with self._send_queue_mutex: - if isinstance(command, QueueMarker): - if isinstance(command, SendQueueMarker): - self._enqueue_for_sending(command) - return True - else: - return False - - elif isinstance(command, Command) and (command_type or tags): - command = command.with_type(command_type).with_tags(tags) - - else: - command = to_command(command, type=command_type, tags=tags) - - if self._internal_flags["trigger_events"]: - results = self._process_command_phase("queuing", command) - - if not results: - # command is no more, return - return False - else: - results = [command] - - # process helper - def process(command, on_sent=None): - if command is None: - # no command, next entry - return False - - # process @ commands - if isinstance(command, AtCommand): - self._process_atcommand_phase("queuing", command) - - # actually enqueue the command for sending - if self._enqueue_for_sending(command, on_sent=on_sent): - if not self._is_streaming(): - # trigger the "queued" phase only if we are not streaming to sd right now - self._process_command_phase("queued", command) - - if self._internal_flags["trigger_events"] and isinstance(command, GcodeCommand) and command.code in GCODE_TO_EVENT: - self._event_bus.fire(GCODE_TO_EVENT[command.code]) - pass - return True - else: - return False - - # split off the final command, because that needs special treatment - if len(results) > 1: - last_command = results[-1] - results = results[:-1] - else: - last_command = results[0] - results = [] - - # track if we enqueued anything at all - enqueued_something = False - - # process all but the last ... - for command in results: - enqueued_something = process(command) or enqueued_something - - # ... and then process the last one with the on_sent callback attached - command = last_command - enqueued_something = process(command, on_sent=on_sent) or enqueued_something - - return enqueued_something - - def _enqueue_for_sending(self, command, linenumber=None, on_sent=None, processed=False, resend=False): - """ - Enqueues a command and optional command_type and linenumber in the send queue. - - Arguments: - command (Command or SendQueueMarker): The command to send or the marker to enqueue - linenumber (int): An optional line number to use for sending the - command. - on_sent (callable or None): Callback to call when the command has been sent - processed (bool): Whether this line has already been processed or not - """ - - try: - target = "send" - if resend: - target = "resend" - - if isinstance(command, Command): - command_type = command.type - else: - command_type = None - - self._send_queue.put((command, linenumber, on_sent, processed), item_type=command_type, target=target) - return True - except TypeAlreadyInQueue as e: - self._logger.debug("Type already in queue: {}".format(e.type)) - return False - - def _send_loop(self): - """ - The send loop is responsible of sending commands in ``self._send_queue`` over the line, if it is cleared for - sending (through received ``ok`` responses from the printer's firmware. - """ - - self._clear_to_send.wait() - - while self._send_queue_active: - try: - # wait until we have something in the queue - try: - entry = self._send_queue.get() - except queue.Empty: - continue - - try: - # make sure we are still active - if not self._send_queue_active: - break - - # sleep if we are dwelling - now = monotonic_time() - if self.flavor.block_while_dwelling and self._internal_flags["dwelling_until"] and now < self._internal_flags["dwelling_until"]: - time.sleep(self._internal_flags["dwelling_until"] - now) - self._internal_flags["dwelling_until"] = False - - # fetch command and optional linenumber from queue - command, linenumber, on_sent, processed = entry - - if isinstance(command, SendQueueMarker): - command.run() - self._continue_sending() - continue - - if linenumber is not None: - # line number predetermined - this only happens for resends, so we'll use the number and - # send directly without any processing (since that already took place on the first sending!) - self._do_send_with_checksum(to_bytes(command.line), linenumber) - - else: - if not processed: - results = self._process_command_phase("sending", command) - - if not results: - # No, we are not going to send this, that was a last-minute bail. - # However, since we already are in the send queue, our _monitor - # loop won't be triggered with the reply from this unsent command - # now, so we try to tickle the processing of any active - # command queues manually - self._commdebug_logger.debug("send_loop => no results") - self._continue_sending() - - # and now let's fetch the next item from the queue - continue - - # we explicitly throw away plugin hook results that try - # to perform command expansion in the sending/sent phase, - # so "results" really should only have more than one entry - # at this point if our core code contains a bug - assert len(results) == 1 - - # we only use the first (and only!) entry here - command = results[0] - - if command.line.strip() == "": - self._logger.info("Refusing to send an empty line to the printer") - - # same here, tickle the queues manually - self._commdebug_logger.debug("send_loop => empty line") - self._continue_sending() - - # and fetch the next item - continue - - # handle @ commands - if isinstance(command, AtCommand): - self._process_command_phase("sending", command) - - # tickle... - self._commdebug_logger.debug("send_loop => at command") - self._continue_sending() - - # ... and fetch the next item - continue - - # now comes the part where we increase line numbers and send stuff - no turning back now - self._do_send(command) - - # trigger "sent" phase and use up one "ok" - if on_sent is not None and callable(on_sent): - # we have a sent callback for this specific command, let's execute it now - on_sent() - self._process_command_phase("sent", command) - - # we only need to use up a clear if the command we just sent was either a gcode command or if we also - # require ack's for unknown commands - use_up_clear = self.flavor.unknown_requires_ack - if isinstance(command, GcodeCommand): - use_up_clear = True - else: - self._commdebug_logger.debug("send_loop => command != instanceof GcodeCommand: {!r}".format(command)) - - if use_up_clear: - # if we need to use up a clear, do that now - self._commdebug_logger.debug("send_loop => clear_to_send.clear: line sent (counter: {}, line number: {})".format(self._clear_to_send.counter, self._current_linenumber)) - self._clear_to_send.clear() - else: - # Otherwise we need to tickle the read queue - there might not be a reply - # to this command, so our _monitor loop will stay waiting until timeout. We - # definitely do not want that, so we tickle the queue manually here - self._commdebug_logger.debug("send_loop => use_up_clear == False") - self._continue_sending() - - finally: - # no matter _how_ we exit this block, we signal that we - # are done processing the last fetched queue entry - self._send_queue.task_done() - - # now we just wait for the next clear and then start again - self._clear_to_send.wait() - except Exception: - self._logger.exception("Caught an exception in the send loop") - self.notify_listeners("on_protocol_log", self, "Closing down send loop") - - def _log_command_phase(self, phase, command): - if self._phase_logger.isEnabledFor(logging.DEBUG): - self._phase_logger.debug("phase: {}, command: {!r}".format(phase, command)) - - def _process_command_phase(self, phase, command, **kwargs): - command = to_command(command, **kwargs) - results = [command] - - self._log_command_phase(phase, command) - - if not self._internal_flags["trigger_events"] or phase not in ("queuing", "queued", "sending", "sent"): - return results - - # send it through the phase specific handlers provided by plugins - for name, hook in self._gcode_hooks[phase].items(): - new_results = [] - for command in results: - try: - hook_results = hook(self, - phase, - str(command), - command.type, - command.code if isinstance(command, GcodeCommand) else None, - subcode=command.subcode if isinstance(command, GcodeCommand) else None, - tags=command.tags) - except Exception: - self._logger.exception("Error while processing hook {name} for phase {phase} and command {command}:".format(**locals())) - else: - normalized = normalize_command_handler_result(command, hook_results, - tags_to_add={"source:rewrite", - "phase:{}".format(phase), - "plugin:{}".format(name)}) - - # make sure we don't allow multi entry results in anything but the queuing phase - if not phase in ("queuing",) and len(normalized) > 1: - self._logger.error("Error while processing hook {name} for phase {phase} and command {command}: Hook returned multi-entry result for phase {phase} and command {command}. That's not supported, if you need to do multi expansion of commands you need to do this in the queuing phase. Ignoring hook result and sending command as-is.".format(**locals())) - new_results.append(command) - else: - new_results += normalized - if not new_results: - # hook handler returned None or empty list for all commands, so we'll stop here and return a full out empty result - return [] - results = new_results - - # if it's a gcode command send it through the specific handler if it exists - new_results = [] - modified = False - for command in results: - if isinstance(command, GcodeCommand): - gcode_handler = "_gcode_" + command.code + "_" + phase - if gcode_handler in self._handlers_gcode: - # noinspection PyCallingNonCallable - handler_results = getattr(self, gcode_handler)(command) - new_results += normalize_command_handler_result(command, handler_results) - modified = True - else: - new_results.append(command) - else: - new_results.append(command) - - if modified: - if not new_results: - # gcode handler returned None or empty list for all commands, so we'll stop here and return a full out empty result - return [] - else: - results = new_results - - # send it through the phase specific command handler if it exists - command_phase_handler = "_command_phase_" + phase - if command_phase_handler in self._handlers_command_phase: - new_results = [] - for command in results: - handler_results = getattr(self, command_phase_handler)(command) - new_results += normalize_command_handler_result(command, handler_results) - results = new_results - - # finally return whatever we resulted on - return results - - def _process_atcommand_phase(self, phase, command): - if (self._is_streaming()) or phase not in ("queuing", "sending"): - return - - # send it through the phase specific handlers provided by plugins - for name, hook in self._atcommand_hooks[phase].items(): - try: - hook(self, phase, command.atcommand, command.parameters, tags=command.tags) - except Exception: - self._logger.exception("Error while processing hook {} for phase {} and command {}:".format(name, phase, command.atcommand)) - - # trigger built-in handler if available - atcommand_handler = "_atcommand_{}_{}".format(command.atcommand, phase) - if atcommand_handler in self._handlers_atcommand: - try: - getattr(self, atcommand_handler)(command) - except Exception: - self._logger.exception("Error in handler for phase {} and command {}".format(phase, command.atcommand)) - - ##~~ actual sending via serial - - def _needs_checksum(self, command): - if not self._transport.message_integrity: - # transport does not have message integrity, let's see if we'll send a checksum - command_requiring_checksum = isinstance(command, GcodeCommand) and command.code in self.flavor.checksum_requiring_commands - command_allowing_checksum = isinstance(command, GcodeCommand) or self.flavor.unknown_with_checksum - return command_requiring_checksum or (command_allowing_checksum and self._checksum_enabled) - - else: - # transport has message integrity, no checksum - return False - - @property - def _checksum_enabled(self): - if not self._transport.message_integrity: - return self.flavor.send_checksum != "never" and (self.state == ProtocolState.PROCESSING # TODO does job need checksum? - or self.flavor.send_checksum == "always" - or not self._internal_flags["firmware_identified"]) - else: - # transport has message integrity, no checksum - return False - - def _emergency_force_send(self, command, message, *args, **kwargs): - """ - Args: - command (Command): the command to send - message (unicode): the message to log - """ - # only jump the queue with our command if the EMERGENCY_PARSER capability is available - if not self._internal_flags["firmware_capability_support"].get(CAPABILITY_EMERGENCY_PARSER, False) \ - or not self._internal_flags["firmware_capabilities"].get(CAPABILITY_EMERGENCY_PARSER, False): - return - - self._logger.info(message) - self._do_send(command) - - # use up an ok since we will get one back for this command and don't want to get out of sync - self._clear_to_send.clear() - - return None, - - def _do_send(self, command): - """ - Args: - command (Command): the command to send - """ - if self._needs_checksum(command): - self._do_increment_and_send_with_checksum(command.bytes) - else: - self._do_send_without_checksum(command.bytes) - - def _do_increment_and_send_with_checksum(self, line): - """ - Args: - line (bytes): the line to send - """ - with self._line_mutex: - line_number = self._current_linenumber - self._add_to_last_lines(to_unicode(line), line_number=line_number) - self._current_linenumber += 1 - self._do_send_with_checksum(line, line_number) - - def _do_send_with_checksum(self, line, line_number): - """ - Args: - line (bytes): the line to send - line_number (int): the line number to send - """ - command_to_send = b"N" + str(line_number).encode("ascii") + b" " + line - checksum = 0 - for c in bytearray(command_to_send): - checksum ^= c - command_to_send = command_to_send + b"*" + str(checksum).encode("ascii") - self._do_send_without_checksum(command_to_send) - - def _do_send_without_checksum(self, data): - """ - Args: - data (bytes): the data to send - """ - self._transport.write(data + b"\n") - - def _add_to_last_lines(self, command, line_number=None): - # type: (str, int) -> None - self._last_lines.append(command, line_number=line_number) - - ##~~ gcode command handlers - - def _gcode_T_sent(self, command): - if command.tool: - self._internal_flags["current_tool"] = int(command.tool) - - def _gcode_G0_sent(self, command): - if command.z is not None and self._internal_flags["current_z"] != command.z: - self._internal_flags["current_z"] = command.z - self.notify_listeners("on_protocol_position_z_update", self, self._internal_flags["current_z"]) - if command.f is not None: - self._internal_flags["current_f"] = command.f - _gcode_G1_sent = _gcode_G0_sent - - def _gcode_G2_sent(self, command): - if command.f is not None: - self._internal_flags["current_f"] = command.f - _gcode_G3_sent = _gcode_G2_sent - _gcode_G28_sent = _gcode_G2_sent - - def _gcode_M140_queuing(self, command): - if not self._printer_profile["heatedBed"]: - self.process_protocol_log("Warn: Not sending \"{}\", printer profile has no heated bed".format(command)) - return None, # Don't send bed commands if we don't have a heated bed - _gcode_M190_queuing = _gcode_M140_queuing - - def _gcode_M155_sending(self, command): - try: - interval = int(command.s) - self._internal_flags["temperature_autoreporting"] = self._internal_flags["firmware_capabilities"].get(CAPABILITY_AUTOREPORT_TEMP, - False) \ - and (interval > 0) - except Exception: - pass - - def _gcode_M27_sending(self, command): - try: - interval = int(command.s) - self._internal_flags["sd_status_autoreporting"] = self._internal_flags["firmware_capabilities"].get(CAPABILITY_AUTOREPORT_SD_STATUS, - False) \ - and (interval > 0) - except Exception: - pass - - def _apply_temperature_offset(self, heater, command, support_r=False): - offset = self._internal_flags["temperature_offsets"].get(heater, 0) - if offset == 0 or not "source:file" in command.tags: - return - - try: - if command.s is not None: - return command.with_args(s=float(command.s) + offset) - elif command.r is not None and support_r: - return command.with_args(r=float(command.r) + offset) - except Exception: - self._logger.exception("Error applying temperature offset") - - def _gcode_M104_sending(self, command, support_r=False): - if command.t: - tool_num = command.t - else: - tool_num = self._internal_flags["current_tool"] - - return self._apply_temperature_offset("tool{}".format(tool_num), command, support_r=support_r) - - def _gcode_M109_sending(self, command): - return self._gcode_M104_sending(command, support_r=True) - - def _gcode_M140_sending(self, command): - return self._apply_temperature_offset("bed", command, support_r=False) - - def _gcode_M190_sending(self, command): - return self._apply_temperature_offset("bed", command, support_r=True) - - def _gcode_M141_sending(self, command): - return self._apply_temperature_offset("chamber", command, support_r=False) - - def _gcode_M191_sending(self, command): - return self._apply_temperature_offset("chamber", command, support_r=True) - - def _gcode_M104_sent(self, command, wait=False, support_r=False): - tool_num = self._internal_flags["current_tool"] - if command.t: - tool_num = command.t - - if wait: - self._internal_flags["former_tool"] = self._internal_flags["current_tool"] - self._internal_flags["current_tool"] = tool_num - - target = None - if command.s is not None: - target = float(command.s) - elif command.r is not None and support_r: - target = float(command.r) - - if target: - self._internal_flags["temperatures"].set_tool(tool_num, target=target) - self.notify_listeners("on_protocol_temperature", self, self._internal_flags["temperatures"].as_dict()) - - def _gcode_M140_sent(self, command, wait=False, support_r=False): - target = None - if command.s is not None: - target = float(command.s) - elif command.r is not None and support_r: - target = float(command.r) - - if target: - self._internal_flags["temperatures"].set_bed(target=target) - self.notify_listeners("on_protocol_temperature", self, self._internal_flags["temperatures"].as_dict()) - - def _gcode_M141_sent(self, command, wait=False, support_r=False): - target = None - if command.s is not None: - target = float(command.s) - elif command.r is not None and support_r: - target = float(command.r) - - if target: - self._internal_flags["temperatures"].set_chamber(target=target) - self.notify_listeners("on_protocol_temperature", self, self._internal_flags["temperatures"].as_dict()) - - def _gcode_M109_sent(self, command): - self._internal_flags["heatup_start"] = monotonic_time() - self._internal_flags["long_running_command"] = True - self._internal_flags["heating"] = True - self._gcode_M104_sent(command, wait=True, support_r=True) - - def _gcode_M190_sent(self, command): - self._internal_flags["heatup_start"] = monotonic_time() - self._internal_flags["long_running_command"] = True - self._internal_flags["heating"] = True - self._gcode_M140_sent(command, wait=True, support_r=True) - - def _gcode_M191_sent(self, command): - self._internal_flags["heatup_start"] = monotonic_time() - self._internal_flags["long_running_command"] = True - self._internal_flags["heating"] = True - self._gcode_M141_sent(command, wait=True, support_r=True) - - def _gcode_M116_sent(self, command): - self._internal_flags["heatup_start"] = monotonic_time() - self._internal_flags["long_running_command"] = True - self._internal_flags["heating"] = True - - def _gcode_M110_sending(self, command): - new_line_number = None - if command.n: - try: - new_line_number = int(command.n) - except Exception: - pass - else: - new_line_number = 0 - - with self._line_mutex: - self._logger.info("M110 detected, setting current line number to {}".format(new_line_number)) - - # send M110 command with new line number - self._current_linenumber = new_line_number - - # after a reset of the line number we have no way to determine what line exactly the printer now wants - self._last_lines.clear() - self._internal_flags["resend_linenumber"] = None - - def _gcode_M112_queuing(self, command): - # emergency stop, jump the queue with the M112 - emergency_stop = self.flavor.command_emergency_stop().bytes - self._do_send_without_checksum(emergency_stop) - self._do_increment_and_send_with_checksum(emergency_stop) - - # No idea if the printer is still listening or if M112 won. Just in case - # we'll now try to also manually make sure all heaters are shut off - better - # safe than sorry. We do this ignoring the queue since at this point it - # is irrelevant whether the printer has sent enough ack's or not, we - # are going to shutdown the connection in a second anyhow. - extruder_count = self._printer_profile["extruder"]["count"] - shared_nozzle = self._printer_profile["extruder"]["sharedNozzle"] - if extruder_count > 1 and not shared_nozzle: - for tool in range(extruder_count): - self._do_increment_and_send_with_checksum(self.flavor.command_set_extruder_temp(0, tool=tool).bytes) - else: - self._do_increment_and_send_with_checksum(self.flavor.command_set_extruder_temp(0).bytes) - - if self._printer_profile["heatedBed"]: - self._do_increment_and_send_with_checksum(self.flavor.command_set_bed_temp(0).bytes) - - # close to reset host state - # TODO needs error handling - """ - self._errorValue = "Closing serial port due to emergency stop M112." - self._log(self._errorValue) - self.close(is_error=True) - """ - - # fire the M112 event since we sent it and we're going to prevent the caller from seeing it - event = GCODE_TO_EVENT.get("M112") - if event is not None: - self._event_bus.fire(event) - - # return None 1-tuple to eat the one that is queuing because we don't want to send it twice - # I hope it got it the first time because as far as I can tell, there is no way to know - return None, - - # TODO - #def _gcode_M114_queued(self, *args, **kwargs): - # self._reset_position_timers() - #_gcode_M114_sent = _gcode_M114_queued - - def _gcode_G4_sent(self, command): - timeout = 0 - if command.p is not None: - try: - timeout = float(command.p) / 1000.0 - except ValueError: - pass - elif command.s is not None: - try: - timeout = float(command.s) - except ValueError: - pass - - self._internal_flags["timeout"] = self._get_timeout("communication_busy" if self._internal_flags["busy_detected"] else "communication") + timeout - self._internal_flags["dwelling_until"] = monotonic_time() + timeout - - ##~~ atcommand handlers - - def _atcommand_pause_queuing(self, command): - tags = command.tags - if tags is None: - tags = set() - if not "script:afterPrintPaused" in tags: - self.pause_processing(tags={"trigger:atcommand_pause"}) - - def _atcommand_cancel_queuing(self, command): - tags = command.tags - if tags is None: - tags = set() - if not "script:afterPrintCancelled" in tags: - self.cancel_processing(tags={"trigger:atcommand_cancel"}) - _atcommand_abort_queuing = _atcommand_cancel_queuing - - def _atcommand_resume_queuing(self, command): - tags = command.tags - if tags is None: - tags = set() - if not "script:beforePrintResumed" in tags: - self.resume_processing(tags={"trigger:atcommand_resume"}) - - ##~~ command phase handlers - - def _command_phase_queuing(self, command): - if isinstance(command, GcodeCommand): - if command.code in self.flavor.emergency_commands and command.code != self.flavor.command_emergency_stop().code: - message = "Force-sending {} to the printer".format(command) - self._logger.info(message) - return self._emergency_force_send(command, message) - - if self.state in ProtocolState.PROCESSING_STATES and command.code in self.flavor.pausing_commands: - self._logger.info("Pausing print job due to command {}".format(command)) - self.pause_processing(tags=command.tags) - - if command.code in self.flavor.blocked_commands: - self._logger.info("Not sending {} to printer, it's configured as a blocked command".format(command)) - return None, - - def _command_phase_sending(self, command, gcode=None): - if gcode is not None and gcode.code in self.flavor.long_running_commands: - self._internal_flags["long_running_command"] = True - - ##~~ autoreporting - - def _set_autoreport_temperature_interval(self, interval=None): - if interval is None: - try: - interval = int(self.interval.get("temperature_autoreport", 2)) - except Exception: - interval = 2 - self.send_commands(self.flavor.command_autoreport_temperature(interval=interval), - tags={"trigger:set_autoreport_temperature_interval"}) - - def _set_autoreport_sdstatus_interval(self, interval=None): - if interval is None: - try: - interval = int(self.interval.get("sd_status_autoreport", 1)) - except Exception: - interval = 1 - self.send_commands(self.flavor.command_autoreport_sd_status(interval=interval), - tags={"trigger:protocol.set_autoreport_sdstatus_interval"}) - - ##~~ busy protocol - - def _set_busy_protocol_interval(self, interval=None): - if interval is None: - try: - interval = max(int(self.timeouts.get("communication_busy", 3)) - 1, 1) - except Exception: - interval = 2 - self.send_commands(self.flavor.command_busy_protocol_interval(interval), - tags={"trigger:protocol.set_busy_protocol_interval"}) - - ##~~ helpers - - def _get_timeout(self, timeout_type): - if timeout_type in self.timeouts: - return monotonic_time() + self.timeouts[timeout_type] - else: - return monotonic_time() - - def _get_max_timeout(self, *offsets): - if len(offsets) == 0: - offsets = (0.0,) - return monotonic_time() + max(offsets) - - def _to_logfile_with_terminal(self, message=None, level=logging.INFO): - log = u"Last lines in terminal:\n" + u"\n".join(map(lambda x: u"| {}".format(x), list(self._terminal_log))) - if message is not None: - log = message + u"\n| " + log - self._logger.log(level, log) - - def _switch_flavor(self, new_flavor): - self.flavor = new_flavor.with_overrides(self.flavor_overrides) - - flavor_comm_attrs = self.get_flavor_attributes_starting_with(self.flavor, "comm_") - flavor_message_attrs = self.get_flavor_attributes_starting_with(self.flavor, "message_") - flavor_error_attrs = self.get_flavor_attributes_starting_with(self.flavor, "error_") - - self._comm_messages = flavor_comm_attrs - self._registered_messages = flavor_comm_attrs + flavor_message_attrs - self._current_registered_messages = self._registered_messages - self._error_messages = flavor_error_attrs - - def _trigger_error(self, text, reason, disconnect=True): - self.state = ProtocolState.ERROR - self._event_bus.fire(Events.ERROR, dict(error=text, reason=reason)) - if disconnect: - self.disconnect(error=True) + def __init__(self, callback): + assert callable(callback) + self.callback = callback + + def __nonzero__(self): + return self.__bool__() + + def __bool__(self): + return bool(self.callback()) + + +class ReprapGcodeProtocol( + Protocol, + Fdm3dPrinterProtocolMixin, + MotorControlProtocolMixin, + FanControlProtocolMixin, + FileStreamingProtocolMixin, + PushingTransportWrapperListener, + TransportListener, +): + name = "Reprap GCODE Protocol" + key = "reprap" + + supported_jobs = [LocalGcodeFilePrintjob, LocalGcodeStreamjob, SDFilePrintjob] + + @classmethod + def get_connection_options(cls): + return [ + GroupChoiceType( + "flavor", + "Firmware Flavor", + sorted( + [Value(f.key, title=f.name) for f in all_flavors()], + key=lambda x: x.title, + ), + ParamGroup( + "flavor_overrides", + "Flavor Overrides", + [ + SmallChoiceType( + "send_checksum", + gettext("Send a checksum with the command"), + [ + Value("printing", title=gettext("When printing")), + Value("always", title=gettext("Always")), + Value("never", title=gettext("Never")), + ], + ), + SmallChoiceType( + "trigger_ok_after_resend", + gettext("Trigger ok after resend"), + [ + Value( + "detect", title=gettext("If detected as necessary") + ), + Value("always", title=gettext("Always")), + Value("never", title=gettext("Never")), + ], + expert=True, + help=gettext( + 'Some Marlin forks lack an acknowledging `ok` with their resend requests. Set this to "Always" or "If detected as necessary" if you run into communication stalls on resend requests.' + ), + ), + BooleanType( + "unknown_requires_ack", + gettext("Unknown commands require `ok`"), + ), + BooleanType( + "unknown_with_checksum", + gettext("Send unknown commands with line number & checksum"), + ), + BooleanType( + "detect_external_heatups", + gettext( + "Try to detect externally triggered blocking heatups" + ), + ), + BooleanType( + "block_while_dwelling", + gettext( + "Block all communication while a dwell command (`G4`) is active" + ), + ), + BooleanType( + "sd_relative_path", + gettext("Select SD files by relative path"), + ), + BooleanType( + "sd_always_available", + gettext("Always assume that the SD card is present"), + ), + BooleanType( + "heatup_abortable", + gettext( + "Allow cancelling blocking heatups if the firmware supports it" + ), + ), + SmallListType( + "blocked_commands", + gettext("Blocked commands"), + help=gettext( + "Use this to specify commands that should never be sent to the printer. Just the G or M code, comma separated. Defaults to `M0` and `M1` since most firmware will block until a button on the controller has been pressed if it receives either of those two commands." + ), + ), + SmallListType( + "checksum_requiring_commands", + gettext("Checksum requiring commands"), + help=gettext(""), + ), + SmallListType( + "long_running_commands", + gettext("Long running commands"), + help=gettext(""), + ), + SmallListType( + "asynchronous_commands", + gettext("Asynchronous commands"), + help=gettext(""), + expert=True, + ), + SmallListType( + "pausing_commands", + gettext("Pausing commands"), + help=gettext(""), + expert=True, + ), + SmallListType( + "emergency_commands", + gettext("Emergency commands"), + help=gettext(""), + expert=True, + ), + ], + help=gettext( + "You can override the firmware flavor default settings here. You usually should *not* need to do that. Only change anything if the defaults don't work for your printer." + ), + advanced=True, + ), + defaults=dict((f.key, f.overridable()) for f in all_flavors()), + default="generic", + ), + ParamGroup( + "error_handling", + gettext("Error handling"), + [ + SmallChoiceType( + "firmware_errors", + gettext("What to do on a firmware error (`Error:` or `!!`)"), + [ + Value( + "disconnect", title=gettext("Disconnect from the printer") + ), + Value( + "cancel", + title=gettext( + "Cancel any ongoing prints but stay connected to the printer" + ), + help=gettext( + "Please note that if you choose this, OctoPrint will still disconnect from the printer in case of *fatal* errors reported by your firmware (e.g. `kill() called`, `fatal:`)" + ), + ), + Value( + "ignore", + title=gettext("Ignore"), + warning=True, + help=gettext( + "Only choose this if your firmware sends error messages that are not actual errors. Might mask printer issues (even fatal errors!), be careful!" + ), + ), + ], + default="disconnect", + ), + # TODO: implement send_m112 flag + BooleanType( + "send_m112", + gettext("Send `M112` on disconnect due to error"), + default=True, + warning=False, + help=gettext( + "If this is checked, OctoPrint will try to send an `M112` prior to a disconnect due to a (fatal) error in order to disable heaters and motors." + ), + ), + ], + advanced=True, + ), + ParamGroup( + "pausing", + gettext("Pausing"), + [ + BooleanType( + "log_position_on_pause", + gettext("Log position on pause"), + default=True, + warning=True, + help=gettext( + "If you disable this, the `pause_position` placeholders in your pause/resume GCODE scripts will stay unpopulated! However, pausing speed might improve slightly." + ), + ) + ], + advanced=True, + ), + ParamGroup( + "cancelling", + gettext("Cancelling"), + [ + BooleanType( + "log_position_on_cancel", + gettext("Log position on cancel"), + default=True, + warning=True, + help=gettext( + "If you disable this, the `cancel_position` placeholders in your cancel GCODE script and the corresponding data in the print recovery data will stay unpopulated! However, cancelling speed might improve slightly." + ), + ) + ], + advanced=True, + ), + ParamGroup( + "intervals", + gettext("Query intervals"), + [ + FloatType( + "temperature_interval_idle", + gettext("Temperature (idle)"), + default=5, + unit="sec", + help=gettext("When printing or idle"), + ), + FloatType( + "temperature_interval_target", + gettext("Temperature (target set)"), + default=2, + unit="sec", + help=gettext("When idle and a target temperature is set"), + ), + FloatType( + "temperature_interval_auto", + gettext("Temperature (autoreport)"), + default=2, + unit="sec", + help=gettext("Autoreport interval to request from the firmware"), + ), + FloatType( + "sdstatus_interval_normal", + gettext("SD Status"), + default=1, + unit="sec", + help=gettext("When printing from the printer's SD"), + ), + FloatType( + "sdstatus_interval_auto", + gettext("SD status (autoreport)"), + default=1, + unit="sec", + help=gettext("Autoreport interval to request from the firmware"), + ), + ], + advanced=True, + ), + ParamGroup( + "timeouts", + gettext("Timeouts"), + [ + FloatType( + "communication_timeout_normal", + gettext("Communication"), + default=30, + unit="sec", + help=gettext("`busy` protocol support not detected"), + ), + FloatType( + "communication_timeout_busy", + gettext("Communication (busy)"), + default=3, + unit="sec", + help=gettext("`busy` protocol support detected"), + ), + FloatType( + "connection_timeout", + gettext("Connection timeout"), + default=10, + unit="sec", + ), + FloatType( + "detection_timeout", + gettext("Autodetection"), + default=1, + unit="sec", + help="", + ), + FloatType( + "position_log_wait", + gettext("Position query"), + default=10, + unit="sec", + ), + FloatType( + "baudrate_detection_pause", + gettext("Initial baudrate detection pause"), + expert=True, + default=1.0, + unit="sec", + help=gettext( + "Some controllers need a bit of a breather before baudrate detection after initial connect. If baudrate detection fails due to a hanging controller, try increasing this value." + ), + ), + FloatType( + "resendok_timeout", + gettext("Timeout for `ok` after resend detection"), + expert=True, + default=0.5, + unit="sec", + help=gettext( + "Some firmwares do not send an `ok` after a resend request. This timeout configures how long OctoPrint will wait for one until it assumes this particular bug to be present and generate its own." + ), + ), + IntegerType( + "max_consecutive_timeouts_idle", + gettext("Max. consecutive timeouts while idle"), + expert=True, + default=2, + help=gettext( + "Set to 0 to disable consecutive timeout detection and handling." + ), + ), + IntegerType( + "max_consecutive_timeouts_printing", + gettext("Max. consecutive timeouts while printing"), + expert=True, + default=5, + help=gettext( + "Set to 0 to disable consecutive timeout detection and handling." + ), + ), + IntegerType( + "max_consecutive_timeouts_long", + gettext("Max. consecutive timeouts during long running commands"), + expert=True, + default=5, + help=gettext( + "Set to 0 to disable consecutive timeout detection and handling." + ), + ), + ], + advanced=True, + ), + ParamGroup( + "capabilities", + gettext("Firmware capability support"), + [ + BooleanType( + "autoreport_temp", + gettext("Enable temperature autoreporting if supported"), + default=True, + help=gettext( + "Uncheck this if you want to disable temperature autoreporting, even if the firmware supports it" + ), + ), + BooleanType( + "autoreport_sd_status", + gettext("Enable sd status autoreporting if supported"), + default=True, + help=gettext( + "Uncheck this if you want to disable sd status autoreporting, even if the firmware supports it" + ), + ), + BooleanType( + "emergency_parser", + gettext("Use emergency parser if supported"), + default=True, + help=gettext( + "Uncheck this if you want to disable force-sending emergency commands to compatible printers, even if the firmware supports it" + ), + ), + BooleanType( + "busy_protocol", + gettext("Use `busy` protocol if supported"), + default=True, + help=gettext( + "Uncheck this if you want to disable use of the `busy` protocol, even if the firmware supports it" + ), + ), + BooleanType( + "chamber_temp", + gettext("Enable chamber temperature management if supported"), + default=True, + help=gettext( + "Uncheck this if you want to disable chamber temperature management, even if the firmware supports it" + ), + ), + ], + advanced=True, + ), + ] + + @staticmethod + def get_flavor_attributes_starting_with(flavor, prefix): + return [x for x in dir(flavor) if x.startswith(prefix)] + + @classmethod + def get_attributes_starting_with(cls, prefix): + return dict((x, getattr(cls, x)) for x in dir(cls) if x.startswith(prefix)) + + def __init__(self, flavor=None, *args, **kwargs): + super(ReprapGcodeProtocol, self).__init__(*args, **kwargs) + + self.flavor = lookup_flavor(flavor) + if self.flavor is None: + self.flavor = GenericFlavor + + self.flavor_overrides = kwargs.get("flavor_overrides", {}) + self.flavor = self.flavor.with_overrides(self.flavor_overrides) + + self.set_current_args( + flavor=self.flavor.key, flavor_overrides=self.flavor_overrides + ) + + self._logger = logging.getLogger(__name__) + self._commdebug_logger = logging.getLogger("COMMDEBUG") + self._phase_logger = logging.getLogger(__name__ + ".command_phases") + + self._terminal_log = collections.deque([], 20) + + self.timeouts = { + "connection": kwargs.get("timeouts", {}).get("connection_timeout", 30.0), + "communication": kwargs.get("timeouts", {}).get( + "communication_timeout_normal", 10.0 + ), + "communication_busy": kwargs.get("timeouts", {}).get( + "communication_timeout_busy", 2.0 + ), + } + self.interval = { + "temperature_idle": kwargs.get("intervals", {}).get( + "temperature_interval_idle", 5.0 + ), + "temperature_printing": kwargs.get("intervals", {}).get( + "temperature_interval_printing", 5.0 + ), + "temperature_autoreport": kwargs.get("intervals", {}).get( + "temperature_interval_autoreport", 2.0 + ), + "sd_status": kwargs.get("intervals", {}).get( + "sd_status_interval_normal", 2.0 + ), + "sd_status_autoreport": kwargs.get("intervals", {}).get( + "sd_status_interval_auto", 1.0 + ), + } + self.max_consecutive_timeouts = { + "idle": kwargs.get("timeouts", {}).get("max_consecutive_idle", 2), + "printing": kwargs.get("timeouts", {}).get("max_consecutive_printing", 5), + "long": kwargs.get("timeouts", {}).get("max_consecutive_long", 5), + } + + self.firmware_errors = kwargs.get("error_handling", {}).get( + "firmware_errors", "disconnect" + ) + + flavor_comm_attrs = self.get_flavor_attributes_starting_with(self.flavor, "comm_") + flavor_message_attrs = self.get_flavor_attributes_starting_with( + self.flavor, "message_" + ) + flavor_error_attrs = self.get_flavor_attributes_starting_with( + self.flavor, "error_" + ) + + self._comm_messages = flavor_comm_attrs + self._registered_messages = flavor_comm_attrs + flavor_message_attrs + self._current_registered_messages = self._registered_messages + self._error_messages = flavor_error_attrs + + self._handlers_gcode = self.get_attributes_starting_with("_gcode_") + self._handlers_atcommand = self.get_attributes_starting_with("_atcommand_") + self._handlers_command_phase = self.get_attributes_starting_with( + "_command_phase_" + ) + + self._capability_support = {} + self._capability_support[CAPABILITY_AUTOREPORT_TEMP] = kwargs.get( + "capabilities", {} + ).get("autoreport_temp", True) + self._capability_support[CAPABILITY_AUTOREPORT_SD_STATUS] = kwargs.get( + "capabilities", {} + ).get("autoreport_sd_status", True) + self._capability_support[CAPABILITY_EMERGENCY_PARSER] = kwargs.get( + "capabilities", {} + ).get("emergency_parser", True) + self._capability_support[CAPABILITY_BUSY_PROTOCOL] = kwargs.get( + "capabilities", {} + ).get("busy_protocol", True) + self._capability_support[CAPABILITY_CHAMBER_TEMP] = kwargs.get( + "capabilities", {} + ).get("chamber_temp", True) + + self._transport = None + + self._internal_flags = { + "temperatures": TemperatureRecord(), + "heating_start": None, + "heating_lost": 0, + "heating": False, + "temperature_autoreporting": False, + "temperature_offsets": {}, + "current_tool": 0, + "former_tool": 0, + "current_f": None, + "current_z": None, + "sd_available": False, + "sd_files": [], + "sd_files_temp": None, + "sd_status_autoreporting": False, + "resend_requested": None, + "resend_linenumber": None, + "resend_count": None, + "long_running_command": False, + "only_from_job": BooleanCallbackValue( + lambda: self.state in ProtocolState.PROCESSING_STATES + and self._job + and self._job.exclusive + ), + "trigger_events": BooleanCallbackValue( + lambda: not ( + self.state in ProtocolState.PROCESSING_STATES + and self._job + and self._job.exclusive + ) + ), + "expect_continous_comms": BooleanCallbackValue( + lambda: self.state in ProtocolState.PROCESSING_STATES + and self._job + and not self._job.parallel + ), + "ignore_ok": 0, + "job_on_hold": BooleanCallbackValue(lambda: self.job_on_hold), + "timeout": None, + "timeout_consecutive": 0, + "ok_timeout": None, + "dwelling_until": None, + "firmware_identified": False, + "firmware_name": None, + "firmware_info": {}, + "firmware_capabilities": {}, + "firmware_capability_support": {}, + "busy_detected": False, + "multiline_error": False, + } + self._protected_flags = protectedkeydict(self._internal_flags) + + self._job_queue = JobQueue() + self._command_queue = CommandQueue() + self._send_queue = SendQueue() + self._clear_to_send = SendToken(max=10, name="protocol.clear_to_send") + + self._current_linenumber = 1 + self._last_lines = LineHistory(max=50) + self._last_communication_error = None + + # last known temperatures + self.pause_temperature = TemperatureRecord() + self.cancel_temperature = TemperatureRecord() + + # last known positions + self.last_position = PositionRecord() + self.pause_position = PositionRecord() + self.cancel_position = PositionRecord() + + # pause and cancel processing + self._record_pause_data = False + self._record_cancel_data = False + + # hooks + self._gcode_hooks = { + "queuing": self._plugin_manager.get_hooks( + "octoprint.comm.protocol.gcode.queuing" + ), + "queued": self._plugin_manager.get_hooks( + "octoprint.comm.protocol.gcode.queued" + ), + "sending": self._plugin_manager.get_hooks( + "octoprint.comm.protocol.gcode.sending" + ), + "sent": self._plugin_manager.get_hooks("octoprint.comm.protocol.gcode.sent"), + "receiving": self._plugin_manager.get_hooks( + "octoprint.comm.protocol.gcode.receiving" + ), + } + + self._error_hooks = self._plugin_manager.get_hooks( + "octoprint.comm.protocol.gcode.error" + ) + + self._atcommand_hooks = ( + { + "queuing": self._plugin_manager.get_hooks( + "octoprint.comm.protocol.atcommand.queuing" + ), + "sending": self._plugin_manager.get_hooks( + "octoprint.comm.protocol.atcommand.sending" + ), + }, + ) + + self._action_hooks = self._plugin_manager.get_hooks( + "octoprint.comm.protocol.action" + ) + + self._script_hooks = self._plugin_manager.get_hooks( + "octoprint.comm.protocol.scripts" + ) + + self._temperature_hooks = self._plugin_manager.get_hooks( + "octoprint.comm.protocol.temperatures.received" + ) + + self._firmware_info_hooks = self._plugin_manager.get_hooks( + "octoprint.comm.firmware.info" + ) + + self._firmware_cap_hooks = self._plugin_manager.get_hooks( + "octoprint.comm.firmware.capabilities" + ) + + # polling + self._temperature_poller = None + self._sd_status_poller = None + + # script processing + self._suppress_scripts = set() + + # user logging + self._action_users = {} + + # resend logging + self._log_resends = True + self._log_resends_rate_start = None + self._log_resends_rate_count = 0 + self._log_resends_rate_frame = 60 + self._log_resends_max = 5 + + # mutexes + self._line_mutex = threading.RLock() + self._send_queue_mutex = threading.RLock() + self._pause_mutex = threading.RLock() + self._cancel_mutex = threading.RLock() + self._suppress_scripts_mutex = threading.RLock() + self._action_users_mutex = threading.RLock() + + # timers + self._pause_position_timer = None + self._cancel_position_timer = None + self._resend_ok_timer = None + + # sending thread + self._send_queue_active = False + self._sending_thread = None + + @property + def _active(self): + return ( + self._transport is not None + and self._transport.active + and self._send_queue_active + ) + + def connect(self, transport, transport_args=None, transport_kwargs=None): + if not isinstance(transport, Transport): + raise ValueError( + "transport must be a Transport subclass but is a {} instead".format( + type(transport) + ) + ) + + self._internal_flags["timeout"] = self._get_timeout("connection") + + transport = PushingTransportWrapper( + LineAwareTransportWrapper(transport), timeout=5.0 + ) + + self._send_queue_active = True + self._sending_thread = threading.Thread( + target=self._send_loop, name="comm.sending_thread" + ) + self._sending_thread.daemon = True + self._sending_thread.start() + + super(ReprapGcodeProtocol, self).connect( + transport, transport_args=transport_args, transport_kwargs=transport_kwargs + ) + + # cancel handling + + def _cancel_preparation_failed(self): + self.process_protocol_log( + "Did not receive parseable position data from printer within {}s, " + "continuing without it".format(self.timeouts.get("position_log_wait", 10.0)) + ) + self._cancel_preparation_done() + + def _cancel_preparation_done( + self, check_timer=True, suppress_script=False, user=None + ): + if user is None: + with self._action_users_mutex: + try: + user = self._action_users.pop("cancel") + except KeyError: + pass + + with self._cancel_mutex: + if self._cancel_position_timer is not None: + self._cancel_position_timer.cancel() + self._cancel_position_timer = None + elif check_timer: + return + + # TODO: recovery data + self.notify_listeners( + "on_protocol_job_cancelled", + self, + self._job, + position=self.cancel_position.as_dict(), + suppress_script=suppress_script, + user=user, + ) + + def finalize(): + self.state = ProtocolState.CONNECTED + + self.send_commands(SendQueueMarker(finalize), part_of_job=True) + self._continue_sending() + + def cancel_processing(self, error=None, user=None, tags=None, log_position=True): + if self.state not in ProtocolState.PROCESSING_STATES + (ProtocolState.PAUSED,): + return + + if self._job is None: + return + + if tags is None: + tags = set() + + def on_move_finish_requested(): + self._record_cancel_data = True + + with self._cancel_mutex: + if self._cancel_position_timer is not None: + self._cancel_position_timer.cancel() + self._cancel_position_timer = ResettableTimer( + self.timeouts.get("position_log_wait", 10.0), + self._cancel_preparation_failed, + ) + self._cancel_position_timer.start() + + self.send_commands( + self.flavor.command_get_position(), + part_of_job=True, + tags=tags | {"trigger:comm.cancel", "trigger:record_position"}, + ) + self._continue_sending() + + # cancel the job + self.state = ProtocolState.CANCELLING + + if self.flavor.heatup_abortable: + self.send_commands( + self.flavor.command_abort_heatup(), + part_of_job=True, + tags=tags | {"trigger:comm.cancel", "trigger:abort_heatup"}, + ) + + self._job.cancel(error=error, user=user, tags=tags) + self.notify_listeners( + "on_protocol_job_cancelling", + self, + self._job, + error=error, + user=user, + tags=tags, + ) + + if log_position and not isinstance(self._job, CopyJobMixin): + with self._action_users_mutex: + self._action_users["cancel"] = user + + self.send_commands( + self.flavor.command_finish_moving(), + part_of_job=True, + on_sent=on_move_finish_requested, + tags=tags | {"trigger:comm.cancel", "trigger:record_position"}, + ) + self._continue_sending() + else: + self._cancel_preparation_done(check_timer=False, user=user) + + # pause handling + + def _pause_preparation_failed(self): + self.process_protocol_log( + "Did not receive parseable position data from printer within {}s, " + "continuing without it".format(self.timeouts.get("position_log_wait", 10.0)) + ) + self._pause_preparation_done() + + def _pause_preparation_done(self, check_timer=True, suppress_script=False, user=None): + if user is None: + with self._action_users_mutex: + try: + user = self._action_users.pop("pause") + except KeyError: + pass + + # do we need to stop a timer? + with self._pause_mutex: + if self._pause_position_timer is not None: + self._pause_position_timer.cancel() + self._pause_position_timer = None + elif check_timer: + return + + self.notify_listeners( + "on_protocol_job_paused", + self, + self._job, + position=self.pause_position.as_dict(), + suppress_script=suppress_script, + user=user, + ) + + # wait for current commands to be sent, then switch to paused state + def finalize(): + # only switch to PAUSED if we were still PAUSING, to avoid "swallowing" received resumes during + # pausing + if self.state == ProtocolState.PAUSING: + self.state = ProtocolState.PAUSED + + self.send_commands(SendQueueMarker(finalize), part_of_job=True) + self._continue_sending() + + def pause_processing( + self, user=None, tags=None, log_position=True, local_handling=True + ): + if self._job is None or self.state not in ( + ProtocolState.PROCESSING, + ProtocolState.STARTING, + ProtocolState.RESUMING, + ): + return + + if isinstance(self._job, CopyJobMixin): + return + + if tags is None: + tags = set() + + self.state = ProtocolState.PAUSING + self._job.pause(local_handling=local_handling, user=user, tags=tags) + self.notify_listeners( + "on_protocol_job_pausing", + self, + self._job, + local_handling=local_handling, + user=user, + tags=tags, + ) + + def on_move_finish_requested(): + self._record_pause_data = True + + with self._pause_mutex: + if self._pause_position_timer is not None: + self._pause_position_timer.cancel() + self._pause_position_timer = None + self._pause_position_timer = ResettableTimer( + self.timeouts.get("position_log_wait", 10.0), + self._pause_preparation_failed, + ) + self._pause_position_timer.start() + + self.send_commands( + self.flavor.command_get_position(), + part_of_job=True, + tags=tags + | {"trigger:comm.set_pause", "trigger:pause", "trigger:record_position"}, + ) + self._continue_sending() + + if log_position and local_handling: + with self._action_users_mutex: + self._action_users["pause"] = user + + self.send_commands( + self.flavor.command_finish_moving(), + part_of_job=True, + on_sent=on_move_finish_requested, + tags=tags + | {"trigger:comm.set_pause", "trigger:pause", "trigger:record_position"}, + ) + self._continue_sending() + else: + self._pause_preparation_done( + check_timer=False, suppress_script=not local_handling, user=user + ) + + def move( + self, + x=None, + y=None, + z=None, + e=None, + feedrate=None, + relative=False, + *args, + **kwargs + ): + tags = kwargs.pop("tags", set()) | {"trigger:protocol.move"} + + cmds = [self.flavor.command_move(x=x, y=y, z=z, e=e, f=feedrate)] + + if relative: + cmds = ( + [self.flavor.command_set_relative_positioning()] + + cmds + + [self.flavor.command_set_absolute_positioning()] + ) + + self.send_commands(*cmds, tags=tags, **kwargs) + + def home(self, x=False, y=False, z=False, *args, **kwargs): + tags = kwargs.pop("tags", set()) | {"trigger:protocol.home"} + self.send_commands(self.flavor.command_home(x=x, y=y, z=z), tags=tags, **kwargs) + + def change_tool(self, tool, *args, **kwargs): + tags = kwargs.pop("tags", set()) | {"trigger:protocol.change_tool"} + self.send_commands(self.flavor.command_set_tool(tool), tags=tags, **kwargs) + + def set_feedrate_multiplier(self, multiplier, *args, **kwargs): + tags = kwargs.pop("tags", set()) | {"trigger:protocol.set_feedrate_multiplier"} + self.send_commands( + self.flavor.command_set_feedrate_multiplier(multiplier), tags=tags, **kwargs + ) + + def set_extrusion_multiplier(self, multiplier, *args, **kwargs): + tags = kwargs.pop("tags", set()) | {"trigger:protocol.set_extrusion_multiplier"} + self.send_commands( + self.flavor.command_set_extrusion_multiplier(multiplier), tags=tags, **kwargs + ) + + def set_temperature(self, heater, temperature, wait=False, *args, **kwargs): + tags = kwargs.pop("tags", set()) | {"trigger:protocol.set_temperature"} + + if heater.startswith("tool"): + try: + tool = int(heater[len("tool") :]) + except ValueError: + self._logger.error( + "Got invalid tool heater, expected tool, got: {}".format(heater) + ) + return + command = self.flavor.command_set_extruder_temp( + temperature, tool=tool, wait=wait + ) + elif heater == "bed": + command = self.flavor.command_set_bed_temp(temperature, wait=wait) + elif heater == "chamber": + command = self.flavor.command_set_chamber_temp(temperature, wait=wait) + else: + self._logger.warn( + "Got unknown heater identifier to set temperature on: {}".format(heater) + ) + return + + self.send_commands(command, tags=tags, **kwargs) + + def set_temperature_offset(self, heater, offset, *args, **kwargs): + self._internal_flags["temperature_offsets"][heater] = offset + + def get_temperature_offsets(self): + return copy.copy(self._internal_flags["temperature_offsets"]) + + ##~~ MotorControlProtocolMixin + + def set_motor_state(self, enabled, *args, **kwargs): + tags = kwargs.pop("tags", set()) | {"trigger:protocol.set_motor_state"} + self.send_commands(self.flavor.command_set_motors(enabled), tags=tags, **kwargs) + + ##~~ FanControlProtocolMixin + + def set_fan_speed(self, speed, *args, **kwargs): + tags = kwargs.pop("tags", set()) | {"trigger:protocol.set_fan_speed"} + self.send_commands(self.flavor.command_set_fan_speed(speed), tags=tags, **kwargs) + + ##~~ FileStreamingProtocolMixin + + def init_file_storage(self, *args, **kwargs): + tags = kwargs.pop("tags", set()) | {"trigger:protocol.init_file_storage"} + self.send_commands(self.flavor.command_sd_init(), tags=tags, **kwargs) + + def list_files(self, *args, **kwargs): + tags = kwargs.pop("tags", set()) | {"trigger:protocol.list_files"} + self.send_commands(self.flavor.command_sd_refresh(), tags=tags, **kwargs) + + def start_file_print(self, name, position=0, *args, **kwargs): + tags = kwargs.pop("tags", set()) | {"trigger:protocol.start_file_print"} + + self.send_commands( + self.flavor.command_sd_select_file(name), + self.flavor.command_sd_set_pos(position), + self.flavor.command_sd_start(), + tags=tags, + **kwargs + ) + + def pause_file_print(self, *args, **kwargs): + if kwargs.get("local_handling", True): + tags = kwargs.pop("tags", set()) | {"trigger:protocol.pause_file_print"} + self.send_commands(self.flavor.command_sd_pause(), tags=tags, **kwargs) + + def resume_file_print(self, *args, **kwargs): + if kwargs.get("local_handling", True): + tags = kwargs.pop("tags", set()) | {"trigger:protocol.resume_file_print"} + self.send_commands(self.flavor.command_sd_resume(), tags=tags, **kwargs) + + def delete_file(self, name, *args, **kwargs): + tags = kwargs.pop("tags", set()) | {"trigger:protocol.delete_file"} + self.send_commands(self.flavor.command_sd_delete(name), tags=tags, **kwargs) + + def record_file(self, name, *args, **kwargs): + tags = kwargs.pop("tags", set()) | {"trigger:protocol.record_file"} + self.send_commands(self.flavor.command_sd_begin_write(name), tags=tags, **kwargs) + + def stop_recording_file(self, *args, **kwargs): + tags = kwargs.pop("tags", set()) | {"trigger:protocol.stop_recording_file"} + self.send_commands(self.flavor.command_sd_end_write(), tags=tags, **kwargs) + + def get_file_print_status(self, *args, **kwargs): + tags = kwargs.pop("tags", set()) | {"trigger:protocol.get_file_print_status"} + self.send_commands(self.flavor.command_sd_status(), tags=tags, **kwargs) + + def start_file_print_status_monitor(self): + if self._internal_flags["sd_status_autoreporting"]: + return + + from octoprint.util import RepeatedTimer + + def poll_status(): + if self.can_send() and not self._internal_flags["sd_status_autoreporting"]: + self.get_file_print_status() + + self._sd_status_poller = RepeatedTimer(self.interval["sd_status"], poll_status) + self._sd_status_poller.start() + + def stop_file_print_status_monitor(self): + if self._sd_status_poller is not None: + self._sd_status_poller.cancel() + self._sd_status_poller = None + + ##~~ + + def can_send(self): + return ( + self._is_operational() + and not self._internal_flags["long_running_command"] + and not self._internal_flags["heating"] + and not self._internal_flags["dwelling_until"] + ) + + def send_commands(self, *commands, **kwargs): + command_type = kwargs.get("command_type") + on_sent = kwargs.get("on_sent") + tags = kwargs.get("tags") + force = kwargs.get("force", False) + part_of_job = kwargs.get("part_of_job", False) + + def sanitize_command(c, ct, t): + if isinstance(c, tuple): + # unwrap 2-tuples that consist of a command & additional tags + if len(c) != 2: + return None + c, at = c + + assert isinstance(at, set) + t |= at + + # noinspection PyCompatibility + if isinstance(c, Command): + return c.with_type(ct).with_tags(t) + elif isinstance(c, QueueMarker): + return c + elif isinstance(c, str): + return to_command(c, type=ct, tags=t) + else: + return None + + result = False + for command in commands: + sanitized = sanitize_command(command, command_type, tags) + if sanitized is None: + continue + + emergency = False + if ( + isinstance(sanitized, GcodeCommand) + and sanitized.code in self.flavor.emergency_commands + ): + emergency = True + + if part_of_job: + if isinstance(sanitized, Command): + sanitized = sanitized.with_tags({"source:job"}) + self._job_queue.put((sanitized, on_sent)) + result = True + + elif ( + self.state in ProtocolState.PROCESSING_STATES + and not self._job.parallel + and not self.job_on_hold + and not force + ): + try: + self._command_queue.put((sanitized, on_sent), item_type=command_type) + result = True + except TypeAlreadyInQueue as e: + self._logger.debug("Type already in queue: " + e.type) + + elif self._is_operational() or force or emergency: + result = ( + self._send_commands( + command, on_sent=on_sent, command_type=command_type, tags=tags + ) + or result + ) + + return result + + def send_script(self, script, context=None, *args, **kwargs): + part_of_job = kwargs.get("part_of_job", False) + + if context is None: + context = {} + + # noinspection PyCompatibility + if isinstance(script, str): + script = GcodeScript(self._settings, script, context=context) + + if not isinstance(script, GcodeScript): + raise InvalidScript("Can't process this script") + + context.update( + { + "printer_profile": self._printer_profile, + "last_position": self.last_position, + "last_temperature": self._internal_flags["temperatures"].as_script_dict(), + } + ) + + if script.name == "afterPrintPaused" or script.name == "beforePrintResumed": + context.update( + { + "pause_position": self.pause_position, + "pause_temperature": self.pause_temperature.as_script_dict(), + } + ) + elif script.name == "afterPrintCancelled": + context.update( + { + "cancel_position": self.cancel_position, + "cancel_temperature": self.cancel_temperature.as_script_dict(), + } + ) + + lines = script.render(context=context) + + # process any hooks + prefix = [] + postfix = [] + + for name, hook in self._script_hooks.items(): + try: + retval = hook( + self, "gcode", script.name + ) # prefix, postfix [ , variables [ , additional tags ] ] + except Exception: + self._logger.exception( + "Error while processing hook {}.".format(name), + extra={"plugin": name}, + ) + else: + if retval is None: + continue + if not isinstance(retval, (list, tuple)) or len(retval) not in [2, 3, 4]: + continue + + def to_list(data, t): + # noinspection PyCompatibility + if isinstance(data, str): + data = list(x.strip() for x in data.split("\n")) + + if isinstance(data, (list, tuple)): + return list(map(lambda x: (x, t), data)) + else: + return None + + if len(retval) >= 3: + # variables are defined + variables = retval[2] + context.update({"plugins": {name: variables}}) + + additional_tags = {"plugin:{}".format(name)} + if len(retval) == 4: + # additional tags are defined + additional_tags |= set(retval[3]) + + p, s = map( + lambda x: to_list(x, additional_tags), retval[0:2] + ) # convert prefix & postfix + if p: + prefix = list(p) + prefix + if s: + postfix += list(s) + + lines = prefix + lines + postfix + self.send_commands( + tags={ + "trigger:protocol.send_script", + "source:script", + "script:{}".format(script.name), + }, + part_of_job=part_of_job, + *lines + ) + + def repair(self, *args, **kwargs): + self._on_comm_ok() + + def join(self, timeout=None): + if timeout is not None: + stop = monotonic_time() + timeout + while ( + self._command_queue.unfinished_tasks or self._send_queue.unfinished_tasks + ) and monotonic_time() < stop: + time.sleep(0.1) + else: + self._command_queue.join() + self._send_queue.join() + + ##~~ State handling + + def _is_operational(self): + return self.state not in ( + ProtocolState.DISCONNECTED, + ProtocolState.DISCONNECTED_WITH_ERROR, + ) + + def _is_busy(self): + return self.state in (ProtocolState.PROCESSING, ProtocolState.PAUSED) + + def _is_streaming(self): + return ( + self._is_busy() and self._job and isinstance(self._job, LocalGcodeStreamjob) + ) + + def _on_switching_state_connecting(self, old_state): + if old_state is not ProtocolState.DISCONNECTED: + return + + hello = self.flavor.command_hello() + if hello: + self._tickle(hello) + + def _on_switching_state_connected(self, old_state): + if old_state == ProtocolState.CONNECTING: + self._internal_flags["timeout"] = self._get_timeout("communication") + + self._send_command(self.flavor.command_set_line(0)) + self._send_command(self.flavor.command_get_firmware_info()) + self._clear_to_send.set() + + def poll_temperature_interval(): + printing_default = 4.0 + target_default = 2.0 + threshold = 25 + + if self.state in ProtocolState.PROCESSING_STATES: + return self.interval.get("temperature_printing", printing_default) + + tools = self._internal_flags["temperatures"].tools + for temp in [tools[k][1] for k in tools]: + if temp > threshold: + return self.interval.get("temperature_target_set", target_default) + + bed = self._internal_flags["temperatures"].bed + if bed and len(bed) > 0 and bed[1] is not None and bed[1] > threshold: + return self.interval.get("temperature_target_set", target_default) + + return self.interval.get("temperature_idle") + + def poll_temperature(): + if ( + self._is_operational() + and not self._internal_flags["temperature_autoreporting"] + and not self._internal_flags["only_from_job"] + and self.can_send() + ): + self._send_command( + self.flavor.command_get_temp(), + command_type="temperature_poll", + tags={"trigger:protocol.poll_temperature"}, + ) + + from octoprint.util import RepeatedTimer + + self._temperature_poller = RepeatedTimer( + poll_temperature_interval, poll_temperature, run_first=True + ) + self._temperature_poller.start() + + def _on_switched_state_starting(self, old_state): + # reset line numbers every time we start a new print job + self.send_commands(self.flavor.command_set_line(0)) + + def _on_switched_state_disconnecting(self, old_state): + self._handle_disconnecting(old_state, False) + + def _on_switched_state_disconnecting_with_error(self, old_state): + self._handle_disconnecting(old_state, True) + + def _handle_disconnecting(self, old_state, error): + if self._temperature_poller is not None: + self._temperature_poller.cancel() + self._temperature_poller = None + + if self._sd_status_poller is not None: + self._sd_status_poller.cancel() + self._sd_status_poller = None + + if not error: + try: + self.send_script("beforePrinterDisconnected") + stop = monotonic_time() + 10.0 # TODO make somehow configurable + while ( + self._command_queue.unfinished_tasks + or self._send_queue.unfinished_tasks + ) and monotonic_time() < stop: + time.sleep(0.1) + except UnknownScript: + pass + except Exception: + self._logger.exception( + "Error while trying to send beforePrinterDisconnected script" + ) + + self._send_queue_active = False + + ##~~ Job handling + + def on_job_started(self, job, *args, **kwargs): + if job != self._job: + return + + self.notify_listeners("on_protocol_job_started", self, job, *args, **kwargs) + + def finalize(): + self.state = ProtocolState.PROCESSING + + self.send_commands(SendQueueMarker(finalize), part_of_job=True) + self._continue_sending() + + def on_job_cancelled(self, job, *args, **kwargs): + if job != self._job: + return + self._job_processed(job) + + def on_job_paused(self, job, *args, **kwargs): + pass + + def on_job_resumed(self, job, *args, **kwargs): + if job != self._job: + return + + user = kwargs.get("user") + tags = kwargs.get("tags") + suppress_script = not kwargs.get("local_handling", True) + + self.notify_listeners( + "on_protocol_job_resumed", + self, + job, + suppress_script=suppress_script, + user=user, + tags=tags, + ) + + def finalize(): + if self.state == ProtocolState.RESUMING: + self.state = ProtocolState.PROCESSING + + self.send_commands(SendQueueMarker(finalize), part_of_job=True) + self._continue_sending() + + def on_job_done(self, job, *args, **kwargs): + if job != self._job: + return + + self.state = ProtocolState.FINISHING + self._job_processed(job) + self.notify_listeners("on_protocol_job_finishing", self, job, *args, **kwargs) + + def finalize(): + self.state = ProtocolState.CONNECTED + self.notify_listeners("on_protocol_job_done", self, job, *args, **kwargs) + + self.send_commands(SendQueueMarker(finalize), part_of_job=True) + self._continue_sending() + + def _job_processed(self, job, *args, **kwargs): + self._job.unregister_listener(self) + + def _job_on_hold_cleared(self): + self._continue_sending() + + ##~~ Transport logging + + def on_transport_log_message(self, transport, data): + super(ReprapGcodeProtocol, self).on_transport_log_message(transport, data) + self._terminal_log.append("--- " + to_unicode(data.strip(), errors="replace")) + + def on_transport_log_received_data(self, transport, data): + super(ReprapGcodeProtocol, self).on_transport_log_received_data(transport, data) + self._terminal_log.append("<<< " + to_unicode(data.strip(), errors="replace")) + + def on_transport_log_sent_data(self, transport, data): + super(ReprapGcodeProtocol, self).on_transport_log_sent_data(transport, data) + self._terminal_log.append(">>> " + to_unicode(data.strip(), errors="replace")) + + ##~~ Receiving + + def on_transport_data_pushed(self, transport, data): + if transport != self._transport: + return + self._receive(data) + + def on_transport_data_exception(self, transport, exception): + if transport != self._transport: + return + + if isinstance(exception, TimeoutTransportException): + self._receive("") + elif isinstance(exception, EofTransportException): + self._receive(None) + + def _receive(self, data): + for name, hook in self._gcode_hooks["receiving"].items(): + try: + data = hook(self, data) + except Exception: + self._logger.exception( + "Error while processing hook {name}:".format(**locals()), + extra={"plugin": name}, + ) + else: + if data is None: + data = "" + + if data is None: + # EOF + # TODO handle EOF + pass + + def convert_line(line): + if line is None: + return None, None + stripped_line = line.strip().strip("\0") + return stripped_line, stripped_line.lower() + + orig_line = to_unicode(data, encoding="ascii", errors="replace").strip() + line, lower_line = convert_line(orig_line) + + self._on_comm_any(line, lower_line) + + for message in self._current_registered_messages: + handler_method = getattr(self, "_on_{}".format(message), None) + if not handler_method: + # no handler, nothing to do + continue + + # match line against flavor specific matcher + matches = getattr(self.flavor, message)( + line, lower_line, self._state, self._protected_flags + ) + if isinstance(matches, tuple) and len(matches) == 2: + matches, continue_further = matches + else: + continue_further = not matches + + if matches: + message_args = {} + + parse_method = getattr(self.flavor, "parse_{}".format(message), None) + if parse_method: + # flavor specific parser? run it + parse_result = parse_method( + line, lower_line, self._state, self._protected_flags + ) + if parse_result is None: + if continue_further: + continue + else: + break + + # add parser result to kwargs + message_args.update(parse_result) + + # before handler: flavor.before_comm_* or flavor.before_message_* + before_handler = getattr(self.flavor, "before_{}".format(message), None) + if before_handler: + before_handler(**message_args) + + # run handler + result = handler_method(**message_args) + + # after handler: flavor.after_comm_* or flavor.after_message_* + after_handler = getattr(self.flavor, "after_{}".format(message), None) + if after_handler: + after_handler(result, **message_args) + + if not result: + # nothing or False returned? handled -> only continue further if instructed + if continue_further: + continue + else: + break + + elif not continue_further: + break + + else: + # unknown message + pass + + def _on_comm_any(self, line, lower_line): + timeout, _ = self.flavor.comm_timeout( + line, lower_line, self._state, self._protected_flags + ) + if not timeout: + self._internal_flags["timeout_consecutive"] = 0 + + offsets = [ + self.timeouts.get( + "communication_busy" + if self._internal_flags["busy_detected"] + else "communication", + 0.0, + ), + ] + if self._temperature_poller: + offsets.append(self._temperature_poller.interval()) + self._internal_flags["timeout"] = self._get_max_timeout(*offsets) + + if len(line): + if ( + self._internal_flags["dwelling_until"] + and monotonic_time() > self._internal_flags["dwelling_until"] + ): + self._internal_flags["dwelling_until"] = False + + if self.state == ProtocolState.CONNECTING and len(line): + hello = self.flavor.command_hello() + if hello: + self._tickle(hello) + + if ( + self._resend_ok_timer + and line + and not getattr(self.flavor, "comm_ok", lambda *a, **kwa: True)( + line, lower_line, self._state, self._protected_flags + ) + ): + # we got anything but an ok after a resend request - this means the ok after the resend request + # was in fact missing and we now need to trigger the timer + self._resend_ok_timer.cancel() + self._resend_simulate_ok() + + def _on_comm_timeout(self, line, lower_line): + general_message = "Configure long running commands or increase communication timeout if that happens regularly on specific commands or long moves." + + # figure out which consecutive timeout maximum we have to use + if self._internal_flags["long_running_command"]: + consecutive_max = self.max_consecutive_timeouts["long"] + elif self.state in ( + ProtocolState.PROCESSING, + ProtocolState.PAUSING, + ProtocolState.CANCELLING, + ): + consecutive_max = self.max_consecutive_timeouts["printing"] + else: + consecutive_max = self.max_consecutive_timeouts["idle"] + + # now increment the timeout counter + self._internal_flags["timeout_consecutive"] += 1 + self._logger.debug( + "Now at {} consecutive timeouts".format( + self._internal_flags["timeout_consecutive"] + ) + ) + + if 0 < consecutive_max < self._internal_flags["timeout_consecutive"]: + # too many consecutive timeouts, we give up + message = ( + "No response from printer after {} consecutive communication timeouts. " + "Have to consider it dead.".format(consecutive_max + 1) + ) + self._logger.info(message) + self.process_protocol_log(message) + + # TODO error handling + self.error = "Too many consecutive timeouts" + + self.disconnect(error=True) + + elif self._internal_flags["resend_requested"] is not None: + message = "Communication timeout during an active resend, resending same line again to trigger response from printer." + self._logger.info(message) + self.notify_listeners( + "on_protocol_log", self, message + " " + general_message + ) + if self._send_same_from_resend(): + self._commdebug_logger.debug( + "on_comm_timeout => clear_to_send.set: timeout during active resend (counter: {})".format( + self._clear_to_send.counter + ) + ) + self._clear_to_send.set() + + elif self._internal_flags["heating"]: + # blocking heatup active, consider that finished + message = "Timeout while in an active heatup, considering heatup to be over" + self._logger.info(message) + self._finish_heatup() + + elif self._internal_flags["long_running_command"]: + # long running command active, ignore timeout + self._logger.debug( + "Ran into a communication timeout, but a command known to be a long runner is currently active" + ) + + elif self.state in (ProtocolState.PROCESSING, ProtocolState.PAUSED): + # printing, try to tickle the printer + message = "Communication timeout while printing, trying to trigger response from printer." + self._logger.info(message) + self.notify_listeners( + "on_protocol_log_message", self, message + " " + general_message + ) + if self._send_command(GcodeCommand("M105", type="temperature")): + self._commdebug_logger.debug( + "on_comm_timeout => clear_to_send.set: timeout while printing (counter: {})".format( + self._clear_to_send.counter + ) + ) + self._clear_to_send.set() + + elif self._clear_to_send.blocked(): + # timeout while idle and no oks left, let's try to tickle the printer + message = "Communication timeout while idle, trying to trigger response from printer." + self._logger.info(message) + self.notify_listeners( + "on_protocol_log_message", self, message + " " + general_message + ) + self._commdebug_logger.debug( + "on_comm_timeout => clear_to_send.set: timeout while idle (counter: {})".format( + self._clear_to_send.counter + ) + ) + self._clear_to_send.set() + + self._internal_flags["ok_timeout"] = self._get_timeout( + "communication_busy" + if self._internal_flags["busy_detected"] + else "communication" + ) + + return self.state != ProtocolState.PROCESSING and line == "" + + def _on_comm_ok(self, wait=False): + if self._internal_flags["ignore_ok"] > 0: + self._internal_flags["ignore_ok"] -= 1 + if self._internal_flags["ignore_ok"] < 0: + self._internal_flags["ignore_ok"] = 0 + self._logger.debug( + "Ignoring this ok, ignore counter is now {}".format( + self._internal_flags["ignore_ok"] + ) + ) + return + + if self.state == ProtocolState.CONNECTING: + self.state = ProtocolState.CONNECTED + return + + if self._resend_ok_timer: + self._resend_ok_timer.cancel() + self._resend_ok_timer = None + + self._internal_flags["ok_timeout"] = self._get_timeout( + "communication_busy" + if self._internal_flags["busy_detected"] + else "communication" + ) + self._commdebug_logger.debug( + "on_comm_ok => clear_to_send.set: {} (counter: {})".format( + "wait" if wait else "ok", self._clear_to_send.counter + ) + ) + self._clear_to_send.set() + + # reset long running commands, persisted current tools and heatup counters on ok + + self._internal_flags["long_running_command"] = False + + if self._internal_flags["former_tool"]: + self._internal_flags["current_tool"] = self._internal_flags["former_tool"] + self._internal_flags["former_tool"] = None + + self._finish_heatup() + + if self.state not in ProtocolState.OPERATIONAL_STATES: + return + + # process ongoing resend requests and queues if we are operational + + if self._internal_flags["resend_requested"] is not None: + self._send_next_from_resend() + else: + self._continue_sending() + + def _on_comm_ignore_ok(self): + self._internal_flags["ignore_ok"] += 1 + self._logger.info( + "Ignoring next ok, counter is now at {}".format( + self._internal_flags["ignore_ok"] + ) + ) + + def _on_comm_wait(self): + if self.state == ProtocolState.PROCESSING and not self.job_on_hold: + self._on_comm_ok(wait=True) + + def _on_comm_resend(self, linenumber): + try: + if linenumber is None: + return False + + if ( + self._internal_flags["resend_requested"] is None + and linenumber == self._current_linenumber + ): + # We don't expect to have an active resend request and the printer is requesting a resend of + # a line we haven't yet sent. + # + # This means the printer got a line from us with N = self._current_linenumber - 1 but had already + # acknowledged that. This can happen if the last line was resent due to a timeout during an active + # (prior) resend request. + # + # We will ignore this resend request and just continue normally. + self._logger.debug( + "Ignoring resend request for line {} == current line, we haven't sent that yet so the printer got N-1 twice from us, probably due to a timeout".format( + linenumber + ) + ) + self.process_protocol_log( + "Ignoring resend request for line {}, we haven't sent that yet".format( + linenumber + ) + ) + return + + last_communication_error = self._last_communication_error + self._last_communication_error = None + + if ( + last_communication_error is not None + and last_communication_error == "linenumber" + and linenumber == self._internal_flags["resend_requested"] + and self._internal_flags["resend_count"] + < self._current_linenumber - linenumber - 1 + ): + self._logger.debug( + "Ignoring resend request for line {}, that still originates from lines we sent before we got the first resend request".format( + linenumber + ) + ) + self.process_protocol_log( + "Ignoring resend request for line {}, originates from lines sent earlier".format( + linenumber + ) + ) + self._internal_flags["resend_count"] += 1 + return + + if linenumber not in self._last_lines: + self._logger.error( + "Printer requested to resend a line we don't have: {}".format( + linenumber + ) + ) + if self._is_busy(): + # TODO set error state & log + self.cancel_processing(error=True) + else: + return + + self._internal_flags["resend_requested"] = linenumber + self._internal_flags["resend_linenumber"] = linenumber + self._internal_flags["resend_count"] = 0 + + # if we log resends, make sure we don't log more resends than the set rate within a window + # + # this it to prevent the log from getting flooded for extremely bad communication issues + if self._log_resends: + now = monotonic_time() + new_rate_window = ( + self._log_resends_rate_start is None + or self._log_resends_rate_start + self._log_resends_rate_frame < now + ) + in_rate = self._log_resends_rate_count < self._log_resends_max + + if new_rate_window or in_rate: + if new_rate_window: + self._log_resends_rate_start = now + self._log_resends_rate_count = 0 + + self._to_logfile_with_terminal( + "Got a resend request from the printer: requested line = {}, " + "current line = {}".format(linenumber, self._current_linenumber) + ) + self._log_resends_rate_count += 1 + + self._send_queue.resend_active = True + + finally: + if self.flavor.trigger_ok_after_resend == "always": + self._on_comm_ok() + elif self.flavor.trigger_ok_after_resend == "detect": + self._resend_ok_timer = threading.Timer( + self.timeouts.get("resendOk", 1.0), self._resend_simulate_ok + ) + self._resend_ok_timer.start() + + def _resend_simulate_ok(self): + self._resend_ok_timer = None + self._on_comm_ok() + self._logger.info( + "Firmware didn't send an 'ok' with their resend request. That's a known bug " + "with some firmware variants out there. Simulating an ok to continue..." + ) + + def _on_comm_start(self): + if self.state == ProtocolState.CONNECTING: + self.state = ProtocolState.CONNECTED + + elif self.state in ProtocolState.OPERATIONAL_STATES: + with self.job_put_on_hold(): + idle = self._state == ProtocolState.CONNECTED + if idle: + message = ( + "Printer sent 'start' while already connected. External reset? " + "Resetting state to be on the safe side." + ) + self.process_protocol_log(message) + self._logger.warn(message) + + self._on_external_reset() + + else: + message = ( + "Printer sent 'start' while processing a job. External reset? " + "Aborting job since printer lost state." + ) + self.process_protocol_log(message) + self._logger.warn(message) + + self._on_external_reset() + self.cancel_processing(log_position=False) + + self.notify_listeners("on_protocol_reset", idle) + + def _on_comm_error(self, line, lower_line, error): + for message in self._error_messages: + handler_method = getattr(self, "_on_{}".format(message), None) + if not handler_method: + continue + + if getattr(self.flavor, message)( + line, lower_line, error, self._state, self._protected_flags + ): + message_args = {} + + parse_method = getattr(self.flavor, "parse_{}".format(message), None) + if parse_method: + parse_result = parse_method( + line, lower_line, error, self._state, self._protected_flags + ) + if parse_result is None: + break + + message_args.update(parse_result) + + if not handler_method(**message_args): + break + else: + for name, hook in self._error_hooks.items(): + try: + ret = hook(self, error) + except Exception: + self._logger.exception( + "Error while processing hook {name}:".format(**locals()), + extra={"plugin": name}, + ) + else: + if ret: + # some plugin handled this, we'll return + return + + # unknown error message + self.error = line + + if self.firmware_errors != "ignore": + if self.firmware_errors == "disconnect" or self.flavor.error_sdcard( + line, lower_line, error, self._state, self._protected_flags + ): + # disconnect + self._trigger_error(error, "firmware") + + elif self._state in ProtocolState.PROCESSING_STATES: + # cancel the print + self.cancel_processing(error=error) + self._clear_to_send.set() + + else: + message = ( + "--- WARNING! Received an error from the printer's firmware, ignoring that as configured " + "but you might want to investigate what happened here! Error: {}".format( + error + ) + ) + self._to_logfile_with_terminal(message, level=logging.WARNING) + self.process_protocol_log(message) + self._clear_to_send.set() + + def _on_error_communication(self, error_type): + self._last_communication_error = error_type + + def _on_comm_busy(self): + self._internal_flags["ok_timeout"] = self._get_timeout( + "communcation_busy" + if self._internal_flags["busy_detected"] + else "communication" + ) + + if not self._internal_flags["busy_detected"] and self._capability_support.get( + CAPABILITY_BUSY_PROTOCOL, False + ): + self.process_protocol_log( + "Printer seems to support the busy protocol, adjusting timeouts and setting busy " + "interval accordingly" + ) + self._internal_flags["busy_detected"] = True + + new_communication_timeout = self.timeouts.get("communication_busy", 2) + self._transport.timeout = new_communication_timeout + busy_interval = max(int(new_communication_timeout) - 1, 1) + + self._logger.info( + "Printer seems to support the busy protocol, telling it to set the busy " + 'interval to our "communication_busy" timeout - 1s = {}s'.format( + busy_interval + ) + ) + + self._set_busy_protocol_interval(interval=busy_interval) + + def _on_comm_action_command(self, line, lower_line, action): + if action == "cancel": + self.process_protocol_log("Cancelling on request of the printer...") + self.cancel_processing() + elif action == "pause": + self.process_protocol_log("Pausing on request of the printer...") + self.pause_processing() + elif action == "paused": + self.process_protocol_log( + "Printer signalled that it paused, switching state..." + ) + self.pause_processing(local_handling=False) + elif action == "resume": + self.process_protocol_log("Resuming on request of the printer...") + self.resume_processing() + elif action == "resumed": + self.process_protocol_log( + "Printer signalled that it resumed, switching state..." + ) + self.resume_processing(local_handling=False) + elif action == "disconnect": + self.process_protocol_log("Disconnecting on request of the printer...") + # TODO inform printer about forced disconnect + self.disconnect() + else: + for hook in self._action_hooks: + try: + self._action_hooks[hook](self, line, action) + except Exception: + self._logger.exception( + "Error while calling hook {} with action command {}".format( + self._action_hooks[hook], action + ) + ) + continue + + def _on_message_temperature(self, max_tool_num, temperatures, heatup_detected): + if heatup_detected: + self._logger.debug("Externally triggered heatup detected") + self._internal_flags["heating"] = True + self._internal_flags["heatup_start"] = monotonic_time() + + shared_nozzle = self._printer_profile["extruder"]["sharedNozzle"] + current_tool_key = "T{}".format(self._internal_flags["current_tool"]) + + for name, hook in self._temperature_hooks.items(): + try: + temperatures = hook(self, temperatures) + if temperatures is None or not temperatures: + return + except Exception: + self._logger.exception( + "Error while processing temperatures in {}, skipping".format(name), + extra={"plugin": name}, + ) + + if current_tool_key in temperatures: + for x in range(max_tool_num + 1): + tool = "T{}".format(x) + if tool not in temperatures: + if shared_nozzle: + # replicate the current temperature across all tools (see #2077) + actual, target = temperatures[current_tool_key] + else: + continue + else: + actual, target = temperatures[tool] + self._internal_flags["temperatures"].set_tool( + x, actual=actual, target=target + ) + + if "B" in temperatures and self._printer_profile["heatedBed"]: + actual, target = temperatures["B"] + self._internal_flags["temperatures"].set_bed(actual=actual, target=target) + + if "C" in temperatures and ( + self._capability_support.get(CAPABILITY_CHAMBER_TEMP, False) + or self._printer_profile["heatedChamber"] + ): + actual, target = temperatures["C"] + self._internal_flags["temperatures"].set_chamber(actual=actual, target=target) + + self.notify_listeners( + "on_protocol_temperature", + self, + self._internal_flags["temperatures"].as_dict(), + ) + + def _on_message_position(self, position): + self.last_position.valid = True + self.last_position.x = position.get("x") + self.last_position.y = position.get("y") + self.last_position.z = position.get("z") + + t_and_f_trustworthy = self._job is None or not self._job.parallel + + if "e" in position: + self.last_position.e = position.get("e") + else: + # multiple extruder coordinates provided, find current one + self.last_position.e = ( + position.get("e{}".format(self._internal_flags["current_tool"])) + if t_and_f_trustworthy + else None + ) + + for key in [key for key in position if key.startswith("e") and len(key) > 1]: + setattr(self.last_position, key, position.get(key)) + + self.last_position.t = ( + self._internal_flags["current_tool"] if t_and_f_trustworthy else None + ) + self.last_position.f = ( + self._internal_flags["current_f"] if t_and_f_trustworthy else None + ) + + reason = None + + if self._record_pause_data: + reason = "pause" + self._record_pause_data = False + self.pause_position.copy_from(self.last_position) + self.pause_temperature.copy_from(self._internal_flags["temperatures"]) + self._pause_preparation_done() + + if self._record_cancel_data: + reason = "cancel" + self._record_cancel_data = False + self.cancel_position.copy_from(self.last_position) + self.cancel_temperature.copy_from(self._internal_flags["temperatures"]) + self._cancel_preparation_done() + + self.notify_listeners( + "on_protocol_position_all_update", self, position, reason=reason + ) + + def _on_message_firmware_info(self, firmware_name, data): + self._event_bus.fire( + Events.FIRMWARE_DATA, {"name": firmware_name, "data": copy.copy(data)} + ) + + if not self._internal_flags["firmware_identified"] and firmware_name: + self._logger.info('Printer reports firmware name "{}"'.format(firmware_name)) + + for flavor in all_flavors(): + if ( + flavor.identifier + and callable(flavor.identifier) + and flavor.identifier(firmware_name, data) + ): + self._logger.info( + 'Detected firmware flavor "{}", switching...'.format(flavor.key) + ) + self._switch_flavor(flavor) + + self._internal_flags["firmware_identified"] = True + self._internal_flags["firmware_name"] = firmware_name + self._internal_flags["firmware_info"] = data + + # notify plugins + for name, hook in self._firmware_info_hooks.items(): + try: + hook(self, firmware_name, copy.copy(data)) + except Exception: + self._logger.exception( + "Error processing firmware info hook {}:".format(name), + extra={"plugin": name}, + ) + + def _on_message_firmware_capability(self, cap, enabled): + self._internal_flags["firmware_capabilities"][cap] = enabled + + if self._capability_support.get(cap, False): + if cap == CAPABILITY_AUTOREPORT_TEMP and enabled: + self._logger.info( + "Firmware states that it supports temperature autoreporting" + ) + self._set_autoreport_temperature_interval() + elif cap == CAPABILITY_AUTOREPORT_SD_STATUS and enabled: + self._logger.info( + "Firmware states that it supports sd status autoreporting" + ) + self._set_autoreport_sdstatus_interval() + elif cap == CAPABILITY_EMERGENCY_PARSER and enabled: + self._logger.info( + "Firmware states that it supports emergency GCODEs to be sent without waiting for an acknowledgement first" + ) + + # notify plugins + for name, hook in self._firmware_cap_hooks.items(): + try: + hook( + self, + cap, + enabled, + copy.copy(self._internal_flags["firmware_capabilities"]), + ) + except Exception: + self._logger.exception( + "Error processing firmware capability hook {}:".format(name), + extra={"plugin": name}, + ) + + def _on_message_sd_init_ok(self): + self._internal_flags["sd_available"] = True + self.list_files() + self.notify_listeners( + "on_protocol_file_storage_available", + self, + self._internal_flags["sd_available"], + ) + + def _on_message_sd_init_fail(self): + self._internal_flags["sd_available"] = False + self.notify_listeners( + "on_protocol_file_storage_available", + self, + self._internal_flags["sd_available"], + ) + + def _on_message_sd_begin_file_list(self): + self._internal_flags["sd_files_temp"] = [] + + def _on_message_sd_end_file_list(self): + self._internal_flags["sd_files"] = self._internal_flags["sd_files_temp"] + self._internal_flags["sd_files_temp"] = None + self.notify_listeners( + "on_protocol_file_list", self, self._internal_flags["sd_files"] + ) + + def _on_message_sd_entry(self, name, long_name, size): + self._internal_flags["sd_files_temp"].append((name, long_name, size)) + + def _on_message_sd_file_opened(self, name, long_name, size): + self.notify_listeners( + "on_protocol_file_print_started", self, name, long_name, size + ) + + def _on_message_sd_done_printing(self): + self.notify_listeners("on_protocol_file_print_done", self) + + def _on_message_sd_printing_byte(self, current, total): + self.notify_listeners("on_protocol_sd_status", self, current, total) + + def _finish_heatup(self): + if self._internal_flags["heating"]: + if self._internal_flags["heating_start"]: + self._internal_flags["heating_lost"] = self._internal_flags[ + "heating_lost" + ] + (monotonic_time() - self._internal_flags["heating_start"]) + self._internal_flags["heating_start"] = None + self._internal_flags["heating"] = False + + def _on_external_reset(self): + with self._send_queue.blocked(): + self._clear_to_send.clear(completely=True) + with self._command_queue.blocked(): + self._command_queue.clear() + self._send_queue.clear() + + with self._line_mutex: + self._current_linenumber = 0 + self._last_lines.clear() + + self.flavor = GenericFlavor.with_overrides(self.flavor_overrides) + + self.send_commands(self.flavor.command_hello(), self.flavor.command_set_line(0)) + + if self._internal_flags["temperature_autoreporting"]: + self._set_autoreport_temperature_interval() + if self._internal_flags["sd_status_autoreporting"]: + self._set_autoreport_sdstatus_interval() + if self._internal_flags["busy_detected"]: + self._set_busy_protocol_interval() + + ##~~ Sending + + def _tickle(self, command): + if self._send_command(command): + if self._clear_to_send.blocked(): + self._commdebug_logger.debug( + "tickle => clear_to_send.set (counter: {})".format( + self._clear_to_send.counter + ) + ) + self._clear_to_send.set() + + def _continue_sending(self): + self._commdebug_logger.debug( + "continue_sending (counter: {}, line number: {})".format( + self._clear_to_send.counter, self._current_linenumber + ) + ) + while self._active: + job_active = self.state in ( + ProtocolState.STARTING, + ProtocolState.PROCESSING, + ) and not ( + self._job is None + or not self._job.active + or isinstance(self._job, SDFilePrintjob) + ) + + if self._send_from_command_queue(): + # we found something in the command queue to send + return True + + elif self.job_on_hold: + # job is on hold, that means we must not send from either job or job queue + return False + + elif self._send_from_job_queue(): + # we found something in the job queue to send + return True + + elif job_active and self._send_next_from_job(): + # we sent the next line from the file + return True + + elif not job_active: + # nothing sent but also no job active, so we can just return false here + return False + + self._logger.debug( + "No command sent on ok while printing, doing another iteration" + ) + + def _send_same_from_resend(self): + return self._send_next_from_resend(again=True) + + def _send_next_from_resend(self, again=False): + self._commdebug_logger.debug( + "send_next_from_resend (counter: {}, line number: {})".format( + self._clear_to_send.counter, self._internal_flags.get("resend_linenumber") + ) + ) + self._last_communication_error = None + + # Make sure we are only handling one sending job at a time + with self._send_queue_mutex: + if again: + # If we are about to send the last line from the active resend request + # again, we first need to increment resend delta. It might already + # be set to None if the last resend line was already sent, so + # if that's the case we set it to 0. It will then be incremented, + # the last line will be sent again, and then the delta will be + # decremented and set to None again, completing the cycle. + if self._internal_flags["resend_linenumber"] is None: + self._internal_flags["resend_linenumber"] = self._current_linenumber + self._internal_flags["resend_linenumber"] -= 1 + + linenumber = self._internal_flags["resend_linenumber"] + + try: + command = self._last_lines[linenumber] + except KeyError: + # TODO what to do? + return False + + result = self._enqueue_for_sending( + to_command(command), linenumber=linenumber, processed=True, resend=True + ) + + self._internal_flags["resend_linenumber"] += 1 + if self._internal_flags["resend_linenumber"] == self._current_linenumber: + self._internal_flags["resend_requested"] = None + self._internal_flags["resend_linenumber"] = None + self._internal_flags["resend_count"] = 0 + + self._send_queue.resend_active = False + + return result + + def _send_next_from_job(self): + with self._send_queue_mutex: + while self._active: + # we loop until we've actually enqueued a line for sending + if self.state != ProtocolState.PROCESSING: + # we are no longer printing, return False + return False + + elif self.job_on_hold: + # job is on hold, return false + return False + + line = self._job.get_next() + if line is None: + # end of job, return False + return False + + pos = self._job.pos + read_lines = self._job.read_lines + actual_lines = self._job.actual_lines + command = to_command( + line, + tags={ + "source:file", + "filepos:{}".format(pos), + "fileline:{}".format(read_lines), + "fileactualline:{}".format(actual_lines), + }, + ) + if self._send_command(command): + return True + + self._logger.debug( + 'Command "{}" from job not enqueued, doing another iteration'.format( + line + ) + ) + + def _send_from_job_queue(self): + try: + command, on_sent = self._job_queue.get_nowait() + result = self._send_command(command, on_sent=on_sent) + if result: + return True + except queue.Empty: + pass + + return False + + def _send_from_command_queue(self): + # We loop here to make sure that if we do NOT send the first command + # from the queue, we'll send the second (if there is one). We do not + # want to get stuck here by throwing away commands. + while True: + if self._internal_flags["only_from_job"]: + # irrelevant command queue => return + return False + + try: + entry = self._command_queue.get(block=False) + except queue.Empty: + # nothing in command queue + return False + + try: + if isinstance(entry, tuple): + if not len(entry) == 2: + # something with that entry is broken, ignore it and fetch + # the next one + continue + cmd, callback = entry + else: + cmd = entry + callback = None + + if self._send_command(cmd, on_sent=callback): + # we actually did add this cmd to the send queue, so let's + # return, we are done here + return True + finally: + self._command_queue.task_done() + + def _send_commands(self, *commands, **kwargs): + command_type = kwargs.pop("command_type", None) + result = False + for command in commands: + if len(commands) > 1: + command_type = None + result = ( + self._send_command(command, command_type=command_type, **kwargs) or result + ) + return result + + def _send_command(self, command, command_type=None, tags=None, on_sent=None): + with self._send_queue_mutex: + if isinstance(command, QueueMarker): + if isinstance(command, SendQueueMarker): + self._enqueue_for_sending(command) + return True + else: + return False + + elif isinstance(command, Command) and (command_type or tags): + command = command.with_type(command_type).with_tags(tags) + + else: + command = to_command(command, type=command_type, tags=tags) + + if self._internal_flags["trigger_events"]: + results = self._process_command_phase("queuing", command) + + if not results: + # command is no more, return + return False + else: + results = [command] + + # process helper + def process(command, on_sent=None): + if command is None: + # no command, next entry + return False + + # process @ commands + if isinstance(command, AtCommand): + self._process_atcommand_phase("queuing", command) + + # actually enqueue the command for sending + if self._enqueue_for_sending(command, on_sent=on_sent): + if not self._is_streaming(): + # trigger the "queued" phase only if we are not streaming to sd right now + self._process_command_phase("queued", command) + + if ( + self._internal_flags["trigger_events"] + and isinstance(command, GcodeCommand) + and command.code in GCODE_TO_EVENT + ): + self._event_bus.fire(GCODE_TO_EVENT[command.code]) + pass + return True + else: + return False + + # split off the final command, because that needs special treatment + if len(results) > 1: + last_command = results[-1] + results = results[:-1] + else: + last_command = results[0] + results = [] + + # track if we enqueued anything at all + enqueued_something = False + + # process all but the last ... + for command in results: + enqueued_something = process(command) or enqueued_something + + # ... and then process the last one with the on_sent callback attached + command = last_command + enqueued_something = process(command, on_sent=on_sent) or enqueued_something + + return enqueued_something + + def _enqueue_for_sending( + self, command, linenumber=None, on_sent=None, processed=False, resend=False + ): + """ + Enqueues a command and optional command_type and linenumber in the send queue. + + Arguments: + command (Command or SendQueueMarker): The command to send or the marker to enqueue + linenumber (int): An optional line number to use for sending the + command. + on_sent (callable or None): Callback to call when the command has been sent + processed (bool): Whether this line has already been processed or not + """ + + try: + target = "send" + if resend: + target = "resend" + + if isinstance(command, Command): + command_type = command.type + else: + command_type = None + + self._send_queue.put( + (command, linenumber, on_sent, processed), + item_type=command_type, + target=target, + ) + return True + except TypeAlreadyInQueue as e: + self._logger.debug("Type already in queue: {}".format(e.type)) + return False + + def _send_loop(self): + """ + The send loop is responsible of sending commands in ``self._send_queue`` over the line, if it is cleared for + sending (through received ``ok`` responses from the printer's firmware. + """ + + self._clear_to_send.wait() + + while self._send_queue_active: + try: + # wait until we have something in the queue + try: + entry = self._send_queue.get() + except queue.Empty: + continue + + try: + # make sure we are still active + if not self._send_queue_active: + break + + # sleep if we are dwelling + now = monotonic_time() + if ( + self.flavor.block_while_dwelling + and self._internal_flags["dwelling_until"] + and now < self._internal_flags["dwelling_until"] + ): + time.sleep(self._internal_flags["dwelling_until"] - now) + self._internal_flags["dwelling_until"] = False + + # fetch command and optional linenumber from queue + command, linenumber, on_sent, processed = entry + + if isinstance(command, SendQueueMarker): + command.run() + self._continue_sending() + continue + + if linenumber is not None: + # line number predetermined - this only happens for resends, so we'll use the number and + # send directly without any processing (since that already took place on the first sending!) + self._do_send_with_checksum(to_bytes(command.line), linenumber) + + else: + if not processed: + results = self._process_command_phase("sending", command) + + if not results: + # No, we are not going to send this, that was a last-minute bail. + # However, since we already are in the send queue, our _monitor + # loop won't be triggered with the reply from this unsent command + # now, so we try to tickle the processing of any active + # command queues manually + self._commdebug_logger.debug("send_loop => no results") + self._continue_sending() + + # and now let's fetch the next item from the queue + continue + + # we explicitly throw away plugin hook results that try + # to perform command expansion in the sending/sent phase, + # so "results" really should only have more than one entry + # at this point if our core code contains a bug + assert len(results) == 1 + + # we only use the first (and only!) entry here + command = results[0] + + if command.line.strip() == "": + self._logger.info( + "Refusing to send an empty line to the printer" + ) + + # same here, tickle the queues manually + self._commdebug_logger.debug("send_loop => empty line") + self._continue_sending() + + # and fetch the next item + continue + + # handle @ commands + if isinstance(command, AtCommand): + self._process_command_phase("sending", command) + + # tickle... + self._commdebug_logger.debug("send_loop => at command") + self._continue_sending() + + # ... and fetch the next item + continue + + # now comes the part where we increase line numbers and send stuff - no turning back now + self._do_send(command) + + # trigger "sent" phase and use up one "ok" + if on_sent is not None and callable(on_sent): + # we have a sent callback for this specific command, let's execute it now + on_sent() + self._process_command_phase("sent", command) + + # we only need to use up a clear if the command we just sent was either a gcode command or if we also + # require ack's for unknown commands + use_up_clear = self.flavor.unknown_requires_ack + if isinstance(command, GcodeCommand): + use_up_clear = True + else: + self._commdebug_logger.debug( + "send_loop => command != instanceof GcodeCommand: {!r}".format( + command + ) + ) + + if use_up_clear: + # if we need to use up a clear, do that now + self._commdebug_logger.debug( + "send_loop => clear_to_send.clear: line sent (counter: {}, line number: {})".format( + self._clear_to_send.counter, self._current_linenumber + ) + ) + self._clear_to_send.clear() + else: + # Otherwise we need to tickle the read queue - there might not be a reply + # to this command, so our _monitor loop will stay waiting until timeout. We + # definitely do not want that, so we tickle the queue manually here + self._commdebug_logger.debug("send_loop => use_up_clear == False") + self._continue_sending() + + finally: + # no matter _how_ we exit this block, we signal that we + # are done processing the last fetched queue entry + self._send_queue.task_done() + + # now we just wait for the next clear and then start again + self._clear_to_send.wait() + except Exception: + self._logger.exception("Caught an exception in the send loop") + self.notify_listeners("on_protocol_log", self, "Closing down send loop") + + def _log_command_phase(self, phase, command): + if self._phase_logger.isEnabledFor(logging.DEBUG): + self._phase_logger.debug("phase: {}, command: {!r}".format(phase, command)) + + def _process_command_phase(self, phase, command, **kwargs): + command = to_command(command, **kwargs) + results = [command] + + self._log_command_phase(phase, command) + + if not self._internal_flags["trigger_events"] or phase not in ( + "queuing", + "queued", + "sending", + "sent", + ): + return results + + # send it through the phase specific handlers provided by plugins + for name, hook in self._gcode_hooks[phase].items(): + new_results = [] + for command in results: + try: + hook_results = hook( + self, + phase, + str(command), + command.type, + command.code if isinstance(command, GcodeCommand) else None, + subcode=command.subcode + if isinstance(command, GcodeCommand) + else None, + tags=command.tags, + ) + except Exception: + self._logger.exception( + "Error while processing hook {name} for phase {phase} and command {command}:".format( + **locals() + ) + ) + else: + normalized = normalize_command_handler_result( + command, + hook_results, + tags_to_add={ + "source:rewrite", + "phase:{}".format(phase), + "plugin:{}".format(name), + }, + ) + + # make sure we don't allow multi entry results in anything but the queuing phase + if phase not in ("queuing",) and len(normalized) > 1: + self._logger.error( + "Error while processing hook {name} for phase {phase} and command {command}: Hook returned multi-entry result for phase {phase} and command {command}. That's not supported, if you need to do multi expansion of commands you need to do this in the queuing phase. Ignoring hook result and sending command as-is.".format( + **locals() + ) + ) + new_results.append(command) + else: + new_results += normalized + if not new_results: + # hook handler returned None or empty list for all commands, so we'll stop here and return a full out empty result + return [] + results = new_results + + # if it's a gcode command send it through the specific handler if it exists + new_results = [] + modified = False + for command in results: + if isinstance(command, GcodeCommand): + gcode_handler = "_gcode_" + command.code + "_" + phase + if gcode_handler in self._handlers_gcode: + # noinspection PyCallingNonCallable + handler_results = getattr(self, gcode_handler)(command) + new_results += normalize_command_handler_result( + command, handler_results + ) + modified = True + else: + new_results.append(command) + else: + new_results.append(command) + + if modified: + if not new_results: + # gcode handler returned None or empty list for all commands, so we'll stop here and return a full out empty result + return [] + else: + results = new_results + + # send it through the phase specific command handler if it exists + command_phase_handler = "_command_phase_" + phase + if command_phase_handler in self._handlers_command_phase: + new_results = [] + for command in results: + handler_results = getattr(self, command_phase_handler)(command) + new_results += normalize_command_handler_result(command, handler_results) + results = new_results + + # finally return whatever we resulted on + return results + + def _process_atcommand_phase(self, phase, command): + if (self._is_streaming()) or phase not in ("queuing", "sending"): + return + + # send it through the phase specific handlers provided by plugins + for name, hook in self._atcommand_hooks[phase].items(): + try: + hook( + self, phase, command.atcommand, command.parameters, tags=command.tags + ) + except Exception: + self._logger.exception( + "Error while processing hook {} for phase {} and command {}:".format( + name, phase, command.atcommand + ) + ) + + # trigger built-in handler if available + atcommand_handler = "_atcommand_{}_{}".format(command.atcommand, phase) + if atcommand_handler in self._handlers_atcommand: + try: + getattr(self, atcommand_handler)(command) + except Exception: + self._logger.exception( + "Error in handler for phase {} and command {}".format( + phase, command.atcommand + ) + ) + + ##~~ actual sending via serial + + def _needs_checksum(self, command): + if not self._transport.message_integrity: + # transport does not have message integrity, let's see if we'll send a checksum + command_requiring_checksum = ( + isinstance(command, GcodeCommand) + and command.code in self.flavor.checksum_requiring_commands + ) + command_allowing_checksum = ( + isinstance(command, GcodeCommand) or self.flavor.unknown_with_checksum + ) + return command_requiring_checksum or ( + command_allowing_checksum and self._checksum_enabled + ) + + else: + # transport has message integrity, no checksum + return False + + @property + def _checksum_enabled(self): + if not self._transport.message_integrity: + return self.flavor.send_checksum != "never" and ( + self.state == ProtocolState.PROCESSING # TODO does job need checksum? + or self.flavor.send_checksum == "always" + or not self._internal_flags["firmware_identified"] + ) + else: + # transport has message integrity, no checksum + return False + + def _emergency_force_send(self, command, message, *args, **kwargs): + """ + Args: + command (Command): the command to send + message (unicode): the message to log + """ + # only jump the queue with our command if the EMERGENCY_PARSER capability is available + if not self._internal_flags["firmware_capability_support"].get( + CAPABILITY_EMERGENCY_PARSER, False + ) or not self._internal_flags["firmware_capabilities"].get( + CAPABILITY_EMERGENCY_PARSER, False + ): + return + + self._logger.info(message) + self._do_send(command) + + # use up an ok since we will get one back for this command and don't want to get out of sync + self._clear_to_send.clear() + + return (None,) + + def _do_send(self, command): + """ + Args: + command (Command): the command to send + """ + if self._needs_checksum(command): + self._do_increment_and_send_with_checksum(command.bytes) + else: + self._do_send_without_checksum(command.bytes) + + def _do_increment_and_send_with_checksum(self, line): + """ + Args: + line (bytes): the line to send + """ + with self._line_mutex: + line_number = self._current_linenumber + self._add_to_last_lines(to_unicode(line), line_number=line_number) + self._current_linenumber += 1 + self._do_send_with_checksum(line, line_number) + + def _do_send_with_checksum(self, line, line_number): + """ + Args: + line (bytes): the line to send + line_number (int): the line number to send + """ + command_to_send = b"N" + str(line_number).encode("ascii") + b" " + line + checksum = 0 + for c in bytearray(command_to_send): + checksum ^= c + command_to_send = command_to_send + b"*" + str(checksum).encode("ascii") + self._do_send_without_checksum(command_to_send) + + def _do_send_without_checksum(self, data): + """ + Args: + data (bytes): the data to send + """ + self._transport.write(data + b"\n") + + def _add_to_last_lines(self, command, line_number=None): + # type: (str, int) -> None + self._last_lines.append(command, line_number=line_number) + + ##~~ gcode command handlers + + def _gcode_T_sent(self, command): + if command.tool: + self._internal_flags["current_tool"] = int(command.tool) + + def _gcode_G0_sent(self, command): + if command.z is not None and self._internal_flags["current_z"] != command.z: + self._internal_flags["current_z"] = command.z + self.notify_listeners( + "on_protocol_position_z_update", self, self._internal_flags["current_z"] + ) + if command.f is not None: + self._internal_flags["current_f"] = command.f + + _gcode_G1_sent = _gcode_G0_sent + + def _gcode_G2_sent(self, command): + if command.f is not None: + self._internal_flags["current_f"] = command.f + + _gcode_G3_sent = _gcode_G2_sent + _gcode_G28_sent = _gcode_G2_sent + + def _gcode_M140_queuing(self, command): + if not self._printer_profile["heatedBed"]: + self.process_protocol_log( + 'Warn: Not sending "{}", printer profile has no heated bed'.format( + command + ) + ) + return (None,) # Don't send bed commands if we don't have a heated bed + + _gcode_M190_queuing = _gcode_M140_queuing + + def _gcode_M155_sending(self, command): + try: + interval = int(command.s) + self._internal_flags["temperature_autoreporting"] = self._internal_flags[ + "firmware_capabilities" + ].get(CAPABILITY_AUTOREPORT_TEMP, False) and (interval > 0) + except Exception: + pass + + def _gcode_M27_sending(self, command): + try: + interval = int(command.s) + self._internal_flags["sd_status_autoreporting"] = self._internal_flags[ + "firmware_capabilities" + ].get(CAPABILITY_AUTOREPORT_SD_STATUS, False) and (interval > 0) + except Exception: + pass + + def _apply_temperature_offset(self, heater, command, support_r=False): + offset = self._internal_flags["temperature_offsets"].get(heater, 0) + if offset == 0 or "source:file" not in command.tags: + return + + try: + if command.s is not None: + return command.with_args(s=float(command.s) + offset) + elif command.r is not None and support_r: + return command.with_args(r=float(command.r) + offset) + except Exception: + self._logger.exception("Error applying temperature offset") + + def _gcode_M104_sending(self, command, support_r=False): + if command.t: + tool_num = command.t + else: + tool_num = self._internal_flags["current_tool"] + + return self._apply_temperature_offset( + "tool{}".format(tool_num), command, support_r=support_r + ) + + def _gcode_M109_sending(self, command): + return self._gcode_M104_sending(command, support_r=True) + + def _gcode_M140_sending(self, command): + return self._apply_temperature_offset("bed", command, support_r=False) + + def _gcode_M190_sending(self, command): + return self._apply_temperature_offset("bed", command, support_r=True) + + def _gcode_M141_sending(self, command): + return self._apply_temperature_offset("chamber", command, support_r=False) + + def _gcode_M191_sending(self, command): + return self._apply_temperature_offset("chamber", command, support_r=True) + + def _gcode_M104_sent(self, command, wait=False, support_r=False): + tool_num = self._internal_flags["current_tool"] + if command.t: + tool_num = command.t + + if wait: + self._internal_flags["former_tool"] = self._internal_flags["current_tool"] + self._internal_flags["current_tool"] = tool_num + + target = None + if command.s is not None: + target = float(command.s) + elif command.r is not None and support_r: + target = float(command.r) + + if target: + self._internal_flags["temperatures"].set_tool(tool_num, target=target) + self.notify_listeners( + "on_protocol_temperature", + self, + self._internal_flags["temperatures"].as_dict(), + ) + + def _gcode_M140_sent(self, command, wait=False, support_r=False): + target = None + if command.s is not None: + target = float(command.s) + elif command.r is not None and support_r: + target = float(command.r) + + if target: + self._internal_flags["temperatures"].set_bed(target=target) + self.notify_listeners( + "on_protocol_temperature", + self, + self._internal_flags["temperatures"].as_dict(), + ) + + def _gcode_M141_sent(self, command, wait=False, support_r=False): + target = None + if command.s is not None: + target = float(command.s) + elif command.r is not None and support_r: + target = float(command.r) + + if target: + self._internal_flags["temperatures"].set_chamber(target=target) + self.notify_listeners( + "on_protocol_temperature", + self, + self._internal_flags["temperatures"].as_dict(), + ) + + def _gcode_M109_sent(self, command): + self._internal_flags["heatup_start"] = monotonic_time() + self._internal_flags["long_running_command"] = True + self._internal_flags["heating"] = True + self._gcode_M104_sent(command, wait=True, support_r=True) + + def _gcode_M190_sent(self, command): + self._internal_flags["heatup_start"] = monotonic_time() + self._internal_flags["long_running_command"] = True + self._internal_flags["heating"] = True + self._gcode_M140_sent(command, wait=True, support_r=True) + + def _gcode_M191_sent(self, command): + self._internal_flags["heatup_start"] = monotonic_time() + self._internal_flags["long_running_command"] = True + self._internal_flags["heating"] = True + self._gcode_M141_sent(command, wait=True, support_r=True) + + def _gcode_M116_sent(self, command): + self._internal_flags["heatup_start"] = monotonic_time() + self._internal_flags["long_running_command"] = True + self._internal_flags["heating"] = True + + def _gcode_M110_sending(self, command): + new_line_number = None + if command.n: + try: + new_line_number = int(command.n) + except Exception: + pass + else: + new_line_number = 0 + + with self._line_mutex: + self._logger.info( + "M110 detected, setting current line number to {}".format(new_line_number) + ) + + # send M110 command with new line number + self._current_linenumber = new_line_number + + # after a reset of the line number we have no way to determine what line exactly the printer now wants + self._last_lines.clear() + self._internal_flags["resend_linenumber"] = None + + def _gcode_M112_queuing(self, command): + # emergency stop, jump the queue with the M112 + emergency_stop = self.flavor.command_emergency_stop().bytes + self._do_send_without_checksum(emergency_stop) + self._do_increment_and_send_with_checksum(emergency_stop) + + # No idea if the printer is still listening or if M112 won. Just in case + # we'll now try to also manually make sure all heaters are shut off - better + # safe than sorry. We do this ignoring the queue since at this point it + # is irrelevant whether the printer has sent enough ack's or not, we + # are going to shutdown the connection in a second anyhow. + extruder_count = self._printer_profile["extruder"]["count"] + shared_nozzle = self._printer_profile["extruder"]["sharedNozzle"] + if extruder_count > 1 and not shared_nozzle: + for tool in range(extruder_count): + self._do_increment_and_send_with_checksum( + self.flavor.command_set_extruder_temp(0, tool=tool).bytes + ) + else: + self._do_increment_and_send_with_checksum( + self.flavor.command_set_extruder_temp(0).bytes + ) + + if self._printer_profile["heatedBed"]: + self._do_increment_and_send_with_checksum( + self.flavor.command_set_bed_temp(0).bytes + ) + + # close to reset host state + # TODO needs error handling + """ + self._errorValue = "Closing serial port due to emergency stop M112." + self._log(self._errorValue) + self.close(is_error=True) + """ + + # fire the M112 event since we sent it and we're going to prevent the caller from seeing it + event = GCODE_TO_EVENT.get("M112") + if event is not None: + self._event_bus.fire(event) + + # return None 1-tuple to eat the one that is queuing because we don't want to send it twice + # I hope it got it the first time because as far as I can tell, there is no way to know + return (None,) + + # TODO + # def _gcode_M114_queued(self, *args, **kwargs): + # self._reset_position_timers() + # _gcode_M114_sent = _gcode_M114_queued + + def _gcode_G4_sent(self, command): + timeout = 0 + if command.p is not None: + try: + timeout = float(command.p) / 1000.0 + except ValueError: + pass + elif command.s is not None: + try: + timeout = float(command.s) + except ValueError: + pass + + self._internal_flags["timeout"] = ( + self._get_timeout( + "communication_busy" + if self._internal_flags["busy_detected"] + else "communication" + ) + + timeout + ) + self._internal_flags["dwelling_until"] = monotonic_time() + timeout + + ##~~ atcommand handlers + + def _atcommand_pause_queuing(self, command): + tags = command.tags + if tags is None: + tags = set() + if "script:afterPrintPaused" not in tags: + self.pause_processing(tags={"trigger:atcommand_pause"}) + + def _atcommand_cancel_queuing(self, command): + tags = command.tags + if tags is None: + tags = set() + if "script:afterPrintCancelled" not in tags: + self.cancel_processing(tags={"trigger:atcommand_cancel"}) + + _atcommand_abort_queuing = _atcommand_cancel_queuing + + def _atcommand_resume_queuing(self, command): + tags = command.tags + if tags is None: + tags = set() + if "script:beforePrintResumed" not in tags: + self.resume_processing(tags={"trigger:atcommand_resume"}) + + ##~~ command phase handlers + + def _command_phase_queuing(self, command): + if isinstance(command, GcodeCommand): + if ( + command.code in self.flavor.emergency_commands + and command.code != self.flavor.command_emergency_stop().code + ): + message = "Force-sending {} to the printer".format(command) + self._logger.info(message) + return self._emergency_force_send(command, message) + + if ( + self.state in ProtocolState.PROCESSING_STATES + and command.code in self.flavor.pausing_commands + ): + self._logger.info("Pausing print job due to command {}".format(command)) + self.pause_processing(tags=command.tags) + + if command.code in self.flavor.blocked_commands: + self._logger.info( + "Not sending {} to printer, it's configured as a blocked command".format( + command + ) + ) + return (None,) + + def _command_phase_sending(self, command, gcode=None): + if gcode is not None and gcode.code in self.flavor.long_running_commands: + self._internal_flags["long_running_command"] = True + + ##~~ autoreporting + + def _set_autoreport_temperature_interval(self, interval=None): + if interval is None: + try: + interval = int(self.interval.get("temperature_autoreport", 2)) + except Exception: + interval = 2 + self.send_commands( + self.flavor.command_autoreport_temperature(interval=interval), + tags={"trigger:set_autoreport_temperature_interval"}, + ) + + def _set_autoreport_sdstatus_interval(self, interval=None): + if interval is None: + try: + interval = int(self.interval.get("sd_status_autoreport", 1)) + except Exception: + interval = 1 + self.send_commands( + self.flavor.command_autoreport_sd_status(interval=interval), + tags={"trigger:protocol.set_autoreport_sdstatus_interval"}, + ) + + ##~~ busy protocol + + def _set_busy_protocol_interval(self, interval=None): + if interval is None: + try: + interval = max(int(self.timeouts.get("communication_busy", 3)) - 1, 1) + except Exception: + interval = 2 + self.send_commands( + self.flavor.command_busy_protocol_interval(interval), + tags={"trigger:protocol.set_busy_protocol_interval"}, + ) + + ##~~ helpers + + def _get_timeout(self, timeout_type): + if timeout_type in self.timeouts: + return monotonic_time() + self.timeouts[timeout_type] + else: + return monotonic_time() + + def _get_max_timeout(self, *offsets): + if len(offsets) == 0: + offsets = (0.0,) + return monotonic_time() + max(offsets) + + def _to_logfile_with_terminal(self, message=None, level=logging.INFO): + log = "Last lines in terminal:\n" + "\n".join( + map(lambda x: "| {}".format(x), list(self._terminal_log)) + ) + if message is not None: + log = message + "\n| " + log + self._logger.log(level, log) + + def _switch_flavor(self, new_flavor): + self.flavor = new_flavor.with_overrides(self.flavor_overrides) + + flavor_comm_attrs = self.get_flavor_attributes_starting_with(self.flavor, "comm_") + flavor_message_attrs = self.get_flavor_attributes_starting_with( + self.flavor, "message_" + ) + flavor_error_attrs = self.get_flavor_attributes_starting_with( + self.flavor, "error_" + ) + + self._comm_messages = flavor_comm_attrs + self._registered_messages = flavor_comm_attrs + flavor_message_attrs + self._current_registered_messages = self._registered_messages + self._error_messages = flavor_error_attrs + + def _trigger_error(self, text, reason, disconnect=True): + self.state = ProtocolState.ERROR + self._event_bus.fire(Events.ERROR, {"error": text, "reason": reason}) + if disconnect: + self.disconnect(error=True) diff --git a/src/octoprint/comm/protocol/reprap/commands/__init__.py b/src/octoprint/comm/protocol/reprap/commands/__init__.py index 21f30bb14..7a1dcef3d 100644 --- a/src/octoprint/comm/protocol/reprap/commands/__init__.py +++ b/src/octoprint/comm/protocol/reprap/commands/__init__.py @@ -1,7 +1,4 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" import copy @@ -11,83 +8,88 @@ from future.utils import with_metaclass from octoprint.util import pp - _compiled_regex_type = type(re.compile(r"a")) + + def _is_compiled_regex(obj): - return isinstance(obj, _compiled_regex_type) + return isinstance(obj, _compiled_regex_type) -__registry = dict() +__registry = {} + def _register_command_class(cls): - __registry[cls.__name__] = cls + __registry[cls.__name__] = cls def to_command(line, type=None, tags=None, **kwargs): - if isinstance(line, Command): - return line + if isinstance(line, Command): + return line - for cls in __registry.values(): - if cls.pattern: - # noinspection PyUnresolvedReferences,PyProtectedMember - if _is_compiled_regex(cls.pattern) and cls.pattern.match(line): - return cls.from_line(line, type=type, tags=tags, **kwargs) - elif callable(cls.pattern) and cls.pattern(line): - return cls.from_line(line, type=type, tags=tags, **kwargs) + for cls in __registry.values(): + if cls.pattern: + # noinspection PyUnresolvedReferences,PyProtectedMember + if _is_compiled_regex(cls.pattern) and cls.pattern.match(line): + return cls.from_line(line, type=type, tags=tags, **kwargs) + elif callable(cls.pattern) and cls.pattern(line): + return cls.from_line(line, type=type, tags=tags, **kwargs) - return Command.from_line(line, type=type, tags=tags, **kwargs) + return Command.from_line(line, type=type, tags=tags, **kwargs) class CommandMetaClass(type): - def __new__(mcs, *args, **kwargs): - c = type.__new__(mcs, *args, **kwargs) - _register_command_class(c) - return c + def __new__(mcs, *args, **kwargs): + c = type.__new__(mcs, *args, **kwargs) + _register_command_class(c) + return c + class Command(with_metaclass(CommandMetaClass, object)): - pattern = None + pattern = None - @classmethod - def from_line(cls, line, type=None, tags=None, **kwargs): - return cls(line, type=type, tags=tags, **kwargs) + @classmethod + def from_line(cls, line, type=None, tags=None, **kwargs): + return cls(line, type=type, tags=tags, **kwargs) - def __init__(self, line, type=None, tags=None, **kwargs): - if tags is None: - tags = set() + def __init__(self, line, type=None, tags=None, **kwargs): + if tags is None: + tags = set() - self.line = line - self.bytes = line.encode("ascii", errors="replace") - self.type = type - self.tags = tags + self.line = line + self.bytes = line.encode("ascii", errors="replace") + self.type = type + self.tags = tags - def __repr__(self): - return "{}({!r},type={!r},tags={})".format(self.__class__.__name__, self.line, self.type, pp(self.tags)) + def __repr__(self): + return "{}({!r},type={!r},tags={})".format( + self.__class__.__name__, self.line, self.type, pp(self.tags) + ) - def __str__(self): - return self.line + def __str__(self): + return self.line - def __bytes__(self): - return self.bytes + def __bytes__(self): + return self.bytes - def __key(self): - return self.line, self.type + def __key(self): + return self.line, self.type - def __eq__(self, other): - return self.__key() == other.__key() + def __eq__(self, other): + return self.__key() == other.__key() - def __hash__(self): - return hash(self.__key()) + def __hash__(self): + return hash(self.__key()) - def with_type(self, type): - c = copy.deepcopy(self) - c.type = type - return c + def with_type(self, type): + c = copy.deepcopy(self) + c.type = type + return c - def with_tags(self, tags): - if tags is None: - return self + def with_tags(self, tags): + if tags is None: + return self - c = copy.deepcopy(self) - c.tags |= tags - return c + c = copy.deepcopy(self) + c.tags |= tags + return c diff --git a/src/octoprint/comm/protocol/reprap/commands/atcommand.py b/src/octoprint/comm/protocol/reprap/commands/atcommand.py index 4637a5aa2..094bc7d9c 100644 --- a/src/octoprint/comm/protocol/reprap/commands/atcommand.py +++ b/src/octoprint/comm/protocol/reprap/commands/atcommand.py @@ -1,40 +1,34 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" from octoprint.comm.protocol.reprap.commands import Command - from octoprint.util import pp + class AtCommand(Command): - pattern = staticmethod(lambda x: x.startswith("@")) + pattern = staticmethod(lambda x: x.startswith("@")) - @staticmethod - def from_line(line, **kwargs): - split = line.split(None, 1) - if len(split) == 2: - atcommand = split[0] - parameters = split[1] - else: - atcommand = split[0] - parameters = "" + @staticmethod + def from_line(line, **kwargs): + split = line.split(None, 1) + if len(split) == 2: + atcommand = split[0] + parameters = split[1] + else: + atcommand = split[0] + parameters = "" - atcommand = atcommand[1:] + atcommand = atcommand[1:] - return AtCommand(line, atcommand, parameters, **kwargs) + return AtCommand(line, atcommand, parameters, **kwargs) - def __init__(self, line, atcommand, parameters, **kwargs): - self.atcommand = atcommand - self.parameters = parameters - super(AtCommand, self).__init__(line, **kwargs) - - def __repr__(self): - return "AtCommand({!r},{!r},{!r},type={!r},tags={}".format(self.line, - self.atcommand, - self.parameters, - self.type, - pp(self.tags)) + def __init__(self, line, atcommand, parameters, **kwargs): + self.atcommand = atcommand + self.parameters = parameters + super(AtCommand, self).__init__(line, **kwargs) + def __repr__(self): + return "AtCommand({!r},{!r},{!r},type={!r},tags={}".format( + self.line, self.atcommand, self.parameters, self.type, pp(self.tags) + ) diff --git a/src/octoprint/comm/protocol/reprap/commands/gcode.py b/src/octoprint/comm/protocol/reprap/commands/gcode.py index 750501e61..219a8d721 100644 --- a/src/octoprint/comm/protocol/reprap/commands/gcode.py +++ b/src/octoprint/comm/protocol/reprap/commands/gcode.py @@ -1,147 +1,162 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" -from octoprint.comm.protocol.reprap.commands import Command - import re import string +from octoprint.comm.protocol.reprap.commands import Command from octoprint.util import pp + class GcodeCommand(Command): - pattern = staticmethod(lambda x: GcodeCommand.command_regex.match(x)) + pattern = staticmethod(lambda x: GcodeCommand.command_regex.match(x)) - command_regex = re.compile(r"^\s*((?P[GM](?P\d+))(\\.(?P\d+))?|(?PT(?P\d+))|(?PF(?P\d+)))") - parameter_regex = re.compile(r"(?P[A-Z])((?P[-+]?[0-9]*\.?[0-9]+)(?!\d)|(\s|$))") + command_regex = re.compile( + r"^\s*((?P[GM](?P\d+))(\\.(?P\d+))?|(?PT(?P\d+))|(?PF(?P\d+)))" + ) + parameter_regex = re.compile( + r"(?P[A-Z])((?P[-+]?[0-9]*\.?[0-9]+)(?!\d)|(\s|$))" + ) - possible_params = tuple(string.ascii_lowercase) + ("subcode", "param", "tool", "feedrate", "original") + possible_params = tuple(string.ascii_lowercase) + ( + "subcode", + "param", + "tool", + "feedrate", + "original", + ) - @staticmethod - def from_line(line, **kwargs): - if isinstance(line, GcodeCommand): - return line + @staticmethod + def from_line(line, **kwargs): + if isinstance(line, GcodeCommand): + return line - tags = kwargs.get("tags") - if tags is None: - tags = set() + tags = kwargs.get("tags") + if tags is None: + tags = set() - command_type = kwargs.get("type") + command_type = kwargs.get("type") - line = line.strip() - code = "" + line = line.strip() + code = "" - args = dict(original=line, type=command_type, tags=tags) + args = {"original": line, "type": command_type, "tags": tags} - match = GcodeCommand.command_regex.match(line) + match = GcodeCommand.command_regex.match(line) - if match is None: - # not a gcode command - return Command.from_line(line, **kwargs) + if match is None: + # not a gcode command + return Command.from_line(line, **kwargs) - if match.group("GM"): - code = match.group("GM") + if match.group("GM"): + code = match.group("GM") - if match.group("subcode"): - args["subcode"] = int(match.group("subcode")) + if match.group("subcode"): + args["subcode"] = int(match.group("subcode")) - if match.group(0) != line: - rest = line[len(match.group(0)):] + if match.group(0) != line: + rest = line[len(match.group(0)) :] - while True: - matched_param = GcodeCommand.parameter_regex.search(rest) - if not matched_param: - break + while True: + matched_param = GcodeCommand.parameter_regex.search(rest) + if not matched_param: + break - key = matched_param.group("key").lower() - if matched_param.group("value"): - value = matched_param.group("value") - if "." in value: - value = float(value) - else: - value = int(value) - else: - value = True - args[key] = value - rest = rest[:matched_param.start()] + rest[matched_param.end():] + key = matched_param.group("key").lower() + if matched_param.group("value"): + value = matched_param.group("value") + if "." in value: + value = float(value) + else: + value = int(value) + else: + value = True + args[key] = value + rest = rest[: matched_param.start()] + rest[matched_param.end() :] - rest = rest.lstrip() - if rest: - args["param"] = rest + rest = rest.lstrip() + if rest: + args["param"] = rest - elif match.group("T"): - code = "T" - args["tool"] = int(match.group("tool")) + elif match.group("T"): + code = "T" + args["tool"] = int(match.group("tool")) - elif match.group("F"): - code = "F" - args["feedrate"] = int(match.group("feedrate")) + elif match.group("F"): + code = "F" + args["feedrate"] = int(match.group("feedrate")) - return GcodeCommand(code, **args) + return GcodeCommand(code, **args) - def __init__(self, code, **kwargs): - self.code = code + def __init__(self, code, **kwargs): + self.code = code - self.subcode = kwargs.pop("subcode", None) - self.tool = kwargs.pop("tool", None) - self.feedrate = kwargs.pop("feedrate", None) - self.param = kwargs.pop("param", None) - self.original = kwargs.pop("original", None) + self.subcode = kwargs.pop("subcode", None) + self.tool = kwargs.pop("tool", None) + self.feedrate = kwargs.pop("feedrate", None) + self.param = kwargs.pop("param", None) + self.original = kwargs.pop("original", None) - command_type = kwargs.pop("type", None) - tags = kwargs.pop("tags", None) + command_type = kwargs.pop("type", None) + tags = kwargs.pop("tags", None) - self.args = kwargs + self.args = kwargs - if self.original is None: - line = self._to_line() - else: - line = self.original + if self.original is None: + line = self._to_line() + else: + line = self.original - super(GcodeCommand, self).__init__(line, type=command_type, tags=tags) + super(GcodeCommand, self).__init__(line, type=command_type, tags=tags) - self._repr = self._to_repr() + self._repr = self._to_repr() - def with_args(self, **kwargs): - args = dict(subcode=self.subcode, - tool=self.tool, - feedrate=self.feedrate, - param=self.param, - type=self.type, - tags=self.tags) - args.update(self.args) + def with_args(self, **kwargs): + args = { + "subcode": self.subcode, + "tool": self.tool, + "feedrate": self.feedrate, + "param": self.param, + "type": self.type, + "tags": self.tags, + } + args.update(self.args) - args.update(kwargs) + args.update(kwargs) - return GcodeCommand(self.code, **args) + return GcodeCommand(self.code, **args) - def __getattr__(self, item): - if len(item) == 1: - return self.args.get(item, None) - raise AttributeError("'GcodeCommand' object has no attribute '{}'".format(item)) + def __getattr__(self, item): + if len(item) == 1: + return self.args.get(item, None) + raise AttributeError("'GcodeCommand' object has no attribute '{}'".format(item)) - def __repr__(self): - return self._repr + def __repr__(self): + return self._repr - def _to_line(self): - attr = [] - for key in string.ascii_lowercase: - value = self.args.get(key, None) - if value is not None: - if value is True: - attr.append(key.upper()) - else: - attr.append("{}{!r}".format(key.upper(), value)) - attribute_str = " ".join(attr) - return "{}{}{}".format(self.code.upper(), " " + attribute_str if attribute_str else "", - " " + self.param if self.param else "") + def _to_line(self): + attr = [] + for key in string.ascii_lowercase: + value = self.args.get(key, None) + if value is not None: + if value is True: + attr.append(key.upper()) + else: + attr.append("{}{!r}".format(key.upper(), value)) + attribute_str = " ".join(attr) + return "{}{}{}".format( + self.code.upper(), + " " + attribute_str if attribute_str else "", + " " + self.param if self.param else "", + ) - def _to_repr(self): - args = [k + "=" + repr(getattr(self, k)) for k in self.possible_params if getattr(self, k, None) is not None] - return "GcodeCommand({!r}{},type={!r},tags={})".format(self.code, - "," + ",".join(args) if args else "", - self.type, - pp(self.tags)) + def _to_repr(self): + args = [ + k + "=" + repr(getattr(self, k)) + for k in self.possible_params + if getattr(self, k, None) is not None + ] + return "GcodeCommand({!r}{},type={!r},tags={})".format( + self.code, "," + ",".join(args) if args else "", self.type, pp(self.tags) + ) diff --git a/src/octoprint/comm/protocol/reprap/flavors/__init__.py b/src/octoprint/comm/protocol/reprap/flavors/__init__.py index 5105b7ad2..fc13e89fd 100644 --- a/src/octoprint/comm/protocol/reprap/flavors/__init__.py +++ b/src/octoprint/comm/protocol/reprap/flavors/__init__.py @@ -1,44 +1,39 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" -from .generic import * # noqa: F403 -from .klipper import * # noqa: F403 -from .marlin import * # noqa: F403 -from .repetier import * # noqa: F403 -from .reprapfirmware import * # noqa: F403 -from .smoothieware import * # noqa: F403 - -from .anet import * # noqa: F403 -from .malyan import * # noqa: F403 +from .anet import * # noqa: F401,F403 +from .generic import * # noqa: F401,F403 +from .klipper import * # noqa: F401,F403 +from .malyan import * # noqa: F401,F403 +from .marlin import * # noqa: F401,F403 +from .repetier import * # noqa: F401,F403 +from .reprapfirmware import * # noqa: F401,F403 +from .smoothieware import * # noqa: F401,F403 class FlavorOverride(object): + def __init__(self, flavor, overrides): + self._flavor = flavor + self._overrides = overrides - def __init__(self, flavor, overrides): - self._flavor = flavor - self._overrides = overrides + @property + def flavor(self): + return self._flavor - @property - def flavor(self): - return self._flavor + @flavor.setter + def flavor(self, value): + self._flavor = value - @flavor.setter - def flavor(self, value): - self._flavor = value + @property + def overrides(self): + return self._overrides - @property - def overrides(self): - return self._overrides + @overrides.setter + def overrides(self, value): + self._overrides = value - @overrides.setter - def overrides(self, value): - self._overrides = value - - def __getattr__(self, item): - try: - return self._overrides[item] - except KeyError: - return getattr(self._flavor, item) + def __getattr__(self, item): + try: + return self._overrides[item] + except KeyError: + return getattr(self._flavor, item) diff --git a/src/octoprint/comm/protocol/reprap/flavors/anet.py b/src/octoprint/comm/protocol/reprap/flavors/anet.py index 705908c0a..9f6dfddf9 100644 --- a/src/octoprint/comm/protocol/reprap/flavors/anet.py +++ b/src/octoprint/comm/protocol/reprap/flavors/anet.py @@ -1,17 +1,14 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" from .repetier import RepetierFlavor + class AnetA8RepetierFlavor(RepetierFlavor): - key = "aneta8repetier" - name = "Anet A8" - - @classmethod - def identifier(cls, firmware_name, firmware_info): - return "anet_a8" in firmware_name.lower() + key = "aneta8repetier" + name = "Anet A8" + @classmethod + def identifier(cls, firmware_name, firmware_info): + return "anet_a8" in firmware_name.lower() diff --git a/src/octoprint/comm/protocol/reprap/flavors/generic.py b/src/octoprint/comm/protocol/reprap/flavors/generic.py index baf4d1297..9c722e61c 100644 --- a/src/octoprint/comm/protocol/reprap/flavors/generic.py +++ b/src/octoprint/comm/protocol/reprap/flavors/generic.py @@ -1,754 +1,818 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" -import re import logging -import time - -from octoprint.comm.protocol.reprap.commands.gcode import GcodeCommand -from octoprint.comm.protocol.reprap.util import regex_float_pattern, regex_positive_float_pattern, regex_int_pattern - -from octoprint.util import chunks, monotonic_time +import re from future.utils import with_metaclass +from octoprint.comm.protocol.reprap.commands.gcode import GcodeCommand +from octoprint.comm.protocol.reprap.util import ( + regex_float_pattern, + regex_int_pattern, + regex_positive_float_pattern, +) +from octoprint.util import chunks, monotonic_time -_flavor_registry = dict() +_flavor_registry = {} def _register_flavor(cls): - key = getattr(cls, "key", None) - if key and not key in _flavor_registry: - _flavor_registry[key] = cls + key = getattr(cls, "key", None) + if key and key not in _flavor_registry: + _flavor_registry[key] = cls def all_flavors(): - return _flavor_registry.values() + return _flavor_registry.values() def lookup_flavor(key): - return _flavor_registry.get(key) + return _flavor_registry.get(key) class FlavorMeta(type): - def __new__(mcs, name, bases, class_dict): - cls = type.__new__(mcs, name, bases, class_dict) - _register_flavor(cls) - return cls + def __new__(mcs, name, bases, class_dict): + cls = type.__new__(mcs, name, bases, class_dict) + _register_flavor(cls) + return cls class GenericFlavor(with_metaclass(FlavorMeta, object)): - key = "generic" - name = "Generic Flavor" + key = "generic" + name = "Generic Flavor" - logger = logging.getLogger(__name__) - - unknown_requires_ack = False - unknown_with_checksum = False - - send_checksum = "printing" - - detect_external_heatups = True - block_while_dwelling = False - - trigger_ok_after_resend = "detect" - - sd_relative_path = False - sd_always_available = False - - checksum_requiring_commands = ["M110"] - long_running_commands = ["G4", "G28", "G29", "G30", "G32", "M190", "M109", "M400", "M226"] - asynchronous_commands = ["G0", "G1", "G2", "G3"] - blocked_commands = ["M0", "M1"] - pausing_commands = ["M0", "M1", "M25"] - emergency_commands = ["M112", "M108", "M410"] - - heatup_abortable = False - - regex_min_max_error = re.compile(r"Error:[0-9]\n") - """Regex matching first line of min/max errors from legacy firmware.""" - - regex_resend_linenumber = re.compile(r"(N|N:)?(?P%s)" % regex_int_pattern) - """Regex to use for request line numbers in resend requests""" - - regex_temp = re.compile(r"(?PB|T(?P\d*)):\s*(?P%s)(\s*/?\s*(?P%s))?" % ( - regex_positive_float_pattern, regex_positive_float_pattern)) - """Regex matching temperature entries in line. - - Groups will be as follows: - - * ``tool``: whole tool designator, incl. optional ``toolnum`` (str) - * ``toolnum``: tool number, if provided (int) - * ``actual``: actual temperature (float) - * ``target``: target temperature, if provided (float) - """ - - regex_position = re.compile(r"(?P[XYZE]):(?P{float})\s*".format(float=regex_float_pattern)) - """Regex for matching position entries in line. - - Groups will be as follows: - - * ``axis``: axis designator, either ``X``, ``Y``, ``Z`` or ``E`` (str) - * ``pos``: axis position (float) - """ - - regex_firmware_splitter = re.compile(r"\s*([A-Z0-9_]+):") - """Regex to use for splitting M115 responses.""" - - regex_sd_file_opened = re.compile(r"file opened:\s*(?P.*?)(\s+size:\s*(?P[0-9]+)|$)") - - regex_sd_printing_byte = re.compile(r"sd printing byte (?P[0-9]*)/(?P[0-9]*)") - """Regex matching SD printing status reports. - - Groups will be as follows: - - * ``current``: current byte position in file being printed - * ``total``: total size of file being printed - """ - - ##~~ Overrides - - _overrides = dict() - - @classmethod - def with_overrides(cls, overrides): - return type(b"{}WithOverrides".format(cls.__name__), (cls,), overrides) - - @classmethod - def overridable(cls): - return dict(unknown_requires_ack=cls.unknown_requires_ack, - unknown_with_checksum=cls.unknown_with_checksum, - send_checksum=cls.send_checksum, - detect_external_heatups=cls.detect_external_heatups, - block_while_dwelling=cls.block_while_dwelling, - trigger_ok_after_resend=cls.trigger_ok_after_resend, - sd_relative_path=cls.sd_relative_path, - checksum_requiring_commands=cls.checksum_requiring_commands, - long_running_commands=cls.long_running_commands, - asynchronous_commands=cls.asynchronous_commands, - blocked_commands=cls.blocked_commands, - pausing_commands=cls.pausing_commands, - emergency_commands=cls.emergency_commands, - heatup_abortable=cls.heatup_abortable) - - ##~~ Identifier - - @classmethod - def identifier(cls, firmware_name, firmware_info): - return False - - ##~~ Message matchers - - @classmethod - def comm_timeout(cls, line, lower_line, state, flags): - now = monotonic_time() - matches = ((line == "" and now > flags["timeout"]) or (flags["expect_continous_comms"] - and not flags["job_on_hold"] - and not flags["long_running_command"] - and not flags["heating"] - and now > flags["ok_timeout"])) and \ - (not cls.block_while_dwelling or not flags["dwelling_until"] or now > flags["dwelling_until"]) - continue_further = line != "" - return matches, continue_further - - @classmethod - def comm_ok(cls, line, lower_line, state, flags): - matches = lower_line.startswith("ok") - continue_further = not matches \ - or cls.message_temperature(line, lower_line, state, flags) \ - or cls.message_position(line, lower_line, state, flags) \ - or cls.message_firmware_info(line, lower_line, state, flags) - return matches, continue_further - - @classmethod - def comm_start(cls, line, lower_line, state, flags): - return lower_line == "start" - - @classmethod - def comm_wait(cls, line, lower_line, state, flags): - return lower_line == "wait" - - @classmethod - def comm_resend(cls, line, lower_line, state, flags): - return lower_line.startswith("resend") or lower_line.startswith("rs") - - @classmethod - def comm_action_command(cls, line, lower_line, state, flags): - return line.startswith("//") and line[2:].strip().startswith("action:") - - @classmethod - def comm_error(cls, line, lower_line, state, flags): - single_line = line.startswith("Error:") or line.startswith("!!") - multi_line = flags.get("multiline_error", False) is not False - - if cls.regex_min_max_error.match(line): - flags["multiline_error"] = line - - return single_line or multi_line - - @classmethod - def comm_ignore_ok(cls, line, lower_line, state, flags): - return False - - @classmethod - def comm_busy(cls, line, lower_line, state, flags): - return line.startswith("echo:busy:") or line.startswith("busy:") - - @classmethod - def error_communication(cls, line, lower_line, error, state, flags): - return any(map(lambda x: x in lower_line, ("line number", - "checksum", - "format error", - "expected line"))) - - @classmethod - def error_sdcard(cls, line, lower_line, error, state, flags): - return any(map(lambda x: x in lower_line, ("volume.init", - "openroot", - "workdir", - "error writing to file", - "cannot open", - "open failed", - "cannot enter"))) - - @classmethod - def error_fatal(cls, line, lower_line, error, state, flags): - return any(map(lambda x: x in lower_line, ("kill() called", - "fatal:"))) - - @classmethod - def message_temperature(cls, line, lower_line, state, flags): - return "T:" in line or "T0:" in line or "B:" in line - - @classmethod - def message_position(cls, line, lower_line, state, flags): - return 'X:' in line and 'Y:' in line and 'Z:' in line - - @classmethod - def message_firmware_info(cls, line, lower_line, state, flags): - return "NAME:" in line - - @classmethod - def message_firmware_capability(cls, line, lower_line, state, flags): - return lower_line.startswith("cap:") - - @classmethod - def message_sd_init_ok(cls, line, lower_line, state, flags): - return "sd card ok" in lower_line - - @classmethod - def message_sd_init_fail(cls, line, lower_line, state, flags): - return "sd init fail" in lower_line or "volume.init failed" in lower_line or "openroot failed" in lower_line - - @classmethod - def message_sd_file_opened(cls, line, lower_line, state, flags): - return lower_line.startswith("file opened") - - @classmethod - def message_sd_file_selected(cls, line, lower_line, state, flags): - return lower_line.startswith("file selected") - - @classmethod - def message_sd_begin_file_list(cls, line, lower_line, state, flags): - return lower_line.startswith("begin file list") - - @classmethod - def message_sd_end_file_list(cls, line, lower_line, state, flags): - return lower_line.startswith("end file list") - - @classmethod - def message_sd_printing_byte(cls, line, lower_line, state, flags): - return "sd printing byte" in lower_line - - @classmethod - def message_sd_not_printing(cls, line, lower_line, state, flags): - return "not sd printing" in lower_line - - @classmethod - def message_sd_done_printing(cls, line, lower_line, state, flags): - return "done printing file" in lower_line - - @classmethod - def message_sd_begin_writing(cls, line, lower_line, state, flags): - return "writing to file" in lower_line - - @classmethod - def message_sd_end_writing(cls, line, lower_line, state, flags): - return "done saving file" in lower_line - - @classmethod - def message_sd_entry(cls, line, lower_line, state, flags): - return flags["sd_files_temp"] is not None - - ##~~ Message parsers - - @classmethod - def parse_comm_error(cls, line, lower_line, state, flags): - multiline = flags.get("multiline_error", False) - if multiline: - flags["multiline_error"] = False - line = line.rstrip() + " - " + multiline - lower_line = line.lower() - - error = (line[6:] if lower_line.startswith("error:") else line[2:]).strip() - return dict(line=line, lower_line=lower_line, error=error) - - @classmethod - def parse_comm_timeout(cls, line, lower_line, state, flags): - return dict(line=line, lower_line=lower_line) - - @classmethod - def parse_comm_action_command(cls, line, lower_line, state, flags): - action = line[2:].strip()[len("action:"):].strip() - return dict(line=line, lower_line=lower_line, action=action) - - @classmethod - def parse_error_communication(cls, line, lower_line, error, state, flags): - if "line number" in lower_line or "expected line" in lower_line: - error_type = "linenumber" - elif "checksum" in lower_line: - error_type = "checksum" - else: - error_type = "other" - - flags["last_communication_error"] = error_type - return dict(error_type=error_type) - - @classmethod - def parse_comm_resend(cls, line, lower_line, state, flags): - line_to_resend = None - match = cls.regex_resend_linenumber.search(line) - if match is not None: - line_to_resend = int(match.group("n")) - return dict(linenumber=line_to_resend) - - @classmethod - def parse_message_temperature(cls, line, lower_line, state, flags): - """ - Parses the provided temperature line. - - The result will be a dictionary mapping from the extruder or bed key to - a tuple with current and target temperature. The result will be canonicalized - with :func:`canonicalize_temperatures` before returning. - - Returns: - tuple: a 2-tuple with the maximum tool number and a dict mapping from - key to (actual, target) tuples, with key either matching ``Tn`` for ``n >= 0`` or ``B`` - """ - - current_tool = flags["current_tool"] - - result = {} - max_tool_num = 0 - for match in re.finditer(cls.regex_temp, line): - values = match.groupdict() - tool = values["tool"] - if tool == "T" and "toolnum" in values and values["toolnum"]: - tool_num = int(values["toolnum"]) - if tool_num > max_tool_num: - max_tool_num = tool_num - - try: - actual = float(values.get("actual", None)) if values.get("actual", None) is not None else None - target = float(values.get("target", None)) if values.get("target", None) is not None else None - result[tool] = actual, target - except ValueError: - # catch conversion issues, we'll rather just not get the temperature update instead of killing the connection - pass - - heatup_detected = not lower_line.startswith("ok") and not flags["heating"] and not flags["temperature_autoreporting"] - - return dict(max_tool_num=max(max_tool_num, current_tool), - temperatures=cls._canonicalize_temperatures(result, current_tool), - heatup_detected=heatup_detected) - - @classmethod - def parse_message_position(cls, line, lower_line, state, flags): - position = dict(x=None, y=None, z=None, e=None) - for match in re.finditer(cls.regex_position, line): - position[match.group("axis").lower()] = float(match.group("pos")) - return dict(position=position) - - @classmethod - def parse_message_firmware_info(cls, line, lower_line, state, flags): - data = cls._parse_firmware_line(line) - firmware_name = data.get("FIRMWARE_NAME") - - if firmware_name is None: - # Malyan's "Marlin compatible firmware" isn't actually Marlin compatible and doesn't even - # report its firmware name properly in response to M115. Wonderful - why stick to established - # protocol when you can do your own thing, right? - # - # Example: NAME: Malyan VER: 2.9 MODEL: M200 HW: HA02 - # - # We do a bit of manual fiddling around here to circumvent that issue and get ourselves a - # reliable firmware name (NAME + VER) out of the Malyan M115 response. - name = data.get("NAME") - ver = data.get("VER") - if "malyan" in name.lower() and ver: - firmware_name = name.strip() + " " + ver.strip() - - if firmware_name is not None: - firmware_name = firmware_name.strip() - - return dict(firmware_name=firmware_name, - data=data) - - @classmethod - def parse_message_firmware_capability(cls, line, lower_line, state, flags): - result = cls._parse_capability_line(line) - if not result: - return - cap, enabled = result - return dict(cap=cap, enabled=enabled) - - @classmethod - def parse_message_sd_file_opened(cls, line, lower_line, state, flags): - match = cls.regex_sd_file_opened.match(lower_line) - if not match: - return - - name = match.group("name") - size = int(match.group("size")) - return dict(name=name, long_name=name, size=size) - - @classmethod - def parse_message_sd_entry(cls, line, lower_line, state, flags): - fileinfo = lower_line.rsplit(None, 1) - if len(fileinfo) > 1: - # we might have extended file information here, so let's split filename and size and try to make them a bit nicer - filename, size = fileinfo - try: - size = int(size) - except ValueError: - # whatever that was, it was not an integer, so we'll just use the whole line as filename and set size to None - filename = lower_line - size = None - else: - # no extended file information, so only the filename is there and we set size to None - filename = lower_line - size = None - - from octoprint.util import filter_non_ascii - - if filter_non_ascii(filename): - return None - else: - if not filename.startswith("/"): - # file from the root of the sd -- we'll prepend a / - filename = "/" + filename - - return dict(name=filename, long_name=filename, size=int(size) if size is not None else None) - - @classmethod - def parse_message_sd_printing_byte(cls, line, lower_line, state, flags): - match = cls.regex_sd_printing_byte.match(lower_line) - if not match: - return None - return dict(current=int(match.group("current")), total=int(match.group("total"))) - - ##~~ Commands - - @classmethod - def command_hello(cls): - return cls.command_set_line(0) - - @classmethod - def command_get_firmware_info(cls): - return GcodeCommand("M115") - - @classmethod - def command_finish_moving(cls): - return GcodeCommand("M400") - - @classmethod - def command_get_position(cls): - return GcodeCommand("M114") - - @classmethod - def command_get_temp(cls): - return GcodeCommand("M105") - - @classmethod - def command_set_line(cls, n): - return GcodeCommand("M110", n=n) - - @classmethod - def command_emergency_stop(cls): - return GcodeCommand("M112") - - @classmethod - def command_abort_heatup(cls): - return GcodeCommand("M108") - - @classmethod - def command_set_extruder_temp(cls, temperature, tool=None, wait=False): - command = "M109" if wait else "M104" - args = dict(s=temperature) - if tool is not None: - args["t"] = tool - return GcodeCommand(command, **args) - - @classmethod - def command_set_bed_temp(cls, temperature, wait=False): - return GcodeCommand("M190" if wait else "M140", s=temperature) - - @classmethod - def command_set_chamber_temp(cls, temperature, wait=False): - return GcodeCommand("M191" if wait else "M141", s=temperature) - - @classmethod - def command_set_relative_positioning(cls): - return GcodeCommand("G91") - - @classmethod - def command_set_absolute_positioning(cls): - return GcodeCommand("G90") - - @classmethod - def command_move(cls, x=None, y=None, z=None, e=None, f=None): - return GcodeCommand("G1", x=x, y=y, z=z, e=e, f=f) - - @classmethod - def command_extrude(cls, e=None, f=None): - return cls.command_move(e=e, f=f) - - @classmethod - def command_home(cls, x=False, y=False, z=False): - return GcodeCommand("G28", x=0 if x else None, y=0 if y else None, z=0 if z else None) - - @classmethod - def command_set_tool(cls, tool): - return GcodeCommand("T{}".format(tool)) - - @classmethod - def command_set_feedrate_multiplier(cls, multiplier): - return GcodeCommand("M220", s=multiplier) - - @classmethod - def command_set_extrusion_multiplier(cls, multiplier): - return GcodeCommand("M221", s=multiplier) - - @classmethod - def command_set_fan_speed(cls, speed): - return GcodeCommand("M106", s=speed) - - @classmethod - def command_set_motors(cls, enable): - return GcodeCommand("M17") if enable else GcodeCommand("M18") - - @classmethod - def command_sd_refresh(cls): - return GcodeCommand("M20") - - @classmethod - def command_sd_init(cls): - return GcodeCommand("M21") - - @classmethod - def command_sd_release(cls): - return GcodeCommand("M22") - - @classmethod - def command_sd_select_file(cls, name): - return GcodeCommand("M23", param=name) - - @classmethod - def command_sd_start(cls): - return GcodeCommand("M24") - - @classmethod - def command_sd_pause(cls): - return GcodeCommand("M25") - - @classmethod - def command_sd_resume(cls): - return GcodeCommand("M24") - - @classmethod - def command_sd_set_pos(cls, pos): - return GcodeCommand("M26", s=pos) - - @classmethod - def command_sd_status(cls): - return GcodeCommand("M27") - - @classmethod - def command_sd_begin_write(cls, name): - return GcodeCommand("M28", param=name) - - @classmethod - def command_sd_end_write(cls): - return GcodeCommand("M29") - - @classmethod - def command_sd_delete(cls, name): - return GcodeCommand("M30", param=name) - - @classmethod - def command_autoreport_temperature(cls, interval): - return GcodeCommand("M155", s=interval) - - @classmethod - def command_autoreport_sd_status(cls, interval): - return GcodeCommand("M27", s=interval) - - @classmethod - def command_busy_protocol_interval(cls, interval): - return GcodeCommand("M113", s=interval) - - ##~~ Helpers - - @classmethod - def _canonicalize_temperatures(cls, parsed, current): - """ - Canonicalizes the temperatures provided in parsed. - - Will make sure that returned result only contains extruder keys - like Tn, so always qualified with a tool number. - - The algorithm for cleaning up the parsed keys is the following: - - * If ``T`` is not included with the reported extruders, return - * If more than just ``T`` is reported: - * If both ``T`` and ``T0`` are reported set ``Tc`` to ``T``, remove - ``T`` from the result. - * Else set ``T0`` to ``T`` and delete ``T`` (Smoothie extra). - * If only ``T`` is reported, set ``Tc`` to ``T`` and delete ``T`` - * return - - Arguments: - parsed (dict): the parsed temperatures (mapping tool => (actual, target)) - to canonicalize - current (int): the current active extruder - Returns: - dict: the canonicalized version of ``parsed`` - """ - - reported_extruders = list(filter(lambda x: x.startswith("T"), parsed.keys())) - if not "T" in reported_extruders: - # Our reported_extruders are either empty or consist purely - # of Tn keys, no need for any action - return parsed - - current_tool_key = "T%d" % current - result = dict(parsed) - - if len(reported_extruders) > 1: - if "T0" in reported_extruders: - # Both T and T0 are present, so T contains the current - # extruder's temperature, e.g. for current_tool == 1: - # - # T: T0: T2: ... B: - # - # becomes - # - # T0: T1: T2: ... B: - # - # Same goes if Tc is already present, it will be overwritten: - # - # T: T0: T1: T2: ... B: - # - # becomes - # - # T0: T1: T2: ... B: - result[current_tool_key] = result["T"] - del result["T"] - else: - # So T is there, but T0 isn't. That looks like Smoothieware which - # always reports the first extruder T0 as T: - # - # T: T1: T2: ... B: - # - # becomes - # - # T0: T1: T2: ... B: - result["T0"] = result["T"] - del result["T"] - - else: - # We only have T. That can mean two things: - # - # * we only have one extruder at all, or - # * we are currently parsing a response to M109/M190, which on - # some firmwares doesn't report the full M105 output while - # waiting for the target temperature to be reached but only - # reports the current tool and bed - # - # In both cases it is however safe to just move our T over - # to T in the parsed data, current should always stay - # 0 for single extruder printers. E.g. for current_tool == 1: - # - # T: - # - # becomes - # - # T1: - - result[current_tool_key] = result["T"] - del result["T"] - - return result - - @classmethod - def _parse_firmware_line(cls, line): - """ - Parses the provided firmware info line. - - The result will be a dictionary mapping from the contained keys to the contained - values. - - Arguments: - line (unicode): the line to parse - - Returns: - dict: a dictionary with the parsed data - """ - - result = dict() - split_line = cls.regex_firmware_splitter.split(line.strip())[1:] # first entry is empty start of trimmed string - for key, value in chunks(split_line, 2): - result[key] = value - return result - - @classmethod - def _parse_capability_line(cls, line): - """ - Parses the provided firmware capability line. - - Lines are expected to be of the format - - Cap::<0 or 1> - - e.g. - - Cap:AUTOREPORT_TEMP:1 - Cap:TOGGLE_LIGHTS:0 - - Args: - line (unicode): the line to parse - - Returns: - tuple: a 2-tuple of the parsed capability name and whether it's on (true) or off (false), or None if the line - could not be parsed - """ - - line = line.lower() - if line.startswith("cap:"): - line = line[len("cap:"):] - - parts = line.split(":") - if len(parts) != 2: - # wrong format, can't parse this - return None - - capability, flag = parts - if not flag in ("0", "1"): - # wrong format, can't parse this - return None - - return capability.upper(), flag == "1" + logger = logging.getLogger(__name__) + + unknown_requires_ack = False + unknown_with_checksum = False + + send_checksum = "printing" + + detect_external_heatups = True + block_while_dwelling = False + + trigger_ok_after_resend = "detect" + + sd_relative_path = False + sd_always_available = False + + checksum_requiring_commands = ["M110"] + long_running_commands = [ + "G4", + "G28", + "G29", + "G30", + "G32", + "M190", + "M109", + "M400", + "M226", + ] + asynchronous_commands = ["G0", "G1", "G2", "G3"] + blocked_commands = ["M0", "M1"] + pausing_commands = ["M0", "M1", "M25"] + emergency_commands = ["M112", "M108", "M410"] + + heatup_abortable = False + + regex_min_max_error = re.compile(r"Error:[0-9]\n") + """Regex matching first line of min/max errors from legacy firmware.""" + + regex_resend_linenumber = re.compile(r"(N|N:)?(?P%s)" % regex_int_pattern) + """Regex to use for request line numbers in resend requests""" + + regex_temp = re.compile( + r"(?PB|T(?P\d*)):\s*(?P%s)(\s*/?\s*(?P%s))?" + % (regex_positive_float_pattern, regex_positive_float_pattern) + ) + """Regex matching temperature entries in line. + + Groups will be as follows: + + * ``tool``: whole tool designator, incl. optional ``toolnum`` (str) + * ``toolnum``: tool number, if provided (int) + * ``actual``: actual temperature (float) + * ``target``: target temperature, if provided (float) + """ + + regex_position = re.compile( + r"(?P[XYZE]):(?P{float})\s*".format(float=regex_float_pattern) + ) + """Regex for matching position entries in line. + + Groups will be as follows: + + * ``axis``: axis designator, either ``X``, ``Y``, ``Z`` or ``E`` (str) + * ``pos``: axis position (float) + """ + + regex_firmware_splitter = re.compile(r"\s*([A-Z0-9_]+):") + """Regex to use for splitting M115 responses.""" + + regex_sd_file_opened = re.compile( + r"file opened:\s*(?P.*?)(\s+size:\s*(?P[0-9]+)|$)" + ) + + regex_sd_printing_byte = re.compile( + r"sd printing byte (?P[0-9]*)/(?P[0-9]*)" + ) + """Regex matching SD printing status reports. + + Groups will be as follows: + + * ``current``: current byte position in file being printed + * ``total``: total size of file being printed + """ + + ##~~ Overrides + + _overrides = {} + + @classmethod + def with_overrides(cls, overrides): + return type(b"{}WithOverrides".format(cls.__name__), (cls,), overrides) + + @classmethod + def overridable(cls): + return { + "unknown_requires_ack": cls.unknown_requires_ack, + "unknown_with_checksum": cls.unknown_with_checksum, + "send_checksum": cls.send_checksum, + "detect_external_heatups": cls.detect_external_heatups, + "block_while_dwelling": cls.block_while_dwelling, + "trigger_ok_after_resend": cls.trigger_ok_after_resend, + "sd_relative_path": cls.sd_relative_path, + "checksum_requiring_commands": cls.checksum_requiring_commands, + "long_running_commands": cls.long_running_commands, + "asynchronous_commands": cls.asynchronous_commands, + "blocked_commands": cls.blocked_commands, + "pausing_commands": cls.pausing_commands, + "emergency_commands": cls.emergency_commands, + "heatup_abortable": cls.heatup_abortable, + } + + ##~~ Identifier + + @classmethod + def identifier(cls, firmware_name, firmware_info): + return False + + ##~~ Message matchers + + @classmethod + def comm_timeout(cls, line, lower_line, state, flags): + now = monotonic_time() + matches = ( + (line == "" and now > flags["timeout"]) + or ( + flags["expect_continous_comms"] + and not flags["job_on_hold"] + and not flags["long_running_command"] + and not flags["heating"] + and now > flags["ok_timeout"] + ) + ) and ( + not cls.block_while_dwelling + or not flags["dwelling_until"] + or now > flags["dwelling_until"] + ) + continue_further = line != "" + return matches, continue_further + + @classmethod + def comm_ok(cls, line, lower_line, state, flags): + matches = lower_line.startswith("ok") + continue_further = ( + not matches + or cls.message_temperature(line, lower_line, state, flags) + or cls.message_position(line, lower_line, state, flags) + or cls.message_firmware_info(line, lower_line, state, flags) + ) + return matches, continue_further + + @classmethod + def comm_start(cls, line, lower_line, state, flags): + return lower_line == "start" + + @classmethod + def comm_wait(cls, line, lower_line, state, flags): + return lower_line == "wait" + + @classmethod + def comm_resend(cls, line, lower_line, state, flags): + return lower_line.startswith("resend") or lower_line.startswith("rs") + + @classmethod + def comm_action_command(cls, line, lower_line, state, flags): + return line.startswith("//") and line[2:].strip().startswith("action:") + + @classmethod + def comm_error(cls, line, lower_line, state, flags): + single_line = line.startswith("Error:") or line.startswith("!!") + multi_line = flags.get("multiline_error", False) is not False + + if cls.regex_min_max_error.match(line): + flags["multiline_error"] = line + + return single_line or multi_line + + @classmethod + def comm_ignore_ok(cls, line, lower_line, state, flags): + return False + + @classmethod + def comm_busy(cls, line, lower_line, state, flags): + return line.startswith("echo:busy:") or line.startswith("busy:") + + @classmethod + def error_communication(cls, line, lower_line, error, state, flags): + return any( + map( + lambda x: x in lower_line, + ("line number", "checksum", "format error", "expected line"), + ) + ) + + @classmethod + def error_sdcard(cls, line, lower_line, error, state, flags): + return any( + map( + lambda x: x in lower_line, + ( + "volume.init", + "openroot", + "workdir", + "error writing to file", + "cannot open", + "open failed", + "cannot enter", + ), + ) + ) + + @classmethod + def error_fatal(cls, line, lower_line, error, state, flags): + return any(map(lambda x: x in lower_line, ("kill() called", "fatal:"))) + + @classmethod + def message_temperature(cls, line, lower_line, state, flags): + return "T:" in line or "T0:" in line or "B:" in line + + @classmethod + def message_position(cls, line, lower_line, state, flags): + return "X:" in line and "Y:" in line and "Z:" in line + + @classmethod + def message_firmware_info(cls, line, lower_line, state, flags): + return "NAME:" in line + + @classmethod + def message_firmware_capability(cls, line, lower_line, state, flags): + return lower_line.startswith("cap:") + + @classmethod + def message_sd_init_ok(cls, line, lower_line, state, flags): + return "sd card ok" in lower_line + + @classmethod + def message_sd_init_fail(cls, line, lower_line, state, flags): + return ( + "sd init fail" in lower_line + or "volume.init failed" in lower_line + or "openroot failed" in lower_line + ) + + @classmethod + def message_sd_file_opened(cls, line, lower_line, state, flags): + return lower_line.startswith("file opened") + + @classmethod + def message_sd_file_selected(cls, line, lower_line, state, flags): + return lower_line.startswith("file selected") + + @classmethod + def message_sd_begin_file_list(cls, line, lower_line, state, flags): + return lower_line.startswith("begin file list") + + @classmethod + def message_sd_end_file_list(cls, line, lower_line, state, flags): + return lower_line.startswith("end file list") + + @classmethod + def message_sd_printing_byte(cls, line, lower_line, state, flags): + return "sd printing byte" in lower_line + + @classmethod + def message_sd_not_printing(cls, line, lower_line, state, flags): + return "not sd printing" in lower_line + + @classmethod + def message_sd_done_printing(cls, line, lower_line, state, flags): + return "done printing file" in lower_line + + @classmethod + def message_sd_begin_writing(cls, line, lower_line, state, flags): + return "writing to file" in lower_line + + @classmethod + def message_sd_end_writing(cls, line, lower_line, state, flags): + return "done saving file" in lower_line + + @classmethod + def message_sd_entry(cls, line, lower_line, state, flags): + return flags["sd_files_temp"] is not None + + ##~~ Message parsers + + @classmethod + def parse_comm_error(cls, line, lower_line, state, flags): + multiline = flags.get("multiline_error", False) + if multiline: + flags["multiline_error"] = False + line = line.rstrip() + " - " + multiline + lower_line = line.lower() + + error = (line[6:] if lower_line.startswith("error:") else line[2:]).strip() + return {"line": line, "lower_line": lower_line, "error": error} + + @classmethod + def parse_comm_timeout(cls, line, lower_line, state, flags): + return {"line": line, "lower_line": lower_line} + + @classmethod + def parse_comm_action_command(cls, line, lower_line, state, flags): + action = line[2:].strip()[len("action:") :].strip() + return {"line": line, "lower_line": lower_line, "action": action} + + @classmethod + def parse_error_communication(cls, line, lower_line, error, state, flags): + if "line number" in lower_line or "expected line" in lower_line: + error_type = "linenumber" + elif "checksum" in lower_line: + error_type = "checksum" + else: + error_type = "other" + + flags["last_communication_error"] = error_type + return {"error_type": error_type} + + @classmethod + def parse_comm_resend(cls, line, lower_line, state, flags): + line_to_resend = None + match = cls.regex_resend_linenumber.search(line) + if match is not None: + line_to_resend = int(match.group("n")) + return {"linenumber": line_to_resend} + + @classmethod + def parse_message_temperature(cls, line, lower_line, state, flags): + """ + Parses the provided temperature line. + + The result will be a dictionary mapping from the extruder or bed key to + a tuple with current and target temperature. The result will be canonicalized + with :func:`canonicalize_temperatures` before returning. + + Returns: + tuple: a 2-tuple with the maximum tool number and a dict mapping from + key to (actual, target) tuples, with key either matching ``Tn`` for ``n >= 0`` or ``B`` + """ + + current_tool = flags["current_tool"] + + result = {} + max_tool_num = 0 + for match in re.finditer(cls.regex_temp, line): + values = match.groupdict() + tool = values["tool"] + if tool == "T" and "toolnum" in values and values["toolnum"]: + tool_num = int(values["toolnum"]) + if tool_num > max_tool_num: + max_tool_num = tool_num + + try: + actual = ( + float(values.get("actual", None)) + if values.get("actual", None) is not None + else None + ) + target = ( + float(values.get("target", None)) + if values.get("target", None) is not None + else None + ) + result[tool] = actual, target + except ValueError: + # catch conversion issues, we'll rather just not get the temperature update instead of killing the connection + pass + + heatup_detected = ( + not lower_line.startswith("ok") + and not flags["heating"] + and not flags["temperature_autoreporting"] + ) + + return { + "max_tool_num": max(max_tool_num, current_tool), + "temperatures": cls._canonicalize_temperatures(result, current_tool), + "heatup_detected": heatup_detected, + } + + @classmethod + def parse_message_position(cls, line, lower_line, state, flags): + position = {"x": None, "y": None, "z": None, "e": None} + for match in re.finditer(cls.regex_position, line): + position[match.group("axis").lower()] = float(match.group("pos")) + return {"position": position} + + @classmethod + def parse_message_firmware_info(cls, line, lower_line, state, flags): + data = cls._parse_firmware_line(line) + firmware_name = data.get("FIRMWARE_NAME") + + if firmware_name is None: + # Malyan's "Marlin compatible firmware" isn't actually Marlin compatible and doesn't even + # report its firmware name properly in response to M115. Wonderful - why stick to established + # protocol when you can do your own thing, right? + # + # Example: NAME: Malyan VER: 2.9 MODEL: M200 HW: HA02 + # + # We do a bit of manual fiddling around here to circumvent that issue and get ourselves a + # reliable firmware name (NAME + VER) out of the Malyan M115 response. + name = data.get("NAME") + ver = data.get("VER") + if "malyan" in name.lower() and ver: + firmware_name = name.strip() + " " + ver.strip() + + if firmware_name is not None: + firmware_name = firmware_name.strip() + + return {"firmware_name": firmware_name, "data": data} + + @classmethod + def parse_message_firmware_capability(cls, line, lower_line, state, flags): + result = cls._parse_capability_line(line) + if not result: + return + cap, enabled = result + return {"cap": cap, "enabled": enabled} + + @classmethod + def parse_message_sd_file_opened(cls, line, lower_line, state, flags): + match = cls.regex_sd_file_opened.match(lower_line) + if not match: + return + + name = match.group("name") + size = int(match.group("size")) + return {"name": name, "long_name": name, "size": size} + + @classmethod + def parse_message_sd_entry(cls, line, lower_line, state, flags): + fileinfo = lower_line.rsplit(None, 1) + if len(fileinfo) > 1: + # we might have extended file information here, so let's split filename and size and try to make them a bit nicer + filename, size = fileinfo + try: + size = int(size) + except ValueError: + # whatever that was, it was not an integer, so we'll just use the whole line as filename and set size to None + filename = lower_line + size = None + else: + # no extended file information, so only the filename is there and we set size to None + filename = lower_line + size = None + + from octoprint.util import filter_non_ascii + + if filter_non_ascii(filename): + return None + else: + if not filename.startswith("/"): + # file from the root of the sd -- we'll prepend a / + filename = "/" + filename + + return { + "name": filename, + "long_name": filename, + "size": int(size) if size is not None else None, + } + + @classmethod + def parse_message_sd_printing_byte(cls, line, lower_line, state, flags): + match = cls.regex_sd_printing_byte.match(lower_line) + if not match: + return None + return { + "current": int(match.group("current")), + "total": int(match.group("total")), + } + + ##~~ Commands + + @classmethod + def command_hello(cls): + return cls.command_set_line(0) + + @classmethod + def command_get_firmware_info(cls): + return GcodeCommand("M115") + + @classmethod + def command_finish_moving(cls): + return GcodeCommand("M400") + + @classmethod + def command_get_position(cls): + return GcodeCommand("M114") + + @classmethod + def command_get_temp(cls): + return GcodeCommand("M105") + + @classmethod + def command_set_line(cls, n): + return GcodeCommand("M110", n=n) + + @classmethod + def command_emergency_stop(cls): + return GcodeCommand("M112") + + @classmethod + def command_abort_heatup(cls): + return GcodeCommand("M108") + + @classmethod + def command_set_extruder_temp(cls, temperature, tool=None, wait=False): + command = "M109" if wait else "M104" + args = {"s": temperature} + if tool is not None: + args["t"] = tool + return GcodeCommand(command, **args) + + @classmethod + def command_set_bed_temp(cls, temperature, wait=False): + return GcodeCommand("M190" if wait else "M140", s=temperature) + + @classmethod + def command_set_chamber_temp(cls, temperature, wait=False): + return GcodeCommand("M191" if wait else "M141", s=temperature) + + @classmethod + def command_set_relative_positioning(cls): + return GcodeCommand("G91") + + @classmethod + def command_set_absolute_positioning(cls): + return GcodeCommand("G90") + + @classmethod + def command_move(cls, x=None, y=None, z=None, e=None, f=None): + return GcodeCommand("G1", x=x, y=y, z=z, e=e, f=f) + + @classmethod + def command_extrude(cls, e=None, f=None): + return cls.command_move(e=e, f=f) + + @classmethod + def command_home(cls, x=False, y=False, z=False): + return GcodeCommand( + "G28", x=0 if x else None, y=0 if y else None, z=0 if z else None + ) + + @classmethod + def command_set_tool(cls, tool): + return GcodeCommand("T{}".format(tool)) + + @classmethod + def command_set_feedrate_multiplier(cls, multiplier): + return GcodeCommand("M220", s=multiplier) + + @classmethod + def command_set_extrusion_multiplier(cls, multiplier): + return GcodeCommand("M221", s=multiplier) + + @classmethod + def command_set_fan_speed(cls, speed): + return GcodeCommand("M106", s=speed) + + @classmethod + def command_set_motors(cls, enable): + return GcodeCommand("M17") if enable else GcodeCommand("M18") + + @classmethod + def command_sd_refresh(cls): + return GcodeCommand("M20") + + @classmethod + def command_sd_init(cls): + return GcodeCommand("M21") + + @classmethod + def command_sd_release(cls): + return GcodeCommand("M22") + + @classmethod + def command_sd_select_file(cls, name): + return GcodeCommand("M23", param=name) + + @classmethod + def command_sd_start(cls): + return GcodeCommand("M24") + + @classmethod + def command_sd_pause(cls): + return GcodeCommand("M25") + + @classmethod + def command_sd_resume(cls): + return GcodeCommand("M24") + + @classmethod + def command_sd_set_pos(cls, pos): + return GcodeCommand("M26", s=pos) + + @classmethod + def command_sd_status(cls): + return GcodeCommand("M27") + + @classmethod + def command_sd_begin_write(cls, name): + return GcodeCommand("M28", param=name) + + @classmethod + def command_sd_end_write(cls): + return GcodeCommand("M29") + + @classmethod + def command_sd_delete(cls, name): + return GcodeCommand("M30", param=name) + + @classmethod + def command_autoreport_temperature(cls, interval): + return GcodeCommand("M155", s=interval) + + @classmethod + def command_autoreport_sd_status(cls, interval): + return GcodeCommand("M27", s=interval) + + @classmethod + def command_busy_protocol_interval(cls, interval): + return GcodeCommand("M113", s=interval) + + ##~~ Helpers + + @classmethod + def _canonicalize_temperatures(cls, parsed, current): + """ + Canonicalizes the temperatures provided in parsed. + + Will make sure that returned result only contains extruder keys + like Tn, so always qualified with a tool number. + + The algorithm for cleaning up the parsed keys is the following: + + * If ``T`` is not included with the reported extruders, return + * If more than just ``T`` is reported: + * If both ``T`` and ``T0`` are reported set ``Tc`` to ``T``, remove + ``T`` from the result. + * Else set ``T0`` to ``T`` and delete ``T`` (Smoothie extra). + * If only ``T`` is reported, set ``Tc`` to ``T`` and delete ``T`` + * return + + Arguments: + parsed (dict): the parsed temperatures (mapping tool => (actual, target)) + to canonicalize + current (int): the current active extruder + Returns: + dict: the canonicalized version of ``parsed`` + """ + + reported_extruders = list(filter(lambda x: x.startswith("T"), parsed.keys())) + if "T" not in reported_extruders: + # Our reported_extruders are either empty or consist purely + # of Tn keys, no need for any action + return parsed + + current_tool_key = "T%d" % current + result = dict(parsed) + + if len(reported_extruders) > 1: + if "T0" in reported_extruders: + # Both T and T0 are present, so T contains the current + # extruder's temperature, e.g. for current_tool == 1: + # + # T: T0: T2: ... B: + # + # becomes + # + # T0: T1: T2: ... B: + # + # Same goes if Tc is already present, it will be overwritten: + # + # T: T0: T1: T2: ... B: + # + # becomes + # + # T0: T1: T2: ... B: + result[current_tool_key] = result["T"] + del result["T"] + else: + # So T is there, but T0 isn't. That looks like Smoothieware which + # always reports the first extruder T0 as T: + # + # T: T1: T2: ... B: + # + # becomes + # + # T0: T1: T2: ... B: + result["T0"] = result["T"] + del result["T"] + + else: + # We only have T. That can mean two things: + # + # * we only have one extruder at all, or + # * we are currently parsing a response to M109/M190, which on + # some firmwares doesn't report the full M105 output while + # waiting for the target temperature to be reached but only + # reports the current tool and bed + # + # In both cases it is however safe to just move our T over + # to T in the parsed data, current should always stay + # 0 for single extruder printers. E.g. for current_tool == 1: + # + # T: + # + # becomes + # + # T1: + + result[current_tool_key] = result["T"] + del result["T"] + + return result + + @classmethod + def _parse_firmware_line(cls, line): + """ + Parses the provided firmware info line. + + The result will be a dictionary mapping from the contained keys to the contained + values. + + Arguments: + line (unicode): the line to parse + + Returns: + dict: a dictionary with the parsed data + """ + + result = {} + split_line = cls.regex_firmware_splitter.split(line.strip())[ + 1: + ] # first entry is empty start of trimmed string + for key, value in chunks(split_line, 2): + result[key] = value + return result + + @classmethod + def _parse_capability_line(cls, line): + """ + Parses the provided firmware capability line. + + Lines are expected to be of the format + + Cap::<0 or 1> + + e.g. + + Cap:AUTOREPORT_TEMP:1 + Cap:TOGGLE_LIGHTS:0 + + Args: + line (unicode): the line to parse + + Returns: + tuple: a 2-tuple of the parsed capability name and whether it's on (true) or off (false), or None if the line + could not be parsed + """ + + line = line.lower() + if line.startswith("cap:"): + line = line[len("cap:") :] + + parts = line.split(":") + if len(parts) != 2: + # wrong format, can't parse this + return None + + capability, flag = parts + if flag not in ("0", "1"): + # wrong format, can't parse this + return None + + return capability.upper(), flag == "1" diff --git a/src/octoprint/comm/protocol/reprap/flavors/klipper.py b/src/octoprint/comm/protocol/reprap/flavors/klipper.py index a50482cd0..2eca111e9 100644 --- a/src/octoprint/comm/protocol/reprap/flavors/klipper.py +++ b/src/octoprint/comm/protocol/reprap/flavors/klipper.py @@ -1,19 +1,16 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License" from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor + class ReprapFirmwareFlavor(GenericFlavor): - key = "klipper" - name = "Klipper" + key = "klipper" + name = "Klipper" - unknown_requires_ack = True - - @classmethod - def identifier(cls, firmware_name, firmware_info): - return "klipper" in firmware_name.lower() + unknown_requires_ack = True + @classmethod + def identifier(cls, firmware_name, firmware_info): + return "klipper" in firmware_name.lower() diff --git a/src/octoprint/comm/protocol/reprap/flavors/malyan.py b/src/octoprint/comm/protocol/reprap/flavors/malyan.py index 7ed86c58d..bb16ac288 100644 --- a/src/octoprint/comm/protocol/reprap/flavors/malyan.py +++ b/src/octoprint/comm/protocol/reprap/flavors/malyan.py @@ -1,22 +1,19 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor + class MalyanFlavor(GenericFlavor): - key = "malyan" - name = "Malyan" + key = "malyan" + name = "Malyan" - send_checksum = "printing" + send_checksum = "printing" - block_while_dwelling = True - sd_always_available = True - - @classmethod - def identifier(cls, firmware_name, firmware_info): - return "malyan" in firmware_name.lower() + block_while_dwelling = True + sd_always_available = True + @classmethod + def identifier(cls, firmware_name, firmware_info): + return "malyan" in firmware_name.lower() diff --git a/src/octoprint/comm/protocol/reprap/flavors/marlin.py b/src/octoprint/comm/protocol/reprap/flavors/marlin.py index 01f0680da..1531663a6 100644 --- a/src/octoprint/comm/protocol/reprap/flavors/marlin.py +++ b/src/octoprint/comm/protocol/reprap/flavors/marlin.py @@ -1,49 +1,52 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" -from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor - import re +from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor + + class MarlinFlavor(GenericFlavor): - key = "marlin" - name = "Marlin" + key = "marlin" + name = "Marlin" - emergency_commands = ["M112", "M108", "M410"] - heatup_abortable = True + emergency_commands = ["M112", "M108", "M410"] + heatup_abortable = True - regex_marlin_kill_error = re.compile(r"Heating failed|Thermal Runaway|MAXTEMP triggered|MINTEMP triggered|Invalid extruder number|Watchdog barked|KILL caused") - """Regex matching first line of kill causing errors from Marlin.""" + regex_marlin_kill_error = re.compile( + r"Heating failed|Thermal Runaway|MAXTEMP triggered|MINTEMP triggered|Invalid extruder number|Watchdog barked|KILL caused" + ) + """Regex matching first line of kill causing errors from Marlin.""" - @classmethod - def comm_error(cls, line, lower_line, state, flags): - result = GenericFlavor.comm_error(line, lower_line, state, flags) + @classmethod + def comm_error(cls, line, lower_line, state, flags): + result = GenericFlavor.comm_error(line, lower_line, state, flags) - if cls.regex_min_max_error.match(line): - flags["multiline_error"] = line + if cls.regex_min_max_error.match(line): + flags["multiline_error"] = line - return result + return result class MarlinLegacyFlavor(GenericFlavor): - key = "marlinlegacy" - name = "Legacy Marlin" + key = "marlinlegacy" + name = "Legacy Marlin" - @classmethod - def identifier(cls, firmware_name, firmware_info): - return "marlin v1" in firmware_name.lower() + @classmethod + def identifier(cls, firmware_name, firmware_info): + return "marlin v1" in firmware_name.lower() class PrusaMarlinFlavor(MarlinFlavor): - key = "prusamarlin" - name = "Marlin: Prusa variant" + key = "prusamarlin" + name = "Marlin: Prusa variant" - @classmethod - def identifier(cls, firmware_name, firmware_info): - return "prusa-firmware" in firmware_name.lower() and "marlin" in firmware_name.lower() + @classmethod + def identifier(cls, firmware_name, firmware_info): + return ( + "prusa-firmware" in firmware_name.lower() + and "marlin" in firmware_name.lower() + ) diff --git a/src/octoprint/comm/protocol/reprap/flavors/repetier.py b/src/octoprint/comm/protocol/reprap/flavors/repetier.py index 8f40ac09f..b33f5b4d0 100644 --- a/src/octoprint/comm/protocol/reprap/flavors/repetier.py +++ b/src/octoprint/comm/protocol/reprap/flavors/repetier.py @@ -1,96 +1,106 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" -from octoprint.comm.protocol.reprap.flavors import GenericFlavor - -from octoprint.comm.protocol.reprap.util import regex_positive_float_pattern - import re +from octoprint.comm.protocol.reprap.flavors import GenericFlavor +from octoprint.comm.protocol.reprap.util import regex_positive_float_pattern + + class RepetierFlavor(GenericFlavor): - key = "repetier" - name = "Repetier" + key = "repetier" + name = "Repetier" - send_checksum = "always" - identical_resends_countdown = 5 - block_while_dwelling = True - detect_external_heatups = False + send_checksum = "always" + identical_resends_countdown = 5 + block_while_dwelling = True + detect_external_heatups = False - sd_always_available = True + sd_always_available = True - regex_tempextr = re.compile("targetextr(?P\d+):(?P%s)" % regex_positive_float_pattern) - """Regex for matching target temp reporting from Repetier. + regex_tempextr = re.compile( + r"targetextr(?P\d+):(?P%s)" % regex_positive_float_pattern + ) + """Regex for matching target temp reporting from Repetier. - Groups will be as follows: + Groups will be as follows: - * ``toolnum``: number of the extruder to which the target temperature - report belongs (int) - * ``target``: new target temperature (float) - """ + * ``toolnum``: number of the extruder to which the target temperature + report belongs (int) + * ``target``: new target temperature (float) + """ - regex_tempbed = re.compile("targetbed:(?P%s)" % regex_positive_float_pattern) - """Regex for matching target temp reporting from Repetier for beds. + regex_tempbed = re.compile("targetbed:(?P%s)" % regex_positive_float_pattern) + """Regex for matching target temp reporting from Repetier for beds. - Groups will be as follows: + Groups will be as follows: - * ``target``: new target temperature (float) - """ + * ``target``: new target temperature (float) + """ - @classmethod - def identifier(cls, firmware_name, firmware_info): - return "repetier" in firmware_name.lower() + @classmethod + def identifier(cls, firmware_name, firmware_info): + return "repetier" in firmware_name.lower() - @classmethod - def message_temperature(cls, line, lower_line, state, flags): - return GenericFlavor.message_temperature(line, lower_line, state, flags) or "targetextr" in lower_line or "targetbed" in lower_line + @classmethod + def message_temperature(cls, line, lower_line, state, flags): + return ( + GenericFlavor.message_temperature(line, lower_line, state, flags) + or "targetextr" in lower_line + or "targetbed" in lower_line + ) - @classmethod - def parse_message_temperature(cls, line, lower_line, state, flags): - if "targetextr" in lower_line: - match = cls.regex_tempextr.match(lower_line) - if match is not None: - tool_num = int(match.group("toolnum")) - target = float(match.group("target")) - tool = "T{}".format(tool_num) - temperatures = dict() - temperatures[tool] = (None, target) - return dict(max_tool_num=max(tool_num, flags.get("current_tool", 0)), - temperatures=temperatures, - heatup_detected=False) - elif "targetbed" in lower_line: - match = cls.regex_tempbed.match(lower_line) - if match is not None: - target = float(match.group("target")) - temperatures = dict(bed=(None, target)) - return dict(max_tool_num=flags.get("current_tool", 0), - temperatures=temperatures, - heatup_detected=False) - else: - # Repetier sends temperature output on it's own line, so we can't use the - # "no ok in temperature output" metric to detected external heatups - result = GenericFlavor.parse_message_temperature(line, lower_line, state, flags) - result[b"heatup_detected"] = False - return result + @classmethod + def parse_message_temperature(cls, line, lower_line, state, flags): + if "targetextr" in lower_line: + match = cls.regex_tempextr.match(lower_line) + if match is not None: + tool_num = int(match.group("toolnum")) + target = float(match.group("target")) + tool = "T{}".format(tool_num) + temperatures = {} + temperatures[tool] = (None, target) + return { + "max_tool_num": max(tool_num, flags.get("current_tool", 0)), + "temperatures": temperatures, + "heatup_detected": False, + } + elif "targetbed" in lower_line: + match = cls.regex_tempbed.match(lower_line) + if match is not None: + target = float(match.group("target")) + temperatures = {"bed": (None, target)} + return { + "max_tool_num": flags.get("current_tool", 0), + "temperatures": temperatures, + "heatup_detected": False, + } + else: + # Repetier sends temperature output on it's own line, so we can't use the + # "no ok in temperature output" metric to detected external heatups + result = GenericFlavor.parse_message_temperature( + line, lower_line, state, flags + ) + result[b"heatup_detected"] = False + return result + ##~~ Preprocessors, returning True stops further processing by the protocol - ##~~ Preprocessors, returning True stops further processing by the protocol - - @classmethod - def preprocess_comm_resend(cls, linenumber, state, flags): - if flags.get("resend_swallow_repetitions", False) \ - and flags.get("resend_swallow_repetitions_counter", 0) \ - and linenumber == flags["resend_requested"] \ - and flags["resend_swallow_repetitions_counter"] > 0: - cls.logger.debug("Ignoring resend request for line {}, that is " - "probably a repetition sent by the firmware to " - "ensure it arrives, not a real request" - .format(linenumber)) - flags["resend_swallow_repetitions_counter"] -= 1 - return True - - flags["resend_swallow_repetitions_counter"] = cls.identical_resends_countdown + @classmethod + def preprocess_comm_resend(cls, linenumber, state, flags): + if ( + flags.get("resend_swallow_repetitions", False) + and flags.get("resend_swallow_repetitions_counter", 0) + and linenumber == flags["resend_requested"] + and flags["resend_swallow_repetitions_counter"] > 0 + ): + cls.logger.debug( + "Ignoring resend request for line {}, that is " + "probably a repetition sent by the firmware to " + "ensure it arrives, not a real request".format(linenumber) + ) + flags["resend_swallow_repetitions_counter"] -= 1 + return True + flags["resend_swallow_repetitions_counter"] = cls.identical_resends_countdown diff --git a/src/octoprint/comm/protocol/reprap/flavors/reprapfirmware.py b/src/octoprint/comm/protocol/reprap/flavors/reprapfirmware.py index b38442f4b..718db51a3 100644 --- a/src/octoprint/comm/protocol/reprap/flavors/reprapfirmware.py +++ b/src/octoprint/comm/protocol/reprap/flavors/reprapfirmware.py @@ -1,19 +1,16 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor + class ReprapFirmwareFlavor(GenericFlavor): - key = "reprapfirmware" - name = "RepRapFirmware" + key = "reprapfirmware" + name = "RepRapFirmware" - sd_relative_path = True - - @classmethod - def identifier(cls, firmware_name, firmware_info): - return "reprapfirmware" in firmware_name.lower() + sd_relative_path = True + @classmethod + def identifier(cls, firmware_name, firmware_info): + return "reprapfirmware" in firmware_name.lower() diff --git a/src/octoprint/comm/protocol/reprap/flavors/smoothieware.py b/src/octoprint/comm/protocol/reprap/flavors/smoothieware.py index ac3d5a977..cb33d0f08 100644 --- a/src/octoprint/comm/protocol/reprap/flavors/smoothieware.py +++ b/src/octoprint/comm/protocol/reprap/flavors/smoothieware.py @@ -1,13 +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" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor + class ReprapFirmwareFlavor(GenericFlavor): - key = "smoothieware" - name = "Smoothieware" - + key = "smoothieware" + name = "Smoothieware" diff --git a/src/octoprint/comm/protocol/reprap/scripts.py b/src/octoprint/comm/protocol/reprap/scripts.py index c62833ba5..ccf065417 100644 --- a/src/octoprint/comm/protocol/reprap/scripts.py +++ b/src/octoprint/comm/protocol/reprap/scripts.py @@ -1,25 +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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" -from octoprint.comm.scripts import Script, UnknownScript from octoprint.comm.protocol.reprap.util import process_gcode_line +from octoprint.comm.scripts import Script, UnknownScript + class GcodeScript(Script): + def __init__(self, settings, name, context=None): + def renderer(ctx): + lines = settings.loadScript("gcode", name, context=ctx) + if lines is None: + raise UnknownScript(name) + return lines - def __init__(self, settings, name, context=None): - def renderer(ctx): - lines = settings.loadScript("gcode", name, context=ctx) - if lines is None: - raise UnknownScript(name) - return lines + super(GcodeScript, self).__init__(name, renderer, context=context) - super(GcodeScript, self).__init__(name, renderer, context=context) - - def render(self, context=None): - script = super(GcodeScript, self).render(context) - return list(filter(lambda x: x is not None and x.strip() != "", - map(lambda x: process_gcode_line(x), - script))) + def render(self, context=None): + script = super(GcodeScript, self).render(context) + return list( + filter( + lambda x: x is not None and x.strip() != "", + map(lambda x: process_gcode_line(x), script), + ) + ) diff --git a/src/octoprint/comm/protocol/reprap/util/__init__.py b/src/octoprint/comm/protocol/reprap/util/__init__.py index 8c7571d1d..8daced1d8 100644 --- a/src/octoprint/comm/protocol/reprap/util/__init__.py +++ b/src/octoprint/comm/protocol/reprap/util/__init__.py @@ -1,398 +1,384 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" -from octoprint.comm.protocol.reprap.commands import Command, to_command -from octoprint.util import PrependableQueue, TypeAlreadyInQueue, CountedEvent - -# noinspection PyCompatibility -from past.builtins import basestring - -import contextlib import copy -import logging import threading -try: - # noinspection PyCompatibility - import queue -except Exception: - # noinspection PyCompatibility - import Queue as queue +from octoprint.comm.protocol.reprap.commands import Command, to_command +from octoprint.util import CountedEvent -regex_float_pattern = "[-+]?[0-9]*\.?[0-9]+" -regex_positive_float_pattern = "[+]?[0-9]*\.?[0-9]+" -regex_int_pattern = "\d+" +regex_float_pattern = r"[-+]?[0-9]*\.?[0-9]+" +regex_positive_float_pattern = r"[+]?[0-9]*\.?[0-9]+" +regex_int_pattern = r"\d+" def strip_comment(line): - if not ";" in line: - # shortcut - return line + if ";" not in line: + # shortcut + return line - escaped = False - result = [] - for c in line: - if c == ";" and not escaped: - break - result += c - escaped = (c == "\\") and not escaped - return "".join(result).strip() + escaped = False + result = [] + for c in line: + if c == ";" and not escaped: + break + result += c + escaped = (c == "\\") and not escaped + return "".join(result).strip() def process_gcode_line(line, offsets=None, current_tool=None): - line = strip_comment(line).strip() - if not len(line): - return None + line = strip_comment(line).strip() + if not len(line): + return None - # if offsets is not None: - # line = apply_temperature_offsets(line, offsets, current_tool=current_tool) + # if offsets is not None: + # line = apply_temperature_offsets(line, offsets, current_tool=current_tool) - return line + return line def normalize_command_handler_result(command, handler_results, tags_to_add=None): - """ - Normalizes a command handler result. + """ + Normalizes a command handler result. - Handler results can be either ``None``, a single result entry or a list of result - entries. + Handler results can be either ``None``, a single result entry or a list of result + entries. - ``None`` results are ignored, the provided ``command``, ``command_type``, - ``gcode``, ``subcode`` and ``tags`` are returned in that case (as single-entry list with - one 5-tuple as entry). + ``None`` results are ignored, the provided ``command``, ``command_type``, + ``gcode``, ``subcode`` and ``tags`` are returned in that case (as single-entry list with + one 5-tuple as entry). - Single result entries are either: + Single result entries are either: - * a single string defining a replacement ``command`` - * a 1-tuple defining a replacement ``command`` - * a 2-tuple defining a replacement ``command`` and ``command_type`` - * a 3-tuple defining a replacement ``command`` and ``command_type`` and additional ``tags`` to set + * a single string defining a replacement ``command`` + * a 1-tuple defining a replacement ``command`` + * a 2-tuple defining a replacement ``command`` and ``command_type`` + * a 3-tuple defining a replacement ``command`` and ``command_type`` and additional ``tags`` to set - A ``command`` that is ``None`` will lead to the entry being ignored for - the normalized result. + A ``command`` that is ``None`` will lead to the entry being ignored for + the normalized result. - The method returns a list of normalized result entries. Normalized result - entries always are a 4-tuple consisting of ``command``, ``command_type``, - ``gcode`` and ``subcode``, the latter three being allowed to be ``None``. The list may - be empty in which case the command is to be suppressed. + The method returns a list of normalized result entries. Normalized result + entries always are a 4-tuple consisting of ``command``, ``command_type``, + ``gcode`` and ``subcode``, the latter three being allowed to be ``None``. The list may + be empty in which case the command is to be suppressed. - Examples: - >>> from octoprint.comm.protocol.reprap.commands.gcode import GcodeCommand - >>> normalize_command_handler_result(GcodeCommand("M105"), None) # doctest: +ALLOW_UNICODE - [GcodeCommand('M105',type=None,tags=set())] - >>> normalize_command_handler_result(GcodeCommand("M105"), GcodeCommand("M110")) # doctest: +ALLOW_UNICODE - [GcodeCommand('M110',type=None,tags=set())] - >>> normalize_command_handler_result(GcodeCommand("M105"), ["M110"]) # doctest: +ALLOW_UNICODE - [GcodeCommand('M110',original='M110',type=None,tags=set())] - >>> normalize_command_handler_result(GcodeCommand("M105"), ["M110", "M117 Foobar"]) # doctest: +ALLOW_UNICODE - [GcodeCommand('M110',original='M110',type=None,tags=set()), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags=set())] - >>> normalize_command_handler_result(GcodeCommand("M105"), [("M110",), "M117 Foobar"]) # doctest: +ALLOW_UNICODE - [GcodeCommand('M110',original='M110',type=None,tags=set()), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags=set())] - >>> normalize_command_handler_result(GcodeCommand("M105"), [("M110", "lineno_reset"), "M117 Foobar"]) # doctest: +ALLOW_UNICODE - [GcodeCommand('M110',original='M110',type='lineno_reset',tags=set()), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags=set())] - >>> normalize_command_handler_result(GcodeCommand("M105"), []) # doctest: +ALLOW_UNICODE - [] - >>> normalize_command_handler_result(GcodeCommand("M105"), ["M110", None]) # doctest: +ALLOW_UNICODE - [GcodeCommand('M110',original='M110',type=None,tags=set())] - >>> normalize_command_handler_result(GcodeCommand("M105"), [("M110",), (None, "ignored")]) # doctest: +ALLOW_UNICODE - [GcodeCommand('M110',original='M110',type=None,tags=set())] - >>> normalize_command_handler_result(GcodeCommand("M105"), [("M110",), ("M117 Foobar", "display_message"), ("tuple", "of", "unexpected", "length"), ("M110", "lineno_reset")]) # doctest: +ALLOW_UNICODE - [GcodeCommand('M110',original='M110',type=None,tags=set()), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type='display_message',tags=set()), GcodeCommand('M110',original='M110',type='lineno_reset',tags=set())] - >>> normalize_command_handler_result(GcodeCommand("M105",tags={"tag1", "tag2"}), ["M110", "M117 Foobar"]) # doctest: +ALLOW_UNICODE - [GcodeCommand('M110',original='M110',type=None,tags={'tag1', 'tag2'}), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags={'tag1', 'tag2'})] - >>> normalize_command_handler_result(GcodeCommand("M105",tags={"tag1", "tag2"}), ["M110", "M117 Foobar"], tags_to_add={"tag3"}) # doctest: +ALLOW_UNICODE - [GcodeCommand('M110',original='M110',type=None,tags={'tag1', 'tag2', 'tag3'}), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags={'tag1', 'tag2', 'tag3'})] + Examples: + >>> from octoprint.comm.protocol.reprap.commands.gcode import GcodeCommand + >>> normalize_command_handler_result(GcodeCommand("M105"), None) # doctest: +ALLOW_UNICODE + [GcodeCommand('M105',type=None,tags=set())] + >>> normalize_command_handler_result(GcodeCommand("M105"), GcodeCommand("M110")) # doctest: +ALLOW_UNICODE + [GcodeCommand('M110',type=None,tags=set())] + >>> normalize_command_handler_result(GcodeCommand("M105"), ["M110"]) # doctest: +ALLOW_UNICODE + [GcodeCommand('M110',original='M110',type=None,tags=set())] + >>> normalize_command_handler_result(GcodeCommand("M105"), ["M110", "M117 Foobar"]) # doctest: +ALLOW_UNICODE + [GcodeCommand('M110',original='M110',type=None,tags=set()), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags=set())] + >>> normalize_command_handler_result(GcodeCommand("M105"), [("M110",), "M117 Foobar"]) # doctest: +ALLOW_UNICODE + [GcodeCommand('M110',original='M110',type=None,tags=set()), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags=set())] + >>> normalize_command_handler_result(GcodeCommand("M105"), [("M110", "lineno_reset"), "M117 Foobar"]) # doctest: +ALLOW_UNICODE + [GcodeCommand('M110',original='M110',type='lineno_reset',tags=set()), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags=set())] + >>> normalize_command_handler_result(GcodeCommand("M105"), []) # doctest: +ALLOW_UNICODE + [] + >>> normalize_command_handler_result(GcodeCommand("M105"), ["M110", None]) # doctest: +ALLOW_UNICODE + [GcodeCommand('M110',original='M110',type=None,tags=set())] + >>> normalize_command_handler_result(GcodeCommand("M105"), [("M110",), (None, "ignored")]) # doctest: +ALLOW_UNICODE + [GcodeCommand('M110',original='M110',type=None,tags=set())] + >>> normalize_command_handler_result(GcodeCommand("M105"), [("M110",), ("M117 Foobar", "display_message"), ("tuple", "of", "unexpected", "length"), ("M110", "lineno_reset")]) # doctest: +ALLOW_UNICODE + [GcodeCommand('M110',original='M110',type=None,tags=set()), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type='display_message',tags=set()), GcodeCommand('M110',original='M110',type='lineno_reset',tags=set())] + >>> normalize_command_handler_result(GcodeCommand("M105",tags={"tag1", "tag2"}), ["M110", "M117 Foobar"]) # doctest: +ALLOW_UNICODE + [GcodeCommand('M110',original='M110',type=None,tags={'tag1', 'tag2'}), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags={'tag1', 'tag2'})] + >>> normalize_command_handler_result(GcodeCommand("M105",tags={"tag1", "tag2"}), ["M110", "M117 Foobar"], tags_to_add={"tag3"}) # doctest: +ALLOW_UNICODE + [GcodeCommand('M110',original='M110',type=None,tags={'tag1', 'tag2', 'tag3'}), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags={'tag1', 'tag2', 'tag3'})] - Arguments: - command (Command): The command for which the handler result was - generated - handler_results: The handler result(s) to normalized. Can be either - a single result entry or a list of result entries. - tags_to_add (set of unicode or None): List of tags to add to expanded result - entries + Arguments: + command (Command): The command for which the handler result was + generated + handler_results: The handler result(s) to normalized. Can be either + a single result entry or a list of result entries. + tags_to_add (set of unicode or None): List of tags to add to expanded result + entries - Returns: - (list) - A list of normalized handler result entries, which are - ``Command`` instances - """ + Returns: + (list) - A list of normalized handler result entries, which are + ``Command`` instances + """ - original = command + original = command - if handler_results is None: - # handler didn't return anything, we'll just continue - return [original] + if handler_results is None: + # handler didn't return anything, we'll just continue + return [original] - if not isinstance(handler_results, list): - handler_results = [handler_results, ] + if not isinstance(handler_results, list): + handler_results = [ + handler_results, + ] - result = [] - for handler_result in handler_results: - # we iterate over all handler result entries and process each one - # individually here + result = [] + for handler_result in handler_results: + # we iterate over all handler result entries and process each one + # individually here - if handler_result is None: - # entry is None, we'll ignore that entry and continue - continue + if handler_result is None: + # entry is None, we'll ignore that entry and continue + continue - def expand_tags(tags, tags_to_add): - tags = tags.copy() - if tags_to_add and isinstance(tags_to_add, set): - tags |= tags_to_add - return tags + def expand_tags(tags, tags_to_add): + tags = tags.copy() + if tags_to_add and isinstance(tags_to_add, set): + tags |= tags_to_add + return tags - if isinstance(handler_result, basestring): - # entry is just a string, replace command with it - if handler_result != original.line: - # command changed, swap it - command = to_command(handler_result, - type=original.type, - tags=expand_tags(original.tags, tags_to_add)) - result.append(command) + if isinstance(handler_result, str): + # entry is just a string, replace command with it + if handler_result != original.line: + # command changed, swap it + command = to_command( + handler_result, + type=original.type, + tags=expand_tags(original.tags, tags_to_add), + ) + result.append(command) - elif isinstance(handler_result, Command): - if handler_result != original: - command = copy.copy(handler_result) - command.tags = expand_tags(original.tags, tags_to_add) - result.append(command) + elif isinstance(handler_result, Command): + if handler_result != original: + command = copy.copy(handler_result) + command.tags = expand_tags(original.tags, tags_to_add) + result.append(command) - elif isinstance(handler_result, tuple): - # entry is a tuple, extract command and command_type - hook_result_length = len(handler_result) + elif isinstance(handler_result, tuple): + # entry is a tuple, extract command and command_type + hook_result_length = len(handler_result) - command_type = original.type - command_tags = original.tags + command_type = original.type + command_tags = original.tags - if hook_result_length == 1: - # handler returned just the command - command_line, = handler_result - elif hook_result_length == 2: - # handler returned command and command_type - command_line, command_type = handler_result - elif hook_result_length == 3: - # handler returned command, command type and additional tags - command_line, command_type, command_tags = handler_result - else: - # handler returned a tuple of an unexpected length, ignore - # and continue - continue + if hook_result_length == 1: + # handler returned just the command + (command_line,) = handler_result + elif hook_result_length == 2: + # handler returned command and command_type + command_line, command_type = handler_result + elif hook_result_length == 3: + # handler returned command, command type and additional tags + command_line, command_type, command_tags = handler_result + else: + # handler returned a tuple of an unexpected length, ignore + # and continue + continue - if command_line is None: - # command is None, ignore it and continue - continue + if command_line is None: + # command is None, ignore it and continue + continue - if command_line != original.line or command_type != original.type: - # command or command_type changed, tags need to be rewritten - command_tags = expand_tags(command_tags, tags_to_add) + if command_line != original.line or command_type != original.type: + # command or command_type changed, tags need to be rewritten + command_tags = expand_tags(command_tags, tags_to_add) - result.append(to_command(command_line, type=command_type, tags=command_tags)) + result.append(to_command(command_line, type=command_type, tags=command_tags)) - # reset to original - command = original + # reset to original + command = original - return result + return result class SendToken(CountedEvent): + def __init__(self, value=0, maximum=None, **kwargs): + super(SendToken, self).__init__(value=value, maximum=maximum, **kwargs) + self._ignored = 0 - def __init__(self, value=0, maximum=None, **kwargs): - super(SendToken, self).__init__(value=value, maximum=maximum, **kwargs) - self._ignored = 0 + def set(self, ignore=False): + with self._mutex: + if ignore: + self._ignored += 1 + self._internal_set(self._counter + 1) - def set(self, ignore=False): - with self._mutex: - if ignore: - self._ignored += 1 - self._internal_set(self._counter + 1) - - def clear(self, completely=False): - with self._mutex: - if completely: - self._internal_set(0) - self._ignored = 0 - else: - if self._ignored > 0: - self._ignored -= 1 - self._internal_set(self._counter - 1) - self._internal_set(self._counter - 1) + def clear(self, completely=False): + with self._mutex: + if completely: + self._internal_set(0) + self._ignored = 0 + else: + if self._ignored > 0: + self._ignored -= 1 + self._internal_set(self._counter - 1) + self._internal_set(self._counter - 1) class LineHistory(object): - def __init__(self, max=None): - self.max = max + def __init__(self, max=None): + self.max = max - self._lines = [] - self._mutex = threading.RLock() - self._line_number_lookup = dict() + self._lines = [] + self._mutex = threading.RLock() + self._line_number_lookup = {} - @property - def lines(self): - with self._mutex: - return [x[0] for x in self._lines] + @property + def lines(self): + with self._mutex: + return [x[0] for x in self._lines] - def append(self, line, line_number=None): - with self._mutex: - self._lines.append((line, line_number)) - if line_number is not None: - self._line_number_lookup[line_number] = line - self._cleanup() + def append(self, line, line_number=None): + with self._mutex: + self._lines.append((line, line_number)) + if line_number is not None: + self._line_number_lookup[line_number] = line + self._cleanup() - def clear(self): - with self._mutex: - self._lines = [] - self._line_number_lookup = dict() + def clear(self): + with self._mutex: + self._lines = [] + self._line_number_lookup = {} - def __len__(self): - with self._mutex: - return len(self._lines) + def __len__(self): + with self._mutex: + return len(self._lines) - def __getitem__(self, line_number): - with self._mutex: - return self._line_number_lookup[line_number] + def __getitem__(self, line_number): + with self._mutex: + return self._line_number_lookup[line_number] - def __contains__(self, line_number): - with self._mutex: - return line_number in self._line_number_lookup + def __contains__(self, line_number): + with self._mutex: + return line_number in self._line_number_lookup - def __iter__(self): - return iter(self.lines) + def __iter__(self): + return iter(self.lines) - def _cleanup(self): - if len(self._lines) <= self.max: - return + def _cleanup(self): + if len(self._lines) <= self.max: + return - while len(self._lines) > self.max: - _, line_number = self._lines.pop(0) - if line_number is not None: - try: - del self._line_number_lookup[line_number] - except KeyError: - pass + while len(self._lines) > self.max: + _, line_number = self._lines.pop(0) + if line_number is not None: + try: + del self._line_number_lookup[line_number] + except KeyError: + pass class PositionRecord(object): - _standard_attrs = {"x", "y", "z", "e", "f", "t"} + _standard_attrs = {"x", "y", "z", "e", "f", "t"} - @classmethod - def valid_e(cls, attr): - if not attr.startswith("e"): - return False + @classmethod + def valid_e(cls, attr): + if not attr.startswith("e"): + return False - try: - int(attr[1:]) - except Exception: - return False + try: + int(attr[1:]) + except Exception: + return False - return True + return True - def __init__(self, *args, **kwargs): - attrs = self._standard_attrs | set([key for key in kwargs if self.valid_e(key)]) - for attr in attrs: - setattr(self, attr, kwargs.get(attr)) + def __init__(self, *args, **kwargs): + attrs = self._standard_attrs | set([key for key in kwargs if self.valid_e(key)]) + for attr in attrs: + setattr(self, attr, kwargs.get(attr)) - def copy_from(self, other): - # make sure all standard attrs and attrs from other are set - attrs = self._standard_attrs | set([key for key in dir(other) if self.valid_e(key)]) - for attr in attrs: - setattr(self, attr, getattr(other, attr)) + def copy_from(self, other): + # make sure all standard attrs and attrs from other are set + attrs = self._standard_attrs | set( + [key for key in dir(other) if self.valid_e(key)] + ) + for attr in attrs: + setattr(self, attr, getattr(other, attr)) - # delete attrs other doesn't have - attrs = set([key for key in dir(self) if self.valid_e(key)]) - attrs - for attr in attrs: - delattr(self, attr) + # delete attrs other doesn't have + attrs = set([key for key in dir(self) if self.valid_e(key)]) - attrs + for attr in attrs: + delattr(self, attr) - def as_dict(self): - attrs = self._standard_attrs | set([key for key in dir(self) if self.valid_e(key)]) - return dict((attr, getattr(self, attr)) for attr in attrs) + def as_dict(self): + attrs = self._standard_attrs | set( + [key for key in dir(self) if self.valid_e(key)] + ) + return dict((attr, getattr(self, attr)) for attr in attrs) class TemperatureRecord(object): - def __init__(self): - self._tools = dict() - self._bed = (None, None) - self._chamber = (None, None) + def __init__(self): + self._tools = {} + self._bed = (None, None) + self._chamber = (None, None) - def copy_from(self, other): - self._tools = other.tools - self._bed = other.bed - self._chamber = other.chamber + def copy_from(self, other): + self._tools = other.tools + self._bed = other.bed + self._chamber = other.chamber - def set_tool(self, tool, actual=None, target=None): - current = self._tools.get(tool, (None, None)) - self._tools[tool] = self._to_new_tuple(current, actual, target) + def set_tool(self, tool, actual=None, target=None): + current = self._tools.get(tool, (None, None)) + self._tools[tool] = self._to_new_tuple(current, actual, target) - def set_bed(self, actual=None, target=None): - current = self._bed - self._bed = self._to_new_tuple(current, actual, target) + def set_bed(self, actual=None, target=None): + current = self._bed + self._bed = self._to_new_tuple(current, actual, target) - def set_chamber(self, actual=None, target=None): - current = self._chamber - self._chamber = self._to_new_tuple(current, actual, target) + def set_chamber(self, actual=None, target=None): + current = self._chamber + self._chamber = self._to_new_tuple(current, actual, target) - @property - def tools(self): - return dict(self._tools) + @property + def tools(self): + return dict(self._tools) - @property - def bed(self): - return self._bed + @property + def bed(self): + return self._bed - @property - def chamber(self): - return self._chamber + @property + def chamber(self): + return self._chamber - def as_dict(self): - result = dict() + def as_dict(self): + result = {} - tools = self.tools - for tool, data in tools.items(): - result["tool{}".format(tool)] = dict(actual=data[0], - target=data[1]) + tools = self.tools + for tool, data in tools.items(): + result["tool{}".format(tool)] = {"actual": data[0], "target": data[1]} - bed = self.bed - result["bed"] = dict(actual=bed[0], - target=bed[1]) + bed = self.bed + result["bed"] = {"actual": bed[0], "target": bed[1]} - chamber = self.chamber - result["chamber"] = dict(actual=chamber[0], - target=chamber[1]) + chamber = self.chamber + result["chamber"] = {"actual": chamber[0], "target": chamber[1]} - return result + return result - def as_script_dict(self): - result = self.as_dict() + def as_script_dict(self): + result = self.as_dict() - # backwards compatibility - tools = self.tools - for tool, data in tools.items(): - result[tool] = dict(actual=data[0], - target=data[1]) + # backwards compatibility + tools = self.tools + for tool, data in tools.items(): + result[tool] = {"actual": data[0], "target": data[1]} - bed = self.bed - result["b"] = dict(actual=bed[0], - target=bed[1]) + bed = self.bed + result["b"] = {"actual": bed[0], "target": bed[1]} - chamber = self.chamber - result["c"] = dict(actual=chamber[0], - target=chamber[1]) + chamber = self.chamber + result["c"] = {"actual": chamber[0], "target": chamber[1]} - return result + return result - @classmethod - def _to_new_tuple(cls, current, actual, target): - if current is None or not isinstance(current, tuple) or len(current) != 2: - current = (None, None) + @classmethod + def _to_new_tuple(cls, current, actual, target): + if current is None or not isinstance(current, tuple) or len(current) != 2: + current = (None, None) - if actual is None and target is None: - return current + if actual is None and target is None: + return current - old_actual, old_target = current + old_actual, old_target = current - if actual is None: - return old_actual, target - elif target is None: - return actual, old_target - else: - return actual, target + if actual is None: + return old_actual, target + elif target is None: + return actual, old_target + else: + return actual, target diff --git a/src/octoprint/comm/protocol/reprap/util/queues.py b/src/octoprint/comm/protocol/reprap/util/queues.py index 8ad5b248a..c3a33af16 100644 --- a/src/octoprint/comm/protocol/reprap/util/queues.py +++ b/src/octoprint/comm/protocol/reprap/util/queues.py @@ -1,16 +1,12 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" -from octoprint.util import PrependableQueue, TypedQueue, TypeAlreadyInQueue +from octoprint.util import PrependableQueue, TypeAlreadyInQueue, TypedQueue try: - import queue + import queue except ImportError: - import Queue as queue - + import Queue as queue import contextlib import logging @@ -18,177 +14,181 @@ import threading class ScriptQueue(PrependableQueue): - pass + pass class JobQueue(PrependableQueue): - pass + pass class CommandQueue(TypedQueue): + def __init__(self, *args, **kwargs): + TypedQueue.__init__(self, *args, **kwargs) + self._unblocked = threading.Event() + self._unblocked.set() - def __init__(self, *args, **kwargs): - TypedQueue.__init__(self, *args, **kwargs) - self._unblocked = threading.Event() - self._unblocked.set() + def block(self): + self._unblocked.clear() - def block(self): - self._unblocked.clear() + def unblock(self): + self._unblocked.set() - def unblock(self): - self._unblocked.set() + @contextlib.contextmanager + def blocked(self): + self.block() + try: + yield + finally: + self.unblock() - @contextlib.contextmanager - def blocked(self): - self.block() - try: - yield - finally: - self.unblock() + def get(self, *args, **kwargs): + self._unblocked.wait() + return TypedQueue.get(self, *args, **kwargs) - def get(self, *args, **kwargs): - self._unblocked.wait() - return TypedQueue.get(self, *args, **kwargs) + def put(self, *args, **kwargs): + self._unblocked.wait() + return TypedQueue.put(self, *args, **kwargs) - def put(self, *args, **kwargs): - self._unblocked.wait() - return TypedQueue.put(self, *args, **kwargs) - - def clear(self): - cleared = [] - while True: - try: - cleared.append(TypedQueue.get(self, False)) - TypedQueue.task_done(self) - except queue.Empty: - break - return cleared + def clear(self): + cleared = [] + while True: + try: + cleared.append(TypedQueue.get(self, False)) + TypedQueue.task_done(self) + except queue.Empty: + break + return cleared class SendQueue(PrependableQueue): + def __init__(self, maxsize=0): + PrependableQueue.__init__(self, maxsize=maxsize) - def __init__(self, maxsize=0): - PrependableQueue.__init__(self, maxsize=maxsize) + self._unblocked = threading.Event() + self._unblocked.set() - self._unblocked = threading.Event() - self._unblocked.set() + self._resend_queue = PrependableQueue() + self._send_queue = PrependableQueue() + self._lookup = set() - self._resend_queue = PrependableQueue() - self._send_queue = PrependableQueue() - self._lookup = set() + self._resend_active = False - self._resend_active = False + @property + def resend_active(self): + return self._resend_active - @property - def resend_active(self): - return self._resend_active + @resend_active.setter + def resend_active(self, resend_active): + with self.mutex: + self._resend_active = resend_active - @resend_active.setter - def resend_active(self, resend_active): - with self.mutex: - self._resend_active = resend_active + def block(self): + self._unblocked.clear() - def block(self): - self._unblocked.clear() + def unblock(self): + self._unblocked.set() - def unblock(self): - self._unblocked.set() + @contextlib.contextmanager + def blocked(self): + self.block() + try: + yield + finally: + self.unblock() - @contextlib.contextmanager - def blocked(self): - self.block() - try: - yield - finally: - self.unblock() + def prepend(self, item, item_type=None, target=None, block=True, timeout=None): + self._unblocked.wait() + PrependableQueue.prepend( + self, (item, item_type, target), block=block, timeout=timeout + ) - def prepend(self, item, item_type=None, target=None, block=True, timeout=None): - self._unblocked.wait() - PrependableQueue.prepend(self, (item, item_type, target), block=block, timeout=timeout) + def put(self, item, item_type=None, target=None, block=True, timeout=None): + self._unblocked.wait() + PrependableQueue.put( + self, (item, item_type, target), block=block, timeout=timeout + ) - def put(self, item, item_type=None, target=None, block=True, timeout=None): - self._unblocked.wait() - PrependableQueue.put(self, (item, item_type, target), block=block, timeout=timeout) + def get(self, block=True, timeout=None): + self._unblocked.wait() + item, _, _ = PrependableQueue.get(self, block=block, timeout=timeout) + return item - def get(self, block=True, timeout=None): - self._unblocked.wait() - item, _, _ = PrependableQueue.get(self, block=block, timeout=timeout) - return item + def clear(self): + cleared = [] + while True: + try: + cleared.append(PrependableQueue.get(self, False)) + PrependableQueue.task_done(self) + except queue.Empty: + break + return cleared - def clear(self): - cleared = [] - while True: - try: - cleared.append(PrependableQueue.get(self, False)) - PrependableQueue.task_done(self) - except queue.Empty: - break - return cleared + def _put(self, item): + _, item_type, target = item + if item_type is not None: + if item_type in self._lookup: + raise TypeAlreadyInQueue( + item_type, "Type {} is already in queue".format(item_type) + ) + else: + self._lookup.add(item_type) - def _put(self, item): - _, item_type, target = item - if item_type is not None: - if item_type in self._lookup: - raise TypeAlreadyInQueue(item_type, "Type {} is already in queue".format(item_type)) - else: - self._lookup.add(item_type) + if target == "resend": + self._resend_queue.put(item) + else: + self._send_queue.put(item) - if target == "resend": - self._resend_queue.put(item) - else: - self._send_queue.put(item) + def _prepend(self, item): + _, item_type, target = item + if item_type is not None: + if item_type in self._lookup: + raise TypeAlreadyInQueue( + item_type, "Type {} is already in queue".format(item_type) + ) + else: + self._lookup.add(item_type) - def _prepend(self, item): - _, item_type, target = item - if item_type is not None: - if item_type in self._lookup: - raise TypeAlreadyInQueue(item_type, "Type {} is already in queue".format(item_type)) - else: - self._lookup.add(item_type) + if target == "resend": + self._resend_queue.prepend(item) + else: + self._send_queue.prepend(item) - if target == "resend": - self._resend_queue.prepend(item) - else: - self._send_queue.prepend(item) + def _get(self): + if self.resend_active: + item = self._resend_queue.get(block=False) + else: + try: + item = self._resend_queue.get(block=False) + except queue.Empty: + item = self._send_queue.get(block=False) - def _get(self): - if self.resend_active: - item = self._resend_queue.get(block=False) - else: - try: - item = self._resend_queue.get(block=False) - except queue.Empty: - item = self._send_queue.get(block=False) + _, item_type, _ = item + if item_type is not None: + if item_type in self._lookup: + self._lookup.remove(item_type) - _, item_type, _ = item - if item_type is not None: - if item_type in self._lookup: - self._lookup.remove(item_type) + return item - return item - - def _qsize(self, len=len): - if self.resend_active: - return self._resend_queue.qsize() - else: - return self._resend_queue.qsize() + self._send_queue.qsize() + def _qsize(self, len=len): + if self.resend_active: + return self._resend_queue.qsize() + else: + return self._resend_queue.qsize() + self._send_queue.qsize() class QueueMarker(object): + def __init__(self, callback): + self.callback = callback - def __init__(self, callback): - self.callback = callback - - def run(self): - if callable(self.callback): - try: - self.callback() - except Exception: - logging.getLogger(__name__).exception("Error while running callback of QueueMarker") + def run(self): + if callable(self.callback): + try: + self.callback() + except Exception: + logging.getLogger(__name__).exception( + "Error while running callback of QueueMarker" + ) class SendQueueMarker(QueueMarker): - pass - - - + pass diff --git a/src/octoprint/comm/scripts/__init__.py b/src/octoprint/comm/scripts/__init__.py index 957563ea2..74b5a89b8 100644 --- a/src/octoprint/comm/scripts/__init__.py +++ b/src/octoprint/comm/scripts/__init__.py @@ -1,37 +1,34 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" + class Script(object): + def __init__(self, name, renderer, context=None): + if context is None: + context = {} - def __init__(self, name, renderer, context=None): - if context is None: - context = dict() + self.name = name + self.renderer = renderer + self.context = context - self.name = name - self.renderer = renderer - self.context = context + def render(self, context=None): + if context is None: + context = {} - def render(self, context=None): - if context is None: - context = dict() + render_context = dict(self.context) + render_context.update(context) - render_context = dict(self.context) - render_context.update(context) + content = self.renderer(render_context) + if content is None: + return None - content = self.renderer(render_context) - if content is None: - return None - - return content.split("\n") + return content.split("\n") class UnknownScript(Exception): - def __init__(self, name, *args, **kwargs): - self.name = name + def __init__(self, name, *args, **kwargs): + self.name = name class InvalidScript(Exception): - pass + pass diff --git a/src/octoprint/comm/transport/__init__.py b/src/octoprint/comm/transport/__init__.py index dd5fbc50d..350ac677e 100644 --- a/src/octoprint/comm/transport/__init__.py +++ b/src/octoprint/comm/transport/__init__.py @@ -1,355 +1,382 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" -from octoprint.comm.util.parameters import get_param_dict - import copy import logging -import time -from octoprint.util import monotonic_time -from octoprint.util.listener import ListenerAware +from octoprint.comm.util.parameters import get_param_dict from octoprint.plugin import plugin_manager from octoprint.settings import SubSettings +from octoprint.util import monotonic_time +from octoprint.util.listener import ListenerAware + +_registry = {} -_registry = dict() def register_transports(): - from .serialtransport import SerialTransport - from .sockettransport import TcpTransport, SerialOverTcpTransport + from .serialtransport import SerialTransport + from .sockettransport import SerialOverTcpTransport, TcpTransport - logger = logging.getLogger(__name__) + logger = logging.getLogger(__name__) - # stock transports - register_transport(SerialTransport) - register_transport(TcpTransport) - register_transport(SerialOverTcpTransport) + # stock transports + register_transport(SerialTransport) + register_transport(TcpTransport) + register_transport(SerialOverTcpTransport) - # more transports provided by plugins - hooks = plugin_manager().get_hooks("octoprint.comm.transport.register") - for name, hook in hooks.items(): - try: - transports = hook() - for transport in transports: - try: - register_transport(transport) - except Exception: - logger.exception("Error while registering transport class {} for plugin {}".format(transport, name)) - except Exception: - logger.exception("Error executing octoprint.comm.transport.register hook for plugin {}".format(name)) + # more transports provided by plugins + hooks = plugin_manager().get_hooks("octoprint.comm.transport.register") + for name, hook in hooks.items(): + try: + transports = hook() + for transport in transports: + try: + register_transport(transport) + except Exception: + logger.exception( + "Error while registering transport class {} for plugin {}".format( + transport, name + ) + ) + except Exception: + logger.exception( + "Error executing octoprint.comm.transport.register hook for plugin {}".format( + name + ) + ) def register_transport(transport_class): - if not hasattr(transport_class, "key"): - raise ValueError("Transport class {} is missing key".format(transport_class)) - _registry[transport_class.key] = transport_class + if not hasattr(transport_class, "key"): + raise ValueError("Transport class {} is missing key".format(transport_class)) + _registry[transport_class.key] = transport_class def lookup_transport(key): - return _registry.get(key) + return _registry.get(key) def all_transports(): - return _registry.values() + return _registry.values() class Transport(ListenerAware): - """ - Transport base class. + """ + Transport base class. - Implement at least ``in_waiting``, ``do_read`` and ``do_write``. - """ + Implement at least ``in_waiting``, ``do_read`` and ``do_write``. + """ - name = None - key = None + name = None + key = None - message_integrity = False + message_integrity = False - @classmethod - def get_connection_options(cls): - return [] + @classmethod + def get_connection_options(cls): + return [] - @classmethod - def get_settings_defaults(cls): - return dict() + @classmethod + def get_settings_defaults(cls): + return {} - def __init__(self, *args, **kwargs): - super(Transport, self).__init__() + def __init__(self, *args, **kwargs): + super(Transport, self).__init__() - self._logger = logging.getLogger(__name__) - self._state = TransportState.DISCONNECTED - self._args = dict() + self._logger = logging.getLogger(__name__) + self._state = TransportState.DISCONNECTED + self._args = {} - self._printer_profile = kwargs.get("printer_profile") - self._plugin_manager = kwargs.get("plugin_manager") - self._event_bus = kwargs.get("event_bus") - self._settings = kwargs.get("settings") - if not isinstance(self._settings, TransportSettings): - self._settings = TransportSettings(self._settings, self) + self._printer_profile = kwargs.get("printer_profile") + self._plugin_manager = kwargs.get("plugin_manager") + self._event_bus = kwargs.get("event_bus") + self._settings = kwargs.get("settings") + if not isinstance(self._settings, TransportSettings): + self._settings = TransportSettings(self._settings, self) - def args(self): - return copy.deepcopy(self._args) + def args(self): + return copy.deepcopy(self._args) - def set_current_args(self, **value): - self._args = copy.deepcopy(value) + def set_current_args(self, **value): + self._args = copy.deepcopy(value) - @property - def state(self): - return self._state + @property + def state(self): + return self._state - @state.setter - def state(self, value): - old_state = self.state - self._state = value - self.notify_listeners("on_transport_log_message", self, "Transport state changed from '{}' to '{}'".format(old_state, value)) + @state.setter + def state(self, value): + old_state = self.state + self._state = value + self.notify_listeners( + "on_transport_log_message", + self, + "Transport state changed from '{}' to '{}'".format(old_state, value), + ) - def connect(self, **params): - if self.state == TransportState.CONNECTED: - raise TransportAlreadyConnectedError("Already connected, disconnect first") - options = self.get_connection_options() - param_dict = get_param_dict(params, options) + def connect(self, **params): + if self.state == TransportState.CONNECTED: + raise TransportAlreadyConnectedError("Already connected, disconnect first") + options = self.get_connection_options() + param_dict = get_param_dict(params, options) - self.create_connection(**param_dict) + self.create_connection(**param_dict) - self.state = TransportState.CONNECTED - self.notify_listeners("on_transport_connected", self) + self.state = TransportState.CONNECTED + self.notify_listeners("on_transport_connected", self) - def disconnect(self, error=None, wait=True): - if self.state == TransportState.DISCONNECTED: - raise TransportNotConnectedError("Already disconnected") + def disconnect(self, error=None, wait=True): + if self.state == TransportState.DISCONNECTED: + raise TransportNotConnectedError("Already disconnected") - success = self.drop_connection(wait=wait) - if not success and not error: - error = "Error disconnecting transport" + success = self.drop_connection(wait=wait) + if not success and not error: + error = "Error disconnecting transport" - if error: - self.state = TransportState.DISCONNECTED_WITH_ERROR - self.notify_listeners("on_transport_log_message", self, error) - else: - self.state = TransportState.DISCONNECTED + if error: + self.state = TransportState.DISCONNECTED_WITH_ERROR + self.notify_listeners("on_transport_log_message", self, error) + else: + self.state = TransportState.DISCONNECTED - self.notify_listeners("on_transport_disconnected", self, error=error) + self.notify_listeners("on_transport_disconnected", self, error=error) - def create_connection(self, *args, **kwargs): - return True + def create_connection(self, *args, **kwargs): + return True - def drop_connection(self, wait=True): - return True + def drop_connection(self, wait=True): + return True - def read(self, size=None, timeout=None): - data = self.do_read(size=size, timeout=timeout) - self.notify_listeners("on_transport_log_received_data", self, data) - return data + def read(self, size=None, timeout=None): + data = self.do_read(size=size, timeout=timeout) + self.notify_listeners("on_transport_log_received_data", self, data) + return data - def write(self, data): - self.do_write(data) - self.notify_listeners("on_transport_log_sent_data", self, data) + def write(self, data): + self.do_write(data) + self.notify_listeners("on_transport_log_sent_data", self, data) - @property - def in_waiting(self): - return 0 + @property + def in_waiting(self): + return 0 - def do_read(self, size=None, timeout=None): - return b"" + def do_read(self, size=None, timeout=None): + return b"" - def do_write(self, data): - pass + def do_write(self, data): + pass - def __str__(self): - return self.__class__.__name__ + def __str__(self): + return self.__class__.__name__ class TransportState(object): - CONNECTED = "connected" - DISCONNECTED = "disconnected" - DISCONNECTED_WITH_ERROR = "disconnected_with_error" + CONNECTED = "connected" + DISCONNECTED = "disconnected" + DISCONNECTED_WITH_ERROR = "disconnected_with_error" class TransportSettings(SubSettings): - def __init__(self, settings, transport): - self.transport = transport.key - SubSettings.__init__(self, settings, ["comm", "transport", transport.key], - defaults=transport.get_settings_defaults()) + def __init__(self, settings, transport): + self.transport = transport.key + SubSettings.__init__( + self, + settings, + ["comm", "transport", transport.key], + defaults=transport.get_settings_defaults(), + ) class TransportNotConnectedError(Exception): - pass + pass class TransportAlreadyConnectedError(Exception): - pass + pass class TransportWrapper(ListenerAware): - unforwarded_handlers = [] - """Allows to explicitly disable certain transport listener handlers on sub classes.""" + unforwarded_handlers = [] + """Allows to explicitly disable certain transport listener handlers on sub classes.""" - def __init__(self, transport): - ListenerAware.__init__(self) - self.transport = transport - self.transport.register_listener(self) + def __init__(self, transport): + ListenerAware.__init__(self) + self.transport = transport + self.transport.register_listener(self) - # make sure we forward any transport listener calls to our own registered listeners + # make sure we forward any transport listener calls to our own registered listeners - def forward_handler(name): - def f(*args, **kwargs): - # replace references to self.transport with self - args = [self if arg == self.transport else arg for arg in args] - kwargs = dict((key, self if value == self.transport else value) for key, value in kwargs.items()) + def forward_handler(name): + def f(*args, **kwargs): + # replace references to self.transport with self + args = [self if arg == self.transport else arg for arg in args] + kwargs = dict( + (key, self if value == self.transport else value) + for key, value in kwargs.items() + ) - # forward - self.notify_listeners(name, *args, **kwargs) - return f + # forward + self.notify_listeners(name, *args, **kwargs) - for handler in filter(lambda x: x.startswith("on_transport_"), dir(TransportListener)): - if handler not in self.__class__.unforwarded_handlers: - setattr(self, handler, forward_handler(handler)) + return f - def __getattr__(self, item): - return getattr(self.transport, item) + for handler in filter( + lambda x: x.startswith("on_transport_"), dir(TransportListener) + ): + if handler not in self.__class__.unforwarded_handlers: + setattr(self, handler, forward_handler(handler)) + + def __getattr__(self, item): + return getattr(self.transport, item) class SeparatorAwareTransportWrapper(TransportWrapper): - unforwarded_handlers = ["on_transport_log_received_data"] - """We have read overwritten and hence send our own received_data notification.""" + unforwarded_handlers = ["on_transport_log_received_data"] + """We have read overwritten and hence send our own received_data notification.""" - def __init__(self, transport, terminator): - TransportWrapper.__init__(self, transport) + def __init__(self, transport, terminator): + TransportWrapper.__init__(self, transport) - self.terminator = terminator + self.terminator = terminator - self._buffered = bytearray() + self._buffered = bytearray() - def read(self, size=None, timeout=None): - start = monotonic_time() - termlen = len(self.terminator) - data = self._buffered + def read(self, size=None, timeout=None): + start = monotonic_time() + termlen = len(self.terminator) + data = self._buffered - while True: - # make sure we always read everything that is waiting - data += bytearray(self.transport.read(self.transport.in_waiting)) + while True: + # make sure we always read everything that is waiting + data += bytearray(self.transport.read(self.transport.in_waiting)) - # check for terminator, if it's there we have found our line - termpos = data.find(self.terminator) - if termpos >= 0: - # line: everything up to and incl. the terminator - line = data[:termpos + termlen] + # check for terminator, if it's there we have found our line + termpos = data.find(self.terminator) + if termpos >= 0: + # line: everything up to and incl. the terminator + line = data[: termpos + termlen] - # buffered: everything after the terminator - self._buffered = data[termpos + termlen:] + # buffered: everything after the terminator + self._buffered = data[termpos + termlen :] - received = bytes(line) - self.notify_listeners("on_transport_log_received_data", self, received) - return received + received = bytes(line) + self.notify_listeners("on_transport_log_received_data", self, received) + return received - # check if timeout expired - if timeout and monotonic_time() > start + timeout: - break + # check if timeout expired + if timeout and monotonic_time() > start + timeout: + break - # if we arrive here we so far couldn't read a full line, wait for more data - c = self.transport.read(1) - if not c: - # EOF - break + # if we arrive here we so far couldn't read a full line, wait for more data + c = self.transport.read(1) + if not c: + # EOF + break - # add to data and loop - data += c + # add to data and loop + data += c - self._buffered = data + self._buffered = data - raise TimeoutTransportException() + raise TimeoutTransportException() + + def __str__(self): + return "SeparatorAwareTransportWrapper({}, separator={})".format( + self.transport, self.terminator + ) - def __str__(self): - return "SeparatorAwareTransportWrapper({}, separator={})".format(self.transport, self.terminator) class LineAwareTransportWrapper(SeparatorAwareTransportWrapper): + def __init__(self, transport): + SeparatorAwareTransportWrapper.__init__(self, transport, b"\n") - def __init__(self, transport): - SeparatorAwareTransportWrapper.__init__(self, transport, b"\n") + def __str__(self): + return "LineAwareTransportWrapper({})".format(self.transport) - def __str__(self): - return "LineAwareTransportWrapper({})".format(self.transport) class PushingTransportWrapper(TransportWrapper): + def __init__( + self, transport, name=b"PushingTransportWrapper.receiver_loop", timeout=None + ): + super(PushingTransportWrapper, self).__init__(transport) + self.name = name + self.timeout = timeout - def __init__(self, transport, name=b"PushingTransportWrapper.receiver_loop", timeout=None): - super(PushingTransportWrapper, self).__init__(transport) - self.name = name - self.timeout = timeout + self._receiver_active = False + self._receiver_thread = None - self._receiver_active = False - self._receiver_thread = None + @property + def active(self): + return self._receiver_active - @property - def active(self): - return self._receiver_active + def connect(self, **kwargs): + self.transport.connect(**kwargs) - def connect(self, **kwargs): - self.transport.connect(**kwargs) + import threading - import threading + self._receiver_active = True + self._receiver_thread = threading.Thread( + target=self._receiver_loop, name=self.name + ) + self._receiver_thread.daemon = True + self._receiver_thread.start() - self._receiver_active = True - self._receiver_thread = threading.Thread(target=self._receiver_loop, name=self.name) - self._receiver_thread.daemon = True - self._receiver_thread.start() + def disconnect(self, *args, **kwargs): + self._receiver_active = False + self.transport.disconnect(*args, **kwargs) - def disconnect(self, *args, **kwargs): - self._receiver_active = False - self.transport.disconnect(*args, **kwargs) + def wait(self): + self._receiver_thread.join() - def wait(self): - self._receiver_thread.join() + def _receiver_loop(self): + while self._receiver_active: + try: + data = self.transport.read(timeout=self.timeout) + self.notify_listeners("on_transport_data_pushed", self, data) + except TimeoutTransportException as ex: + self.notify_listeners("on_transport_data_exception", self, ex) + except Exception: + if self._receiver_active: + raise - def _receiver_loop(self): - while self._receiver_active: - try: - data = self.transport.read(timeout=self.timeout) - self.notify_listeners("on_transport_data_pushed", self, data) - except TimeoutTransportException as ex: - self.notify_listeners("on_transport_data_exception", self, ex) - except Exception: - if self._receiver_active: - raise + def __str__(self): + return "PushingTransportWrapper({})".format(self.transport) - def __str__(self): - return "PushingTransportWrapper({})".format(self.transport) class TransportListener(object): + def on_transport_connected(self, transport): + pass - def on_transport_connected(self, transport): - pass + def on_transport_disconnected(self, transport, error=None): + pass - def on_transport_disconnected(self, transport, error=None): - pass + def on_transport_log_sent_data(self, transport, data): + pass - def on_transport_log_sent_data(self, transport, data): - pass + def on_transport_log_received_data(self, transport, data): + pass - def on_transport_log_received_data(self, transport, data): - pass + def on_transport_log_message(self, transport, data): + pass - def on_transport_log_message(self, transport, data): - pass class PushingTransportWrapperListener(object): + def on_transport_data_pushed(self, transport, data): + pass - def on_transport_data_pushed(self, transport, data): - pass + def on_transport_data_exception(self, transport, exception): + pass - def on_transport_data_exception(self, transport, exception): - pass class TransportException(Exception): - pass + pass + class TimeoutTransportException(TransportException): - pass + pass + class EofTransportException(TransportException): - pass + pass diff --git a/src/octoprint/comm/transport/serialtransport.py b/src/octoprint/comm/transport/serialtransport.py index 3b69c8ab3..c9cdf9034 100644 --- a/src/octoprint/comm/transport/serialtransport.py +++ b/src/octoprint/comm/transport/serialtransport.py @@ -1,241 +1,304 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" -from octoprint.comm.transport import Transport, LineAwareTransportWrapper, PushingTransportWrapper -from octoprint.comm.util.parameters import TextType, IntegerType, ChoiceType, SuggestionType, BooleanType, Value, SmallChoiceType - -from octoprint.util import dummy_gettext as gettext - -import serial import logging +import serial + +from octoprint.comm.transport import Transport +from octoprint.comm.util.parameters import ( + BooleanType, + ChoiceType, + IntegerType, + SmallChoiceType, + SuggestionType, + Value, +) +from octoprint.util import dummy_gettext as gettext + + class SerialTransport(Transport): - name = "Serial Connection" - key = "serial" - message_integrity = False + name = "Serial Connection" + key = "serial" + message_integrity = False - suggested_baudrates = [250000, 230400, 115200, 57600, 38400, 19200, 9600] - unix_port_patterns = ["/dev/ttyUSB*", "/dev/ttyACM*", "/dev/tty.usb*", - "/dev/cu.*", "/dev/cuaU*", "/dev/rfcomm*"] + suggested_baudrates = [250000, 230400, 115200, 57600, 38400, 19200, 9600] + unix_port_patterns = [ + "/dev/ttyUSB*", + "/dev/ttyACM*", + "/dev/tty.usb*", + "/dev/cu.*", + "/dev/cuaU*", + "/dev/rfcomm*", + ] - max_write_passes = 5 + max_write_passes = 5 - @classmethod - def for_additional_ports_and_baudrates(cls, additional_ports, additional_baudrates): - patterns = SerialTransport.unix_port_patterns - if additional_ports: - patterns += additional_ports + @classmethod + def for_additional_ports_and_baudrates(cls, additional_ports, additional_baudrates): + patterns = SerialTransport.unix_port_patterns + if additional_ports: + patterns += additional_ports - baudrates = SerialTransport.suggested_baudrates - if additional_baudrates: - baudrates += additional_baudrates + baudrates = SerialTransport.suggested_baudrates + if additional_baudrates: + baudrates += additional_baudrates - return type(cls.__name__ + b"WithAdditionalPorts", - (cls,), - {b"unix_port_patterns": patterns, - b"suggested_baudrates": baudrates}) + return type( + cls.__name__ + b"WithAdditionalPorts", + (cls,), + {b"unix_port_patterns": patterns, b"suggested_baudrates": baudrates}, + ) - @classmethod - def get_connection_options(cls): - return [ - SuggestionType("port", - gettext("Port"), - cls.get_available_serial_ports(), - lambda value: Value(value)), - SuggestionType("baudrate", - gettext("Baudrate"), - cls.get_available_baudrates(), - lambda value: Value(value), - default=0), - IntegerType("write_timeout", - gettext("Write Timeout"), - min=1, - unit="sec", - default=10, - advanced=True), - BooleanType("exclusive", - gettext("Request exclusive access to the serial port"), - help=gettext("Uncheck this if you are having problems connecting to your printer."), - default=True, - advanced=True), - ChoiceType("parity", - gettext("Parity"), - [Value(serial.PARITY_NONE, gettext("none")), - Value(serial.PARITY_ODD, gettext("odd")), - Value(serial.PARITY_EVEN, gettext("even"))], - default=serial.PARITY_NONE, - advanced=True, - expert=True), - # TODO: implement parity workaround flag - SmallChoiceType("parity_workaround", - gettext("Apply parity double open workaround"), - [Value("always", - title=gettext("Always"), - help=gettext("Use this if you are running into [this problem](https://forum.arduino.cc/index.php?topic=91291.0).")), - Value("detect", - title=gettext("If detected as potentially needed")), - Value("never", - title=gettext("Never"), - help=gettext("Use this if connecting to your printer fails with `(22, 'Invalid argument')`."))], - default="detect", - advanced=True, - expert=True) - ] + @classmethod + def get_connection_options(cls): + return [ + SuggestionType( + "port", + gettext("Port"), + cls.get_available_serial_ports(), + lambda value: Value(value), + ), + SuggestionType( + "baudrate", + gettext("Baudrate"), + cls.get_available_baudrates(), + lambda value: Value(value), + default=0, + ), + IntegerType( + "write_timeout", + gettext("Write Timeout"), + min=1, + unit="sec", + default=10, + advanced=True, + ), + BooleanType( + "exclusive", + gettext("Request exclusive access to the serial port"), + help=gettext( + "Uncheck this if you are having problems connecting to your printer." + ), + default=True, + advanced=True, + ), + ChoiceType( + "parity", + gettext("Parity"), + [ + Value(serial.PARITY_NONE, gettext("none")), + Value(serial.PARITY_ODD, gettext("odd")), + Value(serial.PARITY_EVEN, gettext("even")), + ], + default=serial.PARITY_NONE, + advanced=True, + expert=True, + ), + # TODO: implement parity workaround flag + SmallChoiceType( + "parity_workaround", + gettext("Apply parity double open workaround"), + [ + Value( + "always", + title=gettext("Always"), + help=gettext( + "Use this if you are running into [this problem](https://forum.arduino.cc/index.php?topic=91291.0)." + ), + ), + Value("detect", title=gettext("If detected as potentially needed")), + Value( + "never", + title=gettext("Never"), + help=gettext( + "Use this if connecting to your printer fails with `(22, 'Invalid argument')`." + ), + ), + ], + default="detect", + advanced=True, + expert=True, + ), + ] - @classmethod - def get_available_serial_ports(cls): - import sys + @classmethod + def get_available_serial_ports(cls): + import sys - if sys.platform == "win32": - # windows - from serial.tools.list_ports import comports - ports = comports() + if sys.platform == "win32": + # windows + from serial.tools.list_ports import comports - else: - # posix - import glob + ports = comports() - devices = [device - for pattern in cls.unix_port_patterns - for device in glob.glob(pattern)] + else: + # posix + import glob - plat = sys.platform.lower() + devices = [ + device + for pattern in cls.unix_port_patterns + for device in glob.glob(pattern) + ] - if plat[:5] == "linux": - # linux - from serial.tools.list_ports_linux import SysFS - ports = [info - for info in [SysFS(d) for d in devices] - if info.subsystem != "platform"] - else: - # other posix systems - from serial.tools import list_ports_common - ports = [list_ports_common.ListPortInfo(d) for d in devices] + plat = sys.platform.lower() - port_values = [Value(None, title="Auto detect")] + sorted([Value(port.device, title=port.description) for port in ports], key=lambda x: x.title) - return port_values + if plat[:5] == "linux": + # linux + from serial.tools.list_ports_linux import SysFS - @classmethod - def get_available_baudrates(cls): - return [Value(0, title="Auto detect")] + \ - sorted([Value(baudrate) for baudrate in cls.suggested_baudrates], key=lambda x: x.title, reverse=True) + ports = [ + info + for info in [SysFS(d) for d in devices] + if info.subsystem != "platform" + ] + else: + # other posix systems + from serial.tools import list_ports_common - def __init__(self, *args, **kwargs): - super(SerialTransport, self).__init__() + ports = [list_ports_common.ListPortInfo(d) for d in devices] - self.serial_factory = kwargs.get("serial_factory", None) + port_values = [Value(None, title="Auto detect")] + sorted( + [Value(port.device, title=port.description) for port in ports], + key=lambda x: x.title, + ) + return port_values - self._logger = logging.getLogger(__name__) - self._serial = None + @classmethod + def get_available_baudrates(cls): + return [Value(0, title="Auto detect")] + sorted( + [Value(baudrate) for baudrate in cls.suggested_baudrates], + key=lambda x: x.title, + reverse=True, + ) - self._closing = False + def __init__(self, *args, **kwargs): + super(SerialTransport, self).__init__() - def create_connection(self, **kwargs): - factory = self.serial_factory - if self.serial_factory is None: - factory = self._default_serial_factory + self.serial_factory = kwargs.get("serial_factory", None) - self._closing = False - self._serial = factory(**kwargs) - self.set_current_args(**kwargs) + self._logger = logging.getLogger(__name__) + self._serial = None - return True + self._closing = False - def drop_connection(self, wait=True): - error = False + def create_connection(self, **kwargs): + factory = self.serial_factory + if self.serial_factory is None: + factory = self._default_serial_factory - if self._serial is not None: - self._closing = True + self._closing = False + self._serial = factory(**kwargs) + self.set_current_args(**kwargs) - try: - if callable(getattr(self._serial, "cancel_read", None)): - self._serial.cancel_read() - except Exception: - self._logger.exception("Error while cancelling pending reads from the serial port") + return True - try: - if callable(getattr(self._serial, "cancel_write", None)): - self._serial.cancel_write() - except Exception: - self._logger.exception("Error while cancelling pending writes to the serial port") + def drop_connection(self, wait=True): + error = False - try: - self._serial.close() - except Exception: - self._logger.exception("Error while closing the serial port") - error = True + if self._serial is not None: + self._closing = True - self._serial = None + try: + if callable(getattr(self._serial, "cancel_read", None)): + self._serial.cancel_read() + except Exception: + self._logger.exception( + "Error while cancelling pending reads from the serial port" + ) - return not error + try: + if callable(getattr(self._serial, "cancel_write", None)): + self._serial.cancel_write() + except Exception: + self._logger.exception( + "Error while cancelling pending writes to the serial port" + ) - def do_read(self, size=None, timeout=None): - return self._serial.read(size=size) + try: + self._serial.close() + except Exception: + self._logger.exception("Error while closing the serial port") + error = True - def do_write(self, data): - written = 0 - passes = 0 + self._serial = None - def try_to_write(d): - result = self._serial.write(d) - if result is None or not isinstance(result, int): - # probably some plugin not returning the written bytes, assuming all of them - return len(data) - else: - return result + return not error - while written < len(data): - to_send = data[written:] - old_written = written + def do_read(self, size=None, timeout=None): + return self._serial.read(size=size) - try: - written += try_to_write(to_send) - except serial.SerialTimeoutException: - self._logger.warn("Serial timeout while writing to serial port, trying again.") - try: - # second try - written += try_to_write(to_send) - except Exception: - if not self._closing: - message = "Unexpected error while writing to serial port" - self._logger.exception(message) - self.disconnect(error=message) - break - except Exception: - if not self._closing: - message = "Unexpected error while writing to serial port" - self._logger.exception(message) - self.disconnect(error=message) - break + def do_write(self, data): + written = 0 + passes = 0 - if old_written == written: - passes += 1 - if passes > self.max_write_passes: - message = "Could not write anything to the serial port in {} tries, something appears to be " \ - "wrong with the printer communication".format(self.max_write_passes) - self._logger.error(message) - self.disconnect(error=message) - break + def try_to_write(d): + result = self._serial.write(d) + if result is None or not isinstance(result, int): + # probably some plugin not returning the written bytes, assuming all of them + return len(data) + else: + return result - @property - def in_waiting(self): - return getattr(self._serial, "in_waiting", 0) + while written < len(data): + to_send = data[written:] + old_written = written - def _default_serial_factory(self, **kwargs): - return serial.Serial(port=kwargs.get("port"), - baudrate=kwargs.get("baudrate"), - exclusive=kwargs.get("exclusive"), - parity=kwargs.get("parity"), - write_timeout=kwargs.get("write_timeout", 10) * 1000) + try: + written += try_to_write(to_send) + except serial.SerialTimeoutException: + self._logger.warn( + "Serial timeout while writing to serial port, trying again." + ) + try: + # second try + written += try_to_write(to_send) + except Exception: + if not self._closing: + message = "Unexpected error while writing to serial port" + self._logger.exception(message) + self.disconnect(error=message) + break + except Exception: + if not self._closing: + message = "Unexpected error while writing to serial port" + self._logger.exception(message) + self.disconnect(error=message) + break + + if old_written == written: + passes += 1 + if passes > self.max_write_passes: + message = ( + "Could not write anything to the serial port in {} tries, something appears to be " + "wrong with the printer communication".format( + self.max_write_passes + ) + ) + self._logger.error(message) + self.disconnect(error=message) + break + + @property + def in_waiting(self): + return getattr(self._serial, "in_waiting", 0) + + def _default_serial_factory(self, **kwargs): + return serial.Serial( + port=kwargs.get("port"), + baudrate=kwargs.get("baudrate"), + exclusive=kwargs.get("exclusive"), + parity=kwargs.get("parity"), + write_timeout=kwargs.get("write_timeout", 10) * 1000, + ) + + def __str__(self): + return "SerialTransport" - def __str__(self): - return "SerialTransport" if __name__ == "__main__": - # list ports - ports = SerialTransport.get_available_serial_ports() - for port in ports: - print(port.title + ": " + port.value) + # list ports + ports = SerialTransport.get_available_serial_ports() + for port in ports: + print(port.title + ": " + port.value) diff --git a/src/octoprint/comm/transport/sockettransport.py b/src/octoprint/comm/transport/sockettransport.py index ceef306e8..4bef0d806 100644 --- a/src/octoprint/comm/transport/sockettransport.py +++ b/src/octoprint/comm/transport/sockettransport.py @@ -1,65 +1,61 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" -from octoprint.comm.transport import Transport, LineAwareTransportWrapper -from octoprint.comm.util.parameters import TextType, IntegerType - import socket +from octoprint.comm.transport import Transport +from octoprint.comm.util.parameters import IntegerType, TextType + + class TcpTransport(Transport): - name = "TCP Connection" - key = "tcpsocket" - message_integrity = True + name = "TCP Connection" + key = "tcpsocket" + message_integrity = True - @classmethod - def get_connection_options(cls): - return [ - TextType("host", "Host"), - IntegerType("port", "Port", min=1, max=65535) - ] + @classmethod + def get_connection_options(cls): + return [TextType("host", "Host"), IntegerType("port", "Port", min=1, max=65535)] - def __init__(self): - super(TcpTransport, self).__init__() + def __init__(self): + super(TcpTransport, self).__init__() - self._socket = None + self._socket = None - def create_connection(self, host=None, port=None): - if host is None: - raise ValueError("host must not be None") - if port is None: - raise ValueError("port must not be None") + def create_connection(self, host=None, port=None): + if host is None: + raise ValueError("host must not be None") + if port is None: + raise ValueError("port must not be None") - self._socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) - self._socket.connect((host, port)) - self.set_current_args(host=host, port=port) + self._socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) + self._socket.connect((host, port)) + self.set_current_args(host=host, port=port) - return True + return True - def drop_connection(self, wait=True): - try: - self._socket.close() - return True - except Exception: - self._logger.exception("Error closing socket") - return False + def drop_connection(self, wait=True): + try: + self._socket.close() + return True + except Exception: + self._logger.exception("Error closing socket") + return False - def do_read(self, size=None, timeout=None): - if size is None: - size = 16 - return self._socket.recv(size) + def do_read(self, size=None, timeout=None): + if size is None: + size = 16 + return self._socket.recv(size) - def do_write(self, data): - self._socket.sendall(data) + def do_write(self, data): + self._socket.sendall(data) + + def __str__(self): + return "TcpTransport" - def __str__(self): - return "TcpTransport" class SerialOverTcpTransport(TcpTransport): - name = "Serial Connection over TCP" - key = "serialovertcpsocket" - message_integrity = False + name = "Serial Connection over TCP" + key = "serialovertcpsocket" + message_integrity = False diff --git a/src/octoprint/comm/util/parameters.py b/src/octoprint/comm/util/parameters.py index 31f249542..82f1b36cb 100644 --- a/src/octoprint/comm/util/parameters.py +++ b/src/octoprint/comm/util/parameters.py @@ -1,235 +1,273 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" -from past.builtins import unicode def get_param_dict(data, options): - options_by_name = dict((option.name, option) for option in options) + options_by_name = dict((option.name, option) for option in options) - result = dict() - for key, value in data.items(): - if not key in options_by_name: - continue - option = options_by_name[key] - result[key] = option.convert(value) - return result + result = {} + for key, value in data.items(): + if key not in options_by_name: + continue + option = options_by_name[key] + result[key] = option.convert(value) + return result class ParamType(object): - type = "generic" + type = "generic" - def __init__(self, name, title, default=None, advanced=False, expert=False, warning=False, labels=None, help=None): - if labels is None: - labels = [] + def __init__( + self, + name, + title, + default=None, + advanced=False, + expert=False, + warning=False, + labels=None, + help=None, + ): + if labels is None: + labels = [] - self.name = name - self.title = title - self.default = default - self.advanced = advanced - self.expert = expert - self.warning = warning - self.labels = labels - self.help = help + self.name = name + self.title = title + self.default = default + self.advanced = advanced + self.expert = expert + self.warning = warning + self.labels = labels + self.help = help - def as_dict(self): - return dict(name=self.name, - title=self.title, - default=self.default, - advanced=self.advanced, - expert=self.expert, - warning=self.warning, - labels=self.labels, - help=self.help, - type=self.type) + def as_dict(self): + return { + "name": self.name, + "title": self.title, + "default": self.default, + "advanced": self.advanced, + "expert": self.expert, + "warning": self.warning, + "labels": self.labels, + "help": self.help, + "type": self.type, + } - def convert(self, value): - return value + def convert(self, value): + return value + + def __repr__(self): + return ( + "{}(".format(self.__class__.__name__) + + ", ".join( + [ + "{}={!r}".format(key, value) + for key, value in self.__dict__.items() + if not key.startswith("_") + ] + ) + + ")" + ) - def __repr__(self): - return "{}(".format(self.__class__.__name__) \ - + ", ".join(["{}={!r}".format(key, value) for key, value in self.__dict__.items() if not key.startswith("_")]) + ")" class TextType(ParamType): - type = "text" + type = "text" + + def convert(self, value): + if isinstance(value, bytes): + value = value.decode("utf-8", "replace") + return value - def convert(self, value): - if isinstance(value, bytes): - value = value.decode("utf-8", "replace") - return value class IntegerType(ParamType): - type = "integer" + type = "integer" - def __init__(self, name, title, min=None, max=None, unit=None, **kwargs): - self.min = min - self.max = max - self.unit = unit - ParamType.__init__(self, name, title, **kwargs) + def __init__(self, name, title, min=None, max=None, unit=None, **kwargs): + self.min = min + self.max = max + self.unit = unit + ParamType.__init__(self, name, title, **kwargs) - def as_dict(self): - result = ParamType.as_dict(self) - result.update(dict(min=self.min, - max=self.max, - unit=self.unit)) - return result + def as_dict(self): + result = ParamType.as_dict(self) + result.update({"min": self.min, "max": self.max, "unit": self.unit}) + return result - def convert(self, value): - try: - value = int(value) - except ValueError: - raise ValueError("value {!r} is not a valid integer".format(value)) + def convert(self, value): + try: + value = int(value) + except ValueError: + raise ValueError("value {!r} is not a valid integer".format(value)) - if self.min is not None and value < self.min: - raise ValueError("value {} is less than minimum valid value {}".format(value, self.min)) - if self.max is not None and value > self.max: - raise ValueError("value {} is greater than maximum valid value {}".format(value, self.max)) + if self.min is not None and value < self.min: + raise ValueError( + "value {} is less than minimum valid value {}".format(value, self.min) + ) + if self.max is not None and value > self.max: + raise ValueError( + "value {} is greater than maximum valid value {}".format(value, self.max) + ) + + return value - return value class FloatType(ParamType): - type = "float" + type = "float" - def __init__(self, name, title, min=None, max=None, unit=None, **kwargs): - self.min = min - self.max = max - self.unit = unit - ParamType.__init__(self, name, title, **kwargs) + def __init__(self, name, title, min=None, max=None, unit=None, **kwargs): + self.min = min + self.max = max + self.unit = unit + ParamType.__init__(self, name, title, **kwargs) - def as_dict(self): - result = ParamType.as_dict(self) - result.update(dict(min=self.min, - max=self.max, - unit=self.unit)) - return result + def as_dict(self): + result = ParamType.as_dict(self) + result.update({"min": self.min, "max": self.max, "unit": self.unit}) + return result - def convert(self, value): - try: - value = float(value) - except ValueError: - raise ValueError("value {!r} is not a valid float".format(value)) + def convert(self, value): + try: + value = float(value) + except ValueError: + raise ValueError("value {!r} is not a valid float".format(value)) - if self.min is not None and value < self.min: - raise ValueError("value {} is less than minimum valid value {}".format(value, self.min)) - if self.max is not None and value > self.max: - raise ValueError("value {} is greater than maximum valid value {}".format(value, self.max)) + if self.min is not None and value < self.min: + raise ValueError( + "value {} is less than minimum valid value {}".format(value, self.min) + ) + if self.max is not None and value > self.max: + raise ValueError( + "value {} is greater than maximum valid value {}".format(value, self.max) + ) + + return value - return value class BooleanType(ParamType): - type = "boolean" + type = "boolean" - def convert(self, value): - try: - value = bool(value) - except ValueError: - raise ValueError("value {!r} is not a valid boolean".format(value)) + def convert(self, value): + try: + value = bool(value) + except ValueError: + raise ValueError("value {!r} is not a valid boolean".format(value)) + + return value - return value class ChoiceType(ParamType): - type = "choice" + type = "choice" - def __init__(self, name, title, choices, **kwargs): - self.choices = choices - ParamType.__init__(self, name, title, **kwargs) + def __init__(self, name, title, choices, **kwargs): + self.choices = choices + ParamType.__init__(self, name, title, **kwargs) + + def as_dict(self): + result = ParamType.as_dict(self) + result.update({"choices": list(map(lambda x: x.as_dict(), self.choices))}) + return result - def as_dict(self): - result = ParamType.as_dict(self) - result.update(dict(choices=list(map(lambda x: x.as_dict(), self.choices)))) - return result class SmallChoiceType(ChoiceType): - type = "smallchoice" + type = "smallchoice" + class GroupChoiceType(ChoiceType): - type = "groupchoice" + type = "groupchoice" - def __init__(self, name, title, choices, group, defaults=None, **kwargs): - if defaults is None: - defaults = dict() + def __init__(self, name, title, choices, group, defaults=None, **kwargs): + if defaults is None: + defaults = {} - ChoiceType.__init__(self, name, title, choices, **kwargs) + ChoiceType.__init__(self, name, title, choices, **kwargs) - self.group = group - self.defaults = defaults + self.group = group + self.defaults = defaults + + def as_dict(self): + result = ChoiceType.as_dict(self) + result["group"] = self.group.as_dict() + result["defaults"] = self.defaults + return result - def as_dict(self): - result = ChoiceType.as_dict(self) - result["group"] = self.group.as_dict() - result["defaults"] = self.defaults - return result class SuggestionType(ParamType): - type = "suggestion" + type = "suggestion" - def __init__(self, name, title, suggestions, factory, **kwargs): - self.suggestions = suggestions - self.factory = factory - ParamType.__init__(self, name, title, **kwargs) + def __init__(self, name, title, suggestions, factory, **kwargs): + self.suggestions = suggestions + self.factory = factory + ParamType.__init__(self, name, title, **kwargs) + + def as_dict(self): + result = ParamType.as_dict(self) + result.update({"suggestions": list(map(lambda x: x.as_dict(), self.suggestions))}) + return result - def as_dict(self): - result = ParamType.as_dict(self) - result.update(dict(suggestions=list(map(lambda x: x.as_dict(), self.suggestions)))) - return result class ListType(ParamType): - type = "list" + type = "list" - def __init__(self, name, title, factory=None, **kwargs): - if factory is None: - factory = lambda x: x + def __init__(self, name, title, factory=None, **kwargs): + if factory is None: + factory = lambda x: x - self.factory = factory - ParamType.__init__(self, name, title, **kwargs) + self.factory = factory + ParamType.__init__(self, name, title, **kwargs) - def convert(self, value): - if isinstance(value, unicode): - items = map(unicode.strip, value.split(",")) - elif isinstance(value, list): - items = value - else: - raise ValueError("value {!r} must be either a comma-separated string or a list".format(value)) + def convert(self, value): + if isinstance(value, str): + items = map(str.strip, value.split(",")) + elif isinstance(value, list): + items = value + else: + raise ValueError( + "value {!r} must be either a comma-separated string or a list".format( + value + ) + ) + + return list(map(self.factory, items)) - return list(map(self.factory, items)) class SmallListType(ListType): - type = "smalllist" + type = "smalllist" + class ParamGroup(ParamType): - type = "group" + type = "group" - def __init__(self, name, title, params, **kwargs): - ParamType.__init__(self, name, title, **kwargs) - self.params = params + def __init__(self, name, title, params, **kwargs): + ParamType.__init__(self, name, title, **kwargs) + self.params = params - def as_dict(self): - result = ParamType.as_dict(self) - result["params"] = [x.as_dict() for x in self.params] - return result + def as_dict(self): + result = ParamType.as_dict(self) + result["params"] = [x.as_dict() for x in self.params] + return result + + def convert(self, value): + if not isinstance(value, dict): + raise ValueError("value {!r} must be a dict".format(value)) + return dict((k, v.convert()) for k, v in value.items()) - def convert(self, value): - if not isinstance(value, dict): - raise ValueError("value {!r} must be a dict".format(value)) - return dict((k, v.convert()) for k, v in value.items()) class Value(object): - def __init__(self, value, title=None, warning=False, labels=None, help=None): - if labels is None: - labels = [] + def __init__(self, value, title=None, warning=False, labels=None, help=None): + if labels is None: + labels = [] - self.value = value - self.title = title if title else value - self.warning = warning - self.labels = labels - self.help = help - - def as_dict(self): - return dict(value=self.value, - title=self.title, - warning=self.warning, - labels=self.labels, - help=self.help) + self.value = value + self.title = title if title else value + self.warning = warning + self.labels = labels + self.help = help + def as_dict(self): + return { + "value": self.value, + "title": self.title, + "warning": self.warning, + "labels": self.labels, + "help": self.help, + } diff --git a/src/octoprint/daemon.py b/src/octoprint/daemon.py index dab6751bd..7548e23c2 100644 --- a/src/octoprint/daemon.py +++ b/src/octoprint/daemon.py @@ -1,176 +1,186 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ 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 (OSError, 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..47356c9e8 100644 --- a/src/octoprint/environment.py +++ b/src/octoprint/environment.py @@ -1,7 +1,4 @@ -# -*- 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 +6,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 +class EnvironmentDetector: + 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 = dict() - environment["os"] = self._detect_os() - environment["python"] = self._detect_python() - environment["hardware"] = self._detect_hardware() + def run_detection(self, notify_plugins=True): + try: + environment = {} + environment["os"] = self._detect_os() + environment["python"] = self._detect_python() + environment["hardware"] = self._detect_hardware() - plugin_result = self._detect_from_plugins() - if plugin_result: - environment["plugins"] = plugin_result + plugin_result = self._detect_from_plugins() + if plugin_result: + environment["plugins"] = plugin_result - with self._cache_lock: - self._cache = environment + with self._cache_lock: + self._cache = environment - if notify_plugins: - self.notify_plugins() + if notify_plugins: + self.notify_plugins() - return environment - except Exception: - self._logger.exception("Unexpected error while detecting environment") - with self._cache_lock: - self._cache = dict() - return self._cache + return environment + except Exception: + self._logger.exception("Unexpected error while detecting environment") + with self._cache_lock: + self._cache = {} + return self._cache - def _detect_os(self): - return dict(id=get_os(), - platform=sys.platform) + def _detect_os(self): + return { + "id": get_os(), + "platform": sys.platform, + "bits": 64 if sys.maxsize > 2 ** 32 else 32, + } - def _detect_python(self): - result = dict(version="unknown", - pip="unknown") + def _detect_python(self): + result = {"version": "unknown", "pip": "unknown"} - # determine python version - try: - result["version"] = get_python_version_string() - except Exception: - self._logger.exception("Error detecting python version") + # determine python version + try: + result["version"] = get_python_version_string() + except Exception: + self._logger.exception("Error detecting python version") - # determine if we are running from a virtual environment - try: - if hasattr(sys, "real_prefix") or (hasattr(sys, "base_prefix") and os.path.realpath(sys.prefix) != os.path.realpath(sys.base_prefix)): - result["virtualenv"] = sys.prefix - except Exception: - self._logger.exception("Error detecting whether we are running in a virtual environment") + # determine if we are running from a virtual environment + try: + if hasattr(sys, "real_prefix") or ( + hasattr(sys, "base_prefix") + and os.path.realpath(sys.prefix) != os.path.realpath(sys.base_prefix) + ): + result["virtualenv"] = sys.prefix + except Exception: + self._logger.exception( + "Error detecting whether we are running in a virtual environment" + ) - # try to find pip version - try: - import pkg_resources - result["pip"] = pkg_resources.get_distribution("pip").version - except Exception: - self._logger.exception("Error detecting pip version") + # try to find pip version + try: + import pkg_resources - return result + result["pip"] = pkg_resources.get_distribution("pip").version + except Exception: + self._logger.exception("Error detecting pip version") - def _detect_hardware(self): - result = dict(cores="unknown", - freq="unknown", - ram="unknown") + return result - 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") + def _detect_hardware(self): + result = {"cores": "unknown", "freq": "unknown", "ram": "unknown"} - return result + 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") - def _detect_from_plugins(self): - result = dict() + return 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)) + def _detect_from_plugins(self): + result = {} - return result + for implementation in self._environment_plugins: + try: + additional = implementation.get_additional_environment() + if ( + additional is not None + and isinstance(additional, dict) + and len(additional) + ): + result[implementation._identifier] = additional + except Exception: + self._logger.exception( + "Error while fetching additional " + "environment data from plugin {}".format(implementation._identifier), + extra={"plugin": implementation._identifier}, + ) - 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) + return result - try: - _log(self._format()) - except Exception: - self._logger.exception("Error logging detected environment") + 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 - def _format(self): - with self._cache_lock: - if self._cache is None: - self.run_detection() - environment = copy.deepcopy(self._cache) + octoprint.logging.log_to_handler( + self._logger, only_to_handler, level, message, [] + ) + else: + self._logger.log(level, message) - 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) + try: + _log(self._format()) + except Exception: + self._logger.exception("Error logging detected environment") - def notify_plugins(self): - with self._cache_lock: - if self._cache is None: - self.run_detection(notify_plugins=False) - environment = copy.deepcopy(self._cache) + def _format(self): + with self._cache_lock: + if self._cache is None: + self.run_detection() + 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)) + 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 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 b552e6a9c..2a349717b 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -1,490 +1,535 @@ -# -*- coding: utf-8 -*- -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 collections import datetime import logging -import subprocess -try: - import queue -except ImportError: - import Queue as queue -import threading -import collections +import queue import re +import subprocess +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" +class Events: + # 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" + # connect/disconnect by client + CLIENT_OPENED = "ClientOpened" + CLIENT_CLOSED = "ClientClosed" + CLIENT_AUTHED = "ClientAuthed" + CLIENT_DEAUTHED = "ClientDeauthed" - # 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" + # user login/logout + USER_LOGGED_IN = "UserLoggedIn" + USER_LOGGED_OUT = "UserLoggedOut" - FILE_ADDED = "FileAdded" - FILE_REMOVED = "FileRemoved" - FOLDER_ADDED = "FolderAdded" - FOLDER_REMOVED = "FolderRemoved" + # 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" - # SD Upload - TRANSFER_STARTED = "TransferStarted" - TRANSFER_DONE = "TransferDone" - TRANSFER_FAILED = "TransferFailed" + FILE_ADDED = "FileAdded" + FILE_REMOVED = "FileRemoved" + FOLDER_ADDED = "FolderAdded" + FOLDER_REMOVED = "FolderRemoved" - # 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" + # SD Upload + TRANSFER_STARTED = "TransferStarted" + TRANSFER_DONE = "TransferDone" + TRANSFER_FAILED = "TransferFailed" - # 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 job + PRINT_STARTED = "PrintStarted" + PRINT_DONE = "PrintDone" + PRINT_FAILED = "PrintFailed" + PRINT_CANCELLING = "PrintCancelling" + PRINT_CANCELLED = "PrintCancelled" + PRINT_PAUSED = "PrintPaused" + PRINT_RESUMED = "PrintResumed" + ERROR = "Error" - # 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" + # 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" - # 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" + # 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" - # Printer Profiles - PRINTER_PROFILE_ADDED = "PrinterProfileAdded" - PRINTER_PROFILE_MODIFIED = "PrinterProfileModified" - PRINTER_PROFILE_DELETED = "PrinterProfileDeleted" + # 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" - # Settings - SETTINGS_UPDATED = "SettingsUpdated" + # Printer Profiles + PRINTER_PROFILE_ADDED = "PrinterProfileAdded" + PRINTER_PROFILE_MODIFIED = "PrinterProfileModified" + PRINTER_PROFILE_DELETED = "PrinterProfileDeleted" - @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 + # Settings + SETTINGS_UPDATED = "SettingsUpdated" - # 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 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])") + + @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 - """ +class EventManager: + """ + 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)) - if event == Events.UPDATED_FILES and "type" in payload and payload["type"] == "printables": - # when sending UpdatedFiles with type "printables", also send another event with deprecated type "gcode" - # TODO v1.4.0 Remove again - import copy - legacy_payload = copy.deepcopy(payload) - legacy_payload["type"] = "gcode" - q.put((event, legacy_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. - """ +class GenericEventListener: + """ + 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 f619c4e04..3b9dc932d 100644 --- a/src/octoprint/filemanager/__init__.py +++ b/src/octoprint/filemanager/__init__.py @@ -1,738 +1,1075 @@ -# -*- coding: utf-8 -*- -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 time +from collections import namedtuple import octoprint.plugin import octoprint.util - -from octoprint.events import eventManager, Events - -from .destinations import FileDestinations -from .analysis import QueueEntry, AnalysisQueue -from .util import AbstractFileWrapper, StreamWrapper, DiskFileWrapper +from octoprint.events import Events, eventManager from octoprint.util import get_fully_qualified_classname as fqcn -from collections import namedtuple - -# noinspection PyCompatibility -from past.builtins import basestring +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 - - -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") - - def initialize(self, process_backlog=False): - self.reload_plugins() - if process_backlog: - self.process_backlog() - - def process_backlog(self): - 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 create_print_job(self, destination, path, user=None): - return self._storage(destination).create_print_job(path, user=user) - - 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: - 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)) - except NotImplementedError: - pass - 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 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 + pass + + +class FileManager: + 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 = time.monotonic() + 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 = time.monotonic() + 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, + level=0, + force_refresh=False, + ): + if not destinations: + destinations = list(self._storage_managers.keys()) + if isinstance(destinations, str): + destinations = [destinations] + + result = {} + for dst in destinations: + result[dst] = self._storage_managers[dst].list_files( + path=path, + filter=filter, + recursive=recursive, + level=level, + 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 create_print_job(self, destination, path, user=None): + return self._storage(destination).create_print_job(path, user=user) + + 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: + 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, + }, + ) + except NotImplementedError: + pass + 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 f67fd9dbb..3e611d539 100644 --- a/src/octoprint/filemanager/analysis.py +++ b/src/octoprint/filemanager/analysis.py @@ -1,433 +1,506 @@ -# -*- coding: utf-8 -*- -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 -except ImportError: - import Queue as queue -import os -import threading import collections +import logging +import os +import queue +import threading import time from octoprint.events import Events, eventManager from octoprint.settings import settings -from octoprint.util import monotonic_time +from octoprint.util import dict_merge from octoprint.util import get_fully_qualified_classname as fqcn +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. +class AnalysisQueue: + """ + 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: - 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, + 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, + }, + ) - # TODO: deprecated, remove in a future release - "file": entry.path}) -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. +class AbstractAnalysisQueue: + """ + 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 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: + start_time = time.monotonic() + 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, time.monotonic() - start_time + ) + ) + self._finished_callback(self._current, result) + except RuntimeError as exc: + self._logger.error( + "Analysis for {} ran into error: {}".format(self._current, exc) + ) + finally: + self._current = None + self._current_progress = None - # TODO deprecated, remove in 1.4.0 - "file": entry.path}) - 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: - return self._current.analysis - try: - throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority \ - else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"]) - throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"]) - max_extruders = settings().getInt(["gcodeAnalysis", "maxExtruders"]) - g90_extruder = settings().getBoolean(["feature", "g90InfluencesExtruder"]) - speedx = self._current.printer_profile["axes"]["x"]["speed"] - speedy = self._current.printer_profile["axes"]["y"]["speed"] - offsets = self._current.printer_profile["extruder"]["offsets"] + import sarge + import yaml - 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) + if self._current.analysis and all( + map( + lambda x: x in self._current.analysis, + ("printingArea", "dimensions", "estimatedPrintTime", "filament"), + ) + ): + return self._current.analysis - self._logger.info("Invoking analysis command: {}".format(" ".join(command))) + 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._aborted = False - p = sarge.run(command, async_=True, stdout=sarge.Capture()) + 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) - 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._logger.info("Invoking analysis 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() + self._aborted = False + p = sarge.run( + command, close_fds=CLOSE_FDS, async_=True, stdout=sarge.Capture() + ) - 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))) + while len(p.commands) == 0: + # somewhat ugly... we can't use wait_events because + # the events might not be all set if an exception + # by sarge is triggered within the async process + # thread + time.sleep(0.01) - try: - # 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) + # by now we should have a command, let's wait for its + # process to have been prepared + p.commands[0].process_ready.wait() - # else continue - p.commands[0].poll() - finally: - p.close() + 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)) + ) - output = p.stdout.text - self._logger.debug("Got output: {!r}".format(output)) + 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 "RESULTS:" in output: - raise RuntimeError("No analysis result found") + # else continue + p.commands[0].poll() + finally: + p.close() - _, output = output.split("RESULTS:") - analysis = yaml.safe_load(output) + output = p.stdout.text + self._logger.debug("Got output: {!r}".format(output)) - 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] - } - return result - finally: - self._gcode = None + if "ERROR:" in output: + _, error = output.split("ERROR:") + raise RuntimeError(error.strip()) + elif "RESULTS:" not in output: + raise RuntimeError("No analysis result found") - def _do_abort(self, reenqueue=True): - self._aborted = True - self._reenqueue = reenqueue + _, output = output.split("RESULTS:") + analysis = yaml.safe_load(output) + + result = {} + result["printingArea"] = analysis["printing_area"] + result["dimensions"] = analysis["dimensions"] + if analysis["total_time"]: + result["estimatedPrintTime"] = analysis["total_time"] * 60 + if analysis["extrusion_length"]: + result["filament"] = {} + for i in range(len(analysis["extrusion_length"])): + result["filament"]["tool%d" % i] = { + "length": analysis["extrusion_length"][i], + "volume": analysis["extrusion_volume"][i], + } + + 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..ea9496d32 100644 --- a/src/octoprint/filemanager/destinations.py +++ b/src/octoprint/filemanager/destinations.py @@ -1,9 +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' -class FileDestinations(object): +class FileDestinations: - SDCARD = "sdcard" - LOCAL = "local" + SDCARD = "sdcard" + LOCAL = "local" diff --git a/src/octoprint/filemanager/storage/__init__.py b/src/octoprint/filemanager/storage/__init__.py index 428f268e2..f3a194b30 100644 --- a/src/octoprint/filemanager/storage/__init__.py +++ b/src/octoprint/filemanager/storage/__init__.py @@ -1,457 +1,457 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function - __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" -try: - from os import scandir, walk -except ImportError: - from scandir import scandir, walk - class Storage(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 - # noinspection PyUnreachableCode - yield - - def analysis_backlog_for_path(self, path=None): - # empty generator pattern, yield is intentionally unreachable - return - # noinspection PyUnreachableCode - 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 create_print_job(self, path, user=None): - """ - Retrieves the :class:`~octoprint.job.PrintJob` instance - to use for printing ``path``. - """ - 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 add_history(self, path, data): - """ - Adds a history entry for the given ``path``. - - :param path: path of the file for which to add the history entry - :param data: history entry - """ - raise NotImplementedError() - - def update_history(self, path, index, data): - """ - Updates the history entry for ``path`` at ``index``. - - :param path: path of the file for which to update the history entry - :param index: index - :param data: history entry - """ - raise NotImplementedError() - - def remove_history(self, path, index): - """ - Removes the history entry for ``path`` at ``index``. - :param path: path of the file for which to remove the history entry - :param index: index - """ - 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 + # noinspection PyUnreachableCode + yield + + def analysis_backlog_for_path(self, path=None): + # empty generator pattern, yield is intentionally unreachable + return + # noinspection PyUnreachableCode + 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 create_print_job(self, path, user=None): + """ + Retrieves the :class:`~octoprint.job.PrintJob` instance + to use for printing ``path``. + """ + 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 add_history(self, path, data): + """ + Adds a history entry for the given ``path``. + + :param path: path of the file for which to add the history entry + :param data: history entry + """ + raise NotImplementedError() + + def update_history(self, path, index, data): + """ + Updates the history entry for ``path`` at ``index``. + + :param path: path of the file for which to update the history entry + :param index: index + :param data: history entry + """ + raise NotImplementedError() + + def remove_history(self, path, index): + """ + Removes the history entry for ``path`` at ``index``. + :param path: path of the file for which to remove the history entry + :param index: index + """ + 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 - - if code is None: - code = StorageError.UNKNOWN - self.code = code + 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 diff --git a/src/octoprint/filemanager/storage/local.py b/src/octoprint/filemanager/storage/local.py index ce5533064..0e748f34d 100644 --- a/src/octoprint/filemanager/storage/local.py +++ b/src/octoprint/filemanager/storage/local.py @@ -1,1292 +1,1579 @@ -# -*- 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' +__author__ = "Gina Häußge " +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" +import copy import io import logging import os import shutil -import re -import pylru -import copy - -try: - from os import scandir, walk -except ImportError: - from scandir import scandir, walk - -from octoprint.util import atomic_write from contextlib import contextmanager +from os import scandir, walk -# noinspection PyCompatibility -from past.builtins import basestring - -from emoji import demojize -from slugify import Slugify +import pylru import octoprint.filemanager - -from octoprint.util import is_hidden_path, to_unicode, to_bytes +from octoprint.util import atomic_write, is_hidden_path, time_this, to_bytes, to_unicode +from octoprint.util.text import sanitize from . import Storage, StorageError class LocalFileStorage(Storage): - """ - 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, key="local"): - """ - 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(10) - - 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"]))) - - 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 create_print_job(self, path, user=None): - from octoprint.comm.job import LocalGcodeFilePrintjob - return LocalGcodeFilePrintjob(self.path_on_disk(path), - "local", - self.path_in_storage(path), - name=self.path_in_storage(path), - user=user, - event_data=dict(path=path, - name=self.split_path(path)[1], - origin="local")) - - 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 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) + """ + 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`. + """ + + def __init__(self, basefolder, create=False, key="local"): + """ + 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) + + yield from self._analysis_backlog_generator(path) + + 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, level=0, 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 strip_grandchildren(nodes): + result = {} + for key, node in nodes.items(): + if node["type"] == "folder": + node = copy.copy(node) + node["children"] = strip_children(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: + if level > 0: + result = strip_grandchildren(result) + else: + 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 create_print_job(self, path, user=None): + from octoprint.comm.job import LocalGcodeFilePrintjob + + return LocalGcodeFilePrintjob( + self.path_on_disk(path), + "local", + self.path_in_storage(path), + name=self.path_in_storage(path), + user=user, + event_data={ + "path": path, + "name": self.split_path(path)[1], + "origin": "local", + }, + ) + + 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, str): + 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 = sanitize(name, safe_chars="-_.()[] ").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, str): + 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] + ) / 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/storage/sdcard.py b/src/octoprint/filemanager/storage/sdcard.py index daa0b5f10..1114f4788 100644 --- a/src/octoprint/filemanager/storage/sdcard.py +++ b/src/octoprint/filemanager/storage/sdcard.py @@ -1,14 +1,12 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" -from . import Storage, StorageError +from . import Storage class PrinterSDStorage(Storage): - def create_print_job(self, path, user=None): - from octoprint.comm.job import SDFilePrintjob - return SDFilePrintjob("/" + path, user=user) + def create_print_job(self, path, user=None): + from octoprint.comm.job import SDFilePrintjob + + return SDFilePrintjob("/" + path, user=user) diff --git a/src/octoprint/filemanager/util.py b/src/octoprint/filemanager/util.py index 4a247e62b..a23f81aa9 100644 --- a/src/octoprint/filemanager/util.py +++ b/src/octoprint/filemanager/util.py @@ -1,241 +1,260 @@ -# -*- coding: utf-8 -*- -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. - Arguments: - filename (str): The file's name - """ +class AbstractFileWrapper: + """ + Wrapper for file representations to save to storages. - def __init__(self, filename): - self.filename = filename + Arguments: + filename (str): The file's name + """ - def save(self, path): - """ - Saves the file's content to the given absolute path. + DEFAULT_PERMISSIONS = 0o664 - Arguments: - path (str): The absolute path to where to save the file - """ - raise NotImplementedError() + def __init__(self, filename): + self.filename = filename - def stream(self): - """ - Returns a Python stream object (subclass of io.IOBase) representing the file's contents. + def save(self, path, permissions=None): + """ + Saves the file's content to the given absolute path. + + Arguments: + path (str): The absolute path to where to save the file + permissions (int): The permissions to set on the file + """ + raise NotImplementedError() + + 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 (io.IOBase): One or more 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: - with self.stream() as source: - 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 (io.IOBase): One or more 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. + 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.IOBase): 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 = None + 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 = b'' - while len(result) < n or n == -1: - bytes_left = (n - len(result)) if n != -1 else -1 - if self.leftover is not None: - if bytes_left != -1 and bytes_left < len(self.leftover): - result += self.leftover[:bytes_left] - self.leftover = self.leftover[bytes_left:] - break - else: - result += self.leftover - self.leftover = None + 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() - processed_line = None - while processed_line is None: - line = self.input_stream.readline() - if not line: - break - processed_line = self.process_line(line) + # 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 - 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 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 - Arguments: - line (str): The line as read from `self.input_stream` + 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: - str 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 10dae37d7..14a2762b4 100644 --- a/src/octoprint/logging/__init__.py +++ b/src/octoprint/logging/__init__.py @@ -1,156 +1,161 @@ -# -*- 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 octoprint.logging import filters # noqa: F401 +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 - """ - from logging import _srcfile - import sys + 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, str), "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, str), "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: Union[str, bytes], prefix: str = ": ") -> str: + 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/filters.py b/src/octoprint/logging/filters.py new file mode 100644 index 000000000..fcd545ae0 --- /dev/null +++ b/src/octoprint/logging/filters.py @@ -0,0 +1,26 @@ +import logging + +try: + from urllib import parse as urlparse +except ImportError: + import urlparse + + +class TornadoAccessFilter(logging.Filter): + def filter(self, record): + try: + status, request_line, rtt = record.args + + if status == 409: + + method, url, client = request_line.split() + u = urlparse.urlparse(url) + if u.path in ("/api/printer",): + record.levelno = logging.INFO + record.levelname = logging.getLevelName(record.levelno) + except Exception: + logging.getLogger(__name__).exception( + "Error while filtering log record {!r}".format(record) + ) + + return logging.Filter.filter(self, record) diff --git a/src/octoprint/logging/handlers.py b/src/octoprint/logging/handlers.py index 633f53118..93941443a 100644 --- a/src/octoprint/logging/handlers.py +++ b/src/octoprint/logging/handlers.py @@ -1,179 +1,190 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - +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().__init__(*args, **kwargs) - def emit(self, record): - try: - self._executor.submit(self._emit, record) - except Exception: - self.handleError(record) + def emit(self, record): + if getattr(self._executor, "_shutdown", False): + return - def _emit(self, record): - # noinspection PyUnresolvedReferences - super(AsyncLogHandlerMixin, self).emit(record) + try: + self._executor.submit(self._emit, record) + except Exception: + self.handleError(record) + + def _emit(self, record): + # noinspection PyUnresolvedReferences + super().emit(record) + + def close(self): + self._executor.shutdown(wait=True) + super().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().__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().__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().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 CommunicationLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFileHandler): +class TriggeredRolloverLogHandler( + AsyncLogHandlerMixin, logging.handlers.RotatingFileHandler +): - do_rollover = dict() - 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 = {} + 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, logger): - cls.do_rollover[logger] = True + @classmethod + def arm_rollover(cls, logger): + cls.do_rollover[logger] = True - def __init__(self, *args, **kwargs): - kwargs["encoding"] = kwargs.get("encoding", "utf-8") - super(CommunicationLogHandler, self).__init__(*args, **kwargs) - self.cleanupFiles() + def __init__(self, *args, **kwargs): + kwargs["encoding"] = kwargs.get("encoding", "utf-8") + super().__init__(*args, **kwargs) + self.cleanupFiles() - def shouldRollover(self, record): - return self.do_rollover.pop(record.name, False) + def shouldRollover(self, record): + return self.do_rollover.pop(record.name, False) - 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): - if self.stream: - self.stream.close() - self.stream = None + def doRollover(self): + if self.stream: + self.stream.close() + self.stream = None - if os.path.exists(self.baseFilename): - # figure out creation date/time to use for file suffix - t = time.localtime(os.stat(self.baseFilename).st_mtime) - dfn = self.baseFilename + "." + time.strftime(type(self).suffix_template, t) - if os.path.exists(dfn): - os.remove(dfn) - os.rename(self.baseFilename, dfn) + if os.path.exists(self.baseFilename): + # figure out creation date/time to use for file suffix + t = time.localtime(os.stat(self.baseFilename).st_mtime) + dfn = self.baseFilename + "." + time.strftime(type(self).suffix_template, t) + if os.path.exists(dfn): + os.remove(dfn) + os.rename(self.baseFilename, dfn) - self.cleanupFiles() - if not self.delay: - self.stream = self._open() + self.cleanupFiles() + if not self.delay: + self.stream = self._open() + + +class CommunicationLogHandler(TriggeredRolloverLogHandler): + pass + + +class PluginTimingsLogHandler(TriggeredRolloverLogHandler): + pass class RecordingLogHandler(logging.Handler): - def __init__(self, target=None, *args, **kwargs): - super(RecordingLogHandler, self).__init__(*args, **kwargs) - self._buffer = [] - self._target = target + def __init__(self, target=None, *args, **kwargs): + super().__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 c899e053a..f9d807a22 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ This module represents OctoPrint's plugin subsystem. This includes management and helper methods as well as the registered plugin types. @@ -16,402 +13,483 @@ 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, SubSettings -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.util import deprecated, to_native_str +from octoprint.settings import SubSettings +from octoprint.settings import settings as s # 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_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_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_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_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(SubSettings): - """ - 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.plugin_key = plugin_key + .. method:: add_overlay(overlay, at_end=False, key=None) - SubSettings.__init__(self, settings, ["plugins", plugin_key], - defaults=defaults, - get_preprocessors=get_preprocessors, - set_preprocessors=set_preprocessors) + Adds a new config overlay for the plugin's settings. Will return the overlay's key in the map. - if self.defaults is not None: - self.defaults["plugins"][plugin_key]["_config_version"] = None + :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 - def global_has(self, path, **kwargs): - return self.settings.has(path, **kwargs) + .. method:: remove_overlay(key) - def global_remove(self, path, **kwargs): - return self.settings.remove(path, **kwargs) + Removes an overlay from the settings based on its key. Return ``True`` if the overlay could be found and was + removed, ``False`` otherwise. - 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. + :param key: The key of the overlay to remove + :type key: str + :rtype: boolean + """ - Directly forwards to :func:`octoprint.settings.Settings.get`. - """ - return self.settings.get(path, **kwargs) + def __init__( + self, + settings, + plugin_key, + defaults=None, + get_preprocessors=None, + set_preprocessors=None, + ): + self.plugin_key = plugin_key - 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) + SubSettings.__init__( + self, + settings, + ["plugins", plugin_key], + defaults=defaults, + get_preprocessors=get_preprocessors, + set_preprocessors=set_preprocessors, + ) - 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) + if self.defaults is not None: + self.defaults["plugins"][plugin_key]["_config_version"] = None - def global_get_boolean(self, path, **kwargs): - """ - Like :func:`global_get` but directly orwards to :func:`octoprint.settings.Settings.getBoolean`. - """ - return self.settings.getBoolean(path, **kwargs) + def global_has(self, path, **kwargs): + return self.settings.has(path, **kwargs) - def global_set(self, path, value, **kwargs): - """ - Setter for modifying settings not managed by the plugin itself on the core settings structure. Use this - to modify global settings outside of your plugin. + def global_remove(self, path, **kwargs): + return self.settings.remove(path, **kwargs) - Directly forwards to :func:`octoprint.settings.Settings.set`. - """ - self.settings.set(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_int(self, path, value, **kwargs): - """ - Like :func:`global_set` but directly forwards to :func:`octoprint.settings.Settings.setInt`. - """ - self.settings.setInt(path, value, **kwargs) + Directly forwards to :func:`octoprint.settings.Settings.get`. + """ + return self.settings.get(path, **kwargs) - def global_set_float(self, path, value, **kwargs): - """ - Like :func:`global_set` but directly forwards to :func:`octoprint.settings.Settings.setFloat`. - """ - self.settings.setFloat(path, value, **kwargs) + def global_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_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_float(self, path, **kwargs): + """ + Like :func:`global_get` but directly forwards to :func:`octoprint.settings.Settings.getFloat`. + """ + return self.settings.getFloat(path, **kwargs) - def global_get_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_boolean(self, path, **kwargs): + """ + Like :func:`global_get` but directly orwards to :func:`octoprint.settings.Settings.getBoolean`. + """ + return self.settings.getBoolean(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_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. - 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. + Directly forwards to :func:`octoprint.settings.Settings.set`. + """ + self.settings.set(path, value, **kwargs) - 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``. + 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) - 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_float(self, path, value, **kwargs): + """ + Like :func:`global_set` but directly forwards to :func:`octoprint.settings.Settings.setFloat`. + """ + self.settings.setFloat(path, value, **kwargs) + def global_set_boolean(self, path, value, **kwargs): + """ + Like :func:`global_set` but directly forwards to :func:`octoprint.settings.Settings.setBoolean`. + """ + self.settings.setBoolean(path, value, **kwargs) + + def global_get_basefolder(self, folder_type, **kwargs): + """ + Retrieves a globally defined basefolder of the given ``folder_type``. Directly forwards to + :func:`octoprint.settings.Settings.getBaseFolder`. + """ + return self.settings.getBaseFolder(folder_type, **kwargs) + + def get_plugin_logfile_path(self, postfix=None): + """ + Retrieves the path to a logfile specifically for the plugin. If ``postfix`` is not supplied, the logfile + will be named ``plugin_.log`` and located within the configured ``logs`` folder. If a + postfix is supplied, the name will be ``plugin__.log`` at the same location. + + Plugins may use this for specific logging tasks. For example, a :class:`~octoprint.plugin.SlicingPlugin` might + want to create a log file for logging the output of the slicing engine itself if some debug flag is set. + + Arguments: + postfix (str): Postfix of the logfile for which to create the path. If set, the file name of the log file + will be ``plugin__.log``, if not it will be + ``plugin_.log``. + + Returns: + str: Absolute path to the log file, directly usable by the plugin. + """ + filename = "plugin_" + self.plugin_key + if postfix is not None: + filename += "_" + postfix + filename += ".log" + return os.path.join(self.settings.getBaseFolder("logs"), filename) diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index 40546fe3f..9e7db9af8 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -1,9 +1,5 @@ -# -*- coding: utf-8 -*- -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,1845 +18,2424 @@ 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 sys +import io +import logging +import os +from collections import OrderedDict, defaultdict, namedtuple +from os import scandir import pkg_resources import pkginfo -from past.builtins import unicode - -from octoprint.util import to_unicode -from octoprint.util.version import is_python_compatible, get_python_version_string - -try: - from os import scandir -except ImportError: - from scandir import scandir - - -if sys.version_info[0] == 2: - # noinspection PyDeprecation - import imp -else: - # deprecated in Python 3.4+ and hence vendored for now - import octoprint.vendor.imp as imp +import octoprint.vendor.imp as imp +from octoprint.util import sv, time_this, to_unicode +from octoprint.util.version import get_python_version_string, is_python_compatible # 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 PluginInfo(object): - """ - 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. +class EntryPointOrigin(_EntryPointOrigin): + """ + Origin of a plugin registered via an entry point. - It works on Python module objects and extracts the relevant data from those via accessing the - :ref:`control properties `. + .. attribute:: type - 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 - """ + Always ``entry_point``. - attr_name = '__plugin_name__' - """ Module attribute from which to retrieve the plugin's human readable name. """ + .. attribute:: entry_point - attr_description = '__plugin_description__' - """ Module attribute from which to retrieve the plugin's description. """ + Name of the entry point, usually ``octoprint.plugin``. - 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. """ + .. attribute:: module_name - attr_version = '__plugin_version__' - """ Module attribute from which to retrieve the plugin's version. """ + Module registered to the entry point. - attr_author = '__plugin_author__' - """ Module attribute from which to retrieve the plugin's author. """ + .. attribute:: package_name - attr_url = '__plugin_url__' - """ Module attribute from which to retrieve the plugin's website URL. """ + Python package containing the entry point. - attr_license = '__plugin_license__' - """ Module attribute from which to retrieve the plugin's license. """ + .. attribute:: package_version - 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. - - 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. - """ + Version of the python package containing the entry point. + """ - 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_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. - - .. deprecated:: 1.2.0-dev-694 - - Use :attr:`attr_implementation` instead. - """ - - 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_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`. - - .. deprecated:: 1.2.0-dev-720 - - Use :attr:`attr_load` instead. - """ - - 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_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 hooks(self): - """ - Hooks provided by the plugin. Will be taken from the hooks attribute of the plugin module as defiend 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 - 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_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 = [] - - 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.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 - - kwargs = dict(module_name=module_name, version=version) - 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: - 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: - 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, sorting_value, not plugin_info.bundled if plugin_info else True, 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, x[0], x[1], 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)) + +_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: + """ + 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. + + 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 + """ + + 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_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_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_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. + + 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. + + 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. + + 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_implementation = "__plugin_implementation__" + """ Module attribute from which to retrieve the plugin's provided mixin implementation. """ + + 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_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_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 + """ + 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 = ( + self.looks_like_plugin + and not self.forced_disabled + and not self.blacklisted + and not self.incompatible + and not self.invalid_syntax + and result + ) + + elif phase == "before_load": + pass + + elif phase == "after_load": + pass + + 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 += str(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's AST.""" + return self._cached_parsed_metadata + + @property + def control_properties(self): + return [ + getattr(self.__class__, key) + for key in dir(self.__class__) + if key.startswith("attr_") + ] + + @property + def looks_like_plugin(self): + """ + Returns whether the plugin actually looks like a plugin (has control properties) or not. + """ + return self.parsed_metadata.get("has_control_properties", False) + + 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) + ) + function_defs = list( + filter(lambda x: isinstance(x, ast.FunctionDef) and x.name, root.body) + ) + all_relevant = assignments + function_defs + + def extract_target_ids(node): + return list( + map( + lambda x: x.id, + filter(lambda x: isinstance(x, ast.Name), node.targets), + ) + ) + + def extract_names(node): + if isinstance(node, ast.Assign): + return extract_target_ids(node) + elif isinstance(node, ast.FunctionDef): + return [ + node.name, + ] + else: + return [] + + 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 + + for a in reversed(all_relevant): + targets = extract_names(a) + if any(map(lambda x: x in targets, self.control_properties)): + result["has_control_properties"] = True + 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: + """ + 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") + + if not os.path.isfile(init_py): + # 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",) or key.startswith("__"): + # not py, 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={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 ( + plugin.looks_like_plugin + and 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 plugin.looks_like_plugin + 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: str(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 {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 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. +class Plugin: + """ + 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 d625844ec..a8fb9b869 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ This module bundles all of OctoPrint's supported plugin implementation types as well as their common parent class, :class:`OctoPrintPlugin`. @@ -19,2062 +16,2206 @@ 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 is needed to access the blueprint if the forcelogin plugin is enabled or not. 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 - return True + def get_blueprint_kwargs(self): + """ + Override this if you want your blueprint constructed with additional options such as ``static_folder``, + ``template_folder``, etc. + + 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 OctoPrintPermission, 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, paths in restricted_paths.items(): + if isinstance(level, OctoPrintPermission): + condition = lambda: ( + current_user is not None and current_user.has_permission(level) + ) + else: + condition = conditions.get(level, lambda: False) + + for path in paths: + 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 + certain permissions, or never on the REST API. + + Return a ``dict`` with one of the following keys, mapping to a list of paths (as tuples or lists of + the path elements) for which to restrict access via the REST API accordingly. + + * An :py:class:`~octoprint.access.permissions.OctoPrintPermission` instance: Paths will only be available on the REST API for users with the permission + * ``admin``: Paths will only be available on the REST API for users with admin rights (any user with the SETTINGS permission) + * ``user``: Paths will only be available on the REST API when accessed as a logged in user + * ``never``: Paths 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"))), + the=dict(webcam=dict(data="webcam"))) + + def get_settings_restricted_paths(self): + from octoprint.access.permissions import Permissions + return {'admin':[["some", "admin_only", "path"], ["another", "admin_only", "path"],], + 'user':[["some", "user_only", "path"],], + 'never':[["path", "to", "never", "return"],], + Permissions.WEBCAM:[["the", "webcam", "data"],]} + + # 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))), + # the=dict(webcam=dict(data=None))) + # + # like this for a logged in user without the webcam permission + # + # 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))), + # the=dict(webcam=dict(data=None))) + # + # like this for a logged in user with the webcam permission + # + # 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))), + # the=dict(webcam=dict(data="webcam"))) + # + # 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))), + # the=dict(webcam=dict(data="webcam"))) + + .. 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 + from os 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 + from os import scandir - # 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``. + 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) - Arguments: - path (str): The absolute path from which to read the slicing profile. + # 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. - Returns: - SlicingProfile: The specified slicing profile. - """ - return None + Returns: + SlicingProfile: The :class:`~octoprint.slicing.SlicingProfile` containing the default slicing profile for + this slicer. + """ + return None - # 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. + # 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``. - 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 + Arguments: + path (str): The absolute path from which to read the slicing profile. - # 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``. + Returns: + SlicingProfile: The specified slicing profile. + """ + return None - 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. + # noinspection PyMethodMayBeStatic + def save_slicer_profile(self, path, profile, allow_overwrite=True, overrides=None): + """ + Should save the provided :class:`~octoprint.slicing.SlicingProfile` to the indicated ``path``, after applying + any supplied ``overrides``. If a profile is already saved under the indicated path and ``allow_overwrite`` is + set to False (defaults to True), an :class:`IOError` should be raised. - If provided, ``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. + 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 - ``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: + # 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``. - .. code-block:: python + 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. - 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, ``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. - on_progress_kwargs["_progress"] = your_plugins_slicing_progress - on_progress(*on_progress_args, **on_progress_kwargs) + ``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: - 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. + .. code-block:: python - 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 on_progress is not None: + if on_progress_args is None: + on_progress_args = () + if on_progress_kwargs is None: + on_progress_kwargs = dict() - 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. + on_progress_kwargs["_progress"] = your_plugins_slicing_progress + on_progress(*on_progress_args, **on_progress_kwargs) - For jobs that finished successfully, ``result`` should be a :class:`dict` containing additional information - about the slicing job under the following keys: + 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. - 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. + 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. - 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. + 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 the job gets cancelled, a :class:`~octoprint.slicing.SlicingCancelled` exception should be raised. + For jobs that finished successfully, ``result`` should be a :class:`dict` containing additional information + about the slicing job under the following keys: - Returns: - tuple: A 2-tuple (boolean, object) as outlined above. + 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. - Raises: - SlicingCancelled: The slicing job was cancelled (via :meth:`cancel_slicing`). - """ - pass + 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. - # noinspection PyMethodMayBeStatic - def cancel_slicing(self, machinecode_path): - """ - Cancels the slicing to the indicated file. + If the job gets cancelled, a :class:`~octoprint.slicing.SlicingCancelled` exception should be raised. - Arguments: - machinecode_path (str): The absolute path to the machine code file to which to stop slicing to. - """ - pass + 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/__init__.py b/src/octoprint/plugins/__init__.py index 092cd3e34..e69de29bb 100644 --- a/src/octoprint/plugins/__init__.py +++ b/src/octoprint/plugins/__init__.py @@ -1,2 +0,0 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals diff --git a/src/octoprint/plugins/action_command_notification/__init__.py b/src/octoprint/plugins/action_command_notification/__init__.py new file mode 100644 index 000000000..060539d66 --- /dev/null +++ b/src/octoprint/plugins/action_command_notification/__init__.py @@ -0,0 +1,149 @@ +__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 time + +import flask +from flask_babel import gettext + +import octoprint.plugin +from octoprint.access import USER_GROUP +from octoprint.access.permissions import Permissions +from octoprint.events import Events + + +class ActionCommandNotificationPlugin( + octoprint.plugin.AssetPlugin, + octoprint.plugin.SettingsPlugin, + octoprint.plugin.SimpleApiPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.EventHandlerPlugin, +): + def __init__(self): + self._notifications = [] + + # Additional permissions hook + + def get_additional_permissions(self): + return [ + { + "key": "SHOW", + "name": "Show printer notifications", + "description": gettext("Allows to see printer notifications"), + "default_groups": [USER_GROUP], + "roles": ["show"], + }, + { + "key": "CLEAR", + "name": "Clear printer notifications", + "description": gettext("Allows to clear printer notifications"), + "default_groups": [USER_GROUP], + "roles": ["clear"], + }, + ] + + # ~ AssetPlugin + + def get_assets(self): + return { + "js": ["js/action_command_notification.js"], + "clientjs": ["clientjs/action_command_notification.js"], + "css": ["css/action_command_notification.css"], + } + + # ~ EventHandlerPlugin + + def on_event(self, event, payload): + if event == Events.DISCONNECTED: + self._clear_notifications() + + # ~ SettingsPlugin + + def get_settings_defaults(self): + return {"enable": True, "enable_popups": False} + + # ~ SimpleApiPlugin + + def on_api_get(self, request): + if not Permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW.can(): + return flask.abort(403, "Insufficient permissions") + return flask.jsonify( + notifications=[ + {"timestamp": notification[0], "message": notification[1]} + for notification in self._notifications + ] + ) + + def 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() + + # ~ TemplatePlugin + + def get_template_configs(self): + return [ + { + "type": "settings", + "name": gettext("Printer Notifications"), + "custom_bindings": False, + }, + { + "type": "sidebar", + "name": gettext("Printer Notifications"), + "icon": "bell-o", + "styles_wrapper": ["display: none"], + "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 + + 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 + + if action != "notification": + return + + 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)) + + def _clear_notifications(self): + self._notifications = [] + self._plugin_manager.send_plugin_message(self._identifier, {}) + self._logger.info("Notifications cleared") + + +__plugin_name__ = "Action Command Notification Support" +__plugin_description__ = ( + "Allows your printer to trigger notifications via action commands on the connection" +) +__plugin_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_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, +} 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 new file mode 100644 index 000000000..138226dca --- /dev/null +++ b/src/octoprint/plugins/action_command_notification/static/clientjs/action_command_notification.js @@ -0,0 +1,33 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(["OctoPrintClient"], factory); + } else { + factory(global.OctoPrintClient); + } +})(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.clear = function (opts) { + return this.base.simpleApiCommand( + "action_command_notification", + "clear", + {}, + opts + ); + }; + + 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 new file mode 100644 index 000000000..e15340a1e --- /dev/null +++ b/src/octoprint/plugins/action_command_notification/static/css/action_command_notification.css @@ -0,0 +1,11 @@ +.sidebar_plugin_action_command_notification_entry { + padding: 5px; + 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 new file mode 100644 index 000000000..c9f092d75 --- /dev/null +++ b/src/octoprint/plugins/action_command_notification/static/js/action_command_notification.js @@ -0,0 +1,108 @@ +$(function () { + function ActionCommandNotificationViewModel(parameters) { + var self = this; + + self.loginState = parameters[0]; + self.access = parameters[1]; + self.settings = parameters[2]; + + self.notifications = ko.observableArray([]); + self.sortDesc = ko.observable(false); + self.sortDesc.subscribe(function () { + self._toLocalStorage(); + }); + + self.toDateTimeString = function (timestamp) { + return formatDate(timestamp); + }; + + 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); + }; + + 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; + + OctoPrint.plugins.action_command_notification.clear(); + }; + + self.toggleSorting = function () { + self.sortDesc(!self.sortDesc()); + self.requestData(); + }; + + 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() + ) { + new PNotify({ + title: gettext("Printer Notification"), + text: data.message, + hide: false, + icon: "fa fa-bell-o", + buttons: { + sticker: false, + closer: true + } + }); + } + }; + + 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({ + construct: ActionCommandNotificationViewModel, + dependencies: ["loginStateViewModel", "accessViewModel", "settingsViewModel"], + elements: ["#sidebar_plugin_action_command_notification_wrapper"] + }); +}); 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 new file mode 100644 index 000000000..a5d079b9b --- /dev/null +++ b/src/octoprint/plugins/action_command_notification/templates/action_command_notification_settings.jinja2 @@ -0,0 +1,19 @@ +

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

+ +
+
+
+ +
+
+
+
+ +
+
+
diff --git a/src/octoprint/plugins/action_command_notification/templates/action_command_notification_sidebar.jinja2 b/src/octoprint/plugins/action_command_notification/templates/action_command_notification_sidebar.jinja2 new file mode 100644 index 000000000..c28fc03fe --- /dev/null +++ b/src/octoprint/plugins/action_command_notification/templates/action_command_notification_sidebar.jinja2 @@ -0,0 +1,12 @@ +
+ + +
+
+ {{ _('There are currently no notifications from your printer.') }} +
diff --git a/src/octoprint/plugins/action_command_notification/templates/action_command_notification_sidebar_header.jinja2 b/src/octoprint/plugins/action_command_notification/templates/action_command_notification_sidebar_header.jinja2 new file mode 100644 index 000000000..d4b04232a --- /dev/null +++ b/src/octoprint/plugins/action_command_notification/templates/action_command_notification_sidebar_header.jinja2 @@ -0,0 +1,11 @@ + + + diff --git a/src/octoprint/plugins/action_command_prompt/__init__.py b/src/octoprint/plugins/action_command_prompt/__init__.py index 437ae511a..8d6305126 100644 --- a/src/octoprint/plugins/action_command_prompt/__init__.py +++ b/src/octoprint/plugins/action_command_prompt/__init__.py @@ -1,239 +1,302 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" -import octoprint.plugin - -from octoprint.server import user_permission -from octoprint.access import USER_GROUP -from octoprint.access.permissions import Permissions -from octoprint.events import Events - import flask from flask_babel import gettext -class Prompt(object): - - def __init__(self, text): - self.text = text - self.choices = [] - - self._active = False - - @property - def active(self): - return self._active - - def add_choice(self, text): - self.choices.append(text) - - def activate(self): - self._active = True - - def validate_choice(self, choice): - return 0 <= choice < len(self.choices) +import octoprint.plugin +from octoprint.access import USER_GROUP +from octoprint.access.permissions import Permissions +from octoprint.events import Events -class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, - octoprint.plugin.EventHandlerPlugin, - octoprint.plugin.SettingsPlugin, - octoprint.plugin.SimpleApiPlugin, - octoprint.plugin.TemplatePlugin): +class Prompt: + def __init__(self, text): + self.text = text + self.choices = [] - COMMAND = "M876" - CAP_PROMPT_SUPPORT = "PROMPT_SUPPORT" + self._active = False - # noinspection PyMissingConstructor - def __init__(self): - self._prompt = None - self._enable = "detected" - self._command = None - self._enable_emergency_sending = False - self._enable_signal_support = False - self._cap_prompt_support = False + @property + def active(self): + return self._active - def initialize(self): - self._enable = self._settings.get(["enable"]) - self._command = self._settings.get(["command"]) - self._enable_emergency_sending = self._settings.get_boolean(["enable_emergency_sending"]) - self._enable_signal_support = self._settings.get_boolean(["enable_signal_support"]) + def add_choice(self, text): + self.choices.append(text) - # Additional permissions hook + def activate(self): + self._active = True - def get_additional_permissions(self): - return [ - dict(key="INTERACT", - name="Interact with printer prompts", - description=gettext("Allows to see and interact with printer prompts"), - default_groups=[USER_GROUP], - roles=["interact"]) - ] + def validate_choice(self, choice): + return 0 <= choice < len(self.choices) - #~ AssetPlugin - def get_assets(self): - return dict(js=["js/action_command_prompt.js"], - clientjs=["clientjs/action_command_prompt.js"]) +class ActionCommandPromptPlugin( + octoprint.plugin.AssetPlugin, + octoprint.plugin.EventHandlerPlugin, + octoprint.plugin.SettingsPlugin, + octoprint.plugin.SimpleApiPlugin, + octoprint.plugin.TemplatePlugin, +): - #~ EventHandlerPlugin + COMMAND = "M876" + CAP_PROMPT_SUPPORT = "PROMPT_SUPPORT" - def on_event(self, event, payload): - if event == Events.CONNECTED and self._enable == "always" and self._enable_signal_support: - self._printer.commands(["{command} P1".format(command=self._command)]) - elif event == Events.DISCONNECTED: - self._close_prompt() + # noinspection PyMissingConstructor + def __init__(self): + self._prompt = None + self._enable = "detected" + self._command = None + self._enable_emergency_sending = True + self._enable_signal_support = True + self._cap_prompt_support = False - #~ SettingsPlugin + def initialize(self): + self._enable = self._settings.get(["enable"]) + self._command = self._settings.get(["command"]) + self._enable_emergency_sending = self._settings.get_boolean( + ["enable_emergency_sending"] + ) + self._enable_signal_support = self._settings.get_boolean( + ["enable_signal_support"] + ) - def get_settings_defaults(self): - return dict(enable="detected", - command=self.COMMAND, - enable_emergency_sending=True, - enable_signal_support=True) + # Additional permissions hook - def on_settings_save(self, data): - octoprint.plugin.SettingsPlugin.on_settings_save(self, data) - self._enable = self._settings.get(["enable"]) - self._command = self._settings.get(["command"]) - self._enable_emergency_sending = self._settings.get_boolean(["enable_emergency_sending"]) - self._enable_signal_support = self._settings.get_boolean(["enable_signal_support"]) + def get_additional_permissions(self): + return [ + { + "key": "INTERACT", + "name": "Interact with printer prompts", + "description": gettext("Allows to see and interact with printer prompts"), + "default_groups": [USER_GROUP], + "roles": ["interact"], + } + ] - #~ SimpleApiPlugin + # ~ AssetPlugin - def get_api_commands(self): - return dict(select=["choice"]) + def get_assets(self): + return { + "js": ["js/action_command_prompt.js"], + "clientjs": ["clientjs/action_command_prompt.js"], + } - def on_api_command(self, command, data): - if command == "select": - if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can(): - return flask.abort(403, "Insufficient permissions") + # ~ EventHandlerPlugin - if self._prompt is None: - return flask.abort(409, "No active prompt") + def on_event(self, event, payload): + if ( + event == Events.CONNECTED + and self._enable == "always" + and self._enable_signal_support + ): + self._printer.commands(["{command} P1".format(command=self._command)]) + elif event == Events.DISCONNECTED: + self._close_prompt() - choice = data["choice"] - if not isinstance(choice, int) or not self._prompt.validate_choice(choice): - return flask.abort(400, "{!r} is not a valid value for choice".format(choice)) + # ~ SettingsPlugin - self._answer_prompt(choice) + def get_settings_defaults(self): + return { + "enable": "detected", + "command": self.COMMAND, + "enable_emergency_sending": True, + "enable_signal_support": True, + } - def on_api_get(self, request): - if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can(): - return flask.abort(403, "Insufficient permissions") - if self._prompt is None: - return flask.jsonify() - else: - return flask.jsonify(text=self._prompt.text, choices=self._prompt.choices) + def on_settings_save(self, data): + octoprint.plugin.SettingsPlugin.on_settings_save(self, data) + self._enable = self._settings.get(["enable"]) + self._command = self._settings.get(["command"]) + self._enable_emergency_sending = self._settings.get_boolean( + ["enable_emergency_sending"] + ) + self._enable_signal_support = self._settings.get_boolean( + ["enable_signal_support"] + ) - #~ TemplatePlugin + # ~ SimpleApiPlugin - def get_template_configs(self): - return [dict(type="settings", name=gettext("Action Command Prompt"), custom_bindings=False)] + def get_api_commands(self): + return {"select": ["choice"]} - #~ action command handler + def on_api_command(self, command, data): + if command == "select": + if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can(): + return flask.abort(403, "Insufficient permissions") - def action_command_handler(self, comm, line, action, *args, **kwargs): - if not action.startswith("prompt_"): - return + if self._prompt is None: + return flask.abort(409, "No active prompt") - parts = action.split(None, 1) - if len(parts) == 1: - action = parts[0] - parameter = "" - else: - action, parameter = parts + choice = data["choice"] + if not isinstance(choice, int) or not self._prompt.validate_choice(choice): + return flask.abort( + 400, "{!r} is not a valid value for choice".format(choice) + ) - if action == "prompt_begin": - if self._prompt is not None and self._prompt.active: - self._logger.warning("Prompt is already defined") - return - self._prompt = Prompt(parameter.strip()) + self._answer_prompt(choice) - elif action == "prompt_choice" or action == "prompt_button": - if self._prompt is None: - return - if self._prompt.active: - self._logger.warning("Prompt is already active") - return - self._prompt.add_choice(parameter.strip()) + def on_api_get(self, request): + if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can(): + return flask.abort(403, "Insufficient permissions") + if self._prompt is None: + return flask.jsonify() + else: + return flask.jsonify(text=self._prompt.text, choices=self._prompt.choices) - elif action == "prompt_show": - if self._prompt is None: - return - if self._prompt.active: - self._logger.warning("Prompt is already active") - return - self._show_prompt() + # ~ TemplatePlugin - elif action == "prompt_end": - if self._prompt is None: - return - self._close_prompt() - self._prompt = None + def get_template_configs(self): + return [ + { + "type": "settings", + "name": gettext("Printer Dialogs"), + "custom_bindings": False, + } + ] - #~ queuing handling + # ~ action command handler - def gcode_queuing_handler(self, comm_instance, phase, cmd, cmd_type, gcode, subcode=None, tags=None, *args, **kwargs): - if gcode != self._command: - return + def action_command_handler(self, comm, line, action, *args, **kwargs): + if not action.startswith("prompt_"): + return - if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support) or not self._enable_emergency_sending: - return + parts = action.split(None, 1) + if len(parts) == 1: + action = parts[0] + parameter = "" + else: + action, parameter = parts - if not "S" in cmd: - # we only force-send M876 Sx - return + if action == "prompt_begin": + if self._prompt is not None and self._prompt.active: + self._logger.warning("Prompt is already defined") + return + self._prompt = Prompt(parameter.strip()) - # noinspection PyProtectedMember - return comm_instance._emergency_force_send(cmd, "Force-sending {} to the printer".format(self._command), gcode=gcode) + elif action == "prompt_choice" or action == "prompt_button": + if self._prompt is None: + return + if self._prompt.active: + self._logger.warning("Prompt is already active") + return + self._prompt.add_choice(parameter.strip()) - #~ capability reporting + elif action == "prompt_show": + if self._prompt is None: + return + if self._prompt.active: + self._logger.warning("Prompt is already active") + return + self._show_prompt() - def firmware_capability_handler(self, comm_instance, capability, enabled, already_defined, *args, **kwargs): - if capability == self.CAP_PROMPT_SUPPORT and enabled: - self._cap_prompt_support = True - if self._enable == "detected" and self._enable_signal_support: - self._printer.commands(["{command} P1".format(command=self._command)]) + elif action == "prompt_end": + if self._prompt is None: + return + self._close_prompt() + self._prompt = None - #~ prompt handling + # ~ queuing handling - def _show_prompt(self): - if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support): - return + def gcode_queuing_handler( + self, + comm_instance, + phase, + cmd, + cmd_type, + gcode, + subcode=None, + tags=None, + *args, + **kwargs + ): + if gcode != self._command: + return - self._prompt.activate() - self._plugin_manager.send_plugin_message(self._identifier, dict(action="show", - text=self._prompt.text, - choices=self._prompt.choices)) + if ( + self._enable == "never" + or (self._enable == "detected" and not self._cap_prompt_support) + or not self._enable_emergency_sending + ): + return - def _close_prompt(self): - if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support): - return + if "S" not in cmd: + # we only force-send M876 Sx + return - self._prompt = None - self._plugin_manager.send_plugin_message(self._identifier, dict(action="close")) + # noinspection PyProtectedMember + return comm_instance._emergency_force_send( + cmd, "Force-sending {} to the printer".format(self._command), gcode=gcode + ) - def _answer_prompt(self, choice): - if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support): - return + # ~ capability reporting - self._close_prompt() - self._printer.commands(["{command} S{choice}".format(command=self._command, - choice=choice)]) + def firmware_capability_handler( + self, comm_instance, capability, enabled, already_defined, *args, **kwargs + ): + if capability == self.CAP_PROMPT_SUPPORT and enabled: + self._cap_prompt_support = True + if self._enable == "detected" and self._enable_signal_support: + self._printer.commands(["{command} P1".format(command=self._command)]) + + # ~ prompt handling + + def _show_prompt(self): + if self._enable == "never" or ( + self._enable == "detected" and not self._cap_prompt_support + ): + return + + self._prompt.activate() + self._plugin_manager.send_plugin_message( + self._identifier, + { + "action": "show", + "text": self._prompt.text, + "choices": self._prompt.choices, + }, + ) + + def _close_prompt(self): + if self._enable == "never" or ( + self._enable == "detected" and not self._cap_prompt_support + ): + return + + self._prompt = None + self._plugin_manager.send_plugin_message(self._identifier, {"action": "close"}) + + def _answer_prompt(self, choice): + if self._enable == "never" or ( + self._enable == "detected" and not self._cap_prompt_support + ): + return + + self._close_prompt() + if "{choice}" in self._command: + self._printer.commands([self._command.format(choice=choice)], force=True) + else: + self._printer.commands( + ["{command} S{choice}".format(command=self._command, choice=choice)], + force=True, + ) __plugin_name__ = "Action Command Prompt Support" -__plugin_description__ = "Allows your printer to trigger prompts via action commands on the connection" +__plugin_description__ = ( + "Allows your printer to trigger prompts via action commands on the connection" +) __plugin_author__ = "Gina Häußge" -__plugin_disabling_discouraged__ = gettext("Without this plugin your printer will no longer be able to trigger" - " confirmation or selection prompts in OctoPrint") +__plugin_disabling_discouraged__ = gettext( + "Without this plugin your printer will no longer be able to trigger" + " confirmation or selection prompts in OctoPrint" +) __plugin_license__ = "AGPLv3" +__plugin_pythoncompat__ = ">=2.7,<4" __plugin_implementation__ = ActionCommandPromptPlugin() __plugin_hooks__ = { - "octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler, - "octoprint.comm.protocol.gcode.queuing": __plugin_implementation__.gcode_queuing_handler, - "octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.firmware_capability_handler, - "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions + "octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler, + "octoprint.comm.protocol.gcode.queuing": __plugin_implementation__.gcode_queuing_handler, + "octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.firmware_capability_handler, + "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions, } diff --git a/src/octoprint/plugins/action_command_prompt/static/clientjs/action_command_prompt.js b/src/octoprint/plugins/action_command_prompt/static/clientjs/action_command_prompt.js index 9ba9b4a14..a2560a078 100644 --- a/src/octoprint/plugins/action_command_prompt/static/clientjs/action_command_prompt.js +++ b/src/octoprint/plugins/action_command_prompt/static/clientjs/action_command_prompt.js @@ -4,22 +4,25 @@ } else { factory(global.OctoPrintClient); } -})(this, function(OctoPrintClient) { - var OctoPrintActionCommandPromptClient = function(base) { +})(this, function (OctoPrintClient) { + var OctoPrintActionCommandPromptClient = function (base) { this.base = base; }; - OctoPrintActionCommandPromptClient.prototype.get = function(refresh, opts) { + OctoPrintActionCommandPromptClient.prototype.get = function (refresh, opts) { return this.base.get(this.base.getSimpleApiUrl("action_command_prompt"), opts); }; - OctoPrintActionCommandPromptClient.prototype.select = function(choice, opts) { + OctoPrintActionCommandPromptClient.prototype.select = function (choice, opts) { var data = { choice: choice }; return this.base.simpleApiCommand("action_command_prompt", "select", data, opts); }; - OctoPrintClient.registerPluginComponent("action_command_prompt", OctoPrintActionCommandPromptClient); + OctoPrintClient.registerPluginComponent( + "action_command_prompt", + OctoPrintActionCommandPromptClient + ); return OctoPrintActionCommandPromptClient; }); diff --git a/src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js b/src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js index c35faf7e6..d7d1f02d1 100644 --- a/src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js +++ b/src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js @@ -1,4 +1,4 @@ -$(function() { +$(function () { function ActionCommandPromptViewModel(parameters) { var self = this; @@ -10,21 +10,25 @@ $(function() { self.text = ko.observable(); self.buttons = ko.observableArray([]); - self.active = ko.pureComputed(function() { + self.active = ko.pureComputed(function () { return self.text() !== undefined; }); - self.visible = ko.pureComputed(function() { + self.visible = ko.pureComputed(function () { return self.modal() !== undefined; }); - self.requestData = function() { - if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT)) return; + self.requestData = function () { + if ( + !self.loginState.hasPermission( + self.access.permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT + ) + ) + return; - OctoPrint.plugins.action_command_prompt.get() - .done(self.fromResponse); + OctoPrint.plugins.action_command_prompt.get().done(self.fromResponse); }; - self.fromResponse = function(data) { + self.fromResponse = function (data) { if (data.hasOwnProperty("text") && data.hasOwnProperty("choices")) { self.text(data.text); self.buttons(data.choices); @@ -35,7 +39,7 @@ $(function() { } }; - self.showPrompt = function() { + self.showPrompt = function () { var text = self.text(); var buttons = self.buttons(); @@ -44,12 +48,12 @@ $(function() { message: text, selections: buttons, maycancel: true, // see #3171 - onselect: function(index) { + onselect: function (index) { if (index > -1) { self._select(index); } }, - onclose: function() { + onclose: function () { self.modal(undefined); } }; @@ -57,23 +61,28 @@ $(function() { self.modal(showSelectionDialog(opts)); }; - self._select = function(index) { + self._select = function (index) { OctoPrint.plugins.action_command_prompt.select(index); }; - self._closePrompt = function() { + self._closePrompt = function () { var modal = self.modal(); if (modal) { modal.modal("hide"); } }; - self.onStartupComplete = function() { + self.onStartupComplete = function () { self.requestData(); }; - self.onDataUpdaterPluginMessage = function(plugin, data) { - if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT)) return; + self.onDataUpdaterPluginMessage = function (plugin, data) { + if ( + !self.loginState.hasPermission( + self.access.permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT + ) + ) + return; if (plugin !== "action_command_prompt") { return; } @@ -92,8 +101,7 @@ $(function() { break; } } - } - + }; } OCTOPRINT_VIEWMODELS.push({ diff --git a/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_navbar.jinja2 b/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_navbar.jinja2 index 31e2a266e..c9f903f73 100644 --- a/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_navbar.jinja2 +++ b/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_navbar.jinja2 @@ -1,3 +1,3 @@ diff --git a/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 b/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 index df45ff760..109877965 100644 --- a/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 +++ b/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 @@ -1,6 +1,6 @@

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

-
+
@@ -16,7 +16,7 @@
- +
diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py index ad13b95be..40af06709 100644 --- a/src/octoprint/plugins/announcements/__init__.py +++ b/src/octoprint/plugins/announcements/__init__.py @@ -1,540 +1,631 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License" -import octoprint.plugin - import calendar import io import os import re -import time -import threading import sys -PY2 = sys.version_info[0] < 3 +import threading +import time +from collections import OrderedDict import feedparser import flask +from flask_babel import gettext -from collections import OrderedDict - +import octoprint.plugin +from octoprint import __version__ as OCTOPRINT_VERSION from octoprint.access import ADMIN_GROUP from octoprint.access.permissions import Permissions -from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking, check_etag -from octoprint.util import utmify, count, monotonic_time -from flask_babel import gettext -from octoprint import __version__ as OCTOPRINT_VERSION - - -class AnnouncementPlugin(octoprint.plugin.AssetPlugin, - octoprint.plugin.SettingsPlugin, - octoprint.plugin.BlueprintPlugin, - octoprint.plugin.StartupPlugin, - octoprint.plugin.TemplatePlugin, - octoprint.plugin.EventHandlerPlugin): - - # noinspection PyMissingConstructor - def __init__(self): - self._cached_channel_configs = None - self._cached_channel_configs_mutex = threading.RLock() - - from slugify import Slugify - self._slugify = Slugify() - self._slugify.safe_chars = "-_." - - # Additional permissions hook - - def get_additional_permissions(self): - return [ - dict(key="READ", - name="Read announcements", - description=gettext("Allows to read announcements"), - default_groups=[ADMIN_GROUP], - roles=["read"]), - dict(key="MANAGE", - name="Manage announcement subscriptions", - description=gettext("Allows to manage announcement subscriptions. Includes \"Read announcements\" " - "permission"), - default_groups=[ADMIN_GROUP], - roles=["manage"], - permissions=["PLUGIN_ANNOUNCEMENTS_READ"]) - ] - - # StartupPlugin - - def on_after_startup(self): - # decouple channel fetching from server startup - def fetch_data(): - self._fetch_all_channels() - - thread = threading.Thread(target=fetch_data) - thread.daemon = True - thread.start() - - # SettingsPlugin - - def get_settings_defaults(self): - settings = dict(channels=dict(_important=dict(name="Important Announcements", - description="Important announcements about OctoPrint.", - priority=1, - type="rss", - url="https://octoprint.org/feeds/important.xml"), - _releases=dict(name="Release Announcements", - description="Announcements of new releases and release candidates of OctoPrint.", - priority=2, - type="rss", - url="https://octoprint.org/feeds/releases.xml"), - _blog=dict(name="On the OctoBlog", - description="Development news, community spotlights, OctoPrint On Air episodes and more from the official OctoBlog.", - priority=2, - type="rss", - url="https://octoprint.org/feeds/octoblog.xml"), - _plugins=dict(name="New Plugins in the Repository", - description="Announcements of new plugins released on the official Plugin Repository.", - priority=2, - type="rss", - url="https://plugins.octoprint.org/feed.xml"), - _octopi=dict(name="OctoPi News", - description="News around OctoPi, the Raspberry Pi image including OctoPrint.", - priority=2, - type="rss", - url="https://octoprint.org/feeds/octopi.xml")), - enabled_channels=[], - forced_channels=["_important"], - channel_order=["_important", "_releases", "_blog", "_plugins", "_octopi"], - ttl=6*60, - display_limit=3, - summary_limit=300) - settings["enabled_channels"] = list(settings["channels"].keys()) - return settings - - def get_settings_version(self): - return 1 - - def on_settings_migrate(self, target, current): - if current is None: - # first version had different default feeds and only _important enabled by default - channels = self._settings.get(["channels"]) - if "_news" in channels: - del channels["_news"] - if "_spotlight" in channels: - del channels["_spotlight"] - self._settings.set(["channels"], channels) - - enabled = self._settings.get(["enabled_channels"]) - add_blog = False - if "_news" in enabled: - add_blog = True - enabled.remove("_news") - if "_spotlight" in enabled: - add_blog = True - enabled.remove("_spotlight") - if add_blog and not "_blog" in enabled: - enabled.append("_blog") - self._settings.set(["enabled_channels"], enabled) - - # AssetPlugin - - def get_assets(self): - return dict(js=["js/announcements.js"], - less=["less/announcements.less"], - css=["css/announcements.css"]) - - # Template Plugin - - def get_template_configs(self): - return [ - dict(type="settings", name=gettext("Announcements"), template="announcements_settings.jinja2", custom_bindings=True), - dict(type="navbar", template="announcements_navbar.jinja2", styles=["display: none"], data_bind="visible: loginState.hasPermission(access.permissions.PLUGIN_ANNOUNCEMENTS_ANNOUNCEMENT)") - ] - - # Blueprint Plugin - - @octoprint.plugin.BlueprintPlugin.route("/channels", methods=["GET"]) - @no_firstrun_access - @Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403) - def get_channel_data(self): - from octoprint.settings import valid_boolean_trues - - result = [] - - force = flask.request.values.get("force", "false") in valid_boolean_trues - - enabled = self._settings.get(["enabled_channels"]) - forced = self._settings.get(["forced_channels"]) - - channel_configs = self._get_channel_configs(force=force) - - def view(): - channel_data = self._fetch_all_channels(force=force) - - for key, data in channel_configs.items(): - read_until = channel_configs[key].get("read_until", None) - entries = sorted(self._to_internal_feed(channel_data.get(key, []), read_until=read_until), key=lambda e: e["published"], reverse=True) - unread = count(filter(lambda e: not e["read"], entries)) - - if read_until is None and entries: - last = entries[0]["published"] - self._mark_read_until(key, last) - - result.append(dict(key=key, - channel=data["name"], - url=data["url"], - description=data.get("description", ""), - priority=data.get("priority", 2), - enabled=key in enabled or key in forced, - forced=key in forced, - data=entries, - unread=unread)) - - return flask.jsonify(channels=result) - - def etag(): - import hashlib - hash = hashlib.sha1() - def hash_update(value): - hash.update(value.encode("utf-8")) - hash_update(repr(sorted(enabled))) - hash_update(repr(sorted(forced))) - hash_update(OCTOPRINT_VERSION) - - for channel in sorted(channel_configs.keys()): - hash_update(repr(channel_configs[channel])) - channel_data = self._get_channel_data_from_cache(channel, channel_configs[channel]) - hash_update(repr(channel_data)) - - return hash.hexdigest() - - # noinspection PyShadowingNames - def condition(lm, etag): - return check_etag(etag) - - return with_revalidation_checking(etag_factory=lambda *args, **kwargs: etag(), - condition=lambda lm, etag: condition(lm, etag), - unless=lambda: force)(view)() - - @octoprint.plugin.BlueprintPlugin.route("/channels/", methods=["POST"]) - @no_firstrun_access - @Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403) - def channel_command(self, channel): - from octoprint.server.util.flask import get_json_command_from_request - from octoprint.server import NO_CONTENT - - valid_commands = dict(read=["until"], - toggle=[]) - - command, data, response = get_json_command_from_request(flask.request, valid_commands=valid_commands) - if response is not None: - return response - - if command == "read": - until = data["until"] - self._mark_read_until(channel, until) +from octoprint.server.util.flask import ( + check_etag, + no_firstrun_access, + with_revalidation_checking, +) +from octoprint.util import count, utmify +from octoprint.util.text import sanitize + +PY2 = sys.version_info[0] < 3 + + +class AnnouncementPlugin( + octoprint.plugin.AssetPlugin, + octoprint.plugin.SettingsPlugin, + octoprint.plugin.BlueprintPlugin, + octoprint.plugin.StartupPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.EventHandlerPlugin, +): + + # noinspection PyMissingConstructor + def __init__(self): + self._cached_channel_configs = None + self._cached_channel_configs_mutex = threading.RLock() + + # Additional permissions hook + + def get_additional_permissions(self): + return [ + { + "key": "READ", + "name": "Read announcements", + "description": gettext("Allows to read announcements"), + "default_groups": [ADMIN_GROUP], + "roles": ["read"], + }, + { + "key": "MANAGE", + "name": "Manage announcement subscriptions", + "description": gettext( + 'Allows to manage announcement subscriptions. Includes "Read announcements" ' + "permission" + ), + "default_groups": [ADMIN_GROUP], + "roles": ["manage"], + "permissions": ["PLUGIN_ANNOUNCEMENTS_READ"], + }, + ] + + # StartupPlugin + + def on_after_startup(self): + # decouple channel fetching from server startup + def fetch_data(): + self._fetch_all_channels() + + thread = threading.Thread(target=fetch_data) + thread.daemon = True + thread.start() + + # SettingsPlugin + + def get_settings_defaults(self): + settings = { + "channels": { + "_important": { + "name": "Important Announcements", + "description": "Important announcements about OctoPrint.", + "priority": 1, + "type": "rss", + "url": "https://octoprint.org/feeds/important.xml", + }, + "_releases": { + "name": "Release Announcements", + "description": "Announcements of new releases and release candidates of OctoPrint.", + "priority": 2, + "type": "rss", + "url": "https://octoprint.org/feeds/releases.xml", + }, + "_blog": { + "name": "On the OctoBlog", + "description": "Development news, community spotlights, OctoPrint On Air episodes and more from the official OctoBlog.", + "priority": 2, + "type": "rss", + "url": "https://octoprint.org/feeds/octoblog.xml", + }, + "_plugins": { + "name": "New Plugins in the Repository", + "description": "Announcements of new plugins released on the official Plugin Repository.", + "priority": 2, + "type": "rss", + "url": "https://plugins.octoprint.org/feed.xml", + }, + "_octopi": { + "name": "OctoPi News", + "description": "News around OctoPi, the Raspberry Pi image including OctoPrint.", + "priority": 2, + "type": "rss", + "url": "https://octoprint.org/feeds/octopi.xml", + }, + }, + "enabled_channels": [], + "forced_channels": ["_important"], + "channel_order": ["_important", "_releases", "_blog", "_plugins", "_octopi"], + "ttl": 6 * 60, + "display_limit": 3, + "summary_limit": 300, + } + settings["enabled_channels"] = list(settings["channels"].keys()) + return settings + + def get_settings_version(self): + return 1 + + def on_settings_migrate(self, target, current): + if current is None: + # first version had different default feeds and only _important enabled by default + channels = self._settings.get(["channels"]) + if "_news" in channels: + del channels["_news"] + if "_spotlight" in channels: + del channels["_spotlight"] + self._settings.set(["channels"], channels) + + enabled = self._settings.get(["enabled_channels"]) + add_blog = False + if "_news" in enabled: + add_blog = True + enabled.remove("_news") + if "_spotlight" in enabled: + add_blog = True + enabled.remove("_spotlight") + if add_blog and "_blog" not in enabled: + enabled.append("_blog") + self._settings.set(["enabled_channels"], enabled) + + # AssetPlugin + + def get_assets(self): + return { + "js": ["js/announcements.js"], + "less": ["less/announcements.less"], + "css": ["css/announcements.css"], + } + + # Template Plugin + + def get_template_configs(self): + return [ + { + "type": "settings", + "name": gettext("Announcements"), + "template": "announcements_settings.jinja2", + "custom_bindings": True, + }, + { + "type": "navbar", + "template": "announcements_navbar.jinja2", + "styles": ["display: none"], + "data_bind": "visible: loginState.hasPermission(access.permissions.PLUGIN_ANNOUNCEMENTS_READ)", + }, + ] + + # Blueprint Plugin + + @octoprint.plugin.BlueprintPlugin.route("/channels", methods=["GET"]) + @no_firstrun_access + @Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403) + def get_channel_data(self): + from octoprint.settings import valid_boolean_trues + + result = [] + + force = flask.request.values.get("force", "false") in valid_boolean_trues + + enabled = self._settings.get(["enabled_channels"]) + forced = self._settings.get(["forced_channels"]) + + channel_configs = self._get_channel_configs(force=force) + + def view(): + channel_data = self._fetch_all_channels(force=force) + + for key, data in channel_configs.items(): + read_until = channel_configs[key].get("read_until", None) + entries = sorted( + self._to_internal_feed( + channel_data.get(key, []), read_until=read_until + ), + key=lambda e: e["published"], + reverse=True, + ) + unread = count(filter(lambda e: not e["read"], entries)) + + if read_until is None and entries: + last = entries[0]["published"] + self._mark_read_until(key, last) + + result.append( + { + "key": key, + "channel": data["name"], + "url": data["url"], + "description": data.get("description", ""), + "priority": data.get("priority", 2), + "enabled": key in enabled or key in forced, + "forced": key in forced, + "data": entries, + "unread": unread, + } + ) + + return flask.jsonify(channels=result) + + def etag(): + import hashlib + + hash = hashlib.sha1() + + def hash_update(value): + hash.update(value.encode("utf-8")) + + hash_update(repr(sorted(enabled))) + hash_update(repr(sorted(forced))) + hash_update(OCTOPRINT_VERSION) + + for channel in sorted(channel_configs.keys()): + hash_update(repr(channel_configs[channel])) + channel_data = self._get_channel_data_from_cache( + channel, channel_configs[channel] + ) + hash_update(repr(channel_data)) + + return hash.hexdigest() + + # noinspection PyShadowingNames + def condition(lm, etag): + return check_etag(etag) + + return with_revalidation_checking( + etag_factory=lambda *args, **kwargs: etag(), + condition=lambda lm, etag: condition(lm, etag), + unless=lambda: force, + )(view)() + + @octoprint.plugin.BlueprintPlugin.route("/channels/", methods=["POST"]) + @no_firstrun_access + @Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403) + def channel_command(self, channel): + from octoprint.server import NO_CONTENT + from octoprint.server.util.flask import get_json_command_from_request + + valid_commands = {"read": ["until"], "toggle": []} + + command, data, response = get_json_command_from_request( + flask.request, valid_commands=valid_commands + ) + if response is not None: + return response + + if command == "read": + until = data["until"] + self._mark_read_until(channel, until) + + elif command == "toggle": + if not Permissions.PLUGIN_ANNOUNCEMENTS_MANAGE.can(): + return flask.make_response("Insufficient rights", 403) + self._toggle(channel) + + return NO_CONTENT + + def is_blueprint_protected(self): + return False + + ##~~ EventHandlerPlugin + + def on_event(self, event, payload): + from octoprint.events import Events + + if ( + event != Events.CONNECTIVITY_CHANGED + or not payload + or not payload.get("new", False) + ): + return + self._fetch_all_channels_async() + + # Internal Tools + + def _mark_read_until(self, channel, until): + """Set read_until timestamp of a channel.""" + + current_read_until = None + channel_data = self._settings.get(["channels", channel], merged=True) + if channel_data: + current_read_until = channel_data.get("read_until", None) + + defaults = {"plugins": {"announcements": {"channels": {}}}} + defaults["plugins"]["announcements"]["channels"][channel] = { + "read_until": current_read_until + } + + with self._cached_channel_configs_mutex: + self._settings.set( + ["channels", channel, "read_until"], until, defaults=defaults + ) + self._settings.save() + self._cached_channel_configs = None + + def _toggle(self, channel): + """Toggle enable/disabled state of a channel.""" + + enabled_channels = list(self._settings.get(["enabled_channels"])) + + if channel in enabled_channels: + enabled_channels.remove(channel) + else: + enabled_channels.append(channel) + + self._settings.set(["enabled_channels"], enabled_channels) + self._settings.save() + + def _get_channel_configs(self, force=False): + """Retrieve all channel configs with sanitized keys.""" + + with self._cached_channel_configs_mutex: + if self._cached_channel_configs is None or force: + configs = self._settings.get(["channels"], merged=True) + order = self._settings.get(["channel_order"]) + all_keys = order + [ + key for key in sorted(configs.keys()) if key not in order + ] + + result = OrderedDict() + for key in all_keys: + config = configs.get(key) + if config is None or "url" not in config or "name" not in config: + # strip invalid entries + continue + result[sanitize(key)] = config + self._cached_channel_configs = result + return self._cached_channel_configs + + def _get_channel_config(self, key, force=False): + """Retrieve specific channel config for channel.""" + + safe_key = sanitize(key) + return self._get_channel_configs(force=force).get(safe_key) + + def _fetch_all_channels_async(self, force=False): + thread = threading.Thread( + target=self._fetch_all_channels, kwargs={"force": force} + ) + thread.daemon = True + thread.start() + + def _fetch_all_channels(self, force=False): + """Fetch all channel feeds from cache or network.""" + + channels = self._get_channel_configs(force=force) + enabled = self._settings.get(["enabled_channels"]) + forced = self._settings.get(["forced_channels"]) + + all_channels = {} + for key, config in channels.items(): + if key not in enabled and key not in forced: + continue + + if "url" not in config: + continue + + data = self._get_channel_data(key, config, force=force) + if data is not None: + all_channels[key] = data + + return all_channels + + def _get_channel_data(self, key, config, force=False): + """Fetch individual channel feed from cache/network.""" + + data = None + + if not force: + # we may use the cache, see if we have something in there + data = self._get_channel_data_from_cache(key, config) + + if data is None: + # cache not allowed or empty, fetch from network + if self._connectivity_checker.online: + data = self._get_channel_data_from_network(key, config) + else: + self._logger.info( + "Looks like we are offline, can't fetch announcements for channel {} from network".format( + key + ) + ) + + return data + + def _get_channel_data_from_cache(self, key, config): + """Fetch channel feed from cache.""" + + channel_path = self._get_channel_cache_path(key) + + if os.path.exists(channel_path): + if "ttl" in config and isinstance(config["ttl"], int): + ttl = config["ttl"] + else: + ttl = self._settings.get_int(["ttl"]) + + ttl *= 60 + now = time.time() + if os.stat(channel_path).st_mtime + ttl > now: + d = feedparser.parse(channel_path) + self._logger.debug( + "Loaded channel {} from cache at {}".format(key, channel_path) + ) + return d + + return None + + def _get_channel_data_from_network(self, key, config): + """Fetch channel feed from network.""" + + import requests + + url = config["url"] + try: + start = time.monotonic() + r = requests.get(url, timeout=30) + r.raise_for_status() + self._logger.info( + "Loaded channel {} from {} in {:.2}s".format( + key, config["url"], time.monotonic() - start + ) + ) + except Exception: + self._logger.exception( + "Could not fetch channel {} from {}".format(key, config["url"]) + ) + return None + + response = r.text + channel_path = self._get_channel_cache_path(key) + with io.open(channel_path, mode="wt", encoding="utf-8") as f: + f.write(response) + return feedparser.parse(response) + + def _to_internal_feed(self, feed, read_until=None): + """Convert feed to internal data structure.""" + + result = [] + if "entries" in feed: + for entry in feed["entries"]: + try: + internal_entry = self._to_internal_entry(entry, read_until=read_until) + if internal_entry: + result.append(internal_entry) + except Exception: + self._logger.exception( + "Error while converting entry from feed, skipping it" + ) + return result + + def _to_internal_entry(self, entry, read_until=None): + """Convert feed entries to internal data structure.""" + + timestamp = entry.get("published_parsed", None) + if timestamp is None: + timestamp = entry.get("updated_parsed", None) + if timestamp is None: + return None + + published = calendar.timegm(timestamp) + + read = True + if read_until is not None: + read = published <= read_until + + return { + "title": entry["title"], + "title_without_tags": _strip_tags(entry["title"]), + "summary": _lazy_images(entry["summary"]), + "summary_without_images": _strip_images(entry["summary"]), + "published": published, + "link": utmify( + entry["link"], + source="octoprint", + medium="announcements", + content=OCTOPRINT_VERSION, + ), + "read": read, + } + + def _get_channel_cache_path(self, key): + """Retrieve cache path for channel key.""" + + safe_key = sanitize(key) + return os.path.join(self.get_plugin_data_folder(), "{}.cache".format(safe_key)) + + +_image_tag_re = re.compile(r"") - elif command == "toggle": - if not Permissions.PLUGIN_ANNOUNCEMENTS_MANAGE.can(): - return flask.make_response("Insufficient rights", 403) - self._toggle(channel) - return NO_CONTENT - - ##~~ EventHandlerPlugin - - def on_event(self, event, payload): - from octoprint.events import Events - if event != Events.CONNECTIVITY_CHANGED or not payload or not payload.get("new", False): - return - self._fetch_all_channels_async() - - # Internal Tools - - def _mark_read_until(self, channel, until): - """Set read_until timestamp of a channel.""" - - current_read_until = None - channel_data = self._settings.get(["channels", channel], merged=True) - if channel_data: - current_read_until = channel_data.get("read_until", None) - - defaults = dict(plugins=dict(announcements=dict(channels=dict()))) - defaults["plugins"]["announcements"]["channels"][channel] = dict(read_until=current_read_until) - - with self._cached_channel_configs_mutex: - self._settings.set(["channels", channel, "read_until"], until, defaults=defaults) - self._settings.save() - self._cached_channel_configs = None - - def _toggle(self, channel): - """Toggle enable/disabled state of a channel.""" - - enabled_channels = list(self._settings.get(["enabled_channels"])) - - if channel in enabled_channels: - enabled_channels.remove(channel) - else: - enabled_channels.append(channel) - - self._settings.set(["enabled_channels"], enabled_channels) - self._settings.save() - - def _get_channel_configs(self, force=False): - """Retrieve all channel configs with sanitized keys.""" - - with self._cached_channel_configs_mutex: - if self._cached_channel_configs is None or force: - configs = self._settings.get(["channels"], merged=True) - order = self._settings.get(["channel_order"]) - all_keys = order + [key for key in sorted(configs.keys()) if not key in order] - - result = OrderedDict() - for key in all_keys: - config = configs.get(key) - if config is None or "url" not in config or "name" not in config: - # strip invalid entries - continue - result[self._slugify(key)] = config - self._cached_channel_configs = result - return self._cached_channel_configs - - def _get_channel_config(self, key, force=False): - """Retrieve specific channel config for channel.""" - - safe_key = self._slugify(key) - return self._get_channel_configs(force=force).get(safe_key) - - def _fetch_all_channels_async(self, force=False): - thread = threading.Thread(target=self._fetch_all_channels, kwargs=dict(force=force)) - thread.daemon = True - thread.start() - - def _fetch_all_channels(self, force=False): - """Fetch all channel feeds from cache or network.""" - - channels = self._get_channel_configs(force=force) - enabled = self._settings.get(["enabled_channels"]) - forced = self._settings.get(["forced_channels"]) - - all_channels = dict() - for key, config in channels.items(): - if not key in enabled and not key in forced: - continue - - if not "url" in config: - continue - - data = self._get_channel_data(key, config, force=force) - if data is not None: - all_channels[key] = data - - return all_channels - - def _get_channel_data(self, key, config, force=False): - """Fetch individual channel feed from cache/network.""" - - data = None - - if not force: - # we may use the cache, see if we have something in there - data = self._get_channel_data_from_cache(key, config) - - if data is None: - # cache not allowed or empty, fetch from network - if self._connectivity_checker.online: - data = self._get_channel_data_from_network(key, config) - else: - self._logger.info("Looks like we are offline, can't fetch announcements for channel {} from network".format(key)) - - return data - - def _get_channel_data_from_cache(self, key, config): - """Fetch channel feed from cache.""" - - channel_path = self._get_channel_cache_path(key) - - if os.path.exists(channel_path): - if "ttl" in config and isinstance(config["ttl"], int): - ttl = config["ttl"] - else: - ttl = self._settings.get_int(["ttl"]) - - ttl *= 60 - now = time.time() - if os.stat(channel_path).st_mtime + ttl > now: - d = feedparser.parse(channel_path) - self._logger.debug("Loaded channel {} from cache at {}".format(key, channel_path)) - return d - - return None - - def _get_channel_data_from_network(self, key, config): - """Fetch channel feed from network.""" - - import requests - - url = config["url"] - try: - start = monotonic_time() - r = requests.get(url, timeout=30) - r.raise_for_status() - self._logger.info("Loaded channel {} from {} in {:.2}s".format(key, config["url"], monotonic_time() - start)) - except Exception: - self._logger.exception( - "Could not fetch channel {} from {}".format(key, config["url"])) - return None - - response = r.text - channel_path = self._get_channel_cache_path(key) - with io.open(channel_path, mode="wt", encoding="utf-8") as f: - f.write(response) - return feedparser.parse(response) - - def _to_internal_feed(self, feed, read_until=None): - """Convert feed to internal data structure.""" - - result = [] - if "entries" in feed: - for entry in feed["entries"]: - try: - internal_entry = self._to_internal_entry(entry, read_until=read_until) - if internal_entry: - result.append(internal_entry) - except Exception: - self._logger.exception("Error while converting entry from feed, skipping it") - return result - - def _to_internal_entry(self, entry, read_until=None): - """Convert feed entries to internal data structure.""" - - timestamp = entry.get("published_parsed", None) - if timestamp is None: - timestamp = entry.get("updated_parsed", None) - if timestamp is None: - return None - - published = calendar.timegm(timestamp) - - read = True - if read_until is not None: - read = published <= read_until - - return dict(title=entry["title"], - title_without_tags=_strip_tags(entry["title"]), - summary=_lazy_images(entry["summary"]), - summary_without_images=_strip_images(entry["summary"]), - published=published, - link=utmify(entry["link"], source="octoprint", medium="announcements", content=OCTOPRINT_VERSION), - read=read) - - def _get_channel_cache_path(self, key): - """Retrieve cache path for channel key.""" - - safe_key = self._slugify(key) - return os.path.join(self.get_plugin_data_folder(), "{}.cache".format(safe_key)) - - -_image_tag_re = re.compile(r'') def _strip_images(text): - """ - >>> _strip_images("I'm a link and this is an image: foo") # doctest: +ALLOW_UNICODE - "I'm a link and this is an image: " - >>> _strip_images("One and two and three and four \\"four\\"") # doctest: +ALLOW_UNICODE - 'One and two and three and four ' - >>> _strip_images("No images here") # doctest: +ALLOW_UNICODE - 'No images here' - """ - return _image_tag_re.sub('', text) + """ + >>> _strip_images("I'm a link and this is an image: foo") # doctest: +ALLOW_UNICODE + "I'm a link and this is an image: " + >>> _strip_images("One and two and three and four \\"four\\"") # doctest: +ALLOW_UNICODE + 'One and two and three and four ' + >>> _strip_images("No images here") # doctest: +ALLOW_UNICODE + 'No images here' + """ + return _image_tag_re.sub("", text) + def _replace_images(text, callback): - """ - >>> callback = lambda img: "foobar" - >>> _replace_images("I'm a link and this is an image: foo", callback) # doctest: +ALLOW_UNICODE - "I'm a link and this is an image: foobar" - >>> _replace_images("One and two and three and four \\"four\\"", callback) # doctest: +ALLOW_UNICODE - 'One foobar and two foobar and three foobar and four foobar' - """ - result = text - for match in _image_tag_re.finditer(text): - tag = match.group(0) - replaced = callback(tag) - result = result.replace(tag, replaced) - return result + """ + >>> callback = lambda img: "foobar" + >>> _replace_images("I'm a link and this is an image: foo", callback) # doctest: +ALLOW_UNICODE + "I'm a link and this is an image: foobar" + >>> _replace_images("One and two and three and four \\"four\\"", callback) # doctest: +ALLOW_UNICODE + 'One foobar and two foobar and three foobar and four foobar' + """ + result = text + for match in _image_tag_re.finditer(text): + tag = match.group(0) + replaced = callback(tag) + result = result.replace(tag, replaced) + return result + _image_src_re = re.compile(r'src=(?P[\'"]*)(?P.*?)(?P=quote)(?=\s+|>)') + + def _lazy_images(text, placeholder=None): - """ - >>> _lazy_images("I'm a link and this is an image: foo") # doctest: +ALLOW_UNICODE - 'I\\'m a link and this is an image: \\'foo\\'' - >>> _lazy_images("I'm a link and this is an image: foo", placeholder="ph.png") # doctest: +ALLOW_UNICODE - 'I\\'m a link and this is an image: \\'foo\\'' - >>> _lazy_images("One and two and three and four \\"four\\"", placeholder="ph.png") # doctest: +ALLOW_UNICODE - 'One and two and three and four four' - >>> _lazy_images("No images here") # doctest: +ALLOW_UNICODE - 'No images here' - """ - if placeholder is None: - # 1px transparent gif - placeholder = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" + """ + >>> _lazy_images("I'm a link and this is an image: foo") # doctest: +ALLOW_UNICODE + 'I\\'m a link and this is an image: \\'foo\\'' + >>> _lazy_images("I'm a link and this is an image: foo", placeholder="ph.png") # doctest: +ALLOW_UNICODE + 'I\\'m a link and this is an image: \\'foo\\'' + >>> _lazy_images("One and two and three and four \\"four\\"", placeholder="ph.png") # doctest: +ALLOW_UNICODE + 'One and two and three and four four' + >>> _lazy_images("No images here") # doctest: +ALLOW_UNICODE + 'No images here' + """ + if placeholder is None: + # 1px transparent gif + placeholder = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" - def callback(img_tag): - match = _image_src_re.search(img_tag) - if match is not None: - src = match.group("src") - quote = match.group("quote") - quoted_src = quote + src + quote - img_tag = img_tag.replace(match.group(0), 'src="{}" data-src={}'.format(placeholder, quoted_src)) - return img_tag + def callback(img_tag): + match = _image_src_re.search(img_tag) + if match is not None: + src = match.group("src") + quote = match.group("quote") + quoted_src = quote + src + quote + img_tag = img_tag.replace( + match.group(0), 'src="{}" data-src={}'.format(placeholder, quoted_src) + ) + return img_tag + + return _replace_images(text, callback) - return _replace_images(text, callback) def _strip_tags(text): - """ - >>> _strip_tags("Hello world<img src='foo.jpg'>") # doctest: +ALLOW_UNICODE - "Hello world<img src='foo.jpg'>" - >>> _strip_tags("> > Foo") # doctest: +ALLOW_UNICODE - '> > Foo' - """ - try: - # noinspection PyCompatibility - from html.parser import HTMLParser - except ImportError: - # noinspection PyCompatibility - from HTMLParser import HTMLParser + """ + >>> _strip_tags("Hello world<img src='foo.jpg'>") # doctest: +ALLOW_UNICODE + "Hello world<img src='foo.jpg'>" + >>> _strip_tags("> > Foo") # doctest: +ALLOW_UNICODE + '> > Foo' + """ + from html.parser import HTMLParser - class TagStripper(HTMLParser): + class TagStripper(HTMLParser): + def __init__(self, **kw): + HTMLParser.__init__(self, **kw) + self._fed = [] - def __init__(self, **kw): - HTMLParser.__init__(self, **kw) - self._fed = [] + def handle_data(self, data): + self._fed.append(data) - def handle_data(self, data): - self._fed.append(data) + def handle_entityref(self, ref): + self._fed.append("&{};".format(ref)) - def handle_entityref(self, ref): - self._fed.append("&{};".format(ref)) + def handle_charref(self, ref): + self._fed.append("&#{};".format(ref)) - def handle_charref(self, ref): - self._fed.append("&#{};".format(ref)) + def get_data(self): + return "".join(self._fed) - def get_data(self): - return "".join(self._fed) - - tag_stripper = TagStripper() if PY2 else TagStripper(convert_charrefs=False) - tag_stripper.feed(text) - return tag_stripper.get_data() + tag_stripper = TagStripper() if PY2 else TagStripper(convert_charrefs=False) + tag_stripper.feed(text) + return tag_stripper.get_data() __plugin_name__ = "Announcement Plugin" __plugin_author__ = "Gina Häußge" __plugin_description__ = "Announcements all around OctoPrint" -__plugin_disabling_discouraged__ = gettext("Without this plugin you might miss important announcements " - "regarding security or other critical issues concerning OctoPrint.") +__plugin_disabling_discouraged__ = gettext( + "Without this plugin you might miss important announcements " + "regarding security or other critical issues concerning OctoPrint." +) __plugin_license__ = "AGPLv3" +__plugin_pythoncompat__ = ">=2.7,<4" __plugin_implementation__ = AnnouncementPlugin() __plugin_hooks__ = { - 'octoprint.access.permissions': __plugin_implementation__.get_additional_permissions + "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions } diff --git a/src/octoprint/plugins/announcements/static/js/announcements.js b/src/octoprint/plugins/announcements/static/js/announcements.js index ece0a9367..75720f39a 100644 --- a/src/octoprint/plugins/announcements/static/js/announcements.js +++ b/src/octoprint/plugins/announcements/static/js/announcements.js @@ -1,4 +1,4 @@ -$(function() { +$(function () { function AnnouncementsViewModel(parameters) { var self = this; @@ -9,22 +9,29 @@ $(function() { self.channels = new ItemListHelper( "plugin.announcements.channels", { - "channel": function (a, b) { + channel: function (a, b) { // sorts ascending - if (a["channel"].toLocaleLowerCase() < b["channel"].toLocaleLowerCase()) return -1; - if (a["channel"].toLocaleLowerCase() > b["channel"].toLocaleLowerCase()) return 1; + if ( + a["channel"].toLocaleLowerCase() < + b["channel"].toLocaleLowerCase() + ) + return -1; + if ( + a["channel"].toLocaleLowerCase() > + b["channel"].toLocaleLowerCase() + ) + return 1; return 0; } }, - { - }, + {}, "name", [], [], 5 ); - self.unread = ko.observable(); + self.unread = ko.observable(false); self.hiddenChannels = []; self.channelNotifications = {}; @@ -32,30 +39,34 @@ $(function() { self.announcementDialogContent = undefined; self.announcementDialogTabs = undefined; - self.setupTabLink = function(item) { + self.setupTabLink = function (item) { $("a[data-toggle='tab']", item).on("show", self.resetContentScroll); }; - self.resetContentScroll = function() { + self.resetContentScroll = function () { self.announcementDialogContent.scrollTop(0); }; - self.toggleButtonCss = function(data) { + self.toggleButtonCss = function (data) { var icon = data.enabled ? "fa fa-toggle-on" : "fa fa-toggle-off"; - var disabled = (self.enableToggle(data)) ? "" : " disabled"; + var disabled = self.enableToggle(data) ? "" : " disabled"; return icon + disabled; }; - self.toggleButtonTitle = function(data) { - return data.forced ? gettext("Cannot be toggled") : (data.enabled ? gettext("Disable Channel") : gettext("Enable Channel")); + self.toggleButtonTitle = function (data) { + return data.forced + ? gettext("Cannot be toggled") + : data.enabled + ? gettext("Disable Channel") + : gettext("Enable Channel"); }; - self.enableToggle = function(data) { + self.enableToggle = function (data) { return !data.forced; }; - self.cleanedLink = function(data) { + self.cleanedLink = function (data) { // Strips any query parameters from the link and returns it var link = data.link; if (!link) return link; @@ -67,8 +78,13 @@ $(function() { return link; }; - self.markRead = function(channel, until, reload) { - if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return; + self.markRead = function (channel, until, reload) { + if ( + !self.loginState.hasPermission( + self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ + ) + ) + return; reload = !!reload; @@ -85,16 +101,21 @@ $(function() { dataType: "json", data: JSON.stringify(payload), contentType: "application/json; charset=UTF-8", - success: function() { + success: function () { if (reload) { - self.retrieveData() + self.retrieveData(); } } - }) + }); }; - self.toggleChannel = function(channel) { - if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_MANAGE)) return; + self.toggleChannel = function (channel) { + if ( + !self.loginState.hasPermission( + self.access.permissions.PLUGIN_ANNOUNCEMENTS_MANAGE + ) + ) + return; var url = PLUGIN_BASEURL + "announcements/channels/" + channel; @@ -108,18 +129,23 @@ $(function() { dataType: "json", data: JSON.stringify(payload), contentType: "application/json; charset=UTF-8", - success: function() { - self.retrieveData() + success: function () { + self.retrieveData(); } - }) + }); }; - self.refreshAnnouncements = function() { + self.refreshAnnouncements = function () { self.retrieveData(true); }; - self.retrieveData = function(force) { - if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return; + self.retrieveData = function (force) { + if ( + !self.loginState.hasPermission( + self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ + ) + ) + return; var url = PLUGIN_BASEURL + "announcements/channels"; if (force) { @@ -130,20 +156,25 @@ $(function() { url: url, type: "GET", dataType: "json", - success: function(data) { + success: function (data) { self.fromResponse(data); } }); }; - self.fromResponse = function(data) { - if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return; + self.fromResponse = function (data) { + if ( + !self.loginState.hasPermission( + self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ + ) + ) + return; var currentTab = $("li.active a", self.announcementDialogTabs).attr("href"); var unread = 0; var channels = []; - _.each(data.channels, function(value) { + _.each(data.channels, function (value) { value.last = value.data.length ? value.data[0].published : undefined; value.count = value.data.length; unread += value.unread; @@ -157,8 +188,13 @@ $(function() { self.selectTab(currentTab); }; - self.showAnnouncementDialog = function(channel) { - if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return; + self.showAnnouncementDialog = function (channel) { + if ( + !self.loginState.hasPermission( + self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ + ) + ) + return; // lazy load images that still need lazy-loading $("#plugin_announcements_dialog_content article img").lazyload(); @@ -166,12 +202,18 @@ $(function() { self.announcementDialogContent.scrollTop(0); if (!self.announcementDialog.hasClass("in")) { - self.announcementDialog.modal({ - minHeight: function() { return Math.max($.fn.modal.defaults.maxHeight() - 80, 250); } - }).css({ - width: 'auto', - 'margin-left': function() { return -($(this).width() /2); } - }); + self.announcementDialog + .modal({ + minHeight: function () { + return Math.max($.fn.modal.defaults.maxHeight() - 80, 250); + } + }) + .css({ + "width": "auto", + "margin-left": function () { + return -($(this).width() / 2); + } + }); } var tab = undefined; @@ -183,24 +225,29 @@ $(function() { return false; }; - self.selectTab = function(tab) { + self.selectTab = function (tab) { if (tab != undefined) { if (!_.startsWith(tab, "#")) { tab = "#" + tab; } $('a[href="' + tab + '"]', self.announcementDialogTabs).tab("show"); } else { - $('a:first', self.announcementDialogTabs).tab("show"); + $("a:first", self.announcementDialogTabs).tab("show"); } }; - self.displayAnnouncements = function(channels) { - if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return; + self.displayAnnouncements = function (channels) { + if ( + !self.loginState.hasPermission( + self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ + ) + ) + return; var displayLimit = self.settings.settings.plugins.announcements.display_limit(); var maxLength = self.settings.settings.plugins.announcements.summary_limit(); - var cutAfterNewline = function(text) { + var cutAfterNewline = function (text) { text = text.trim(); var firstNewlinePos = text.indexOf("\n"); @@ -211,7 +258,7 @@ $(function() { return text; }; - var stripParagraphs = function(text) { + var stripParagraphs = function (text) { if (_.startsWith(text, "

")) { text = text.substr("

".length); } @@ -219,10 +266,10 @@ $(function() { text = text.substr(0, text.length - "

".length); } - return text.replace(/<\/p>\s*

/ig, "
"); + return text.replace(/<\/p>\s*

/gi, "
"); }; - _.each(channels, function(value) { + _.each(channels, function (value) { var key = value.key; var channel = value.channel; var priority = value.priority; @@ -233,7 +280,9 @@ $(function() { return; } - var newItems = _.filter(items, function(entry) { return !entry.read; }); + var newItems = _.filter(items, function (entry) { + return !entry.read; + }); if (newItems.length == 0) { // no new items at all, we don't display anything for this channel return; @@ -248,23 +297,48 @@ $(function() { var rest = newItems.length - displayedItems.length; var text = "

    "; - _.each(displayedItems, function(item) { - var limitedSummary = stripParagraphs(item.summary_without_images.trim()); + _.each(displayedItems, function (item) { + var limitedSummary = stripParagraphs( + item.summary_without_images.trim() + ); if (limitedSummary.length > maxLength) { limitedSummary = limitedSummary.substr(0, maxLength); - limitedSummary = limitedSummary.substr(0, Math.min(limitedSummary.length, limitedSummary.lastIndexOf(" "))); + limitedSummary = limitedSummary.substr( + 0, + Math.min( + limitedSummary.length, + limitedSummary.lastIndexOf(" ") + ) + ); limitedSummary += "..."; } - text += "
  • " + cutAfterNewline(item.title) + "
    " + formatTimeAgo(item.published) + "

    " + limitedSummary + "

  • "; + text += + "
  • " + + cutAfterNewline(item.title) + + "
    " + + formatTimeAgo(item.published) + + "

    " + + limitedSummary + + "

  • "; }); text += "
"; if (rest) { - text += "

" + gettext(_.sprintf("... and %(rest)d more.", {rest: rest})) + "

"; + text += + "

" + + gettext(_.sprintf("... and %(rest)d more.", {rest: rest})) + + "

"; } - text += "" + gettext("You can edit your announcement subscriptions under Settings > Announcements.") + ""; + text += + "" + + gettext( + "You can edit your announcement subscriptions under Settings > Announcements." + ) + + ""; var options = { title: channel, @@ -272,27 +346,31 @@ $(function() { hide: false, confirm: { confirm: true, - buttons: [{ - text: gettext("Later"), - click: function(notice) { - notice.remove(); - self.hiddenChannels.push(key); + buttons: [ + { + text: gettext("Later"), + click: function (notice) { + notice.remove(); + self.hiddenChannels.push(key); + } + }, + { + text: gettext("Mark read"), + click: function (notice) { + notice.remove(); + self.markRead(key, value.last); + } + }, + { + text: gettext("Read..."), + addClass: "btn-primary", + click: function (notice) { + notice.remove(); + self.showAnnouncementDialog(key); + self.markRead(key, value.last); + } } - }, { - text: gettext("Mark read"), - click: function(notice) { - notice.remove(); - self.markRead(key, value.last); - } - }, { - text: gettext("Read..."), - addClass: "btn-primary", - click: function(notice) { - notice.remove(); - self.showAnnouncementDialog(key); - self.markRead(key, value.last); - } - }] + ] }, buttons: { sticker: false, @@ -311,41 +389,48 @@ $(function() { }); }; - self.hideAnnouncements = function() { - _.each(self.channelNotifications, function(notification, key) { + self.hideAnnouncements = function () { + _.each(self.channelNotifications, function (notification, key) { notification.remove(); }); self.channelNotifications = {}; }; - self.configureAnnouncements = function() { + self.configureAnnouncements = function () { self.settings.show("settings_plugin_announcements"); }; - self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() { - if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) { + self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () { + if ( + !self.loginState.hasPermission( + self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ + ) + ) { self.hideAnnouncements(); } else { self.retrieveData(); } }; - self.onStartup = function() { + self.onStartup = function () { self.announcementDialog = $("#plugin_announcements_dialog"); self.announcementDialogContent = $("#plugin_announcements_dialog_content"); self.announcementDialogTabs = $("#plugin_announcements_dialog_tabs"); }; - self.onEventConnectivityChanged = function(payload) { + self.onEventConnectivityChanged = function (payload) { if (!payload || !payload.new) return; self.retrieveData(); - } - + }; } OCTOPRINT_VIEWMODELS.push({ construct: AnnouncementsViewModel, dependencies: ["loginStateViewModel", "settingsViewModel", "accessViewModel"], - elements: ["#plugin_announcements_dialog", "#settings_plugin_announcements", "#navbar_plugin_announcements"] + elements: [ + "#plugin_announcements_dialog", + "#settings_plugin_announcements", + "#navbar_plugin_announcements" + ] }); }); diff --git a/src/octoprint/plugins/announcements/static/less/announcements.less b/src/octoprint/plugins/announcements/static/less/announcements.less index 9e90b346c..42ffeb5f1 100644 --- a/src/octoprint/plugins/announcements/static/less/announcements.less +++ b/src/octoprint/plugins/announcements/static/less/announcements.less @@ -1,5 +1,6 @@ table { - th, td { + th, + td { &.settings_plugin_announcements_channels_name { text-overflow: ellipsis; text-align: left; diff --git a/src/octoprint/plugins/announcements/templates/announcements.jinja2 b/src/octoprint/plugins/announcements/templates/announcements.jinja2 index 47bf0952e..670a1bf78 100644 --- a/src/octoprint/plugins/announcements/templates/announcements.jinja2 +++ b/src/octoprint/plugins/announcements/templates/announcements.jinja2 @@ -28,7 +28,7 @@
@@ -40,7 +40,7 @@
diff --git a/src/octoprint/plugins/announcements/templates/announcements_navbar.jinja2 b/src/octoprint/plugins/announcements/templates/announcements_navbar.jinja2 index 7f936f0da..ac2d7f696 100644 --- a/src/octoprint/plugins/announcements/templates/announcements_navbar.jinja2 +++ b/src/octoprint/plugins/announcements/templates/announcements_navbar.jinja2 @@ -1,3 +1,3 @@ - + diff --git a/src/octoprint/plugins/announcements/templates/announcements_settings.jinja2 b/src/octoprint/plugins/announcements/templates/announcements_settings.jinja2 index b3d42996d..cda2596ae 100644 --- a/src/octoprint/plugins/announcements/templates/announcements_settings.jinja2 +++ b/src/octoprint/plugins/announcements/templates/announcements_settings.jinja2 @@ -32,4 +32,4 @@ - + diff --git a/src/octoprint/plugins/appkeys/__init__.py b/src/octoprint/plugins/appkeys/__init__.py index 9bb3c70df..c3c7110d3 100644 --- a/src/octoprint/plugins/appkeys/__init__.py +++ b/src/octoprint/plugins/appkeys/__init__.py @@ -1,445 +1,492 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, unicode_literals +import io +import os +import threading +import time +from collections import defaultdict import flask -import threading -import os import yaml -import io -import time -from binascii import hexlify -from collections import defaultdict from flask_babel import gettext import octoprint.plugin -from octoprint.settings import valid_boolean_trues -from octoprint.server.util.flask import restricted_access, no_firstrun_access -from octoprint.server import NO_CONTENT, current_user, admin_permission -from octoprint.util import atomic_write, monotonic_time, ResettableTimer - from octoprint.access import ADMIN_GROUP from octoprint.access.permissions import Permissions +from octoprint.server import NO_CONTENT, admin_permission, current_user +from octoprint.server.util.flask import no_firstrun_access, restricted_access +from octoprint.settings import valid_boolean_trues +from octoprint.util import ResettableTimer, atomic_write, generate_api_key +CUTOFF_TIME = 10 * 60 # 10min +POLL_TIMEOUT = 5 # 5 seconds -CUTOFF_TIME = 10 * 60 # 10min -POLL_TIMEOUT = 5 # 5 seconds class AppAlreadyExists(Exception): - pass + pass + + +class PendingDecision: + def __init__(self, app_id, app_token, user_id, user_token, timeout_callback=None): + self.app_id = app_id + self.app_token = app_token + self.user_id = user_id + self.user_token = user_token + self.created = time.monotonic() + + if callable(timeout_callback): + self.poll_timeout = ResettableTimer( + POLL_TIMEOUT, timeout_callback, [user_token] + ) + self.poll_timeout.start() + + def external(self): + return { + "app_id": self.app_id, + "user_id": self.user_id, + "user_token": self.user_token, + } + + def __repr__(self): + return "PendingDecision({!r}, {!r}, {!r}, {!r}, timeout_callback=...)".format( + self.app_id, self.app_token, self.user_id, self.user_token + ) + + +class ReadyDecision: + def __init__(self, app_id, app_token, user_id): + self.app_id = app_id + self.app_token = app_token + self.user_id = user_id + + @classmethod + def for_pending(cls, pending, user_id): + return cls(pending.app_id, pending.app_token, user_id) + + def __repr__(self): + return "ReadyDecision({!r}, {!r}, {!r})".format( + self.app_id, self.app_token, self.user_id + ) + + +class ActiveKey: + def __init__(self, app_id, api_key, user_id): + self.app_id = app_id + self.api_key = api_key + self.user_id = user_id + + def external(self): + return {"app_id": self.app_id, "api_key": self.api_key, "user_id": self.user_id} + + def internal(self): + return {"app_id": self.app_id, "api_key": self.api_key} + + @classmethod + def for_internal(cls, internal, user_id): + return cls(internal["app_id"], internal["api_key"], user_id) + + def __repr__(self): + return "ActiveKey({!r}, {!r}, {!r})".format( + self.app_id, self.api_key, self.user_id + ) + + +class AppKeysPlugin( + octoprint.plugin.AssetPlugin, + octoprint.plugin.BlueprintPlugin, + octoprint.plugin.SimpleApiPlugin, + octoprint.plugin.TemplatePlugin, +): + def __init__(self): + self._pending_decisions = [] + self._pending_lock = threading.RLock() + + self._ready_decisions = [] + self._ready_lock = threading.RLock() + + self._keys = defaultdict(list) + self._keys_lock = threading.RLock() + + self._key_path = None + + def initialize(self): + self._key_path = os.path.join(self.get_plugin_data_folder(), "keys.yaml") + self._load_keys() + + # Additional permissions hook + + def get_additional_permissions(self): + return [ + { + "key": "ADMIN", + "name": "Admin access", + "description": gettext("Allows administrating all application keys"), + "roles": ["admin"], + "dangerous": True, + "default_groups": [ADMIN_GROUP], + } + ] + + ##~~ TemplatePlugin + + def get_template_configs(self): + return [ + {"type": "usersettings", "name": gettext("Application Keys")}, + {"type": "settings", "name": gettext("Application Keys")}, + ] + + ##~~ AssetPlugin + + def get_assets(self): + return { + "js": ["js/appkeys.js"], + "clientjs": ["clientjs/appkeys.js"], + "less": ["less/appkeys.less"], + "css": ["css/appkeys.css"], + } + + ##~~ BlueprintPlugin mixin + + @octoprint.plugin.BlueprintPlugin.route("/probe", methods=["GET"]) + @no_firstrun_access + def handle_probe(self): + return NO_CONTENT + + @octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"]) + @no_firstrun_access + def handle_request(self): + data = flask.request.json + if data is None: + return flask.make_response("Missing key request", 400) + + if "app" not in data: + return flask.make_response("No app name provided", 400) + + app_name = data["app"] + user_id = None + if "user" in data and data["user"]: + user_id = data["user"] + + app_token, user_token = self._add_pending_decision(app_name, user_id=user_id) + + self._plugin_manager.send_plugin_message( + self._identifier, + { + "type": "request_access", + "app_name": app_name, + "user_token": user_token, + "user_id": user_id, + }, + ) + response = flask.jsonify(app_token=app_token) + response.status_code = 201 + response.headers["Location"] = flask.url_for( + ".handle_decision_poll", app_token=app_token, _external=True + ) + return response + + @octoprint.plugin.BlueprintPlugin.route("/request/") + @no_firstrun_access + def handle_decision_poll(self, app_token): + result = self._get_pending_by_app_token(app_token) + if result: + for pending_decision in result: + pending_decision.poll_timeout.reset() + + response = flask.jsonify(message="Awaiting decision") + response.status_code = 202 + return response + + result = self._get_decision(app_token) + if result: + return flask.jsonify(api_key=result) + + return flask.abort(404) + + @octoprint.plugin.BlueprintPlugin.route("/decision/", methods=["POST"]) + @restricted_access + def handle_decision(self, user_token): + data = flask.request.json + if "decision" not in data: + return flask.make_response("No decision provided", 400) + decision = data["decision"] in valid_boolean_trues + user_id = current_user.get_name() + + result = self._set_decision(user_token, decision, user_id) + if not result: + return flask.abort(404) + + # Close access_request dialog for this request on all open OctoPrint connections + self._plugin_manager.send_plugin_message( + self._identifier, {"type": "end_request", "user_token": user_token} + ) + + return NO_CONTENT + + def is_blueprint_protected(self): + return False # No API key required to request API access + + ##~~ SimpleApiPlugin mixin + + def get_api_commands(self): + return {"generate": ["app"], "revoke": ["key"]} + + def on_api_get(self, request): + user_id = current_user.get_name() + if not user_id: + return flask.abort(403) + + if ( + request.values.get("all") in valid_boolean_trues + and Permissions.PLUGIN_APPKEYS_ADMIN.can() + ): + keys = self._all_api_keys() + else: + keys = self._api_keys_for_user(user_id) + + return flask.jsonify( + keys=list(map(lambda x: x.external(), keys)), + pending={ + x.user_token: x.external() for x in self._get_pending_by_user_id(user_id) + }, + ) + + def on_api_command(self, command, data): + user_id = current_user.get_name() + if not user_id: + return flask.abort(403) + + if command == "revoke": + api_key = data.get("key") + if not api_key: + return flask.abort(400) + + if not admin_permission.can(): + user_for_key = self._user_for_api_key(api_key) + if user_for_key is None or user_for_key.user_id != user_id: + return flask.abort(403) + + self._delete_api_key(api_key) + + elif command == "generate": + # manual generateKey + app_name = data.get("app") + if not app_name: + return flask.abort(400) + + selected_user_id = data.get("user", user_id) + if selected_user_id != user_id and not Permissions.PLUGIN_APPKEYS_ADMIN.can(): + return flask.abort(403) + + key = self._add_api_key(selected_user_id, app_name.strip()) + return flask.jsonify(user_id=selected_user_id, app_id=app_name, api_key=key) + + return NO_CONTENT + + ##~~ key validator hook + + def validate_api_key(self, api_key, *args, **kwargs): + return self._user_for_api_key(api_key) + + ##~~ Helpers + + def _add_pending_decision(self, app_name, user_id=None): + app_token = self._generate_key() + user_token = self._generate_key() + + with self._pending_lock: + self._remove_stale_pending() + self._pending_decisions.append( + PendingDecision( + app_name, + app_token, + user_id, + user_token, + timeout_callback=self._expire_pending, + ) + ) + + return app_token, user_token + + def _get_pending_by_app_token(self, app_token): + result = [] + with self._pending_lock: + self._remove_stale_pending() + for data in self._pending_decisions: + if data.app_token == app_token: + result.append(data) + return result + + def _get_pending_by_user_id(self, user_id): + result = [] + with self._pending_lock: + self._remove_stale_pending() + for data in self._pending_decisions: + if data.user_id == user_id or data.user_id is None: + result.append(data) + return result + + def _expire_pending(self, user_token): + with self._pending_lock: + len_before = len(self._pending_decisions) + self._pending_decisions = list( + filter(lambda x: x.user_token != user_token, self._pending_decisions) + ) + len_after = len(self._pending_decisions) + + if len_after < len_before: + self._plugin_manager.send_plugin_message( + self._identifier, {"type": "end_request", "user_token": user_token} + ) + + def _remove_stale_pending(self): + with self._pending_lock: + cutoff = time.monotonic() - CUTOFF_TIME + len_before = len(self._pending_decisions) + self._pending_decisions = list( + filter(lambda x: x.created >= cutoff, self._pending_decisions) + ) + len_after = len(self._pending_decisions) + if len_after < len_before: + self._logger.info( + "Deleted {} stale pending authorization requests".format( + len_before - len_after + ) + ) + + def _set_decision(self, user_token, decision, user_id): + with self._pending_lock: + self._remove_stale_pending() + for data in self._pending_decisions: + if data.user_token == user_token and ( + data.user_id == user_id or data.user_id is None + ): + pending = data + break + else: + return False # not found + + if decision: + with self._ready_lock: + self._ready_decisions.append(ReadyDecision.for_pending(pending, user_id)) + + with self._pending_lock: + self._pending_decisions = list( + filter(lambda x: x.user_token != user_token, self._pending_decisions) + ) + + return True + + def _get_decision(self, app_token): + self._remove_stale_pending() + + with self._ready_lock: + for data in self._ready_decisions: + if data.app_token == app_token: + decision = data + break + else: + return False # not found + + api_key = self._add_api_key(decision.user_id, decision.app_id) + + with self._ready_lock: + self._ready_decisions = list( + filter(lambda x: x.app_token != app_token, self._ready_decisions) + ) + + return api_key + + def _add_api_key(self, user_id, app_name): + with self._keys_lock: + for key in self._keys[user_id]: + if key.app_id.lower() == app_name.lower(): + return key.api_key + + key = ActiveKey(app_name, self._generate_key(), user_id) + self._keys[user_id].append(key) + self._save_keys() + return key.api_key + + def _delete_api_key(self, api_key): + with self._keys_lock: + for user_id, data in self._keys.items(): + self._keys[user_id] = list(filter(lambda x: x.api_key != api_key, data)) + self._save_keys() + + def _user_for_api_key(self, api_key): + with self._keys_lock: + for user_id, data in self._keys.items(): + if any(filter(lambda x: x.api_key == api_key, data)): + return self._user_manager.find_user(userid=user_id) + return None + + def _api_keys_for_user(self, user_id): + with self._keys_lock: + return self._keys[user_id] + + def _all_api_keys(self): + with self._keys_lock: + result = [] + for keys in self._keys.values(): + result += keys + return result + + def _generate_key(self): + return generate_api_key() + + def _load_keys(self): + with self._keys_lock: + if not os.path.exists(self._key_path): + return + + try: + with io.open( + self._key_path, "rt", encoding="utf-8", errors="strict" + ) as f: + persisted = yaml.safe_load(f) + except Exception: + self._logger.exception( + "Could not load application keys from {}".format(self._key_path) + ) + return + + if not isinstance(persisted, dict): + return + + keys = defaultdict(list) + for user_id, persisted_keys in persisted.items(): + keys[user_id] = [ + ActiveKey.for_internal(x, user_id) for x in persisted_keys + ] + self._keys = keys + + def _save_keys(self): + with self._keys_lock: + to_persist = {} + for user_id, keys in self._keys.items(): + to_persist[user_id] = [x.internal() for x in keys] + + try: + with atomic_write(self._key_path, mode="wt") as f: + yaml.safe_dump(to_persist, f, allow_unicode=True) + except Exception: + self._logger.exception( + "Could not write application keys to {}".format(self._key_path) + ) -class PendingDecision(object): - def __init__(self, app_id, app_token, user_id, user_token, timeout_callback=None): - self.app_id = app_id - self.app_token = app_token - self.user_id = user_id - self.user_token = user_token - self.created = monotonic_time() - - if callable(timeout_callback): - self.poll_timeout = ResettableTimer(POLL_TIMEOUT, timeout_callback, [user_token]) - self.poll_timeout.start() - - def external(self): - return dict(app_id=self.app_id, - user_id=self.user_id, - user_token=self.user_token) - - def __repr__(self): - return u"PendingDecision({!r}, {!r}, {!r}, {!r}, timeout_callback=...)".format(self.app_id, - self.app_token, - self.user_id, - self.user_token) - - -class ReadyDecision(object): - def __init__(self, app_id, app_token, user_id): - self.app_id = app_id - self.app_token = app_token - self.user_id = user_id - - @classmethod - def for_pending(cls, pending, user_id): - return cls(pending.app_id, pending.app_token, user_id) - - def __repr__(self): - return u"ReadyDecision({!r}, {!r}, {!r})".format(self.app_id, - self.app_token, - self.user_id) - - -class ActiveKey(object): - def __init__(self, app_id, api_key, user_id): - self.app_id = app_id - self.api_key = api_key - self.user_id = user_id - - def external(self): - return dict(app_id=self.app_id, - api_key=self.api_key, - user_id=self.user_id) - - def internal(self): - return dict(app_id=self.app_id, - api_key=self.api_key) - - @classmethod - def for_internal(cls, internal, user_id): - return cls(internal["app_id"], internal["api_key"], user_id) - - def __repr__(self): - return u"ActiveKey({!r}, {!r}, {!r})".format(self.app_id, - self.api_key, - self.user_id) - - -class AppKeysPlugin(octoprint.plugin.AssetPlugin, - octoprint.plugin.BlueprintPlugin, - octoprint.plugin.SimpleApiPlugin, - octoprint.plugin.TemplatePlugin): - - def __init__(self): - self._pending_decisions = [] - self._pending_lock = threading.RLock() - - self._ready_decisions = [] - self._ready_lock = threading.RLock() - - self._keys = defaultdict(list) - self._keys_lock = threading.RLock() - - self._key_path = None - - def initialize(self): - self._key_path = os.path.join(self.get_plugin_data_folder(), "keys.yaml") - self._load_keys() - - # Additional permissions hook - - def get_additional_permissions(self): - return [ - dict(key="ADMIN", - name="Admin access", - description=gettext("Allows administrating all application keys"), - roles=["admin"], - dangerous=True, - default_groups=[ADMIN_GROUP]) - ] - - ##~~ TemplatePlugin - - def get_template_configs(self): - return [dict(type="usersettings", name=gettext("Application Keys")), - dict(type="settings", name=gettext("Application Keys"))] - - ##~~ AssetPlugin - - def get_assets(self): - return dict(js=["js/appkeys.js"], - clientjs=["clientjs/appkeys.js"], - less=["less/appkeys.less"], - css=["css/appkeys.css"]) - - ##~~ BlueprintPlugin mixin - - @octoprint.plugin.BlueprintPlugin.route("/probe", methods=["GET"]) - @no_firstrun_access - def handle_probe(self): - return NO_CONTENT - - @octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"]) - @no_firstrun_access - def handle_request(self): - data = flask.request.json - if data is None: - return flask.make_response("Missing key request", 400) - - if not "app" in data: - return flask.make_response("No app name provided", 400) - - app_name = data["app"] - user_id = None - if "user" in data and data["user"]: - user_id = data["user"] - - app_token, user_token = self._add_pending_decision(app_name, user_id=user_id) - - self._plugin_manager.send_plugin_message(self._identifier, dict(type="request_access", - app_name=app_name, - user_token=user_token, - user_id=user_id)) - response = flask.jsonify(app_token=app_token) - response.status_code = 201 - response.headers["Location"] = flask.url_for(".handle_decision_poll", app_token=app_token, _external=True) - return response - - @octoprint.plugin.BlueprintPlugin.route("/request/") - @no_firstrun_access - def handle_decision_poll(self, app_token): - result = self._get_pending_by_app_token(app_token) - if result: - for pending_decision in result: - pending_decision.poll_timeout.reset() - - response = flask.jsonify(message="Awaiting decision") - response.status_code = 202 - return response - - result = self._get_decision(app_token) - if result: - return flask.jsonify(api_key=result) - - return flask.abort(404) - - @octoprint.plugin.BlueprintPlugin.route("/decision/", methods=["POST"]) - @restricted_access - def handle_decision(self, user_token): - data = flask.request.json - if not "decision" in data: - return flask.make_response("No decision provided", 400) - decision = data["decision"] in valid_boolean_trues - user_id = current_user.get_name() - - result = self._set_decision(user_token, decision, user_id) - if not result: - return flask.abort(404) - - # Close access_request dialog for this request on all open OctoPrint connections - self._plugin_manager.send_plugin_message(self._identifier, dict( - type="end_request", - user_token=user_token - )) - - return NO_CONTENT - - def is_blueprint_protected(self): - return False # No API key required to request API access - - ##~~ SimpleApiPlugin mixin - - def get_api_commands(self): - return dict(generate=["app"], - revoke=["key"]) - - def on_api_get(self, request): - user_id = current_user.get_name() - if not user_id: - return flask.abort(403) - - if request.values.get("all") in valid_boolean_trues and Permissions.PLUGIN_APPKEYS_ADMIN.can(): - keys = self._all_api_keys() - else: - keys = self._api_keys_for_user(user_id) - - return flask.jsonify(keys=list(map(lambda x: x.external(), keys)), - pending=dict((x.user_token, x.external()) for x in self._get_pending_by_user_id(user_id))) - - def on_api_command(self, command, data): - user_id = current_user.get_name() - if not user_id: - return flask.abort(403) - - if command == "revoke": - api_key = data.get("key") - if not api_key: - return flask.abort(400) - - if not admin_permission.can(): - user_for_key = self._user_for_api_key(api_key) - if user_for_key is None or user_for_key.user_id != user_id: - return flask.abort(403) - - self._delete_api_key(api_key) - - elif command == "generate": - # manual generateKey - app_name = data.get("app") - if not app_name: - return flask.abort(400) - - self._add_api_key(user_id, app_name.strip()) - - return NO_CONTENT - - ##~~ key validator hook - - def validate_api_key(self, api_key, *args, **kwargs): - return self._user_for_api_key(api_key) - - ##~~ Helpers - - def _add_pending_decision(self, app_name, user_id=None): - app_token = self._generate_key() - user_token = self._generate_key() - - with self._pending_lock: - self._remove_stale_pending() - self._pending_decisions.append(PendingDecision(app_name, app_token, user_id, user_token, - timeout_callback=self._expire_pending)) - - return app_token, user_token - - def _get_pending_by_app_token(self, app_token): - result = [] - with self._pending_lock: - self._remove_stale_pending() - for data in self._pending_decisions: - if data.app_token == app_token: - result.append(data) - return result - - def _get_pending_by_user_id(self, user_id): - result = [] - with self._pending_lock: - self._remove_stale_pending() - for data in self._pending_decisions: - if data.user_id == user_id or data.user_id is None: - result.append(data) - return result - - def _expire_pending(self, user_token): - with self._pending_lock: - len_before = len(self._pending_decisions) - self._pending_decisions = list(filter(lambda x: x.user_token != user_token, - self._pending_decisions)) - len_after = len(self._pending_decisions) - - if len_after < len_before: - self._plugin_manager.send_plugin_message(self._identifier, dict( - type="end_request", - user_token=user_token - )) - - def _remove_stale_pending(self): - with self._pending_lock: - cutoff = monotonic_time() - CUTOFF_TIME - len_before = len(self._pending_decisions) - self._pending_decisions = list(filter(lambda x: x.created >= cutoff, - self._pending_decisions)) - len_after = len(self._pending_decisions) - if len_after < len_before: - self._logger.info("Deleted {} stale pending authorization requests".format(len_before - len_after)) - - def _set_decision(self, user_token, decision, user_id): - with self._pending_lock: - self._remove_stale_pending() - for data in self._pending_decisions: - if data.user_token == user_token and (data.user_id == user_id or data.user_id is None): - pending = data - break - else: - return False # not found - - if decision: - with self._ready_lock: - self._ready_decisions.append(ReadyDecision.for_pending(pending, user_id)) - - with self._pending_lock: - self._pending_decisions = list(filter(lambda x: x.user_token != user_token, - self._pending_decisions)) - - return True - - def _get_decision(self, app_token): - self._remove_stale_pending() - - with self._ready_lock: - for data in self._ready_decisions: - if data.app_token == app_token: - decision = data - break - else: - return False # not found - - api_key = self._add_api_key(decision.user_id, decision.app_id) - - with self._ready_lock: - self._ready_decisions = list(filter(lambda x: x.app_token != app_token, - self._ready_decisions)) - - return api_key - - def _add_api_key(self, user_id, app_name): - with self._keys_lock: - for key in self._keys[user_id]: - if key.app_id.lower() == app_name.lower(): - return key.api_key - - key = ActiveKey(app_name, self._generate_key(), user_id) - self._keys[user_id].append(key) - self._save_keys() - return key.api_key - - def _delete_api_key(self, api_key): - with self._keys_lock: - for user_id, data in self._keys.items(): - self._keys[user_id] = list(filter(lambda x: x.api_key != api_key, data)) - self._save_keys() - - def _user_for_api_key(self, api_key): - with self._keys_lock: - for user_id, data in self._keys.items(): - if any(filter(lambda x: x.api_key == api_key, data)): - if self._user_manager.enabled: - return self._user_manager.findUser(userid=user_id) - elif user_id == "_admin" or user_id == "dummy": - # dummy = backwards compatible - return self._user_manager.anonymous_user_factory() - return None - - def _api_keys_for_user(self, user_id): - with self._keys_lock: - return self._keys[user_id] - - def _all_api_keys(self): - with self._keys_lock: - result = [] - for user_id, keys in self._keys.items(): - result += keys - return result - - def _generate_key(self): - return hexlify(os.urandom(16)) - - def _load_keys(self): - with self._keys_lock: - if not os.path.exists(self._key_path): - return - - try: - with io.open(self._key_path, 'rt', encoding="utf-8", errors="strict") as f: - persisted = yaml.safe_load(f) - except Exception: - self._logger.exception("Could not load application keys from {}".format(self._key_path)) - return - - if not isinstance(persisted, dict): - return - - keys = defaultdict(list) - for user_id, persisted_keys in persisted.items(): - keys[user_id] = [ActiveKey.for_internal(x, user_id) for x in persisted_keys] - self._keys = keys - - def _save_keys(self): - with self._keys_lock: - to_persist = dict() - for user_id, keys in self._keys.items(): - to_persist[user_id] = [x.internal() for x in keys] - - try: - with atomic_write(self._key_path, mode='wt') as f: - yaml.safe_dump(to_persist, f, allow_unicode=True) - except Exception: - self._logger.exception("Could not write application keys to {}".format(self._key_path)) - __plugin_name__ = "Application Keys Plugin" -__plugin_description__ = "Implements a workflow for third party clients to obtain API keys" +__plugin_description__ = ( + "Implements a workflow for third party clients to obtain API keys" +) __plugin_author__ = "Gina Häußge, Aldo Hoeben" -__plugin_disabling_discouraged__ = gettext("Without this plugin third party clients will no longer be able to " - "obtain an API key without you manually copy-pasting it.") +__plugin_disabling_discouraged__ = gettext( + "Without this plugin third party clients will no longer be able to " + "obtain an API key without you manually copy-pasting it." +) +__plugin_license__ = "AGPLv3" +__plugin_pythoncompat__ = ">=2.7,<4" __plugin_implementation__ = AppKeysPlugin() __plugin_hooks__ = { - "octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key, - "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions + "octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key, + "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions, } diff --git a/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js b/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js index 9b29428aa..b58adfca4 100644 --- a/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js +++ b/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js @@ -4,55 +4,80 @@ } else { factory(global.OctoPrintClient); } -})(this, function(OctoPrintClient) { - var OctoPrintAppKeysClient = function(base) { +})(this, function (OctoPrintClient) { + var OctoPrintAppKeysClient = function (base) { this.base = base; }; - OctoPrintAppKeysClient.prototype.getKeys = function(opts) { + OctoPrintAppKeysClient.prototype.getKeys = function (opts) { return this.base.simpleApiGet("appkeys", opts); }; - OctoPrintAppKeysClient.prototype.getAllKeys = function(opts) { - return this.base.get(OctoPrintClient.prototype.getSimpleApiUrl("appkeys") + "?all=true", opts); + OctoPrintAppKeysClient.prototype.getAllKeys = function (opts) { + return this.base.get( + OctoPrintClient.prototype.getSimpleApiUrl("appkeys") + "?all=true", + opts + ); }; - OctoPrintAppKeysClient.prototype.generateKey = function(app, opts) { - return this.base.simpleApiCommand("appkeys", "generate", {"app": app}, opts); + OctoPrintAppKeysClient.prototype.generateKey = function (app, opts) { + return this.base.simpleApiCommand("appkeys", "generate", {app: app}, opts); }; - OctoPrintAppKeysClient.prototype.revokeKey = function(key, opts) { - return this.base.simpleApiCommand("appkeys", "revoke", {"key": key}, opts); + OctoPrintAppKeysClient.prototype.generateKeyForUser = function (user, app, opts) { + return this.base.simpleApiCommand( + "appkeys", + "generate", + {app: app, user: user}, + opts + ); }; - OctoPrintAppKeysClient.prototype.decide = function(token, decision, opts) { - return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "decision/" + token, {decision: !!decision}, opts); + OctoPrintAppKeysClient.prototype.revokeKey = function (key, opts) { + return this.base.simpleApiCommand("appkeys", "revoke", {key: key}, opts); }; - OctoPrintAppKeysClient.prototype.probe = function(opts) { + OctoPrintAppKeysClient.prototype.decide = function (token, decision, opts) { + return this.base.postJson( + this.base.getBlueprintUrl("appkeys") + "decision/" + token, + {decision: !!decision}, + opts + ); + }; + + OctoPrintAppKeysClient.prototype.probe = function (opts) { return this.base.get(this.base.getBlueprintUrl("appkeys") + "probe", opts); }; - OctoPrintAppKeysClient.prototype.request = function(app, opts) { + OctoPrintAppKeysClient.prototype.request = function (app, opts) { return this.requestForUser(app, undefined, opts); }; - OctoPrintAppKeysClient.prototype.requestForUser = function(app, user, opts) { - return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "request", {app: app, user: user}, opts); + OctoPrintAppKeysClient.prototype.requestForUser = function (app, user, opts) { + return this.base.postJson( + this.base.getBlueprintUrl("appkeys") + "request", + {app: app, user: user}, + opts + ); }; - OctoPrintAppKeysClient.prototype.checkDecision = function(token, opts) { - return this.base.get(this.base.getBlueprintUrl("appkeys") + "request/" + token, opts); + OctoPrintAppKeysClient.prototype.checkDecision = function (token, opts) { + return this.base.get( + this.base.getBlueprintUrl("appkeys") + "request/" + token, + opts + ); }; - OctoPrintAppKeysClient.prototype.authenticate = function(app, user) { + OctoPrintAppKeysClient.prototype.authenticate = function (app, user) { var deferred = $.Deferred(); var client = this; - client.probe() - .done(function() { - client.requestForUser(app, user) - .done(function(response) { + client + .probe() + .done(function () { + client + .requestForUser(app, user) + .done(function (response) { var token = response.app_token; if (!token) { // no token received, something went wrong @@ -61,9 +86,10 @@ } var interval = 1000; - var poll = function() { - client.checkDecision(token) - .done(function(response) { + var poll = function () { + client + .checkDecision(token) + .done(function (response) { if (response.api_key) { // got a decision, resolve the promise deferred.resolve(response.api_key); @@ -73,19 +99,19 @@ window.setTimeout(poll, interval); } }) - .fail(function() { + .fail(function () { // something went wrong deferred.reject(); }); }; window.setTimeout(poll, interval); }) - .fail(function() { + .fail(function () { // something went wrong deferred.reject(); }); }) - .fail(function() { + .fail(function () { // workflow unsupported deferred.reject(); }); diff --git a/src/octoprint/plugins/appkeys/static/css/appkeys.css b/src/octoprint/plugins/appkeys/static/css/appkeys.css index 6240d21d7..4e0828030 100644 --- a/src/octoprint/plugins/appkeys/static/css/appkeys.css +++ b/src/octoprint/plugins/appkeys/static/css/appkeys.css @@ -1 +1 @@ -#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions{width:75px;text-align:center}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions a,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions a{color:#000}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_user,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_user{width:100px}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox{text-align:center;width:10px}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox input[type=checkbox],#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox input[type=checkbox]{margin-top:0} \ No newline at end of file +#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions{width:75px;text-align:center}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions a,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions a{color:#000}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_user,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_user{width:100px}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox{text-align:center;width:10px}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox input[type=checkbox],#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox input[type=checkbox]{margin-top:0}#plugin_appkeys_keygenerated .control-text{display:inline-block} \ No newline at end of file diff --git a/src/octoprint/plugins/appkeys/static/js/appkeys.js b/src/octoprint/plugins/appkeys/static/js/appkeys.js index bdd72e97b..adfa8c3a8 100644 --- a/src/octoprint/plugins/appkeys/static/js/appkeys.js +++ b/src/octoprint/plugins/appkeys/static/js/appkeys.js @@ -1,20 +1,63 @@ -$(function() { +$(function () { + function AppKeysDialogViewModel(parameters) { + var self = this; + + self.dialog = undefined; + + self.onStartup = function () { + self.dialog = $("#plugin_appkeys_keygenerated"); + }; + + self.showDialog = function (title, data) { + if (self.dialog === undefined) return; + + var qrcode = { + text: data.api_key, + size: 180, + fill: "#000", + background: null, + label: "", + fontname: "sans", + fontcolor: "#000", + radius: 0, + ecLevel: "L" + }; + + self.dialog.find("#plugin_appkeys_keygenerated_title").text(title); + self.dialog.find("#plugin_appkeys_keygenerated_user").text(data.user_id); + self.dialog.find("#plugin_appkeys_keygenerated_app").text(data.app_id); + self.dialog.find("#plugin_appkeys_keygenerated_key_text").text(data.api_key); + self.dialog + .find("#plugin_appkeys_keygenerated_key_copy") + .off() + .click(function () { + copyToClipboard(data.api_key); + }); + self.dialog + .find("#plugin_appkeys_keygenerated_key_qrcode") + .empty() + .qrcode(qrcode); + + self.dialog.modal("show"); + }; + } + function UserAppKeysViewModel(parameters) { var self = this; - self.loginState = parameters[0]; + self.dialog = parameters[0]; + self.loginState = parameters[1]; self.keys = new ItemListHelper( "plugin.appkeys.userkeys", { - "app": function (a, b) { + app: function (a, b) { // sorts ascending if (a["app_id"].toLowerCase() < b["app_id"].toLowerCase()) return -1; if (a["app_id"].toLowerCase() > b["app_id"].toLowerCase()) return 1; return 0; } }, - { - }, + {}, "app", [], [], @@ -25,51 +68,62 @@ $(function() { self.editorApp = ko.observable(); - self.requestData = function() { - OctoPrint.plugins.appkeys.getKeys() - .done(self.fromResponse); + self.requestData = function () { + OctoPrint.plugins.appkeys.getKeys().done(self.fromResponse); }; - self.fromResponse = function(response) { + self.fromResponse = function (response) { self.keys.updateItems(response.keys); self.pending = response.pending; - _.each(self.pending, function(data, token) { + _.each(self.pending, function (data, token) { self.openRequests[token] = self.promptForAccess(data.app_id, token); - }) + }); }; - self.generateKey = function() { - return OctoPrint.plugins.appkeys.generateKey(self.editorApp()) + self.generateKey = function () { + return OctoPrint.plugins.appkeys + .generateKey(self.editorApp()) .done(self.requestData) - .done(function() { + .done(function () { self.editorApp(""); }); }; - self.revokeKey = function(key) { - var perform = function() { - OctoPrint.plugins.appkeys.revokeKey(key) - .done(self.requestData); + self.revokeKey = function (key) { + var perform = function () { + OctoPrint.plugins.appkeys.revokeKey(key).done(self.requestData); }; - showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: key}), - perform); + showConfirmationDialog( + _.sprintf( + gettext('You are about to revoke the application key "%(key)s".'), + {key: _.escape(key)} + ), + perform + ); }; - self.allowApp = function(token) { - return OctoPrint.plugins.appkeys.decide(token, true) - .done(self.requestData); + self.allowApp = function (token) { + return OctoPrint.plugins.appkeys.decide(token, true).done(self.requestData); }; - self.denyApp = function(token) { - return OctoPrint.plugins.appkeys.decide(token, false) - .done(self.requestData); + self.denyApp = function (token) { + return OctoPrint.plugins.appkeys.decide(token, false).done(self.requestData); }; - self.promptForAccess = function(app, token) { - var message = gettext("\"%(app)s\" has requested access to control OctoPrint through the API."); - message = _.sprintf(message, {app: app}); - message = "

" + message + "

" + gettext("Do you want to allow access to this application with your user account?") + "

"; + self.promptForAccess = function (app, token) { + var message = gettext( + '"%(app)s" has requested access to control OctoPrint through the API.' + ); + message = _.sprintf(message, {app: _.escape(app)}); + message = + "

" + + message + + "

" + + gettext( + "Do you want to allow access to this application with your user account?" + ) + + "

"; return new PNotify({ title: gettext("Access Request"), text: message, @@ -77,19 +131,22 @@ $(function() { icon: "fa fa-key", confirm: { confirm: true, - buttons: [{ - text: gettext("Allow"), - click: function(notice) { - self.allowApp(token); - notice.remove(); + buttons: [ + { + text: gettext("Allow"), + click: function (notice) { + self.allowApp(token); + notice.remove(); + } + }, + { + text: gettext("Deny"), + click: function (notice) { + self.denyApp(token); + notice.remove(); + } } - }, { - text: gettext("Deny"), - click: function(notice) { - self.denyApp(token); - notice.remove(); - } - }] + ] }, buttons: { sticker: false, @@ -98,15 +155,15 @@ $(function() { }); }; - self.onUserSettingsShown = function() { + self.onUserSettingsShown = function () { self.requestData(); }; - self.onUserLoggedIn = function() { + self.onUserLoggedIn = function () { self.requestData(); }; - self.onDataUpdaterPluginMessage = function(plugin, data) { + self.onDataUpdaterPluginMessage = function (plugin, data) { if (plugin !== "appkeys") { return; } @@ -127,7 +184,6 @@ $(function() { } self.openRequests[token] = self.promptForAccess(app, token); - } else if (data.type === "end_request") { token = data.user_token; @@ -136,7 +192,7 @@ $(function() { if (self.openRequests[token].state !== "closed") { self.openRequests[token].remove(); } - delete self.openRequests[token] + delete self.openRequests[token]; } } }; @@ -144,12 +200,14 @@ $(function() { function AllAppKeysViewModel(parameters) { var self = this; - self.loginState = parameters[0]; + self.dialog = parameters[0]; + self.loginState = parameters[1]; + self.access = parameters[2]; self.keys = new ItemListHelper( "plugin.appkeys.allkeys", { - "user_app": function (a, b) { + user_app: function (a, b) { // sorts ascending, first by user, then by app if (a["user_id"] > b["user_id"]) return 1; if (a["user_id"] < b["user_id"]) return -1; @@ -160,8 +218,7 @@ $(function() { return 0; } }, - { - }, + {}, "user_app", [], [], @@ -170,27 +227,33 @@ $(function() { self.users = ko.observableArray([]); self.apps = ko.observableArray([]); + self.editorApp = ko.observable(); + self.editorUser = ko.observable(); + self.markedForDeletion = ko.observableArray([]); - self.onSettingsShown = function() { + self.onSettingsShown = function () { self.requestData(); + self.editorUser(self.loginState.username()); + self.editorApp(""); }; - self.onUserLoggedIn = function() { + self.onUserLoggedIn = function () { self.requestData(); + self.editorUser(self.loginState.username()); + self.editorApp(""); }; - self.requestData = function() { - OctoPrint.plugins.appkeys.getAllKeys() - .done(self.fromResponse); + self.requestData = function () { + OctoPrint.plugins.appkeys.getAllKeys().done(self.fromResponse); }; - self.fromResponse = function(response) { + self.fromResponse = function (response) { self.keys.updateItems(response.keys); var users = []; var apps = []; - _.each(response.keys, function(key) { + _.each(response.keys, function (key) { users.push(key.user_id); apps.push(key.app_id.toLowerCase()); }); @@ -204,65 +267,116 @@ $(function() { self.apps(apps); }; - self.revokeKey = function(key) { - var perform = function() { - OctoPrint.plugins.appkeys.revokeKey(key) - .done(self.requestData); + self.generateKey = function () { + return OctoPrint.plugins.appkeys + .generateKeyForUser(self.editorUser(), self.editorApp()) + .done(self.requestData) + .done(function () { + self.editorUser(self.loginState.username()); + self.editorApp(""); + }) + .done(function (data) { + self.dialog.showDialog(gettext("New key generated!"), data); + }); + }; + + self.revokeKey = function (key) { + var perform = function () { + OctoPrint.plugins.appkeys.revokeKey(key).done(self.requestData); }; - showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: key}), - perform); + showConfirmationDialog( + _.sprintf( + gettext('You are about to revoke the application key "%(key)s".'), + {key: _.escape(key)} + ), + perform + ); }; - self.revokeMarked = function() { - var perform = function() { - self._bulkRevoke(self.markedForDeletion()) - .done(function() { - self.markedForDeletion.removeAll(); - }); + self.revokeMarked = function () { + var perform = function () { + self._bulkRevoke(self.markedForDeletion()).done(function () { + self.markedForDeletion.removeAll(); + }); }; - showConfirmationDialog(_.sprintf(gettext("You are about to revoke %(count)d application keys."), {count: self.markedForDeletion().length}), - perform); + showConfirmationDialog( + _.sprintf( + gettext("You are about to revoke %(count)d application keys."), + {count: self.markedForDeletion().length} + ), + perform + ); }; - self.markAllOnPageForDeletion = function() { - self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(self.keys.paginatedItems(), "api_key")))); + self.markAllOnPageForDeletion = function () { + self.markedForDeletion( + _.uniq( + self + .markedForDeletion() + .concat(_.map(self.keys.paginatedItems(), "api_key")) + ) + ); }; - self.markAllForDeletion = function() { + self.markAllForDeletion = function () { self.markedForDeletion(_.uniq(_.map(self.keys.allItems, "api_key"))); }; - self.markAllByUserForDeletion = function(user) { - self.markAllByFilterForDeletion(function(e) { return (e.user_id === user); }); + self.markAllByUserForDeletion = function (user) { + self.markAllByFilterForDeletion(function (e) { + return e.user_id === user; + }); }; - self.markAllByAppForDeletion = function(app) { - self.markAllByFilterForDeletion(function(e) { return (e.app_id.toLowerCase() === app); }) + self.markAllByAppForDeletion = function (app) { + self.markAllByFilterForDeletion(function (e) { + return e.app_id.toLowerCase() === app; + }); }; - self.markAllByFilterForDeletion = function(filter) { - self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(_.filter(self.keys.allItems, filter), "api_key")))); + self.markAllByFilterForDeletion = function (filter) { + self.markedForDeletion( + _.uniq( + self + .markedForDeletion() + .concat(_.map(_.filter(self.keys.allItems, filter), "api_key")) + ) + ); }; - self.clearMarked = function() { + self.clearMarked = function () { self.markedForDeletion.removeAll(); }; - self._bulkRevoke = function(keys) { + self._bulkRevoke = function (keys) { var title, message, handler; title = gettext("Revoking application keys"); - message = _.sprintf(gettext("Revoking %(count)d application keys..."), {count: keys.length}); - handler = function(key) { - return OctoPrint.plugins.appkeys.revokeKey(key) - .done(function() { - deferred.notify(_.sprintf(gettext("Revoked %(key)s..."), {key: key}), true); + message = _.sprintf(gettext("Revoking %(count)d application keys..."), { + count: keys.length + }); + handler = function (key) { + return OctoPrint.plugins.appkeys + .revokeKey(key) + .done(function () { + deferred.notify( + _.sprintf(gettext("Revoked %(key)s..."), { + key: _.escape(key) + }), + true + ); }) - .fail(function(jqXHR) { - var short = _.sprintf(gettext("Revocation of %(key)s failed, continuing..."), {key: key}); - var long = _.sprintf(gettext("Deletion of %(key)s failed: %(error)s"), {key: key, error: jqXHR.responseText}); + .fail(function (jqXHR) { + var short = _.sprintf( + gettext("Revocation of %(key)s failed, continuing..."), + {key: _.escape(key)} + ); + var long = _.sprintf( + gettext("Deletion of %(key)s failed: %(error)s"), + {key: _.escape(key), error: _.escape(jqXHR.responseText)} + ); deferred.notify(short, long, false); }); }; @@ -280,29 +394,30 @@ $(function() { showProgressModal(options, promise); var requests = []; - _.each(keys, function(key) { + _.each(keys, function (key) { var request = handler(key); - requests.push(request) + requests.push(request); + }); + $.when.apply($, _.map(requests, wrapPromiseWithAlways)).done(function () { + deferred.resolve(); + self.requestData(); }); - $.when.apply($, _.map(requests, wrapPromiseWithAlways)) - .done(function() { - deferred.resolve(); - self.requestData(); - }); return promise; }; } + OCTOPRINT_VIEWMODELS.push([AppKeysDialogViewModel, [], []]); + OCTOPRINT_VIEWMODELS.push([ UserAppKeysViewModel, - ["loginStateViewModel"], + ["appKeysDialogViewModel", "loginStateViewModel"], ["#usersettings_plugin_appkeys"] ]); OCTOPRINT_VIEWMODELS.push([ AllAppKeysViewModel, - ["loginStateViewModel"], + ["appKeysDialogViewModel", "loginStateViewModel", "accessViewModel"], ["#settings_plugin_appkeys"] - ]) + ]); }); diff --git a/src/octoprint/plugins/appkeys/static/less/appkeys.less b/src/octoprint/plugins/appkeys/static/less/appkeys.less index 0e7d3f1c8..38f95fdaa 100644 --- a/src/octoprint/plugins/appkeys/static/less/appkeys.less +++ b/src/octoprint/plugins/appkeys/static/less/appkeys.less @@ -22,3 +22,9 @@ } } } + +#plugin_appkeys_keygenerated { + .control-text { + display: inline-block; + } +} diff --git a/src/octoprint/plugins/appkeys/templates/appkeys.jinja2 b/src/octoprint/plugins/appkeys/templates/appkeys.jinja2 new file mode 100644 index 000000000..92ab98920 --- /dev/null +++ b/src/octoprint/plugins/appkeys/templates/appkeys.jinja2 @@ -0,0 +1,38 @@ + diff --git a/src/octoprint/plugins/appkeys/templates/appkeys_settings.jinja2 b/src/octoprint/plugins/appkeys/templates/appkeys_settings.jinja2 index 6da481c60..d5d2b360a 100644 --- a/src/octoprint/plugins/appkeys/templates/appkeys_settings.jinja2 +++ b/src/octoprint/plugins/appkeys/templates/appkeys_settings.jinja2 @@ -1,10 +1,12 @@ +{{ _('Registered application keys') }} +

{{ _('There are no application keys registered yet.') }}

- +
+{{ _('Manually generate an application key') }} + +
+
+ +
+ +
+
+
+ +
+ +
+
+
+
+ +
+
+
diff --git a/src/octoprint/plugins/appkeys/templates/appkeys_usersettings.jinja2 b/src/octoprint/plugins/appkeys/templates/appkeys_usersettings.jinja2 index 1bfeaf07f..5c0930efb 100644 --- a/src/octoprint/plugins/appkeys/templates/appkeys_usersettings.jinja2 +++ b/src/octoprint/plugins/appkeys/templates/appkeys_usersettings.jinja2 @@ -13,8 +13,8 @@ -
{{ _('API Key') }}: - +
{{ _('API Key') }}: + @@ -33,7 +33,7 @@ {{ _('Manually generate an application key') }} -
+
diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index c4340c11d..e59bfa2ac 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -1,976 +1,1414 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" -import octoprint.plugin +from os import scandir -from octoprint.settings import default_settings -from octoprint.plugin.core import FolderOrigin -from octoprint.server import admin_permission, NO_CONTENT -from octoprint.server.util.flask import no_firstrun_access -from octoprint.util import is_hidden_path, to_bytes -from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, get_comparable_version, is_octoprint_compatible -from octoprint.util.platform import is_os_compatible -from octoprint.util.pip import LocalPipCaller +import octoprint.plugin from octoprint.access import ADMIN_GROUP from octoprint.access.permissions import Permissions +from octoprint.events import Events +from octoprint.server import NO_CONTENT +from octoprint.server.util.flask import no_firstrun_access +from octoprint.settings import default_settings +from octoprint.util import is_hidden_path, to_bytes +from octoprint.util.pip import create_pip_caller +from octoprint.util.platform import is_os_compatible +from octoprint.util.version import ( + get_comparable_version, + get_octoprint_version, + get_octoprint_version_string, + is_octoprint_compatible, +) try: - from os import scandir + import zlib # check if zlib is available except ImportError: - from scandir import scandir + zlib = None -try: - import zlib # check if zlib is available -except ImportError: - zlib = None - - -from flask_babel import gettext import io -import flask +import json import logging import os -import requests -import sarge import shutil +import sys import tempfile import threading import time -import zipfile -import json -import sys import traceback +import zipfile +import flask +import requests +import sarge +from flask_babel import gettext + +from octoprint.plugins.pluginmanager import DEFAULT_PLUGIN_REPOSITORY +from octoprint.settings import valid_boolean_trues +from octoprint.util.text import sanitize UNKNOWN_PLUGINS_FILE = "unknown_plugins_from_restore.json" -BACKUP_FILE_PREFIX = "octoprint-backup" - BACKUP_DATE_TIME_FMT = "%Y%m%d-%H%M%S" -def build_backup_filename(): - return "{}-{}.zip".format(BACKUP_FILE_PREFIX, - time.strftime(BACKUP_DATE_TIME_FMT)) - - -class BackupPlugin(octoprint.plugin.SettingsPlugin, - octoprint.plugin.TemplatePlugin, - octoprint.plugin.AssetPlugin, - octoprint.plugin.BlueprintPlugin, - octoprint.plugin.StartupPlugin): - - _pip_caller = None - - # noinspection PyMissingConstructor - def __init__(self): - self._in_progress = [] - self._in_progress_lock = threading.RLock() - - # Additional permissions hook - - def get_additional_permissions(self): - return [ - dict(key="ACCESS", - name="Backup access", - description=gettext("Allows access to backups and restores"), - roles=["access"], - dangerous=True, - default_groups=[ADMIN_GROUP]) - ] - - ##~~ StartupPlugin - - def on_after_startup(self): - self._clean_dir_backup(self._settings._basedir, - on_log_progress=self._logger.info) - - ##~~ AssetPlugin - - def get_assets(self): - return dict(js=["js/backup.js"], - clientjs=["clientjs/backup.js"], - css=["css/backup.css"], - less=["less/backup.less"]) - - ##~~ TemplatePlugin - - def get_template_configs(self): - return [dict(type="settings", name=gettext("Backup & Restore"))] - - ##~~ BlueprintPlugin - - @octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"]) - @no_firstrun_access - @Permissions.PLUGIN_BACKUP_ACCESS.require(403) - def get_state(self): - backups = self._get_backups() - unknown_plugins = self._get_unknown_plugins() - return flask.jsonify(backups=backups, - backup_in_progress=len(self._in_progress) > 0, - unknown_plugins=unknown_plugins, - restore_supported=is_os_compatible(["!windows"])) - - @octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["GET"]) - @no_firstrun_access - @Permissions.PLUGIN_BACKUP_ACCESS.require(403) - def get_unknown_plugins(self): - # TODO add caching - unknown_plugins = self._get_unknown_plugins() - return flask.jsonify(unknown_plugins=unknown_plugins) - - @octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["DELETE"]) - @no_firstrun_access - @Permissions.PLUGIN_BACKUP_ACCESS.require(403) - def delete_unknown_plugins(self): - data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE) - try: - os.remove(data_file) - except Exception: - pass - return NO_CONTENT - - @octoprint.plugin.BlueprintPlugin.route("/backup", methods=["GET"]) - @no_firstrun_access - @Permissions.PLUGIN_BACKUP_ACCESS.require(403) - def get_backups(self): - backups = self._get_backups() - return flask.jsonify(backups=backups) - - @octoprint.plugin.BlueprintPlugin.route("/backup", methods=["POST"]) - @no_firstrun_access - @Permissions.PLUGIN_BACKUP_ACCESS.require(403) - def create_backup(self): - backup_file = build_backup_filename() - - data = flask.request.json - exclude = data.get("exclude", []) - - def on_backup_start(name, temporary_path, exclude): - self._logger.info("Creating backup zip at {} (excluded: {})...".format(temporary_path, - ",".join(exclude) if len(exclude) else "-")) - - with self._in_progress_lock: - self._in_progress.append(name) - self._send_client_message("backup_started", payload=dict(name=name)) - - def on_backup_done(name, final_path, exclude): - with self._in_progress_lock: - self._in_progress.remove(name) - self._send_client_message("backup_done", payload=dict(name=name)) - - self._logger.info("... done creating backup zip.") - - def on_backup_error(name, exc_info): - with self._in_progress_lock: - try: - self._in_progress.remove(name) - except ValueError: - # we'll ignore that - pass - - self._send_client_message("backup_error", payload=dict(name=name, - error="{}".format(exc_info[1]))) - self._logger.error("Error while creating backup zip", exc_info=exc_info) - - thread = threading.Thread(target=self._create_backup, - args=(backup_file,), - kwargs=dict(exclude=exclude, - settings=self._settings, - plugin_manager=self._plugin_manager, - datafolder=self.get_plugin_data_folder(), - on_backup_start=on_backup_start, - on_backup_done=on_backup_done, - on_backup_error=on_backup_error)) - thread.daemon = True - thread.start() - - response = flask.jsonify(started=True, - name=backup_file) - response.status_code = 201 - return response - - @octoprint.plugin.BlueprintPlugin.route("/backup/", methods=["DELETE"]) - @no_firstrun_access - @Permissions.PLUGIN_BACKUP_ACCESS.require(403) - def delete_backup(self, filename): - backup_folder = self.get_plugin_data_folder() - full_path = os.path.realpath(os.path.join(backup_folder, filename)) - if full_path.startswith(backup_folder) \ - and os.path.exists(full_path) \ - and not is_hidden_path(full_path): - try: - os.remove(full_path) - except Exception: - self._logger.exception("Could not delete {}".format(filename)) - raise - return NO_CONTENT - - @octoprint.plugin.BlueprintPlugin.route("/restore", methods=["POST"]) - @no_firstrun_access - @Permissions.PLUGIN_BACKUP_ACCESS.require(403) - def perform_restore(self): - if not is_os_compatible(["!windows"]): - return flask.make_response("Invalid request, the restores are not supported on the underlying operating system", 400) - - input_name = "file" - input_upload_path = input_name + "." + self._settings.global_get(["server", "uploads", "pathSuffix"]) - - if input_upload_path in flask.request.values: - # file to restore was uploaded - path = flask.request.values[input_upload_path] - - elif flask.request.json and "path" in flask.request.json: - # existing backup is supposed to be restored - backup_folder = self.get_plugin_data_folder() - path = os.path.realpath(os.path.join(backup_folder, flask.request.json["path"])) - if not path.startswith(backup_folder) \ - or not os.path.exists(path) \ - or is_hidden_path(path): - return flask.abort(404) - - else: - return flask.make_response("Invalid request, neither a file nor a path of a file to restore provided", 400) - - def on_install_plugins(plugins): - force_user = self._settings.global_get_boolean(["plugins", "pluginmanager", "pip_force_user"]) - pip_args = self._settings.global_get(["plugins", "pluginmanager", "pip_args"]) - - def on_log(line): - self._logger.info(line) - self._send_client_message("logline", dict(line=line, type="stdout")) - - for plugin in plugins: - octoprint_compatible = is_octoprint_compatible(*plugin["compatibility"]["octoprint"]) - os_compatible = is_os_compatible(plugin["compatibility"]["os"]) - compatible = octoprint_compatible and os_compatible - if not compatible: - if not octoprint_compatible and not os_compatible: - self._logger.warn("Cannot install plugin {}, it is incompatible to this version " - "of OctoPrint and the underlying operating system".format(plugin["id"])) - elif not octoprint_compatible: - self._logger.warn("Cannot install plugin {}, it is incompatible to this version " - "of OctoPrint".format(plugin["id"])) - elif not os_compatible: - self._logger.warn("Cannot install plugin {}, it is incompatible to the underlying " - "operating system".format(plugin["id"])) - self._send_client_message("plugin_incompatible", dict(plugin=plugin["id"], - octoprint_compatible=octoprint_compatible, - os_compatible=os_compatible)) - continue - - self._logger.info("Installing plugin {}".format(plugin["id"])) - self._send_client_message("installing_plugin", dict(plugin=plugin["id"])) - self.__class__._install_plugin(plugin, - force_user=force_user, - pip_args=pip_args, - on_log=on_log) - - def on_report_unknown_plugins(plugins): - self._send_client_message("unknown_plugins", payload=dict(plugins=plugins)) - - def on_log_progress(line): - self._logger.info(line) - self._send_client_message("logline", payload=dict(line=line, stream="stdout")) - - def on_log_error(line, exc_info=None): - self._logger.error(line, exc_info=exc_info) - self._send_client_message("logline", payload=dict(line=line, stream="stderr")) - - if exc_info is not None: - exc_type, exc_value, exc_tb = exc_info - output = traceback.format_exception(exc_type, exc_value, exc_tb) - for line in output: - self._send_client_message("logline", payload=dict(line=line.rstrip(), stream="stderr")) - - def on_restore_start(path): - self._send_client_message("restore_started") - - def on_restore_done(path): - self._send_client_message("restore_done") - - def on_restore_failed(path): - self._send_client_message("restore_failed") - - def on_invalid_backup(line): - on_log_error(line) - - archive = tempfile.NamedTemporaryFile(delete=False) - archive.close() - shutil.copy(path, archive.name) - path = archive.name - - # noinspection PyTypeChecker - thread = threading.Thread(target=self._restore_backup, - args=(path,), - kwargs=dict(settings=self._settings, - plugin_manager=self._plugin_manager, - datafolder=self.get_plugin_data_folder(), - on_install_plugins=on_install_plugins, - on_report_unknown_plugins=on_report_unknown_plugins, - on_invalid_backup=on_invalid_backup, - on_log_progress=on_log_progress, - on_log_error=on_log_error, - on_restore_start=on_restore_start, - on_restore_done=on_restore_done, - on_restore_failed=on_restore_failed)) - thread.daemon = True - thread.start() - - return flask.jsonify(started=True) - - ##~~ tornado hook - - def route_hook(self, *args, **kwargs): - from octoprint.server.util.tornado import LargeResponseHandler, path_validation_factory - from octoprint.util import is_hidden_path - from octoprint.server import app - from octoprint.server.util.tornado import access_validation_factory - from octoprint.server.util.flask import admin_validator - - return [ - (r"/download/(.*)", LargeResponseHandler, dict(path=self.get_plugin_data_folder(), - as_attachment=True, - path_validation=path_validation_factory(lambda path: not is_hidden_path(path), - status_code=404), - access_validation=access_validation_factory(app, admin_validator))) - ] - - def bodysize_hook(self, current_max_body_sizes, *args, **kwargs): - # max upload size of 1GB for the restore endpoint - return [("POST", r"/restore", 1024 * 1024 * 1024)] - - ##~~ CLI hook - - def cli_commands_hook(self, cli_group, pass_octoprint_ctx, *args, **kwargs): - import click - - @click.command("backup") - @click.option("--exclude", multiple=True, - help="Identifiers of data folders to exclude, e.g. 'uploads' to exclude uploads or " - "'timelapse' to exclude timelapses.") - def backup_command(exclude): - """ - Creates a new backup. - """ - - backup_file = build_backup_filename() - settings = octoprint.plugin.plugin_settings_for_settings_plugin("backup", self, settings=cli_group.settings) - - datafolder = os.path.join(settings.getBaseFolder("data"), "backup") - if not os.path.isdir(datafolder): - os.makedirs(datafolder) - - click.echo("Creating backup at {}, please wait...".format(backup_file)) - self._create_backup(backup_file, - exclude=exclude, - settings=settings, - plugin_manager=cli_group.plugin_manager, - datafolder=datafolder) - click.echo("Done.") - - @click.command("restore") - @click.argument("path") - def restore_command(path): - """ - Restores an existing backup from the backup zip provided as argument. - - OctoPrint does not need to run for this to proceed. - """ - settings = octoprint.plugin.plugin_settings_for_settings_plugin("backup", self, settings=cli_group.settings) - plugin_manager = cli_group.plugin_manager - - datafolder = os.path.join(settings.getBaseFolder("data"), "backup") - if not os.path.isdir(datafolder): - os.makedirs(datafolder) - - # register plugin manager plugin setting overlays - plugin_info = plugin_manager.get_plugin_info("pluginmanager") - if plugin_info and plugin_info.implementation: - default_settings_overlay = dict(plugins=dict()) - default_settings_overlay["plugins"]["pluginmanager"] = plugin_info.implementation.get_settings_defaults() - settings.add_overlay(default_settings_overlay, at_end=True) - - if not os.path.isabs(path): - datafolder = os.path.join(settings.getBaseFolder("data"), "backup") - if not os.path.isdir(datafolder): - os.makedirs(datafolder) - path = os.path.join(datafolder, path) - - if not os.path.exists(path): - click.echo("Backup {} does not exist".format(path), err=True) - sys.exit(-1) - - archive = tempfile.NamedTemporaryFile(delete=False) - archive.close() - shutil.copy(path, archive.name) - path = archive.name - - def on_install_plugins(plugins): - if not plugins: - return - - force_user = settings.global_get_boolean(["plugins", "pluginmanager", "pip_force_user"]) - pip_args = settings.global_get(["plugins", "pluginmanager", "pip_args"]) - - def log(line): - click.echo("\t{}".format(line)) - - for plugin in plugins: - octoprint_compatible = is_octoprint_compatible(*plugin["compatibility"]["octoprint"]) - os_compatible = is_os_compatible(plugin["compatibility"]["os"]) - compatible = octoprint_compatible and os_compatible - if not compatible: - if not octoprint_compatible and not os_compatible: - click.echo("Cannot install plugin {}, it is incompatible to this version of " - "OctoPrint and the underlying operating system".format(plugin["id"])) - elif not octoprint_compatible: - click.echo("Cannot install plugin {}, it is incompatible to this version of " - "OctoPrint".format(plugin["id"])) - elif not os_compatible: - click.echo("Cannot install plugin {}, it is incompatible to the underlying " - "operating system".format(plugin["id"])) - continue - - click.echo("Installing plugin {}".format(plugin["id"])) - self.__class__._install_plugin(plugin, - force_user=force_user, - pip_args=pip_args, - on_log=log) - - def on_report_unknown_plugins(plugins): - if not plugins: - return - - click.echo("The following plugins were not found in the plugin repository. You'll need to install them manually.") - for plugin in plugins: - click.echo("\t{} (Homepage: {})".format(plugin["name"], plugin["url"] if plugin["url"] else "?")) - - def on_log_progress(line): - click.echo(line) - - def on_log_error(line, exc_info=None): - click.echo(line, err=True) - - if exc_info is not None: - exc_type, exc_value, exc_tb = exc_info - output = traceback.format_exception(exc_type, exc_value, exc_tb) - for line in output: - click.echo(line.rstrip(), err=True) - - if self._restore_backup(path, - settings=settings, - plugin_manager=plugin_manager, - datafolder=datafolder, - on_install_plugins=on_install_plugins, - on_report_unknown_plugins=on_report_unknown_plugins, - on_log_progress=on_log_progress, - on_log_error=on_log_error, - on_invalid_backup=on_log_error): - click.echo("Restored from {}".format(path)) - else: - click.echo("Restoring from {} failed".format(path), err=True) - - return [backup_command, restore_command] - - ##~~ helpers - - def _get_backups(self): - backups = [] - for entry in scandir(self.get_plugin_data_folder()): - if is_hidden_path(entry.path): - continue - if not entry.is_file(): - continue - if not entry.name.endswith(".zip"): - continue - - backups.append(dict(name=entry.name, - date=entry.stat().st_mtime, - size=entry.stat().st_size, - url=flask.url_for("index") + "plugin/backup/download/" + entry.name)) - return backups - - def _get_unknown_plugins(self): - data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE) - if os.path.exists(data_file): - try: - with io.open(data_file, mode='rb', encoding="utf-8") as f: - unknown_plugins = json.load(f) - - assert isinstance(unknown_plugins, list) - assert all(map(lambda x: isinstance(x, dict) and "key" in x and "name" in x and "url" in x, unknown_plugins)) - - installed_plugins = self._plugin_manager.plugins - unknown_plugins = list(filter(lambda x: x["key"] not in installed_plugins, unknown_plugins)) - if not unknown_plugins: - # no plugins left uninstalled, delete data file - try: - os.remove(data_file) - except Exception: - self._logger.exception("Error while deleting list of unknown plugins at {}".format(data_file)) - - return unknown_plugins - except Exception: - self._logger.exception("Error while reading list of unknown plugins from {}".format(data_file)) - try: - os.remove(data_file) - except Exception: - self._logger.exception("Error while deleting list of unknown plugins at {}".format(data_file)) - - return [] - - @classmethod - def _clean_dir_backup(cls, basedir, - on_log_progress=None): - basedir_backup = basedir + ".bck" - - if os.path.exists(basedir_backup): - def remove_bck(): - if callable(on_log_progress): - on_log_progress("Found config folder backup from prior restore, deleting it...") - shutil.rmtree(basedir_backup) - if callable(on_log_progress): - on_log_progress("... deleted.") - - thread = threading.Thread(target=remove_bck) - thread.daemon = True - thread.start() - - @classmethod - def _get_disk_size(cls, path, ignored=None): - if ignored is None: - ignored = [] - - if path in ignored: - return 0 - - total = 0 - for entry in scandir(path): - if entry.is_dir(): - total += cls._get_disk_size(entry.path, ignored=ignored) - elif entry.is_file(): - total += entry.stat().st_size - return total - - @classmethod - def _free_space(cls, path, size): - from psutil import disk_usage - return disk_usage(path).free > size - - @classmethod - def _get_plugin_repository_data(cls, url, logger=None): - if logger is None: - logger = logging.getLogger(__name__) - - try: - r = requests.get(url, timeout=30) - r.raise_for_status() - except Exception: - logger.exception("Error while fetching the plugin repository data from {}".format(url)) - return dict() - - from octoprint.plugins.pluginmanager import map_repository_entry - return dict((plugin["id"], plugin) for plugin in map(map_repository_entry, r.json())) - - @classmethod - def _install_plugin(cls, plugin, force_user=False, pip_args=None, on_log=None): - if pip_args is None: - pip_args = [] - - if on_log is None: - on_log = logging.getLogger(__name__).info - - # prepare pip caller - def log(prefix, *lines): - for line in lines: - on_log("{} {}".format(prefix, line.rstrip())) - - def log_call(*lines): - log(">", *lines) - - def log_stdout(*lines): - log("<", *lines) - - def log_stderr(*lines): - log("!", *lines) - - if cls._pip_caller is None: - cls._pip_caller = LocalPipCaller(force_user=force_user) - - cls._pip_caller.on_log_call = log_call - cls._pip_caller.on_log_stdout = log_stdout - cls._pip_caller.on_log_stderr = log_stderr - - # install plugin - pip = ["install", sarge.shell_quote(plugin["archive"]), '--no-cache-dir'] - - if plugin.get("follow_dependency_links"): - pip.append("--process-dependency-links") - - if force_user: - pip.append("--user") - - if pip_args: - pip += pip_args - - cls._pip_caller.execute(*pip) - - @classmethod - def _create_backup(cls, name, - exclude=None, - settings=None, - plugin_manager=None, - datafolder=None, - on_backup_start=None, - on_backup_done=None, - on_backup_error=None): - exclude_by_default = ("generated", "logs", "watched",) - - try: - if exclude is None: - exclude = [] - if not isinstance(exclude, list): - exclude = list(exclude) - - if "timelapse" in exclude: - exclude.append("timelapse_tmp") - - configfile = settings._configfile - basedir = settings._basedir - - temporary_path = os.path.join(datafolder, ".{}".format(name)) - final_path = os.path.join(datafolder, name) - - own_folder = datafolder - defaults = [os.path.join(basedir, "config.yaml"),] + \ - [os.path.join(basedir, folder) for folder in default_settings["folder"].keys()] - - # check how much many bytes we are about to backup - size = os.stat(configfile).st_size - for folder in default_settings["folder"].keys(): - if folder in exclude or folder in exclude_by_default: - continue - size += cls._get_disk_size(settings.global_get_basefolder(folder), - ignored=[own_folder,]) - size += cls._get_disk_size(basedir, ignored=defaults + [own_folder,]) - - # since we can't know the compression ratio beforehand, we assume we need the same amount of space - if not cls._free_space(os.path.dirname(temporary_path), size): - raise InsufficientSpace() - - compression = zipfile.ZIP_DEFLATED if zlib else zipfile.ZIP_STORED - - if callable(on_backup_start): - on_backup_start(name, temporary_path, exclude) - - with zipfile.ZipFile(temporary_path, mode="w", compression=compression, allowZip64=True) as zip: - def add_to_zip(source, target, ignored=None): - if ignored is None: - ignored = [] - - if source in ignored: - return - - if os.path.isdir(source): - for entry in scandir(source): - add_to_zip(entry.path, os.path.join(target, entry.name), ignored=ignored) - elif os.path.isfile(source): - zip.write(source, arcname=target) - - # add metadata - metadata = dict(version=get_octoprint_version_string(), - excludes=exclude) - zip.writestr("metadata.json", json.dumps(metadata)) - - # backup current config file - add_to_zip(configfile, "basedir/config.yaml", ignored=[own_folder,]) - - # backup configured folder paths - for folder in default_settings["folder"].keys(): - if folder in exclude or folder in exclude_by_default: - continue - - add_to_zip(settings.global_get_basefolder(folder), - "basedir/" + folder.replace("_", "/"), - ignored=[own_folder,]) - - # backup anything else that might be lying around in our basedir - add_to_zip(basedir, "basedir", ignored=defaults + [own_folder, ]) - - # add list of installed plugins - plugins = [] - plugin_folder = settings.global_get_basefolder("plugins") - for key, plugin in plugin_manager.plugins.items(): - if plugin.bundled or (isinstance(plugin.origin, FolderOrigin) and plugin.origin.folder == plugin_folder): - # ignore anything bundled or from the plugins folder we already include in the backup - continue - - plugins.append(dict(key=plugin.key, - name=plugin.name, - url=plugin.url)) - - if len(plugins): - zip.writestr("plugin_list.json", json.dumps(plugins)) - - shutil.move(temporary_path, final_path) - - if callable(on_backup_done): - on_backup_done(name, final_path, exclude) - except Exception as exc: ## noqa: F841 - # TODO py3: use the exception, not sys.exc_info() - if callable(on_backup_error): - exc_info = sys.exc_info() - try: - on_backup_error(name, exc_info) - finally: - del exc_info - raise - - @classmethod - def _restore_backup(cls, path, - settings=None, - plugin_manager=None, - datafolder=None, - on_install_plugins=None, - on_report_unknown_plugins=None, - on_invalid_backup=None, - on_log_progress=None, - on_log_error=None, - on_restore_start=None, - on_restore_done=None, - on_restore_failed=None): - if not is_os_compatible(["!windows"]): - if callable(on_log_error): - on_log_error("Restore is not supported on this operating system") - if callable(on_restore_failed): - on_restore_failed(path) - return False - - restart_command = settings.global_get(["server", "commands", "serverRestartCommand"]) - - basedir = settings._basedir - cls._clean_dir_backup(basedir, - on_log_progress=on_log_progress) - - plugin_repo = dict() - repo_url = settings.global_get(["plugins", "pluginmanager", "repository"]) - if repo_url: - plugin_repo = cls._get_plugin_repository_data(repo_url) - - if callable(on_restore_start): - on_restore_start(path) - - try: - - with zipfile.ZipFile(path, "r") as zip: - # read metadata - try: - metadata_zipinfo = zip.getinfo("metadata.json") - except KeyError: - if callable(on_invalid_backup): - on_invalid_backup("Not an OctoPrint backup, lacks metadata.json") - if callable(on_restore_failed): - on_restore_failed(path) - return False - - metadata_bytes = zip.read(metadata_zipinfo) - metadata = json.loads(metadata_bytes) - - backup_version = get_comparable_version(metadata["version"], base=True) - if backup_version > get_octoprint_version(base=True): - if callable(on_invalid_backup): - on_invalid_backup("Backup is from a newer version of OctoPrint and cannot be applied") - if callable(on_restore_failed): - on_restore_failed(path) - return False - - # unzip to temporary folder - temp = tempfile.mkdtemp() - try: - if callable(on_log_progress): - on_log_progress("Unpacking backup to {}...".format(temp)) - abstemp = os.path.abspath(temp) - for member in zip.infolist(): - abspath = os.path.abspath(os.path.join(temp, member.filename)) - if abspath.startswith(abstemp): - zip.extract(member, temp) - - # sanity check - configfile = os.path.join(temp, "basedir", "config.yaml") - if not os.path.exists(configfile): - if callable(on_invalid_backup): - on_invalid_backup("Backup lacks config.yaml") - if callable(on_restore_failed): - on_restore_failed(path) - return False - - import yaml - - with io.open(configfile, "rt", encoding="utf-8") as f: - configdata = yaml.safe_load(f) - - if configdata.get("accessControl", dict()).get("enabled", True): - userfile = os.path.join(temp, "basedir", "users.yaml") - if not os.path.exists(userfile): - if callable(on_invalid_backup): - on_invalid_backup("Backup lacks users.yaml") - if callable(on_restore_failed): - on_restore_failed(path) - return False - - if callable(on_log_progress): - on_log_progress("Unpacked") - - # install available plugins - plugins = [] - plugin_list_file = os.path.join(temp, "plugin_list.json") - if os.path.exists(plugin_list_file): - with io.open(os.path.join(temp, "plugin_list.json"), 'rb') as f: - plugins = json.load(f) - - known_plugins = [] - unknown_plugins = [] - if plugins: - if plugin_repo: - for plugin in plugins: - if plugin["key"] in plugin_manager.plugins: - # already installed - continue - - if plugin["key"] in plugin_repo: - # not installed, can be installed from repository url - known_plugins.append(plugin_repo[plugin["key"]]) - else: - # not installed, not installable - unknown_plugins.append(plugin) - - else: - # no repo, all plugins are not installable - unknown_plugins = plugins - - if callable(on_log_progress): - if known_plugins: - on_log_progress("Known and installable plugins: {}".format(", ".join(map(lambda x: x["id"], known_plugins)))) - if unknown_plugins: - on_log_progress("Unknown plugins: {}".format(", ".join(map(lambda x: x["key"], unknown_plugins)))) - - if callable(on_install_plugins): - on_install_plugins(known_plugins) - - if callable(on_report_unknown_plugins): - on_report_unknown_plugins(unknown_plugins) - - # move config data - basedir_backup = basedir + ".bck" - basedir_extracted = os.path.join(temp, "basedir") - - if callable(on_log_progress): - on_log_progress("Renaming {} to {}...".format(basedir, basedir_backup)) - shutil.move(basedir, basedir_backup) - - try: - if callable(on_log_progress): - on_log_progress("Moving {} to {}...".format(basedir_extracted, basedir)) - shutil.move(basedir_extracted, basedir) - except Exception: - if callable(on_log_error): - on_log_error("Error while restoring config data", exc_info=sys.exc_info()) - on_log_error("Rolling back old config data") - - shutil.move(basedir_backup, basedir) - - if callable(on_restore_failed): - on_restore_failed(path) - return False - - if unknown_plugins: - if callable(on_log_progress): - on_log_progress("Writing info file about unknown plugins") - - if not os.path.isdir(datafolder): - os.makedirs(datafolder) - - unknown_plugins_path = os.path.join(datafolder, UNKNOWN_PLUGINS_FILE) - try: - with io.open(unknown_plugins_path, mode='wb') as f: - f.write(to_bytes(json.dumps(unknown_plugins))) - except Exception: - if callable(on_log_error): - on_log_error("Could not persist list of unknown plugins to {}".format(unknown_plugins_path), - exc_info = sys.exc_info()) - - finally: - if callable(on_log_progress): - on_log_progress("Removing temporary unpacked folder") - shutil.rmtree(temp) - - except Exception: - exc_info = sys.exc_info() - try: - if callable(on_log_error): - on_log_error("Error while running restore", exc_info=exc_info) - if callable(on_restore_failed): - on_restore_failed(path) - finally: - del exc_info - return False - - finally: - # remove zip - if callable(on_log_progress): - on_log_progress("Removing temporary zip") - os.remove(path) - - # restart server - if restart_command: - import sarge - - if callable(on_log_progress): - on_log_progress("Restarting...") - if callable(on_restore_done): - on_restore_done(path) - - try: - sarge.run(restart_command, async_=True) - except Exception: - if callable(on_log_error): - on_log_error("Error while restarting via command {}".format(restart_command), - exc_info=sys.exc_info()) - on_log_error("Please restart OctoPrint manually") - return False - - else: - if callable(on_restore_done): - on_restore_done(path) - - return True - - - def _send_client_message(self, message, payload=None): - if payload is None: - payload = dict() - payload["type"] = message - self._plugin_manager.send_plugin_message(self._identifier, payload) +class BackupPlugin( + octoprint.plugin.SettingsPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.AssetPlugin, + octoprint.plugin.BlueprintPlugin, + octoprint.plugin.StartupPlugin, + octoprint.plugin.WizardPlugin, +): + + _pip_caller = None + + # noinspection PyMissingConstructor + def __init__(self): + self._in_progress = [] + self._in_progress_lock = threading.RLock() + + # Additional permissions hook + + def get_additional_permissions(self): + return [ + { + "key": "ACCESS", + "name": "Backup access", + "description": gettext("Allows access to backups and restores"), + "roles": ["access"], + "dangerous": True, + "default_groups": [ADMIN_GROUP], + } + ] + + # Socket emit hook + + def socket_emit_hook(self, socket, user, message, payload, *args, **kwargs): + if message != "event" or payload["type"] != Events.PLUGIN_BACKUP_BACKUP_CREATED: + return True + + return user and user.has_permission(Permissions.PLUGIN_BACKUP_ACCESS) + + ##~~ StartupPlugin + + def on_after_startup(self): + self._clean_dir_backup(self._settings._basedir, on_log_progress=self._logger.info) + + ##~~ SettingsPlugin + + def get_settings_defaults(self): + return {"restore_unsupported": False} + + ##~~ AssetPlugin + + def get_assets(self): + return { + "js": ["js/backup.js"], + "clientjs": ["clientjs/backup.js"], + "css": ["css/backup.css"], + "less": ["less/backup.less"], + } + + ##~~ TemplatePlugin + + def get_template_configs(self): + return [ + {"type": "settings", "name": gettext("Backup & Restore")}, + {"type": "wizard", "name": gettext("Restore Backup?")}, + ] + + ##~~ BlueprintPlugin + + @octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"]) + @no_firstrun_access + @Permissions.PLUGIN_BACKUP_ACCESS.require(403) + def get_state(self): + backups = self._get_backups() + unknown_plugins = self._get_unknown_plugins() + return flask.jsonify( + backups=backups, + backup_in_progress=len(self._in_progress) > 0, + unknown_plugins=unknown_plugins, + restore_supported=self._restore_supported(self._settings), + ) + + @octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["GET"]) + @no_firstrun_access + @Permissions.PLUGIN_BACKUP_ACCESS.require(403) + def get_unknown_plugins(self): + # TODO add caching + unknown_plugins = self._get_unknown_plugins() + return flask.jsonify(unknown_plugins=unknown_plugins) + + @octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["DELETE"]) + @no_firstrun_access + @Permissions.PLUGIN_BACKUP_ACCESS.require(403) + def delete_unknown_plugins(self): + data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE) + try: + os.remove(data_file) + except Exception: + pass + return NO_CONTENT + + @octoprint.plugin.BlueprintPlugin.route("/backup", methods=["GET"]) + @no_firstrun_access + @Permissions.PLUGIN_BACKUP_ACCESS.require(403) + def get_backups(self): + backups = self._get_backups() + return flask.jsonify(backups=backups) + + @octoprint.plugin.BlueprintPlugin.route("/backup", methods=["POST"]) + @no_firstrun_access + @Permissions.PLUGIN_BACKUP_ACCESS.require(403) + def create_backup(self): + + data = flask.request.json + exclude = data.get("exclude", []) + filename = self._build_backup_filename(settings=self._settings) + + self._start_backup(exclude, filename) + + response = flask.jsonify(started=True, name=filename) + response.status_code = 201 + return response + + @octoprint.plugin.BlueprintPlugin.route("/backup/", methods=["DELETE"]) + @no_firstrun_access + @Permissions.PLUGIN_BACKUP_ACCESS.require(403) + def delete_backup(self, filename): + self._delete_backup(filename) + + return NO_CONTENT + + @octoprint.plugin.BlueprintPlugin.route("/restore", methods=["POST"]) + def perform_restore(self): + if not Permissions.PLUGIN_BACKUP_ACCESS.can() and not self._settings.global_get( + ["server", "firstRun"] + ): + return flask.abort(403) + + if not self._restore_supported(self._settings): + return flask.make_response( + "Invalid request, the restores are not supported on the underlying operating system", + 400, + ) + + input_name = "file" + input_upload_path = ( + input_name + + "." + + self._settings.global_get(["server", "uploads", "pathSuffix"]) + ) + + if input_upload_path in flask.request.values: + # file to restore was uploaded + path = flask.request.values[input_upload_path] + + elif flask.request.json and "path" in flask.request.json: + # existing backup is supposed to be restored + backup_folder = self.get_plugin_data_folder() + path = os.path.realpath( + os.path.join(backup_folder, flask.request.json["path"]) + ) + if ( + not path.startswith(backup_folder) + or not os.path.exists(path) + or is_hidden_path(path) + ): + return flask.abort(404) + + else: + return flask.make_response( + "Invalid request, neither a file nor a path of a file to restore provided", + 400, + ) + + def on_install_plugins(plugins): + force_user = self._settings.global_get_boolean( + ["plugins", "pluginmanager", "pip_force_user"] + ) + pip_args = self._settings.global_get(["plugins", "pluginmanager", "pip_args"]) + + def on_log(line): + self._logger.info(line) + self._send_client_message("logline", {"line": line, "type": "stdout"}) + + for plugin in plugins: + octoprint_compatible = is_octoprint_compatible( + *plugin["compatibility"]["octoprint"] + ) + os_compatible = is_os_compatible(plugin["compatibility"]["os"]) + compatible = octoprint_compatible and os_compatible + if not compatible: + if not octoprint_compatible and not os_compatible: + self._logger.warning( + "Cannot install plugin {}, it is incompatible to this version " + "of OctoPrint and the underlying operating system".format( + plugin["id"] + ) + ) + elif not octoprint_compatible: + self._logger.warning( + "Cannot install plugin {}, it is incompatible to this version " + "of OctoPrint".format(plugin["id"]) + ) + elif not os_compatible: + self._logger.warning( + "Cannot install plugin {}, it is incompatible to the underlying " + "operating system".format(plugin["id"]) + ) + self._send_client_message( + "plugin_incompatible", + { + "plugin": plugin["id"], + "octoprint_compatible": octoprint_compatible, + "os_compatible": os_compatible, + }, + ) + continue + + self._logger.info("Installing plugin {}".format(plugin["id"])) + self._send_client_message("installing_plugin", {"plugin": plugin["id"]}) + self.__class__._install_plugin( + plugin, + force_user=force_user, + pip_command=self._settings.global_get( + ["server", "commands", "localPipCommand"] + ), + pip_args=pip_args, + on_log=on_log, + ) + + def on_report_unknown_plugins(plugins): + self._send_client_message("unknown_plugins", payload={"plugins": plugins}) + + def on_log_progress(line): + self._logger.info(line) + self._send_client_message( + "logline", payload={"line": line, "stream": "stdout"} + ) + + def on_log_error(line, exc_info=None): + self._logger.error(line, exc_info=exc_info) + self._send_client_message( + "logline", payload={"line": line, "stream": "stderr"} + ) + + if exc_info is not None: + exc_type, exc_value, exc_tb = exc_info + output = traceback.format_exception(exc_type, exc_value, exc_tb) + for line in output: + self._send_client_message( + "logline", payload={"line": line.rstrip(), "stream": "stderr"} + ) + + def on_restore_start(path): + self._send_client_message("restore_started") + + def on_restore_done(path): + self._send_client_message("restore_done") + + def on_restore_failed(path): + self._send_client_message("restore_failed") + + def on_invalid_backup(line): + on_log_error(line) + + archive = tempfile.NamedTemporaryFile(delete=False) + archive.close() + shutil.copy(path, archive.name) + path = archive.name + + # noinspection PyTypeChecker + thread = threading.Thread( + target=self._restore_backup, + args=(path,), + kwargs={ + "settings": self._settings, + "plugin_manager": self._plugin_manager, + "datafolder": self.get_plugin_data_folder(), + "on_install_plugins": on_install_plugins, + "on_report_unknown_plugins": on_report_unknown_plugins, + "on_invalid_backup": on_invalid_backup, + "on_log_progress": on_log_progress, + "on_log_error": on_log_error, + "on_restore_start": on_restore_start, + "on_restore_done": on_restore_done, + "on_restore_failed": on_restore_failed, + }, + ) + thread.daemon = True + thread.start() + + return flask.jsonify(started=True) + + def is_blueprint_protected(self): + return False + + ##~~ WizardPlugin + + def is_wizard_required(self): + return self._settings.global_get(["server", "firstRun"]) and is_os_compatible( + ["!windows"] + ) + + def get_wizard_details(self): + return {"required": self.is_wizard_required()} + + ##~~ tornado hook + + def route_hook(self, *args, **kwargs): + from octoprint.server import app + from octoprint.server.util.flask import admin_validator + from octoprint.server.util.tornado import ( + LargeResponseHandler, + access_validation_factory, + path_validation_factory, + ) + from octoprint.util import is_hidden_path + + return [ + ( + r"/download/(.*)", + LargeResponseHandler, + { + "path": self.get_plugin_data_folder(), + "as_attachment": True, + "path_validation": path_validation_factory( + lambda path: not is_hidden_path(path), status_code=404 + ), + "access_validation": access_validation_factory(app, admin_validator), + }, + ) + ] + + def bodysize_hook(self, current_max_body_sizes, *args, **kwargs): + # max upload size of 1GB for the restore endpoint + return [("POST", r"/restore", 1024 * 1024 * 1024)] + + # Exported plugin helpers + def create_backup_helper(self, exclude=None, filename=None): + """ + .. versionadded:: 1.6.0 + + Create a backup from a plugin or other internal call + + This helper is exported as ``create_backup`` and can be used from the plugin + manager's ``get_helpers`` method. + + **Example** + + The following code snippet can be used from within a plugin, and will create a backup + excluding two folders (``timelapse`` and ``uploads``) + + .. code-block:: python + + helpers = self._plugin_manager.get_helpers("backup", "create_backup") + + if helpers and "create_backup" in helpers: + helpers["create_backup"](exclude=["timelapse", "uploads"]) + + By using the ``if helpers [...]`` clause, plugins can fall back to other methods + when they are running under versions where these helpers did not exist. + + + :param list exclude: Names of data folders to exclude, defaults to None + :param str filename: Name of backup to be created, if None (default) the backup + name will be auto-generated. This should use a ``.zip`` extension. + """ + if exclude is None: + exclude = [] + if not isinstance(exclude, list): + exclude = list(exclude) + + self._start_backup(exclude, filename=filename) + + def delete_backup_helper(self, filename): + """ + .. versionadded:: 1.6.0 + + Delete the specified backup from a plugin or other internal call + + This helper is exported as ``delete_backup`` and can be used through the plugin + manager's ``get_helpers`` method. + + **Example** + The following code snippet can be used from within a plugin, and will attempt to + delete the backup named ``ExampleBackup.zip``. + + .. code-block:: python + + helpers = self._plugin_manager.get_helpers("backup", "delete_backup") + + if helpers and "delete_backup" in helpers: + helpers["delete_backup"]("ExampleBackup.zip") + + By using the ``if helpers [...]`` clause, plugins can fall back to other methods + when they are running under versions where these helpers did not exist. + + .. warning:: + + This method will fail silently if the backup does not exist, and so + it is recommended that you make sure the name comes from a verified source, + for example the name from the events or other helpers. + + :param str filename: The name of the backup to delete + """ + self._delete_backup(filename) + + ##~~ CLI hook + + def cli_commands_hook(self, cli_group, pass_octoprint_ctx, *args, **kwargs): + import click + + @click.command("backup") + @click.option( + "--exclude", + multiple=True, + help="Identifiers of data folders to exclude, e.g. 'uploads' to exclude uploads or " + "'timelapse' to exclude timelapses.", + ) + @click.option( + "--path", + type=click.Path(), + default=None, + help="Specify full path to backup file to be created", + ) + def backup_command(exclude, path): + """ + Creates a new backup. + """ + + settings = octoprint.plugin.plugin_settings_for_settings_plugin( + "backup", self, settings=cli_group.settings + ) + + if path is not None: + datafolder, filename = os.path.split(os.path.abspath(path)) + else: + filename = self._build_backup_filename(settings=settings) + datafolder = os.path.join(settings.getBaseFolder("data"), "backup") + + if not os.path.isdir(datafolder): + os.makedirs(datafolder) + + click.echo("Creating backup at {}, please wait...".format(filename)) + self._create_backup( + filename, + exclude=exclude, + settings=settings, + plugin_manager=cli_group.plugin_manager, + datafolder=datafolder, + ) + click.echo("Done.") + click.echo("Backup located at {}".format(os.path.join(datafolder, filename))) + + @click.command("restore") + @click.argument("path") + def restore_command(path): + """ + Restores an existing backup from the backup zip provided as argument. + + OctoPrint does not need to run for this to proceed. + """ + settings = octoprint.plugin.plugin_settings_for_settings_plugin( + "backup", self, settings=cli_group.settings + ) + plugin_manager = cli_group.plugin_manager + + datafolder = os.path.join(settings.getBaseFolder("data"), "backup") + if not os.path.isdir(datafolder): + os.makedirs(datafolder) + + # register plugin manager plugin setting overlays + plugin_info = plugin_manager.get_plugin_info("pluginmanager") + if plugin_info and plugin_info.implementation: + default_settings_overlay = {"plugins": {}} + default_settings_overlay["plugins"][ + "pluginmanager" + ] = plugin_info.implementation.get_settings_defaults() + settings.add_overlay(default_settings_overlay, at_end=True) + + if not os.path.isabs(path): + datafolder = os.path.join(settings.getBaseFolder("data"), "backup") + if not os.path.isdir(datafolder): + os.makedirs(datafolder) + path = os.path.join(datafolder, path) + + if not os.path.exists(path): + click.echo("Backup {} does not exist".format(path), err=True) + sys.exit(-1) + + archive = tempfile.NamedTemporaryFile(delete=False) + archive.close() + shutil.copy(path, archive.name) + path = archive.name + + def on_install_plugins(plugins): + if not plugins: + return + + force_user = settings.global_get_boolean( + ["plugins", "pluginmanager", "pip_force_user"] + ) + pip_args = settings.global_get(["plugins", "pluginmanager", "pip_args"]) + + def log(line): + click.echo("\t{}".format(line)) + + for plugin in plugins: + octoprint_compatible = is_octoprint_compatible( + *plugin["compatibility"]["octoprint"] + ) + os_compatible = is_os_compatible(plugin["compatibility"]["os"]) + compatible = octoprint_compatible and os_compatible + if not compatible: + if not octoprint_compatible and not os_compatible: + click.echo( + "Cannot install plugin {}, it is incompatible to this version of " + "OctoPrint and the underlying operating system".format( + plugin["id"] + ) + ) + elif not octoprint_compatible: + click.echo( + "Cannot install plugin {}, it is incompatible to this version of " + "OctoPrint".format(plugin["id"]) + ) + elif not os_compatible: + click.echo( + "Cannot install plugin {}, it is incompatible to the underlying " + "operating system".format(plugin["id"]) + ) + continue + + click.echo("Installing plugin {}".format(plugin["id"])) + self.__class__._install_plugin( + plugin, + force_user=force_user, + pip_command=settings.global_get( + ["server", "commands", "localPipCommand"] + ), + pip_args=pip_args, + on_log=log, + ) + + def on_report_unknown_plugins(plugins): + if not plugins: + return + + click.echo( + "The following plugins were not found in the plugin repository. You'll need to install them manually." + ) + for plugin in plugins: + click.echo( + "\t{} (Homepage: {})".format( + plugin["name"], plugin["url"] if plugin["url"] else "?" + ) + ) + + def on_log_progress(line): + click.echo(line) + + def on_log_error(line, exc_info=None): + click.echo(line, err=True) + + if exc_info is not None: + exc_type, exc_value, exc_tb = exc_info + output = traceback.format_exception(exc_type, exc_value, exc_tb) + for line in output: + click.echo(line.rstrip(), err=True) + + if self._restore_backup( + path, + settings=settings, + plugin_manager=plugin_manager, + datafolder=datafolder, + on_install_plugins=on_install_plugins, + on_report_unknown_plugins=on_report_unknown_plugins, + on_log_progress=on_log_progress, + on_log_error=on_log_error, + on_invalid_backup=on_log_error, + ): + click.echo("Restored from {}".format(path)) + else: + click.echo("Restoring from {} failed".format(path), err=True) + + return [backup_command, restore_command] + + ##~~ helpers + + def _start_backup(self, exclude, filename=None): + if filename is None: + filename = self._build_backup_filename(settings=self._settings) + + def on_backup_start(name, temporary_path, exclude): + self._logger.info( + "Creating backup zip at {} (excluded: {})...".format( + temporary_path, ",".join(exclude) if len(exclude) else "-" + ) + ) + + with self._in_progress_lock: + self._in_progress.append(name) + self._send_client_message("backup_started", payload={"name": name}) + + def on_backup_done(name, final_path, exclude): + with self._in_progress_lock: + self._in_progress.remove(name) + self._send_client_message("backup_done", payload={"name": name}) + + self._logger.info("... done creating backup zip.") + + self._event_bus.fire( + Events.PLUGIN_BACKUP_BACKUP_CREATED, + {"name": name, "path": final_path, "excludes": exclude}, + ) + + def on_backup_error(name, exc_info): + with self._in_progress_lock: + try: + self._in_progress.remove(name) + except ValueError: + # we'll ignore that + pass + + self._send_client_message( + "backup_error", payload={"name": name, "error": "{}".format(exc_info[1])} + ) + self._logger.error("Error while creating backup zip", exc_info=exc_info) + + thread = threading.Thread( + target=self._create_backup, + args=(filename,), + kwargs={ + "exclude": exclude, + "settings": self._settings, + "plugin_manager": self._plugin_manager, + "logger": self._logger, + "datafolder": self.get_plugin_data_folder(), + "on_backup_start": on_backup_start, + "on_backup_done": on_backup_done, + "on_backup_error": on_backup_error, + }, + ) + thread.daemon = True + thread.start() + + def _delete_backup(self, filename): + """ + Delete the backup specified + Args: + filename (str): Name of backup to delete + """ + backup_folder = self.get_plugin_data_folder() + full_path = os.path.realpath(os.path.join(backup_folder, filename)) + if ( + full_path.startswith(backup_folder) + and os.path.exists(full_path) + and not is_hidden_path(full_path) + ): + try: + os.remove(full_path) + except Exception: + self._logger.exception("Could not delete {}".format(filename)) + raise + + def _get_backups(self): + backups = [] + for entry in scandir(self.get_plugin_data_folder()): + if is_hidden_path(entry.path): + continue + if not entry.is_file(): + continue + if not entry.name.endswith(".zip"): + continue + + backups.append( + { + "name": entry.name, + "date": entry.stat().st_mtime, + "size": entry.stat().st_size, + "url": flask.url_for("index") + + "plugin/backup/download/" + + entry.name, + } + ) + return backups + + def _get_unknown_plugins(self): + data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE) + if os.path.exists(data_file): + try: + with io.open(data_file, mode="rt", encoding="utf-8") as f: + unknown_plugins = json.load(f) + + assert isinstance(unknown_plugins, list) + assert all( + map( + lambda x: isinstance(x, dict) + and "key" in x + and "name" in x + and "url" in x, + unknown_plugins, + ) + ) + + installed_plugins = self._plugin_manager.plugins + unknown_plugins = list( + filter(lambda x: x["key"] not in installed_plugins, unknown_plugins) + ) + if not unknown_plugins: + # no plugins left uninstalled, delete data file + try: + os.remove(data_file) + except Exception: + self._logger.exception( + "Error while deleting list of unknown plugins at {}".format( + data_file + ) + ) + + return unknown_plugins + except Exception: + self._logger.exception( + "Error while reading list of unknown plugins from {}".format( + data_file + ) + ) + try: + os.remove(data_file) + except Exception: + self._logger.exception( + "Error while deleting list of unknown plugins at {}".format( + data_file + ) + ) + + return [] + + @classmethod + def _clean_dir_backup(cls, basedir, on_log_progress=None): + basedir_backup = basedir + ".bck" + + if os.path.exists(basedir_backup): + + def remove_bck(): + if callable(on_log_progress): + on_log_progress( + "Found config folder backup from prior restore, deleting it..." + ) + shutil.rmtree(basedir_backup) + if callable(on_log_progress): + on_log_progress("... deleted.") + + thread = threading.Thread(target=remove_bck) + thread.daemon = True + thread.start() + + @classmethod + def _get_disk_size(cls, path, ignored=None): + if ignored is None: + ignored = [] + + if path in ignored: + return 0 + + total = 0 + for entry in scandir(path): + if entry.is_dir(): + total += cls._get_disk_size(entry.path, ignored=ignored) + elif entry.is_file(): + total += entry.stat().st_size + return total + + @classmethod + def _free_space(cls, path, size): + from psutil import disk_usage + + return disk_usage(path).free > size + + @classmethod + def _get_plugin_repository_data(cls, url, logger=None): + if logger is None: + logger = logging.getLogger(__name__) + + try: + r = requests.get(url, timeout=30) + r.raise_for_status() + except Exception: + logger.exception( + "Error while fetching the plugin repository data from {}".format(url) + ) + return {} + + from octoprint.plugins.pluginmanager import map_repository_entry + + return {plugin["id"]: plugin for plugin in map(map_repository_entry, r.json())} + + @classmethod + def _install_plugin( + cls, plugin, force_user=False, pip_command=None, pip_args=None, on_log=None + ): + if pip_args is None: + pip_args = [] + + if on_log is None: + on_log = logging.getLogger(__name__).info + + # prepare pip caller + def log(prefix, *lines): + for line in lines: + on_log("{} {}".format(prefix, line.rstrip())) + + def log_call(*lines): + log(">", *lines) + + def log_stdout(*lines): + log("<", *lines) + + def log_stderr(*lines): + log("!", *lines) + + if cls._pip_caller is None: + cls._pip_caller = create_pip_caller( + command=pip_command, force_user=force_user + ) + + cls._pip_caller.on_log_call = log_call + cls._pip_caller.on_log_stdout = log_stdout + cls._pip_caller.on_log_stderr = log_stderr + + # install plugin + pip = ["install", sarge.shell_quote(plugin["archive"]), "--no-cache-dir"] + + if plugin.get("follow_dependency_links"): + pip.append("--process-dependency-links") + + if force_user: + pip.append("--user") + + if pip_args: + pip += pip_args + + cls._pip_caller.execute(*pip) + + @classmethod + def _create_backup( + cls, + name, + exclude=None, + settings=None, + plugin_manager=None, + logger=None, + datafolder=None, + on_backup_start=None, + on_backup_done=None, + on_backup_error=None, + ): + if logger is None: + logger = logging.getLogger(__name__) + + exclude_by_default = ( + "generated", + "logs", + "watched", + ) + + try: + if exclude is None: + exclude = [] + if not isinstance(exclude, list): + exclude = list(exclude) + + if "timelapse" in exclude: + exclude.append("timelapse_tmp") + + current_excludes = list(exclude) + additional_excludes = list() + plugin_data = settings.global_get_basefolder("data") + for plugin, hook in plugin_manager.get_hooks( + "octoprint.plugin.backup.additional_excludes" + ).items(): + try: + additional = hook(current_excludes) + if isinstance(additional, list): + if "." in additional: + current_excludes.append(os.path.join("data", plugin)) + additional_excludes.append(os.path.join(plugin_data, plugin)) + else: + current_excludes += map( + lambda x: os.path.join("data", plugin, x), additional + ) + additional_excludes += map( + lambda x: os.path.join(plugin_data, plugin, x), additional + ) + except Exception: + logger.exception( + "Error while retrieving additional excludes " + "from plugin {name}".format(**locals()), + extra={"plugin": plugin}, + ) + + configfile = settings._configfile + basedir = settings._basedir + + temporary_path = os.path.join(datafolder, ".{}".format(name)) + final_path = os.path.join(datafolder, name) + + own_folder = datafolder + defaults = [os.path.join(basedir, "config.yaml"),] + [ + os.path.join(basedir, folder) + for folder in default_settings["folder"].keys() + ] + + # check how many bytes we are about to backup + size = os.stat(configfile).st_size + for folder in default_settings["folder"].keys(): + if folder in exclude or folder in exclude_by_default: + continue + size += cls._get_disk_size( + settings.global_get_basefolder(folder), + ignored=[ + own_folder, + ], + ) + size += cls._get_disk_size( + basedir, + ignored=defaults + + [ + own_folder, + ], + ) + + # since we can't know the compression ratio beforehand, we assume we need the same amount of space + if not cls._free_space(os.path.dirname(temporary_path), size): + raise InsufficientSpace() + + compression = zipfile.ZIP_DEFLATED if zlib else zipfile.ZIP_STORED + + if callable(on_backup_start): + on_backup_start(name, temporary_path, exclude) + + with zipfile.ZipFile( + temporary_path, mode="w", compression=compression, allowZip64=True + ) as zip: + + def add_to_zip(source, target, ignored=None): + if ignored is None: + ignored = [] + + if source in ignored: + return + + if os.path.isdir(source): + for entry in scandir(source): + add_to_zip( + entry.path, + os.path.join(target, entry.name), + ignored=ignored, + ) + elif os.path.isfile(source): + zip.write(source, arcname=target) + + # add metadata + metadata = { + "version": get_octoprint_version_string(), + "excludes": exclude, + } + zip.writestr("metadata.json", json.dumps(metadata)) + + # backup current config file + add_to_zip( + configfile, + "basedir/config.yaml", + ignored=[ + own_folder, + ], + ) + + # backup configured folder paths + for folder in default_settings["folder"].keys(): + if folder in exclude or folder in exclude_by_default: + continue + + add_to_zip( + settings.global_get_basefolder(folder), + "basedir/" + folder.replace("_", "/"), + ignored=[ + own_folder, + ] + + additional_excludes, + ) + + # backup anything else that might be lying around in our basedir + add_to_zip( + basedir, + "basedir", + ignored=defaults + + [ + own_folder, + ] + + additional_excludes, + ) + + # add list of installed plugins + helpers = plugin_manager.get_helpers( + "pluginmanager", "generate_plugins_json" + ) + if helpers and "generate_plugins_json" in helpers: + plugins = helpers["generate_plugins_json"]( + settings=settings, plugin_manager=plugin_manager + ) + + if len(plugins): + zip.writestr("plugin_list.json", json.dumps(plugins)) + + shutil.move(temporary_path, final_path) + + if callable(on_backup_done): + on_backup_done(name, final_path, exclude) + + except Exception as exc: # noqa: F841 + # TODO py3: use the exception, not sys.exc_info() + if callable(on_backup_error): + exc_info = sys.exc_info() + try: + on_backup_error(name, exc_info) + finally: + del exc_info + raise + + @classmethod + def _restore_backup( + cls, + path, + settings=None, + plugin_manager=None, + datafolder=None, + on_install_plugins=None, + on_report_unknown_plugins=None, + on_invalid_backup=None, + on_log_progress=None, + on_log_error=None, + on_restore_start=None, + on_restore_done=None, + on_restore_failed=None, + ): + if not cls._restore_supported(settings): + if callable(on_log_error): + on_log_error("Restore is not supported on this operating system") + if callable(on_restore_failed): + on_restore_failed(path) + return False + + restart_command = settings.global_get( + ["server", "commands", "serverRestartCommand"] + ) + + basedir = settings._basedir + cls._clean_dir_backup(basedir, on_log_progress=on_log_progress) + + repo_url = settings.global_get(["plugins", "pluginmanager", "repository"]) + if not repo_url: + repo_url = DEFAULT_PLUGIN_REPOSITORY + + plugin_repo = cls._get_plugin_repository_data(repo_url) + + if callable(on_restore_start): + on_restore_start(path) + + try: + + with zipfile.ZipFile(path, "r") as zip: + # read metadata + try: + metadata_zipinfo = zip.getinfo("metadata.json") + except KeyError: + if callable(on_invalid_backup): + on_invalid_backup("Not an OctoPrint backup, lacks metadata.json") + if callable(on_restore_failed): + on_restore_failed(path) + return False + + metadata_bytes = zip.read(metadata_zipinfo) + metadata = json.loads(metadata_bytes) + + backup_version = get_comparable_version(metadata["version"], base=True) + if backup_version > get_octoprint_version(base=True): + if callable(on_invalid_backup): + on_invalid_backup( + "Backup is from a newer version of OctoPrint and cannot be applied" + ) + if callable(on_restore_failed): + on_restore_failed(path) + return False + + # unzip to temporary folder + temp = tempfile.mkdtemp() + try: + if callable(on_log_progress): + on_log_progress("Unpacking backup to {}...".format(temp)) + + abstemp = os.path.abspath(temp) + dirs = {} + for member in zip.infolist(): + abspath = os.path.abspath(os.path.join(temp, member.filename)) + if abspath.startswith(abstemp): + date_time = time.mktime(member.date_time + (0, 0, -1)) + + zip.extract(member, temp) + + if os.path.isdir(abspath): + dirs[abspath] = date_time + else: + os.utime(abspath, (date_time, date_time)) + + # set time on folders + for abspath, date_time in dirs.items(): + os.utime(abspath, (date_time, date_time)) + + # sanity check + configfile = os.path.join(temp, "basedir", "config.yaml") + if not os.path.exists(configfile): + if callable(on_invalid_backup): + on_invalid_backup("Backup lacks config.yaml") + if callable(on_restore_failed): + on_restore_failed(path) + return False + + import yaml + + with io.open(configfile, "rt", encoding="utf-8") as f: + configdata = yaml.safe_load(f) + + userfile = os.path.join(temp, "basedir", "users.yaml") + if not os.path.exists(userfile): + if callable(on_invalid_backup): + on_invalid_backup("Backup lacks users.yaml") + if callable(on_restore_failed): + on_restore_failed(path) + return False + + if callable(on_log_progress): + on_log_progress("Unpacked") + + # install available plugins + plugins = [] + plugin_list_file = os.path.join(temp, "plugin_list.json") + if os.path.exists(plugin_list_file): + with io.open(os.path.join(temp, "plugin_list.json"), "rb") as f: + plugins = json.load(f) + + known_plugins = [] + unknown_plugins = [] + if plugins: + if plugin_repo: + for plugin in plugins: + if plugin["key"] in plugin_manager.plugins: + # already installed + continue + + if plugin["key"] in plugin_repo: + # not installed, can be installed from repository url + known_plugins.append(plugin_repo[plugin["key"]]) + else: + # not installed, not installable + unknown_plugins.append(plugin) + + else: + # no repo, all plugins are not installable + unknown_plugins = plugins + + if callable(on_log_progress): + if known_plugins: + on_log_progress( + "Known and installable plugins: {}".format( + ", ".join(map(lambda x: x["id"], known_plugins)) + ) + ) + if unknown_plugins: + on_log_progress( + "Unknown plugins: {}".format( + ", ".join( + map(lambda x: x["key"], unknown_plugins) + ) + ) + ) + + if callable(on_install_plugins): + on_install_plugins(known_plugins) + + if callable(on_report_unknown_plugins): + on_report_unknown_plugins(unknown_plugins) + + # move config data + basedir_backup = basedir + ".bck" + basedir_extracted = os.path.join(temp, "basedir") + + if callable(on_log_progress): + on_log_progress( + "Renaming {} to {}...".format(basedir, basedir_backup) + ) + shutil.move(basedir, basedir_backup) + + try: + if callable(on_log_progress): + on_log_progress( + "Moving {} to {}...".format(basedir_extracted, basedir) + ) + shutil.move(basedir_extracted, basedir) + except Exception: + if callable(on_log_error): + on_log_error( + "Error while restoring config data", + exc_info=sys.exc_info(), + ) + on_log_error("Rolling back old config data") + + shutil.move(basedir_backup, basedir) + + if callable(on_restore_failed): + on_restore_failed(path) + return False + + if unknown_plugins: + if callable(on_log_progress): + on_log_progress("Writing info file about unknown plugins") + + if not os.path.isdir(datafolder): + os.makedirs(datafolder) + + unknown_plugins_path = os.path.join( + datafolder, UNKNOWN_PLUGINS_FILE + ) + try: + with io.open(unknown_plugins_path, mode="wb") as f: + f.write(to_bytes(json.dumps(unknown_plugins))) + except Exception: + if callable(on_log_error): + on_log_error( + "Could not persist list of unknown plugins to {}".format( + unknown_plugins_path + ), + exc_info=sys.exc_info(), + ) + + finally: + if callable(on_log_progress): + on_log_progress("Removing temporary unpacked folder") + shutil.rmtree(temp) + + except Exception: + exc_info = sys.exc_info() + try: + if callable(on_log_error): + on_log_error("Error while running restore", exc_info=exc_info) + if callable(on_restore_failed): + on_restore_failed(path) + finally: + del exc_info + return False + + finally: + # remove zip + if callable(on_log_progress): + on_log_progress("Removing temporary zip") + os.remove(path) + + # restart server + if not restart_command: + restart_command = ( + configdata.get("server", {}) + .get("commands", {}) + .get("serverRestartCommand") + ) + + if restart_command: + import sarge + + if callable(on_log_progress): + on_log_progress("Restarting...") + if callable(on_restore_done): + on_restore_done(path) + + try: + sarge.run(restart_command, close_fds=True, async_=True) + except Exception: + if callable(on_log_error): + on_log_error( + "Error while restarting via command {}".format(restart_command), + exc_info=sys.exc_info(), + ) + on_log_error("Please restart OctoPrint manually") + return False + + else: + if callable(on_restore_done): + on_restore_done(path) + if callable(on_log_error): + on_log_error( + "No restart command configured. Please restart OctoPrint manually." + ) + + return True + + @classmethod + def _build_backup_filename(cls, settings): + if settings.global_get(["appearance", "name"]) == "": + backup_prefix = "octoprint" + else: + backup_prefix = settings.global_get(["appearance", "name"]) + backup_prefix = sanitize(backup_prefix) + return "{}-backup-{}.zip".format( + backup_prefix, time.strftime(BACKUP_DATE_TIME_FMT) + ) + + @classmethod + def _restore_supported(cls, settings): + return ( + is_os_compatible(["!windows"]) + and not settings.get_boolean(["restore_unsupported"]) + and os.environ.get("OCTOPRINT_BACKUP_RESTORE_UNSUPPORTED", False) + not in valid_boolean_trues + ) + + def _send_client_message(self, message, payload=None): + if payload is None: + payload = {} + payload["type"] = message + self._plugin_manager.send_plugin_message(self._identifier, payload) class InsufficientSpace(Exception): - pass + pass + + +def _register_custom_events(*args, **kwargs): + return ["backup_created"] + __plugin_name__ = "Backup & Restore" __plugin_author__ = "Gina Häußge" __plugin_description__ = "Backup & restore your OctoPrint settings and data" -__plugin_disabling_discouraged__ = gettext("Without this plugin you will no longer be able to backup " - "& restore your OctoPrint settings and data.") +__plugin_disabling_discouraged__ = gettext( + "Without this plugin you will no longer be able to backup " + "& restore your OctoPrint settings and data." +) __plugin_license__ = "AGPLv3" +__plugin_pythoncompat__ = ">=2.7,<4" __plugin_implementation__ = BackupPlugin() __plugin_hooks__ = { - "octoprint.server.http.routes": __plugin_implementation__.route_hook, - "octoprint.server.http.bodysize": __plugin_implementation__.bodysize_hook, - "octoprint.cli.commands": __plugin_implementation__.cli_commands_hook, - "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions + "octoprint.server.http.routes": __plugin_implementation__.route_hook, + "octoprint.server.http.bodysize": __plugin_implementation__.bodysize_hook, + "octoprint.cli.commands": __plugin_implementation__.cli_commands_hook, + "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions, + "octoprint.events.register_custom_events": _register_custom_events, + "octoprint.server.sockjs.emit": __plugin_implementation__.socket_emit_hook, +} +__plugin_helpers__ = { + "create_backup": __plugin_implementation__.create_backup_helper, + "delete_backup": __plugin_implementation__.delete_backup_helper, } diff --git a/src/octoprint/plugins/backup/static/clientjs/backup.js b/src/octoprint/plugins/backup/static/clientjs/backup.js index 5f2ee6e62..179588a7a 100644 --- a/src/octoprint/plugins/backup/static/clientjs/backup.js +++ b/src/octoprint/plugins/backup/static/clientjs/backup.js @@ -4,17 +4,17 @@ } else { factory(global.OctoPrintClient); } -})(this, function(OctoPrintClient) { - var OctoPrintBackupClient = function(base) { +})(this, function (OctoPrintClient) { + var OctoPrintBackupClient = function (base) { this.base = base; this.url = this.base.getBlueprintUrl("backup"); }; - OctoPrintBackupClient.prototype.get = function(refresh, opts) { + OctoPrintBackupClient.prototype.get = function (refresh, opts) { return this.base.get(this.url, opts); }; - OctoPrintBackupClient.prototype.createBackup = function(exclude, opts) { + OctoPrintBackupClient.prototype.createBackup = function (exclude, opts) { exclude = exclude || []; var data = { @@ -24,11 +24,11 @@ return this.base.postJson(this.url + "backup", data, opts); }; - OctoPrintBackupClient.prototype.deleteBackup = function(backup, opts) { + OctoPrintBackupClient.prototype.deleteBackup = function (backup, opts) { return this.base.delete(this.url + "backup/" + backup, opts); }; - OctoPrintBackupClient.prototype.restoreBackup = function(backup, opts) { + OctoPrintBackupClient.prototype.restoreBackup = function (backup, opts) { var data = { path: backup }; diff --git a/src/octoprint/plugins/backup/static/js/backup.js b/src/octoprint/plugins/backup/static/js/backup.js index 348860204..5f1894efd 100644 --- a/src/octoprint/plugins/backup/static/js/backup.js +++ b/src/octoprint/plugins/backup/static/js/backup.js @@ -1,4 +1,4 @@ -$(function() { +$(function () { function BackupViewModel(parameters) { var self = this; @@ -8,15 +8,14 @@ $(function() { self.backups = new ItemListHelper( "plugin.backup.backups", { - "date": function (a, b) { + date: function (a, b) { // sorts descending if (a["date"] > b["date"]) return -1; if (a["date"] < b["date"]) return 1; return 0; } }, - { - }, + {}, "date", [], [], @@ -29,14 +28,15 @@ $(function() { self.backupInProgress = ko.observable(false); self.restoreSupported = ko.observable(true); - self.backupUploadButton = $("#settings-backup-upload"); self.backupUploadData = undefined; - self.backupUploadButton.fileupload({ + self.backupUploadName = ko.observable(); + + var backupFileuploadOptions = { dataType: "json", maxNumberOfFiles: 1, autoUpload: false, headers: OctoPrint.getRequestHeaders(), - add: function(e, data) { + add: function (e, data) { if (data.files.length === 0) { // no files? ignore return false; @@ -45,12 +45,15 @@ $(function() { self.backupUploadName(data.files[0].name); self.backupUploadData = data; }, - done: function(e, data) { + done: function (e, data) { self.backupUploadName(undefined); self.backupUploadData = undefined; } - }); - self.backupUploadName = ko.observable(); + }; + + $("#settings-backup-upload").fileupload(backupFileuploadOptions); + $("#wizard-backup-upload").fileupload(backupFileuploadOptions); + self.restoreInProgress = ko.observable(false); self.restoreTitle = ko.observable(); self.restoreDialog = undefined; @@ -59,113 +62,151 @@ $(function() { self.loglines = ko.observableArray([]); - self.requestData = function() { - OctoPrint.plugins.backup.get() - .done(self.fromResponse); + self.requestData = function () { + OctoPrint.plugins.backup.get().done(self.fromResponse); }; - self.fromResponse = function(response) { + self.fromResponse = function (response) { self.backups.updateItems(response.backups); self.unknownPlugins(response.unknown_plugins); self.restoreSupported(response.restore_supported); }; - self.createBackup = function() { + self.createBackup = function () { var excluded = self.excludeFromBackup(); - OctoPrint.plugins.backup.createBackup(excluded) - .done(function() { - self.excludeFromBackup([]); - }) + OctoPrint.plugins.backup.createBackup(excluded).done(function () { + self.excludeFromBackup([]); + }); }; - self.removeBackup = function(backup) { - var perform = function() { - OctoPrint.plugins.backup.deleteBackup(backup) - .done(function() { - self.requestData(); - }); + self.removeBackup = function (backup) { + var perform = function () { + OctoPrint.plugins.backup.deleteBackup(backup).done(function () { + self.requestData(); + }); }; - showConfirmationDialog(_.sprintf(gettext("You are about to delete backup file \"%(name)s\"."), {name: backup}), - perform); + showConfirmationDialog( + _.sprintf(gettext('You are about to delete backup file "%(name)s".'), { + name: _.escape(backup) + }), + perform + ); }; - self.restoreBackup = function(backup) { + self.restoreBackup = function (backup) { if (!self.restoreSupported()) return; - var perform = function() { + var perform = function () { self.restoreInProgress(true); self.loglines.removeAll(); self.loglines.push({line: "Preparing to restore...", stream: "message"}); self.loglines.push({line: " ", stream: "message"}); - self.restoreDialog.modal({keyboard: false, backdrop: "static", show: true}); + self.restoreDialog.modal({ + keyboard: false, + backdrop: "static", + show: true + }); OctoPrint.plugins.backup.restoreBackup(backup); }; - showConfirmationDialog(_.sprintf(gettext("You are about to restore the backup file \"%(name)s\". This cannot be undone."), {name: backup}), - perform); + showConfirmationDialog( + _.sprintf( + gettext( + 'You are about to restore the backup file "%(name)s". This cannot be undone.' + ), + {name: _.escape(backup)} + ), + perform + ); }; - self.performRestoreFromUpload = function() { + self.performRestoreFromUpload = function () { if (self.backupUploadData === undefined) return; - var perform = function() { + var perform = function () { self.restoreInProgress(true); self.loglines.removeAll(); - self.loglines.push({line: "Uploading backup, this can take a while. Please wait...", stream: "message"}); + self.loglines.push({ + line: "Uploading backup, this can take a while. Please wait...", + stream: "message" + }); self.loglines.push({line: " ", stream: "message"}); - self.restoreDialog.modal({keyboard: false, backdrop: "static", show: true}); + self.restoreDialog.modal({ + keyboard: false, + backdrop: "static", + show: true + }); self.backupUploadData.submit(); }; - showConfirmationDialog(_.sprintf(gettext("You are about to upload and restore the backup file \"%(name)s\". This cannot be undone."), {name: self.backupUploadName()}), - perform); + showConfirmationDialog( + _.sprintf( + gettext( + 'You are about to upload and restore the backup file "%(name)s". This cannot be undone.' + ), + {name: _.escape(self.backupUploadName())} + ), + perform + ); }; - self.deleteUnknownPluginRecord = function() { - var perform = function() { - OctoPrint.plugins.backup.deleteUnknownPlugins() - .done(function() { - self.requestData(); - }); + self.deleteUnknownPluginRecord = function () { + var perform = function () { + OctoPrint.plugins.backup.deleteUnknownPlugins().done(function () { + self.requestData(); + }); }; - showConfirmationDialog(gettext("You are about to delete the record of plugins unknown during the last restore."), - perform); + showConfirmationDialog( + gettext( + "You are about to delete the record of plugins unknown during the last restore." + ), + perform + ); }; - self.markFilesOnPage = function() { - self.markedForBackupDeletion(_.uniq(self.markedForBackupDeletion().concat(_.map(self.backups.paginatedItems(), "name")))); + self.markFilesOnPage = function () { + self.markedForBackupDeletion( + _.uniq( + self + .markedForBackupDeletion() + .concat(_.map(self.backups.paginatedItems(), "name")) + ) + ); }; - self.markAllFiles = function() { + self.markAllFiles = function () { self.markedForBackupDeletion(_.map(self.backups.allItems, "name")); }; - self.clearMarkedFiles = function() { + self.clearMarkedFiles = function () { self.markedForBackupDeletion.removeAll(); }; - self.removeMarkedFiles = function() { - var perform = function() { - self._bulkRemove(self.markedForBackupDeletion()) - .done(function() { - self.markedForBackupDeletion.removeAll(); - }); + self.removeMarkedFiles = function () { + var perform = function () { + self._bulkRemove(self.markedForBackupDeletion()).done(function () { + self.markedForBackupDeletion.removeAll(); + }); }; - showConfirmationDialog(_.sprintf(gettext("You are about to delete %(count)d backups."), {count: self.markedForBackupDeletion().length}), - perform); + showConfirmationDialog( + _.sprintf(gettext("You are about to delete %(count)d backups."), { + count: self.markedForBackupDeletion().length + }), + perform + ); }; - self.onStartup = function() { + self.onStartup = function () { self.restoreDialog = $("#settings_plugin_backup_restoredialog"); self.restoreOutput = $("#settings_plugin_backup_restoredialog_output"); }; - self.onSettingsShown = function() { + self.onSettingsShown = function () { self.requestData(); }; - self.onDataUpdaterPluginMessage = function(plugin, data) { + self.onDataUpdaterPluginMessage = function (plugin, data) { if (plugin !== "backup") return; if (data.type === "backup_done") { @@ -182,74 +223,131 @@ $(function() { self.backupInProgress(false); new PNotify({ title: gettext("Creating the backup failed"), - text: _.sprintf(gettext("OctoPrint could not create your backup. Please consult octoprint.log for details. Error: %(error)s"), {error:data.error}), + text: _.sprintf( + gettext( + "OctoPrint could not create your backup. Please consult octoprint.log for details. Error: %(error)s" + ), + {error: _.escape(data.error)} + ), type: "error", hide: false }); } else if (data.type === "restore_started") { - self.loglines.push({line: gettext("Restoring from backup..."), stream: "message"}); + self.loglines.push({ + line: gettext("Restoring from backup..."), + stream: "message" + }); self.loglines.push({line: " ", stream: "message"}); } else if (data.type === "restore_failed") { self.loglines.push({line: " ", stream: "message"}); - self.loglines.push({line: gettext("Restore failed! Check the above output and octoprint.log for reasons as to why."), stream: "error"}); + self.loglines.push({ + line: gettext( + "Restore failed! Check the above output and octoprint.log for reasons as to why." + ), + stream: "error" + }); self.restoreInProgress(false); } else if (data.type === "restore_done") { self.loglines.push({line: " ", stream: "message"}); - self.loglines.push({line: gettext("Restore successful! The server will now be restarted!"), stream: "message"}); + self.loglines.push({ + line: gettext( + "Restore successful! The server will now be restarted!" + ), + stream: "message" + }); self.restoreInProgress(false); } else if (data.type === "installing_plugin") { self.loglines.push({line: " ", stream: "message"}); self.loglines.push({ - line: _.sprintf(gettext("Installing plugin \"%(plugin)s\"..."), {plugin: data.plugin}), + line: _.sprintf(gettext('Installing plugin "%(plugin)s"...'), { + plugin: _.escape(data.plugin) + }), stream: "message" }); } else if (data.type === "plugin_incompatible") { self.loglines.push({line: " ", stream: "message"}); self.loglines.push({ - line: _.sprintf(gettext("Cannot install plugin \"%(plugin)s\" due to it being incompatible to this OctoPrint version and/or underlying operating system"), {plugin: data.plugin.key}), + line: _.sprintf( + gettext( + 'Cannot install plugin "%(plugin)s" due to it being incompatible to this OctoPrint version and/or underlying operating system' + ), + {plugin: _.escape(data.plugin.key)} + ), stream: "stderr" }); } else if (data.type === "unknown_plugins") { if (data.plugins.length > 0) { self.loglines.push({line: " ", stream: "message"}); - self.loglines.push({line: _.sprintf(gettext("There are %(count)d plugins you'll need to install manually since they aren't registered on the repository:"), {count: data.plugins.length}), stream: "message"}); - _.each(data.plugins, function(plugin) { - self.loglines.push({line: plugin.name + ": " + plugin.url, stream: "message"}); + self.loglines.push({ + line: _.sprintf( + gettext( + "There are %(count)d plugins you'll need to install manually since they aren't registered on the repository:" + ), + {count: data.plugins.length} + ), + stream: "message" + }); + _.each(data.plugins, function (plugin) { + self.loglines.push({ + line: plugin.name + ": " + plugin.url, + stream: "message" + }); }); self.loglines.push({line: " ", stream: "message"}); self.unknownPlugins(data.plugins); } } else if (data.type === "logline") { - self.loglines.push(self._preprocessLine({line: data.line, stream: data.stream})); + self.loglines.push( + self._preprocessLine({line: data.line, stream: data.stream}) + ); self._scrollRestoreOutputToEnd(); } }; - self._scrollRestoreOutputToEnd = function() { - self.restoreOutput.scrollTop(self.restoreOutput[0].scrollHeight - self.restoreOutput.height()); + self._scrollRestoreOutputToEnd = function () { + self.restoreOutput.scrollTop( + self.restoreOutput[0].scrollHeight - self.restoreOutput.height() + ); }; self._forcedStdoutLine = /You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./; - self._preprocessLine = function(line) { + self._preprocessLine = function (line) { if (line.stream === "stderr" && line.line.match(self._forcedStdoutLine)) { line.stream = "stdout"; } return line; }; - self._bulkRemove = function(files) { + self._bulkRemove = function (files) { var title, message, handler; title = gettext("Deleting backups"); - message = _.sprintf(gettext("Deleting %(count)d backups..."), {count: files.length}); - handler = function(filename) { - return OctoPrint.plugins.backup.deleteBackup(filename) - .done(function() { - deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: filename}), true); + message = _.sprintf(gettext("Deleting %(count)d backups..."), { + count: files.length + }); + handler = function (filename) { + return OctoPrint.plugins.backup + .deleteBackup(filename) + .done(function () { + deferred.notify( + _.sprintf(gettext("Deleted %(filename)s..."), { + filename: _.escape(filename) + }), + true + ); }) - .fail(function(jqXHR) { - var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: filename}); - var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: filename, error: jqXHR.responseText}); + .fail(function (jqXHR) { + var short = _.sprintf( + gettext("Deletion of %(filename)s failed, continuing..."), + {filename: _.escape(filename)} + ); + var long = _.sprintf( + gettext("Deletion of %(filename)s failed: %(error)s"), + { + filename: _.escape(filename), + error: _.escape(jqXHR.responseText) + } + ); deferred.notify(short, long, false); }); }; @@ -267,15 +365,14 @@ $(function() { showProgressModal(options, promise); var requests = []; - _.each(files, function(filename) { + _.each(files, function (filename) { var request = handler(filename); - requests.push(request) + requests.push(request); + }); + $.when.apply($, _.map(requests, wrapPromiseWithAlways)).done(function () { + deferred.resolve(); + self.requestData(); }); - $.when.apply($, _.map(requests, wrapPromiseWithAlways)) - .done(function() { - deferred.resolve(); - self.requestData(); - }); return promise; }; @@ -284,6 +381,6 @@ $(function() { OCTOPRINT_VIEWMODELS.push({ construct: BackupViewModel, dependencies: ["loginStateViewModel", "settingsViewModel"], - elements: ["#settings_plugin_backup"] + elements: ["#settings_plugin_backup", "#wizard_plugin_backup"] }); }); diff --git a/src/octoprint/plugins/backup/templates/backup_settings.jinja2 b/src/octoprint/plugins/backup/templates/backup_settings.jinja2 index 6fcc72ca4..d6fdede80 100644 --- a/src/octoprint/plugins/backup/templates/backup_settings.jinja2 +++ b/src/octoprint/plugins/backup/templates/backup_settings.jinja2 @@ -20,7 +20,7 @@
- +