diff --git a/.editorconfig b/.editorconfig index bf65494f2..c67a242b4 100644 --- a/.editorconfig +++ b/.editorconfig @@ -13,6 +13,10 @@ trim_trailing_whitespace = true indent_style = tab indent_size = 4 +[src/octoprint/vendor/sockjs/**.py] +indent_style = space +indent_size = 4 + [src/octoprint/static/js/app/**.js] indent_style = space indent_size = 4 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/fixtures/with_acl/config.yaml b/.github/fixtures/with_acl/config.yaml new file mode 100644 index 000000000..76cd71aad --- /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..fac60a9d4 --- /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/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 000000000..830ddfbd7 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,175 @@ +name: Build +on: + push: + release: + types: [published, prereleased] + +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 + + test-unit: + name: 🧪 Unit tests + strategy: + matrix: + python: ["2.7", "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-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 + strategy: + matrix: + python: ["2.7", "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: + - 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/lock.yml b/.github/workflows/lock.yml new file mode 100644 index 000000000..45a57141c --- /dev/null +++ b/.github/workflows/lock.yml @@ -0,0 +1,16 @@ +name: 'Lock outdated issues & PRs' + +on: + schedule: + - cron: '0 0 * * *' + +jobs: + lock: + runs-on: ubuntu-latest + steps: + - name: 🔒 Lock issues & PRs closed over a year + uses: dessant/lock-threads@v2 + with: + github-token: ${{ github.token }} + issue-lock-comment: '' + pr-lock-comment: '' diff --git a/.github/workflows/test_install.yml b/.github/workflows/test_install.yml new file mode 100644 index 000000000..98c3d4d01 --- /dev/null +++ b/.github/workflows/test_install.yml @@ -0,0 +1,75 @@ +name: Test install of branches and latest release twice per day + +on: + schedule: + - cron: '0 */12 * * *' + +jobs: + install-branch: + name: Install branch + strategy: + matrix: + os: ["ubuntu-latest"] + python: ["2.7", "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: ["2.7", "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_docs.yml b/.github/workflows/trigger_docs.yml new file mode 100644 index 000000000..6a4fc565c --- /dev/null +++ b/.github/workflows/trigger_docs.yml @@ -0,0 +1,19 @@ +name: Trigger doc build +on: + push: + release: + types: + - released + - prereleased + +jobs: + trigger: + runs-on: ubuntu-latest + 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..4aa025b88 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 +docs/_build devtools @@ -19,24 +20,26 @@ linux-Cura-* 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 +.tox + +venv* +testconf* + +node_modules +tests/cypress/screenshots +tests/cypress/videos 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/AUTHORS.md b/AUTHORS.md index 8398e0cb5..db2e16367 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -115,6 +115,13 @@ date of first contribution): * [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) + * [Federico Nembrini](https://github.com/FedericoNembrini) 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 c7a906db4..ece6d517e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,4 @@ # Changelog -See [the releases on Github](https://github.com/foosel/OctoPrint/releases) for detailed changelogs for all releases +See [the releases on Github](https://github.com/OctoPrint/OctoPrint/releases) for detailed changelogs for all releases and release candidates. diff --git a/README.md b/README.md index 0e4ac5f3a..2aba60f76 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,11 @@ # 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) +![GitHub release](https://img.shields.io/github/v/release/OctoPrint/OctoPrint?logo=github&logoColor=white) +![PyPI](https://img.shields.io/pypi/v/OctoPrint?logo=python&logoColor=white) +![Build status](https://img.shields.io/github/workflow/status/OctoPrint/OctoPrint/Build) +[![Community Forum](https://img.shields.io/discourse/users?logo=discourse&logoColor=white&server=https%3A%2F%2Fcommunity.octoprint.org)](https://community.octoprint.org) +[![Discord](https://img.shields.io/discord/704958479194128507?label=discord&logo=discord&logoColor=white)](https://discord.octoprint.org) [![Twitter Follow](https://img.shields.io/twitter/follow/OctoPrint3d.svg?style=social&label=Follow)](https://twitter.com/OctoPrint3d) @@ -13,9 +14,9 @@ and released under the [GNU Affero General Public License V3](http://www.gnu.org 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). @@ -30,17 +31,17 @@ If you enjoy OctoPrint, please consider becoming a regular supporter!** 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,12 +49,12 @@ 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) which is a custom SD card image that includes OctoPrint plus dependencies. @@ -61,12 +62,18 @@ 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 2.7, 3.6 or 3.7, pip and virtualenv and their dependencies set up on your system: -1. Checkout OctoPrint: `git clone https://github.com/foosel/OctoPrint.git` +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` + +Or alternatively, for an install from source: + +1. Checkout OctoPrint: `git clone https://github.com/OctoPrint/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`. +3. Create a user-owned virtual environment therein: `virtualenv venv` 4. Install OctoPrint *into that virtual environment*: `./venv/bin/pip install .` You may then start the OctoPrint server via `/path/to/OctoPrint/venv/bin/octoprint`, see [Usage](#usage) @@ -78,11 +85,7 @@ 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`: - - pip install . - -You should do this every time after pulling from the repository, since the dependencies may have changed. +OctoPrint via `pip`. OctoPrint currently supports Python 2.7, 3.6 and 3.7. @@ -90,7 +93,7 @@ OctoPrint currently supports Python 2.7, 3.6 and 3.7. 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/SUPPORTERS.md b/SUPPORTERS.md index a06ccfb07..8876adb44 100644 --- a/SUPPORTERS.md +++ b/SUPPORTERS.md @@ -1,14 +1,14 @@ -# 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 - * Alex Krilov * Andrew Moorby * Arnljot Arntsen + * Ash King * BigTreeTech * Boris Hussein * Brad Jackson @@ -27,13 +27,15 @@ thanks to everyone who contributed! * Hog Duske * Hugh Blemings * jean-claude migneault - * Jeff Renfer - * Jeremiah Avery + * Jeremy Cole + * Joe Pasqua + * John Robinson * Joshua Wills * Justin Kaufman * Kaile Riser * Kale Stedman * Kazuhiro Ogura + * Kelly C McNiece * Kenneth Jiang * Kurt Wubbels * Kyle Menigoz @@ -41,7 +43,7 @@ thanks to everyone who contributed! * Lee Dohm * Makespace Madrid * Mark Walker - * Martin Majewski + * Marvin Nahmias * Michael Aumock * Miles Flavel * Mosaic Manufacturing @@ -49,6 +51,7 @@ thanks to everyone who contributed! * Patrick Glyré * Patrick McGinnis * Prof Yuh Wen Chen + * Raise3D * Randy C. Will * Ranjib Dey * Richard Michaud @@ -56,11 +59,11 @@ thanks to everyone who contributed! * Robert Gusek * Ronald Griehsler * Sacha Telgenhof - * Simon Hallam + * Sebastien Andrivet * Stefan Krister * Steve Thompson + * Stewart Danos * Sven Mueller - * Trent Shumay * Ulrich Kempken -and 1741 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [Github Sponsors](https://github.com/users/foosel/sponsorship)! +and 1886 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [Github Sponsors](https://github.com/users/foosel/sponsorship)! \ No newline at end of file diff --git a/THIRDPARTYLICENSES.md b/THIRDPARTYLICENSES.md index 568a14bc5..594251edb 100644 --- a/THIRDPARTYLICENSES.md +++ b/THIRDPARTYLICENSES.md @@ -24,10 +24,12 @@ * [LESS](http://lesscss.org): Apache License 2.0 * [lodash](https://lodash.com): MIT * [Loglevel](https://github.com/pimterry/loglevel): 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 @@ -39,12 +41,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 @@ -58,19 +62,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/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/files.rst b/docs/api/files.rst index 618567df9..85c479c1c 100644 --- a/docs/api/files.rst +++ b/docs/api/files.rst @@ -572,7 +572,8 @@ 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. @@ -768,7 +769,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. diff --git a/docs/api/util.rst b/docs/api/util.rst index b4e33a831..3dde7f6ca 100644 --- a/docs/api/util.rst +++ b/docs/api/util.rst @@ -99,6 +99,14 @@ 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! + 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! + Requires the ``ADMIN`` permission. **Example 1** @@ -286,6 +294,32 @@ 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 + } + :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 +336,7 @@ 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 :statuscode 200: No error occurred .. _sec-api-util-datamodel: @@ -409,3 +444,25 @@ 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. diff --git a/docs/bundledplugins/action_command_notification.rst b/docs/bundledplugins/action_command_notification.rst new file mode 100644 index 000000000..aff4d75be --- /dev/null +++ b/docs/bundledplugins/action_command_notification.rst @@ -0,0 +1,61 @@ +.. _sec-bundledplugins-action_command_notification: + +Action Command Notification support +=================================== + +The OctoPrint Action Command Notification Support Plugin comes bundled with OctoPrint (starting with 1.4.1). + +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..247f741ff 100644 --- a/docs/bundledplugins/action_command_prompt.rst +++ b/docs/bundledplugins/action_command_prompt.rst @@ -19,17 +19,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 +26,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 +64,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 @@ -103,6 +96,8 @@ This would produce the following output: If the user selects "Abort print", OctoPrint will send ``2`` as selected choice. +.. _sec-bundledplugins-action_command_prompt-sourcecode: + Source code ----------- diff --git a/docs/bundledplugins/file_check.rst b/docs/bundledplugins/file_check.rst new file mode 100644 index 000000000..814066697 --- /dev/null +++ b/docs/bundledplugins/file_check.rst @@ -0,0 +1,7 @@ +.. _sec-bundledplugins-file_check: + +File Check +========== + +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..c7e95facc --- /dev/null +++ b/docs/bundledplugins/firmware_check.rst @@ -0,0 +1,7 @@ +.. _sec-bundledplugins-firmware_check: + +Firmware Check +============== + +The firmware 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/gcodeviewer.rst b/docs/bundledplugins/gcodeviewer.rst new file mode 100644 index 000000000..2531f7533 --- /dev/null +++ b/docs/bundledplugins/gcodeviewer.rst @@ -0,0 +1,35 @@ +.. _sec-bundledplugins-gcodeviewer: + +GCode Viewer Plugin +=================== + +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 206aaab57..d26c4fa87 100644 --- a/docs/bundledplugins/index.rst +++ b/docs/bundledplugins/index.rst @@ -7,15 +7,19 @@ Bundled Plugins .. toctree:: :maxdepth: 2 + action_command_notification.rst action_command_prompt.rst announcements.rst - tracking.rst appkeys.rst backup.rst discovery.rst errortracking.rst + file_check.rst + firmware_check.rst + gcodeviewer.rst logging.rst loginui.rst pluginmanager.rst printer_safety_check.rst softwareupdate.rst + tracking.rst 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 d72735ec6..5ee80148f 100644 --- a/docs/bundledplugins/softwareupdate.rst +++ b/docs/bundledplugins/softwareupdate.rst @@ -37,9 +37,9 @@ There you can adjust the following settings: * **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 `_. + "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 `_). + (``/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. * **Version cache TTL**: The "time to live" of the cache OctoPrint will use to temporarily persist the version information @@ -133,7 +133,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 @@ -146,6 +146,9 @@ Configuring the Plugin 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: @@ -196,10 +199,28 @@ Version checks * ``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. + * ``pypi_release``: Checks `pypi.org `_ for new releases of a specified package. Additional + config parameters: * ``package``: (mandatory) Name of the package which to check. + * ``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. + + * ``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 + * ``command_line``: Uses a provided script to determine whether an update is available. Additional config parameters: @@ -233,20 +254,42 @@ Version checks 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. @@ -273,7 +316,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 @@ -329,6 +372,37 @@ 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-events: Events diff --git a/docs/conf.py b/docs/conf.py index 9de6f2608..e774cb6bb 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -35,8 +35,11 @@ needs_sphinx = '1.3' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['codeblockext', 'onlineinclude', 'sphinx.ext.todo', 'sphinx.ext.autodoc', 'sphinxcontrib.httpdomain', - 'sphinx.ext.napoleon', 'sphinxcontrib.mermaid'] + 'sphinx.ext.napoleon', 'sphinxcontrib.mermaid', 'sphinx.ext.intersphinx'] todo_include_todos = True +intersphinx_mapping = {'python': ('https://docs.python.org/3', None), + 'python2': ('https://docs.python.org/2', None), + 'pyserial': ('https://pythonhosted.org/pyserial', None)} # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] @@ -104,13 +107,9 @@ 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' - -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()] +import sphinx_rtd_theme +html_theme = 'sphinx_rtd_theme' +html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # The theme to use for HTML and HTML Help pages. See the documentation for # a list of built-in themes. @@ -146,7 +145,7 @@ if not on_rtd: # only import and set the theme if we're building docs locally 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. @@ -190,7 +189,7 @@ def setup(app): #html_file_suffix = None # Output file base name for HTML help builder. -htmlhelp_basename = 'OctoPrintdoc' +htmlhelp_basename = 'OctoPrintDoc' # -- Options for LaTeX output -------------------------------------------------- diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index 64001bde6..f96751326 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -293,174 +293,6 @@ The following settings are only relevant to you if you want to do OctoPrint deve # enable or disable the loading animation showLoadingAnimation: 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 - .. _sec-configuration-config_yaml-estimation: Estimation @@ -1025,6 +857,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 @@ -1126,9 +977,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 diff --git a/docs/configuration/logging_yaml.rst b/docs/configuration/logging_yaml.rst index bb68c2028..b0de4ef19 100644 --- a/docs/configuration/logging_yaml.rst +++ b/docs/configuration/logging_yaml.rst @@ -81,8 +81,8 @@ used for the ``serial.log`` and the ``console`` handler used for the output to s maxBytes: 2097152 # 2 * 1024 * 1024 = 2 MB in bytes filename: /path/to/octoprints/logs/serial.log -You can find more information on the used logging handlers in the -`Python documentation on logging handlers `_. +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/environment.rst b/docs/development/environment.rst index 71c953de3..7eeed2f4c 100644 --- a/docs/development/environment.rst +++ b/docs/development/environment.rst @@ -19,7 +19,7 @@ below. * Checkout the OctoPrint sources from their Git repository: - * ``git clone -b devel https://github.com/foosel/OctoPrint.git`` + * ``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 @@ -29,6 +29,12 @@ below. * PY2: ``virtualenv --python=python2 venv2`` * PY3: ``virtualenv --python=python3 venv3`` + .. note:: + + This assumes that `python2` and `python3` are binaries available directly on your ``PATH``. If your Python 2 and 3 + binaries cannot be found on your ``PATH`` like this you'll need to specify the full paths to them here, + e.g. ``virtualenv --python=/path/to/python2/bin/python venv2`` + * Activate one of the virtual environments: * PY2: ``source venv2/bin/activate`` (Linux, macOS) or ``source venv2/Scripts/activate`` (Git Bash under Windows, see below) @@ -41,7 +47,7 @@ below. * Install OctoPrint in `"editable" mode `_, including its regular *and* development and plugin development dependencies: - * ``pip install -e .[develop,plugins]`` + * ``pip install -e '.[develop,plugins]'`` When the virtual environment is activated you can then: @@ -86,7 +92,7 @@ installed: .. todo:: Using a Linux distribution that doesn't use ``apt`` or ``zypper``? Please send a - `Pull Request `_ to get the necessary + `Pull Request `_ to get the necessary steps into this guide! Then: @@ -94,7 +100,7 @@ Then: .. code-block:: none cd ~/devel - git clone -b devel https://github.com/foosel/OctoPrint.git + git clone -b devel https://github.com/OctoPrint/OctoPrint.git cd OctoPrint virtualenv venv source ./venv/bin/activate @@ -131,7 +137,7 @@ 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 source ./venv/Scripts/activate @@ -145,7 +151,7 @@ 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:: @@ -178,7 +184,7 @@ 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 @@ -197,7 +203,7 @@ IDE Setup .. 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: @@ -214,22 +220,29 @@ PyCharm - 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`` + * Module parameters: ``serve --debug`` * Project: ``OctoPrint`` * Python interpreter: the ``venv`` local virtual environment * 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$`` + + - Add Run/Debug Configuration, select "Python tests" and therein "pytest": + + * Name: OctoPrint pytest + * Target: Custom * Project: ``OctoPrint`` * Python interpreter: the ``venv`` local virtual environment * Working directory: the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``) diff --git a/docs/development/index.rst b/docs/development/index.rst index 8b3038592..d8e330da9 100644 --- a/docs/development/index.rst +++ b/docs/development/index.rst @@ -9,3 +9,4 @@ Development environment.rst virtual_printer.rst + profiling.rst 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/virtual_printer.rst b/docs/development/virtual_printer.rst index ebf931113..48f57ede3 100644 --- a/docs/development/virtual_printer.rst +++ b/docs/development/virtual_printer.rst @@ -12,24 +12,7 @@ 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: @@ -40,6 +23,178 @@ The config.yaml file has many configuration options for the virtual printer that 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 + + # 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 + .. _sec-development-virtual-printer-log: Log file diff --git a/docs/events/index.rst b/docs/events/index.rst index 224656b3f..fe24e847f 100644 --- a/docs/events/index.rst +++ b/docs/events/index.rst @@ -197,12 +197,15 @@ 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 diff --git a/docs/features/custom_controls.rst b/docs/features/custom_controls.rst index f130596c1..fa69cc435 100644 --- a/docs/features/custom_controls.rst +++ b/docs/features/custom_controls.rst @@ -210,12 +210,12 @@ 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. * - ``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.]+)``). diff --git a/docs/features/gcode_scripts.rst b/docs/features/gcode_scripts.rst index d07a609f8..6351fef37 100644 --- a/docs/features/gcode_scripts.rst +++ b/docs/features/gcode_scripts.rst @@ -18,13 +18,7 @@ simple "send-as-is" scripts but making use of a full blown templating language i 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: @@ -250,7 +244,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..8e8e26765 100644 --- a/docs/features/plugins.rst +++ b/docs/features/plugins.rst @@ -28,7 +28,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/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-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/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/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/gettingstarted.rst b/docs/plugins/gettingstarted.rst index 7a4090b76..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 @@ -143,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 @@ -1091,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 4c5361ac2..ebc8859e1 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. @@ -215,7 +215,7 @@ octoprint.access.permissions 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``, + 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 _. @@ -472,12 +472,12 @@ 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) @@ -890,6 +890,25 @@ 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) + + 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 @@ -907,21 +926,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:** 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/python3_migration.rst b/docs/plugins/python3_migration.rst index 90f08149e..170e039e7 100644 --- a/docs/plugins/python3_migration.rst +++ b/docs/plugins/python3_migration.rst @@ -70,7 +70,7 @@ Then create an editable install of your plugin, start the server and start testi .. note:: - If you want to migrate your existing OctoPrint install *on OctoPi* to Python 3, I suggest to first make a + 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): @@ -79,7 +79,7 @@ Then create an editable install of your plugin, start the server and start testi mv ~/oprint ~/oprint.py2 virtualenv --python=/usr/bin/python3 oprint source ~/oprint/bin/activate - pip install "OctoPrint>=1.4.0rc1" + pip install "OctoPrint>=1.4.0" sudo service octoprint restart .. _sec-plugins-python3-markup: @@ -218,7 +218,7 @@ 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-imports: +.. _sec-plugins-python3-pitfalls-absolute-imports: Absolute imports ................ @@ -246,6 +246,33 @@ 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 @@ -312,13 +339,14 @@ As a summary, follow this checklist to migrate your plugin to be compatible to b * 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, update your - registration file in the Official Plugin Repository to include the correct Python compatibility information as well: + * 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,<3" + python: ">=2.7,<4" .. _sec-plugins-python3-furtherreading: diff --git a/docs/plugins/viewmodels.rst b/docs/plugins/viewmodels.rst index a5fc5bd46..33d28e9a8 100644 --- a/docs/plugins/viewmodels.rst +++ b/docs/plugins/viewmodels.rst @@ -438,7 +438,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..24913f1ce 100644 --- a/docs/sphinxext/codeblockext.py +++ b/docs/sphinxext/codeblockext.py @@ -12,7 +12,7 @@ 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,6 +22,10 @@ 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. @@ -30,7 +34,7 @@ def _merge_dict(a, b): result.update(b) return result -class literal_block_ext(General, FixedTextElement): +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. @@ -59,6 +63,7 @@ class CodeBlockExt(CodeBlock): option_spec = _merge_dict(CodeBlock.option_spec, dict(whitespace=directives.flag)) def run(self): + # type: () -> List[nodes.Node] # get result from parent implementation code_block = CodeBlock.run(self) @@ -67,7 +72,7 @@ class CodeBlockExt(CodeBlock): Recursive method to turn all literal blocks located within a node into :class:`literal_block_ext`. """ - if isinstance(node, container): + if isinstance(node, nodes.container): # container node => handle all children children = [] for child in node.children: @@ -75,7 +80,7 @@ class CodeBlockExt(CodeBlock): node.children = children return node - elif isinstance(node, literal_block): + elif isinstance(node, nodes.literal_block): # literal block => replace it return self._wrap_literal_block(node) diff --git a/docs/sphinxext/onlineinclude.py b/docs/sphinxext/onlineinclude.py index d60b9af4b..ed4a1742a 100644 --- a/docs/sphinxext/onlineinclude.py +++ b/docs/sphinxext/onlineinclude.py @@ -12,6 +12,7 @@ from contextlib import closing 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 @@ -53,22 +54,20 @@ class OnlineIncludeDirective(LiteralInclude): if not document.settings.file_insertion_enabled: return [document.reporter.warning('File insertion disabled', line=self.lineno)] - env = document.settings.env - # convert options['diff'] to absolute path if 'diff' in self.options: - _, path = env.relfn2path(self.options['diff']) + _, path = self.env.relfn2path(self.options['diff']) self.options['diff'] = path try: location = self.state_machine.get_source_and_line(self.lineno) url = self.arguments[0] - reader = OnlineIncludeReader(url, self.options, env.config) + reader = OnlineIncludeReader(url, self.options, self.config) text, lines = reader.read(location=location) retnode = nodes.literal_block(text, text, source=url) - self.set_source_info(retnode) + set_source_info(self, retnode) if self.options.get('diff'): # if diff is set, set udiff retnode['language'] = 'udiff' elif 'language' in self.options: diff --git a/scripts/README.md b/scripts/README.md index 51da00e50..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/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..14f5d7f4b 100644 --- a/scripts/octoprint.service +++ b/scripts/octoprint.service @@ -4,6 +4,8 @@ After=network-online.target Wants=network-online.target [Service] +Environment="LC_ALL=C.UTF-8" +Environment="LANG=C.UTF-8" Type=simple User=pi ExecStart=/home/pi/OctoPrint/venv/bin/octoprint diff --git a/setup.cfg b/setup.cfg index 24ae4b6df..6f5421829 100644 --- a/setup.cfg +++ b/setup.cfg @@ -12,3 +12,13 @@ versionfile_build = octoprint/_version.py tag_prefix = parentdir_prefix = lookupfile = .versioneer-lookup + +[flake8] +ignore = + D + E + W + F401 + F523 +exclude = + src/octoprint/vendor diff --git a/setup.py b/setup.py index 6724f3ff4..2937c4385 100644 --- a/setup.py +++ b/setup.py @@ -1,7 +1,6 @@ #!/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 @@ -19,66 +18,71 @@ PYTHON_REQUIRES = ">=2.7.9, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.* # Requirements for setup.py SETUP_REQUIRES = [ - "markdown>=3.1,<3.2", + "markdown>=3.1,<3.2" # newer versions require Python 3 ] # Requirements for our application INSTALL_REQUIRES = [ + # additional OctoPrint plugins that are maintained on a different release cycle + "OctoPrint-FirmwareCheck>=2020.06.22", + "OctoPrint-FileCheck>=2020.06.22", + # 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 + "markupsafe>=1.1,<2.0", # Jinja dependency, newer versions require Python 3 + "tornado==5.1.1", # newer versions require Python 3 + "markdown>=3.1,<3.2", # newer versions require Python 3 "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-Babel>=0.12,<0.13", - "Flask-Assets>=0.12,<0.13", - "blinker>=1.4,<1.5", # dependency of the now vendor bundled flask_principal - "werkzeug>=0.16,<0.17", - "cachelib>=0.1,<0.2", - "PyYAML>=5.1,<6", - "markdown>=3.1,<3.2", - "pyserial>=3.4,<3.5", - "netaddr>=0.7.19,<0.8", - "watchdog>=0.9.0,<0.10", + "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", + "cachelib>=0.1,<1", + "PyYAML>=5.3.1,<6", + "pyserial>=3.4,<4", + "netaddr>=0.7.19,<1", + "watchdog>=0.10.2,<1", "sarge==0.1.5post0", - "netifaces>=0.10.9,<0.11", - "pylru>=1.2,<1.3", + "netifaces>=0.10.9,<1", + "pylru>=1.2,<2", "rsa>=4.0,<5", - "pkginfo>=1.5.0.1,<1.6", - "requests>=2.22.0,<3", - "semantic_version>=2.8,<2.9", - "psutil>=5.6.5,<5.7", - "Click>=7,<8", - "awesome-slugify>=1.6.5,<1.7", - "feedparser>=5.2.1,<5.3", - "future>=0.18.2,<0.19", - "websocket-client>=0.56,<0.57", - "wrapt>=1.11.2,<1.12", - "emoji>=0.5.4,<0.6", - "frozendict>=1.2,<1.3", - "sentry-sdk==0.13.2", - "filetype>=1.0.5,<2" + "pkginfo>=1.5.0.1,<2", + "requests>=2.23.0,<3", + "semantic_version>=2.8.5,<3", + "psutil>=5.7,<6", + "Click>=7.1.2,<8", + "feedparser>=5.2.1,<6", + "future>=0.18.2,<1", + "websocket-client>=0.57,<1", + "wrapt>=1.12.1,<2", + "emoji>=0.5.4,<1", + "frozendict>=1.2,<2", + "sentry-sdk>=0.15.1,<1", + "filetype>=1.0.7,<2", + + # vendor bundle dependencies + "unidecode>=0.04.14,<0.05", # dependency of awesome-slugify + "blinker>=1.4,<2" # dependency of flask_principal ] # Python 2 specific requirements INSTALL_REQUIRES_PYTHON2 = [ - "futures>=3.3,<3.4", - "monotonic>=1.5,<1.6", - "scandir>=1.10,<1.11", - "chainmap>=1.0.3,<1.1", + "futures>=3.3,<4", + "monotonic>=1.5,<2", + "scandir>=1.10,<2", + "chainmap>=1.0.3,<2", "typing>=3.7.4.1,<4" ] # OSX specific requirements INSTALL_REQUIRES_OSX = [ - "appdirs>=1.4.3", + "appdirs>=1.4.4", ] # Additional requirements for optional install options @@ -87,25 +91,30 @@ EXTRA_REQUIRES = dict( develop=[ # Testing dependencies - SEE ALSO tox.ini "mock>=3.0.5,<4", - "pytest==4.6.6", - "pytest-doctest-custom>=1.0.0,<1.1", + "pytest==4.6.10", + "pytest-doctest-custom>=1.0.0,<2", "ddt", # linter "flake8", - # Documentation dependencies - "sphinx>=1.8.5,<2", - "sphinxcontrib-httpdomain", - "sphinxcontrib-mermaid>=0.3.1", - "sphinx_rtd_theme", - "readthedocs-sphinx-ext==0.5.17" # Later versions require Jinja >= 2.9 + # profiler + "pyinstrument", ], # Dependencies for developing OctoPrint plugins plugins=[ - "cookiecutter>=1.6,<1.7" - ] + "cookiecutter>=1.7.2,<1.8" + ], + + # Dependencies for building the documentation - Python 3 required! + docs=[ + "sphinx>=3,<4", + "sphinxcontrib-httpdomain", + "sphinxcontrib-mermaid", + "sphinx_rtd_theme", + "readthedocs-sphinx-ext" + ], ) # Dependency links for any of the aforementioned dependencies @@ -171,6 +180,9 @@ def md_to_html_build_py_factory(files, baseclass): dict(files=files)) def get_cmdclass(): + # make sure these are always available, even when run by dependabot + global versioneer, octoprint_setuptools, md_to_html_build_py_factory + cmdclass = versioneer.get_cmdclass() # add clean command @@ -194,6 +206,10 @@ def get_cmdclass(): def params(): + # make sure these are always available, even when run by dependabot + global versioneer, get_cmdclass, read_file_contents, here, \ + PYTHON_REQUIRES, SETUP_REQUIRES, INSTALL_REQUIRES, EXTRA_REQUIRES, DEPENDENCY_LINKS + name = "OctoPrint" version = versioneer.get_version() cmdclass = get_cmdclass() @@ -247,7 +263,7 @@ def params(): "Funding": "https://donate.octoprint.org" } - packages = find_packages(where="src") + packages = setuptools.find_packages(where="src") package_dir = { "": "src", } @@ -261,10 +277,10 @@ def params(): zip_safe = False 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 + # 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['develop'] + install_requires = install_requires + extras_require['docs'] entry_points = { "console_scripts": [ @@ -274,4 +290,4 @@ def params(): return locals() -setup(**params()) +setuptools.setup(**params()) diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index 876407781..18322aa29 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -47,6 +47,13 @@ if version_info.major == 2 and version_info.minor <= 7 and version_info.micro < except ImportError: pass +elif version_info.major == 3 and version_info.minor >= 8 and sys.platform == "win32": + # Python 3.8 makes proactor event loop the default on Windows, Tornado doesn't like that + # + # see https://github.com/tornadoweb/tornado/issues/2608 + import asyncio + asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) + del version_info #~~ custom exceptions @@ -559,15 +566,22 @@ def init_connectivity_checker(settings, event_manager): 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=dict(old=old_value, + new=new_value, + connection=connection_working, + resolution=resolution_working)) connectivityChecker = ConnectivityChecker(connectivityInterval, connectivityHost, port=connectivityPort, + name=connectivityName, enabled=connectivityEnabled, on_change=on_connectivity_change) + connectivityChecker.check_immediately() + connectivityChecker.log_full_report() return connectivityChecker diff --git a/src/octoprint/access/groups.py b/src/octoprint/access/groups.py index b7d425795..70ab58d23 100644 --- a/src/octoprint/access/groups.py +++ b/src/octoprint/access/groups.py @@ -43,6 +43,8 @@ class GroupManager(object): def __init__(self): self._logger = logging.getLogger(__name__) self._group_change_listeners = [] + + self._default_groups = [] self._init_defaults() @property @@ -62,39 +64,50 @@ class GroupManager(object): return self.find_group(GUEST_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) + self._default_groups = { + ADMIN_GROUP: dict(name="Admins", + description="Administrators", + permissions=self.default_permissions_for_group(ADMIN_GROUP), + subgroups=[], + changeable=False, + removable=False, + default=False, + toggleable=True), + USER_GROUP: dict(name="Operator", + description="Group to gain operator access", + permissions=self.default_permissions_for_group(USER_GROUP), + subgroups=[], + changeable=True, + default=True, + removable=False, + toggleable=True), + GUEST_GROUP: dict(name="Guests", + description="Anyone who is not currently logged in", + permissions=self.default_permissions_for_group(GUEST_GROUP), + subgroups=[], + changeable=True, + default=False, + removable=False, + toggleable=False), + READONLY_GROUP: dict(name="Read-only Access", + description="Group to gain read-only access", + permissions=self.default_permissions_for_group(READONLY_GROUP), + subgroups=[], + changeable=False, + removable=False, + default=False, + toggleable=True) + } + + for key, g in self._default_groups.items(): + self.add_group(key, g["name"], g["description"], + g["permissions"], g["subgroups"], + changeable=g.get("changeable", True), + removable=g.get("removable", True), + default=g.get("default", False), + toggleable=g.get("toggleable", True), + save=False) + def register_listener(self, listener): self._group_change_listeners.append(listener) @@ -164,6 +177,8 @@ class GroupChangeListener(object): class FilebasedGroupManager(GroupManager): + FILE_VERSION = 2 + def __init__(self, path=None): if path is None: path = settings().get(["accessControl", "groupfile"]) @@ -188,23 +203,41 @@ class FilebasedGroupManager(GroupManager): groups = data data = dict(groups=groups) + file_version = data.get("_version", 1) + if file_version < self.FILE_VERSION: + # make sure we migrate the file on disk after loading + self._logger.info("Detected file version {} on group " + "storage, migrating to version {}".format(file_version, self.FILE_VERSION)) + self._dirty = True + groups = data.get("groups", dict()) tracked_permissions = data.get("tracked", list()) 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(): + 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 - removable = self._groups[key].is_removable() - changeable = self._groups[key].is_changeable() - toggleable = self._groups[key].is_toggleable() + name = self._default_groups[key].get("name", "") + description = self._default_groups[key].get("description", "") + removable = self._default_groups[key].get("removable", True) + changeable = self._default_groups[key].get("changeable", True) + toggleable = self._default_groups[key].get("toggleable", True) + + if file_version == 1: + # 1.4.0/file version 1 has a bug that resets default to True for users group on modification + set_default = self._default_groups[key].get("default", False) + else: + set_default = attributes.get("default", False) else: + name = attributes.get("name", "") + description = attributes.get("description", "") removable = True changeable = True toggleable = True + set_default = attributes.get("default", False) permissions = self._to_permissions(*attributes.get("permissions", [])) default_permissions = self.default_permissions_for_group(key) @@ -214,11 +247,11 @@ class FilebasedGroupManager(GroupManager): subgroups = attributes.get("subgroups", []) - group = Group(key, attributes.get("name", ""), - description=attributes.get("description", ""), + group = Group(key, name, + description=description, permissions=permissions, subgroups=subgroups, - default=attributes.get("default", False), + default=set_default, removable=removable, changeable=changeable, toggleable=toggleable) @@ -227,6 +260,9 @@ class FilebasedGroupManager(GroupManager): for group in self._groups.values(): group._subgroups = self._to_groups(*group._subgroups) + if self._dirty: + self._save() + except Exception: self._logger.exception("Error while loading groups from file {}".format(self._groupfile)) @@ -238,14 +274,16 @@ class FilebasedGroupManager(GroupManager): 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 not key in self._default_groups: + groups[key]["name"] = group.get_name() + groups[key]["description"] = group.get_description() - data = dict(groups=groups, + data = dict(_version=self.FILE_VERSION, + groups=groups, tracked=[x.key for x in Permissions.all()]) with atomic_write(self._groupfile, mode='wt', permissions=0o600, max_permissions=0o666) as f: diff --git a/src/octoprint/access/permissions.py b/src/octoprint/access/permissions.py index c638aa93f..d342efeda 100644 --- a/src/octoprint/access/permissions.py +++ b/src/octoprint/access/permissions.py @@ -298,12 +298,14 @@ class Permissions(with_metaclass(PermissionsMetaClass)): dangerous=True) FILES_LIST = OctoPrintPermission("File List", - gettext("Allows to retrieve a list of all uploaded files, including" + 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"), + 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", @@ -312,7 +314,8 @@ class Permissions(with_metaclass(PermissionsMetaClass)): RoleNeed("files_download"), default_groups=[USER_GROUP, READONLY_GROUP]) FILES_DELETE = OctoPrintPermission("File Delete", - gettext("Allows users to delete files"), + 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", diff --git a/src/octoprint/access/users.py b/src/octoprint/access/users.py index 275bb691d..a0d0f7ba9 100644 --- a/src/octoprint/access/users.py +++ b/src/octoprint/access/users.py @@ -240,6 +240,13 @@ class UserManager(GroupChangeListener, object): 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] @@ -474,14 +481,19 @@ class FilebasedUserManager(UserManager): self._customized = True with io.open(self._userfile, 'rt', encoding='utf-8') as f: data = yaml.safe_load(f) + for name, attributes in data.items(): + if not isinstance(attributes, dict): + continue + permissions = [] if "permissions" in attributes: permissions = attributes["permissions"] - groups = {self._group_manager.user_group} # the user group is mandatory for all logged in users if "groups" in attributes: - groups |= set(attributes["groups"]) + groups = set(attributes["groups"]) + else: + groups = {self._group_manager.user_group} # migrate from roles to permissions if "roles" in attributes and not "permissions" in attributes: diff --git a/src/octoprint/cli/plugins.py b/src/octoprint/cli/plugins.py index e628ae4c6..40c444c17 100644 --- a/src/octoprint/cli/plugins.py +++ b/src/octoprint/cli/plugins.py @@ -8,8 +8,34 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms 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 +from octoprint.util import dict_merge + +LOGGING_CONFIG = { + "version": 1, + "formatters": { + "brief": { + "format": "%(message)s" + } + }, + "handlers": { + "console": { + "class": "logging.StreamHandler", + "formatter": "brief", + "stream": "ext://sys.stdout" + } + }, + "loggers": { + "octoprint.plugin.core": { + "level": logging.ERROR + } + }, + "root": { + "level": logging.WARNING + } +} #~~ "octoprint plugin:command" commands @@ -48,6 +74,9 @@ class OctoPrintPluginCommands(click.MultiCommand): if ctx.obj is None: ctx.obj = OctoPrintContext() + logging_config = dict_merge(LOGGING_CONFIG, dict(root=dict(level=logging.DEBUG if ctx.obj.verbosity > 0 else logging.WARNING))) + logging.config.dictConfig(logging_config) + # initialize settings and plugin manager based on provided # context (basedir and configfile) from octoprint import init_settings, init_pluginsystem, FatalStartupError @@ -63,8 +92,6 @@ class OctoPrintPluginCommands(click.MultiCommand): # fetch registered hooks self.hooks = self.plugin_manager.get_hooks("octoprint.cli.commands") - logging.basicConfig(level=logging.DEBUG if ctx.obj.verbosity > 0 else logging.WARN) - self._initialized = True def list_commands(self, ctx): diff --git a/src/octoprint/cli/server.py b/src/octoprint/cli/server.py index ab9ea5fe4..5a28741a9 100644 --- a/src/octoprint/cli/server.py +++ b/src/octoprint/cli/server.py @@ -50,12 +50,12 @@ def run_server(basedir, configfile, host, port, v6_only, debug, allow_root, logg 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") + .warning("requests/urllib3 will run in an insecure SSL environment. " + "You might see corresponding warnings logged later " + "(\"InsecurePlatformWarning\"). It is recommended to either " + "update to a Python version >= 2.7.9 or alternatively " + "install PyOpenSSL plus its dependencies. For details see " + "https://urllib3.readthedocs.org/en/latest/security.html#openssl-pyopenssl") logger.info(get_divider_line("*")) def log_register_rollover(safe_mode=None, plugin_manager=None, environment_detector=None, **kwargs): diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py index 809ee4a44..71d8aa4eb 100644 --- a/src/octoprint/filemanager/__init__.py +++ b/src/octoprint/filemanager/__init__.py @@ -675,6 +675,9 @@ class FileManager(object): 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) diff --git a/src/octoprint/filemanager/analysis.py b/src/octoprint/filemanager/analysis.py index 3359d8fa3..9f04f2183 100644 --- a/src/octoprint/filemanager/analysis.py +++ b/src/octoprint/filemanager/analysis.py @@ -19,7 +19,8 @@ import time from octoprint.events import Events, eventManager from octoprint.settings import settings from octoprint.util import monotonic_time -from octoprint.util import get_fully_qualified_classname as fqcn +from octoprint.util import get_fully_qualified_classname as fqcn, dict_merge +from octoprint.util.platform import CLOSE_FDS class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile, analysis")): @@ -345,8 +346,12 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): import sys import yaml - if self._current.analysis: + if self._current.analysis and all(map(lambda x: x in self._current.analysis, ("printingArea", + "dimensions", + "estimatedPrintTime", + "filament"))): return self._current.analysis + try: throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority \ else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"]) @@ -370,7 +375,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): self._logger.info("Invoking analysis command: {}".format(" ".join(command))) self._aborted = False - p = sarge.run(command, async_=True, stdout=sarge.Capture()) + p = sarge.run(command, close_fds=CLOSE_FDS, async_=True, stdout=sarge.Capture()) while len(p.commands) == 0: # somewhat ugly... we can't use wait_events because @@ -421,7 +426,11 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): "length": analysis["extrusion_length"][i], "volume": analysis["extrusion_volume"][i] } - return result + + if self._current.analysis and isinstance(self._current.analysis, dict): + return dict_merge(result, self._current.analysis) + else: + return result finally: self._gcode = None diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index 925e1e812..04a97765b 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -24,7 +24,7 @@ from contextlib import contextmanager from past.builtins import basestring from emoji import demojize -from slugify import Slugify +from octoprint.vendor.awesome_slugify import Slugify import octoprint.filemanager @@ -307,6 +307,15 @@ class StorageInterface(object): """ raise NotImplementedError() + def get_additional_metadata(self, path, key): + """ + Fetches additional metadata at ``key`` from the metadata of ``path``. + + :param path: the virtual path to the file for which to fetch additional metadata + :param key: key of metadata to fetch + """ + raise NotImplementedError() + def set_additional_metadata(self, path, key, data, overwrite=False, merge=False): """ Adds additional metadata to the metadata of ``path``. Metadata in ``data`` will be saved under ``key``. @@ -488,7 +497,7 @@ class LocalFileStorage(StorageInterface): self._persisted_metadata_lock_mutex = threading.RLock() self._persisted_metadata_locks = dict() - self._metadata_cache = pylru.lrucache(10) + self._metadata_cache = pylru.lrucache(100) self._old_metadata = None self._initialize_metadata() @@ -877,6 +886,15 @@ class LocalFileStorage(StorageInterface): path, name = self.sanitize(path) self._delete_history(name, path, index) + def get_additional_metadata(self, path, key): + path, name = self.sanitize(path) + metadata = self._get_metadata(path) + + if not name in metadata: + return + + return metadata[name].get(key) + def set_additional_metadata(self, path, key, data, overwrite=False, merge=False): path, name = self.sanitize(path) metadata = self._get_metadata(path) diff --git a/src/octoprint/filemanager/util.py b/src/octoprint/filemanager/util.py index 00f3aa215..7074d508a 100644 --- a/src/octoprint/filemanager/util.py +++ b/src/octoprint/filemanager/util.py @@ -71,7 +71,7 @@ class StreamWrapper(AbstractFileWrapper): 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. + *streams: One or more :py:`io.IOBase` streams to process one after another to save to storage. """ def __init__(self, filename, *streams): if not len(streams) > 0: @@ -88,7 +88,7 @@ class StreamWrapper(AbstractFileWrapper): import shutil with atomic_write(path, mode='wb') as dest: - with self.stream() as source: + for source in self.streams: shutil.copyfileobj(source, dest) def stream(self): @@ -107,7 +107,7 @@ class MultiStream(io.RawIOBase): their contents in the order they are provided to the constructor. Arguments: - *streams (io.RawIOBase): One or more streams to concatenate. + *streams: One or more :py:`io.IOBase` streams to concatenate. """ def __init__(self, *streams): io.RawIOBase.__init__(self) @@ -170,31 +170,32 @@ class LineProcessorStream(io.RawIOBase): def __init__(self, input_stream): io.RawIOBase.__init__(self) self.input_stream = io.BufferedReader(input_stream) - self.leftover = None + self.leftover = bytearray() def read(self, n=-1): if n == 0: return b'' - result = b'' + result = bytearray() while len(result) < n or n == -1: + # add left over from previous loop bytes_left = (n - len(result)) if n != -1 else -1 - if 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 + if bytes_left != -1 and bytes_left < len(self.leftover): + # only s + result += self.leftover[:bytes_left] + self.leftover = self.leftover[bytes_left:] + break + else: + result += self.leftover + self.leftover = bytearray() + # read one line from the underlying stream processed_line = None while processed_line is None: line = self.input_stream.readline() if not line: break processed_line = self.process_line(line) - if processed_line is None: break @@ -206,7 +207,7 @@ class LineProcessorStream(io.RawIOBase): else: result += processed_line - return result + return bytes(result) def readinto(self, b): n = len(b) diff --git a/src/octoprint/logging/__init__.py b/src/octoprint/logging/__init__.py index 10dae37d7..d884c948f 100644 --- a/src/octoprint/logging/__init__.py +++ b/src/octoprint/logging/__init__.py @@ -20,8 +20,11 @@ def log_to_handler(logger, handler, level, msg, exc_info=None, extra=None, *args extra: optional extra data *args: log args """ - from logging import _srcfile import sys + try: + from logging import _srcfile + except ImportError: + _srcfile = None # this is just the same as logging.Logger._log diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index e718a7aa3..69ff0c79d 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -38,7 +38,7 @@ def _validate_plugin(phase, plugin_info): 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): + 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. @@ -63,6 +63,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_en 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. @@ -95,6 +97,9 @@ def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_en 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: @@ -108,6 +113,7 @@ def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_en 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: diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index f7956fe5e..4c900687a 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -119,21 +119,21 @@ class PluginInfo(object): """ 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. - + """ + 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. """ @@ -649,7 +649,8 @@ class PluginManager(object): 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): + 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: @@ -666,6 +667,8 @@ class PluginManager(object): 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 @@ -677,6 +680,7 @@ class PluginManager(object): self.plugin_validators = plugin_validators self.logging_prefix = logging_prefix self.compatibility_ignored_list = compatibility_ignored_list + self.plugin_considered_bundled = plugin_considered_bundled self.enabled_plugins = dict() self.disabled_plugins = dict() @@ -878,7 +882,8 @@ class PluginManager(object): # plugin is already defined or marked as uninstalled, ignore it continue - kwargs = dict(module_name=module_name, version=version) + bundled = key in self.plugin_considered_bundled + kwargs = dict(module_name=module_name, version=version, bundled=bundled) package_name = entry_point.dist.project_name try: entry_point_metadata = EntryPointMetadata(entry_point) 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..eb06109a7 --- /dev/null +++ b/src/octoprint/plugins/action_command_notification/__init__.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import octoprint.plugin + +from octoprint.access import USER_GROUP +from octoprint.access.permissions import Permissions +from octoprint.events import Events + +import flask +from flask_babel import gettext + +import time + +class ActionCommandNotificationPlugin(octoprint.plugin.AssetPlugin, + octoprint.plugin.SettingsPlugin, + octoprint.plugin.SimpleApiPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.EventHandlerPlugin): + + def __init__(self): + self._notifications = [] + + # Additional permissions hook + + def get_additional_permissions(self): + return [ + dict(key="SHOW", + name="Show printer notifications", + description=gettext("Allows to see printer notifications"), + default_groups=[USER_GROUP], + roles=["show"]), + dict(key="CLEAR", + name="Clear printer notifications", + description=gettext("Allows to clear printer notifications"), + default_groups=[USER_GROUP], + roles=["clear"]) + ] + + #~ AssetPlugin + + def get_assets(self): + return dict(js=["js/action_command_notification.js"], + clientjs=["clientjs/action_command_notification.js"], + css=["css/action_command_notification.css"]) + + #~ EventHandlerPlugin + + def on_event(self, event, payload): + if event == Events.DISCONNECTED: + self._clear_notifications() + + #~ SettingsPlugin + + def get_settings_defaults(self): + return dict(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=[dict(timestamp=notification[0], + message=notification[1]) for notification in self._notifications]) + + def get_api_commands(self): + return dict(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 [ + dict(type="settings", + name=gettext("Printer Notifications"), + custom_bindings=False), + dict(type="sidebar", + name=gettext("Printer Notifications"), + icon="bell-o", + styles_wrapper=["display: none"], + data_bind="visible: loginState.hasPermissionKo(access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW)" + " && settings.settings.plugins.action_command_notification.enable()") + ] + + #~ 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, dict(message=message)) + + self._logger.info("Got a notification: {}".format(message)) + + def _clear_notifications(self): + self._notifications = [] + self._plugin_manager.send_plugin_message(self._identifier, dict()) + self._logger.info("Notifications cleared") + +__plugin_name__ = "Action Command Notification Support" +__plugin_description__ = "Allows your printer to trigger notifications via action commands on the connection" +__plugin_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..249b69704 --- /dev/null +++ b/src/octoprint/plugins/action_command_notification/static/clientjs/action_command_notification.js @@ -0,0 +1,22 @@ +(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..ed15d2c39 --- /dev/null +++ b/src/octoprint/plugins/action_command_notification/static/css/action_command_notification.css @@ -0,0 +1,5 @@ +.sidebar_plugin_action_command_notification_entry { + padding: 5px; + line-height: 20px; + border-bottom: 1px solid #ddd; +} 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..991557caa --- /dev/null +++ b/src/octoprint/plugins/action_command_notification/static/js/action_command_notification.js @@ -0,0 +1,65 @@ +$(function() { + function ActionCommandNotificationViewModel(parameters) { + var self = this; + + self.loginState = parameters[0]; + self.access = parameters[1]; + self.settings = parameters[2]; + + self.notifications = ko.observableArray([]); + + 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) { + self.notifications(response.notifications); + }; + + self.clear = function() { + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_CLEAR)) return; + + OctoPrint.plugins.action_command_notification.clear(); + }; + + self.onStartup = self.onUserLoggedIn = self.onUserLoggedOut = function() { + self.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 + } + }); + } + }; + + } + + 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..64f676176 --- /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..67e8557c7 --- /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_prompt/__init__.py b/src/octoprint/plugins/action_command_prompt/__init__.py index 73ea2f77a..680ea9dd1 100644 --- a/src/octoprint/plugins/action_command_prompt/__init__.py +++ b/src/octoprint/plugins/action_command_prompt/__init__.py @@ -50,8 +50,8 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, self._prompt = None self._enable = "detected" self._command = None - self._enable_emergency_sending = False - self._enable_signal_support = False + self._enable_emergency_sending = True + self._enable_signal_support = True self._cap_prompt_support = False def initialize(self): @@ -130,7 +130,7 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, #~ TemplatePlugin def get_template_configs(self): - return [dict(type="settings", name=gettext("Action Command Prompt"), custom_bindings=False)] + return [dict(type="settings", name=gettext("Printer Dialogs"), custom_bindings=False)] #~ action command handler @@ -223,7 +223,7 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, if "{choice}" in self._command: self._printer.commands([self._command.format(choice=choice)]) else: - self._printer.commands(["{command} S{choice}".format(command=self._command, + self._printer.commands(["{command} S{choice}".format(command=self._command, choice=choice)]) @@ -233,6 +233,7 @@ __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_license__ = "AGPLv3" +__plugin_pythoncompat__ = ">=2.7,<4" __plugin_implementation__ = ActionCommandPromptPlugin() __plugin_hooks__ = { "octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler, diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py index 5997acb02..f5a5dd6da 100644 --- a/src/octoprint/plugins/announcements/__init__.py +++ b/src/octoprint/plugins/announcements/__init__.py @@ -42,7 +42,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, self._cached_channel_configs = None self._cached_channel_configs_mutex = threading.RLock() - from slugify import Slugify + from octoprint.vendor.awesome_slugify import Slugify self._slugify = Slugify() self._slugify.safe_chars = "-_." @@ -149,7 +149,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, 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)") + dict(type="navbar", template="announcements_navbar.jinja2", styles=["display: none"], data_bind="visible: loginState.hasPermission(access.permissions.PLUGIN_ANNOUNCEMENTS_READ)") ] # Blueprint Plugin @@ -536,6 +536,7 @@ __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_license__ = "AGPLv3" +__plugin_pythoncompat__ = ">=2.7,<4" __plugin_implementation__ = AnnouncementPlugin() __plugin_hooks__ = { diff --git a/src/octoprint/plugins/appkeys/__init__.py b/src/octoprint/plugins/appkeys/__init__.py index 8199071e9..b96c113b6 100644 --- a/src/octoprint/plugins/appkeys/__init__.py +++ b/src/octoprint/plugins/appkeys/__init__.py @@ -256,7 +256,12 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin, if not app_name: return flask.abort(400) - self._add_api_key(user_id, app_name.strip()) + 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 @@ -437,6 +442,8 @@ __plugin_description__ = "Implements a workflow for third party clients to obtai __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_license__ = "AGPLv3" +__plugin_pythoncompat__ = ">=2.7,<4" __plugin_implementation__ = AppKeysPlugin() __plugin_hooks__ = { "octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key, diff --git a/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js b/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js index 9b29428aa..48868d32f 100644 --- a/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js +++ b/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js @@ -21,6 +21,10 @@ 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.revokeKey = function(key, opts) { return this.base.simpleApiCommand("appkeys", "revoke", {"key": key}, opts); }; 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 bb5fdc822..e26b2ae64 100644 --- a/src/octoprint/plugins/appkeys/static/js/appkeys.js +++ b/src/octoprint/plugins/appkeys/static/js/appkeys.js @@ -1,7 +1,49 @@ $(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", @@ -144,7 +186,9 @@ $(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", @@ -170,14 +214,21 @@ $(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.requestData(); + self.editorUser(self.loginState.username()); + self.editorApp(""); }; self.onUserLoggedIn = function() { self.requestData(); + self.editorUser(self.loginState.username()); + self.editorApp(""); }; self.requestData = function() { @@ -204,6 +255,18 @@ $(function() { self.apps(apps); }; + 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) @@ -294,15 +357,21 @@ $(function() { }; } + 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..6bd592977 --- /dev/null +++ b/src/octoprint/plugins/appkeys/templates/appkeys.jinja2 @@ -0,0 +1,39 @@ + + diff --git a/src/octoprint/plugins/appkeys/templates/appkeys_settings.jinja2 b/src/octoprint/plugins/appkeys/templates/appkeys_settings.jinja2 index 6da481c60..5c383b42e 100644 --- a/src/octoprint/plugins/appkeys/templates/appkeys_settings.jinja2 +++ b/src/octoprint/plugins/appkeys/templates/appkeys_settings.jinja2 @@ -1,3 +1,5 @@ +{{ _('Registered application keys') }} +

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

@@ -41,7 +43,7 @@
{{ _('API Key') }}: - +  |  @@ -56,4 +58,26 @@
  • »
  • + + {{ _('Manually generate an application key') }} + +
    +
    + +
    + +
    +
    +
    + +
    + +
    +
    +
    +
    + +
    +
    +
    diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index 2d5e7dafd..c0bd77866 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -61,7 +61,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, octoprint.plugin.TemplatePlugin, octoprint.plugin.AssetPlugin, octoprint.plugin.BlueprintPlugin, - octoprint.plugin.StartupPlugin): + octoprint.plugin.StartupPlugin, + octoprint.plugin.WizardPlugin): _pip_caller = None @@ -99,7 +100,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, ##~~ TemplatePlugin def get_template_configs(self): - return [dict(type="settings", name=gettext("Backup & Restore"))] + return [dict(type="settings", name=gettext("Backup & Restore")), + dict(type="wizard", name=gettext("Restore Backup?"))] ##~~ BlueprintPlugin @@ -210,9 +212,10 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, 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 Permissions.PLUGIN_BACKUP_ACCESS.can() and not self._settings.global_get(["server", "firstRun"]): + return flask.abort(403) + if not is_os_compatible(["!windows"]): return flask.make_response("Invalid request, the restores are not supported on the underlying operating system", 400) @@ -249,14 +252,14 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, 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"])) + 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.warn("Cannot install plugin {}, it is incompatible to this version " - "of OctoPrint".format(plugin["id"])) + self._logger.warning("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._logger.warning("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)) @@ -325,6 +328,14 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, def is_blueprint_protected(self): return False + ##~~ WizardPlugin + + def is_wizard_required(self): + return self._settings.global_get(["server", "firstRun"]) + + def get_wizard_details(self): + return dict(required=self.is_wizard_required()) + ##~~ tornado hook def route_hook(self, *args, **kwargs): @@ -355,15 +366,21 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, @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): + @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. """ - 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 path is not None: + datafolder, backup_file = os.path.split(os.path.abspath(path)) + else: + backup_file = build_backup_filename() + datafolder = os.path.join(settings.getBaseFolder("data"), "backup") + if not os.path.isdir(datafolder): os.makedirs(datafolder) @@ -374,6 +391,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, plugin_manager=cli_group.plugin_manager, datafolder=datafolder) click.echo("Done.") + click.echo("Backup located at {}".format(os.path.join(datafolder, backup_file))) @click.command("restore") @click.argument("path") @@ -796,12 +814,25 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, 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): @@ -929,6 +960,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, os.remove(path) # restart server + if not restart_command: + restart_command = configdata.get("server", dict()).get("commands", dict()).get("serverRestartCommand") + if restart_command: import sarge @@ -938,7 +972,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, on_restore_done(path) try: - sarge.run(restart_command, async_=True) + 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), @@ -949,6 +983,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, 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 @@ -970,6 +1006,7 @@ __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_license__ = "AGPLv3" +__plugin_pythoncompat__ = ">=2.7,<4" __plugin_implementation__ = BackupPlugin() __plugin_hooks__ = { "octoprint.server.http.routes": __plugin_implementation__.route_hook, diff --git a/src/octoprint/plugins/backup/static/js/backup.js b/src/octoprint/plugins/backup/static/js/backup.js index 2414b3a53..8bfe05e00 100644 --- a/src/octoprint/plugins/backup/static/js/backup.js +++ b/src/octoprint/plugins/backup/static/js/backup.js @@ -29,9 +29,10 @@ $(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, @@ -49,8 +50,11 @@ $(function() { 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; @@ -284,6 +288,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..e19733aa5 100644 --- a/src/octoprint/plugins/backup/templates/backup_settings.jinja2 +++ b/src/octoprint/plugins/backup/templates/backup_settings.jinja2 @@ -96,26 +96,8 @@

    {{ _('Restore settings & files from an uploaded backup archive.') }}

    -
    -
    - -
    -
    - - {{ _('Browse...') }} - - - -
    -
    -
    - -
    -
    - -
    -
    -
    + {% set plugin_backup_upload_form_id='settings-backup-upload' %} + {% include "snippets/plugin/backup/backup_plugin_upload_form.jinja2" %}
    diff --git a/src/octoprint/plugins/backup/templates/backup_wizard.jinja2 b/src/octoprint/plugins/backup/templates/backup_wizard.jinja2 new file mode 100644 index 000000000..8ba4f479c --- /dev/null +++ b/src/octoprint/plugins/backup/templates/backup_wizard.jinja2 @@ -0,0 +1,8 @@ +

    {{ _('Restore from a backup?') }}

    + +{% trans %}

    + If you would like to restore OctoPrint configuration from a backup now is the time. +

    {% endtrans %} + +{% set plugin_backup_upload_form_id='wizard-backup-upload' %} +{% include "snippets/plugin/backup/backup_plugin_upload_form.jinja2" %} diff --git a/src/octoprint/plugins/backup/templates/snippets/plugin/backup/backup_plugin_upload_form.jinja2 b/src/octoprint/plugins/backup/templates/snippets/plugin/backup/backup_plugin_upload_form.jinja2 new file mode 100644 index 000000000..268a567f5 --- /dev/null +++ b/src/octoprint/plugins/backup/templates/snippets/plugin/backup/backup_plugin_upload_form.jinja2 @@ -0,0 +1,20 @@ +
    +
    + +
    +
    + + {{ _('Browse...') }} + + + +
    +
    +
    + +
    +
    + +
    +
    +
    diff --git a/src/octoprint/plugins/corewizard/__init__.py b/src/octoprint/plugins/corewizard/__init__.py index 64047f5ff..6cb038dd8 100644 --- a/src/octoprint/plugins/corewizard/__init__.py +++ b/src/octoprint/plugins/corewizard/__init__.py @@ -123,4 +123,5 @@ __plugin_description__ = "Provides wizard dialogs for core components and functi __plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to perform " "setup steps that might be required after an update.") __plugin_license__ = "AGPLv3" +__plugin_pythoncompat__ = ">=2.7,<4" __plugin_implementation__ = CoreWizardPlugin() diff --git a/src/octoprint/plugins/corewizard/subwizards.py b/src/octoprint/plugins/corewizard/subwizards.py index 0fee431c7..7d206ea00 100644 --- a/src/octoprint/plugins/corewizard/subwizards.py +++ b/src/octoprint/plugins/corewizard/subwizards.py @@ -107,7 +107,7 @@ class OnlineCheckSubwizard(object): return dict(required=self._is_onlinecheck_wizard_required()) def _get_onlinecheck_wizard_name(self): - return gettext("Online connectivity check") + return gettext("Online Connectivity Check") def _get_onlinecheck_additional_wizard_template_data(self): return dict(mandatory=self._is_onlinecheck_wizard_required()) @@ -125,7 +125,7 @@ class PluginBlacklistSubwizard(object): return dict(required=self._is_pluginblacklist_wizard_required()) def _get_pluginblacklist_wizard_name(self): - return gettext("Plugin blacklist") + return gettext("Plugin Blacklist") def _get_pluginblacklist_additional_wizard_template_data(self): return dict(mandatory=self._is_pluginblacklist_wizard_required()) diff --git a/src/octoprint/plugins/corewizard/templates/corewizard_onlinecheck_wizard.jinja2 b/src/octoprint/plugins/corewizard/templates/corewizard_onlinecheck_wizard.jinja2 index 98a4ea007..15a554505 100644 --- a/src/octoprint/plugins/corewizard/templates/corewizard_onlinecheck_wizard.jinja2 +++ b/src/octoprint/plugins/corewizard/templates/corewizard_onlinecheck_wizard.jinja2 @@ -24,7 +24,21 @@
    {% include "snippets/settings/server/serverOnlineCheckHost.jinja2" %} {% include "snippets/settings/server/serverOnlineCheckPort.jinja2" %} - {% include "snippets/settings/server/serverOnlineCheckTest.jinja2" %} + {% include "snippets/settings/server/serverOnlineCheckTestConnectivity.jinja2" %} +
    + +

    {% trans %} + If you also want to check if name resolution works (strongly recommended), define a host name + to check name resolution against. If you don't know what to set here, the default value + (OctoPrint's domain) should work. If you don't want to perform regular resolution checks along + side with the general connectivity check, leave the field empty. +{% endtrans %}

    + +
    +
    + {% include "snippets/settings/server/serverOnlineCheckName.jinja2" %} + {% include "snippets/settings/server/serverOnlineCheckTestResolution.jinja2" %} +

    {% trans %} diff --git a/src/octoprint/plugins/discovery/__init__.py b/src/octoprint/plugins/discovery/__init__.py index c9ee8dea9..3a12687e9 100644 --- a/src/octoprint/plugins/discovery/__init__.py +++ b/src/octoprint/plugins/discovery/__init__.py @@ -714,3 +714,4 @@ __plugin_description__ = "Makes the OctoPrint instance discoverable via Bonjour/ __plugin_disabling_discouraged__ = gettext("Without this plugin your OctoPrint instance will no longer be " "discoverable on the network via Bonjour and uPnP.") __plugin_license__ = "AGPLv3" +__plugin_pythoncompat__ = ">=2.7,<4" diff --git a/src/octoprint/plugins/errortracking/__init__.py b/src/octoprint/plugins/errortracking/__init__.py index c6f21b1dc..d205c3a78 100644 --- a/src/octoprint/plugins/errortracking/__init__.py +++ b/src/octoprint/plugins/errortracking/__init__.py @@ -13,8 +13,8 @@ from octoprint.util.version import get_octoprint_version_string, is_released_oct from flask import jsonify from flask_babel import gettext -SENTRY_URL_SERVER = "https://2e668ba966024cfc962ba97eef89dc15@sentry.io/1373987" -SENTRY_URL_COREUI = "https://dccc2e2f3c6b4adda72f376bbb7fe561@sentry.io/1374096" +SENTRY_URL_SERVER = "https://a928e3eb40864ed086f765d6976bf792@o118517.ingest.sentry.io/1373987" +SENTRY_URL_COREUI = "https://26fe846c0ff34995a39bbb67a04b3f42@o118517.ingest.sentry.io/1374096" SETTINGS_DEFAULTS = dict(enabled=False, enabled_unreleased=False, @@ -25,15 +25,14 @@ SETTINGS_DEFAULTS = dict(enabled=False, import serial import requests.exceptions import errno -import octoprint.util.avr_isp.ispBase import tornado.websocket IGNORED_EXCEPTIONS = [ # serial exceptions in octoprint.util.comm (serial.SerialException, lambda exc, logger, plugin, cb: logger == "octoprint.util.comm"), - # isp errors during port auto detection in octoprint.util.comm - (octoprint.util.avr_isp.ispBase.IspError, lambda exc, logger, plugin, cb: logger == "octoprint.util.comm"), + # KeyboardInterrupts + KeyboardInterrupt, # IOErrors of any kind due to a full file system (IOError, lambda exc, logger, plugin, cb: getattr(exc, "errno") and exc.errno in (getattr(errno, "ENOSPC"),)), @@ -209,4 +208,6 @@ def __plugin_enable__(): __plugin_name__ = "Error Tracking" __plugin_author__ = "Gina Häußge" +__plugin_license__ = "AGPLv3" +__plugin_pythoncompat__ = ">=2.7,<4" __plugin_implementation__ = ErrorTrackingPlugin() diff --git a/src/octoprint/plugins/errortracking/static/js/sentry.min.js b/src/octoprint/plugins/errortracking/static/js/sentry.min.js index 83bb176de..bc3fd88aa 100644 --- a/src/octoprint/plugins/errortracking/static/js/sentry.min.js +++ b/src/octoprint/plugins/errortracking/static/js/sentry.min.js @@ -1,2 +1,2 @@ -/*! @sentry/browser 5.0.5 (913eafc4) | https://github.com/getsentry/sentry-javascript */ -var Sentry=function(n){"use strict";var t=function(n,r){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,t){n.__proto__=t}||function(n,t){for(var r in t)t.hasOwnProperty(r)&&(n[r]=t[r])})(n,r)};function r(n,r){function i(){this.constructor=n}t(n,r),n.prototype=null===r?Object.create(r):(i.prototype=r.prototype,new i)}var i,e,o,u=function(){return(u=Object.assign||function(n){for(var t,r=1,i=arguments.length;r0&&e[e.length-1])&&(6===o[0]||2===o[0])){u=0;continue}if(3===o[0]&&(!e||o[1]>e[0]&&o[1]0)&&!(i=o.next()).done;)u.push(i.value)}catch(n){e={error:n}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(e)throw e.error}}return u}function a(){for(var n=[],t=0;t=200&&t<300?n.Success:429===t?n.RateLimit:t>=400&&t<500?n.Invalid:t>=500?n.Failed:n.Unknown}}(n.Status||(n.Status={}));var b={};function w(){return"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0)?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:b}function g(){var n=w(),t=n.crypto||n.msCrypto;if(void 0!==t&&t.getRandomValues){var r=new Uint16Array(8);t.getRandomValues(r),r[3]=4095&r[3]|16384,r[4]=16383&r[4]|32768;var i=function(n){for(var t=n.toString(16);t.length<4;)t="0"+t;return t};return i(r[0])+i(r[1])+i(r[2])+i(r[3])+i(r[4])+i(r[5])+i(r[6])+i(r[7])}return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,function(n){var t=16*Math.random()|0;return("x"===n?t:3&t|8).toString(16)})}function E(n){var t,r,i,e,o,u=[];if(!n||!n.tagName)return"";if(u.push(n.tagName.toLowerCase()),n.id&&u.push("#"+n.id),(t=n.className)&&d(t))for(r=t.split(/\s+/),o=0;o"}return n.event_id||""}function S(n){var t=w();if(!("console"in t))return n();var r=t.console,i={};["debug","info","warn","error","log"].forEach(function(n){n in t.console&&r[n].__sentry__&&(i[n]=r[n].__sentry_wrapped__,r[n]=r[n].__sentry_original__)});var e=n();return Object.keys(i).forEach(function(n){r[n]=i[n]}),e}function _(n,t,r,i){void 0===i&&(i={handled:!0,type:"generic"}),n.exception=n.exception||{},n.exception.values=n.exception.values||[],n.exception.values[0]=n.exception.values[0]||{},n.exception.values[0].value=n.exception.values[0].value||t||"",n.exception.values[0].type=n.exception.values[0].type||r||"Error",n.exception.values[0].mechanism=n.exception.values[0].mechanism||i}var O,k=function(){function n(){this.t="function"==typeof WeakSet,this.i=this.t?new WeakSet:[]}return n.prototype.memoize=function(n){if(this.t)return!!this.i.has(n)||(this.i.add(n),!1);for(var t=0;tr?D(n,t-1,r):i}function I(n,t){return"domain"===t&&"object"==typeof n&&n.o?"[Domain]":"domainEmitter"===t?"[DomainEmitter]":"undefined"!=typeof global&&n===global?"[Global]":"undefined"!=typeof window&&n===window?"[Window]":"undefined"!=typeof document&&n===document?"[Document]":"undefined"!=typeof Event&&n instanceof Event?Object.getPrototypeOf(n)?n.constructor.name:"Event":m(r=n)&&"nativeEvent"in r&&"preventDefault"in r&&"stopPropagation"in r?"[SyntheticEvent]":Number.isNaN(n)?"[NaN]":void 0===n?"[undefined]":"function"==typeof n?"[Function: "+(n.name||"")+"]":n;var r}function A(n,t,r,i){if(void 0===r&&(r=1/0),void 0===i&&(i=new k),0===r)return function(n){var t=Object.prototype.toString.call(n);if("string"==typeof n)return n;if("[object Object]"===t)return"[Object]";if("[object Array]"===t)return"[Array]";var r=I(n);return p(r)?r:t}(t);if(null!=t&&"function"==typeof t.toJSON)return t.toJSON();var e=I(t,n);if(p(e))return e;var o=h(t)?function(n){var t={message:n.message,name:n.name,stack:n.stack};for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r]);return t}(t):t,u=Array.isArray(t)?[]:{};if(i.memoize(t))return"[Circular ~]";for(var c in o)Object.prototype.hasOwnProperty.call(o,c)&&(u[c]=A(c,o[c],r-1,i));return i.unmemoize(t),u}function C(n,t){try{return JSON.parse(JSON.stringify(n,function(n,r){return A(n,r,t)}))}catch(n){return"**non-serializable**"}}!function(n){n.PENDING="PENDING",n.RESOLVED="RESOLVED",n.REJECTED="REJECTED"}(O||(O={}));var M=function(){function n(n){var t=this;this.u=O.PENDING,this.s=[],this.h=function(n){t.v(n,O.RESOLVED)},this.l=function(n){t.v(n,O.REJECTED)},this.v=function(n,r){t.u===O.PENDING&&(y(n)?n.then(t.h,t.l):(t.p=n,t.u=r,t.m()))},this.m=function(){t.u!==O.PENDING&&(t.u===O.REJECTED?t.s.forEach(function(n){return n.onFail&&n.onFail(t.p)}):t.s.forEach(function(n){return n.onSuccess&&n.onSuccess(t.p)}),t.s=[])},this.g=function(n){t.s=t.s.concat(n),t.m()};try{n(this.h,this.l)}catch(n){this.l(n)}}return n.prototype.then=function(t,r){var i=this;return new n(function(n,e){i.g({onFail:function(t){if(r)try{return void n(r(t))}catch(n){return void e(n)}else e(t)},onSuccess:function(r){if(t)try{return void n(t(r))}catch(n){return void e(n)}else n(r)}})})},n.prototype.catch=function(n){return this.then(function(n){return n},n)},n.prototype.toString=function(){return"[object SyncPromise]"},n.resolve=function(t){return new n(function(n){n(t)})},n.reject=function(t){return new n(function(n,r){r(t)})},n}(),N=function(){function n(){this.j=!1,this.S=[],this._=[],this.O=[],this.k={},this.T={},this.R={}}return n.prototype.addScopeListener=function(n){this.S.push(n)},n.prototype.addEventProcessor=function(n){return this._.push(n),this},n.prototype.D=function(){var n=this;this.j||(this.j=!0,setTimeout(function(){n.S.forEach(function(t){t(n)}),n.j=!1}))},n.prototype.I=function(n,t,r,i){var e=this;return void 0===i&&(i=0),new M(function(o,c){var s=n[i];if(null===t||"function"!=typeof s)o(t);else{var f=s(u({},t),r);y(f)?f.then(function(t){return e.I(n,t,r,i+1).then(o)}).catch(c):e.I(n,f,r,i+1).then(o).catch(c)}})},n.prototype.setUser=function(n){return this.k=C(n),this.D(),this},n.prototype.setTags=function(n){return this.T=u({},this.T,C(n)),this.D(),this},n.prototype.setTag=function(n,t){var r;return this.T=u({},this.T,((r={})[n]=C(t),r)),this.D(),this},n.prototype.setExtras=function(n){return this.R=u({},this.R,C(n)),this.D(),this},n.prototype.setExtra=function(n,t){var r;return this.R=u({},this.R,((r={})[n]=C(t),r)),this.D(),this},n.prototype.setFingerprint=function(n){return this.A=C(n),this.D(),this},n.prototype.setLevel=function(n){return this.C=C(n),this.D(),this},n.clone=function(t){var r=new n;return Object.assign(r,t,{S:[]}),t&&(r.O=a(t.O),r.T=u({},t.T),r.R=u({},t.R),r.k=t.k,r.C=t.C,r.A=t.A,r._=a(t._)),r},n.prototype.clear=function(){return this.O=[],this.T={},this.R={},this.k={},this.C=void 0,this.A=void 0,this.D(),this},n.prototype.addBreadcrumb=function(n,t){return this.O=void 0!==t&&t>=0?a(this.O,[C(n)]).slice(-t):a(this.O,[C(n)]),this.D(),this},n.prototype.clearBreadcrumbs=function(){return this.O=[],this.D(),this},n.prototype.M=function(n){n.fingerprint=n.fingerprint?Array.isArray(n.fingerprint)?n.fingerprint:[n.fingerprint]:[],this.A&&(n.fingerprint=n.fingerprint.concat(this.A)),n.fingerprint&&!n.fingerprint.length&&delete n.fingerprint},n.prototype.applyToEvent=function(n,t){return this.R&&Object.keys(this.R).length&&(n.extra=u({},this.R,n.extra)),this.T&&Object.keys(this.T).length&&(n.tags=u({},this.T,n.tags)),this.k&&Object.keys(this.k).length&&(n.user=u({},this.k,n.user)),this.C&&(n.level=this.C),this.M(n),(!n.breadcrumbs||0===n.breadcrumbs.length)&&this.O.length>0&&(n.breadcrumbs=this.O),this.I(a(F(),this._),n,t)},n}();function F(){var n=w();return n.__SENTRY__=n.__SENTRY__||{},n.__SENTRY__.globalEventProcessors=n.__SENTRY__.globalEventProcessors||[],n.__SENTRY__.globalEventProcessors}function U(n){F().push(n)}var L=w(),P="Sentry Logger ",$=function(){function n(){this.N=!1}return n.prototype.disable=function(){this.N=!1},n.prototype.enable=function(){this.N=!0},n.prototype.log=function(){for(var n=[],t=0;t0?n[n.length-1].scope:void 0,r=N.clone(t);return this.getStack().push({client:this.getClient(),scope:r}),r},n.prototype.popScope=function(){return void 0!==this.getStack().pop()},n.prototype.withScope=function(n){var t=this.pushScope();try{n(t)}finally{this.popScope()}},n.prototype.getClient=function(){return this.getStackTop().client},n.prototype.getScope=function(){return this.getStackTop().scope},n.prototype.getStack=function(){return this.U},n.prototype.getStackTop=function(){return this.U[this.U.length-1]},n.prototype.captureException=function(n,t){var r=this.P=g();return this.L("captureException",n,u({},t,{event_id:r})),r},n.prototype.captureMessage=function(n,t,r){var i=this.P=g();return this.L("captureMessage",n,t,u({},r,{event_id:i})),i},n.prototype.captureEvent=function(n,t){var r=this.P=g();return this.L("captureEvent",n,u({},t,{event_id:r})),r},n.prototype.lastEventId=function(){return this.P},n.prototype.addBreadcrumb=function(n,t){var r=this.getStackTop();if(r.scope&&r.client){var i=r.client.getOptions(),e=i.beforeBreadcrumb,o=i.maxBreadcrumbs,c=void 0===o?30:o;if(!(c<=0)){var s=(new Date).getTime()/1e3,f=u({timestamp:s},n),a=e?S(function(){return e(f,t)}):f;null!==a&&r.scope.addBreadcrumb(a,Math.min(c,100))}}},n.prototype.configureScope=function(n){var t=this.getStackTop();t.scope&&t.client&&n(t.scope)},n.prototype.run=function(n){var t=G(this);try{n(this)}finally{G(t)}},n.prototype.getIntegration=function(n){var t=this.getClient();if(!t)return null;try{return t.getIntegration(n)}catch(t){return q.warn("Cannot retrieve integration "+n.id+" from the current Hub"),null}},n}();function B(){var n=w();return n.__SENTRY__=n.__SENTRY__||{hub:void 0},n}function G(n){var t=B(),r=z(t);return V(t,n),r}function J(){var n,t,r=B();X(r)&&!z(r).isOlderThan(H)||V(r,new W);try{var i=(n=module,t="domain",n.require(t)).active;if(!i)return z(r);if(!X(i)||z(i).isOlderThan(H)){var e=z(r).getStackTop();V(i,new W(e.client,N.clone(e.scope)))}return z(i)}catch(n){return z(r)}}function X(n){return!!(n&&n.__SENTRY__&&n.__SENTRY__.hub)}function z(n){return n&&n.__SENTRY__&&n.__SENTRY__.hub?n.__SENTRY__.hub:(n.__SENTRY__=n.__SENTRY__||{},n.__SENTRY__.hub=new W,n.__SENTRY__.hub)}function V(n,t){return!!n&&(n.__SENTRY__=n.__SENTRY__||{},n.__SENTRY__.hub=t,!0)}function K(n){for(var t=[],r=1;r1&&(h=l.slice(0,-1).join("/"),v=l.pop()),Object.assign(this,{host:c,pass:u,path:h,projectId:v,port:a,protocol:i,user:e})},n.prototype.q=function(n){this.protocol=n.protocol,this.user=n.user,this.pass=n.pass||"",this.host=n.host,this.port=n.port||"",this.path=n.path||"",this.projectId=n.projectId},n.prototype.H=function(){var n=this;if(["protocol","user","host","projectId"].forEach(function(t){if(!n[t])throw new Q("Invalid Dsn")}),"http"!==this.protocol&&"https"!==this.protocol)throw new Q("Invalid Dsn");if(this.port&&Number.isNaN(parseInt(this.port,10)))throw new Q("Invalid Dsn")},n}(),tn=function(){function n(n){this.dsn=n,this.W=new nn(n)}return n.prototype.getDsn=function(){return this.W},n.prototype.getStoreEndpoint=function(){return""+this.B()+this.getStoreEndpointPath()},n.prototype.getStoreEndpointWithUrlEncodedAuth=function(){var n,t={sentry_key:this.W.user,sentry_version:"7"};return this.getStoreEndpoint()+"?"+(n=t,Object.keys(n).map(function(t){return encodeURIComponent(t)+"="+encodeURIComponent(n[t])}).join("&"))},n.prototype.B=function(){var n=this.W,t=n.protocol?n.protocol+":":"",r=n.port?":"+n.port:"";return t+"//"+n.host+r},n.prototype.getStoreEndpointPath=function(){var n=this.W;return(n.path?"/"+n.path:"")+"/api/"+n.projectId+"/store/"},n.prototype.getRequestHeaders=function(n,t){var r=this.W,i=["Sentry sentry_version=7"];return i.push("sentry_timestamp="+(new Date).getTime()),i.push("sentry_client="+n+"/"+t),i.push("sentry_key="+r.user),r.pass&&i.push("sentry_secret="+r.pass),{"Content-Type":"application/json","X-Sentry-Auth":i.join(", ")}},n.prototype.getReportDialogEndpoint=function(n){void 0===n&&(n={});var t=this.W,r=this.B()+(t.path?"/"+t.path:"")+"/api/embed/error-page/",i=[];for(var e in i.push("dsn="+t.toString()),n)if("user"===e){if(!n.user)continue;n.user.name&&i.push("name="+encodeURIComponent(n.user.name)),n.user.email&&i.push("email="+encodeURIComponent(n.user.email))}else i.push(encodeURIComponent(e)+"="+encodeURIComponent(n[e]));return i.length?r+"?"+i.join("&"):r},n}();function rn(n,t){return void 0===t&&(t=0),0===t?n:n.length<=t?n:n.substr(0,t)+"..."}function en(n,t){if(!Array.isArray(n))return"";for(var r=[],i=0;i=t)return rn(n[0],t);for(var r=n.length;r>0;r--){var i=n.slice(0,r).join(", ");if(!(i.length>t))return r===n.length?i:rn(i,t)}return""}var un=[];function cn(n){var t={};return function(n){var t=n.defaultIntegrations&&a(n.defaultIntegrations)||[],r=n.integrations,i=[];if(Array.isArray(r)){var e=r.map(function(n){return n.name}),o=[];t.forEach(function(n){-1===e.indexOf(n.name)&&-1===o.indexOf(n.name)&&(i.push(n),o.push(n.name))}),r.forEach(function(n){-1===o.indexOf(n.name)&&(i.push(n),o.push(n.name))})}else{if("function"!=typeof r)return a(t);i=r(t),i=Array.isArray(i)?i:[i]}return i}(n).forEach(function(n){t[n.name]=n,function(n){-1===un.indexOf(n.name)&&(n.setupOnce(U,J),un.push(n.name),q.log("Integration installed: "+n.name))}(n)}),t}var sn,fn=function(){function n(n,t){this.G=!1,this.J=new n(t),this.X=t,t.dsn&&(this.V=new nn(t.dsn)),this.K=cn(this.X)}return n.prototype.captureException=function(n,t,r){var i=this,e=t&&t.event_id;return this.G=!0,this.Z().eventFromException(n,t).then(function(n){return i.Y(n,t,r)}).then(function(n){e=n&&n.event_id,i.G=!1}).catch(function(n){q.log(n),i.G=!1}),e},n.prototype.captureMessage=function(n,t,r,i){var e=this,o=r&&r.event_id;return this.G=!0,(p(n)?this.Z().eventFromMessage(""+n,t,r):this.Z().eventFromException(n,r)).then(function(n){return e.Y(n,r,i)}).then(function(n){o=n&&n.event_id,e.G=!1}).catch(function(n){q.log(n),e.G=!1}),o},n.prototype.captureEvent=function(n,t,r){var i=this,e=t&&t.event_id;return this.G=!0,this.Y(n,t,r).then(function(n){e=n&&n.event_id,i.G=!1}).catch(function(n){q.log(n),i.G=!1}),e},n.prototype.getDsn=function(){return this.V},n.prototype.getOptions=function(){return this.X},n.prototype.flush=function(n){return c(this,void 0,void 0,function(){return s(this,function(t){switch(t.label){case 0:return[4,Promise.all([this.Z().getTransport().close(n),this.nn()])];case 1:return[2,t.sent().reduce(function(n,t){return n&&t})]}})})},n.prototype.close=function(n){return c(this,void 0,void 0,function(){var t=this;return s(this,function(r){return[2,this.flush(n).finally(function(){t.getOptions().enabled=!1})]})})},n.prototype.getIntegrations=function(){return this.K||{}},n.prototype.getIntegration=function(n){try{return this.K[n.id]||null}catch(t){return q.warn("Cannot retrieve integration "+n.id+" from the current Client"),null}},n.prototype.nn=function(n){return void 0===n&&(n=0),c(this,void 0,void 0,function(){var t=this;return s(this,function(r){return[2,new Promise(function(r){t.G?n>=10?r(!1):setTimeout(function(){return c(t,void 0,void 0,function(){var t;return s(this,function(i){switch(i.label){case 0:return t=r,[4,this.nn(n+1)];case 1:return t.apply(void 0,[i.sent()]),[2]}})})},10):r(!0)})]})})},n.prototype.Z=function(){return this.J},n.prototype.tn=function(){return!1!==this.getOptions().enabled&&void 0!==this.V},n.prototype.rn=function(n,t,r){var i=this.getOptions(),e=i.environment,o=i.release,c=i.dist,s=i.maxValueLength,f=void 0===s?250:s,a=u({},n);void 0===a.environment&&void 0!==e&&(a.environment=e),void 0===a.release&&void 0!==o&&(a.release=o),void 0===a.dist&&void 0!==c&&(a.dist=c),a.message&&(a.message=rn(a.message,f));var h=a.exception&&a.exception.values&&a.exception.values[0];h&&h.value&&(h.value=rn(h.value,f));var v=a.request;v&&v.url&&(v.url=rn(v.url,f)),void 0===a.event_id&&(a.event_id=g()),this.in(a.sdk);var l=M.resolve(a);return t&&(l=t.applyToEvent(a,r)),l},n.prototype.in=function(n){var t=Object.keys(this.K);n&&t.length>0&&(n.integrations=t)},n.prototype.Y=function(n,t,r){var i=this,e=this.getOptions(),o=e.beforeSend,u=e.sampleRate;return this.tn()?"number"==typeof u&&Math.random()>u?M.reject("This event has been sampled, will not send event."):new M(function(e,u){i.rn(n,r,t).then(function(n){if(null!==n){var r=n;try{if(t&&t.data&&!0===t.data.__sentry__||!o)return i.Z().sendEvent(r),void e(r);var c=o(n,t);if(void 0===c)q.error("`beforeSend` method has to return `null` or a valid event.");else if(y(c))i.en(c,e,u);else{if(null===(r=c))return q.log("`beforeSend` returned `null`, will not send event."),void e(null);i.Z().sendEvent(r),e(r)}}catch(n){i.captureException(n,{data:{__sentry__:!0},originalException:n}),u("`beforeSend` throw an error, will not send event.")}}else u("An event processor returned null, will not send event.")})}):M.reject("SDK not enabled, will not send event.")},n.prototype.en=function(n,t,r){var i=this;n.then(function(n){null!==n?(i.Z().sendEvent(n),t(n)):r("`beforeSend` returned `null`, will not send event.")}).catch(function(n){r("beforeSend rejected with "+n)})},n}(),an=function(){function t(){}return t.prototype.sendEvent=function(t){return c(this,void 0,void 0,function(){return s(this,function(t){return[2,Promise.resolve({reason:"NoopTransport: Event has been skipped because no Dsn is configured.",status:n.Status.Skipped})]})})},t.prototype.close=function(n){return c(this,void 0,void 0,function(){return s(this,function(n){return[2,Promise.resolve(!0)]})})},t}(),hn=function(){function n(n){this.X=n,this.X.dsn||q.warn("No DSN provided, backend will not do anything."),this.on=this.un()}return n.prototype.un=function(){return new an},n.prototype.eventFromException=function(n,t){throw new Q("Backend has to implement `eventFromException` method")},n.prototype.eventFromMessage=function(n,t,r){throw new Q("Backend has to implement `eventFromMessage` method")},n.prototype.sendEvent=function(n){this.on.sendEvent(n).catch(function(n){q.error("Error while sending event: "+n)})},n.prototype.getTransport=function(){return this.on},n}();var vn=function(){function n(){this.name=n.id}return n.prototype.setupOnce=function(){sn=Function.prototype.toString,Function.prototype.toString=function(){for(var n=[],t=0;t|[a-z]:|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,o=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|moz-extension).*?:\/.*?|\[native code\]|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i,u=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i,c=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,s=/\((\S*)(?::(\d+))(?::(\d+))\)/,f=n.stack.split("\n"),a=[],h=/^(.*) is undefined$/.exec(n.message),v=0,l=f.length;v eval")>-1&&(t=c.exec(r[3]))?r[3]=t[1]:0!==v||r[5]||void 0===n.columnNumber||(a[0].column=n.columnNumber+1),i={url:r[3],func:r[1]||gn,args:r[2]?r[2].split(","):[],line:r[4]?+r[4]:null,column:r[5]?+r[5]:null}}!i.func&&i.line&&(i.func=gn),i.context=null,a.push(i)}return a.length?(a[0]&&a[0].line&&!a[0].column&&h&&(a[0].column=null),{mode:"stack",name:n.name,message:n.message,stack:a}):null}function t(n,t,r,i){var e={url:t,line:r};if(e.url&&e.line){if(n.incomplete=!1,e.func||(e.func=gn),e.context||(e.context=null),/ '([^']+)' /.exec(i)&&(e.column=null),n.stack.length>0&&n.stack[0].url===e.url){if(n.stack[0].line===e.line)return!1;if(!n.stack[0].line&&n.stack[0].func===e.func)return n.stack[0].line=e.line,n.stack[0].context=e.context,!1}return n.stack.unshift(e),n.partial=!0,!0}return n.incomplete=!0,!1}function r(n,e){for(var o,u,c=/function\s+([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*)?\s*\(/i,s=[],f={},a=!1,h=r.caller;h&&!a;h=h.caller)if(h!==i&&h!==wn.report){if(u={url:null,func:gn,args:[],line:null,column:null},h.name?u.func=h.name:(o=c.exec(h.toString()))&&(u.func=o[1]),void 0===u.func)try{u.func=o.input.substring(0,o.input.indexOf("{"))}catch(n){}f[""+h]?a=!0:f[""+h]=!0,s.push(u)}e&&s.splice(0,e);var v={mode:"callers",name:n.name,message:n.message,stack:s};return t(v,n.sourceURL||n.fileName,n.line||n.lineNumber,n.message||n.description),v}function i(t,i){var e=null;i=null==i?0:+i;try{if(e=function(n){var t=n.stacktrace;if(t){for(var r,i=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,e=/ line (\d+), column (\d+)\s*(?:in (?:]+)>|([^\)]+))\((.*)\))? in (.*):\s*$/i,o=t.split("\n"),u=[],c=0;c0&&r(!1)},n);Promise.all(t.yn).then(function(){clearTimeout(i),r(!0)}).catch(function(){r(!0)})})]})})},n}(),Nn=function(){function n(n){this.options=n,this.yn=new Mn(30),this.url=new tn(this.options.dsn).getStoreEndpointWithUrlEncodedAuth()}return n.prototype.sendEvent=function(n){return c(this,void 0,void 0,function(){return s(this,function(n){throw new Q("Transport Class has to implement `sendEvent` method")})})},n.prototype.close=function(n){return c(this,void 0,void 0,function(){return s(this,function(t){return[2,this.yn.drain(n)]})})},n}(),Fn=w(),Un=function(t){function i(){return null!==t&&t.apply(this,arguments)||this}return r(i,t),i.prototype.sendEvent=function(t){return c(this,void 0,void 0,function(){var r;return s(this,function(i){return r={body:JSON.stringify(t),method:"POST",referrerPolicy:yn()?"origin":""},[2,this.yn.add(Fn.fetch(this.url,r).then(function(t){return{status:n.Status.fromHttpCode(t.status)}}))]})})},i}(Nn),Ln=function(t){function i(){return null!==t&&t.apply(this,arguments)||this}return r(i,t),i.prototype.sendEvent=function(t){return c(this,void 0,void 0,function(){var r=this;return s(this,function(i){return[2,this.yn.add(new Promise(function(i,e){var o=new XMLHttpRequest;o.onreadystatechange=function(){4===o.readyState&&(200===o.status&&i({status:n.Status.fromHttpCode(o.status)}),e(o))},o.open("POST",r.url),o.send(JSON.stringify(t))}))]})})},i}(Nn),Pn=Object.freeze({BaseTransport:Nn,FetchTransport:Un,XHRTransport:Ln}),$n=function(t){function i(){return null!==t&&t.apply(this,arguments)||this}return r(i,t),i.prototype.un=function(){if(!this.X.dsn)return t.prototype.un.call(this);var n=this.X.transportOptions?this.X.transportOptions:{dsn:this.X.dsn};return this.X.transport?new this.X.transport(n):mn()?new Un(n):new Ln(n)},i.prototype.eventFromException=function(t,r){var i,e,o=this;if(v(t)&&t.error)return t=t.error,i=Dn(kn(t)),M.resolve(this.bn(i,r));if(l(t)||(e=t,"[object DOMException]"===Object.prototype.toString.call(e))){var u=t,c=u.name||(l(u)?"DOMError":"DOMException"),s=u.message?c+": "+u.message:c;return this.eventFromMessage(s,n.Severity.Error,r).then(function(n){return _(n,s),M.resolve(o.bn(n,r))})}if(h(t))return i=Dn(kn(t)),M.resolve(this.bn(i,r));if(m(t)&&r&&r.syntheticException)return _(i=function(n,t){var r=Object.keys(n).sort(),i={extra:{__serialized__:D(n)},message:"Non-Error exception captured with keys: "+on(r)};if(t){var e=In(kn(t).stack);i.stacktrace={frames:e}}return i}(t,r.syntheticException),"Custom Object",void 0,{handled:!0,synthetic:!0,type:"generic"}),i.level=n.Severity.Error,M.resolve(this.bn(i,r));var f=t;return this.eventFromMessage(f,void 0,r).then(function(t){return _(t,""+f,void 0,{handled:!0,synthetic:!0,type:"generic"}),t.level=n.Severity.Error,M.resolve(o.bn(t,r))})},i.prototype.bn=function(n,t){return u({},n,{event_id:t&&t.event_id})},i.prototype.eventFromMessage=function(t,r,i){void 0===r&&(r=n.Severity.Info);var e={event_id:i&&i.event_id,level:r,message:t};if(this.X.attachStacktrace&&i&&i.syntheticException){var o=In(kn(i.syntheticException).stack);e.stacktrace={frames:o}}return M.resolve(e)},i}(hn),qn="sentry.javascript.browser",Hn=function(n){function t(t){return void 0===t&&(t={}),n.call(this,$n,t)||this}return r(t,n),t.prototype.rn=function(t,r,i){return t.platform=t.platform||"javascript",t.sdk=u({},t.sdk,{name:qn,packages:a(t.sdk&&t.sdk.packages||[],[{name:"npm:@sentry/browser",version:"5.0.5"}]),version:"5.0.5"}),n.prototype.rn.call(this,t,r,i)},t.prototype.showReportDialog=function(n){void 0===n&&(n={});var t=w().document;if(t)if(this.tn()){var r=n.dsn||this.getDsn();if(n.eventId)if(r){var i=t.createElement("script");i.async=!0,i.src=new tn(r).getReportDialogEndpoint(n),(t.head||t.body).appendChild(i)}else q.error("Missing `Dsn` option in showReportDialog call");else q.error("Missing `eventId` option in showReportDialog call")}else q.error("Trying to call showReportDialog with Sentry Client is disabled")},t}(fn),Wn=1e3,Bn=0;function Gn(n,t,r){if(void 0===t&&(t={}),"function"!=typeof n)return n;try{if(n.__sentry__)return n;if(n.__sentry_wrapped__)return n.__sentry_wrapped__}catch(t){return n}var sentryWrapped=function(){r&&"function"==typeof r&&r.apply(this,arguments);var i=Array.prototype.slice.call(arguments);try{var e=i.map(function(n){return Gn(n,t)});return n.handleEvent?n.handleEvent.apply(this,e):n.apply(this,e)}catch(n){throw Bn+=1,setTimeout(function(){Bn-=1}),Z(function(r){r.addEventProcessor(function(n){var r=u({},n);return t.mechanism&&_(r,void 0,void 0,t.mechanism),r.extra=u({},r.extra,{arguments:C(i,3)}),r}),captureException(n)}),n}};try{for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(sentryWrapped[i]=n[i])}catch(n){}n.prototype=n.prototype||{},sentryWrapped.prototype=n.prototype,Object.defineProperty(n,"__sentry_wrapped__",{enumerable:!1,value:sentryWrapped}),Object.defineProperties(sentryWrapped,{__sentry__:{enumerable:!1,value:!0},__sentry_original__:{enumerable:!1,value:n}});try{Object.defineProperty(sentryWrapped,"name",{get:function(){return n.name}})}catch(n){}return sentryWrapped}function Jn(n){return function(t){if(An=void 0,Cn!==t){var r;Cn=t;try{r=function(n){for(var t,r=n,i=[],e=0,o=0,u=" > ".length;r&&e++<5&&!("html"===(t=E(r))||e>1&&o+i.length*u+t.length>=80);)i.push(t),o+=t.length,r=r.parentNode;return i.reverse().join(" > ")}(t.target)}catch(n){r=""}J().addBreadcrumb({category:"ui."+n,message:r},{event:t,name:n})}}}function Xn(){return function(n){var t;try{t=n.target}catch(n){return}var r=t&&t.tagName;r&&("INPUT"===r||"TEXTAREA"===r||t.isContentEditable)&&(An||Jn("input")(n),clearTimeout(An),An=setTimeout(function(){An=void 0},Wn))}}var zn=function(){function n(t){this.name=n.id,this.X=u({onerror:!0,onunhandledrejection:!0},t)}return n.prototype.setupOnce=function(){Error.stackTraceLimit=50,Sn(function(t,r,i){if(!(Bn>0)){var e=J().getIntegration(n);e&&J().captureEvent(e.wn(t),{data:{stack:t},originalException:i})}}),this.X.onerror&&(q.log("Global Handler attached: onerror"),_n()),this.X.onunhandledrejection&&(q.log("Global Handler attached: onunhandledrejection"),On())},n.prototype.wn=function(n){var t=Dn(n),r={mode:n.mode};n.message&&(r.message=n.message),n.name&&(r.name=n.name);var i=J().getClient(),e=i&&i.getOptions().maxValueLength||250;return _(t,n.original?rn(JSON.stringify(C(n.original)),e):"","onunhandledrejection"===n.mechanism?"UnhandledRejection":"Error",{data:r,handled:!1,type:n.mechanism}),t},n.id="GlobalHandlers",n}(),Vn=function(){function n(){this.gn=0,this.name=n.id}return n.prototype.En=function(n){return function(){for(var t=[],r=0;r"}catch(n){return""}}var Zn,Qn=w(),Yn=function(){function t(n){this.name=t.id,this.X=u({console:!0,dom:!0,fetch:!0,history:!0,sentry:!0,xhr:!0},n)}return t.prototype.Sn=function(){"console"in Qn&&["debug","info","warn","error","log"].forEach(function(r){r in Qn.console&&T(Qn.console,r,function(i){return function(){for(var e=[],o=0;o2?t[2]:void 0;return i&&u(Zn,String(i)),n.apply(this,t)}}},t.prototype.Tn=function(){if("XMLHttpRequest"in Qn){var n=XMLHttpRequest.prototype;T(n,"open",function(n){return function(){for(var t=[],r=0;r"},handled:!0,type:"instrument"}})})}(n,e)}),"onreadystatechange"in e&&"function"==typeof e.onreadystatechange?T(e,"onreadystatechange",function(n){return Gn(n,{mechanism:{data:{function:"onreadystatechange",handler:n&&n.name||""},handled:!0,type:"instrument"}},o)}):e.onreadystatechange=o,n.apply(this,r)}})}},t.addBreadcrumb=function(n,r){J().getIntegration(t)&&J().addBreadcrumb(n,r)},t.prototype.setupOnce=function(){this.X.console&&this.Sn(),this.X.dom&&this._n(),this.X.xhr&&this.Tn(),this.X.fetch&&this.On(),this.X.history&&this.kn()},t.id="Breadcrumbs",t}();function nt(t){try{var r=JSON.parse(t);Yn.addBreadcrumb({category:"sentry",event_id:r.event_id,level:r.level||n.Severity.fromString("error"),message:j(r)},{event:r})}catch(n){q.error("Error while adding sentry type breadcrumb")}}var tt="cause",rt=5,it=function(){function n(t){void 0===t&&(t={}),this.name=n.id,this.Rn=t.key||tt,this.mn=t.limit||rt}return n.prototype.setupOnce=function(){U(function(t,r){var i=J().getIntegration(n);return i?i.handler(t,r):t})},n.prototype.handler=function(n,t){if(!(n.exception&&n.exception.values&&t&&t.originalException instanceof Error))return n;var r=this.walkErrorTree(t.originalException,this.Rn);return n.exception.values=a(r,n.exception.values),n},n.prototype.walkErrorTree=function(n,t,r){if(void 0===r&&(r=[]),!(n[t]instanceof Error)||r.length+1>=this.mn)return r;var i=Rn(kn(n[t]));return this.walkErrorTree(n[t],t,a([i],r))},n.id="LinkedErrors",n}(),et=w(),ot=function(){function n(){this.name=n.id}return n.prototype.setupOnce=function(){U(function(t){if(J().getIntegration(n)){if(!et.navigator||!et.location)return t;var r=t.request||{};return r.url=r.url||et.location.href,r.headers=r.headers||{},r.headers["User-Agent"]=et.navigator.userAgent,u({},t,{request:r})}return t})},n.id="UserAgent",n}(),ut=Object.freeze({GlobalHandlers:zn,TryCatch:Vn,Breadcrumbs:Yn,LinkedErrors:it,UserAgent:ot}),ct=[new dn,new vn,new Vn,new Yn,new zn,new it,new ot];var st={},ft=w();ft.Sentry&&ft.Sentry.Integrations&&(st=ft.Sentry.Integrations);var at=u({},st,pn,ut);return n.Integrations=at,n.Transports=Pn,n.addGlobalEventProcessor=U,n.addBreadcrumb=function(n){K("addBreadcrumb",n)},n.captureException=captureException,n.captureEvent=function(n){return K("captureEvent",n)},n.captureMessage=function(n,t){var r;try{throw new Error(n)}catch(n){r=n}return K("captureMessage",n,t,{originalException:n,syntheticException:r})},n.configureScope=function(n){K("configureScope",n)},n.withScope=Z,n.getHubFromCarrier=z,n.getCurrentHub=J,n.Hub=W,n.Scope=N,n.BrowserClient=Hn,n.defaultIntegrations=ct,n.forceLoad=function(){},n.init=function(n){void 0===n&&(n={}),void 0===n.defaultIntegrations&&(n.defaultIntegrations=ct),function(n,t){!0===t.debug&&q.enable(),J().bindClient(new n(t))}(Hn,n)},n.lastEventId=function(){return J().lastEventId()},n.onLoad=function(n){n()},n.showReportDialog=function(n){void 0===n&&(n={}),n.eventId||(n.eventId=J().lastEventId());var t=J().getClient();t&&t.showReportDialog(n)},n.flush=function(n){return c(this,void 0,void 0,function(){var t;return s(this,function(r){return(t=J().getClient())?[2,t.flush(n)]:[2,Promise.reject(!1)]})})},n.close=function(n){return c(this,void 0,void 0,function(){var t;return s(this,function(r){return(t=J().getClient())?[2,t.close(n)]:[2,Promise.reject(!1)]})})},n.SDK_NAME=qn,n.SDK_VERSION="5.0.5",n}({}); +/*! @sentry/browser 5.18.1 (b1261aab) | https://github.com/getsentry/sentry-javascript */ +var Sentry=function(t){var n=function(t,r){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var r in n)n.hasOwnProperty(r)&&(t[r]=n[r])})(t,r)};function r(t,r){function e(){this.constructor=t}n(t,r),t.prototype=null===r?Object.create(r):(e.prototype=r.prototype,new e)}var e=function(){return(e=Object.assign||function(t){for(var n,r=1,e=arguments.length;r=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}}}function o(t,n){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var e,i,o=r.call(t),u=[];try{for(;(void 0===n||n-- >0)&&!(e=o.next()).done;)u.push(e.value)}catch(t){i={error:t}}finally{try{e&&!e.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return u}function u(){for(var t=[],n=0;n=200&&n<300?t.Success:429===n?t.RateLimit:n>=400&&n<500?t.Invalid:n>=500?t.Failed:t.Unknown}}(t.Status||(t.Status={}));var f=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(t,n){return t.__proto__=n,t}:function(t,n){for(var r in n)t.hasOwnProperty(r)||(t[r]=n[r]);return t});var h=function(t){function n(n){var r=this.constructor,e=t.call(this,n)||this;return e.message=n,e.name=r.prototype.constructor.name,f(e,r.prototype),e}return r(n,t),n}(Error);function v(t){switch(Object.prototype.toString.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":return!0;default:return E(t,Error)}}function l(t){return"[object ErrorEvent]"===Object.prototype.toString.call(t)}function d(t){return"[object DOMError]"===Object.prototype.toString.call(t)}function p(t){return"[object String]"===Object.prototype.toString.call(t)}function y(t){return null===t||"object"!=typeof t&&"function"!=typeof t}function m(t){return"[object Object]"===Object.prototype.toString.call(t)}function b(t){return"undefined"!=typeof Event&&E(t,Event)}function w(t){return"undefined"!=typeof Element&&E(t,Element)}function g(t){return Boolean(t&&t.then&&"function"==typeof t.then)}function E(t,n){try{return t instanceof n}catch(t){return!1}}function x(t,n){return void 0===n&&(n=0),"string"!=typeof t||0===n?t:t.length<=n?t:t.substr(0,n)+"..."}function j(t,n){if(!Array.isArray(t))return"";for(var r=[],e=0;e"}return t.event_id||""}function I(t){var n=O();if(!("console"in n))return t();var r=n.console,e={};["debug","info","warn","error","log","assert"].forEach(function(t){t in n.console&&r[t].__sentry_original__&&(e[t]=r[t],r[t]=r[t].__sentry_original__)});var i=t();return Object.keys(e).forEach(function(t){r[t]=e[t]}),i}function N(t,n,r){t.exception=t.exception||{},t.exception.values=t.exception.values||[],t.exception.values[0]=t.exception.values[0]||{},t.exception.values[0].value=t.exception.values[0].value||n||"",t.exception.values[0].type=t.exception.values[0].type||r||"Error"}function C(t,n){void 0===n&&(n={});try{t.exception.values[0].mechanism=t.exception.values[0].mechanism||{},Object.keys(n).forEach(function(r){t.exception.values[0].mechanism[r]=n[r]})}catch(t){}}function M(t){try{for(var n=t,r=[],e=0,i=0,o=" > ".length,u=void 0;n&&e++<5&&!("html"===(u=A(n))||e>1&&i+r.length*o+u.length>=80);)r.push(u),i+=u.length,n=n.parentNode;return r.reverse().join(" > ")}catch(t){return""}}function A(t){var n,r,e,i,o,u=t,c=[];if(!u||!u.tagName)return"";if(c.push(u.tagName.toLowerCase()),u.id&&c.push("#"+u.id),(n=u.className)&&p(n))for(r=n.split(/\s+/),o=0;o"}try{o.currentTarget=w(i.currentTarget)?M(i.currentTarget):Object.prototype.toString.call(i.currentTarget)}catch(t){o.currentTarget=""}for(var e in"undefined"!=typeof CustomEvent&&E(t,CustomEvent)&&(o.detail=i.detail),i)Object.prototype.hasOwnProperty.call(i,e)&&(o[e]=i);return o}return t}function Z(t){return function(t){return~-encodeURI(t).split(/%..|./).length}(JSON.stringify(t))}function tt(t,n,r){void 0===n&&(n=3),void 0===r&&(r=102400);var e=et(t,n);return Z(e)>r?tt(t,n-1,r):e}function nt(t,n){return"domain"===n&&t&&"object"==typeof t&&t.u?"[Domain]":"domainEmitter"===n?"[DomainEmitter]":"undefined"!=typeof global&&t===global?"[Global]":"undefined"!=typeof window&&t===window?"[Window]":"undefined"!=typeof document&&t===document?"[Document]":m(r=t)&&"nativeEvent"in r&&"preventDefault"in r&&"stopPropagation"in r?"[SyntheticEvent]":"number"==typeof t&&t!=t?"[NaN]":void 0===t?"[undefined]":"function"==typeof t?"[Function: "+$(t)+"]":t;var r}function rt(t,n,r,e){if(void 0===r&&(r=1/0),void 0===e&&(e=new K),0===r)return function(t){var n=Object.prototype.toString.call(t);if("string"==typeof t)return t;if("[object Object]"===n)return"[Object]";if("[object Array]"===n)return"[Array]";var r=nt(t);return y(r)?r:n}(n);if(null!=n&&"function"==typeof n.toJSON)return n.toJSON();var i=nt(n,t);if(y(i))return i;var o=Y(n),u=Array.isArray(n)?[]:{};if(e.memoize(n))return"[Circular ~]";for(var c in o)Object.prototype.hasOwnProperty.call(o,c)&&(u[c]=rt(c,o[c],r-1,e));return e.unmemoize(n),u}function et(t,n){try{return JSON.parse(JSON.stringify(t,function(t,r){return rt(t,r,n)}))}catch(t){return"**non-serializable**"}}function it(t,n){void 0===n&&(n=40);var r=Object.keys(Y(t));if(r.sort(),!r.length)return"[object has no keys]";if(r[0].length>=n)return x(r[0],n);for(var e=r.length;e>0;e--){var i=r.slice(0,e).join(", ");if(!(i.length>n))return e===r.length?i:x(i,n)}return""}!function(t){t.PENDING="PENDING",t.RESOLVED="RESOLVED",t.REJECTED="REJECTED"}(z||(z={}));var ot=function(){function t(t){var n=this;this.s=z.PENDING,this.h=[],this.v=function(t){n.l(z.RESOLVED,t)},this.p=function(t){n.l(z.REJECTED,t)},this.l=function(t,r){n.s===z.PENDING&&(g(r)?r.then(n.v,n.p):(n.s=t,n.m=r,n.g()))},this.j=function(t){n.h=n.h.concat(t),n.g()},this.g=function(){if(n.s!==z.PENDING){var t=n.h.slice();n.h=[],t.forEach(function(t){t.done||(n.s===z.RESOLVED&&t.onfulfilled&&t.onfulfilled(n.m),n.s===z.REJECTED&&t.onrejected&&t.onrejected(n.m),t.done=!0)})}};try{t(this.v,this.p)}catch(t){this.p(t)}}return t.prototype.toString=function(){return"[object SyncPromise]"},t.resolve=function(n){return new t(function(t){t(n)})},t.reject=function(n){return new t(function(t,r){r(n)})},t.all=function(n){return new t(function(r,e){if(Array.isArray(n))if(0!==n.length){var i=n.length,o=[];n.forEach(function(n,u){t.resolve(n).then(function(t){o[u]=t,0===(i-=1)&&r(o)}).then(null,e)})}else r([]);else e(new TypeError("Promise.all requires an array as input."))})},t.prototype.then=function(n,r){var e=this;return new t(function(t,i){e.j({done:!1,onfulfilled:function(r){if(n)try{return void t(n(r))}catch(t){return void i(t)}else t(r)},onrejected:function(n){if(r)try{return void t(r(n))}catch(t){return void i(t)}else i(n)}})})},t.prototype.catch=function(t){return this.then(function(t){return t},t)},t.prototype.finally=function(n){var r=this;return new t(function(t,e){var i,o;return r.then(function(t){o=!1,i=t,n&&n()},function(t){o=!0,i=t,n&&n()}).then(function(){o?e(i):t(i)})})},t}(),ut=function(){function t(t){this.k=t,this.S=[]}return t.prototype.isReady=function(){return void 0===this.k||this.length()0&&r(!1)},t);ot.all(n.S).then(function(){clearTimeout(e),r(!0)}).then(null,function(){r(!0)})})},t}();function ct(){if(!("fetch"in O()))return!1;try{return new Headers,new Request(""),new Response,!0}catch(t){return!1}}function at(t){return t&&/^function fetch\(\)\s+\{\s+\[native code\]\s+\}$/.test(t.toString())}function st(){if(!ct())return!1;try{return new Request("_",{referrerPolicy:"origin"}),!0}catch(t){return!1}}var ft,ht=O(),vt={},lt={};function dt(t){if(!lt[t])switch(lt[t]=!0,t){case"console":!function(){if(!("console"in ht))return;["debug","info","warn","error","log","assert"].forEach(function(t){t in ht.console&&Q(ht.console,t,function(n){return function(){for(var r=[],e=0;e2?n[2]:void 0;if(e){var i=ft,o=String(e);ft=o,yt("history",{from:i,to:o})}return t.apply(this,n)}}ht.onpopstate=function(){for(var t=[],n=0;n1&&(v=d.slice(0,-1).join("/"),l=d.pop()),l){var p=l.match(/^\d+/);p&&(l=p[0])}this.O({host:a,pass:c,path:v,projectId:l,port:f,protocol:e,user:i})},t.prototype.O=function(t){this.protocol=t.protocol,this.user=t.user,this.pass=t.pass||"",this.host=t.host,this.port=t.port||"",this.path=t.path||"",this.projectId=t.projectId},t.prototype._=function(){var t=this;if(["protocol","user","host","projectId"].forEach(function(n){if(!t[n])throw new h("Invalid Dsn: "+n+" missing")}),!this.projectId.match(/^\d+$/))throw new h("Invalid Dsn: Invalid projectId "+this.projectId);if("http"!==this.protocol&&"https"!==this.protocol)throw new h("Invalid Dsn: Invalid protocol "+this.protocol);if(this.port&&isNaN(parseInt(this.port,10)))throw new h("Invalid Dsn: Invalid port "+this.port)},t}(),Dt=function(){function t(){this.D=!1,this.R=[],this.I=[],this.N=[],this.C={},this.M={},this.A={},this.q={}}return t.prototype.addScopeListener=function(t){this.R.push(t)},t.prototype.addEventProcessor=function(t){return this.I.push(t),this},t.prototype.U=function(){var t=this;this.D||(this.D=!0,setTimeout(function(){t.R.forEach(function(n){n(t)}),t.D=!1}))},t.prototype.L=function(t,n,r,i){var o=this;return void 0===i&&(i=0),new ot(function(u,c){var a=t[i];if(null===n||"function"!=typeof a)u(n);else{var s=a(e({},n),r);g(s)?s.then(function(n){return o.L(t,n,r,i+1).then(u)}).then(null,c):o.L(t,s,r,i+1).then(u).then(null,c)}})},t.prototype.setUser=function(t){return this.C=t||{},this.U(),this},t.prototype.setTags=function(t){return this.M=e({},this.M,t),this.U(),this},t.prototype.setTag=function(t,n){var r;return this.M=e({},this.M,((r={})[t]=n,r)),this.U(),this},t.prototype.setExtras=function(t){return this.A=e({},this.A,t),this.U(),this},t.prototype.setExtra=function(t,n){var r;return this.A=e({},this.A,((r={})[t]=n,r)),this.U(),this},t.prototype.setFingerprint=function(t){return this.H=t,this.U(),this},t.prototype.setLevel=function(t){return this.F=t,this.U(),this},t.prototype.setTransactionName=function(t){return this.P=t,this.U(),this},t.prototype.setTransaction=function(t){return this.setTransactionName(t)},t.prototype.setContext=function(t,n){var r;return this.q=e({},this.q,((r={})[t]=n,r)),this.U(),this},t.prototype.setSpan=function(t){return this.X=t,this.U(),this},t.prototype.getSpan=function(){return this.X},t.prototype.getTransaction=function(){var t=this.getSpan();if(t&&t.spanRecorder&&t.spanRecorder.spans[0])return t.spanRecorder.spans[0]},t.clone=function(n){var r=new t;return n&&(r.N=u(n.N),r.M=e({},n.M),r.A=e({},n.A),r.q=e({},n.q),r.C=n.C,r.F=n.F,r.X=n.X,r.P=n.P,r.H=n.H,r.I=u(n.I)),r},t.prototype.update=function(n){if(!n)return this;if("function"==typeof n){var r=n(this);return r instanceof t?r:this}return n instanceof t?(this.M=e({},this.M,n.M),this.A=e({},this.A,n.A),this.q=e({},this.q,n.q),n.C&&(this.C=n.C),n.F&&(this.F=n.F),n.H&&(this.H=n.H)):m(n)&&(n=n,this.M=e({},this.M,n.tags),this.A=e({},this.A,n.extra),this.q=e({},this.q,n.contexts),n.user&&(this.C=n.user),n.level&&(this.F=n.level),n.fingerprint&&(this.H=n.fingerprint)),this},t.prototype.clear=function(){return this.N=[],this.M={},this.A={},this.C={},this.q={},this.F=void 0,this.P=void 0,this.H=void 0,this.X=void 0,this.U(),this},t.prototype.addBreadcrumb=function(t,n){var r=e({timestamp:F()},t);return this.N=void 0!==n&&n>=0?u(this.N,[r]).slice(-n):u(this.N,[r]),this.U(),this},t.prototype.clearBreadcrumbs=function(){return this.N=[],this.U(),this},t.prototype.W=function(t){t.fingerprint=t.fingerprint?Array.isArray(t.fingerprint)?t.fingerprint:[t.fingerprint]:[],this.H&&(t.fingerprint=t.fingerprint.concat(this.H)),t.fingerprint&&!t.fingerprint.length&&delete t.fingerprint},t.prototype.applyToEvent=function(t,n){return this.A&&Object.keys(this.A).length&&(t.extra=e({},this.A,t.extra)),this.M&&Object.keys(this.M).length&&(t.tags=e({},this.M,t.tags)),this.C&&Object.keys(this.C).length&&(t.user=e({},this.C,t.user)),this.q&&Object.keys(this.q).length&&(t.contexts=e({},this.q,t.contexts)),this.F&&(t.level=this.F),this.P&&(t.transaction=this.P),this.X&&(t.contexts=e({trace:this.X.getTraceContext()},t.contexts)),this.W(t),t.breadcrumbs=u(t.breadcrumbs||[],this.N),t.breadcrumbs=t.breadcrumbs.length>0?t.breadcrumbs:void 0,this.L(u(Rt(),this.I),t,n)},t}();function Rt(){var t=O();return t.__SENTRY__=t.__SENTRY__||{},t.__SENTRY__.globalEventProcessors=t.__SENTRY__.globalEventProcessors||[],t.__SENTRY__.globalEventProcessors}function It(t){Rt().push(t)}var Nt=3,Ct=function(){function t(t,n,r){void 0===n&&(n=new Dt),void 0===r&&(r=Nt),this.$=r,this.B=[],this.B.push({client:t,scope:n}),this.bindClient(t)}return t.prototype.G=function(t){for(var n,r=[],e=1;e0?t[t.length-1].scope:void 0,r=Dt.clone(n);return this.getStack().push({client:this.getClient(),scope:r}),r},t.prototype.popScope=function(){return void 0!==this.getStack().pop()},t.prototype.withScope=function(t){var n=this.pushScope();try{t(n)}finally{this.popScope()}},t.prototype.getClient=function(){return this.getStackTop().client},t.prototype.getScope=function(){return this.getStackTop().scope},t.prototype.getStack=function(){return this.B},t.prototype.getStackTop=function(){return this.B[this.B.length-1]},t.prototype.captureException=function(t,n){var r=this.J=_(),i=n;if(!n){var o=void 0;try{throw new Error("Sentry syntheticException")}catch(t){o=t}i={originalException:t,syntheticException:o}}return this.G("captureException",t,e({},i,{event_id:r})),r},t.prototype.captureMessage=function(t,n,r){var i=this.J=_(),o=r;if(!r){var u=void 0;try{throw new Error(t)}catch(t){u=t}o={originalException:t,syntheticException:u}}return this.G("captureMessage",t,n,e({},o,{event_id:i})),i},t.prototype.captureEvent=function(t,n){var r=this.J=_();return this.G("captureEvent",t,e({},n,{event_id:r})),r},t.prototype.lastEventId=function(){return this.J},t.prototype.addBreadcrumb=function(t,n){var r=this.getStackTop();if(r.scope&&r.client){var i=r.client.getOptions&&r.client.getOptions()||{},o=i.beforeBreadcrumb,u=void 0===o?null:o,c=i.maxBreadcrumbs,a=void 0===c?100:c;if(!(a<=0)){var s=F(),f=e({timestamp:s},t),h=u?I(function(){return u(f,n)}):f;null!==h&&r.scope.addBreadcrumb(h,Math.min(a,100))}}},t.prototype.setUser=function(t){var n=this.getStackTop();n.scope&&n.scope.setUser(t)},t.prototype.setTags=function(t){var n=this.getStackTop();n.scope&&n.scope.setTags(t)},t.prototype.setExtras=function(t){var n=this.getStackTop();n.scope&&n.scope.setExtras(t)},t.prototype.setTag=function(t,n){var r=this.getStackTop();r.scope&&r.scope.setTag(t,n)},t.prototype.setExtra=function(t,n){var r=this.getStackTop();r.scope&&r.scope.setExtra(t,n)},t.prototype.setContext=function(t,n){var r=this.getStackTop();r.scope&&r.scope.setContext(t,n)},t.prototype.configureScope=function(t){var n=this.getStackTop();n.scope&&n.client&&t(n.scope)},t.prototype.run=function(t){var n=At(this);try{t(this)}finally{At(n)}},t.prototype.getIntegration=function(t){var n=this.getClient();if(!n)return null;try{return n.getIntegration(t)}catch(n){return V.warn("Cannot retrieve integration "+t.id+" from the current Hub"),null}},t.prototype.startSpan=function(t){return this.V("startSpan",t)},t.prototype.startTransaction=function(t){return this.V("startTransaction",t)},t.prototype.traceHeaders=function(){return this.V("traceHeaders")},t.prototype.V=function(t){for(var n=[],r=1;r=t&&r({interval:i,ready:!1})):r({interval:i,ready:!0})},1)})},t.prototype.ut=function(){return this.et},t.prototype.st=function(){return!1!==this.getOptions().enabled&&void 0!==this.ot},t.prototype.ft=function(t,n,r){var i=this,o=this.getOptions().normalizeDepth,u=void 0===o?3:o,c=e({},t,{event_id:t.event_id||(r&&r.event_id?r.event_id:_()),timestamp:t.timestamp||F()});this.ht(c),this.vt(c);var a=n;r&&r.captureContext&&(a=Dt.clone(a).update(r.captureContext));var s=ot.resolve(c);return a&&(s=a.applyToEvent(c,r)),s.then(function(t){return"number"==typeof u&&u>0?i.lt(t,u):t})},t.prototype.lt=function(t,n){if(!t)return null;var r=e({},t,t.breadcrumbs&&{breadcrumbs:t.breadcrumbs.map(function(t){return e({},t,t.data&&{data:et(t.data,n)})})},t.user&&{user:et(t.user,n)},t.contexts&&{contexts:et(t.contexts,n)},t.extra&&{extra:et(t.extra,n)});return t.contexts&&t.contexts.trace&&(r.contexts.trace=t.contexts.trace),r},t.prototype.ht=function(t){var n=this.getOptions(),r=n.environment,e=n.release,i=n.dist,o=n.maxValueLength,u=void 0===o?250:o;void 0===t.environment&&void 0!==r&&(t.environment=r),void 0===t.release&&void 0!==e&&(t.release=e),void 0===t.dist&&void 0!==i&&(t.dist=i),t.message&&(t.message=x(t.message,u));var c=t.exception&&t.exception.values&&t.exception.values[0];c&&c.value&&(c.value=x(c.value,u));var a=t.request;a&&a.url&&(a.url=x(a.url,u))},t.prototype.vt=function(t){var n=t.sdk,r=Object.keys(this.nt);n&&r.length>0&&(n.integrations=r)},t.prototype.dt=function(t){this.ut().sendEvent(t)},t.prototype.ct=function(t,n,r){var e=this,i=this.getOptions(),o=i.beforeSend,u=i.sampleRate;if(!this.st())return ot.reject("SDK not enabled, will not send event.");var c="transaction"===t.type;return!c&&"number"==typeof u&&Math.random()>u?ot.reject("This event has been sampled, will not send event."):new ot(function(i,u){e.ft(t,r,n).then(function(t){if(null!==t){var r=t;if(n&&n.data&&!0===n.data.__sentry__||!o||c)return e.dt(r),void i(r);var a=o(t,n);if(void 0===a)V.error("`beforeSend` method has to return `null` or a valid event.");else if(g(a))e.pt(a,i,u);else{if(null===(r=a))return V.log("`beforeSend` returned `null`, will not send event."),void i(null);e.dt(r),i(r)}}else u("An event processor returned null, will not send event.")}).then(null,function(t){e.captureException(t,{data:{__sentry__:!0},originalException:t}),u("Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: "+t)})})},t.prototype.pt=function(t,n,r){var e=this;t.then(function(t){null!==t?(e.dt(t),n(t)):r("`beforeSend` returned `null`, will not send event.")}).then(null,function(t){r("beforeSend rejected with "+t)})},t}(),Jt=function(){function n(){}return n.prototype.sendEvent=function(n){return ot.resolve({reason:"NoopTransport: Event has been skipped because no Dsn is configured.",status:t.Status.Skipped})},n.prototype.close=function(t){return ot.resolve(!0)},n}(),zt=function(){function t(t){this.it=t,this.it.dsn||V.warn("No DSN provided, backend will not do anything."),this.yt=this.bt()}return t.prototype.bt=function(){return new Jt},t.prototype.eventFromException=function(t,n){throw new h("Backend has to implement `eventFromException` method")},t.prototype.eventFromMessage=function(t,n,r){throw new h("Backend has to implement `eventFromMessage` method")},t.prototype.sendEvent=function(t){this.yt.sendEvent(t).then(null,function(t){V.error("Error while sending event: "+t)})},t.prototype.getTransport=function(){return this.yt},t}();function Vt(t,n){var r="transaction"===t.type,e={body:JSON.stringify(t),url:r?n.getEnvelopeEndpointWithUrlEncodedAuth():n.getStoreEndpointWithUrlEncodedAuth()};if(r){var i=JSON.stringify({event_id:t.event_id,sent_at:new Date(1e3*F()).toISOString()})+"\n"+JSON.stringify({type:t.type})+"\n"+e.body;e.body=i}return e}var Kt=function(){function t(){this.name=t.id}return t.prototype.setupOnce=function(){Bt=Function.prototype.toString,Function.prototype.toString=function(){for(var t=[],n=0;n|[-a-z]+:|.*bundle|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,rn=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:file|https?|blob|chrome|webpack|resource|moz-extension).*?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js))(?::(\d+))?(?::(\d+))?\s*$/i,en=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i,on=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,un=/\((\S*)(?::(\d+))(?::(\d+))\)/;function cn(t){var n=null,r=t&&t.framesToPop;try{if(n=function(t){if(!t||!t.stacktrace)return null;for(var n,r=t.stacktrace,e=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,i=/ line (\d+), column (\d+)\s*(?:in (?:]+)>|([^\)]+))\((.*)\))? in (.*):\s*$/i,o=r.split("\n"),u=[],c=0;c eval")>-1&&(n=on.exec(r[3]))?(r[1]=r[1]||"eval",r[3]=n[1],r[4]=n[2],r[5]=""):0!==u||r[5]||void 0===t.columnNumber||(i[0].column=t.columnNumber+1),e={url:r[3],func:r[1]||tn,args:r[2]?r[2].split(","):[],line:r[4]?+r[4]:null,column:r[5]?+r[5]:null}}!e.func&&e.line&&(e.func=tn),i.push(e)}if(!i.length)return null;return{message:sn(t),name:t.name,stack:i}}(t))return an(n,r)}catch(t){}return{message:sn(t),name:t&&t.name,stack:[],failed:!0}}function an(t,n){try{return e({},t,{stack:t.stack.slice(n)})}catch(n){return t}}function sn(t){var n=t&&t.message;return n?n.error&&"string"==typeof n.error.message?n.error.message:n:"No error message"}var fn=50;function hn(t){var n=ln(t.stack),r={type:t.name,value:t.message};return n&&n.length&&(r.stacktrace={frames:n}),void 0===r.type&&""===r.value&&(r.value="Unrecoverable error caught"),r}function vn(t){return{exception:{values:[hn(t)]}}}function ln(t){if(!t||!t.length)return[];var n=t,r=n[0].func||"",e=n[n.length-1].func||"";return-1===r.indexOf("captureMessage")&&-1===r.indexOf("captureException")||(n=n.slice(1)),-1!==e.indexOf("sentryWrapped")&&(n=n.slice(0,-1)),n.slice(0,fn).map(function(t){return{colno:null===t.column?void 0:t.column,filename:t.url||n[0].url,function:t.func||"?",in_app:!0,lineno:null===t.line?void 0:t.line}}).reverse()}function dn(t,n,r){var e,i;if(void 0===r&&(r={}),l(t)&&t.error)return e=vn(cn(t=t.error));if(d(t)||(i=t,"[object DOMException]"===Object.prototype.toString.call(i))){var o=t,u=o.name||(d(o)?"DOMError":"DOMException"),c=o.message?u+": "+o.message:u;return N(e=pn(c,n,r),c),e}return v(t)?e=vn(cn(t)):m(t)||b(t)?(C(e=function(t,n,r){var e={exception:{values:[{type:b(t)?t.constructor.name:r?"UnhandledRejection":"Error",value:"Non-Error "+(r?"promise rejection":"exception")+" captured with keys: "+it(t)}]},extra:{__serialized__:tt(t)}};if(n){var i=ln(cn(n).stack);e.stacktrace={frames:i}}return e}(t,n,r.rejection),{synthetic:!0}),e):(N(e=pn(t,n,r),""+t,void 0),C(e,{synthetic:!0}),e)}function pn(t,n,r){void 0===r&&(r={});var e={message:t};if(r.attachStacktrace&&n){var i=ln(cn(n).stack);e.stacktrace={frames:i}}return e}var yn=function(){function t(t){this.options=t,this.S=new ut(30),this.Ot=new Xt(this.options.dsn),this.url=this.Ot.getStoreEndpointWithUrlEncodedAuth()}return t.prototype.sendEvent=function(t){throw new h("Transport Class has to implement `sendEvent` method")},t.prototype.close=function(t){return this.S.drain(t)},t}(),mn=O(),bn=function(n){function e(){var t=null!==n&&n.apply(this,arguments)||this;return t._t=new Date(Date.now()),t}return r(e,n),e.prototype.sendEvent=function(n){var r=this;if(new Date(Date.now())0}function kn(t,n,r){if(void 0===n&&(n={}),"function"!=typeof t)return t;try{if(t.__sentry__)return t;if(t.__sentry_wrapped__)return t.__sentry_wrapped__}catch(n){return t}var sentryWrapped=function(){var i=Array.prototype.slice.call(arguments);try{r&&"function"==typeof r&&r.apply(this,arguments);var o=i.map(function(t){return kn(t,n)});return t.handleEvent?t.handleEvent.apply(this,o):t.apply(this,o)}catch(t){throw xn+=1,setTimeout(function(){xn-=1}),Pt(function(r){r.addEventProcessor(function(t){var r=e({},t);return n.mechanism&&(N(r,void 0,void 0),C(r,n.mechanism)),r.extra=e({},r.extra,{arguments:i}),r}),captureException(t)}),t}};try{for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(sentryWrapped[i]=t[i])}catch(t){}t.prototype=t.prototype||{},sentryWrapped.prototype=t.prototype,Object.defineProperty(t,"__sentry_wrapped__",{enumerable:!1,value:sentryWrapped}),Object.defineProperties(sentryWrapped,{__sentry__:{enumerable:!1,value:!0},__sentry_original__:{enumerable:!1,value:t}});try{Object.getOwnPropertyDescriptor(sentryWrapped,"name").configurable&&Object.defineProperty(sentryWrapped,"name",{get:function(){return t.name}})}catch(t){}return sentryWrapped}var Sn=function(){function n(t){this.name=n.id,this.Dt=!1,this.Rt=!1,this.it=e({onerror:!0,onunhandledrejection:!0},t)}return n.prototype.setupOnce=function(){Error.stackTraceLimit=50,this.it.onerror&&(V.log("Global Handler attached: onerror"),this.It()),this.it.onunhandledrejection&&(V.log("Global Handler attached: onunhandledrejection"),this.Nt())},n.prototype.It=function(){var t=this;this.Dt||(pt({callback:function(r){var e=r.error,i=qt(),o=i.getIntegration(n),u=e&&!0===e.__sentry_own_request__;if(o&&!jn()&&!u){var c=i.getClient(),a=y(e)?t.Ct(r.msg,r.url,r.line,r.column):t.Mt(dn(e,void 0,{attachStacktrace:c&&c.getOptions().attachStacktrace,rejection:!1}),r.url,r.line,r.column);C(a,{handled:!1,type:"onerror"}),i.captureEvent(a,{originalException:e})}},type:"error"}),this.Dt=!0)},n.prototype.Nt=function(){var r=this;this.Rt||(pt({callback:function(e){var i=e;try{"reason"in e?i=e.reason:"detail"in e&&"reason"in e.detail&&(i=e.detail.reason)}catch(t){}var o=qt(),u=o.getIntegration(n),c=i&&!0===i.__sentry_own_request__;if(!u||jn()||c)return!0;var a=o.getClient(),s=y(i)?r.At(i):dn(i,void 0,{attachStacktrace:a&&a.getOptions().attachStacktrace,rejection:!0});s.level=t.Severity.Error,C(s,{handled:!1,type:"onunhandledrejection"}),o.captureEvent(s,{originalException:i})},type:"unhandledrejection"}),this.Rt=!0)},n.prototype.Ct=function(t,n,r,e){var i,o=l(t)?t.message:t;if(p(o)){var u=o.match(/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i);u&&(i=u[1],o=u[2])}var c={exception:{values:[{type:i||"Error",value:o}]}};return this.Mt(c,n,r,e)},n.prototype.At=function(t){return{exception:{values:[{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+t}]}}},n.prototype.Mt=function(t,n,r,e){t.exception=t.exception||{},t.exception.values=t.exception.values||[],t.exception.values[0]=t.exception.values[0]||{},t.exception.values[0].stacktrace=t.exception.values[0].stacktrace||{},t.exception.values[0].stacktrace.frames=t.exception.values[0].stacktrace.frames||[];var i=isNaN(parseInt(e,10))?void 0:e,o=isNaN(parseInt(r,10))?void 0:r,u=p(n)&&n.length>0?n:function(){try{return document.location.href}catch(t){return""}}();return 0===t.exception.values[0].stacktrace.frames.length&&t.exception.values[0].stacktrace.frames.push({colno:i,filename:u,function:"?",in_app:!0,lineno:o}),t},n.id="GlobalHandlers",n}(),Tn=["EventTarget","Window","Node","ApplicationCache","AudioTrackList","ChannelMergerNode","CryptoOperation","EventSource","FileReader","HTMLUnknownElement","IDBDatabase","IDBRequest","IDBTransaction","KeyOperation","MediaController","MessagePort","ModalWindow","Notification","SVGElementInstance","Screen","TextTrack","TextTrackCue","TextTrackList","WebSocket","WebSocketWorker","Worker","XMLHttpRequest","XMLHttpRequestEventTarget","XMLHttpRequestUpload"],On=function(){function t(n){this.name=t.id,this.it=e({XMLHttpRequest:!0,eventTarget:!0,requestAnimationFrame:!0,setInterval:!0,setTimeout:!0},n)}return t.prototype.qt=function(t){return function(){for(var n=[],r=0;r"}0!==n.length&&qt().addBreadcrumb({category:"ui."+t.name,message:n},{event:t.event,name:t.name})},n.prototype.Xt=function(t){if(t.endTimestamp){if(t.xhr.__sentry_own_request__)return;qt().addBreadcrumb({category:"xhr",data:t.xhr.__sentry_xhr__,type:"http"},{xhr:t.xhr})}else;},n.prototype.Wt=function(n){n.endTimestamp&&(n.fetchData.url.match(/sentry_key/)&&"POST"===n.fetchData.method||(n.error?qt().addBreadcrumb({category:"fetch",data:n.fetchData,level:t.Severity.Error,type:"http"},{data:n.error,input:n.args}):qt().addBreadcrumb({category:"fetch",data:e({},n.fetchData,{status_code:n.response.status}),type:"http"},{input:n.args,response:n.response})))},n.prototype.$t=function(t){var n=O(),r=t.from,e=t.to,i=D(n.location.href),o=D(r),u=D(e);o.path||(o=i),i.protocol===u.protocol&&i.host===u.host&&(e=u.relative),i.protocol===o.protocol&&i.host===o.host&&(r=o.relative),qt().addBreadcrumb({category:"navigation",data:{from:r,to:e}})},n.prototype.setupOnce=function(){var t=this;this.it.console&&pt({callback:function(){for(var n=[],r=0;r=this.k)return r;var e=hn(cn(t[n]));return this.Jt(t[n],n,u([e],r))},t.id="LinkedErrors",t}(),Nn=O(),Cn=function(){function t(){this.name=t.id}return t.prototype.setupOnce=function(){It(function(n){if(qt().getIntegration(t)){if(!Nn.navigator||!Nn.location)return n;var r=n.request||{};return r.url=r.url||Nn.location.href,r.headers=r.headers||{},r.headers["User-Agent"]=Nn.navigator.userAgent,e({},n,{request:r})}return n})},t.id="UserAgent",t}(),Mn=Object.freeze({GlobalHandlers:Sn,TryCatch:On,Breadcrumbs:_n,LinkedErrors:In,UserAgent:Cn}),An="sentry.javascript.browser",qn=function(t){function n(n){return void 0===n&&(n={}),t.call(this,En,n)||this}return r(n,t),n.prototype.ft=function(n,r,i){return n.platform=n.platform||"javascript",n.sdk=e({},n.sdk,{name:An,packages:u(n.sdk&&n.sdk.packages||[],[{name:"npm:@sentry/browser",version:"5.18.1"}]),version:"5.18.1"}),t.prototype.ft.call(this,n,r,i)},n.prototype.dt=function(n){var r=this.getIntegration(_n);r&&r.addSentryBreadcrumb(n),t.prototype.dt.call(this,n)},n.prototype.showReportDialog=function(t){void 0===t&&(t={});var n=O().document;if(n)if(this.st()){var r=t.dsn||this.getDsn();if(t.eventId)if(r){var e=n.createElement("script");e.async=!0,e.src=new Xt(r).getReportDialogEndpoint(t),t.onLoad&&(e.onload=t.onLoad),(n.head||n.body).appendChild(e)}else V.error("Missing `Dsn` option in showReportDialog call");else V.error("Missing `eventId` option in showReportDialog call")}else V.error("Trying to call showReportDialog with Sentry Client is disabled")},n}(Gt),Un=[new Yt,new Kt,new On,new _n,new Sn,new In,new Cn];var Ln={},Hn=O();Hn.Sentry&&Hn.Sentry.Integrations&&(Ln=Hn.Sentry.Integrations);var Fn=e({},Ln,Zt,Mn);return t.BrowserClient=qn,t.Hub=Ct,t.Integrations=Fn,t.SDK_NAME=An,t.SDK_VERSION="5.18.1",t.Scope=Dt,t.Transports=gn,t.addBreadcrumb=function(t){Ft("addBreadcrumb",t)},t.addGlobalEventProcessor=It,t.captureEvent=function(t){return Ft("captureEvent",t)},t.captureException=captureException,t.captureMessage=function(t,n){var r;try{throw new Error(t)}catch(t){r=t}return Ft("captureMessage",t,"string"==typeof n?n:void 0,e({originalException:t,syntheticException:r},"string"!=typeof n?{captureContext:n}:void 0))},t.close=function(t){var n=qt().getClient();return n?n.close(t):ot.reject(!1)},t.configureScope=function(t){Ft("configureScope",t)},t.defaultIntegrations=Un,t.flush=function(t){var n=qt().getClient();return n?n.flush(t):ot.reject(!1)},t.forceLoad=function(){},t.getCurrentHub=qt,t.getHubFromCarrier=Lt,t.init=function(t){if(void 0===t&&(t={}),void 0===t.defaultIntegrations&&(t.defaultIntegrations=Un),void 0===t.release){var n=O();n.SENTRY_RELEASE&&n.SENTRY_RELEASE.id&&(t.release=n.SENTRY_RELEASE.id)}!function(t,n){!0===n.debug&&V.enable();var r=qt(),e=new t(n);r.bindClient(e)}(qn,t)},t.lastEventId=function(){return qt().lastEventId()},t.makeMain=At,t.onLoad=function(t){t()},t.setContext=function(t,n){Ft("setContext",t,n)},t.setExtra=function(t,n){Ft("setExtra",t,n)},t.setExtras=function(t){Ft("setExtras",t)},t.setTag=function(t,n){Ft("setTag",t,n)},t.setTags=function(t){Ft("setTags",t)},t.setUser=function(t){Ft("setUser",t)},t.showReportDialog=function(t){void 0===t&&(t={}),t.eventId||(t.eventId=qt().lastEventId());var n=qt().getClient();n&&n.showReportDialog(t)},t.startTransaction=function(t){return Ft("startTransaction",e({},t))},t.withScope=Pt,t.wrap=function(t){return kn(t)()},t}({}); diff --git a/src/octoprint/plugins/errortracking/templates/errortracking_javascripts.jinja2 b/src/octoprint/plugins/errortracking/templates/errortracking_javascripts.jinja2 index d449fb7fd..776eaf8a5 100644 --- a/src/octoprint/plugins/errortracking/templates/errortracking_javascripts.jinja2 +++ b/src/octoprint/plugins/errortracking/templates/errortracking_javascripts.jinja2 @@ -8,18 +8,14 @@ Sentry.init({ dsn: errortracking_url_coreui, release: VERSION, - whitelistUrls: [ - // only include static assets - "/static/" - ], - blacklistUrls: [ - // exclude third party plugins - "/static/webassets/packed_plugins.js" + allowUrls: [ + // only include errors raise in HTML, packed core & client + {% assets "js_client" %}"{{ ASSET_URL }}",{% endassets %} + {% assets "js_core" %}"{{ ASSET_URL }}",{% endassets %} + {% if g.locale %}"{{ url_for('localeJs', locale=g.locale, domain='messages') }}"{% endif %} ] }); - Sentry.configureScope(function (scope) { - scope.setUser({"id": errortracking_unique_id}); - }); + Sentry.setUser({"id": errortracking_unique_id}); ERRORTRACKING_ENABLED = true; log.info("Initialized error tracking"); }; diff --git a/src/octoprint/plugins/gcodeviewer/__init__.py b/src/octoprint/plugins/gcodeviewer/__init__.py new file mode 100644 index 000000000..d4d9961d0 --- /dev/null +++ b/src/octoprint/plugins/gcodeviewer/__init__.py @@ -0,0 +1,69 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import octoprint.plugin + +from flask_babel import gettext + +class GcodeviewerPlugin(octoprint.plugin.AssetPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.SettingsPlugin): + + def get_assets(self): + js = ["js/gcodeviewer.js", + "js/viewer/ui.js", + "js/viewer/reader.js", + "js/viewer/renderer.js" + ] + + return dict(js=js, + less=["less/gcodeviewer.less"], + css=["css/gcodeviewer.css"]) + + def get_template_configs(self): + return [ + dict(type="tab", + template="gcodeviewer_tab.jinja2", + div="gcode", + styles=["display: none;"], + data_bind="visible: loginState.hasAllPermissionsKo(access.permissions.GCODE_VIEWER, access.permissions.FILES_DOWNLOAD)"), + dict(type="settings", + template="gcodeviewer_settings.jinja2", + custom_bindings=True), + dict(type="generic", + template="gcodeviewer_initscript.jinja2") + ] + + def get_settings_defaults(self): + return dict(mobileSizeThreshold=2 * 1024 * 1024, # 2MB + sizeThreshold=20 * 1024 * 1024) # 20MB + + def get_settings_version(self): + return 1 + + def on_settings_migrate(self, target, current): + if current is None: + config = self._settings.global_get(["gcodeViewer"]) + if config: + self._logger.info("Migrating settings from gcodeViewer to plugins.gcodeviewer...") + if "mobileSizeThreshold" in config: + self._settings.set_int(["mobileSizeThreshold"], config["mobileSizeThreshold"]) + if "sizeThreshold" in config: + self._settings.set_int(["sizeThreshold"], config["sizeThreshold"]) + self._settings.global_remove(["gcodeViewer"]) + + +__plugin_name__ = gettext("GCode Viewer") +__plugin_author__ = "Gina Häußge" +__plugin_description__ = "Provides a GCODE viewer in OctoPrint's UI." +__plugin_disabling_discouraged__ = gettext("Without this plugin the GCode Viewer in OctoPrint will no longer be " + "available.") +__plugin_license__ = "AGPLv3" +__plugin_pythoncompat__ = ">=2.7,<4" +__plugin_implementation__ = GcodeviewerPlugin() +#__plugin_hooks__ = { +# "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions +#} diff --git a/src/octoprint/plugins/gcodeviewer/static/css/gcodeviewer.css b/src/octoprint/plugins/gcodeviewer/static/css/gcodeviewer.css new file mode 100644 index 000000000..a4ed68acb --- /dev/null +++ b/src/octoprint/plugins/gcodeviewer/static/css/gcodeviewer.css @@ -0,0 +1 @@ +#gcode .progress{width:588px}#gcode .progress .bar{-webkit-transition:width 0s linear;-moz-transition:width 0s linear;-o-transition:width 0s linear;transition:width 0s linear}#gcode .canvas_container{position:relative}#gcode .canvas_container:hover,#gcode .canvas_container:active{outline:0}#gcode .layer-buttons{padding-top:5px;padding-bottom:7px}#gcode #gcode_layer_slider{position:absolute;right:0;top:0;height:568px;float:right}#gcode #gcode_layer_slider .slider-handle{width:14px;height:14px;margin-left:-3px;margin-top:-7px}#gcode #gcode_command_slider .slider-handle{width:14px;height:14px;margin-left:-7px;margin-top:-3px} \ No newline at end of file diff --git a/src/octoprint/static/js/app/viewmodels/gcode.js b/src/octoprint/plugins/gcodeviewer/static/js/gcodeviewer.js similarity index 97% rename from src/octoprint/static/js/app/viewmodels/gcode.js rename to src/octoprint/plugins/gcodeviewer/static/js/gcodeviewer.js index 6b5ab9bd4..364d1bcb9 100644 --- a/src/octoprint/static/js/app/viewmodels/gcode.js +++ b/src/octoprint/plugins/gcodeviewer/static/js/gcodeviewer.js @@ -6,6 +6,9 @@ $(function() { self.settings = parameters[1]; self.access = parameters[2]; + self.sizeThresholdStr = undefined; + self.mobileSizeThresholdStr = undefined; + self.ui_progress_percentage = ko.observable(); self.ui_progress_type = ko.observable(); self.ui_progress_text = ko.pureComputed(function() { @@ -285,6 +288,9 @@ $(function() { self.maxLayer = undefined; self.initialize = function() { + self.sizeThresholdStr = sizeObservable(self.settings.settings.plugins.gcodeviewer.sizeThreshold); + self.mobileSizeThresholdStr = sizeObservable(self.settings.settings.plugins.gcodeviewer.mobileSizeThreshold); + var layerSliderElement = $("#gcode_slider_layers"); var commandSliderElement = $("#gcode_slider_commands"); var containerElement = $("#gcode_canvas"); @@ -478,7 +484,8 @@ $(function() { self.selectedFile.date(data.job.file.date); self.selectedFile.size(data.job.file.size); - if (data.job.file.size > CONFIG_GCODE_SIZE_THRESHOLD || (OctoPrint.coreui.browser.mobile && data.job.file.size > CONFIG_GCODE_MOBILE_SIZE_THRESHOLD)) { + if (data.job.file.size > self.settings.settings.plugins.gcodeviewer.sizeThreshold() + || (OctoPrint.coreui.browser.mobile && data.job.file.size > self.settings.settings.plugins.gcodeviewer.mobileSizeThreshold())) { self.waitForApproval(true); self.loadedFilepath = undefined; self.loadedFileDate = undefined; @@ -754,6 +761,6 @@ $(function() { OCTOPRINT_VIEWMODELS.push({ construct: GcodeViewModel, dependencies: ["loginStateViewModel", "settingsViewModel", "accessViewModel"], - elements: ["#gcode", "#gcode_link"] + elements: ["#gcode", "#gcode_link", "#settings_plugin_gcodeviewer"] }); }); diff --git a/src/octoprint/static/gcodeviewer/js/gCodeReader.js b/src/octoprint/plugins/gcodeviewer/static/js/viewer/reader.js similarity index 100% rename from src/octoprint/static/gcodeviewer/js/gCodeReader.js rename to src/octoprint/plugins/gcodeviewer/static/js/viewer/reader.js diff --git a/src/octoprint/static/gcodeviewer/js/renderer.js b/src/octoprint/plugins/gcodeviewer/static/js/viewer/renderer.js similarity index 99% rename from src/octoprint/static/gcodeviewer/js/renderer.js rename to src/octoprint/plugins/gcodeviewer/static/js/viewer/renderer.js index f93db508d..f4e480e1b 100644 --- a/src/octoprint/static/gcodeviewer/js/renderer.js +++ b/src/octoprint/plugins/gcodeviewer/static/js/viewer/renderer.js @@ -680,7 +680,7 @@ GCODE.renderer = (function(){ // neither extrusion nor move if (cmd.retract == -1) { // retract => draw dot if configured to do so - if (renderOptions["showRetracts"]) { + if (renderOptions["showRetracts"] && !isNotCurrentLayer) { strokePathIfNeeded("fill"); ctx.fillStyle = getColorRetractForTool(tool); ctx.strokeStyle = ctx.fillStyle; @@ -689,7 +689,7 @@ GCODE.renderer = (function(){ } strokePathIfNeeded("move", getColorMoveForTool(tool)); - if(renderOptions["showMoves"]){ + if(renderOptions["showMoves"] && !isNotCurrentLayer) { // move => draw line from (prevX, prevY) to (x, y) in move color ctx.lineWidth = lineWidthFactor; ctx.lineTo(x,y); @@ -713,7 +713,7 @@ GCODE.renderer = (function(){ } } else { // we were previously retracting, now we are restarting => draw dot if configured to do so - if (renderOptions["showRetracts"]) { + if (renderOptions["showRetracts"] && !isNotCurrentLayer) { strokePathIfNeeded("fill"); ctx.fillStyle = getColorRestartForTool(tool); ctx.strokeStyle = ctx.fillStyle; @@ -731,7 +731,7 @@ GCODE.renderer = (function(){ ctx.stroke(); } - if (renderOptions["showHead"]) { + if (renderOptions["showHead"] && !isNotCurrentLayer) { var sizeHeadSpot = renderOptions["sizeHeadSpot"] * lineWidthFactor + lineWidthFactor / 2; var shade = tool * 0.15; ctx.fillStyle = pusher.color(renderOptions["colorHead"]).shade(shade).alpha(alpha).html(); diff --git a/src/octoprint/static/gcodeviewer/js/ui.js b/src/octoprint/plugins/gcodeviewer/static/js/viewer/ui.js similarity index 89% rename from src/octoprint/static/gcodeviewer/js/ui.js rename to src/octoprint/plugins/gcodeviewer/static/js/viewer/ui.js index b6c80323b..4cfcf74a9 100644 --- a/src/octoprint/static/gcodeviewer/js/ui.js +++ b/src/octoprint/plugins/gcodeviewer/static/js/viewer/ui.js @@ -97,14 +97,6 @@ GCODE.ui = (function(){ var warnings = []; var fatal = []; - Modernizr.addTest('filereader', function () { - return !!(window.File && window.FileList && window.FileReader); - }); - - if(!Modernizr.canvas)fatal.push("

  • Your browser doesn't seem to support HTML5 Canvas, this application won't work without it.
  • "); - if(!Modernizr.webworkers)fatal.push("
  • Your browser doesn't seem to support HTML5 Web Workers, this application won't work without it.
  • "); - if(!Modernizr.svg)fatal.push("
  • Your browser doesn't seem to support HTML5 SVG, this application won't work without it.
  • "); - var errorList = document.getElementById("errorList"); if(fatal.length>0){ if (errorList) { @@ -118,7 +110,6 @@ GCODE.ui = (function(){ warnings.push("
  • Your browser doesn't seem to support HTML5 Web GL, 3d mode is not recommended, going to be SLOW!
  • "); GCODE.renderer3d.setOption({rendererType: "canvas"}); } - if(!Modernizr.draganddrop)warnings.push("
  • Your browser doesn't seem to support HTML5 Drag'n'Drop, Drop area will not work.
  • "); if(warnings.length>0){ if (errorList) { diff --git a/src/octoprint/static/gcodeviewer/js/Worker.js b/src/octoprint/plugins/gcodeviewer/static/js/viewer/worker.js similarity index 100% rename from src/octoprint/static/gcodeviewer/js/Worker.js rename to src/octoprint/plugins/gcodeviewer/static/js/viewer/worker.js diff --git a/src/octoprint/plugins/gcodeviewer/static/less/gcodeviewer.less b/src/octoprint/plugins/gcodeviewer/static/less/gcodeviewer.less new file mode 100644 index 000000000..044cb5cce --- /dev/null +++ b/src/octoprint/plugins/gcodeviewer/static/less/gcodeviewer.less @@ -0,0 +1,50 @@ +/** GCODE viewer */ + +#gcode { + .progress { + width: 588px; + + .bar { + -webkit-transition: width 0s linear; + -moz-transition: width 0s linear; + -o-transition: width 0s linear; + transition: width 0s linear; + } + } + + .canvas_container { + position: relative; + &:hover, &:active { + outline: 0; + } + } + + .layer-buttons { + padding-top: 5px; + padding-bottom: 7px; + } + + #gcode_layer_slider { + position: absolute; + right: 0; + top: 0; + height: 568px; + float: right; + + .slider-handle { + width: 14px; + height: 14px; + margin-left: -3px; + margin-top: -7px; + } + } + + #gcode_command_slider { + .slider-handle { + width: 14px; + height: 14px; + margin-left: -7px; + margin-top: -3px; + } + } +} diff --git a/src/octoprint/plugins/gcodeviewer/templates/gcodeviewer_initscript.jinja2 b/src/octoprint/plugins/gcodeviewer/templates/gcodeviewer_initscript.jinja2 new file mode 100644 index 000000000..b5b7e1bde --- /dev/null +++ b/src/octoprint/plugins/gcodeviewer/templates/gcodeviewer_initscript.jinja2 @@ -0,0 +1,3 @@ + diff --git a/src/octoprint/templates/dialogs/settings/gcodevisualizer.jinja2 b/src/octoprint/plugins/gcodeviewer/templates/gcodeviewer_settings.jinja2 similarity index 58% rename from src/octoprint/templates/dialogs/settings/gcodevisualizer.jinja2 rename to src/octoprint/plugins/gcodeviewer/templates/gcodeviewer_settings.jinja2 index 4ae0dcebe..aea74d13a 100644 --- a/src/octoprint/templates/dialogs/settings/gcodevisualizer.jinja2 +++ b/src/octoprint/plugins/gcodeviewer/templates/gcodeviewer_settings.jinja2 @@ -1,22 +1,15 @@
    -
    -
    - -
    -
    -
    - +
    +
    - +
    {{ _('on desktop')}}
    - +
    {{ _('on mobile')}}
    diff --git a/src/octoprint/templates/tabs/gcodeviewer.jinja2 b/src/octoprint/plugins/gcodeviewer/templates/gcodeviewer_tab.jinja2 similarity index 100% rename from src/octoprint/templates/tabs/gcodeviewer.jinja2 rename to src/octoprint/plugins/gcodeviewer/templates/gcodeviewer_tab.jinja2 diff --git a/src/octoprint/plugins/logging/__init__.py b/src/octoprint/plugins/logging/__init__.py index 9372c5b19..d0cc01e69 100644 --- a/src/octoprint/plugins/logging/__init__.py +++ b/src/octoprint/plugins/logging/__init__.py @@ -51,8 +51,10 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin, free, total = self._get_usage() loggers = self._get_available_loggers() levels = self._get_logging_levels() + serial_log_enabled = self._settings.global_get_boolean(["serial", "log"]) return jsonify(logs=dict(files=files, free=free, total=total), - setup=dict(loggers=loggers, levels=levels)) + setup=dict(loggers=loggers, levels=levels), + serial_log=dict(enabled=serial_log_enabled)) @octoprint.plugin.BlueprintPlugin.route("/logs", methods=["GET"]) @no_firstrun_access @@ -226,11 +228,9 @@ __plugin_description__ = "Provides access to OctoPrint's logs and logging config __plugin_disabling_discouraged__ = gettext("Without this plugin you will no longer be able to retrieve " "OctoPrint's logs or modify the current logging levels through " "the web interface.") -def __plugin_load__(): - global __plugin_implementation__ - __plugin_implementation__ = LoggingPlugin() - - global __plugin_hooks__ - __plugin_hooks__ = { - "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions - } +__plugin_license__ = "AGPLv3" +__plugin_pythoncompat__ = ">=2.7,<4" +__plugin_implementation__ = LoggingPlugin() +__plugin_hooks__ = { + "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions +} diff --git a/src/octoprint/plugins/logging/static/js/logging.js b/src/octoprint/plugins/logging/static/js/logging.js index 7a7978ac7..ff37477f7 100644 --- a/src/octoprint/plugins/logging/static/js/logging.js +++ b/src/octoprint/plugins/logging/static/js/logging.js @@ -3,11 +3,16 @@ $(function() { var self = this; self.loginState = parameters[0]; + self.access = parameters[1]; + self.availableLoggers = ko.observableArray(); self.availableLoggersName = ko.observable(); self.availableLoggersLevel = ko.observable(); self.configuredLoggers = ko.observableArray(); self.configuredLoggersChanged = false; + self.serialLogEnabled = ko.observable(); + self.freeSpace = ko.observable(undefined); + self.totalSpace = ko.observable(undefined); self.markedForDeletion = ko.observableArray([]); @@ -54,6 +59,9 @@ $(function() { ); self.requestData = function() { + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)) { + return; + } OctoPrint.plugins.logging.get() .done(self.fromResponse); }; @@ -61,6 +69,7 @@ $(function() { self.fromResponse = function(response) { self.fromLogsResponse(response.logs); self.fromSetupResponse(response.setup); + self.fromSerialLogResponse(response.serial_log); }; self.fromLogsResponse = function(response) { @@ -71,6 +80,9 @@ $(function() { return; self.listHelper.updateItems(files); + + self.freeSpace(response.free); + self.totalSpace(response.total); }; self.fromSetupResponse = function(response) { @@ -94,11 +106,44 @@ $(function() { self.availableLoggers(availableLoggers); }; + self.fromSerialLogResponse = function(response) { + if (!response) return; + + self.serialLogEnabled(response.enabled); + }; + + self.popoverContent = function() { + var free = self.freeSpace(); + var total = self.totalSpace(); + + var content = "

    " + + gettext("You currently have serial.log enabled. Please remember to turn it off " + + "again once your are done debugging whatever issue prompted you to turn it on.") + + "

    " + + gettext("It can negatively impact print performance and also take up a lot of storage space " + + "depending on how long you stay connected to your printer and thus should only be used for " + + "debugging.") + + "

    "; + + if (free !== undefined && total !== undefined) { + content += "

    " + gettext("Log storage:") + " " + + formatSize(free) + " / " + + formatSize(total) + + "

    "; + } + + return content; + }; + self.configuredLoggersHasChanged = function () { self.configuredLoggersChanged = true; }; self.addLogger = function() { + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)) { + return; + } + var component = self.availableLoggersName(); var level = self.availableLoggersLevel(); @@ -109,6 +154,10 @@ $(function() { }; self.removeLogger = function(logger) { + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)) { + return; + } + self.configuredLoggers.remove(logger); self.availableLoggers.push(logger.component); @@ -116,6 +165,9 @@ $(function() { }; self.removeFile = function(filename) { + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)) { + return; + } var perform = function() { OctoPrint.plugins.logging.deleteLog(filename) .done(self.requestData); @@ -134,10 +186,16 @@ $(function() { }; self.clearMarkedFiles = function() { + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)) { + return; + } self.markedForDeletion.removeAll(); }; self.removeMarkedFiles = function() { + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)) { + return; + } var perform = function() { self._bulkRemove(self.markedForDeletion(), "files") .done(function() { @@ -149,11 +207,17 @@ $(function() { perform); }; - self.onSettingsShown = function() { + self.onServerReconnect = self.onUserLoggedIn = self.onEventSettingsUpdated = function() { + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)) { + return; + } self.requestData(); }; self.onSettingsBeforeSave = function () { + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)) { + return; + } if ( self.configuredLoggersChanged ) { console.log("ConfiguredLoggers has changed. Saving!"); var levels = {}; @@ -167,6 +231,9 @@ $(function() { }; self._bulkRemove = function(files) { + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)) { + return; + } var title = gettext("Deleting log files"); var message = _.sprintf(gettext("Deleting %(count)d log files..."), {count: files.length}); var handler = function(filename) { @@ -211,7 +278,7 @@ $(function() { OCTOPRINT_VIEWMODELS.push({ construct: LoggingViewModel, additionalNames: ["logsViewModel"], - dependencies: ["loginStateViewModel"], - elements: ["#settings_plugin_logging"] + dependencies: ["loginStateViewModel", "accessViewModel"], + elements: ["#settings_plugin_logging", "#navbar_plugin_logging"] }); }); diff --git a/src/octoprint/plugins/logging/templates/logging_navbar.jinja2 b/src/octoprint/plugins/logging/templates/logging_navbar.jinja2 new file mode 100644 index 000000000..f03a75d09 --- /dev/null +++ b/src/octoprint/plugins/logging/templates/logging_navbar.jinja2 @@ -0,0 +1,3 @@ + + + diff --git a/src/octoprint/plugins/loginui/__init__.py b/src/octoprint/plugins/loginui/__init__.py index c274b3dfe..0a2f66ff7 100644 --- a/src/octoprint/plugins/loginui/__init__.py +++ b/src/octoprint/plugins/loginui/__init__.py @@ -115,6 +115,8 @@ __plugin_description__ = "Displays a standalone login UI if needed" __plugin_disabling_discouraged__ = gettext("Without this plugin there will be no dedicated login page for users in " "case anonymous read only access is disabled - instead your non logged in " "visitors will get a broken UI.") +__plugin_license__ = "AGPLv3" +__plugin_pythoncompat__ = ">=2.7,<4" __plugin_hidden__ = True __plugin_implementation__ = LoginUiPlugin() diff --git a/src/octoprint/plugins/pi_support/__init__.py b/src/octoprint/plugins/pi_support/__init__.py index 3690360f2..f405935cf 100644 --- a/src/octoprint/plugins/pi_support/__init__.py +++ b/src/octoprint/plugins/pi_support/__init__.py @@ -18,6 +18,8 @@ from octoprint.access.groups import USER_GROUP import octoprint.plugin import octoprint.events +from octoprint.util.platform import CLOSE_FDS + _PROC_DT_MODEL_PATH = "/proc/device-tree/model" _OCTOPI_VERSION_PATH = "/etc/octopi_version" _VCGENCMD_THROTTLE = "/usr/bin/vcgencmd get_throttled" @@ -150,7 +152,7 @@ def get_vcgencmd_throttled_state(command): if __LOCAL_DEBUG: output = "throttled={}".format(next(_VCGENCMD_OUTPUT)) # mock for local debugging else: - output = sarge.get_stdout(command) + output = sarge.get_stdout(command, close_fds=CLOSE_FDS) if not "throttled=0x" in output: raise ValueError("cannot parse \"{}\" output: {}".format(command, output)) @@ -334,6 +336,7 @@ __plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will n "provide additional information about your Pi, " "which will make it more tricky to help you if you need support.") __plugin_license__ = "AGPLv3" +__plugin_pythoncompat__ = ">=2.7,<4" def __plugin_check__(): try: diff --git a/src/octoprint/plugins/pi_support/static/js/pi_support.js b/src/octoprint/plugins/pi_support/static/js/pi_support.js index e6b0aaef1..4f3a8a13d 100644 --- a/src/octoprint/plugins/pi_support/static/js/pi_support.js +++ b/src/octoprint/plugins/pi_support/static/js/pi_support.js @@ -29,13 +29,11 @@ $(function() { self.fromThrottleState(response.throttle_state); // OctoPi version - $("#octopi_support_footer").remove(); + $("#pi_support_footer").remove(); if (!response.octopi_version) return; - var octoPrintVersion = $(".footer span.version"); - var octoPiVersion = $(" " + gettext("running on") + " " + gettext("OctoPi") - + " " + response.octopi_version + ""); - $(octoPiVersion).insertAfter(octoPrintVersion); + var octoPiVersion = $(""); + $("#footer_version").append(octoPiVersion); }) }; diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 3605d08db..b19dfd218 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -14,10 +14,11 @@ from octoprint.settings import valid_boolean_trues from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking, check_etag from octoprint.access import ADMIN_GROUP from octoprint.access.permissions import Permissions -from octoprint.util import to_bytes +from octoprint.util import to_bytes, TemporaryDirectory from octoprint.util.pip import LocalPipCaller from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, is_octoprint_compatible, is_python_compatible from octoprint.util.platform import get_os, is_os_compatible +from octoprint.util.net import download_file from octoprint.events import Events from flask import jsonify, make_response @@ -33,6 +34,9 @@ import os import copy import time import threading +import tempfile +import shutil +import filetype from datetime import datetime @@ -91,6 +95,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, octoprint.plugin.EventHandlerPlugin): ARCHIVE_EXTENSIONS = (".zip", ".tar.gz", ".tgz", ".tar") + PYTHON_EXTENSIONS = (".py",) # valid pip install URL schemes according to https://pip.pypa.io/en/stable/reference/pip_install/ URL_SCHEMES = ("http", "https", "git", @@ -188,7 +193,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if helpers and "get_throttled" in helpers: self._get_throttled = helpers["get_throttled"] if self._settings.get_boolean(["ignore_throttled"]): - self._logger.warn("!!! THROTTLE STATE IGNORED !!! You have configured the Plugin Manager plugin to ignore an active throttle state of the underlying system. You might run into stability issues or outright corrupt your install. Consider fixing the throttling issue instead of suppressing it.") + self._logger.warning("!!! THROTTLE STATE IGNORED !!! You have configured the Plugin Manager plugin to ignore an active throttle state of the underlying system. You might run into stability issues or outright corrupt your install. Consider fixing the throttling issue instead of suppressing it.") # decouple repository fetching from server startup self._fetch_all_data(do_async=True) @@ -240,7 +245,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, return dict( all=plugins, thirdparty=list(filter(lambda p: not p["bundled"], plugins)), - archive_extensions=self.__class__.ARCHIVE_EXTENSIONS + file_extensions=self.ARCHIVE_EXTENSIONS + self.PYTHON_EXTENSIONS ) def get_template_types(self, template_sorting, template_rules, *args, **kwargs): @@ -250,10 +255,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, ##~~ BlueprintPlugin - @octoprint.plugin.BlueprintPlugin.route("/upload_archive", methods=["POST"]) + @octoprint.plugin.BlueprintPlugin.route("/upload_file", methods=["POST"]) @no_firstrun_access @Permissions.PLUGIN_PLUGINMANAGER_INSTALL.require(403) - def upload_archive(self): + def upload_file(self): import flask input_name = "file" @@ -265,21 +270,19 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, upload_path = flask.request.values[input_upload_path] upload_name = flask.request.values[input_upload_name] - exts = list(filter(lambda x: upload_name.lower().endswith(x), self.__class__.ARCHIVE_EXTENSIONS)) + exts = list(filter(lambda x: upload_name.lower().endswith(x), self.ARCHIVE_EXTENSIONS + self.PYTHON_EXTENSIONS)) if not len(exts): - return flask.make_response("File doesn't have a valid extension for a plugin archive", 400) + return flask.make_response("File doesn't have a valid extension for a plugin archive or a single file plugin", 400) ext = exts[0] - import tempfile - import shutil - import os - archive = tempfile.NamedTemporaryFile(delete=False, suffix="{ext}".format(**locals())) try: archive.close() shutil.copy(upload_path, archive.name) - return self.command_install(path=archive.name, force="force" in flask.request.values and flask.request.values["force"] in valid_boolean_trues) + return self.command_install(path=archive.name, + name=upload_name, + force="force" in flask.request.values and flask.request.values["force"] in valid_boolean_trues) finally: try: os.remove(archive.name) @@ -420,38 +423,92 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, plugin = self._plugin_manager.plugins[plugin_name] return self.command_toggle(plugin, command) - def command_install(self, url=None, path=None, force=False, reinstall=None, dependency_links=False): + # noinspection PyMethodMayBeStatic + def _is_archive(self, path): + _, ext = os.path.splitext(path) + if ext in PluginManagerPlugin.ARCHIVE_EXTENSIONS: + return True + + kind = filetype.guess(path) + if kind: + return ".{}".format(kind.extension) in PluginManagerPlugin.ARCHIVE_EXTENSIONS + return False + + def _is_pythonfile(self, path): + _, ext = os.path.splitext(path) + if ext in PluginManagerPlugin.PYTHON_EXTENSIONS: + import ast + try: + with io.open(path, 'rb') as f: + ast.parse(f.read(), filename=path) + return True + except Exception as exc: + self._logger.exception("Could not parse {} as python file: {}".format(path, exc)) + + return False + + def command_install(self, url=None, path=None, name=None, force=False, reinstall=None, dependency_links=False): + folder = None + + try: + source = path + source_type = "path" + + if url is not None: + # fetch URL + folder = TemporaryDirectory() + path = download_file(url, folder.name) + source = url + source_type = "url" + + # determine type of path + if self._is_archive(path): + return self._command_install_archive(path, + source=source, + source_type=source_type, + force=force, + reinstall=reinstall, + dependency_links=dependency_links) + + elif self._is_pythonfile(path): + return self._command_install_pythonfile(path, + source=source, + source_type=source_type, + name=name) + + else: + self._logger.error("{} is neither an archive nor a python file, can't install that.".format(source)) + result = dict(result=False, + source=source, + source_type=source_type, + reason="Could not install plugin from {}, was neither " + "a plugin archive nor a single file plugin".format(source)) + self._send_result_notification("install", result) + return jsonify(result) + + finally: + if folder is not None: + folder.cleanup() + + # noinspection DuplicatedCode + def _command_install_archive(self, path, source=None, source_type=None, force=False, reinstall=None, dependency_links=False): throttled = self._get_throttled() if throttled and isinstance(throttled, dict) and throttled.get("current_issue", False) and not self._settings.get_boolean(["ignore_throttled"]): # currently throttled, we refuse to run return make_response("System is currently throttled, refusing to install " "anything due to possible stability issues", 409) - if url is not None: - if not any(map(lambda scheme: url.startswith(scheme + "://"), self.URL_SCHEMES)): - raise ValueError("Invalid URL to pip install from") + path = os.path.abspath(path) + path_url = "file://" + path + if os.sep != "/": + # windows gets special handling + path = path.replace(os.sep, "/").lower() + path_url = "file:///" + path - source = url - source_type = "url" - already_installed_check = lambda line: url in line - - elif path is not None: - path = os.path.abspath(path) - path_url = "file://" + path - if os.sep != "/": - # windows gets special handling - path = path.replace(os.sep, "/").lower() - path_url = "file:///" + path - - source = path - source_type = "path" - already_installed_check = lambda line: path_url in line.lower() # lower case in case of windows - - else: - raise ValueError("Either URL or path must be provided") + already_installed_check = lambda line: path_url in line.lower() # lower case in case of windows self._logger.info("Installing plugin from {}".format(source)) - pip_args = ["--disable-pip-version-check", "install", sarge.shell_quote(source), "--no-cache-dir"] + pip_args = ["--disable-pip-version-check", "install", sarge.shell_quote(path_url), "--no-cache-dir"] if dependency_links or self._settings.get_boolean(["dependency_links"]): pip_args.append("--process-dependency-links") @@ -480,7 +537,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._log_message("Looks like the plugin was already installed. Forcing a reinstall.") force = True except Exception: - self._logger.exception("Could not install plugin from %s" % url) + self._logger.exception("Could not install plugin from %s" % source) return make_response("Could not install plugin from URL, see the log for more details", 500) else: if force: @@ -543,9 +600,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, all_plugins_after = self._plugin_manager.find_plugins(existing=dict(), ignore_uninstalled=False) new_plugin = self._find_installed_plugin(installed, plugins=all_plugins_after) + if new_plugin is None: self._logger.warning("The plugin was installed successfully, but couldn't be found afterwards to " - "initialize properly during runtime. Please restart OctoPrint.") + "initialize properly during runtime. Please restart OctoPrint.") result = dict(result=True, source=source, source_type=source_type, @@ -591,6 +649,68 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._send_result_notification("install", result) return jsonify(result) + # noinspection DuplicatedCode + def _command_install_pythonfile(self, path, source=None, source_type=None, name=None): + if name is None: + name = os.path.basename(path) + + self._logger.info("Installing single file plugin {} from {}".format(name, source)) + + all_plugins_before = self._plugin_manager.find_plugins(existing=dict()) + + destination = os.path.join(self._settings.global_get_basefolder("plugins"), name) + plugin_id, _ = os.path.splitext(name) + + try: + self._log_call("cp {} {}".format(path, destination)) + shutil.copy(path, destination) + except: + self._logger.exception("Could not install plugin from {}".format(source)) + return make_response("Could not install plugin from URL, see the log for more details", 500) + + plugins = self._plugin_manager.find_plugins(existing=dict(), ignore_uninstalled=False) + new_plugin = plugins.get(plugin_id) + if new_plugin is None: + self._logger.warning("The plugin was installed successfully, but couldn't be found afterwards to " + "initialize properly during runtime. Please restart OctoPrint.") + result = dict(result=True, + source=source, + source_type=source_type, + needs_restart=True, + needs_refresh=True, + needs_reconnect=True, + was_reinstalled=False, + plugin="unknown") + self._send_result_notification("install", result) + return jsonify(result) + + self._plugin_manager.reload_plugins() + needs_restart = self._plugin_manager.is_restart_needing_plugin(new_plugin) \ + or new_plugin.key in all_plugins_before + needs_refresh = new_plugin.implementation \ + and isinstance(new_plugin.implementation, octoprint.plugin.ReloadNeedingPlugin) + needs_reconnect = self._plugin_manager.has_any_of_hooks(new_plugin, self._reconnect_hooks) and self._printer.is_operational() + + self._logger.info("The plugin was installed successfully: {}, version {}".format(new_plugin.name, new_plugin.version)) + self._plugin_manager.log_all_plugins() + + # noinspection PyUnresolvedReferences + self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN, dict(id=new_plugin.key, + version=new_plugin.version, + source=source, + source_type=source_type)) + + result = dict(result=True, + source=source, + source_type=source_type, + needs_restart=needs_restart, + needs_refresh=needs_refresh, + needs_reconnect=needs_reconnect, + was_reinstalled=new_plugin.key in all_plugins_before, + plugin=self._to_external_plugin(new_plugin)) + self._send_result_notification("install", result) + return jsonify(result) + def command_uninstall(self, plugin, cleanup=False): if plugin.key == "pluginmanager": return make_response("Can't uninstall Plugin Manager", 403) @@ -764,7 +884,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, def _cleanup_settings(self, plugin): # delete plugin settings - self._settings.global_set(["plugins", plugin], None) + self._settings.global_remove(["plugins", plugin]) + self._settings.global_remove(["server", "seenWizards", plugin]) return True def _cleanup_data(self, plugin): @@ -1000,7 +1121,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, # validation if not isinstance(repo_data, (list, tuple)): - self._logger.warn("Invalid repository data: expected a list, got {!r}".format(repo_data)) + self._logger.warning("Invalid repository data: expected a list, got {!r}".format(repo_data)) return None try: @@ -1180,6 +1301,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, version=plugin.version, url=plugin.url, license=plugin.license, + python=plugin.pythoncompat, bundled=plugin.bundled, managable=plugin.managable, enabled=plugin.enabled, @@ -1238,6 +1360,7 @@ __plugin_author__ = "Gina Häußge" __plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/pluginmanager.html" __plugin_description__ = "Allows installing and managing OctoPrint plugins" __plugin_license__ = "AGPLv3" +__plugin_pythoncompat__ = ">=2.7,<4" __plugin_hidden__ = True def __plugin_load__(): diff --git a/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css b/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css index 7450d4f01..9e48d34f6 100644 --- a/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css +++ b/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css @@ -1 +1 @@ -#settings_plugin_pluginmanager_pluginlist{display:block;width:auto;max-height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_orphanlist{display:block;width:auto;max-height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_id,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_id{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a.disabled,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty div,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:300px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009} \ No newline at end of file +#settings_plugin_pluginmanager_pluginlist{display:block;width:auto;max-height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name .prop,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name .prop{white-space:nowrap}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_orphanlist{display:block;width:auto;max-height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_id,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_id{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a.disabled,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:400px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty div,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .meta{white-space:nowrap;text-overflow:ellipsis;overflow:hidden}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .stats .prop{white-space:nowrap}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009} \ No newline at end of file diff --git a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js index 32689c659..833480db6 100644 --- a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js +++ b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js @@ -57,14 +57,50 @@ $(function() { { "title": function (a, b) { // sorts ascending - if (a["title"].toLocaleLowerCase() < b["title"].toLocaleLowerCase()) return -1; - if (a["title"].toLocaleLowerCase() > b["title"].toLocaleLowerCase()) return 1; + if (a.title.toLocaleLowerCase() < b.title.toLocaleLowerCase()) return -1; + if (a.title.toLocaleLowerCase() > b.title.toLocaleLowerCase()) return 1; return 0; }, "published": function (a, b) { // sorts descending - if (a["published"].toLocaleLowerCase() > b["published"].toLocaleLowerCase()) return -1; - if (a["published"].toLocaleLowerCase() < b["published"].toLocaleLowerCase()) return 1; + if (a.published.toLocaleLowerCase() > b.published.toLocaleLowerCase()) return -1; + if (a.published.toLocaleLowerCase() < b.published.toLocaleLowerCase()) return 1; + return 0; + }, + "popularity": function (a, b) { + // sorts descending + var countA = (a.stats && a.stats.instances_month) ? a.stats.instances_month : 0; + var countB = (b.stats && b.stats.instances_month) ? b.stats.instances_month : 0; + + if (countA > countB) return -1; + if (countA < countB) return 1; + return 0; + }, + "release_date": function (a, b) { + // sorts descending + var valA = (a.github && a.github.latest_release) ? a.github.latest_release.date.toLocaleLowerCase() : ""; + var valB = (b.github && b.github.latest_release) ? b.github.latest_release.date.toLocaleLowerCase() : ""; + + if (valA > valB) return -1; + if (valA < valB) return 1; + return 0; + }, + "push_date": function (a, b) { + // sorts descending + var valA = (a.github) ? a.github.last_push.toLocaleLowerCase() : ""; + var valB = (b.github) ? b.github.last_push.toLocaleLowerCase() : ""; + + if (valA > valB) return -1; + if (valA < valB) return 1; + return 0; + }, + "stars": function (a, b) { + // sorts descending + var valA = (a.github) ? a.github.stars : 0; + var valB = (b.github) ? b.github.stars : 0; + + if (valA > valB) return -1; + if (valA < valB) return 1; return 0; } }, @@ -74,6 +110,9 @@ $(function() { }, "filter_incompatible": function(plugin) { return plugin.is_compatible.octoprint && plugin.is_compatible.os && plugin.is_compatible.python; + }, + "filter_abandoned": function(plugin) { + return !plugin.abandoned; } }, "title", @@ -122,7 +161,7 @@ $(function() { self.followDependencyLinks = ko.observable(false); - self.pipAvailable = ko.observable(false); + self.pipAvailable = ko.observable(true); self.pipVersion = ko.observable(); self.pipInstallDir = ko.observable(); self.pipUseUser = ko.observable(); @@ -133,6 +172,8 @@ $(function() { self.safeMode = ko.observable(); self.online = ko.observable(); + self.requestError = ko.observable(false); + self.pipUseUserString = ko.pureComputed(function() { return self.pipUseUser() ? "yes" : "no"; }); @@ -174,9 +215,9 @@ $(function() { self.noticeCountText = ko.pureComputed(function() { var count = self.noticeCount(); - if (count == 0) { + if (count === 0) { return gettext("There are no plugin notices. Great!"); - } else if (count == 1) { + } else if (count === 1) { return gettext("There is a plugin notice for one of your installed plugins."); } else { return _.sprintf(gettext("There are %(count)d plugin notices for one or more of your installed plugins."), {count: count}); @@ -249,8 +290,8 @@ $(function() { && !self.invalidUrl(); }); - self.invalidArchive = ko.pureComputed(function() { - var allowedArchiveExtensions = [".zip", ".tar.gz", ".tgz", ".tar"]; + self.invalidFile = ko.pureComputed(function() { + var allowedFileExtensions = [".zip", ".tar.gz", ".tgz", ".tar", ".py"]; var name = self.uploadFilename(); var lowerName = name !== undefined ? name.toLocaleLowerCase() : undefined; @@ -260,10 +301,10 @@ $(function() { }; return name !== undefined - && !(_.any(allowedArchiveExtensions, lowerNameHasExtension)); + && !(_.any(allowedFileExtensions, lowerNameHasExtension)); }); - self.enableArchiveInstall = ko.pureComputed(function() { + self.enableFileInstall = ko.pureComputed(function() { var name = self.uploadFilename(); return self.enableManagement() && self.pipAvailable() @@ -271,7 +312,7 @@ $(function() { && !self.throttled() && name !== undefined && name.trim() !== "" - && !self.invalidArchive(); + && !self.invalidFile(); }); self.uploadElement.fileupload({ @@ -279,7 +320,7 @@ $(function() { maxNumberOfFiles: 1, autoUpload: false, add: function(e, data) { - if (data.files.length == 0) { + if (data.files.length === 0) { return false; } @@ -435,7 +476,11 @@ $(function() { options.eval_notices = options.eval_notices || false; OctoPrint.plugins.pluginmanager.get({repo: options.refresh_repo, notices: options.refresh_notices, orphans: options.refresh_orphans}) + .fail(function() { + self.requestError(true); + }) .done(function(data) { + self.requestError(false); self.fromResponse(data, options); }); }; @@ -449,7 +494,7 @@ $(function() { return; } - if (data.key == "pluginmanager") return; + if (data.key === "pluginmanager") return; var onSuccess = function() { self.requestData(); @@ -463,7 +508,7 @@ $(function() { }) }; - if (self._getToggleCommand(data) == "enable") { + if (self._getToggleCommand(data) === "enable") { if (data.safe_mode_victim) return; OctoPrint.plugins.pluginmanager.enable(data.key) .done(onSuccess) @@ -505,7 +550,10 @@ $(function() { }; self.showRepository = function() { - self.repositoryDialog.modal("show"); + self.repositoryDialog.modal({ + minHeight: function() { return Math.max($.fn.modal.defaults.maxHeight() - 80, 250); }, + show: true + }); }; self.pluginDetails = function(data) { @@ -745,7 +793,7 @@ $(function() { self.savePluginSettings = function() { var repository = self.config_repositoryUrl(); - if (repository != undefined && repository.trim() == "") { + if (repository !== undefined && repository.trim() === "") { repository = null; } @@ -757,7 +805,7 @@ $(function() { } var notices = self.config_noticesUrl(); - if (notices != undefined && notices.trim() == "") { + if (notices !== undefined && notices.trim() === "") { notices = null; } @@ -769,7 +817,7 @@ $(function() { } var pipArgs = self.config_pipAdditionalArgs(); - if (pipArgs != undefined && pipArgs.trim() == "") { + if (pipArgs !== undefined && pipArgs.trim() === "") { pipArgs = null; } @@ -990,7 +1038,7 @@ $(function() { }; self.toggleButtonCss = function(data) { - var icon = self._getToggleCommand(data) == "enable" ? "fa fa-toggle-off" : "fa fa-toggle-on"; + var icon = self._getToggleCommand(data) === "enable" ? "fa fa-toggle-off" : "fa fa-toggle-on"; var disabled = (self.enableToggle(data)) ? "" : " disabled"; return icon + disabled; @@ -998,7 +1046,7 @@ $(function() { self.toggleButtonTitle = function(data) { var command = self._getToggleCommand(data); - if (command == "enable") { + if (command === "enable") { if (data.blacklisted) { return gettext("Blacklisted"); } else if (data.safe_mode_victim) { @@ -1012,7 +1060,7 @@ $(function() { }; self.showPluginNotifications = function(plugin) { - if (!plugin.notifications || plugin.notifications.length == 0) return; + if (!plugin.notifications || plugin.notifications.length === 0) return; self._removeAllNoticeNotificationsForPlugin(plugin.key); _.each(plugin.notifications, function(notification) { @@ -1021,7 +1069,7 @@ $(function() { }; self.showPluginNotificationsLinkText = function(plugins) { - if (!plugins.notifications || plugins.notifications.length == 0) return; + if (!plugins.notifications || plugins.notifications.length === 0) return; var count = plugins.notifications.length; var importantCount = _.filter(plugins.notifications, function(notification) { return notification.important }).length; @@ -1057,8 +1105,8 @@ $(function() { var text = ""; if (notification.versions && notification.versions.length > 0) { - var versions = _.map(notification.versions, function(v) { return (v == version) ? "" + v + "" : v; }).join(", "); - text += "" + _.sprintf(gettext("Affected versions: %(versions)s"), {versions: _.escape(versions)}) + ""; + var versions = _.map(notification.versions, function(v) { return (v === version) ? "" + _.escape(v) + "" : _.escape(v); }).join(", "); + text += "" + _.sprintf(gettext("Affected versions: %(versions)s"), {versions: versions}) + ""; } else { text += "" + gettext("Affected versions: all") + ""; } @@ -1167,7 +1215,7 @@ $(function() { if (!Modernizr.localstorage) return false; - if (localStorage[noticeLocalStorageKey] == undefined) + if (localStorage[noticeLocalStorageKey] === undefined) return false; var knownData = JSON.parse(localStorage[noticeLocalStorageKey]); diff --git a/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less b/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less index 89f5ee3d0..2c5beb3bc 100644 --- a/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less +++ b/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less @@ -16,6 +16,10 @@ &.settings_plugin_plugin_manager_plugins_name { text-overflow: ellipsis; text-align: left; + + .prop { + white-space: nowrap; + } } &.settings_plugin_plugin_manager_plugins_actions { @@ -106,7 +110,7 @@ #settings_plugin_pluginmanager_repositorydialog_empty { overflow: hidden; width: 100%; - height: 300px; + height: 400px; background-image: url("../img/repo_unavailable.png"); text-align: center; display: table; @@ -119,7 +123,7 @@ #settings_plugin_pluginmanager_repositorydialog_list { width: auto; - height: 300px; + height: 400px; overflow-x: hidden; overflow-y: scroll; padding-right: 2px; @@ -127,6 +131,16 @@ .entry { border-bottom: 1px solid #ddd; padding: 5px; + + .meta { + white-space: nowrap; + text-overflow: ellipsis; + overflow: hidden; + } + + .stats .prop { + white-space: nowrap; + } } } } diff --git a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 index e24babc17..a774980da 100644 --- a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 +++ b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 @@ -34,6 +34,13 @@ {% endtrans %}
    {% endmacro %} +{% macro pluginmanager_requesterror() %} +
    {% trans %} + There appears to have been an error retrieving the plugin data from the backend. Please report this + in the bug tracker & be sure to include all requested logs. +{% endtrans %}
    +{% endmacro %} +
    +
    + +
    +
    + + MB + {{ _('The minimum amount of free disk space that has to be available on various locations for OctoPrint to allow updates. Should not be set to 0.') }} +
    +
    +