diff --git a/.editorconfig b/.editorconfig index c67a242b4..278fd7b94 100644 --- a/.editorconfig +++ b/.editorconfig @@ -8,19 +8,23 @@ end_of_line = lf charset = utf-8 insert_final_newline = true trim_trailing_whitespace = true +indent_style = space +max_line_length = 90 [**.py] -indent_style = tab indent_size = 4 -[src/octoprint/vendor/sockjs/**.py] -indent_style = space -indent_size = 4 +[**.yaml] +indent_size = 2 [src/octoprint/static/js/app/**.js] -indent_style = space indent_size = 4 -[.travis.yml] -indent_style = space +[src/octoprint/static/js/login/**.js] +indent_size = 4 + +[src/octoprint/static/js/recovery/**.js] +indent_size = 4 + +[src/octoprint/static/less/octoprint.less] indent_size = 2 diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 000000000..005b4260f --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,16 @@ +# refs to ignore during git blame, use with --ignore-revs-file + +# Switch to black formatting +1f93b2355a2816918e11a55e61b42010d15a6720 +5f2a95d154650366078b0d387e5b01427c4340c0 + +# Switch to prettier formatting +6b44909f21ee39237b7504cd31ffa6cf28275c33 + +# EOF/trailing whitespace check +#cae6730ea87da18bd6ebfeaf3e1e9cd354390939 + +# dict_to_literal, set_to_literal, not_in, flake8 fixes +#af60fd642832736966104ae71d852d745397c749 +#986312b6ae7eeadcaf620cc99d53b23794be83b6 +#b5be8f3eaec18ae2a88110a3a16c552931d493dd diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 7ee1a4b4c..0f76418a2 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -17,7 +17,7 @@ or request features within OctoPrint (not OctoPi, not any OctoPrint plugins and not unofficial OctoPrint versions). Do not seek support here ("I need help with ...", "I have a -question ..."), that belongs on the community forum at +question ..."), that belongs on the community forum at community.octoprint.org, NOT here. Mark requests with a "[Request]" prefix in the title please. For bug @@ -37,7 +37,7 @@ Thank you! #### What were you doing? - diff --git a/.github/fixtures/with_acl/config.yaml b/.github/fixtures/with_acl/config.yaml index 76cd71aad..57fadccbf 100644 --- a/.github/fixtures/with_acl/config.yaml +++ b/.github/fixtures/with_acl/config.yaml @@ -1,18 +1,18 @@ accessControl: - salt: zXmvzI3uWuTLkSPOEfA2ZLwn3f3sGUNS + salt: zXmvzI3uWuTLkSPOEfA2ZLwn3f3sGUNS plugins: - virtual_printer: - enabled: true - tracking: - enabled: false + virtual_printer: + enabled: true + tracking: + enabled: false server: - firstRun: false - onlineCheck: - enabled: false - pluginBlacklist: - enabled: false - secretKey: rrdHjvmeGMPSdYWg2NGdiM7mpz9pjekk - seenWizards: - backup: null - corewizard: 3 - tracking: null + firstRun: false + onlineCheck: + enabled: false + pluginBlacklist: + enabled: false + secretKey: rrdHjvmeGMPSdYWg2NGdiM7mpz9pjekk + seenWizards: + backup: null + corewizard: 3 + tracking: null diff --git a/.github/fixtures/with_acl/users.yaml b/.github/fixtures/with_acl/users.yaml index fac60a9d4..7ac3a086d 100644 --- a/.github/fixtures/with_acl/users.yaml +++ b/.github/fixtures/with_acl/users.yaml @@ -1,22 +1,22 @@ admin: - active: true - apikey: null - groups: + active: true + apikey: null + groups: - admins - users - password: 3033587f3b040680c77ce4fb7e8d61422878ef49a2a784227689f3b44ce66ada7f6161f8b2b037267f0d37b783a5600276eb88e1d224d24915f64e187a49a89f - permissions: [] - roles: + password: 3033587f3b040680c77ce4fb7e8d61422878ef49a2a784227689f3b44ce66ada7f6161f8b2b037267f0d37b783a5600276eb88e1d224d24915f64e187a49a89f + permissions: [] + roles: - user - admin - settings: {} + settings: {} user: - active: true - apikey: null - groups: + active: true + apikey: null + groups: - users - password: 3033587f3b040680c77ce4fb7e8d61422878ef49a2a784227689f3b44ce66ada7f6161f8b2b037267f0d37b783a5600276eb88e1d224d24915f64e187a49a89f - permissions: [] - roles: + password: 3033587f3b040680c77ce4fb7e8d61422878ef49a2a784227689f3b44ce66ada7f6161f8b2b037267f0d37b783a5600276eb88e1d224d24915f64e187a49a89f + permissions: [] + roles: - user - settings: {} + settings: {} diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 057d9d623..0e0ecd233 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,8 +1,11 @@ name: Build on: push: + pull_request: + types: [opened, sychronize, reopened] release: types: [published, prereleased] + workflow_dispatch: jobs: build: @@ -28,6 +31,70 @@ jobs: name: dist path: dist + lint-black: + name: 🧹 black + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: 🏗 Set up Python 3.7 + uses: actions/setup-python@v1 + with: + python-version: 3.7 + - name: 🏗 Set up dev dependencies + run: | + pip install -e .[develop] + - name: 🚀 Run black + run: | + pre-commit run --hook-stage manual black --all-files --show-diff-on-failure + + lint-prettier: + name: 🧹 prettier + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: 🏗 Set up Python 3.7 + uses: actions/setup-python@v1 + with: + python-version: 3.7 + - name: 🏗 Set up dev dependencies + run: | + pip install -e .[develop] + - name: 🚀 Run prettier + run: | + pre-commit run --hook-stage manual prettier --all-files --show-diff-on-failure + + lint-isort: + name: 🧹 isort + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: 🏗 Set up Python 3.7 + uses: actions/setup-python@v1 + with: + python-version: 3.7 + - name: 🏗 Set up dev dependencies + run: | + pip install -e .[develop] + - name: 🚀 Run isort + run: | + pre-commit run --hook-stage manual isort --all-files --show-diff-on-failure + + lint-flake8: + name: 🧹 Flake8 + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: 🏗 Set up Python 3.7 + uses: actions/setup-python@v1 + with: + python-version: 3.7 + - name: 🏗 Set up dev dependencies + run: | + pip install -e .[develop] + - name: 🚀 Run flake8 + run: | + pre-commit run --hook-stage manual flake8 --all-files + test-unit: name: 🧪 Unit tests strategy: @@ -47,22 +114,6 @@ jobs: run: | pytest - test-flake8: - name: 🧪 Flake8 - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: 🏗 Set up Python 3.7 - uses: actions/setup-python@v1 - with: - python-version: 3.7 - - name: 🏗 Set up test dependencies - run: | - pip install -e .[develop] - - name: 🚀 Run test suite - run: | - flake8 src/ tests setup.py - test-install: name: 🧪 Installation tests needs: build @@ -121,8 +172,8 @@ jobs: with: working-directory: tests/cypress browser: chrome - start: 'octoprint -b ${{ github.workspace }}/e2econfig serve --host 127.0.0.1 --port 5000' - wait-on: 'http://127.0.0.1:5000/online.txt' + start: "octoprint -b ${{ github.workspace }}/e2econfig serve --host 127.0.0.1 --port 5000" + wait-on: "http://127.0.0.1:5000/online.txt" - name: ⬆ Upload screenshots uses: actions/upload-artifact@v1 @@ -141,6 +192,10 @@ jobs: name: 📦 Publish on TestPyPI if: github.event_name == 'release' needs: + - lint-black + - lint-prettier + - lint-isort + - lint-flake8 - test-unit - test-install - test-e2e diff --git a/.github/workflows/issue_labeler.yml b/.github/workflows/issue_labeler.yml index a8842872f..5b6e026e7 100644 --- a/.github/workflows/issue_labeler.yml +++ b/.github/workflows/issue_labeler.yml @@ -1,10 +1,10 @@ name: "Issue Labeler" on: issues: - types: [opened, edited] + types: [opened, edited, closed, reopened] jobs: - apply-label: + label-opened-and-edited: runs-on: ubuntu-latest steps: - uses: actions/github-script@v2 @@ -12,19 +12,50 @@ jobs: github-token: ${{ secrets.GITHUB_TOKEN }} script: | let labels = []; + let setLabels = false; + context.payload.issue.labels.forEach(label => { labels.push(label.name) }); - if (context.payload.issue.title.match(/\[request\]|feature request/i)) { - labels.push('type:request'); - } - if (context.payload.issue.title.match(/\[brainstorming\]/i)) { - labels.push('type:brainstorming'); - } - if (context.payload.issue.title.match(/\[rc feedback\]/i)) { - labels.push('type:rc feedback'); + 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 (labels.length > 0) { - github.issues.addLabels({ + if (setLabels) { + github.issues.setLabels({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, diff --git a/.github/workflows/lock.yml b/.github/workflows/lock.yml index 45a57141c..b753d3fc0 100644 --- a/.github/workflows/lock.yml +++ b/.github/workflows/lock.yml @@ -1,8 +1,8 @@ -name: 'Lock outdated issues & PRs' +name: "Lock outdated issues & PRs" on: schedule: - - cron: '0 0 * * *' + - cron: "0 0 * * *" jobs: lock: @@ -12,5 +12,5 @@ jobs: uses: dessant/lock-threads@v2 with: github-token: ${{ github.token }} - issue-lock-comment: '' - pr-lock-comment: '' + issue-lock-comment: "" + pr-lock-comment: "" diff --git a/.github/workflows/test_install.yml b/.github/workflows/test_install.yml index 7904648d2..578737033 100644 --- a/.github/workflows/test_install.yml +++ b/.github/workflows/test_install.yml @@ -6,7 +6,7 @@ on: - master workflow_dispatch: schedule: - - cron: '0 */12 * * *' + - cron: "0 */12 * * *" jobs: install-branch: @@ -35,14 +35,14 @@ jobs: DISCORD_WEBHOOK: ${{ secrets.discord_webhook }} uses: Ilshidur/action-discord@master with: - args: '☑️ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ matrix.branch }}` was successful' + args: "☑️ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ matrix.branch }}` was successful" - name: 📧 Discord failure notification if: failure() env: DISCORD_WEBHOOK: ${{ secrets.discord_webhook }} uses: Ilshidur/action-discord@master with: - args: '🚫 Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ matrix.branch }}` failed' + args: "🚫 Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ matrix.branch }}` failed" install-latest: name: Install latest release @@ -69,11 +69,11 @@ jobs: DISCORD_WEBHOOK: ${{ secrets.discord_webhook }} uses: Ilshidur/action-discord@master with: - args: '☑️ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ steps.latest.outputs.release }}` was successful' + args: "☑️ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ steps.latest.outputs.release }}` was successful" - name: 📧 Discord failure notification if: failure() env: DISCORD_WEBHOOK: ${{ secrets.discord_webhook }} uses: Ilshidur/action-discord@master with: - args: '🚫 Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ steps.latest.outputs.release }}` failed' + args: "🚫 Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ steps.latest.outputs.release }}` failed" diff --git a/.github/workflows/trigger_docker.yml b/.github/workflows/trigger_docker.yml index 1d842b60c..92f93b44a 100644 --- a/.github/workflows/trigger_docker.yml +++ b/.github/workflows/trigger_docker.yml @@ -13,6 +13,6 @@ jobs: uses: peter-evans/repository-dispatch@v1 with: token: ${{ secrets.DOCKER_ACCESS_TOKEN }} - repository: OctoPrint/docker - event-type: octoprint-release - client-payload: '{"ref": "${{ github.ref }}", "sha": "${{ github.sha }}", "event-name": "${{ github.event_name }}", "event-type": "${{ github.event.action }}"}' + repository: ${{ github.repository_owner }}/octoprint-docker + event-type: "release" + client-payload: '{"tag_name": "${{ github.event.release.tag_name }}"}' diff --git a/.gitignore b/.gitignore index 4aa025b88..f330dc36c 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ src/octoprint/templates/_data/AUTHORS.md src/octoprint/templates/_data/CHANGELOG.md src/octoprint/templates/_data/SUPPORTERS.md src/octoprint/templates/_data/THIRDPARTYLICENSES.md +src/octoprint/plugins/pi_support/.local_debug docs/_build devtools @@ -35,6 +36,7 @@ pypy .eggs .mypy_cache .pytest_cache +.python-version .tox venv* diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 000000000..ea54569cb --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,44 @@ +exclude: ^(src/octoprint/vendor/|src/octoprint/static/js/lib|src/octoprint/static/vendor|tests/static/js/lib|tests/util/_files|docs/|scripts/|translations/|.*\.css|.*\.svg) +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v2.3.0 + hooks: + - id: end-of-file-fixer + - id: trailing-whitespace + - id: check-case-conflict + - id: check-json + - id: check-yaml + - id: check-toml + - id: check-merge-conflict + - id: fix-encoding-pragma + - repo: https://github.com/OctoPrint/codemods + rev: devel + hooks: + - id: codemod_dict_to_literal + args: ["--ignore", "src/octoprint/vendor"] + stages: ["manual"] + - id: codemod_set_to_literal + args: ["--ignore", "src/octoprint/vendor"] + stages: ["manual"] + - id: codemod_not_in + args: ["--ignore", "src/octoprint/vendor"] + stages: ["manual"] + - repo: https://github.com/pre-commit/mirrors-isort + rev: v5.5.4 + hooks: + - id: isort + - repo: https://github.com/psf/black + rev: 20.8b1 + hooks: + - id: black + args: ["--config", "black.toml"] + - repo: https://gitlab.com/pycqa/flake8 + rev: 3.8.1 + hooks: + - id: flake8 + additional_dependencies: + - flake8-bugbear + - repo: https://github.com/pre-commit/mirrors-prettier + rev: v2.1.2 + hooks: + - id: prettier diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 000000000..5c83e9d95 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,15 @@ +src/octoprint/static/js/lib +src/octoprint/static/vendor +src/octoprint/static/less/bootstrap +src/octoprint/static/less/font-awesome.less +*.md +*.css +**/package.json +**/package-lock.json +**/*.min.js +docs +build +dist +venv +venv2 +venv3 diff --git a/.prettierrc.yaml b/.prettierrc.yaml new file mode 100644 index 000000000..30baf7d8a --- /dev/null +++ b/.prettierrc.yaml @@ -0,0 +1,11 @@ +printWidth: 90 +tabWidth: 4 +semi: true +trailingComma: "none" +singleQuote: false +quoteProps: consistent +bracketSpacing: false +overrides: + - files: ["*.yaml", "*.yml", "*.json", "*.less"] + options: + tabWidth: 2 diff --git a/.tx/config b/.tx/config index 33bd3437b..402bc41dd 100644 --- a/.tx/config +++ b/.tx/config @@ -5,4 +5,3 @@ host = https://www.transifex.com file_filter = translations//LC_MESSAGES/messages.po source_file = translations/messages.pot source_lang = en - diff --git a/.versioneer-lookup b/.versioneer-lookup index cdea36dc7..2ca573de6 100644 --- a/.versioneer-lookup +++ b/.versioneer-lookup @@ -18,19 +18,19 @@ prerelease HEAD \(detached.* -# maintenance is currently the branch for preparation of maintenance release 1.4.3 +# maintenance is currently the branch for preparation of maintenance release 1.5.0 # so are any fix/... and improve/... branches -maintenance 1.4.3 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev -fix/.* 1.4.3 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev -improve/.* 1.4.3 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev +maintenance 1.5.0 42769dad7dda3bc0c6c94e0e8ce832af9b14a565 pep440-dev +fix/.* 1.5.0 42769dad7dda3bc0c6c94e0e8ce832af9b14a565 pep440-dev +improve/.* 1.5.0 42769dad7dda3bc0c6c94e0e8ce832af9b14a565 pep440-dev # staging/hotfix is the branch for preparation of the 1.4.2 hotfix release staging/hotfix 1.4.2 3ab84ed7e4c3aaaf71fe0f184b465f25d689f929 pep440-dev -# staging/maintenance is currently the branch for preparation of 1.4.1rc5 +# staging/maintenance is currently the branch for preparation of 1.5.0rc4 # so is regressionfix/... -staging/maintenance 1.4.1rc5 458ab91f915307857941f839a1b743430b8786a4 pep440-dev -regressionfix/.* 1.4.1rc5 458ab91f915307857941f839a1b743430b8786a4 pep440-dev +staging/maintenance 1.5.0rc4 5e7ea35239908f9ed91895751d8a8202aa76ed4b pep440-dev +regressionfix/.* 1.5.0rc4 5e7ea35239908f9ed91895751d8a8202aa76ed4b pep440-dev # staging/devel is currently inactive (but has the 1.4.1rc4 namespace) staging/devel 1.4.1rc4 650d54d1885409fa1d411eb54b9e8c7ff428910f pep440-dev diff --git a/AUTHORS.md b/AUTHORS.md index db2e16367..a50ec706b 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -121,7 +121,15 @@ date of first contribution): * [Josh Friend](https://github.com/joshfriend) * [Lachlan Cresswell](https://github.com/lachyc) * [Khoi Pham](https://github.com/osubuu) + * [Timofei Korostelev](https://github.com/chudsaviet) * [Federico Nembrini](https://github.com/FedericoNembrini) + * [Uri Shaked](https://github.com/urish) + * [Brian Vanderbusch](https://github.com/LongLiveCHIEF) + * [Charlie Powell](https://github.com/cp2004) + * [Ollis Git](https://github.com/OllisGit) + * [Sophist](https://github.com/Sophist-UK) + * [Manuel McLure](https://github.com/ManuelMcLure) + * ["j7126"](https://github.com/j7126) OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by [Daid Braam](https://github.com/daid). Parts of its communication layer and diff --git a/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..68c62a498 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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. @@ -49,7 +49,7 @@ 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 @@ -71,12 +71,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 @@ -125,17 +125,17 @@ following section *completely* and also follow the instructions in the 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 +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 +**Always use the following template, even if only adding a "me too" to an existing ticket**: ``` @@ -152,7 +152,7 @@ or request features within OctoPrint (not OctoPi, not any OctoPrint plugins and not unofficial OctoPrint versions). Do not seek support here ("I need help with ...", "I have a -question ..."), that belongs on the community forum at +question ..."), that belongs on the community forum at community.octoprint.org, NOT here. Mark requests with a "[Request]" prefix in the title please. For bug @@ -172,7 +172,7 @@ Thank you! #### What were you doing? - @@ -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 b96c113b6..855ac50b5 100644 --- a/src/octoprint/plugins/appkeys/__init__.py +++ b/src/octoprint/plugins/appkeys/__init__.py @@ -1,451 +1,495 @@ # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals -import flask -import threading -import os -import yaml import io -import time -import uuid +import os +import threading from collections import defaultdict + +import flask +import yaml from flask_babel import gettext import octoprint.plugin -from octoprint.settings import valid_boolean_trues -from octoprint.server.util.flask import restricted_access, no_firstrun_access -from octoprint.server import NO_CONTENT, current_user, admin_permission -from octoprint.util import atomic_write, monotonic_time, ResettableTimer, generate_api_key - from octoprint.access import ADMIN_GROUP from octoprint.access.permissions import Permissions +from octoprint.server import NO_CONTENT, admin_permission, current_user +from octoprint.server.util.flask import no_firstrun_access, restricted_access +from octoprint.settings import valid_boolean_trues +from octoprint.util import ResettableTimer, atomic_write, generate_api_key, monotonic_time + +CUTOFF_TIME = 10 * 60 # 10min +POLL_TIMEOUT = 5 # 5 seconds -CUTOFF_TIME = 10 * 60 # 10min -POLL_TIMEOUT = 5 # 5 seconds class AppAlreadyExists(Exception): - pass + pass class PendingDecision(object): - def __init__(self, app_id, app_token, user_id, user_token, timeout_callback=None): - self.app_id = app_id - self.app_token = app_token - self.user_id = user_id - self.user_token = user_token - self.created = monotonic_time() + def __init__(self, app_id, app_token, user_id, user_token, timeout_callback=None): + self.app_id = app_id + self.app_token = app_token + self.user_id = user_id + self.user_token = user_token + self.created = monotonic_time() - if callable(timeout_callback): - self.poll_timeout = ResettableTimer(POLL_TIMEOUT, timeout_callback, [user_token]) - self.poll_timeout.start() + if callable(timeout_callback): + self.poll_timeout = ResettableTimer( + POLL_TIMEOUT, timeout_callback, [user_token] + ) + self.poll_timeout.start() - def external(self): - return dict(app_id=self.app_id, - user_id=self.user_id, - user_token=self.user_token) + def external(self): + return { + "app_id": self.app_id, + "user_id": self.user_id, + "user_token": self.user_token, + } - def __repr__(self): - return u"PendingDecision({!r}, {!r}, {!r}, {!r}, timeout_callback=...)".format(self.app_id, - self.app_token, - self.user_id, - self.user_token) + def __repr__(self): + return "PendingDecision({!r}, {!r}, {!r}, {!r}, timeout_callback=...)".format( + self.app_id, self.app_token, self.user_id, self.user_token + ) class ReadyDecision(object): - def __init__(self, app_id, app_token, user_id): - self.app_id = app_id - self.app_token = app_token - self.user_id = user_id + def __init__(self, app_id, app_token, user_id): + self.app_id = app_id + self.app_token = app_token + self.user_id = user_id - @classmethod - def for_pending(cls, pending, user_id): - return cls(pending.app_id, pending.app_token, user_id) + @classmethod + def for_pending(cls, pending, user_id): + return cls(pending.app_id, pending.app_token, user_id) - def __repr__(self): - return u"ReadyDecision({!r}, {!r}, {!r})".format(self.app_id, - self.app_token, - self.user_id) + def __repr__(self): + return "ReadyDecision({!r}, {!r}, {!r})".format( + self.app_id, self.app_token, self.user_id + ) class ActiveKey(object): - def __init__(self, app_id, api_key, user_id): - self.app_id = app_id - self.api_key = api_key - self.user_id = user_id - - def external(self): - return 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 + def __init__(self, app_id, api_key, user_id): + self.app_id = app_id + self.api_key = api_key + self.user_id = user_id + + def external(self): + return {"app_id": self.app_id, "api_key": self.api_key, "user_id": self.user_id} + + def internal(self): + return {"app_id": self.app_id, "api_key": self.api_key} + + @classmethod + def for_internal(cls, internal, user_id): + return cls(internal["app_id"], internal["api_key"], user_id) + + def __repr__(self): + return "ActiveKey({!r}, {!r}, {!r})".format( + self.app_id, self.api_key, self.user_id + ) + + +class AppKeysPlugin( + octoprint.plugin.AssetPlugin, + octoprint.plugin.BlueprintPlugin, + octoprint.plugin.SimpleApiPlugin, + octoprint.plugin.TemplatePlugin, +): + def __init__(self): + self._pending_decisions = [] + self._pending_lock = threading.RLock() + + self._ready_decisions = [] + self._ready_lock = threading.RLock() + + self._keys = defaultdict(list) + self._keys_lock = threading.RLock() + + self._key_path = None + + def initialize(self): + self._key_path = os.path.join(self.get_plugin_data_folder(), "keys.yaml") + self._load_keys() + + # Additional permissions hook + + def get_additional_permissions(self): + return [ + { + "key": "ADMIN", + "name": "Admin access", + "description": gettext("Allows administrating all application keys"), + "roles": ["admin"], + "dangerous": True, + "default_groups": [ADMIN_GROUP], + } + ] + + ##~~ TemplatePlugin + + def get_template_configs(self): + return [ + {"type": "usersettings", "name": gettext("Application Keys")}, + {"type": "settings", "name": gettext("Application Keys")}, + ] + + ##~~ AssetPlugin + + def get_assets(self): + return { + "js": ["js/appkeys.js"], + "clientjs": ["clientjs/appkeys.js"], + "less": ["less/appkeys.less"], + "css": ["css/appkeys.css"], + } + + ##~~ BlueprintPlugin mixin + + @octoprint.plugin.BlueprintPlugin.route("/probe", methods=["GET"]) + @no_firstrun_access + def handle_probe(self): + return NO_CONTENT + + @octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"]) + @no_firstrun_access + def handle_request(self): + data = flask.request.json + if data is None: + return flask.make_response("Missing key request", 400) + + if "app" not in data: + return flask.make_response("No app name provided", 400) + + app_name = data["app"] + user_id = None + if "user" in data and data["user"]: + user_id = data["user"] + + app_token, user_token = self._add_pending_decision(app_name, user_id=user_id) + + self._plugin_manager.send_plugin_message( + self._identifier, + { + "type": "request_access", + "app_name": app_name, + "user_token": user_token, + "user_id": user_id, + }, + ) + response = flask.jsonify(app_token=app_token) + response.status_code = 201 + response.headers["Location"] = flask.url_for( + ".handle_decision_poll", app_token=app_token, _external=True + ) + return response + + @octoprint.plugin.BlueprintPlugin.route("/request/") + @no_firstrun_access + def handle_decision_poll(self, app_token): + result = self._get_pending_by_app_token(app_token) + if result: + for pending_decision in result: + pending_decision.poll_timeout.reset() + + response = flask.jsonify(message="Awaiting decision") + response.status_code = 202 + return response + + result = self._get_decision(app_token) + if result: + return flask.jsonify(api_key=result) + + return flask.abort(404) + + @octoprint.plugin.BlueprintPlugin.route("/decision/", methods=["POST"]) + @restricted_access + def handle_decision(self, user_token): + data = flask.request.json + if "decision" not in data: + return flask.make_response("No decision provided", 400) + decision = data["decision"] in valid_boolean_trues + user_id = current_user.get_name() + + result = self._set_decision(user_token, decision, user_id) + if not result: + return flask.abort(404) + + # Close access_request dialog for this request on all open OctoPrint connections + self._plugin_manager.send_plugin_message( + self._identifier, {"type": "end_request", "user_token": user_token} + ) + + return NO_CONTENT + + def is_blueprint_protected(self): + return False # No API key required to request API access + + ##~~ SimpleApiPlugin mixin + + def get_api_commands(self): + return {"generate": ["app"], "revoke": ["key"]} + + def on_api_get(self, request): + user_id = current_user.get_name() + if not user_id: + return flask.abort(403) + + if ( + request.values.get("all") in valid_boolean_trues + and Permissions.PLUGIN_APPKEYS_ADMIN.can() + ): + keys = self._all_api_keys() + else: + keys = self._api_keys_for_user(user_id) + + return flask.jsonify( + keys=list(map(lambda x: x.external(), keys)), + pending=dict( + (x.user_token, x.external()) + for x in self._get_pending_by_user_id(user_id) + ), + ) + + def on_api_command(self, command, data): + user_id = current_user.get_name() + if not user_id: + return flask.abort(403) + + if command == "revoke": + api_key = data.get("key") + if not api_key: + return flask.abort(400) + + if not admin_permission.can(): + user_for_key = self._user_for_api_key(api_key) + if user_for_key is None or user_for_key.user_id != user_id: + return flask.abort(403) + + self._delete_api_key(api_key) + + elif command == "generate": + # manual generateKey + app_name = data.get("app") + if not app_name: + return flask.abort(400) + + selected_user_id = data.get("user", user_id) + if selected_user_id != user_id and not Permissions.PLUGIN_APPKEYS_ADMIN.can(): + return flask.abort(403) + + key = self._add_api_key(selected_user_id, app_name.strip()) + return flask.jsonify(user_id=selected_user_id, app_id=app_name, api_key=key) + + return NO_CONTENT + + ##~~ key validator hook + + def validate_api_key(self, api_key, *args, **kwargs): + return self._user_for_api_key(api_key) + + ##~~ Helpers + + def _add_pending_decision(self, app_name, user_id=None): + app_token = self._generate_key() + user_token = self._generate_key() + + with self._pending_lock: + self._remove_stale_pending() + self._pending_decisions.append( + PendingDecision( + app_name, + app_token, + user_id, + user_token, + timeout_callback=self._expire_pending, + ) + ) + + return app_token, user_token + + def _get_pending_by_app_token(self, app_token): + result = [] + with self._pending_lock: + self._remove_stale_pending() + for data in self._pending_decisions: + if data.app_token == app_token: + result.append(data) + return result + + def _get_pending_by_user_id(self, user_id): + result = [] + with self._pending_lock: + self._remove_stale_pending() + for data in self._pending_decisions: + if data.user_id == user_id or data.user_id is None: + result.append(data) + return result + + def _expire_pending(self, user_token): + with self._pending_lock: + len_before = len(self._pending_decisions) + self._pending_decisions = list( + filter(lambda x: x.user_token != user_token, self._pending_decisions) + ) + len_after = len(self._pending_decisions) + + if len_after < len_before: + self._plugin_manager.send_plugin_message( + self._identifier, {"type": "end_request", "user_token": user_token} + ) + + def _remove_stale_pending(self): + with self._pending_lock: + cutoff = monotonic_time() - CUTOFF_TIME + len_before = len(self._pending_decisions) + self._pending_decisions = list( + filter(lambda x: x.created >= cutoff, self._pending_decisions) + ) + len_after = len(self._pending_decisions) + if len_after < len_before: + self._logger.info( + "Deleted {} stale pending authorization requests".format( + len_before - len_after + ) + ) + + def _set_decision(self, user_token, decision, user_id): + with self._pending_lock: + self._remove_stale_pending() + for data in self._pending_decisions: + if data.user_token == user_token and ( + data.user_id == user_id or data.user_id is None + ): + pending = data + break + else: + return False # not found + + if decision: + with self._ready_lock: + self._ready_decisions.append(ReadyDecision.for_pending(pending, user_id)) + + with self._pending_lock: + self._pending_decisions = list( + filter(lambda x: x.user_token != user_token, self._pending_decisions) + ) + + return True + + def _get_decision(self, app_token): + self._remove_stale_pending() + + with self._ready_lock: + for data in self._ready_decisions: + if data.app_token == app_token: + decision = data + break + else: + return False # not found + + api_key = self._add_api_key(decision.user_id, decision.app_id) + + with self._ready_lock: + self._ready_decisions = list( + filter(lambda x: x.app_token != app_token, self._ready_decisions) + ) + + return api_key + + def _add_api_key(self, user_id, app_name): + with self._keys_lock: + for key in self._keys[user_id]: + if key.app_id.lower() == app_name.lower(): + return key.api_key + + key = ActiveKey(app_name, self._generate_key(), user_id) + self._keys[user_id].append(key) + self._save_keys() + return key.api_key + + def _delete_api_key(self, api_key): + with self._keys_lock: + for user_id, data in self._keys.items(): + self._keys[user_id] = list(filter(lambda x: x.api_key != api_key, data)) + self._save_keys() + + def _user_for_api_key(self, api_key): + with self._keys_lock: + for user_id, data in self._keys.items(): + if any(filter(lambda x: x.api_key == api_key, data)): + 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) + ) - @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) - - 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, 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.find_user(userid=user_id) - elif user_id == "_admin" or user_id == "dummy": - # dummy = backwards compatible - return self._user_manager.anonymous_user_factory() - return None - - def _api_keys_for_user(self, user_id): - with self._keys_lock: - return self._keys[user_id] - - def _all_api_keys(self): - with self._keys_lock: - result = [] - for user_id, keys in self._keys.items(): - result += keys - return result - - def _generate_key(self): - return generate_api_key() - - def _load_keys(self): - with self._keys_lock: - if not os.path.exists(self._key_path): - return - - try: - with io.open(self._key_path, 'rt', encoding="utf-8", errors="strict") as f: - persisted = yaml.safe_load(f) - except Exception: - self._logger.exception("Could not load application keys from {}".format(self._key_path)) - return - - if not isinstance(persisted, dict): - return - - keys = defaultdict(list) - for user_id, persisted_keys in persisted.items(): - keys[user_id] = [ActiveKey.for_internal(x, user_id) for x in persisted_keys] - self._keys = keys - - def _save_keys(self): - with self._keys_lock: - to_persist = 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 48868d32f..b58adfca4 100644 --- a/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js +++ b/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js @@ -4,59 +4,80 @@ } else { factory(global.OctoPrintClient); } -})(this, function(OctoPrintClient) { - var OctoPrintAppKeysClient = function(base) { +})(this, function (OctoPrintClient) { + var OctoPrintAppKeysClient = function (base) { this.base = base; }; - OctoPrintAppKeysClient.prototype.getKeys = function(opts) { + OctoPrintAppKeysClient.prototype.getKeys = function (opts) { return this.base.simpleApiGet("appkeys", opts); }; - OctoPrintAppKeysClient.prototype.getAllKeys = function(opts) { - return this.base.get(OctoPrintClient.prototype.getSimpleApiUrl("appkeys") + "?all=true", opts); + OctoPrintAppKeysClient.prototype.getAllKeys = function (opts) { + return this.base.get( + OctoPrintClient.prototype.getSimpleApiUrl("appkeys") + "?all=true", + opts + ); }; - OctoPrintAppKeysClient.prototype.generateKey = function(app, opts) { - return this.base.simpleApiCommand("appkeys", "generate", {"app": app}, opts); + OctoPrintAppKeysClient.prototype.generateKey = function (app, opts) { + return this.base.simpleApiCommand("appkeys", "generate", {app: app}, opts); }; - OctoPrintAppKeysClient.prototype.generateKeyForUser = function(user, app, opts) { - return this.base.simpleApiCommand("appkeys", "generate", {"app": app, "user": user}, opts); + OctoPrintAppKeysClient.prototype.generateKeyForUser = function (user, app, opts) { + return this.base.simpleApiCommand( + "appkeys", + "generate", + {app: app, user: user}, + opts + ); }; - OctoPrintAppKeysClient.prototype.revokeKey = function(key, opts) { - return this.base.simpleApiCommand("appkeys", "revoke", {"key": key}, opts); + OctoPrintAppKeysClient.prototype.revokeKey = function (key, opts) { + return this.base.simpleApiCommand("appkeys", "revoke", {key: key}, opts); }; - OctoPrintAppKeysClient.prototype.decide = function(token, decision, opts) { - return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "decision/" + token, {decision: !!decision}, opts); + OctoPrintAppKeysClient.prototype.decide = function (token, decision, opts) { + return this.base.postJson( + this.base.getBlueprintUrl("appkeys") + "decision/" + token, + {decision: !!decision}, + opts + ); }; - OctoPrintAppKeysClient.prototype.probe = function(opts) { + OctoPrintAppKeysClient.prototype.probe = function (opts) { return this.base.get(this.base.getBlueprintUrl("appkeys") + "probe", opts); }; - OctoPrintAppKeysClient.prototype.request = function(app, opts) { + OctoPrintAppKeysClient.prototype.request = function (app, opts) { return this.requestForUser(app, undefined, opts); }; - OctoPrintAppKeysClient.prototype.requestForUser = function(app, user, opts) { - return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "request", {app: app, user: user}, opts); + OctoPrintAppKeysClient.prototype.requestForUser = function (app, user, opts) { + return this.base.postJson( + this.base.getBlueprintUrl("appkeys") + "request", + {app: app, user: user}, + opts + ); }; - OctoPrintAppKeysClient.prototype.checkDecision = function(token, opts) { - return this.base.get(this.base.getBlueprintUrl("appkeys") + "request/" + token, opts); + OctoPrintAppKeysClient.prototype.checkDecision = function (token, opts) { + return this.base.get( + this.base.getBlueprintUrl("appkeys") + "request/" + token, + opts + ); }; - OctoPrintAppKeysClient.prototype.authenticate = function(app, user) { + OctoPrintAppKeysClient.prototype.authenticate = function (app, user) { var deferred = $.Deferred(); var client = this; - client.probe() - .done(function() { - client.requestForUser(app, user) - .done(function(response) { + client + .probe() + .done(function () { + client + .requestForUser(app, user) + .done(function (response) { var token = response.app_token; if (!token) { // no token received, something went wrong @@ -65,9 +86,10 @@ } var interval = 1000; - var poll = function() { - client.checkDecision(token) - .done(function(response) { + var poll = function () { + client + .checkDecision(token) + .done(function (response) { if (response.api_key) { // got a decision, resolve the promise deferred.resolve(response.api_key); @@ -77,19 +99,19 @@ window.setTimeout(poll, interval); } }) - .fail(function() { + .fail(function () { // something went wrong deferred.reject(); }); }; window.setTimeout(poll, interval); }) - .fail(function() { + .fail(function () { // something went wrong deferred.reject(); }); }) - .fail(function() { + .fail(function () { // workflow unsupported deferred.reject(); }); diff --git a/src/octoprint/plugins/appkeys/static/js/appkeys.js b/src/octoprint/plugins/appkeys/static/js/appkeys.js index e26b2ae64..adfa8c3a8 100644 --- a/src/octoprint/plugins/appkeys/static/js/appkeys.js +++ b/src/octoprint/plugins/appkeys/static/js/appkeys.js @@ -1,14 +1,14 @@ -$(function() { +$(function () { function AppKeysDialogViewModel(parameters) { var self = this; self.dialog = undefined; - self.onStartup = function() { + self.onStartup = function () { self.dialog = $("#plugin_appkeys_keygenerated"); }; - self.showDialog = function(title, data) { + self.showDialog = function (title, data) { if (self.dialog === undefined) return; var qrcode = { @@ -27,17 +27,19 @@ $(function() { self.dialog.find("#plugin_appkeys_keygenerated_user").text(data.user_id); self.dialog.find("#plugin_appkeys_keygenerated_app").text(data.app_id); self.dialog.find("#plugin_appkeys_keygenerated_key_text").text(data.api_key); - self.dialog.find("#plugin_appkeys_keygenerated_key_copy") + self.dialog + .find("#plugin_appkeys_keygenerated_key_copy") .off() - .click(function() { + .click(function () { copyToClipboard(data.api_key); }); - self.dialog.find("#plugin_appkeys_keygenerated_key_qrcode") + self.dialog + .find("#plugin_appkeys_keygenerated_key_qrcode") .empty() .qrcode(qrcode); self.dialog.modal("show"); - } + }; } function UserAppKeysViewModel(parameters) { @@ -48,15 +50,14 @@ $(function() { self.keys = new ItemListHelper( "plugin.appkeys.userkeys", { - "app": function (a, b) { + app: function (a, b) { // sorts ascending if (a["app_id"].toLowerCase() < b["app_id"].toLowerCase()) return -1; if (a["app_id"].toLowerCase() > b["app_id"].toLowerCase()) return 1; return 0; } }, - { - }, + {}, "app", [], [], @@ -67,51 +68,62 @@ $(function() { self.editorApp = ko.observable(); - self.requestData = function() { - OctoPrint.plugins.appkeys.getKeys() - .done(self.fromResponse); + self.requestData = function () { + OctoPrint.plugins.appkeys.getKeys().done(self.fromResponse); }; - self.fromResponse = function(response) { + self.fromResponse = function (response) { self.keys.updateItems(response.keys); self.pending = response.pending; - _.each(self.pending, function(data, token) { + _.each(self.pending, function (data, token) { self.openRequests[token] = self.promptForAccess(data.app_id, token); - }) + }); }; - self.generateKey = function() { - return OctoPrint.plugins.appkeys.generateKey(self.editorApp()) + self.generateKey = function () { + return OctoPrint.plugins.appkeys + .generateKey(self.editorApp()) .done(self.requestData) - .done(function() { + .done(function () { self.editorApp(""); }); }; - self.revokeKey = function(key) { - var perform = function() { - OctoPrint.plugins.appkeys.revokeKey(key) - .done(self.requestData); + self.revokeKey = function (key) { + var perform = function () { + OctoPrint.plugins.appkeys.revokeKey(key).done(self.requestData); }; - showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: _.escape(key)}), - perform); + showConfirmationDialog( + _.sprintf( + gettext('You are about to revoke the application key "%(key)s".'), + {key: _.escape(key)} + ), + perform + ); }; - self.allowApp = function(token) { - return OctoPrint.plugins.appkeys.decide(token, true) - .done(self.requestData); + self.allowApp = function (token) { + return OctoPrint.plugins.appkeys.decide(token, true).done(self.requestData); }; - self.denyApp = function(token) { - return OctoPrint.plugins.appkeys.decide(token, false) - .done(self.requestData); + self.denyApp = function (token) { + return OctoPrint.plugins.appkeys.decide(token, false).done(self.requestData); }; - self.promptForAccess = function(app, token) { - var message = gettext("\"%(app)s\" has requested access to control OctoPrint through the API."); + self.promptForAccess = function (app, token) { + var message = gettext( + '"%(app)s" has requested access to control OctoPrint through the API.' + ); message = _.sprintf(message, {app: _.escape(app)}); - message = "

" + message + "

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

"; + message = + "

" + + message + + "

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

"; return new PNotify({ title: gettext("Access Request"), text: message, @@ -119,19 +131,22 @@ $(function() { icon: "fa fa-key", confirm: { confirm: true, - buttons: [{ - text: gettext("Allow"), - click: function(notice) { - self.allowApp(token); - notice.remove(); + buttons: [ + { + text: gettext("Allow"), + click: function (notice) { + self.allowApp(token); + notice.remove(); + } + }, + { + text: gettext("Deny"), + click: function (notice) { + self.denyApp(token); + notice.remove(); + } } - }, { - text: gettext("Deny"), - click: function(notice) { - self.denyApp(token); - notice.remove(); - } - }] + ] }, buttons: { sticker: false, @@ -140,15 +155,15 @@ $(function() { }); }; - self.onUserSettingsShown = function() { + self.onUserSettingsShown = function () { self.requestData(); }; - self.onUserLoggedIn = function() { + self.onUserLoggedIn = function () { self.requestData(); }; - self.onDataUpdaterPluginMessage = function(plugin, data) { + self.onDataUpdaterPluginMessage = function (plugin, data) { if (plugin !== "appkeys") { return; } @@ -169,7 +184,6 @@ $(function() { } self.openRequests[token] = self.promptForAccess(app, token); - } else if (data.type === "end_request") { token = data.user_token; @@ -178,7 +192,7 @@ $(function() { if (self.openRequests[token].state !== "closed") { self.openRequests[token].remove(); } - delete self.openRequests[token] + delete self.openRequests[token]; } } }; @@ -193,7 +207,7 @@ $(function() { self.keys = new ItemListHelper( "plugin.appkeys.allkeys", { - "user_app": function (a, b) { + user_app: function (a, b) { // sorts ascending, first by user, then by app if (a["user_id"] > b["user_id"]) return 1; if (a["user_id"] < b["user_id"]) return -1; @@ -204,8 +218,7 @@ $(function() { return 0; } }, - { - }, + {}, "user_app", [], [], @@ -219,29 +232,28 @@ $(function() { self.markedForDeletion = ko.observableArray([]); - self.onSettingsShown = function() { + self.onSettingsShown = function () { self.requestData(); self.editorUser(self.loginState.username()); self.editorApp(""); }; - self.onUserLoggedIn = function() { + self.onUserLoggedIn = function () { self.requestData(); self.editorUser(self.loginState.username()); self.editorApp(""); }; - self.requestData = function() { - OctoPrint.plugins.appkeys.getAllKeys() - .done(self.fromResponse); + self.requestData = function () { + OctoPrint.plugins.appkeys.getAllKeys().done(self.fromResponse); }; - self.fromResponse = function(response) { + self.fromResponse = function (response) { self.keys.updateItems(response.keys); var users = []; var apps = []; - _.each(response.keys, function(key) { + _.each(response.keys, function (key) { users.push(key.user_id); apps.push(key.app_id.toLowerCase()); }); @@ -255,77 +267,116 @@ $(function() { self.apps(apps); }; - self.generateKey = function() { - return OctoPrint.plugins.appkeys.generateKeyForUser(self.editorUser(), self.editorApp()) + self.generateKey = function () { + return OctoPrint.plugins.appkeys + .generateKeyForUser(self.editorUser(), self.editorApp()) .done(self.requestData) - .done(function() { + .done(function () { self.editorUser(self.loginState.username()); self.editorApp(""); }) - .done(function(data) { + .done(function (data) { self.dialog.showDialog(gettext("New key generated!"), data); }); - } + }; - self.revokeKey = function(key) { - var perform = function() { - OctoPrint.plugins.appkeys.revokeKey(key) - .done(self.requestData); + self.revokeKey = function (key) { + var perform = function () { + OctoPrint.plugins.appkeys.revokeKey(key).done(self.requestData); }; - showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: _.escape(key)}), - perform); + showConfirmationDialog( + _.sprintf( + gettext('You are about to revoke the application key "%(key)s".'), + {key: _.escape(key)} + ), + perform + ); }; - self.revokeMarked = function() { - var perform = function() { - self._bulkRevoke(self.markedForDeletion()) - .done(function() { - self.markedForDeletion.removeAll(); - }); + self.revokeMarked = function () { + var perform = function () { + self._bulkRevoke(self.markedForDeletion()).done(function () { + self.markedForDeletion.removeAll(); + }); }; - showConfirmationDialog(_.sprintf(gettext("You are about to revoke %(count)d application keys."), {count: self.markedForDeletion().length}), - perform); + showConfirmationDialog( + _.sprintf( + gettext("You are about to revoke %(count)d application keys."), + {count: self.markedForDeletion().length} + ), + perform + ); }; - self.markAllOnPageForDeletion = function() { - self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(self.keys.paginatedItems(), "api_key")))); + self.markAllOnPageForDeletion = function () { + self.markedForDeletion( + _.uniq( + self + .markedForDeletion() + .concat(_.map(self.keys.paginatedItems(), "api_key")) + ) + ); }; - self.markAllForDeletion = function() { + self.markAllForDeletion = function () { self.markedForDeletion(_.uniq(_.map(self.keys.allItems, "api_key"))); }; - self.markAllByUserForDeletion = function(user) { - self.markAllByFilterForDeletion(function(e) { return (e.user_id === user); }); + self.markAllByUserForDeletion = function (user) { + self.markAllByFilterForDeletion(function (e) { + return e.user_id === user; + }); }; - self.markAllByAppForDeletion = function(app) { - self.markAllByFilterForDeletion(function(e) { return (e.app_id.toLowerCase() === app); }) + self.markAllByAppForDeletion = function (app) { + self.markAllByFilterForDeletion(function (e) { + return e.app_id.toLowerCase() === app; + }); }; - self.markAllByFilterForDeletion = function(filter) { - self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(_.filter(self.keys.allItems, filter), "api_key")))); + self.markAllByFilterForDeletion = function (filter) { + self.markedForDeletion( + _.uniq( + self + .markedForDeletion() + .concat(_.map(_.filter(self.keys.allItems, filter), "api_key")) + ) + ); }; - self.clearMarked = function() { + self.clearMarked = function () { self.markedForDeletion.removeAll(); }; - self._bulkRevoke = function(keys) { + self._bulkRevoke = function (keys) { var title, message, handler; title = gettext("Revoking application keys"); - message = _.sprintf(gettext("Revoking %(count)d application keys..."), {count: keys.length}); - handler = function(key) { - return OctoPrint.plugins.appkeys.revokeKey(key) - .done(function() { - deferred.notify(_.sprintf(gettext("Revoked %(key)s..."), {key: _.escape(key)}), true); + message = _.sprintf(gettext("Revoking %(count)d application keys..."), { + count: keys.length + }); + handler = function (key) { + return OctoPrint.plugins.appkeys + .revokeKey(key) + .done(function () { + deferred.notify( + _.sprintf(gettext("Revoked %(key)s..."), { + key: _.escape(key) + }), + true + ); }) - .fail(function(jqXHR) { - var short = _.sprintf(gettext("Revocation of %(key)s failed, continuing..."), {key: _.escape(key)}); - var long = _.sprintf(gettext("Deletion of %(key)s failed: %(error)s"), {key: _.escape(key), error: _.escape(jqXHR.responseText)}); + .fail(function (jqXHR) { + var short = _.sprintf( + gettext("Revocation of %(key)s failed, continuing..."), + {key: _.escape(key)} + ); + var long = _.sprintf( + gettext("Deletion of %(key)s failed: %(error)s"), + {key: _.escape(key), error: _.escape(jqXHR.responseText)} + ); deferred.notify(short, long, false); }); }; @@ -343,25 +394,20 @@ $(function() { showProgressModal(options, promise); var requests = []; - _.each(keys, function(key) { + _.each(keys, function (key) { var request = handler(key); - requests.push(request) + requests.push(request); + }); + $.when.apply($, _.map(requests, wrapPromiseWithAlways)).done(function () { + deferred.resolve(); + self.requestData(); }); - $.when.apply($, _.map(requests, wrapPromiseWithAlways)) - .done(function() { - deferred.resolve(); - self.requestData(); - }); return promise; }; } - OCTOPRINT_VIEWMODELS.push([ - AppKeysDialogViewModel, - [], - [] - ]); + OCTOPRINT_VIEWMODELS.push([AppKeysDialogViewModel, [], []]); OCTOPRINT_VIEWMODELS.push([ UserAppKeysViewModel, @@ -373,5 +419,5 @@ $(function() { AllAppKeysViewModel, ["appKeysDialogViewModel", "loginStateViewModel", "accessViewModel"], ["#settings_plugin_appkeys"] - ]) + ]); }); diff --git a/src/octoprint/plugins/appkeys/templates/appkeys.jinja2 b/src/octoprint/plugins/appkeys/templates/appkeys.jinja2 index 6bd592977..92ab98920 100644 --- a/src/octoprint/plugins/appkeys/templates/appkeys.jinja2 +++ b/src/octoprint/plugins/appkeys/templates/appkeys.jinja2 @@ -4,7 +4,7 @@