Merge pull request #3762 from OctoPrint/improve/codestyling

Switch to using black, isort, prettier, various pre-commit hooks
This commit is contained in:
Gina Häußge authored and GitHub committed 2020-10-07 19:08:54 +02:00
commit 29726b15d1
367 files changed
+77286 -60645

No files matched your search

+11 -7
View File
@@ -8,19 +8,23 @@ end_of_line = lf
charset = utf-8
insert_final_newline = true
trim_trailing_whitespace = true
indent_style = space
max_line_length = 90
[**.py]
indent_style = tab
indent_size = 4
[src/octoprint/vendor/sockjs/**.py]
indent_style = space
indent_size = 4
[**.yaml]
indent_size = 2
[src/octoprint/static/js/app/**.js]
indent_style = space
indent_size = 4
[.travis.yml]
indent_style = space
[src/octoprint/static/js/login/**.js]
indent_size = 4
[src/octoprint/static/js/recovery/**.js]
indent_size = 4
[src/octoprint/static/less/octoprint.less]
indent_size = 2
+14
View File
@@ -1 +1,15 @@
# refs to ignore during git blame, use with --ignore-revs-file
# Switch to black formatting
1f93b2355a2816918e11a55e61b42010d15a6720
# Switch to prettier formatting
6b44909f21ee39237b7504cd31ffa6cf28275c33
# EOF/trailing whitespace check
#cae6730ea87da18bd6ebfeaf3e1e9cd354390939
# dict_to_literal, set_to_literal, not_in, flake8 fixes
#af60fd642832736966104ae71d852d745397c749
#986312b6ae7eeadcaf620cc99d53b23794be83b6
#b5be8f3eaec18ae2a88110a3a16c552931d493dd
+3 -3
View File
@@ -17,7 +17,7 @@ or request features within OctoPrint (not OctoPi, not any OctoPrint
plugins and not unofficial OctoPrint versions).
Do not seek support here ("I need help with ...", "I have a
question ..."), that belongs on the community forum at
question ..."), that belongs on the community forum at
community.octoprint.org, NOT here.
Mark requests with a "[Request]" prefix in the title please. For bug
@@ -37,7 +37,7 @@ Thank you!
#### What were you doing?
<!--
<!--
Please be as specific as possible here. The maintainers will need to
reproduce your issue in order to fix it and that is not possible if they
don't know what you did to get it to happen in the first place.
@@ -61,7 +61,7 @@ to also include a link to a file with which to reproduce the problem.
#### Did the same happen when running OctoPrint in safe mode?
<!--
<!--
Test if you can reproduce your problem in safe mode. You can find information
on how to enable safe mode in the Contribution Guidelines.
+4 -4
View File
@@ -16,15 +16,15 @@ checklist:
made sure your changes don't interfere with current development by
talking it through with the maintainers, e.g. through a
Brainstorming ticket
* [ ] Your PR targets OctoPrint's devel branch if it's a completely
* [ ] Your PR targets OctoPrint's devel branch if it's a completely
new feature, or maintenance if it's a bug fix or improvement of
existing functionality for the current stable version (no PRs
existing functionality for the current stable version (no PRs
against master or anything else please)
* [ ] Your PR was opened from a custom branch on your repository
(no PRs from your version of master, maintenance or devel please),
e.g. dev/my_new_feature or fix/my_bugfix
* [ ] Your PR only contains relevant changes: no unrelated files,
no dead code, ideally only one commit - rebase and squash your PR
no dead code, ideally only one commit - rebase and squash your PR
if necessary!
* [ ] Your changes follow the existing coding style
* [ ] If your changes include style sheets: You have modified the
@@ -37,7 +37,7 @@ checklist:
* [ ] You have added yourself to the AUTHORS.md file :)
<!--
Describe your PR further using the template provided below. The more
Describe your PR further using the template provided below. The more
details the better!
-->
+15 -15
View File
@@ -1,18 +1,18 @@
accessControl:
salt: zXmvzI3uWuTLkSPOEfA2ZLwn3f3sGUNS
salt: zXmvzI3uWuTLkSPOEfA2ZLwn3f3sGUNS
plugins:
virtual_printer:
enabled: true
tracking:
enabled: false
virtual_printer:
enabled: true
tracking:
enabled: false
server:
firstRun: false
onlineCheck:
enabled: false
pluginBlacklist:
enabled: false
secretKey: rrdHjvmeGMPSdYWg2NGdiM7mpz9pjekk
seenWizards:
backup: null
corewizard: 3
tracking: null
firstRun: false
onlineCheck:
enabled: false
pluginBlacklist:
enabled: false
secretKey: rrdHjvmeGMPSdYWg2NGdiM7mpz9pjekk
seenWizards:
backup: null
corewizard: 3
tracking: null
+14 -14
View File
@@ -1,22 +1,22 @@
admin:
active: true
apikey: null
groups:
active: true
apikey: null
groups:
- admins
- users
password: 3033587f3b040680c77ce4fb7e8d61422878ef49a2a784227689f3b44ce66ada7f6161f8b2b037267f0d37b783a5600276eb88e1d224d24915f64e187a49a89f
permissions: []
roles:
password: 3033587f3b040680c77ce4fb7e8d61422878ef49a2a784227689f3b44ce66ada7f6161f8b2b037267f0d37b783a5600276eb88e1d224d24915f64e187a49a89f
permissions: []
roles:
- user
- admin
settings: {}
settings: {}
user:
active: true
apikey: null
groups:
active: true
apikey: null
groups:
- users
password: 3033587f3b040680c77ce4fb7e8d61422878ef49a2a784227689f3b44ce66ada7f6161f8b2b037267f0d37b783a5600276eb88e1d224d24915f64e187a49a89f
permissions: []
roles:
password: 3033587f3b040680c77ce4fb7e8d61422878ef49a2a784227689f3b44ce66ada7f6161f8b2b037267f0d37b783a5600276eb88e1d224d24915f64e187a49a89f
permissions: []
roles:
- user
settings: {}
settings: {}
+70 -18
View File
@@ -31,6 +31,70 @@ jobs:
name: dist
path: dist
lint-black:
name: 🧹 black
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: 🏗 Set up Python 3.7
uses: actions/setup-python@v1
with:
python-version: 3.7
- name: 🏗 Set up dev dependencies
run: |
pip install -e .[develop]
- name: 🚀 Run black
run: |
pre-commit run --hook-stage manual black --all-files --show-diff-on-failure
lint-prettier:
name: 🧹 prettier
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: 🏗 Set up Python 3.7
uses: actions/setup-python@v1
with:
python-version: 3.7
- name: 🏗 Set up dev dependencies
run: |
pip install -e .[develop]
- name: 🚀 Run prettier
run: |
pre-commit run --hook-stage manual prettier --all-files --show-diff-on-failure
lint-isort:
name: 🧹 isort
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: 🏗 Set up Python 3.7
uses: actions/setup-python@v1
with:
python-version: 3.7
- name: 🏗 Set up dev dependencies
run: |
pip install -e .[develop]
- name: 🚀 Run isort
run: |
pre-commit run --hook-stage manual isort --all-files --show-diff-on-failure
lint-flake8:
name: 🧹 Flake8
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: 🏗 Set up Python 3.7
uses: actions/setup-python@v1
with:
python-version: 3.7
- name: 🏗 Set up dev dependencies
run: |
pip install -e .[develop]
- name: 🚀 Run flake8
run: |
pre-commit run --hook-stage manual flake8 --all-files
test-unit:
name: 🧪 Unit tests
strategy:
@@ -50,22 +114,6 @@ jobs:
run: |
pytest
test-flake8:
name: 🧪 Flake8
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: 🏗 Set up Python 3.7
uses: actions/setup-python@v1
with:
python-version: 3.7
- name: 🏗 Set up test dependencies
run: |
pip install -e .[develop]
- name: 🚀 Run test suite
run: |
flake8 src/ tests setup.py
test-install:
name: 🧪 Installation tests
needs: build
@@ -124,8 +172,8 @@ jobs:
with:
working-directory: tests/cypress
browser: chrome
start: 'octoprint -b ${{ github.workspace }}/e2econfig serve --host 127.0.0.1 --port 5000'
wait-on: 'http://127.0.0.1:5000/online.txt'
start: "octoprint -b ${{ github.workspace }}/e2econfig serve --host 127.0.0.1 --port 5000"
wait-on: "http://127.0.0.1:5000/online.txt"
- name: ⬆ Upload screenshots
uses: actions/upload-artifact@v1
@@ -144,6 +192,10 @@ jobs:
name: 📦 Publish on TestPyPI
if: github.event_name == 'release'
needs:
- lint-black
- lint-prettier
- lint-isort
- lint-flake8
- test-unit
- test-install
- test-e2e
+4 -4
View File
@@ -1,8 +1,8 @@
name: 'Lock outdated issues & PRs'
name: "Lock outdated issues & PRs"
on:
schedule:
- cron: '0 0 * * *'
- cron: "0 0 * * *"
jobs:
lock:
@@ -12,5 +12,5 @@ jobs:
uses: dessant/lock-threads@v2
with:
github-token: ${{ github.token }}
issue-lock-comment: ''
pr-lock-comment: ''
issue-lock-comment: ""
pr-lock-comment: ""
+5 -5
View File
@@ -6,7 +6,7 @@ on:
- master
workflow_dispatch:
schedule:
- cron: '0 */12 * * *'
- cron: "0 */12 * * *"
jobs:
install-branch:
@@ -35,14 +35,14 @@ jobs:
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
uses: Ilshidur/action-discord@master
with:
args: '☑️ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ matrix.branch }}` was successful'
args: "☑️ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ matrix.branch }}` was successful"
- name: 📧 Discord failure notification
if: failure()
env:
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
uses: Ilshidur/action-discord@master
with:
args: '🚫 Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ matrix.branch }}` failed'
args: "🚫 Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ matrix.branch }}` failed"
install-latest:
name: Install latest release
@@ -69,11 +69,11 @@ jobs:
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
uses: Ilshidur/action-discord@master
with:
args: '☑️ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ steps.latest.outputs.release }}` was successful'
args: "☑️ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ steps.latest.outputs.release }}` was successful"
- name: 📧 Discord failure notification
if: failure()
env:
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
uses: Ilshidur/action-discord@master
with:
args: '🚫 Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ steps.latest.outputs.release }}` failed'
args: "🚫 Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ steps.latest.outputs.release }}` failed"
+1 -1
View File
@@ -14,5 +14,5 @@ jobs:
with:
token: ${{ secrets.DOCKER_ACCESS_TOKEN }}
repository: ${{ github.repository_owner }}/octoprint-docker
event-type: 'release'
event-type: "release"
client-payload: '{"tag_name": "${{ github.event.release.tag_name }}"}'
+38
View File
@@ -0,0 +1,38 @@
exclude: ^(src/octoprint/vendor/|src/octoprint/static/js/lib|src/octoprint/static/vendor|tests/static/js/lib|tests/util/_files|docs/|scripts/|translations/|.*\.css|.*\.svg)
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.3.0
hooks:
- id: end-of-file-fixer
- id: trailing-whitespace
- id: check-yaml
- id: check-toml
- repo: https://github.com/OctoPrint/codemods
rev: main
hooks:
- id: codemod_dict_to_literal
args: ["--ignore", "src/octoprint/vendor"]
stages: ["manual"]
- id: codemod_set_to_literal
args: ["--ignore", "src/octoprint/vendor"]
stages: ["manual"]
- id: codemod_not_in
args: ["--ignore", "src/octoprint/vendor"]
stages: ["manual"]
- repo: https://github.com/pre-commit/mirrors-isort
rev: v5.5.4
hooks:
- id: isort
- repo: https://github.com/psf/black
rev: stable
hooks:
- id: black
args: ["--config", "black.toml"]
- repo: https://gitlab.com/pycqa/flake8
rev: 3.8.1
hooks:
- id: flake8
- repo: https://github.com/prettier/prettier
rev: master
hooks:
- id: prettier
+15
View File
@@ -0,0 +1,15 @@
src/octoprint/static/js/lib
src/octoprint/static/vendor
src/octoprint/static/less/bootstrap
src/octoprint/static/less/font-awesome.less
*.md
*.css
**/package.json
**/package-lock.json
**/*.min.js
docs
build
dist
venv
venv2
venv3
+11
View File
@@ -0,0 +1,11 @@
printWidth: 90
tabWidth: 4
semi: true
trailingComma: "none"
singleQuote: false
quoteProps: consistent
bracketSpacing: false
overrides:
- files: ["*.yaml", "*.yml", "*.json", "*.less"]
options:
tabWidth: 2
-1
View File
@@ -5,4 +5,3 @@ host = https://www.transifex.com
file_filter = translations/<lang>/LC_MESSAGES/messages.po
source_file = translations/messages.pot
source_lang = en
+24 -16
View File
@@ -325,8 +325,7 @@ and branching strategy.
commits of your full virtual environment). Make sure your PR consists
**ideally of only one commit** (use git's rebase and squash functionality).
7. Make sure you **follow the current coding style**. This means:
* Tabs instead of spaces in the Python files[2]
* Spaces instead of tabs in the JavaScript sources
* Spaces for indenting and alignment, indentation width 4.
* English language (code, variables, comments, ...)
* Comments where necessary: Tell *why* the code does something like it does
it, structure your code
@@ -347,19 +346,32 @@ and branching strategy.
in the OctoPrint checkout folder. An [automatic build workflow](https://github.com/OctoPrint/OctoPrint/actions?query=workflow%3ABuild)
is also setup so that if the tests should fail, your PR will be marked
accordingly.
9. **Test your changes thoroughly**. That also means testing with usage
scenarios you don't normally use, e.g. if you only use access control, test
without and vice versa. If you only test with your printer, test with the
virtual printer and vice versa. State in your pull request how you tested
your changes. Ideally **add unit tests** - OctoPrint severely lacks in that
department, but we are trying to change that, so any new code already covered
with a test suite helps a lot!
10. In your pull request's description, **state what your pull request does**,
9. Run the **pre-commit check suite** against your changes. You can run that (after
[initial development environment setup with "develop" dependencies](https://docs.octoprint.org/en/master/development/environment.html))
by running
```
pre-commit run --hook-stage manual --all-files
```
in the OctoPrint checkout folder. If you install the pre-commit hooks via
`pre-commit install` (which you really should!) this will even be taken care of for you prior to committing.
An [automatic build workflow](https://github.com/OctoPrint/OctoPrint/actions?query=workflow%3ABuild)
is in place that will run these checks - if they fail your PR will be marked accordingly.
10. **Test your changes thoroughly**. That also means testing with usage
scenarios you don't normally use, e.g. if you only use access control, test
without and vice versa. If you only test with your printer, test with the
virtual printer and vice versa. State in your pull request how you tested
your changes. Ideally **add unit tests** - OctoPrint severely lacks in that
department, but we are trying to change that, so any new code already covered
with a test suite helps a lot!
11. In your pull request's description, **state what your pull request does**,
as in, what feature does it implement, what bug does it fix. The more
thoroughly you explain your intent behind the PR here, the higher the
chances it will get merged fast. There is a template provided below
that can help you here.
11. Don't forget to **add yourself to the [AUTHORS](./AUTHORS.md)
12. Don't forget to **add yourself to the [AUTHORS](./AUTHORS.md)
file** :)
Template to use for Pull Request descriptions:
@@ -415,14 +427,10 @@ See [the corresponding chapter in the documentation](https://docs.octoprint.org/
new features, suggest getting in touch on the forum for larger changes
* 2020-08-10: Update versioning scheme and PR instructions
* 2020-09-23: Move branch & versioning into development docs
* 2020-10-07: Introduce `pre-commit`
## Footnotes
* [1] - If you are wondering why, the problem is that anything that you add
to your PR's branch will also become part of your PR, so if you create a
PR from your version of `devel` chances are high you'll add changes to the
PR that do not belong to the PR.
* [2] - Yes, we know that this goes against PEP-8. OctoPrint started out as
a fork of Cura and hence stuck to the coding style found therein. Changing
it now would make the history and especially `git blame` completely
unusable, so for now we'll have to deal with it (this decision might be
revisited in the future).
+5 -1
View File
@@ -1,12 +1,16 @@
# OctoPrint
![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)
[![PyPI pyversions](https://img.shields.io/pypi/pyversions/octoprint.svg)](https://pypi.python.org/pypi/octoprint/)
![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)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)
[![Imports: isort](https://img.shields.io/badge/%20imports-isort-%231674b1)](https://pycqa.github.io/isort/)
[![pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white)](https://github.com/pre-commit/pre-commit)
OctoPrint provides a snappy web interface for controlling consumer 3D printers. It is Free Software
+1 -1
View File
@@ -6,6 +6,6 @@ Always update to the latest version of OctoPrint to keep up with security patche
## Reporting a Vulnerability
Email to security@octoprint.org.
Email to security@octoprint.org.
For the sake of the userbase of OctoPrint please always disclose responsibly and with a 90+ day window.
+1 -1
View File
@@ -62,4 +62,4 @@ thanks to everyone who contributed!
* Sven Mueller
* Ulrich Kempken
and 1943 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [Github Sponsors](https://github.com/users/foosel/sponsorship)!
and 1943 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [Github Sponsors](https://github.com/users/foosel/sponsorship)!
+21
View File
@@ -0,0 +1,21 @@
[tool.black]
line-length = 90
include = '''
(
(
src
| tests
| .github
).*\.pyi?$
)|(
setup\.py
)
'''
exclude = '''
(
src/octoprint/vendor # we want to still be able to apply patches from upstream w/o
# match issues
)
'''
+89 -69
View File
@@ -18,8 +18,8 @@ import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('../src/'))
sys.path.append(os.path.abspath('sphinxext'))
sys.path.insert(0, os.path.abspath("../src/"))
sys.path.append(os.path.abspath("sphinxext"))
import octoprint._version
from datetime import date
@@ -30,32 +30,46 @@ year_current = date.today().year
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
needs_sphinx = '1.3'
needs_sphinx = "1.3"
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['codeblockext', 'onlineinclude', 'sphinx.ext.todo', 'sphinx.ext.autodoc', 'sphinxcontrib.httpdomain',
'sphinx.ext.napoleon', 'sphinxcontrib.mermaid', 'sphinx.ext.intersphinx']
extensions = [
"codeblockext",
"onlineinclude",
"sphinx.ext.todo",
"sphinx.ext.autodoc",
"sphinxcontrib.httpdomain",
"sphinx.ext.napoleon",
"sphinxcontrib.mermaid",
"sphinx.ext.intersphinx",
]
todo_include_todos = True
intersphinx_mapping = {'python': ('https://docs.python.org/3', None),
'python2': ('https://docs.python.org/2', None),
'pyserial': ('https://pythonhosted.org/pyserial', None)}
intersphinx_mapping = {
"python": ("https://docs.python.org/3", None),
"python2": ("https://docs.python.org/2", None),
"pyserial": ("https://pythonhosted.org/pyserial", None),
}
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
templates_path = ["_templates"]
# The suffix of source filenames.
source_suffix = '.rst'
source_suffix = ".rst"
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
master_doc = "index"
# General information about the project.
project = 'OctoPrint'
copyright = '%d-%d, Gina Häußge' % (year_since, year_current) if year_current > year_since else '%d, Gina Häußge' % year_since
project = "OctoPrint"
copyright = (
"%d-%d, Gina Häußge" % (year_since, year_current)
if year_current > year_since
else "%d, Gina Häußge" % year_since
)
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
@@ -68,133 +82,136 @@ release = version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
exclude_patterns = ["_build"]
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
pygments_style = "sphinx"
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# keep_warnings = False
numfig = True
# -- Options for HTML output ---------------------------------------------------
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of built-in themes.
#html_theme = "sphinx_rtd_theme"
# html_theme = "sphinx_rtd_theme"
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the built-in static files,
# so a file named "default.css" will overwrite the built-in "default.css".
html_static_path = ['_static']
html_static_path = ["_static"]
def setup(app):
app.add_css_file("theme_overrides.css")
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'OctoPrintDoc'
htmlhelp_basename = "OctoPrintDoc"
# -- Options for LaTeX output --------------------------------------------------
#latex_elements = {
# latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
@@ -203,47 +220,44 @@ htmlhelp_basename = 'OctoPrintDoc'
# Additional stuff for the LaTeX preamble.
#'preamble': '',
#}
# }
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
#latex_documents = [
# latex_documents = [
# ('index', 'OctoPrint.tex', 'OctoPrint Documentation',
# 'Gina Häußge', 'manual'),
#]
# ]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# latex_logo = None
# For "manual" documents, if this is true, then top-level headings are parts,
# not chapters.
#latex_use_parts = False
# latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'octoprint', 'OctoPrint Documentation',
['Gina Häußge'], 1)
]
man_pages = [("index", "octoprint", "OctoPrint Documentation", ["Gina Häußge"], 1)]
# If true, show URL addresses after external links.
#man_show_urls = False
# man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
@@ -252,19 +266,25 @@ man_pages = [
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'OctoPrint', 'OctoPrint Documentation',
'Gina Häußge', 'OctoPrint', 'One line description of project.',
'Miscellaneous'),
(
"index",
"OctoPrint",
"OctoPrint Documentation",
"Gina Häußge",
"OctoPrint",
"One line description of project.",
"Miscellaneous",
),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# texinfo_no_detailmenu = False
+33 -4
View File
@@ -13,8 +13,8 @@ below.
* Prerequisites:
* `Python 2.7 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
* `Python 3.7 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
* `Python 2.7 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
* `Git <https://git-scm.com>`_
* Checkout the OctoPrint sources from their Git repository:
@@ -26,8 +26,8 @@ below.
installing and running OctoPrint and its dependencies. Creating virtual environments avoids potential versioning
issues for the dependencies with system wide installed instances:
* PY2: ``virtualenv --python=python2 venv2``
* PY3: ``virtualenv --python=python3 venv3``
* PY2: ``virtualenv --python=python2 venv2``
.. note::
@@ -35,10 +35,11 @@ below.
binaries cannot be found on your ``PATH`` like this you'll need to specify the full paths to them here,
e.g. ``virtualenv --python=/path/to/python2/bin/python venv2``
* Activate one of the virtual environments:
* Activate one of the virtual environments (the Python 3 venv should be considered the
primary one at this point):
* PY2: ``source venv2/bin/activate`` (Linux, macOS) or ``source venv2/Scripts/activate`` (Git Bash under Windows, see below)
* PY3: ``source venv3/bin/activate`` (Linux, macOS) or ``source venv3/Scripts/activate`` (Git Bash under Windows, see below)
* PY2: ``source venv2/bin/activate`` (Linux, macOS) or ``source venv2/Scripts/activate`` (Git Bash under Windows, see below)
* Update ``pip`` in the virtual environment:
@@ -49,10 +50,20 @@ below.
* ``pip install -e '.[develop,plugins]'``
* Set up the pre-commit hooks that make sure any changes you do adhere to the styling rules:
* ``pre-commit install``
* Tell ``git`` where to find the file with revisions to exclude for ``git blame``:
* ``git config blame.ignoreRevsFile .git-blame-ignore-revs``
When the virtual environment is activated you can then:
* run the OctoPrint server via ``octoprint serve``
* run the test suite from the checked out source folder via ``pytest``
* trigger the pre-commit check suite manually from the checked out source folder via
``pre-commit run --hook-stage manual --all-files``
To switch the activated virtual environment, simply activate the new environment as described above.
@@ -106,6 +117,8 @@ Then:
source ./venv3/bin/activate
pip install --upgrade pip
pip install -e .[develop,plugins,docs]
pre-commit install
git config blame.ignoreRevsFile .git-blame-ignore-revs
You can then start OctoPrint via ``octoprint`` after activating one of the two virtual environments.
@@ -149,6 +162,8 @@ Open the Git Bash you just installed and in that:
source ./venv3/Scripts/activate
pip install --upgrade pip
pip install -e .[develop,plugins,docs]
pre-commit install
git config blame.ignoreRevsFile .git-blame-ignore-revs
.. _sec-development-environment-mac:
@@ -198,6 +213,8 @@ You'll need a user account with administrator privileges.
source venv/bin/activate
pip install --upgrade pip
pip install -e .[develop,plugins]
pre-commit install
git config blame.ignoreRevsFile .git-blame-ignore-revs
.. _sec-development-environment-ides:
@@ -276,6 +293,18 @@ PyCharm
Note that this requires you to also have installed the additional ``docs`` dependencies into the Python 3 venv as
described above via ``pip install -e .[develop,plugins,docs]``.
- Settings > Tools > File Watchers (you might have to enable this, it's a bundled plugin), add new:
* Name: pre-commit
* File type: Python
* Scope: Module 'OctoPrint'
* Program: ``<OctoPrint venv3 folder>/bin/pre-commit`` (Linux) or ``<OctoPrint venv3 folder>/Scripts/pre-commit`` (Windows)
* Arguments: ``run --hook-stage manual --files $FilePath$``
* Output paths to refresh: ``$FilePath$``
* Working directory: ``$ProjectFileDir$``
* disable "Auto-save edited files to trigger the watched"
* enable "Trigger the watched on external changes"
To switch between Python 2 and 3, all you need to do now is change the Project Default Interpreter and restart
OctoPrint. On current PyCharm versions you can do that right from a small selection field in the footer of the IDE.
Otherwise go through Settings.
+214 -186
View File
@@ -2,7 +2,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'The MIT License <http://opensource.org/licenses/MIT>'
__license__ = "The MIT License <http://opensource.org/licenses/MIT>"
__copyright__ = "Copyright (C) 2015 Gina Häußge - Released under terms of the MIT License"
from sphinx.directives.code import CodeBlock
@@ -21,235 +21,263 @@ from pygments.lexers.python import PythonConsoleLexer
from pygments.util import ClassNotFound
if False:
# For type annotation
from typing import Any, Dict, List, Tuple # NOQA
# For type annotation
from typing import Any, Dict, List, Tuple # NOQA
def _merge_dict(a, b):
"""
Little helper to merge two dicts a and b on the fly.
"""
result = dict(a)
result.update(b)
return result
"""
Little helper to merge two dicts a and b on the fly.
"""
result = dict(a)
result.update(b)
return result
class literal_block_ext(nodes.General, nodes.FixedTextElement):
"""
Custom node which is basically the same as a :class:`literal_block`, just with whitespace support and introduced
in order to be able to have a custom visitor.
"""
"""
Custom node which is basically the same as a :class:`literal_block`, just with whitespace support and introduced
in order to be able to have a custom visitor.
"""
@classmethod
def from_literal_block(cls, block):
"""
Factory method constructing an instance exactly copying all attributes over from ``block`` and settings a
custom ``tagname``.
"""
new = literal_block_ext()
for a in (
"attributes",
"basic_attributes",
"child_text_separator",
"children",
"document",
"known_attributes",
"line",
"list_attributes",
"local_attributes",
"parent",
"rawsource",
"source",
):
setattr(new, a, getattr(block, a))
new.tagname = "literal_block_ext"
return new
@classmethod
def from_literal_block(cls, block):
"""
Factory method constructing an instance exactly copying all attributes over from ``block`` and settings a
custom ``tagname``.
"""
new = literal_block_ext()
for a in ("attributes", "basic_attributes", "child_text_separator", "children", "document", "known_attributes",
"line", "list_attributes", "local_attributes", "parent", "rawsource", "source"):
setattr(new, a, getattr(block, a))
new.tagname = "literal_block_ext"
return new
class CodeBlockExt(CodeBlock):
"""
This is basically an extension of a regular :class:`CodeBlock` directive which just supports an additional option
``whitespace`` which if present will enable (together with everything else in here) to render whitespace in
code blocks.
"""
"""
This is basically an extension of a regular :class:`CodeBlock` directive which just supports an additional option
``whitespace`` which if present will enable (together with everything else in here) to render whitespace in
code blocks.
"""
option_spec = _merge_dict(CodeBlock.option_spec, dict(whitespace=directives.flag))
option_spec = _merge_dict(CodeBlock.option_spec, {"whitespace": directives.flag})
def run(self):
# type: () -> List[nodes.Node]
# get result from parent implementation
code_block = CodeBlock.run(self)
def run(self):
# type: () -> List[nodes.Node]
# get result from parent implementation
code_block = CodeBlock.run(self)
def find_and_wrap_literal_block(node):
"""
Recursive method to turn all literal blocks located within a node into :class:`literal_block_ext`.
"""
def find_and_wrap_literal_block(node):
"""
Recursive method to turn all literal blocks located within a node into :class:`literal_block_ext`.
"""
if isinstance(node, nodes.container):
# container node => handle all children
children = []
for child in node.children:
children.append(find_and_wrap_literal_block(child))
node.children = children
return node
if isinstance(node, nodes.container):
# container node => handle all children
children = []
for child in node.children:
children.append(find_and_wrap_literal_block(child))
node.children = children
return node
elif isinstance(node, nodes.literal_block):
# literal block => replace it
return self._wrap_literal_block(node)
elif isinstance(node, nodes.literal_block):
# literal block => replace it
return self._wrap_literal_block(node)
else:
# no idea what that is => leave it alone
return node
else:
# no idea what that is => leave it alone
return node
# replace all created literal_blocks with literal_block_ext instances
return list(map(find_and_wrap_literal_block, code_block))
# replace all created literal_blocks with literal_block_ext instances
return list(map(find_and_wrap_literal_block, code_block))
def _wrap_literal_block(self, node):
literal = literal_block_ext.from_literal_block(node)
literal["whitespace"] = "whitespace" in self.options
return literal
def _wrap_literal_block(self, node):
literal = literal_block_ext.from_literal_block(node)
literal["whitespace"] = "whitespace" in self.options
return literal
class PygmentsBridgeExt(object):
"""
Wrapper for :class:`PygmentsBridge`, delegates everything to the wrapped ``bridge`` but :method:`highlight_block`,
which calls the parent implementation for lexer selection, then
"""
"""
Wrapper for :class:`PygmentsBridge`, delegates everything to the wrapped ``bridge`` but :method:`highlight_block`,
which calls the parent implementation for lexer selection, then
"""
def __init__(self, bridge, whitespace):
self._bridge = bridge
self._whitespace = whitespace
def __init__(self, bridge, whitespace):
self._bridge = bridge
self._whitespace = whitespace
def __getattr__(self, item):
return getattr(self._bridge, item)
def __getattr__(self, item):
return getattr(self._bridge, item)
def highlight_block(self, source, lang, opts=None, warn=None, force=False, **kwargs):
if not self._whitespace:
return self._bridge.highlight_block(source, lang, opts=opts, warn=warn, force=force, **kwargs)
def highlight_block(self, source, lang, opts=None, warn=None, force=False, **kwargs):
if not self._whitespace:
return self._bridge.highlight_block(
source, lang, opts=opts, warn=warn, force=force, **kwargs
)
# We are still here => we need to basically do everything the parent implementation does (and does so in a very
# inextensible way...), but inject the whitespace filter into the used lexer just before the highlighting run
# and remove it afterwards so the lexer can be safely reused.
#
# For this we define a context manager that will allow us to wrap a lexer and modify its filters on the fly to
# include the whitespace filter.
# We are still here => we need to basically do everything the parent implementation does (and does so in a very
# inextensible way...), but inject the whitespace filter into the used lexer just before the highlighting run
# and remove it afterwards so the lexer can be safely reused.
#
# For this we define a context manager that will allow us to wrap a lexer and modify its filters on the fly to
# include the whitespace filter.
class whitespace(object):
def __init__(self, lexer):
self._lexer = lexer
self._orig_filters = lexer.filters
self._orig_tabsize = lexer.tabsize
class whitespace(object):
def __init__(self, lexer):
self._lexer = lexer
self._orig_filters = lexer.filters
self._orig_tabsize = lexer.tabsize
def __enter__(self):
new_filters = list(self._orig_filters)
new_filters.append(VisibleWhitespaceFilter(spaces=True, tabs=True, tabsize=self._lexer.tabsize))
self._lexer.filters = new_filters
self._lexer.tabsize = 0
return self._lexer
def __enter__(self):
new_filters = list(self._orig_filters)
new_filters.append(
VisibleWhitespaceFilter(
spaces=True, tabs=True, tabsize=self._lexer.tabsize
)
)
self._lexer.filters = new_filters
self._lexer.tabsize = 0
return self._lexer
def __exit__(self, type, value, traceback):
self._lexer.filters = self._orig_filters
self._lexer.tabsize = self._orig_tabsize
def __exit__(self, type, value, traceback):
self._lexer.filters = self._orig_filters
self._lexer.tabsize = self._orig_tabsize
# Then a ton of copy-pasted code follows. Sadly, we need to do this since we have no way to inject ourselves
# into the highlighting call otherwise - lexer selection and actual call are tightly coupled in the original
# "highlight_block" method, with no means for external code to inject different functionality.
#
# Unless otherwise marked ("MODIFIED"), any code in this method after this line is copied verbatim from the
# implementation of sphinx.highlighting.PygmentsBridge, released under the Simplified BSD License, the copyright
# lies with the respective authors.
# Then a ton of copy-pasted code follows. Sadly, we need to do this since we have no way to inject ourselves
# into the highlighting call otherwise - lexer selection and actual call are tightly coupled in the original
# "highlight_block" method, with no means for external code to inject different functionality.
#
# Unless otherwise marked ("MODIFIED"), any code in this method after this line is copied verbatim from the
# implementation of sphinx.highlighting.PygmentsBridge, released under the Simplified BSD License, the copyright
# lies with the respective authors.
if not isinstance(source, text_type):
source = source.decode()
if not isinstance(source, text_type):
source = source.decode()
# find out which lexer to use
if lang in ('py', 'python'):
if source.startswith('>>>'):
# interactive session
lexer = sphinx.highlighting.lexers['pycon']
elif not force:
# maybe Python -- try parsing it
if self.try_parse(source):
lexer = sphinx.highlighting.lexers['python']
else:
lexer = sphinx.highlighting.lexers['none']
else:
lexer = sphinx.highlighting.lexers['python']
elif lang in ('python3', 'py3') and source.startswith('>>>'):
# for py3, recognize interactive sessions, but do not try parsing...
lexer = sphinx.highlighting.lexers['pycon3']
elif lang == 'guess':
# try:
lexer = sphinx.highlighting.guess_lexer(source)
# except Exception:
# lexer = sphinx.highlighting.lexers['none']
else:
if lang in sphinx.highlighting.lexers:
lexer = sphinx.highlighting.lexers[lang]
else:
try:
lexer = sphinx.highlighting.lexers[lang] = sphinx.highlighting.get_lexer_by_name(lang, **opts or {})
except ClassNotFound:
if warn:
warn('Pygments lexer name %r is not known' % lang)
lexer = sphinx.highlighting.lexers['none']
else:
raise
else:
lexer.add_filter('raiseonerror')
# find out which lexer to use
if lang in ("py", "python"):
if source.startswith(">>>"):
# interactive session
lexer = sphinx.highlighting.lexers["pycon"]
elif not force:
# maybe Python -- try parsing it
if self.try_parse(source):
lexer = sphinx.highlighting.lexers["python"]
else:
lexer = sphinx.highlighting.lexers["none"]
else:
lexer = sphinx.highlighting.lexers["python"]
elif lang in ("python3", "py3") and source.startswith(">>>"):
# for py3, recognize interactive sessions, but do not try parsing...
lexer = sphinx.highlighting.lexers["pycon3"]
elif lang == "guess":
# try:
lexer = sphinx.highlighting.guess_lexer(source)
# except Exception:
# lexer = sphinx.highlighting.lexers['none']
else:
if lang in sphinx.highlighting.lexers:
lexer = sphinx.highlighting.lexers[lang]
else:
try:
lexer = sphinx.highlighting.lexers[
lang
] = sphinx.highlighting.get_lexer_by_name(lang, **opts or {})
except ClassNotFound:
if warn:
warn("Pygments lexer name %r is not known" % lang)
lexer = sphinx.highlighting.lexers["none"]
else:
raise
else:
lexer.add_filter("raiseonerror")
if not isinstance(source, text_type):
source = source.decode()
if not isinstance(source, text_type):
source = source.decode()
# trim doctest options if wanted
if isinstance(lexer, PythonConsoleLexer) and self._bridge.trim_doctest_flags:
source = doctest.blankline_re.sub('', source)
source = doctest.doctestopt_re.sub('', source)
# trim doctest options if wanted
if isinstance(lexer, PythonConsoleLexer) and self._bridge.trim_doctest_flags:
source = doctest.blankline_re.sub("", source)
source = doctest.doctestopt_re.sub("", source)
# highlight via Pygments
formatter = self._bridge.get_formatter(**kwargs)
try:
# MODIFIED: replaced by whitespace wrapped call
with whitespace(lexer) as l:
hlsource = highlight(source, l, formatter)
# /MODIFIED
except ErrorToken:
# this is most probably not the selected language,
# so let it pass unhighlighted
# highlight via Pygments
formatter = self._bridge.get_formatter(**kwargs)
try:
# MODIFIED: replaced by whitespace wrapped call
with whitespace(lexer) as l:
hlsource = highlight(source, l, formatter)
# /MODIFIED
except ErrorToken:
# this is most probably not the selected language,
# so let it pass unhighlighted
# MODIFIED: replaced by whitespace wrapped call
with whitespace(sphinx.highlighting.lexers["none"]) as l:
hlsource = highlight(source, l, formatter)
# /MODIFIED
return hlsource
# MODIFIED: replaced by whitespace wrapped call
with whitespace(sphinx.highlighting.lexers["none"]) as l:
hlsource = highlight(source, l, formatter)
# /MODIFIED
return hlsource
class whitespace_highlighter(object):
"""
Context manager for adapting the used highlighter on a translator for a given node's whitespace properties.
"""
def __init__(self, translator, node):
self.translator = translator
self.node = node
"""
Context manager for adapting the used highlighter on a translator for a given node's whitespace properties.
"""
self._orig_highlighter = self.translator.highlighter
def __init__(self, translator, node):
self.translator = translator
self.node = node
def __enter__(self):
whitespace = self.node["whitespace"] if "whitespace" in self.node else False
if whitespace:
self.translator.highlighter = PygmentsBridgeExt(self._orig_highlighter, whitespace)
return self.translator
self._orig_highlighter = self.translator.highlighter
def __exit__(self, exc_type, exc_val, exc_tb):
self.translator.highlighter = self._orig_highlighter
def __enter__(self):
whitespace = self.node["whitespace"] if "whitespace" in self.node else False
if whitespace:
self.translator.highlighter = PygmentsBridgeExt(
self._orig_highlighter, whitespace
)
return self.translator
def __exit__(self, exc_type, exc_val, exc_tb):
self.translator.highlighter = self._orig_highlighter
def visit_literal_block_ext(translator, node):
"""
When our custom code block is visited, we temporarily exchange the highlighter used in the translator, call the
visitor for regular literal blocks, then switch back again.
"""
with whitespace_highlighter(translator, node):
translator.visit_literal_block(node)
"""
When our custom code block is visited, we temporarily exchange the highlighter used in the translator, call the
visitor for regular literal blocks, then switch back again.
"""
with whitespace_highlighter(translator, node):
translator.visit_literal_block(node)
def depart_literal_block_ext(translator, node):
"""
Just call the depart function for regular literal blocks.
"""
with whitespace_highlighter(translator, node):
translator.depart_literal_block(node)
"""
Just call the depart function for regular literal blocks.
"""
with whitespace_highlighter(translator, node):
translator.depart_literal_block(node)
def setup(app):
# custom directive
app.add_directive("code-block-ext", CodeBlockExt)
# custom directive
app.add_directive("code-block-ext", CodeBlockExt)
# custom node type
handler = (visit_literal_block_ext, depart_literal_block_ext)
app.add_node(literal_block_ext, html=handler, latex=handler, text=handler)
# custom node type
handler = (visit_literal_block_ext, depart_literal_block_ext)
app.add_node(literal_block_ext, html=handler, latex=handler, text=handler)
return dict(version="0.1")
return {"version": "0.1"}
+90 -75
View File
@@ -2,7 +2,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'The MIT License <http://opensource.org/licenses/MIT>'
__license__ = "The MIT License <http://opensource.org/licenses/MIT>"
__copyright__ = "Copyright (C) 2015 Gina Häußge - Released under terms of the MIT License"
@@ -10,103 +10,118 @@ import codecs
import requests
from contextlib import closing
from sphinx.directives.code import LiteralIncludeReader, LiteralInclude, dedent_lines, \
nodes, parselinenos, logger, container_wrapper
from sphinx.directives.code import (
LiteralIncludeReader,
LiteralInclude,
dedent_lines,
nodes,
parselinenos,
logger,
container_wrapper,
)
from sphinx.util.nodes import set_source_info
if False:
# For type annotation
from typing import Any, List # NOQA
# For type annotation
from typing import Any, List # NOQA
cache = {}
cache = dict()
class OnlineIncludeReader(LiteralIncludeReader):
def read_file(self, filename, location=None):
# type: (unicode, Any) -> List[unicode]
def read_file(self, filename, location=None):
# type: (unicode, Any) -> List[unicode]
global cache
try:
if filename in cache:
lines = cache[filename]
else:
with closing(requests.get(filename, stream=True)) as r:
r.encoding = self.encoding
lines = r.text.splitlines(True)
cache[filename] = lines
global cache
try:
if filename in cache:
lines = cache[filename]
else:
with closing(requests.get(filename, stream=True)) as r:
r.encoding = self.encoding
lines = r.text.splitlines(True)
cache[filename] = lines
if "tab-width" in self.options:
lines = [line.expandtabs(self.options["tab-width"]) for line in lines]
if 'tab-width' in self.options:
lines = [line.expandtabs(self.options['tab-width']) for line in lines]
return lines
except (IOError, OSError):
raise IOError('Include file %r not found or reading it failed' % filename)
except UnicodeError:
raise UnicodeError('Encoding %r used for reading included file %r seems to '
'be wrong, try giving an :encoding: option' % (self.encoding, filename))
return lines
except (IOError, OSError):
raise IOError("Include file %r not found or reading it failed" % filename)
except UnicodeError:
raise UnicodeError(
"Encoding %r used for reading included file %r seems to "
"be wrong, try giving an :encoding: option" % (self.encoding, filename)
)
class OnlineIncludeDirective(LiteralInclude):
def run(self):
# type: () -> List[nodes.Node]
document = self.state.document
if not document.settings.file_insertion_enabled:
return [
document.reporter.warning("File insertion disabled", line=self.lineno)
]
# convert options['diff'] to absolute path
if "diff" in self.options:
_, path = self.env.relfn2path(self.options["diff"])
self.options["diff"] = path
def run(self):
# type: () -> List[nodes.Node]
document = self.state.document
if not document.settings.file_insertion_enabled:
return [document.reporter.warning('File insertion disabled',
line=self.lineno)]
# convert options['diff'] to absolute path
if 'diff' in self.options:
_, path = self.env.relfn2path(self.options['diff'])
self.options['diff'] = path
try:
location = self.state_machine.get_source_and_line(self.lineno)
url = self.arguments[0]
try:
location = self.state_machine.get_source_and_line(self.lineno)
url = self.arguments[0]
reader = OnlineIncludeReader(url, self.options, self.config)
text, lines = reader.read(location=location)
reader = OnlineIncludeReader(url, self.options, self.config)
text, lines = reader.read(location=location)
retnode = nodes.literal_block(text, text, source=url)
set_source_info(self, retnode)
if self.options.get("diff"): # if diff is set, set udiff
retnode["language"] = "udiff"
elif "language" in self.options:
retnode["language"] = self.options["language"]
retnode["linenos"] = (
"linenos" in self.options
or "lineno-start" in self.options
or "lineno-match" in self.options
)
retnode["classes"] += self.options.get("class", [])
extra_args = retnode["highlight_args"] = {}
if "emphasize-lines" in self.options:
hl_lines = parselinenos(self.options["emphasize-lines"], lines)
if any(i >= lines for i in hl_lines):
logger.warning(
"line number spec is out of range(1-%d): %r"
% (lines, self.options["emphasize-lines"]),
location=location,
)
extra_args["hl_lines"] = [x + 1 for x in hl_lines if x < lines]
extra_args["linenostart"] = reader.lineno_start
retnode = nodes.literal_block(text, text, source=url)
set_source_info(self, retnode)
if self.options.get('diff'): # if diff is set, set udiff
retnode['language'] = 'udiff'
elif 'language' in self.options:
retnode['language'] = self.options['language']
retnode['linenos'] = ('linenos' in self.options or
'lineno-start' in self.options or
'lineno-match' in self.options)
retnode['classes'] += self.options.get('class', [])
extra_args = retnode['highlight_args'] = {}
if 'emphasize-lines' in self.options:
hl_lines = parselinenos(self.options['emphasize-lines'], lines)
if any(i >= lines for i in hl_lines):
logger.warning('line number spec is out of range(1-%d): %r' %
(lines, self.options['emphasize-lines']),
location=location)
extra_args['hl_lines'] = [x + 1 for x in hl_lines if x < lines]
extra_args['linenostart'] = reader.lineno_start
if "caption" in self.options:
caption = self.options["caption"] or self.arguments[0]
retnode = container_wrapper(self, retnode, caption)
if 'caption' in self.options:
caption = self.options['caption'] or self.arguments[0]
retnode = container_wrapper(self, retnode, caption)
# retnode will be note_implicit_target that is linked from caption and numref.
# when options['name'] is provided, it should be primary ID.
self.add_name(retnode)
# retnode will be note_implicit_target that is linked from caption and numref.
# when options['name'] is provided, it should be primary ID.
self.add_name(retnode)
return [retnode]
except Exception as exc:
return [document.reporter.warning(str(exc), line=self.lineno)]
return [retnode]
except Exception as exc:
return [document.reporter.warning(str(exc), line=self.lineno)]
def visit_onlineinclude(translator, node):
translator.visit_literal_block(node)
translator.visit_literal_block(node)
def depart_onlineinclude(translator, node):
translator.depart_literal_block(node)
translator.depart_literal_block(node)
def setup(app):
app.add_directive("onlineinclude", OnlineIncludeDirective)
app.add_directive("onlineinclude", OnlineIncludeDirective)
handler = (visit_onlineinclude, depart_onlineinclude)
app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler)
handler = (visit_onlineinclude, depart_onlineinclude)
app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler)
+6 -3
View File
@@ -10,17 +10,20 @@ basedir = os.path.dirname(os.path.realpath(__file__))
old = os.path.join(basedir, "octoprint")
if os.path.exists(old):
# rename left-overs from old file structure
print("""
print(
"""
Found left-overs from old file structure, renaming to
"octoprint.backup". Please remove this manually (I don't
dare to do so myself since you might have changes in there
I don't know anything about).
""")
"""
)
os.rename(old, os.path.join(basedir, "octoprint.backup"))
sys.path.insert(0, os.path.join(basedir, "src"))
import octoprint
import octoprint # noqa: E402
if len(sys.argv) == 1:
sys.argv.append("serve")
octoprint.main()
+17 -6
View File
@@ -14,11 +14,22 @@ parentdir_prefix =
lookupfile = .versioneer-lookup
[flake8]
ignore =
D
E
W
F401
F523
max-line-length = 90
extend-ignore = E203, E231, E265, E266, E402, E501, E731
select = B,C,E,F,W,T4,B9
exclude =
src/octoprint/vendor
[isort]
multi_line_output = 3
include_trailing_comma = True
force_grid_wrap = 0
use_parentheses = True
ensure_newline_before_comments = True
line_length = 90
skip =
src/octoprint/vendor
known_first_party =
octoprint
octoprint_setuptools
octoprint_client
+234 -230
View File
@@ -1,302 +1,306 @@
#!/usr/bin/env python2
# coding=utf-8
from distutils.command.build_py import build_py as _build_py
import os
import versioneer
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "src"))
import octoprint_setuptools
import setuptools
from distutils.command.build_py import build_py as _build_py
#-----------------------------------------------------------------------------------------------------------------------
import versioneer # noqa: F401
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "src"))
import setuptools # noqa: F401,E402
import octoprint_setuptools # noqa: F401,E402
# ----------------------------------------------------------------------------------------
# Supported python versions
# we test against 2.7, 3.6 and 3.7, so that's what we'll mark as supported
PYTHON_REQUIRES = ">=2.7.9, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, <4"
# Requirements for setup.py
SETUP_REQUIRES = [
"markdown>=3.1,<3.2" # newer versions require Python 3
]
SETUP_REQUIRES = ["markdown>=3.1,<3.2"] # newer versions require Python 3
# Requirements for our application
INSTALL_REQUIRES = [
# additional OctoPrint plugins that are maintained on a different release cycle
"OctoPrint-FirmwareCheck>=2020.06.22",
"OctoPrint-FileCheck>=2020.07.06",
# the following dependencies are non trivial to update since later versions introduce backwards incompatible
# changes that might affect plugins, or due to other observed problems
"markupsafe>=1.1,<2.0", # Jinja dependency, newer versions require Python 3
"tornado==5.1.1", # newer versions require Python 3
"markdown>=3.1,<3.2", # newer versions require Python 3
"rsa==4.0", # newer versions require Python 3
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
# anything below this should be checked on releases for new versions
"flask>=1.1.2,<2",
"Jinja2>=2.11.2,<3",
"Flask-Login>=0.5,<0.6", # flask-login doesn't use semver & breaks stuff on minor version increases
"Flask-Babel>=1.0,<2",
"Flask-Assets>=2.0,<3",
"werkzeug>=1.0.1,<2",
"itsdangerous>=1.1.0,<2",
"cachelib>=0.1,<1",
"PyYAML>=5.3.1,<6",
"pyserial>=3.4,<4",
"netaddr>=0.7.19,<1",
"watchdog>=0.10.2,<1",
"sarge==0.1.5post0",
"netifaces>=0.10.9,<1",
"pylru>=1.2,<2",
"pkginfo>=1.5.0.1,<2",
"requests>=2.23.0,<3",
"semantic_version>=2.8.5,<3",
"psutil>=5.7,<6",
"Click>=7.1.2,<8",
"feedparser>=5.2.1,<6",
"future>=0.18.2,<1",
"websocket-client>=0.57,<1",
"wrapt>=1.12.1,<2",
"emoji>=0.5.4,<1",
"frozendict>=1.2,<2",
"sentry-sdk>=0.15.1,<1",
"filetype>=1.0.7,<2",
# vendor bundle dependencies
"unidecode>=0.04.14,<0.05", # dependency of awesome-slugify
"blinker>=1.4,<2" # dependency of flask_principal
# additional OctoPrint plugins that are maintained on a different release cycle
"OctoPrint-FirmwareCheck>=2020.06.22",
"OctoPrint-FileCheck>=2020.07.06",
# the following dependencies are non trivial to update since later versions
# introduce backwards incompatible changes that might affect plugins, or due to
# other observed problems
"markupsafe>=1.1,<2.0", # Jinja dependency, newer versions require Python 3
"tornado==5.1.1", # newer versions require Python 3
"markdown>=3.1,<3.2", # newer versions require Python 3
"rsa==4.0", # newer versions require Python 3
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
# anything below this should be checked on releases for new versions
"flask>=1.1.2,<2",
"Jinja2>=2.11.2,<3",
"Flask-Login>=0.5,<0.6", # flask-login doesn't use semver & breaks stuff on minor version increases
"Flask-Babel>=1.0,<2",
"Flask-Assets>=2.0,<3",
"werkzeug>=1.0.1,<2",
"itsdangerous>=1.1.0,<2",
"cachelib>=0.1,<1",
"PyYAML>=5.3.1,<6",
"pyserial>=3.4,<4",
"netaddr>=0.7.19,<1",
"watchdog>=0.10.2,<1",
"sarge==0.1.5post0",
"netifaces>=0.10.9,<1",
"pylru>=1.2,<2",
"pkginfo>=1.5.0.1,<2",
"requests>=2.23.0,<3",
"semantic_version>=2.8.5,<3",
"psutil>=5.7,<6",
"Click>=7.1.2,<8",
"feedparser>=5.2.1,<6",
"future>=0.18.2,<1",
"websocket-client>=0.57,<1",
"wrapt>=1.12.1,<2",
"emoji>=0.5.4,<1",
"frozendict>=1.2,<2",
"sentry-sdk>=0.15.1,<1",
"filetype>=1.0.7,<2",
# vendor bundled dependencies
"unidecode>=0.04.14,<0.05", # dependency of awesome-slugify
"blinker>=1.4,<2", # dependency of flask_principal
]
# Python 2 specific requirements
INSTALL_REQUIRES_PYTHON2 = [
"futures>=3.3,<4",
"monotonic>=1.5,<2",
"scandir>=1.10,<2",
"chainmap>=1.0.3,<2",
"typing>=3.7.4.1,<4"
"futures>=3.3,<4",
"monotonic>=1.5,<2",
"scandir>=1.10,<2",
"chainmap>=1.0.3,<2",
"typing>=3.7.4.1,<4",
]
# Python 3 specific requirements
INSTALL_REQUIRES_PYTHON3 = [
"zeroconf>=0.24,<0.25"
]
INSTALL_REQUIRES_PYTHON3 = ["zeroconf>=0.24,<0.25"]
# OSX specific requirements
INSTALL_REQUIRES_OSX = [
"appdirs>=1.4.4",
"appdirs>=1.4.4",
]
# Additional requirements for optional install options
EXTRA_REQUIRES = dict(
# Dependencies for developing OctoPrint
develop=[
# Testing dependencies - SEE ALSO tox.ini
"mock>=3.0.5,<4",
"pytest==4.6.10",
"pytest-doctest-custom>=1.0.0,<2",
"ddt",
# linter
"flake8",
# profiler
"pyinstrument",
],
# Dependencies for developing OctoPrint plugins
plugins=[
"cookiecutter>=1.7.2,<1.8"
],
# Dependencies for building the documentation - Python 3 required!
docs=[
"sphinx>=3,<4",
"sphinxcontrib-httpdomain",
"sphinxcontrib-mermaid",
"sphinx_rtd_theme",
"readthedocs-sphinx-ext"
],
)
EXTRA_REQUIRES = {
"develop": [
# Testing dependencies
"mock>=3.0.5,<4",
"pytest==4.6.10",
"pytest-doctest-custom>=1.0.0,<2",
"ddt",
# pre-commit
"pre-commit",
# profiler
"pyinstrument",
],
# Dependencies for developing OctoPrint plugins
"plugins": ["cookiecutter>=1.7.2,<1.8"],
# Dependencies for building the documentation - Python 3 required!
"docs": [
"sphinx>=3,<4",
"sphinxcontrib-httpdomain",
"sphinxcontrib-mermaid",
"sphinx_rtd_theme",
"readthedocs-sphinx-ext",
],
}
# Dependency links for any of the aforementioned dependencies
DEPENDENCY_LINKS = []
# adapted from https://hynek.me/articles/conditional-python-dependencies/
if int(setuptools.__version__.split(".", 1)[0]) < 18:
# no bdist_wheel support for setuptools < 18 since we build universal wheels and our optional dependencies
# would get lost there
assert "bdist_wheel" not in sys.argv
# no bdist_wheel support for setuptools < 18 since we build universal wheels and our optional dependencies
# would get lost there
assert "bdist_wheel" not in sys.argv
# add optional dependencies for setuptools versions < 18 that don't yet support environment markers
if sys.version_info[0] < 3:
INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON2
else:
INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON3
# add optional dependencies for setuptools versions < 18 that don't yet support environment markers
if sys.version_info[0] < 3:
INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON2
else:
INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON3
if sys.platform == "darwin":
INSTALL_REQUIRES += INSTALL_REQUIRES_OSX
if sys.platform == "darwin":
INSTALL_REQUIRES += INSTALL_REQUIRES_OSX
else:
# environment markers supported
EXTRA_REQUIRES[":python_version < '3'"] = INSTALL_REQUIRES_PYTHON2
EXTRA_REQUIRES[":python_version >= '3'"] = INSTALL_REQUIRES_PYTHON3
EXTRA_REQUIRES[":sys_platform == 'darwin'"] = INSTALL_REQUIRES_OSX
# environment markers supported
EXTRA_REQUIRES[":python_version < '3'"] = INSTALL_REQUIRES_PYTHON2
EXTRA_REQUIRES[":python_version >= '3'"] = INSTALL_REQUIRES_PYTHON3
EXTRA_REQUIRES[":sys_platform == 'darwin'"] = INSTALL_REQUIRES_OSX
#-----------------------------------------------------------------------------------------------------------------------
# -----------------------------------------------------------------------------------------------------------------------
# Anything below here is just command setup and general setup configuration
here = os.path.abspath(os.path.dirname(__file__))
def read_file_contents(path):
import codecs
with codecs.open(path, encoding="utf-8") as f:
return f.read()
import codecs
with codecs.open(path, encoding="utf-8") as f:
return f.read()
def md_to_html_build_py_factory(files, baseclass):
class md_to_html_build_py(baseclass):
files = dict()
class md_to_html_build_py(baseclass):
files = {}
def run(self):
print("RUNNING md_to_html_build_py")
if not self.dry_run:
for directory, files in self.files.items():
target_dir = os.path.join(self.build_lib, directory)
self.mkpath(target_dir)
def run(self):
print("RUNNING md_to_html_build_py")
if not self.dry_run:
for directory, files in self.files.items():
target_dir = os.path.join(self.build_lib, directory)
self.mkpath(target_dir)
for entry in files:
if isinstance(entry, tuple):
if len(entry) != 2:
continue
source, dest = entry[0], os.path.join(target_dir, entry[1])
else:
source = entry
dest = os.path.join(target_dir, source + ".html")
for entry in files:
if isinstance(entry, tuple):
if len(entry) != 2:
continue
source, dest = entry[0], os.path.join(target_dir, entry[1])
else:
source = entry
dest = os.path.join(target_dir, source + ".html")
print("Rendering markdown from {} to {}".format(source, dest))
print("Rendering markdown from {} to {}".format(source, dest))
from markdown import markdownFromFile
markdownFromFile(input=source,
output=dest,
encoding="utf-8")
baseclass.run(self)
from markdown import markdownFromFile
markdownFromFile(input=source, output=dest, encoding="utf-8")
baseclass.run(self)
return type(md_to_html_build_py)(
md_to_html_build_py.__name__, (md_to_html_build_py,), {"files": files}
)
return type(md_to_html_build_py)(md_to_html_build_py.__name__,
(md_to_html_build_py,),
dict(files=files))
def get_cmdclass():
# make sure these are always available, even when run by dependabot
global versioneer, octoprint_setuptools, md_to_html_build_py_factory
# make sure these are always available, even when run by dependabot
global versioneer, octoprint_setuptools, md_to_html_build_py_factory
cmdclass = versioneer.get_cmdclass()
cmdclass = versioneer.get_cmdclass()
# add clean command
cmdclass.update(dict(clean=octoprint_setuptools.CleanCommand.for_options(source_folder="src", eggs=["OctoPrint*.egg-info"])))
# add clean command
cmdclass.update(
{
"clean": octoprint_setuptools.CleanCommand.for_options(
source_folder="src", eggs=["OctoPrint*.egg-info"]
)
}
)
# add translation commands
translation_dir = "translations"
pot_file = os.path.join(translation_dir, "messages.pot")
bundled_dir = os.path.join("src", "octoprint", "translations")
cmdclass.update(octoprint_setuptools.get_babel_commandclasses(pot_file=pot_file, output_dir=translation_dir, pack_name_prefix="OctoPrint-i18n-", pack_path_prefix="", bundled_dir=bundled_dir))
# add translation commands
translation_dir = "translations"
pot_file = os.path.join(translation_dir, "messages.pot")
bundled_dir = os.path.join("src", "octoprint", "translations")
cmdclass.update(
octoprint_setuptools.get_babel_commandclasses(
pot_file=pot_file,
output_dir=translation_dir,
pack_name_prefix="OctoPrint-i18n-",
pack_path_prefix="",
bundled_dir=bundled_dir,
)
)
cmdclass["build_py"] = md_to_html_build_py_factory({
"octoprint/templates/_data": [
"AUTHORS.md",
"SUPPORTERS.md",
"THIRDPARTYLICENSES.md",
]
}, cmdclass["build_py"] if "build_py" in cmdclass else _build_py)
cmdclass["build_py"] = md_to_html_build_py_factory(
{
"octoprint/templates/_data": [
"AUTHORS.md",
"SUPPORTERS.md",
"THIRDPARTYLICENSES.md",
]
},
cmdclass["build_py"] if "build_py" in cmdclass else _build_py,
)
return cmdclass
return cmdclass
def params():
# make sure these are always available, even when run by dependabot
global versioneer, get_cmdclass, read_file_contents, here, \
PYTHON_REQUIRES, SETUP_REQUIRES, INSTALL_REQUIRES, EXTRA_REQUIRES, DEPENDENCY_LINKS
# make sure these are always available, even when run by dependabot
global versioneer, get_cmdclass, read_file_contents, here, PYTHON_REQUIRES, SETUP_REQUIRES, INSTALL_REQUIRES, EXTRA_REQUIRES, DEPENDENCY_LINKS
name = "OctoPrint"
version = versioneer.get_version()
cmdclass = get_cmdclass()
name = "OctoPrint"
version = versioneer.get_version()
cmdclass = get_cmdclass()
description = "The snappy web interface for your 3D printer"
long_description = read_file_contents(os.path.join(here, "README.md"))
long_description_content_type = "text/markdown"
description = "The snappy web interface for your 3D printer"
long_description = read_file_contents(os.path.join(here, "README.md"))
long_description_content_type = "text/markdown"
python_requires = PYTHON_REQUIRES
setup_requires = SETUP_REQUIRES
install_requires = INSTALL_REQUIRES
extras_require = EXTRA_REQUIRES
dependency_links = DEPENDENCY_LINKS
python_requires = PYTHON_REQUIRES
setup_requires = SETUP_REQUIRES
install_requires = INSTALL_REQUIRES
extras_require = EXTRA_REQUIRES
dependency_links = DEPENDENCY_LINKS
classifiers = [
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Framework :: Flask",
"Intended Audience :: Developers",
"Intended Audience :: Education",
"Intended Audience :: End Users/Desktop",
"Intended Audience :: Manufacturing",
"Intended Audience :: Other Audience",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: GNU Affero General Public License v3",
"Natural Language :: English",
"Natural Language :: German",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: JavaScript",
"Topic :: Printing",
"Topic :: System :: Monitoring"
]
author = "Gina Häußge"
author_email = "gina@octoprint.org"
url = "https://octoprint.org"
license = "GNU Affero General Public License v3"
keywords = "3dprinting 3dprinter 3d-printing 3d-printer octoprint"
classifiers = [
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Framework :: Flask",
"Intended Audience :: Developers",
"Intended Audience :: Education",
"Intended Audience :: End Users/Desktop",
"Intended Audience :: Manufacturing",
"Intended Audience :: Other Audience",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: GNU Affero General Public License v3",
"Natural Language :: English",
"Natural Language :: German",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: JavaScript",
"Topic :: Printing",
"Topic :: System :: Monitoring",
]
author = "Gina Häußge"
author_email = "gina@octoprint.org"
url = "https://octoprint.org"
license = "GNU Affero General Public License v3"
keywords = "3dprinting 3dprinter 3d-printing 3d-printer octoprint"
project_urls={
"Community Forum": "https://community.octoprint.org",
"Bug Reports": "https://github.com/foosel/OctoPrint/issues",
"Source": "https://github.com/foosel/OctoPrint",
"Funding": "https://donate.octoprint.org"
}
project_urls = {
"Community Forum": "https://community.octoprint.org",
"Bug Reports": "https://github.com/foosel/OctoPrint/issues",
"Source": "https://github.com/foosel/OctoPrint",
"Funding": "https://donate.octoprint.org",
}
packages = setuptools.find_packages(where="src")
package_dir = {
"": "src",
}
package_data = {
"octoprint": octoprint_setuptools.package_data_dirs('src/octoprint',
['static', 'templates', 'plugins', 'translations'])
+ ['util/piptestballoon/setup.py']
}
packages = setuptools.find_packages(where="src")
package_dir = {
"": "src",
}
package_data = {
"octoprint": octoprint_setuptools.package_data_dirs(
"src/octoprint", ["static", "templates", "plugins", "translations"]
)
+ ["util/piptestballoon/setup.py"]
}
include_package_data = True
zip_safe = False
include_package_data = True
zip_safe = False
if os.environ.get('READTHEDOCS', None) == 'True':
# we can't tell read the docs to please perform a pip install -e .[docs], so we help
# it a bit here by explicitly adding the development dependencies, which include our
# documentation dependencies
install_requires = install_requires + extras_require['docs']
if os.environ.get("READTHEDOCS", None) == "True":
# we can't tell read the docs to please perform a pip install -e .[docs], so we help
# it a bit here by explicitly adding the development dependencies, which include our
# documentation dependencies
install_requires = install_requires + extras_require["docs"]
entry_points = {
"console_scripts": [
"octoprint = octoprint:main"
]
}
entry_points = {"console_scripts": ["octoprint = octoprint:main"]}
return locals()
return locals()
setuptools.setup(**params())
+632 -510
View File
File diff suppressed because it is too large. Load diff
+3 -2
View File
@@ -3,5 +3,6 @@
from __future__ import absolute_import, division, print_function, unicode_literals
if __name__ == "__main__":
import octoprint
octoprint.main()
import octoprint
octoprint.main()
+113 -81
View File
@@ -14,11 +14,11 @@ from __future__ import absolute_import, division, print_function, unicode_litera
import errno
import io
import logging
import os
import re
import subprocess
import sys
import logging
def get_keywords():
@@ -64,12 +64,14 @@ HANDLERS = {}
def register_vcs_handler(vcs, method): # decorator
"""Decorator to mark a method as the handler for a particular VCS."""
def decorate(f):
"""Store f in HANDLERS[vcs][method]."""
if vcs not in HANDLERS:
HANDLERS[vcs] = {}
HANDLERS[vcs][method] = f
return f
return decorate
@@ -81,9 +83,12 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
try:
dispcmd = str([c] + args)
# remember shell=False, so use git.cmd on windows, not just git
p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,
stderr=(subprocess.PIPE if hide_stderr
else None))
p = subprocess.Popen(
[c] + args,
cwd=cwd,
stdout=subprocess.PIPE,
stderr=(subprocess.PIPE if hide_stderr else None),
)
break
except EnvironmentError:
e = sys.exc_info()[1]
@@ -116,12 +121,17 @@ def versions_from_parentdir(parentdir_prefix, root, verbose):
dirname = os.path.basename(root)
if not dirname.startswith(parentdir_prefix):
if verbose:
print("guessing rootdir is '%s', but '%s' doesn't start with "
"prefix '%s'" % (root, dirname, parentdir_prefix))
print(
"guessing rootdir is '%s', but '%s' doesn't start with "
"prefix '%s'" % (root, dirname, parentdir_prefix)
)
raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
return {"version": dirname[len(parentdir_prefix):],
"full-revisionid": None,
"dirty": False, "error": None}
return {
"version": dirname[len(parentdir_prefix) :],
"full-revisionid": None,
"dirty": False,
"error": None,
}
@register_vcs_handler("git", "get_keywords")
@@ -163,7 +173,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
# starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
# just "foo-1.0". If we see a "tag: " prefix, prefer those.
TAG = "tag: "
tags = {r[len(TAG):] for r in refs if r.startswith(TAG)}
tags = {r[len(TAG) :] for r in refs if r.startswith(TAG)}
if not tags:
# Either we're using git < 1.8.3, or there really are no tags. We use
# a heuristic: assume all version tags have a digit. The old git %d
@@ -172,12 +182,15 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
# between branches and tags. By ignoring refnames without digits, we
# filter out many common branch names like "release" and
# "stabilization", as well as "HEAD" and "master".
tags = {r for r in refs if re.search(r'\d', r)}
tags = {r for r in refs if re.search(r"\d", r)}
if verbose:
print("discarding '%s', no digits" % ",".join(refs-tags))
print("discarding '%s', no digits" % ",".join(refs - tags))
branches = [r for r in refs if not r.startswith(TAG)
and r != "HEAD" and not r.startswith("refs/")]
branches = [
r
for r in refs
if not r.startswith(TAG) and r != "HEAD" and not r.startswith("refs/")
]
if verbose:
print("likely branches: %s" % ",".join(sorted(branches)))
branch = None
@@ -189,22 +202,28 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
for ref in sorted(tags):
# sorting will prefer e.g. "2.0" over "2.0rc1"
if ref.startswith(tag_prefix):
r = ref[len(tag_prefix):]
r = ref[len(tag_prefix) :]
if verbose:
print("picking %s" % r)
result = {"version": r,
"full-revisionid": keywords["full"].strip(),
"dirty": False, "error": None}
result = {
"version": r,
"full-revisionid": keywords["full"].strip(),
"dirty": False,
"error": None,
}
if branch is not None:
result["branch"] = branch
return result
# no suitable tags, so version is "0+unknown", but full hex is still there
if verbose:
print("no suitable tags, using unknown + full revision id")
return {"version": "0+unknown",
"full-revisionid": keywords["full"].strip(),
"dirty": False, "error": "no suitable tags"}
return {
"version": "0+unknown",
"full-revisionid": keywords["full"].strip(),
"dirty": False,
"error": "no suitable tags",
}
@register_vcs_handler("git", "pieces_from_vcs")
@@ -225,10 +244,19 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
GITS = ["git.cmd", "git.exe"]
# if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
# if there isn't one, this yields HEX[-dirty] (no NUM)
describe_out = run_command(GITS, ["describe", "--tags", "--dirty",
"--always", "--long",
"--match", "%s*" % tag_prefix],
cwd=root)
describe_out = run_command(
GITS,
[
"describe",
"--tags",
"--dirty",
"--always",
"--long",
"--match",
"%s*" % tag_prefix,
],
cwd=root,
)
# --long was added in git-1.5.5
if describe_out is None:
raise NotThisMethod("'git describe' failed")
@@ -251,12 +279,10 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
dirty = git_describe.endswith("-dirty")
pieces["dirty"] = dirty
if dirty:
git_describe = git_describe[:git_describe.rindex("-dirty")]
git_describe = git_describe[: git_describe.rindex("-dirty")]
# figure out our branch
abbrev_ref_out = run_command(GITS,
["rev-parse", "--abbrev-ref", "HEAD"],
cwd=root)
abbrev_ref_out = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root)
if abbrev_ref_out is not None and abbrev_ref_out != "HEAD":
pieces["branch"] = abbrev_ref_out.strip()
@@ -264,11 +290,10 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
if "-" in git_describe:
# TAG-NUM-gHEX
mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe)
if not mo:
# unparseable. Maybe git-describe is misbehaving?
pieces["error"] = ("unable to parse git-describe output: '%s'"
% describe_out)
pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out
return pieces
# tag
@@ -277,10 +302,12 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
if verbose:
fmt = "tag '%s' doesn't start with prefix '%s'"
print(fmt % (full_tag, tag_prefix))
pieces["error"] = ("tag '%s' doesn't start with prefix '%s'"
% (full_tag, tag_prefix))
pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % (
full_tag,
tag_prefix,
)
return pieces
pieces["closest-tag"] = full_tag[len(tag_prefix):]
pieces["closest-tag"] = full_tag[len(tag_prefix) :]
# distance: number of commits since tag
pieces["distance"] = int(mo.group(2))
@@ -291,8 +318,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
else:
# HEX: no tags
pieces["closest-tag"] = None
count_out = run_command(GITS, ["rev-list", "HEAD", "--count"],
cwd=root)
count_out = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root)
pieces["distance"] = int(count_out) # total number of commits
return pieces
@@ -309,11 +335,12 @@ def git_parse_lookup_file(path):
return []
import re
lookup = []
with io.open(path, "rt", encoding="utf-8") as f:
for line in f:
if '#' in line:
line = line[:line.index("#")]
if "#" in line:
line = line[: line.index("#")]
line = line.strip()
if not line:
continue
@@ -353,8 +380,7 @@ def git_pieces_from_lookup(lookup, root, verbose, run_command=run_command):
if sys.platform == "win32":
GITS = ["git.cmd", "git.exe"]
stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"],
cwd=root)
stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root)
if stdout is None:
raise NotThisMethod("git rev-parse --abbrev-ref HEAD failed")
@@ -365,37 +391,33 @@ def git_pieces_from_lookup(lookup, root, verbose, run_command=run_command):
for matcher, render, tag, ref_commit in lookup:
if matcher.match(current_branch):
if tag is None or ref_commit is None:
raise NotThisMethod("tag or ref_commit is unset for "
"this branch")
raise NotThisMethod("tag or ref_commit is unset for " "this branch")
stdout = run_command(GITS,
["rev-list", "%s..HEAD" % ref_commit,
"--count"],
cwd=root)
stdout = run_command(
GITS, ["rev-list", "%s..HEAD" % ref_commit, "--count"], cwd=root
)
if stdout is None:
raise NotThisMethod("git rev-list %s..HEAD "
"--count failed" % ref_commit)
raise NotThisMethod(
"git rev-list %s..HEAD " "--count failed" % ref_commit
)
try:
num_commits = int(stdout.strip())
except ValueError:
raise NotThisMethod("git rev-list %s..HEAD --count didn't "
"return a valid number" % ref_commit)
raise NotThisMethod(
"git rev-list %s..HEAD --count didn't "
"return a valid number" % ref_commit
)
stdout = run_command(GITS,
["rev-parse", "--short", "HEAD"],
cwd=root)
stdout = run_command(GITS, ["rev-parse", "--short", "HEAD"], cwd=root)
if stdout is None:
raise NotThisMethod("git describe rev-parse "
"--short HEAD failed")
raise NotThisMethod("git describe rev-parse " "--short HEAD failed")
short_hash = stdout.strip()
stdout = run_command(GITS,
["describe", "--tags",
"--dirty", "--always"],
cwd=root)
stdout = run_command(
GITS, ["describe", "--tags", "--dirty", "--always"], cwd=root
)
if stdout is None:
raise NotThisMethod("git describe --tags --dirty "
"--always failed")
raise NotThisMethod("git describe --tags --dirty " "--always failed")
dirty = stdout.strip().endswith("-dirty")
stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
@@ -411,7 +433,7 @@ def git_pieces_from_lookup(lookup, root, verbose, run_command=run_command):
"closest-tag": tag,
"distance": num_commits,
"error": None,
"render": render
"render": render,
}
raise NotThisMethod("no matching lookup definition found")
@@ -442,8 +464,7 @@ def render_pep440(pieces):
rendered += ".dirty"
else:
# exception #1
rendered = "0+untagged.%d.g%s" % (pieces["distance"],
pieces["short"])
rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"])
if pieces["dirty"]:
rendered += ".dirty"
return rendered
@@ -603,10 +624,12 @@ def render_git_describe_long(pieces):
def render(pieces, style):
"""Render the given version pieces into the requested style."""
if pieces["error"]:
return {"version": "unknown",
"full-revisionid": pieces.get("long"),
"dirty": None,
"error": pieces["error"]}
return {
"version": "unknown",
"full-revisionid": pieces.get("long"),
"dirty": None,
"error": pieces["error"],
}
if "render" in pieces and pieces["render"] is not None:
style = pieces["render"]
@@ -633,8 +656,12 @@ def render(pieces, style):
else:
raise ValueError("unknown style '%s'" % style)
result = {"version": rendered, "full-revisionid": pieces["long"],
"dirty": pieces["dirty"], "error": None}
result = {
"version": rendered,
"full-revisionid": pieces["long"],
"dirty": pieces["dirty"],
"error": None,
}
if "branch" in pieces and pieces["branch"] is not None:
result["branch"] = pieces["branch"]
return result
@@ -651,8 +678,7 @@ def get_versions():
verbose = cfg.verbose
try:
return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,
verbose)
return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose)
except NotThisMethod:
pass
@@ -661,14 +687,17 @@ def get_versions():
# versionfile_source is the relative path from the top of the source
# tree (where the .git directory might live) to this file. Invert
# this to find the root from __file__.
for i in cfg.versionfile_source.split('/'):
for i in cfg.versionfile_source.split("/"):
root = os.path.dirname(root)
except NameError:
return {"version": "0+unknown", "full-revisionid": None,
"dirty": None,
"error": "unable to find root of source tree"}
return {
"version": "0+unknown",
"full-revisionid": None,
"dirty": None,
"error": "unable to find root of source tree",
}
lookupfile = cfg.lookupfile if cfg.lookupfile is not None else ".versioneer-lookup"
lookupfile = cfg.lookupfile if cfg.lookupfile is not None else ".versioneer-lookup"
lookuppath = os.path.join(root, lookupfile)
if os.path.exists(lookuppath):
try:
@@ -690,6 +719,9 @@ def get_versions():
except NotThisMethod:
pass
return {"version": "0+unknown", "full-revisionid": None,
"dirty": None,
"error": "unable to compute version"}
return {
"version": "0+unknown",
"full-revisionid": None,
"dirty": None,
"error": "unable to compute version",
}
File diff suppressed because it is too large. Load diff
+366 -293
View File
@@ -2,389 +2,462 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Marc Hannappel <salandora@gmail.com>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
from future.utils import with_metaclass
from flask import g, abort
from flask_babel import gettext
from octoprint.vendor.flask_principal import Permission, PermissionDenied, RoleNeed, Need
from functools import wraps
from collections import OrderedDict, defaultdict
from functools import wraps
from flask import abort, g
from flask_babel import gettext
from future.utils import with_metaclass
# noinspection PyCompatibility
from past.builtins import basestring
from octoprint.access import ADMIN_GROUP, USER_GROUP, READONLY_GROUP
from octoprint.access import ADMIN_GROUP, READONLY_GROUP, USER_GROUP
from octoprint.vendor.flask_principal import Need, Permission, PermissionDenied, RoleNeed
class OctoPrintPermission(Permission):
@classmethod
def convert_needs_to_dict(cls, needs):
ret_needs = defaultdict(list)
for need in needs:
if need.value not in ret_needs[need.method]:
ret_needs[need.method].append(need.value)
return ret_needs
@classmethod
def convert_needs_to_dict(cls, needs):
ret_needs = defaultdict(list)
for need in needs:
if need.value not in ret_needs[need.method]:
ret_needs[need.method].append(need.value)
return ret_needs
@classmethod
def convert_to_needs(cls, needs):
result = []
for need in needs:
# noinspection PyCompatibility
if isinstance(need, Need):
result.append(need)
elif isinstance(need, Permission):
result += need.needs
elif isinstance(need, basestring):
result.append(RoleNeed(need))
return result
@classmethod
def convert_to_needs(cls, needs):
result = []
for need in needs:
# noinspection PyCompatibility
if isinstance(need, Need):
result.append(need)
elif isinstance(need, Permission):
result += need.needs
elif isinstance(need, basestring):
result.append(RoleNeed(need))
return result
def __init__(self, name, description, *needs, **kwargs):
self._name = name
self._description = description
self._dangerous = kwargs.pop("dangerous", False)
self._default_groups = kwargs.pop("default_groups", [])
def __init__(self, name, description, *needs, **kwargs):
self._name = name
self._description = description
self._dangerous = kwargs.pop("dangerous", False)
self._default_groups = kwargs.pop("default_groups", [])
self._key = None
self._key = None
Permission.__init__(self, *self.convert_to_needs(needs))
Permission.__init__(self, *self.convert_to_needs(needs))
def as_dict(self):
return {"key": self.key,
"name": self.get_name(),
"dangerous": self._dangerous,
"default_groups": self._default_groups,
"description": self.get_description(),
"needs": self.convert_needs_to_dict(self.needs)}
def as_dict(self):
return {
"key": self.key,
"name": self.get_name(),
"dangerous": self._dangerous,
"default_groups": self._default_groups,
"description": self.get_description(),
"needs": self.convert_needs_to_dict(self.needs),
}
@property
def key(self):
return self._key
@property
def key(self):
return self._key
@key.setter
def key(self, value):
self._key = value
@key.setter
def key(self, value):
self._key = value
@property
def default_groups(self):
return self._default_groups
@property
def default_groups(self):
return self._default_groups
def get_name(self):
return self._name
def get_name(self):
return self._name
def get_description(self):
return self._description
def get_description(self):
return self._description
def allows(self, identity):
"""Whether the identity can access this permission.
Overridden from Permission.allows to make sure the Identity provides ALL
required needs instead of ANY required need.
def allows(self, identity):
"""Whether the identity can access this permission.
Overridden from Permission.allows to make sure the Identity provides ALL
required needs instead of ANY required need.
:param identity: The identity
"""
if self.needs and len(self.needs.intersection(identity.provides)) != len(self.needs):
return False
:param identity: The identity
"""
if self.needs and len(self.needs.intersection(identity.provides)) != len(
self.needs
):
return False
if self.excludes and self.excludes.intersection(identity.provides):
return False
if self.excludes and self.excludes.intersection(identity.provides):
return False
return True
return True
def union(self, other):
"""Create a new OctoPrintPermission with the requirements of the union of this
and other.
def union(self, other):
"""Create a new OctoPrintPermission with the requirements of the union of this
and other.
:param other: The other permission
"""
p = self.__class__(self._name, self._description, *self.needs.union(other.needs))
p.excludes.update(self.excludes.union(other.excludes))
return p
:param other: The other permission
"""
p = self.__class__(self._name, self._description, *self.needs.union(other.needs))
p.excludes.update(self.excludes.union(other.excludes))
return p
def difference(self, other):
"""Create a new OctoPrintPermission consisting of requirements in this
permission and not in the other.
"""
def difference(self, other):
"""Create a new OctoPrintPermission consisting of requirements in this
permission and not in the other.
"""
p = self.__class__(
self._name, self._description, *self.needs.difference(other.needs)
)
p.excludes.update(self.excludes.difference(other.excludes))
return p
p = self.__class__(self._name, self._description, *self.needs.difference(other.needs))
p.excludes.update(self.excludes.difference(other.excludes))
return p
def __repr__(self):
return "{}({!r}, {!r}, {})".format(
self.__class__.__name__,
self.get_name(),
self.get_description(),
", ".join(map(repr, self.needs)),
)
def __repr__(self):
return '{}({!r}, {!r}, {})'.format(self.__class__.__name__,
self.get_name(),
self.get_description(),
', '.join(map(repr, self.needs)))
def __hash__(self):
return self.get_name().__hash__()
def __hash__(self):
return self.get_name().__hash__()
def __eq__(self, other):
return isinstance(other, OctoPrintPermission) and other.get_name() == self.get_name()
def __eq__(self, other):
return (
isinstance(other, OctoPrintPermission) and other.get_name() == self.get_name()
)
class PluginOctoPrintPermission(OctoPrintPermission):
def __init__(self, *args, **kwargs):
self.plugin = kwargs.pop("plugin", None)
OctoPrintPermission.__init__(self, *args, **kwargs)
def __init__(self, *args, **kwargs):
self.plugin = kwargs.pop("plugin", None)
OctoPrintPermission.__init__(self, *args, **kwargs)
def as_dict(self):
result = OctoPrintPermission.as_dict(self)
result["plugin"] = self.plugin
return result
def as_dict(self):
result = OctoPrintPermission.as_dict(self)
result["plugin"] = self.plugin
return result
class PluginIdentityContext(object):
"""Identity context for not initialized Permissions
"""Identity context for not initialized Permissions
Needed to support @Permissions.PLUGIN_X_Y.require()
Needed to support @Permissions.PLUGIN_X_Y.require()
Will search the permission when needed
"""
def __init__(self, key, http_exception=None):
self.key = key
self.http_exception = http_exception
"""The permission of this principal
"""
Will search the permission when needed
"""
@property
def identity(self):
"""The identity of this principal
"""
return g.identity
def __init__(self, key, http_exception=None):
self.key = key
self.http_exception = http_exception
"""The permission of this principal
"""
def can(self):
"""Whether the identity has access to the permission
"""
permission = getattr(Permissions, self.key)
if permission is None or isinstance(permission, PluginPermissionDecorator):
raise UnknownPermission(self.key)
@property
def identity(self):
"""The identity of this principal"""
return g.identity
return permission.can()
def can(self):
"""Whether the identity has access to the permission"""
permission = getattr(Permissions, self.key)
if permission is None or isinstance(permission, PluginPermissionDecorator):
raise UnknownPermission(self.key)
def __call__(self, f):
@wraps(f)
def _decorated(*args, **kw):
with self:
rv = f(*args, **kw)
return rv
return permission.can()
return _decorated
def __call__(self, f):
@wraps(f)
def _decorated(*args, **kw):
with self:
rv = f(*args, **kw)
return rv
def __enter__(self):
permission = getattr(Permissions, self.key)
if permission is None or isinstance(permission, PluginPermissionDecorator):
raise UnknownPermission(self.key)
return _decorated
# check the permission here
if not permission.can():
if self.http_exception:
abort(self.http_exception, permission)
raise PermissionDenied(permission)
def __enter__(self):
permission = getattr(Permissions, self.key)
if permission is None or isinstance(permission, PluginPermissionDecorator):
raise UnknownPermission(self.key)
def __exit__(self, *args):
return False
# check the permission here
if not permission.can():
if self.http_exception:
abort(self.http_exception, permission)
raise PermissionDenied(permission)
def __exit__(self, *args):
return False
class PluginPermissionDecorator(Permission):
"""Decorator Class for not initialized Permissions
"""Decorator Class for not initialized Permissions
Needed to support @Permissions.PLUGIN_X_Y.require()
"""
def __init__(self, key):
self.key = key
Needed to support @Permissions.PLUGIN_X_Y.require()
"""
def require(self, http_exception=None):
return PluginIdentityContext(self.key, http_exception)
def __init__(self, key):
self.key = key
def require(self, http_exception=None):
return PluginIdentityContext(self.key, http_exception)
class PermissionsMetaClass(type):
permissions = OrderedDict()
permissions = OrderedDict()
def __new__(mcs, name, bases, args):
cls = type.__new__(mcs, name, bases, args)
def __new__(mcs, name, bases, args):
cls = type.__new__(mcs, name, bases, args)
for key, value in args.items():
if isinstance(value, OctoPrintPermission):
value.key = key
mcs.permissions[key] = value
delattr(cls, key)
for key, value in args.items():
if isinstance(value, OctoPrintPermission):
value.key = key
mcs.permissions[key] = value
delattr(cls, key)
return cls
return cls
def __setattr__(cls, key, value):
if isinstance(value, OctoPrintPermission):
if key in cls.permissions:
raise PermissionAlreadyExists(key)
value.key = key
cls.permissions[key] = value
def __setattr__(cls, key, value):
if isinstance(value, OctoPrintPermission):
if key in cls.permissions:
raise PermissionAlreadyExists(key)
value.key = key
cls.permissions[key] = value
def __getattr__(cls, key):
permission = cls.permissions.get(key)
def __getattr__(cls, key):
permission = cls.permissions.get(key)
if key.startswith("PLUGIN_") and permission is None:
return PluginPermissionDecorator(key)
if key.startswith("PLUGIN_") and permission is None:
return PluginPermissionDecorator(key)
return permission
return permission
def all(cls):
return list(cls.permissions.values())
def all(cls):
return list(cls.permissions.values())
def filter(cls, cb):
return list(filter(cb, cls.all()))
def filter(cls, cb):
return list(filter(cb, cls.all()))
def find(cls, p, filter=None):
key = None
if isinstance(p, OctoPrintPermission):
key = p.key
elif isinstance(p, dict):
key = p.get("key")
elif isinstance(p, basestring):
key = p
def find(cls, p, filter=None):
key = None
if isinstance(p, OctoPrintPermission):
key = p.key
elif isinstance(p, dict):
key = p.get("key")
elif isinstance(p, basestring):
key = p
if key is None:
return None
if key is None:
return None
return cls.match(lambda p: p.key == key, filter=filter)
return cls.match(lambda p: p.key == key, filter=filter)
def match(cls, match, filter=None):
if callable(filter):
permissions = cls.filter(filter)
else:
permissions = cls.all()
def match(cls, match, filter=None):
if callable(filter):
permissions = cls.filter(filter)
else:
permissions = cls.all()
for permission in permissions:
if match(permission):
return permission
for permission in permissions:
if match(permission):
return permission
return None
return None
class Permissions(with_metaclass(PermissionsMetaClass)):
# Special permission
ADMIN = OctoPrintPermission("Admin",
gettext("Admin is allowed to do everything"),
RoleNeed("admin"),
dangerous=True,
default_groups=[ADMIN_GROUP])
# Special permission
ADMIN = OctoPrintPermission(
"Admin",
gettext("Admin is allowed to do everything"),
RoleNeed("admin"),
dangerous=True,
default_groups=[ADMIN_GROUP],
)
STATUS = OctoPrintPermission("Status",
gettext("Allows to gather basic status information, e.g. job progress, "
"printer state, temperatures, ... Mandatory for the default UI "
"to work"),
RoleNeed("status"),
default_groups=[USER_GROUP, READONLY_GROUP])
STATUS = OctoPrintPermission(
"Status",
gettext(
"Allows to gather basic status information, e.g. job progress, "
"printer state, temperatures, ... Mandatory for the default UI "
"to work"
),
RoleNeed("status"),
default_groups=[USER_GROUP, READONLY_GROUP],
)
CONNECTION = OctoPrintPermission("Connection",
gettext("Allows to connect to and disconnect from a printer"),
RoleNeed("connection"),
default_groups=[USER_GROUP])
CONNECTION = OctoPrintPermission(
"Connection",
gettext("Allows to connect to and disconnect from a printer"),
RoleNeed("connection"),
default_groups=[USER_GROUP],
)
WEBCAM = OctoPrintPermission("Webcam",
gettext("Allows to watch the webcam stream"),
RoleNeed("webcam"),
default_groups=[USER_GROUP, READONLY_GROUP])
WEBCAM = OctoPrintPermission(
"Webcam",
gettext("Allows to watch the webcam stream"),
RoleNeed("webcam"),
default_groups=[USER_GROUP, READONLY_GROUP],
)
SYSTEM = OctoPrintPermission("System",
gettext("Allows to run system commands, e.g. restart OctoPrint, "
"shutdown or reboot the system"),
RoleNeed("system"),
dangerous=True)
SYSTEM = OctoPrintPermission(
"System",
gettext(
"Allows to run system commands, e.g. restart OctoPrint, "
"shutdown or reboot the system"
),
RoleNeed("system"),
dangerous=True,
)
FILES_LIST = OctoPrintPermission("File List",
gettext("Allows to retrieve a list of all uploaded files and folders, including"
"their metadata (e.g. date, file size, analysis results, ...)"),
RoleNeed("files_list"),
default_groups=[USER_GROUP, READONLY_GROUP])
FILES_UPLOAD = OctoPrintPermission("File Upload",
gettext("Allows users to upload new files, create new folders and copy existing ones. If "
"the File Delete permission is also set, File Upload also allows "
"moving files and folders."),
RoleNeed("files_upload"),
default_groups=[USER_GROUP])
FILES_DOWNLOAD = OctoPrintPermission("File Download",
gettext("Allows users to download files. The GCODE viewer is "
"affected by this as well."),
RoleNeed("files_download"),
default_groups=[USER_GROUP, READONLY_GROUP])
FILES_DELETE = OctoPrintPermission("File Delete",
gettext("Allows users to delete files and folders. If the File Upload permission is "
"also set, File Delete also allows moving files and folders."),
RoleNeed("files_delete"),
default_groups=[USER_GROUP])
FILES_SELECT = OctoPrintPermission("File Select",
gettext("Allows to select a file for printing"),
RoleNeed("files_select"),
default_groups=[USER_GROUP])
FILES_LIST = OctoPrintPermission(
"File List",
gettext(
"Allows to retrieve a list of all uploaded files and folders, including"
"their metadata (e.g. date, file size, analysis results, ...)"
),
RoleNeed("files_list"),
default_groups=[USER_GROUP, READONLY_GROUP],
)
FILES_UPLOAD = OctoPrintPermission(
"File Upload",
gettext(
"Allows users to upload new files, create new folders and copy existing ones. If "
"the File Delete permission is also set, File Upload also allows "
"moving files and folders."
),
RoleNeed("files_upload"),
default_groups=[USER_GROUP],
)
FILES_DOWNLOAD = OctoPrintPermission(
"File Download",
gettext(
"Allows users to download files. The GCODE viewer is "
"affected by this as well."
),
RoleNeed("files_download"),
default_groups=[USER_GROUP, READONLY_GROUP],
)
FILES_DELETE = OctoPrintPermission(
"File Delete",
gettext(
"Allows users to delete files and folders. If the File Upload permission is "
"also set, File Delete also allows moving files and folders."
),
RoleNeed("files_delete"),
default_groups=[USER_GROUP],
)
FILES_SELECT = OctoPrintPermission(
"File Select",
gettext("Allows to select a file for printing"),
RoleNeed("files_select"),
default_groups=[USER_GROUP],
)
PRINT = OctoPrintPermission("Print",
gettext("Allows to start, pause and cancel a print job"),
RoleNeed("print"),
default_groups=[USER_GROUP])
PRINT = OctoPrintPermission(
"Print",
gettext("Allows to start, pause and cancel a print job"),
RoleNeed("print"),
default_groups=[USER_GROUP],
)
GCODE_VIEWER = OctoPrintPermission("GCODE viewer",
gettext("Allows access to the GCODE viewer if the \"File Download\""
"permission is also set."),
RoleNeed("gcodeviewer"),
default_groups=[USER_GROUP, READONLY_GROUP])
GCODE_VIEWER = OctoPrintPermission(
"GCODE viewer",
gettext(
'Allows access to the GCODE viewer if the "File Download"'
"permission is also set."
),
RoleNeed("gcodeviewer"),
default_groups=[USER_GROUP, READONLY_GROUP],
)
MONITOR_TERMINAL = OctoPrintPermission("Terminal",
gettext("Allows to watch the terminal tab but not to send commands "
"to the printer from it"),
RoleNeed("monitor_terminal"),
default_groups=[USER_GROUP, READONLY_GROUP])
MONITOR_TERMINAL = OctoPrintPermission(
"Terminal",
gettext(
"Allows to watch the terminal tab but not to send commands "
"to the printer from it"
),
RoleNeed("monitor_terminal"),
default_groups=[USER_GROUP, READONLY_GROUP],
)
CONTROL = OctoPrintPermission("Control",
gettext("Allows to control of the printer by using the temperature controls,"
"the control tab or sending commands through the terminal."),
RoleNeed("control"),
default_groups=[USER_GROUP])
CONTROL = OctoPrintPermission(
"Control",
gettext(
"Allows to control of the printer by using the temperature controls,"
"the control tab or sending commands through the terminal."
),
RoleNeed("control"),
default_groups=[USER_GROUP],
)
SLICE = OctoPrintPermission("Slice",
gettext("Allows to slice files"),
RoleNeed("slice"),
default_groups=[USER_GROUP])
SLICE = OctoPrintPermission(
"Slice",
gettext("Allows to slice files"),
RoleNeed("slice"),
default_groups=[USER_GROUP],
)
TIMELAPSE_LIST = OctoPrintPermission("Timelapse List",
gettext("Allows to list timelapse videos"),
RoleNeed("timelapse_list"),
default_groups=[USER_GROUP, READONLY_GROUP])
TIMELAPSE_DOWNLOAD = OctoPrintPermission("Timelapse Download",
gettext("Allows to download timelapse videos"),
RoleNeed("timelapse_download"),
default_groups=[USER_GROUP, READONLY_GROUP])
TIMELAPSE_DELETE = OctoPrintPermission("Timelapse Delete",
gettext("Allows to delete timelapse videos and unrendered timelapses"),
RoleNeed("timelapse_delete"),
default_groups=[USER_GROUP])
TIMELAPSE_ADMIN = OctoPrintPermission("Timelapse Admin",
gettext("Allows to change the timelapse settings and delete or "
"render unrendered timelapses. Includes the \"Timelapse List\","
"\"Timelapse Delete\" and \"Timelapse Download\" permissions"),
RoleNeed("timelapse_admin"), TIMELAPSE_LIST, TIMELAPSE_DOWNLOAD,
default_groups=[USER_GROUP])
SETTINGS_READ = OctoPrintPermission("Settings Access",
gettext("Allows to read non sensitive settings. Mandatory for the "
"default UI to work."),
RoleNeed("settings_read"),
default_groups=[USER_GROUP, READONLY_GROUP])
SETTINGS = OctoPrintPermission("Settings Admin",
gettext("Allows to manage settings and also to read sensitive settings"),
RoleNeed("settings"),
dangerous=True)
TIMELAPSE_LIST = OctoPrintPermission(
"Timelapse List",
gettext("Allows to list timelapse videos"),
RoleNeed("timelapse_list"),
default_groups=[USER_GROUP, READONLY_GROUP],
)
TIMELAPSE_DOWNLOAD = OctoPrintPermission(
"Timelapse Download",
gettext("Allows to download timelapse videos"),
RoleNeed("timelapse_download"),
default_groups=[USER_GROUP, READONLY_GROUP],
)
TIMELAPSE_DELETE = OctoPrintPermission(
"Timelapse Delete",
gettext("Allows to delete timelapse videos and unrendered timelapses"),
RoleNeed("timelapse_delete"),
default_groups=[USER_GROUP],
)
TIMELAPSE_ADMIN = OctoPrintPermission(
"Timelapse Admin",
gettext(
"Allows to change the timelapse settings and delete or "
'render unrendered timelapses. Includes the "Timelapse List",'
'"Timelapse Delete" and "Timelapse Download" permissions'
),
RoleNeed("timelapse_admin"),
TIMELAPSE_LIST,
TIMELAPSE_DOWNLOAD,
default_groups=[USER_GROUP],
)
SETTINGS_READ = OctoPrintPermission(
"Settings Access",
gettext(
"Allows to read non sensitive settings. Mandatory for the "
"default UI to work."
),
RoleNeed("settings_read"),
default_groups=[USER_GROUP, READONLY_GROUP],
)
SETTINGS = OctoPrintPermission(
"Settings Admin",
gettext("Allows to manage settings and also to read sensitive settings"),
RoleNeed("settings"),
dangerous=True,
)
class PermissionAlreadyExists(Exception):
def __init__(self, permission):
Exception.__init__(self, "Permission %s already exists" % permission)
def __init__(self, permission):
Exception.__init__(self, "Permission %s already exists" % permission)
class UnknownPermission(Exception):
def __init__(self, permissionname):
Exception.__init__(self, "Unknown permission: %s" % permissionname)
def __init__(self, permissionname):
Exception.__init__(self, "Unknown permission: %s" % permissionname)
+1300 -1130
View File
File diff suppressed because it is too large. Load diff
+211 -120
View File
@@ -1,177 +1,268 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
click.disable_unicode_literals_warning = True
import octoprint
import sys
#~~ click context
import click
import octoprint
click.disable_unicode_literals_warning = True
# ~~ click context
class OctoPrintContext(object):
"""Custom context wrapping the standard options."""
"""Custom context wrapping the standard options."""
def __init__(self, configfile=None, basedir=None, verbosity=0, safe_mode=False):
self.configfile = configfile
self.basedir = basedir
self.verbosity = verbosity
self.safe_mode = safe_mode
def __init__(self, configfile=None, basedir=None, verbosity=0, safe_mode=False):
self.configfile = configfile
self.basedir = basedir
self.verbosity = verbosity
self.safe_mode = safe_mode
pass_octoprint_ctx = click.make_pass_decorator(OctoPrintContext, ensure=True)
"""Decorator to pass in the :class:`OctoPrintContext` instance."""
#~~ Custom click option to hide from help
# ~~ Custom click option to hide from help
class HiddenOption(click.Option):
"""Custom option sub class with empty help."""
def get_help_record(self, ctx):
pass
"""Custom option sub class with empty help."""
def get_help_record(self, ctx):
pass
def hidden_option(*param_decls, **attrs):
"""Attaches a hidden option to the command. All positional arguments are
passed as parameter declarations to :class:`Option`; all keyword
arguments are forwarded unchanged. This is equivalent to creating an
:class:`Option` instance manually and attaching it to the
:attr:`Command.params` list.
"""
"""Attaches a hidden option to the command. All positional arguments are
passed as parameter declarations to :class:`Option`; all keyword
arguments are forwarded unchanged. This is equivalent to creating an
:class:`Option` instance manually and attaching it to the
:attr:`Command.params` list.
"""
import inspect
from click.decorators import _param_memo
import inspect
def decorator(f):
if 'help' in attrs:
attrs['help'] = inspect.cleandoc(attrs['help'])
_param_memo(f, HiddenOption(param_decls, **attrs))
return f
return decorator
from click.decorators import _param_memo
def decorator(f):
if "help" in attrs:
attrs["help"] = inspect.cleandoc(attrs["help"])
_param_memo(f, HiddenOption(param_decls, **attrs))
return f
return decorator
# ~~ helper for setting context options
#~~ helper for setting context options
def set_ctx_obj_option(ctx, param, value):
"""Helper for setting eager options on the context."""
if ctx.obj is None:
ctx.obj = OctoPrintContext()
if value != param.default:
setattr(ctx.obj, param.name, value)
elif param.default is not None:
setattr(ctx.obj, param.name, param.default)
"""Helper for setting eager options on the context."""
if ctx.obj is None:
ctx.obj = OctoPrintContext()
if value != param.default:
setattr(ctx.obj, param.name, value)
elif param.default is not None:
setattr(ctx.obj, param.name, param.default)
# ~~ helper for retrieving context options
#~~ helper for retrieving context options
def get_ctx_obj_option(ctx, key, default, include_parents=True):
if include_parents and hasattr(ctx, "parent") and ctx.parent:
fallback = get_ctx_obj_option(ctx.parent, key, default)
else:
fallback = default
return getattr(ctx.obj, key, fallback)
if include_parents and hasattr(ctx, "parent") and ctx.parent:
fallback = get_ctx_obj_option(ctx.parent, key, default)
else:
fallback = default
return getattr(ctx.obj, key, fallback)
# ~~ helper for setting a lot of bulk options
#~~ helper for setting a lot of bulk options
def bulk_options(options):
"""
Utility decorator to decorate a function with a list of click decorators.
"""
Utility decorator to decorate a function with a list of click decorators.
The provided list of ``options`` will be reversed to ensure correct
processing order (inverse from what would be intuitive).
"""
The provided list of ``options`` will be reversed to ensure correct
processing order (inverse from what would be intuitive).
"""
def decorator(f):
options.reverse()
for option in options:
option(f)
return f
return decorator
def decorator(f):
options.reverse()
for option in options:
option(f)
return f
return decorator
# ~~ helper for setting --basedir, --config and --verbose options
#~~ helper for setting --basedir, --config and --verbose options
def standard_options(hidden=False):
"""
Decorator to add the standard options shared among all "octoprint" commands.
"""
Decorator to add the standard options shared among all "octoprint" commands.
Adds the options ``--basedir``, ``--config`` and ``--verbose``. If ``hidden``
is set to ``True``, the options will be available on the command but not
listed in its help page.
"""
Adds the options ``--basedir``, ``--config`` and ``--verbose``. If ``hidden``
is set to ``True``, the options will be available on the command but not
listed in its help page.
"""
factory = click.option
if hidden:
factory = hidden_option
factory = click.option
if hidden:
factory = hidden_option
options = [
factory("--basedir", "-b", type=click.Path(), callback=set_ctx_obj_option, is_eager=True, expose_value=False,
help="Specify the basedir to use for configs, uploads, timelapses etc."),
factory("--config", "-c", "configfile", type=click.Path(), callback=set_ctx_obj_option, is_eager=True, expose_value=False,
help="Specify the config file to use."),
factory("--verbose", "-v", "verbosity", count=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False,
help="Increase logging verbosity."),
factory("--safe", "safe_mode", is_flag=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False,
help="Enable safe mode; disables all third party plugins.")
]
options = [
factory(
"--basedir",
"-b",
type=click.Path(),
callback=set_ctx_obj_option,
is_eager=True,
expose_value=False,
help="Specify the basedir to use for configs, uploads, timelapses etc.",
),
factory(
"--config",
"-c",
"configfile",
type=click.Path(),
callback=set_ctx_obj_option,
is_eager=True,
expose_value=False,
help="Specify the config file to use.",
),
factory(
"--verbose",
"-v",
"verbosity",
count=True,
callback=set_ctx_obj_option,
is_eager=True,
expose_value=False,
help="Increase logging verbosity.",
),
factory(
"--safe",
"safe_mode",
is_flag=True,
callback=set_ctx_obj_option,
is_eager=True,
expose_value=False,
help="Enable safe mode; disables all third party plugins.",
),
]
return bulk_options(options)
return bulk_options(options)
#~~ helper for settings legacy options we still have to support on "octoprint"
legacy_options = bulk_options([
hidden_option("--host", type=click.STRING, callback=set_ctx_obj_option),
hidden_option("--port", type=click.INT, callback=set_ctx_obj_option),
hidden_option("--logging", type=click.Path(), callback=set_ctx_obj_option),
hidden_option("--debug", "-d", is_flag=True, callback=set_ctx_obj_option),
hidden_option("--daemon", type=click.Choice(["start", "stop", "restart"]), callback=set_ctx_obj_option),
hidden_option("--pid", type=click.Path(), default="/tmp/octoprint.pid", callback=set_ctx_obj_option),
hidden_option("--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option),
hidden_option("--ignore-blacklist", "ignore_blacklist", is_flag=True, callback=set_ctx_obj_option)
])
# ~~ helper for settings legacy options we still have to support on "octoprint"
legacy_options = bulk_options(
[
hidden_option("--host", type=click.STRING, callback=set_ctx_obj_option),
hidden_option("--port", type=click.INT, callback=set_ctx_obj_option),
hidden_option("--logging", type=click.Path(), callback=set_ctx_obj_option),
hidden_option("--debug", "-d", is_flag=True, callback=set_ctx_obj_option),
hidden_option(
"--daemon",
type=click.Choice(["start", "stop", "restart"]),
callback=set_ctx_obj_option,
),
hidden_option(
"--pid",
type=click.Path(),
default="/tmp/octoprint.pid",
callback=set_ctx_obj_option,
),
hidden_option(
"--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option
),
hidden_option(
"--ignore-blacklist",
"ignore_blacklist",
is_flag=True,
callback=set_ctx_obj_option,
),
]
)
"""Legacy options available directly on the "octoprint" command in earlier versions.
Kept available for reasons of backwards compatibility, but hidden from the
generated help pages."""
#~~ "octoprint" command, merges server_commands and plugin_commands groups
# ~~ "octoprint" command, merges server_commands and plugin_commands groups
from .server import server_commands
from .plugins import plugin_commands
from .dev import dev_commands
from .client import client_commands
from .config import config_commands
from .analysis import analysis_commands
from .user import user_commands
from .analysis import analysis_commands # noqa: E402
from .client import client_commands # noqa: E402
from .config import config_commands # noqa: E402
from .dev import dev_commands # noqa: E402
from .plugins import plugin_commands # noqa: E402
from .server import server_commands # noqa: E402
from .user import user_commands # noqa: E402
@click.group(name="octoprint", invoke_without_command=True, cls=click.CommandCollection,
sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands, analysis_commands, user_commands])
@click.group(
name="octoprint",
invoke_without_command=True,
cls=click.CommandCollection,
sources=[
server_commands,
plugin_commands,
dev_commands,
client_commands,
config_commands,
analysis_commands,
user_commands,
],
)
@standard_options()
@legacy_options
@click.version_option(version=octoprint.__version__, allow_from_autoenv=False)
@click.pass_context
def octo(ctx, **kwargs):
if ctx.invoked_subcommand is None:
# We have to support calling the octoprint command without any
# sub commands to remain backwards compatible.
#
# But better print a message to inform people that they should
# use the sub commands instead.
if ctx.invoked_subcommand is None:
# We have to support calling the octoprint command without any
# sub commands to remain backwards compatible.
#
# But better print a message to inform people that they should
# use the sub commands instead.
def get_value(key):
return get_ctx_obj_option(ctx, key, kwargs.get(key))
daemon = get_value("daemon")
def get_value(key):
return get_ctx_obj_option(ctx, key, kwargs.get(key))
if daemon:
click.echo("Daemon operation via \"octoprint --daemon "
"start|stop|restart\" is deprecated, please use "
"\"octoprint daemon start|stop|restart\" from now on")
daemon = get_value("daemon")
if sys.platform == "win32" or sys.platform == "darwin":
click.echo("Sorry, daemon mode is not supported under your operating system right now")
else:
from octoprint.cli.server import daemon_command
ctx.invoke(daemon_command, command=daemon, **kwargs)
else:
click.echo("Starting the server via \"octoprint\" is deprecated, "
"please use \"octoprint serve\" from now on.")
if daemon:
click.echo(
'Daemon operation via "octoprint --daemon '
'start|stop|restart" is deprecated, please use '
'"octoprint daemon start|stop|restart" from now on'
)
from octoprint.cli.server import serve_command
ctx.invoke(serve_command, **kwargs)
if sys.platform == "win32" or sys.platform == "darwin":
click.echo(
"Sorry, daemon mode is not supported under your operating system right now"
)
else:
from octoprint.cli.server import daemon_command
ctx.invoke(daemon_command, command=daemon, **kwargs)
else:
click.echo(
'Starting the server via "octoprint" is deprecated, '
'please use "octoprint serve" from now on.'
)
from octoprint.cli.server import serve_command
ctx.invoke(serve_command, **kwargs)
+71 -42
View File
@@ -1,22 +1,25 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
click.disable_unicode_literals_warning = True
#~~ "octoprint util" commands
# ~~ "octoprint util" commands
@click.group()
def analysis_commands():
pass
pass
@analysis_commands.group(name="analysis")
def util():
"""Analysis tools."""
pass
"""Analysis tools."""
pass
@util.command(name="gcode")
@@ -30,49 +33,75 @@ def util():
@click.option("--g90-extruder", "g90_extruder", is_flag=True)
@click.option("--progress", "progress", is_flag=True)
@click.argument("path", type=click.Path())
def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle_lines, g90_extruder, progress):
"""Runs a GCODE file analysis."""
def gcode_command(
path,
speedx,
speedy,
speedz,
offset,
maxt,
throttle,
throttle_lines,
g90_extruder,
progress,
):
"""Runs a GCODE file analysis."""
import time
import yaml
from octoprint.util import monotonic_time
from octoprint.util.gcodeInterpreter import gcode
import time
throttle_callback = None
if throttle:
def throttle_callback(filePos, readBytes):
if filePos % throttle_lines == 0:
# only apply throttle every $throttle_lines lines
time.sleep(throttle)
import yaml
offsets = offset
if offsets is None:
offsets = []
elif isinstance(offset, tuple):
offsets = list(offsets)
offsets = [(0, 0)] + offsets
if len(offsets) < maxt:
offsets += [(0, 0)] * (maxt - len(offsets))
from octoprint.util import monotonic_time
from octoprint.util.gcodeInterpreter import gcode
start_time = monotonic_time()
throttle_callback = None
if throttle:
progress_callback = None
if progress:
def progress_callback(percentage):
click.echo("PROGRESS:{}".format(percentage))
interpreter = gcode(progress_callback=progress_callback)
def throttle_callback(filePos, readBytes):
if filePos % throttle_lines == 0:
# only apply throttle every $throttle_lines lines
time.sleep(throttle)
interpreter.load(path,
speedx=speedx,
speedy=speedy,
offsets=offsets,
throttle=throttle_callback,
max_extruders=maxt,
g90_extruder=g90_extruder)
offsets = offset
if offsets is None:
offsets = []
elif isinstance(offset, tuple):
offsets = list(offsets)
offsets = [(0, 0)] + offsets
if len(offsets) < maxt:
offsets += [(0, 0)] * (maxt - len(offsets))
start_time = monotonic_time()
progress_callback = None
if progress:
def progress_callback(percentage):
click.echo("PROGRESS:{}".format(percentage))
interpreter = gcode(progress_callback=progress_callback)
interpreter.load(
path,
speedx=speedx,
speedy=speedy,
offsets=offsets,
throttle=throttle_callback,
max_extruders=maxt,
g90_extruder=g90_extruder,
)
click.echo("DONE:{}s".format(monotonic_time() - start_time))
click.echo("RESULTS:")
click.echo(
yaml.safe_dump(
interpreter.get_result(),
default_flow_style=False,
indent=4,
allow_unicode=True,
)
)
click.echo("DONE:{}s".format(monotonic_time() - start_time))
click.echo("RESULTS:")
click.echo(yaml.safe_dump(interpreter.get_result(), default_flow_style=False, indent=4, allow_unicode=True))
if __name__ == "__main__":
gcode_command()
gcode_command()
+205 -140
View File
@@ -1,107 +1,125 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
click.disable_unicode_literals_warning = True
import io
import json
import octoprint_client
from octoprint.cli import get_ctx_obj_option, bulk_options
from octoprint import init_settings, FatalStartupError
import click
from past.builtins import unicode
import octoprint_client
from octoprint import FatalStartupError, init_settings
from octoprint.cli import bulk_options, get_ctx_obj_option
click.disable_unicode_literals_warning = True
class JsonStringParamType(click.ParamType):
name = "json"
name = "json"
def convert(self, value, param, ctx):
try:
return json.loads(value)
except Exception:
self.fail("%s is not a valid json string" % value, param, ctx)
def convert(self, value, param, ctx):
try:
return json.loads(value)
except Exception:
self.fail("%s is not a valid json string" % value, param, ctx)
def create_client(settings=None, apikey=None, host=None, port=None, httpuser=None, httppass=None, https=False, prefix=None):
assert(host is not None or settings is not None)
assert(port is not None or settings is not None)
assert(apikey is not None or settings is not None)
def create_client(
settings=None,
apikey=None,
host=None,
port=None,
httpuser=None,
httppass=None,
https=False,
prefix=None,
):
assert host is not None or settings is not None
assert port is not None or settings is not None
assert apikey is not None or settings is not None
if not host:
host = settings.get(["server", "host"])
host = host if host != "0.0.0.0" else "127.0.0.1"
if not port:
port = settings.getInt(["server", "port"])
if not host:
host = settings.get(["server", "host"])
host = host if host != "0.0.0.0" else "127.0.0.1"
if not port:
port = settings.getInt(["server", "port"])
if not apikey:
apikey = settings.get(["api", "key"])
if not apikey:
apikey = settings.get(["api", "key"])
baseurl = octoprint_client.build_base_url(https=https,
httpuser=httpuser,
httppass=httppass,
host=host,
port=port,
prefix=prefix)
baseurl = octoprint_client.build_base_url(
https=https,
httpuser=httpuser,
httppass=httppass,
host=host,
port=port,
prefix=prefix,
)
return octoprint_client.Client(baseurl, apikey)
return octoprint_client.Client(baseurl, apikey)
client_options = bulk_options([
click.option("--apikey", "-a", type=click.STRING),
click.option("--host", "-h", type=click.STRING),
click.option("--port", "-p", type=click.INT),
click.option("--httpuser", type=click.STRING),
click.option("--httppass", type=click.STRING),
click.option("--https", is_flag=True),
click.option("--prefix", type=click.STRING)
])
client_options = bulk_options(
[
click.option("--apikey", "-a", type=click.STRING),
click.option("--host", "-h", type=click.STRING),
click.option("--port", "-p", type=click.INT),
click.option("--httpuser", type=click.STRING),
click.option("--httppass", type=click.STRING),
click.option("--https", is_flag=True),
click.option("--prefix", type=click.STRING),
]
)
"""Common options to configure an API client."""
@click.group()
def client_commands():
pass
pass
@client_commands.group("client", context_settings={"ignore_unknown_options": True})
@client_options
@click.pass_context
def client(ctx, apikey, host, port, httpuser, httppass, https, prefix):
"""Basic API client."""
try:
settings = None
if not host or not port or not apikey:
settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
"""Basic API client."""
try:
settings = None
if not host or not port or not apikey:
settings = init_settings(
get_ctx_obj_option(ctx, "basedir", None),
get_ctx_obj_option(ctx, "configfile", None),
)
ctx.obj.client = create_client(settings=settings,
apikey=apikey,
host=host,
port=port,
httpuser=httpuser,
httppass=httppass,
https=https,
prefix=prefix)
ctx.obj.client = create_client(
settings=settings,
apikey=apikey,
host=host,
port=port,
httpuser=httpuser,
httppass=httppass,
https=https,
prefix=prefix,
)
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the client.", err=True)
ctx.exit(-1)
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the client.", err=True)
ctx.exit(-1)
def log_response(response, status_code=True, body=True, headers=False):
if status_code:
click.echo("Status Code: {}".format(response.status_code))
if headers:
for header, value in response.headers.items():
click.echo("{}: {}".format(header, value))
click.echo()
if body:
click.echo(response.text)
if status_code:
click.echo("Status Code: {}".format(response.status_code))
if headers:
for header, value in response.headers.items():
click.echo("{}: {}".format(header, value))
click.echo()
if body:
click.echo(response.text)
@client.command("get")
@@ -109,9 +127,9 @@ def log_response(response, status_code=True, body=True, headers=False):
@click.option("--timeout", type=float, default=None)
@click.pass_context
def get(ctx, path, timeout):
"""Performs a GET request against the specified server path."""
r = ctx.obj.client.get(path, timeout=timeout)
log_response(r)
"""Performs a GET request against the specified server path."""
r = ctx.obj.client.get(path, timeout=timeout)
log_response(r)
@client.command("post_json")
@@ -120,9 +138,9 @@ def get(ctx, path, timeout):
@click.option("--timeout", type=float, default=None)
@click.pass_context
def post_json(ctx, path, data, timeout):
"""POSTs JSON data to the specified server path."""
r = ctx.obj.client.post_json(path, data, timeout=timeout)
log_response(r)
"""POSTs JSON data to the specified server path."""
r = ctx.obj.client.post_json(path, data, timeout=timeout)
log_response(r)
@client.command("patch_json")
@@ -131,75 +149,118 @@ def post_json(ctx, path, data, timeout):
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
@click.pass_context
def patch_json(ctx, path, data, timeout):
"""PATCHes JSON data to the specified server path."""
r = ctx.obj.client.patch(path, data, encoding="json", timeout=timeout)
log_response(r)
"""PATCHes JSON data to the specified server path."""
r = ctx.obj.client.patch(path, data, encoding="json", timeout=timeout)
log_response(r)
@client.command("post_from_file")
@click.argument("path")
@click.argument("file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True))
@click.argument(
"file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True)
)
@click.option("--json", is_flag=True)
@click.option("--yaml", is_flag=True)
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
@click.pass_context
def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout):
"""POSTs JSON data to the specified server path, taking the data from the specified file."""
if json_flag or yaml_flag:
if json_flag:
with io.open(file_path, 'rt') as fp:
data = json.load(fp)
else:
import yaml
with io.open(file_path, 'rt') as fp:
data = yaml.safe_load(fp)
"""POSTs JSON data to the specified server path, taking the data from the specified file."""
if json_flag or yaml_flag:
if json_flag:
with io.open(file_path, "rt") as fp:
data = json.load(fp)
else:
import yaml
r = ctx.obj.client.post_json(path, data, timeout=timeout)
else:
with io.open(file_path, 'rb') as fp:
data = fp.read()
with io.open(file_path, "rt") as fp:
data = yaml.safe_load(fp)
r = ctx.obj.client.post(path, data, timeout=timeout)
r = ctx.obj.client.post_json(path, data, timeout=timeout)
else:
with io.open(file_path, "rb") as fp:
data = fp.read()
log_response(r)
r = ctx.obj.client.post(path, data, timeout=timeout)
log_response(r)
@client.command("command")
@click.argument("path")
@click.argument("command")
@click.option("--str", "-s", "str_params", multiple=True, nargs=2, type=click.Tuple([unicode, unicode]))
@click.option("--int", "-i", "int_params", multiple=True, nargs=2, type=click.Tuple([unicode, int]))
@click.option("--float", "-f", "float_params", multiple=True, nargs=2, type=click.Tuple([unicode, float]))
@click.option("--bool", "-b", "bool_params", multiple=True, nargs=2, type=click.Tuple([unicode, bool]))
@click.option(
"--str",
"-s",
"str_params",
multiple=True,
nargs=2,
type=click.Tuple([unicode, unicode]),
)
@click.option(
"--int", "-i", "int_params", multiple=True, nargs=2, type=click.Tuple([unicode, int])
)
@click.option(
"--float",
"-f",
"float_params",
multiple=True,
nargs=2,
type=click.Tuple([unicode, float]),
)
@click.option(
"--bool",
"-b",
"bool_params",
multiple=True,
nargs=2,
type=click.Tuple([unicode, bool]),
)
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
@click.pass_context
def command(ctx, path, command, str_params, int_params, float_params, bool_params, timeout):
"""Sends a JSON command to the specified server path."""
data = {}
params = str_params + int_params + float_params + bool_params
for param in params:
data[param[0]] = param[1]
r = ctx.obj.client.post_command(path, command, additional=data, timeout=timeout)
log_response(r, body=False)
def command(
ctx, path, command, str_params, int_params, float_params, bool_params, timeout
):
"""Sends a JSON command to the specified server path."""
data = {}
params = str_params + int_params + float_params + bool_params
for param in params:
data[param[0]] = param[1]
r = ctx.obj.client.post_command(path, command, additional=data, timeout=timeout)
log_response(r, body=False)
@client.command("upload")
@click.argument("path")
@click.argument("file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True))
@click.option("--parameter", "-P", "params", multiple=True, nargs=2, type=click.Tuple([unicode, unicode]))
@click.argument(
"file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True)
)
@click.option(
"--parameter",
"-P",
"params",
multiple=True,
nargs=2,
type=click.Tuple([unicode, unicode]),
)
@click.option("--file-name", type=click.STRING)
@click.option("--content-type", type=click.STRING)
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
@click.pass_context
def upload(ctx, path, file_path, params, file_name, content_type, timeout):
"""Uploads the specified file to the specified server path."""
data = {}
for param in params:
data[param[0]] = param[1]
"""Uploads the specified file to the specified server path."""
data = {}
for param in params:
data[param[0]] = param[1]
r = ctx.obj.client.upload(path, file_path,
additional=data, file_name=file_name, content_type=content_type, timeout=timeout)
log_response(r)
r = ctx.obj.client.upload(
path,
file_path,
additional=data,
file_name=file_name,
content_type=content_type,
timeout=timeout,
)
log_response(r)
@client.command("delete")
@@ -207,41 +268,45 @@ def upload(ctx, path, file_path, params, file_name, content_type, timeout):
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
@click.pass_context
def delete(ctx, path, timeout):
"""Sends a DELETE request to the specified server path."""
r = ctx.obj.client.delete(path, timeout=timeout)
log_response(r)
"""Sends a DELETE request to the specified server path."""
r = ctx.obj.client.delete(path, timeout=timeout)
log_response(r)
@client.command("listen")
@click.pass_context
def listen(ctx):
def on_connect(ws):
click.echo("--- Connected!")
def on_connect(ws):
click.echo("--- Connected!")
def on_close(ws):
click.echo("--- Connection closed!")
def on_close(ws):
click.echo("--- Connection closed!")
def on_error(ws, error):
click.echo("!!! Error: {}".format(error))
def on_error(ws, error):
click.echo("!!! Error: {}".format(error))
def on_sent(ws, data):
click.echo(">>> {}".format(json.dumps(data)))
def on_sent(ws, data):
click.echo(">>> {}".format(json.dumps(data)))
def on_heartbeat(ws):
click.echo("<3")
def on_heartbeat(ws):
click.echo("<3")
def on_message(ws, message_type, message_payload):
click.echo("<<< {}, Payload: {}".format(message_type, json.dumps(message_payload)))
def on_message(ws, message_type, message_payload):
click.echo(
"<<< {}, Payload: {}".format(message_type, json.dumps(message_payload))
)
socket = ctx.obj.client.create_socket(on_connect=on_connect,
on_close=on_close,
on_error=on_error,
on_sent=on_sent,
on_heartbeat=on_heartbeat,
on_message=on_message)
socket = ctx.obj.client.create_socket(
on_connect=on_connect,
on_close=on_close,
on_error=on_error,
on_sent=on_sent,
on_heartbeat=on_heartbeat,
on_message=on_message,
)
click.echo("--- Waiting for client to exit")
try:
socket.wait()
finally:
click.echo("--- Goodbye...")
click.echo("--- Waiting for client to exit")
try:
socket.wait()
finally:
click.echo("--- Goodbye...")
+158 -147
View File
@@ -1,95 +1,104 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
click.disable_unicode_literals_warning = True
import logging
from octoprint import init_settings, FatalStartupError
from octoprint.cli import standard_options, bulk_options, get_ctx_obj_option
import yaml
import json
import logging
import pprint
import click
import yaml
from octoprint import FatalStartupError, init_settings
from octoprint.cli import get_ctx_obj_option, standard_options
click.disable_unicode_literals_warning = True
def _to_settings_path(path):
if not isinstance(path, (list, tuple)):
path = list(filter(lambda x: x, map(lambda x: x.strip(), path.split("."))))
return path
if not isinstance(path, (list, tuple)):
path = list(filter(lambda x: x, map(lambda x: x.strip(), path.split("."))))
return path
def _set_helper(settings, path, value, data_type=None):
path = _to_settings_path(path)
path = _to_settings_path(path)
method = settings.set
if data_type is not None:
name = None
if data_type == bool:
name = "setBoolean"
elif data_type == float:
name = "setFloat"
elif data_type == int:
name = "setInt"
method = settings.set
if data_type is not None:
name = None
if data_type == bool:
name = "setBoolean"
elif data_type == float:
name = "setFloat"
elif data_type == int:
name = "setInt"
if name is not None:
method = getattr(settings, name)
if name is not None:
method = getattr(settings, name)
method(path, value)
settings.save()
method(path, value)
settings.save()
# ~~ "octoprint config" commands
#~~ "octoprint config" commands
@click.group()
def config_commands():
pass
pass
@config_commands.group(name="config")
@click.pass_context
def config(ctx):
"""Basic config manipulation."""
logging.basicConfig(level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN)
try:
ctx.obj.settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the settings manager.", err=True)
ctx.exit(-1)
"""Basic config manipulation."""
logging.basicConfig(
level=logging.DEBUG
if get_ctx_obj_option(ctx, "verbosity", 0) > 0
else logging.WARN
)
try:
ctx.obj.settings = init_settings(
get_ctx_obj_option(ctx, "basedir", None),
get_ctx_obj_option(ctx, "configfile", None),
)
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the settings manager.", err=True)
ctx.exit(-1)
@config.command(name="set")
@standard_options(hidden=True)
@click.argument("path", type=click.STRING)
@click.argument("value", type=click.STRING)
@click.option("--bool", "as_bool", is_flag=True,
help="Interpret value as bool")
@click.option("--float", "as_float", is_flag=True,
help="Interpret value as float")
@click.option("--int", "as_int", is_flag=True,
help="Interpret value as int")
@click.option("--json", "as_json", is_flag=True,
help="Parse value from json")
@click.option("--bool", "as_bool", is_flag=True, help="Interpret value as bool")
@click.option("--float", "as_float", is_flag=True, help="Interpret value as float")
@click.option("--int", "as_int", is_flag=True, help="Interpret value as int")
@click.option("--json", "as_json", is_flag=True, help="Parse value from json")
@click.pass_context
def set_command(ctx, path, value, as_bool, as_float, as_int, as_json):
"""Sets a config path to the provided value."""
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(e.message, err=True)
ctx.exit(-1)
"""Sets a config path to the provided value."""
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(e.message, err=True)
ctx.exit(-1)
data_type = None
if as_bool:
data_type = bool
elif as_float:
data_type = float
elif as_int:
data_type = int
data_type = None
if as_bool:
data_type = bool
elif as_float:
data_type = float
elif as_int:
data_type = int
_set_helper(ctx.obj.settings, path, value, data_type=data_type)
_set_helper(ctx.obj.settings, path, value, data_type=data_type)
@config.command(name="remove")
@@ -97,8 +106,8 @@ def set_command(ctx, path, value, as_bool, as_float, as_int, as_json):
@click.argument("path", type=click.STRING)
@click.pass_context
def remove_command(ctx, path):
"""Removes a config path."""
_set_helper(ctx.obj.settings, path, None)
"""Removes a config path."""
_set_helper(ctx.obj.settings, path, None)
@config.command(name="append_value")
@@ -108,25 +117,25 @@ def remove_command(ctx, path):
@click.option("--json", "as_json", is_flag=True)
@click.pass_context
def append_value_command(ctx, path, value, as_json=False):
"""Appends value to list behind config path."""
path = _to_settings_path(path)
"""Appends value to list behind config path."""
path = _to_settings_path(path)
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(e.message, err=True)
ctx.exit(-1)
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(e.message, err=True)
ctx.exit(-1)
current = ctx.obj.settings.get(path)
if current is None:
current = []
if not isinstance(current, list):
click.echo("Cannot append to non-list value at given path", err=True)
ctx.exit(-1)
current = ctx.obj.settings.get(path)
if current is None:
current = []
if not isinstance(current, list):
click.echo("Cannot append to non-list value at given path", err=True)
ctx.exit(-1)
current.append(value)
_set_helper(ctx.obj.settings, path, current)
current.append(value)
_set_helper(ctx.obj.settings, path, current)
@config.command(name="insert_value")
@@ -137,25 +146,25 @@ def append_value_command(ctx, path, value, as_json=False):
@click.option("--json", "as_json", is_flag=True)
@click.pass_context
def insert_value_command(ctx, path, index, value, as_json=False):
"""Inserts value at index of list behind config key."""
path = _to_settings_path(path)
"""Inserts value at index of list behind config key."""
path = _to_settings_path(path)
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(e.message, err=True)
ctx.exit(-1)
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(e.message, err=True)
ctx.exit(-1)
current = ctx.obj.settings.get(path)
if current is None:
current = []
if not isinstance(current, list):
click.echo("Cannot insert into non-list value at given path", err=True)
ctx.exit(-1)
current = ctx.obj.settings.get(path)
if current is None:
current = []
if not isinstance(current, list):
click.echo("Cannot insert into non-list value at given path", err=True)
ctx.exit(-1)
current.insert(index, value)
_set_helper(ctx.obj.settings, path, current)
current.insert(index, value)
_set_helper(ctx.obj.settings, path, current)
@config.command(name="remove_value")
@@ -165,78 +174,80 @@ def insert_value_command(ctx, path, index, value, as_json=False):
@click.option("--json", "as_json", is_flag=True)
@click.pass_context
def remove_value_command(ctx, path, value, as_json=False):
"""Removes value from list at config path."""
path = _to_settings_path(path)
"""Removes value from list at config path."""
path = _to_settings_path(path)
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(e.message, err=True)
ctx.exit(-1)
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(e.message, err=True)
ctx.exit(-1)
current = ctx.obj.settings.get(path)
if current is None:
current = []
if not isinstance(current, list):
click.echo("Cannot remove value from non-list value at given path", err=True)
ctx.exit(-1)
current = ctx.obj.settings.get(path)
if current is None:
current = []
if not isinstance(current, list):
click.echo("Cannot remove value from non-list value at given path", err=True)
ctx.exit(-1)
if not value in current:
click.echo("Value is not contained in list at given path")
ctx.exit()
if value not in current:
click.echo("Value is not contained in list at given path")
ctx.exit()
current.remove(value)
_set_helper(ctx.obj.settings, path, current)
current.remove(value)
_set_helper(ctx.obj.settings, path, current)
@config.command(name="get")
@click.argument("path", type=click.STRING)
@click.option("--json", "as_json", is_flag=True,
help="Output value formatted as JSON")
@click.option("--yaml", "as_yaml", is_flag=True,
help="Output value formatted as YAML")
@click.option("--raw", "as_raw", is_flag=True,
help="Output value as raw string representation")
@click.option("--json", "as_json", is_flag=True, help="Output value formatted as JSON")
@click.option("--yaml", "as_yaml", is_flag=True, help="Output value formatted as YAML")
@click.option(
"--raw", "as_raw", is_flag=True, help="Output value as raw string representation"
)
@standard_options(hidden=True)
@click.pass_context
def get_command(ctx, path, as_json=False, as_yaml=False, as_raw=False):
"""Retrieves value from config path."""
path = _to_settings_path(path)
value = ctx.obj.settings.get(path, merged=True)
"""Retrieves value from config path."""
path = _to_settings_path(path)
value = ctx.obj.settings.get(path, merged=True)
if as_json:
output = json.dumps(value)
elif as_yaml:
output = yaml.safe_dump(value, default_flow_style=False, indent=4, allow_unicode=True)
elif as_raw:
output = value
else:
output = pprint.pformat(value)
if as_json:
output = json.dumps(value)
elif as_yaml:
output = yaml.safe_dump(
value, default_flow_style=False, indent=4, allow_unicode=True
)
elif as_raw:
output = value
else:
output = pprint.pformat(value)
click.echo(output)
click.echo(output)
@config.command(name="effective")
@click.option("--json", "as_json", is_flag=True,
help="Output value formatted as JSON")
@click.option("--yaml", "as_yaml", is_flag=True,
help="Output value formatted as YAML")
@click.option("--raw", "as_raw", is_flag=True,
help="Output value as raw string representation")
@click.option("--json", "as_json", is_flag=True, help="Output value formatted as JSON")
@click.option("--yaml", "as_yaml", is_flag=True, help="Output value formatted as YAML")
@click.option(
"--raw", "as_raw", is_flag=True, help="Output value as raw string representation"
)
@standard_options(hidden=True)
@click.pass_context
def effective_command(ctx, as_json=False, as_yaml=False, as_raw=False):
"""Retrieves the full effective config."""
value = ctx.obj.settings.effective
"""Retrieves the full effective config."""
value = ctx.obj.settings.effective
if as_json:
output = json.dumps(value)
elif as_yaml:
output = yaml.safe_dump(value, default_flow_style=False, indent=4, allow_unicode=True)
elif as_raw:
output = value
else:
output = pprint.pformat(value)
if as_json:
output = json.dumps(value)
elif as_yaml:
output = yaml.safe_dump(
value, default_flow_style=False, indent=4, allow_unicode=True
)
elif as_raw:
output = value
else:
output = pprint.pformat(value)
click.echo(output)
click.echo(output)
+211 -178
View File
@@ -2,236 +2,269 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
click.disable_unicode_literals_warning = True
from past.builtins import basestring
class OctoPrintDevelCommands(click.MultiCommand):
"""
Custom `click.MultiCommand <http://click.pocoo.org/5/api/#click.MultiCommand>`_
implementation that provides commands relevant for (plugin) development
based on availability of development dependencies.
"""
"""
Custom `click.MultiCommand <http://click.pocoo.org/5/api/#click.MultiCommand>`_
implementation that provides commands relevant for (plugin) development
based on availability of development dependencies.
"""
sep = ":"
groups = ("plugin",)
sep = ":"
groups = ("plugin",)
def __init__(self, *args, **kwargs):
click.MultiCommand.__init__(self, *args, **kwargs)
def __init__(self, *args, **kwargs):
click.MultiCommand.__init__(self, *args, **kwargs)
from octoprint.util.commandline import CommandlineCaller
from functools import partial
from functools import partial
def log_util(f):
def log(*lines):
for line in lines:
f(line)
return log
from octoprint.util.commandline import CommandlineCaller
self.command_caller = CommandlineCaller()
self.command_caller.on_log_call = log_util(lambda x: click.echo(">> {}".format(x)))
self.command_caller.on_log_stdout = log_util(click.echo)
self.command_caller.on_log_stderr = log_util(partial(click.echo, err=True))
def log_util(f):
def log(*lines):
for line in lines:
f(line)
def _get_prefix_methods(self, method_prefix):
for name in [x for x in dir(self) if x.startswith(method_prefix)]:
method = getattr(self, name)
yield method
return log
def _get_commands_from_prefix_methods(self, method_prefix):
for method in self._get_prefix_methods(method_prefix):
result = method()
if result is not None and isinstance(result, click.Command):
yield result
self.command_caller = CommandlineCaller()
self.command_caller.on_log_call = log_util(
lambda x: click.echo(">> {}".format(x))
)
self.command_caller.on_log_stdout = log_util(click.echo)
self.command_caller.on_log_stderr = log_util(partial(click.echo, err=True))
def _get_commands(self):
result = {}
for group in self.groups:
for command in self._get_commands_from_prefix_methods("{}_".format(group)):
result[group + self.sep + command.name] = command
return result
def _get_prefix_methods(self, method_prefix):
for name in [x for x in dir(self) if x.startswith(method_prefix)]:
method = getattr(self, name)
yield method
def list_commands(self, ctx):
result = [name for name in self._get_commands()]
result.sort()
return result
def _get_commands_from_prefix_methods(self, method_prefix):
for method in self._get_prefix_methods(method_prefix):
result = method()
if result is not None and isinstance(result, click.Command):
yield result
def get_command(self, ctx, cmd_name):
commands = self._get_commands()
return commands.get(cmd_name, None)
def _get_commands(self):
result = {}
for group in self.groups:
for command in self._get_commands_from_prefix_methods("{}_".format(group)):
result[group + self.sep + command.name] = command
return result
def plugin_new(self):
try:
import cookiecutter.main
except ImportError:
return None
def list_commands(self, ctx):
result = [name for name in self._get_commands()]
result.sort()
return result
try:
# we depend on Cookiecutter >= 1.4
from cookiecutter.prompt import StrictEnvironment
except ImportError:
return None
def get_command(self, ctx, cmd_name):
commands = self._get_commands()
return commands.get(cmd_name, None)
import contextlib
def plugin_new(self):
try:
import cookiecutter.main
except ImportError:
return None
@contextlib.contextmanager
def custom_cookiecutter_config(config):
"""
Allows overriding cookiecutter's user config with a custom dict
with fallback to the original data.
"""
from octoprint.util import fallback_dict
try:
# we depend on Cookiecutter >= 1.4
from cookiecutter.prompt import StrictEnvironment
except ImportError:
return None
original_get_user_config = cookiecutter.main.get_user_config
try:
def f(*args, **kwargs):
original_config = original_get_user_config(*args, **kwargs)
return fallback_dict(config, original_config)
cookiecutter.main.get_user_config = f
yield
finally:
cookiecutter.main.get_user_config = original_get_user_config
import contextlib
@contextlib.contextmanager
def custom_cookiecutter_prompt(options):
"""
Custom cookiecutter prompter for the template config.
@contextlib.contextmanager
def custom_cookiecutter_config(config):
"""
Allows overriding cookiecutter's user config with a custom dict
with fallback to the original data.
"""
from octoprint.util import fallback_dict
If a setting is available in the provided options (read from the CLI)
that will be used, otherwise the user will be prompted for a value
via click.
"""
original_prompt_for_config = cookiecutter.main.prompt_for_config
original_get_user_config = cookiecutter.main.get_user_config
try:
def custom_prompt_for_config(context, no_input=False):
cookiecutter_dict = {}
def f(*args, **kwargs):
original_config = original_get_user_config(*args, **kwargs)
return fallback_dict(config, original_config)
env = StrictEnvironment()
cookiecutter.main.get_user_config = f
yield
finally:
cookiecutter.main.get_user_config = original_get_user_config
for key, raw in context['cookiecutter'].items():
if key in options:
val = options[key]
else:
if not isinstance(raw, basestring):
raw = str(raw)
val = env.from_string(raw).render(cookiecutter=cookiecutter_dict)
@contextlib.contextmanager
def custom_cookiecutter_prompt(options):
"""
Custom cookiecutter prompter for the template config.
if not no_input:
val = click.prompt(key, default=val)
If a setting is available in the provided options (read from the CLI)
that will be used, otherwise the user will be prompted for a value
via click.
"""
original_prompt_for_config = cookiecutter.main.prompt_for_config
cookiecutter_dict[key] = val
return cookiecutter_dict
def custom_prompt_for_config(context, no_input=False):
cookiecutter_dict = {}
try:
cookiecutter.main.prompt_for_config = custom_prompt_for_config
yield
finally:
cookiecutter.main.prompt_for_config = original_prompt_for_config
env = StrictEnvironment()
@click.command("new")
@click.option("--name", "-n", help="The name of the plugin")
@click.option("--package", "-p", help="The plugin package")
@click.option("--author", "-a", help="The plugin author's name")
@click.option("--email", "-e", help="The plugin author's mail address")
@click.option("--license", "-l", help="The plugin's license")
@click.option("--description", "-d", help="The plugin's description")
@click.option("--homepage", help="The plugin's homepage URL")
@click.option("--source", "-s", help="The URL to the plugin's source")
@click.option("--installurl", "-i", help="The plugin's install URL")
@click.argument("identifier", required=False)
def command(name, package, author, email, description, license, homepage, source, installurl, identifier):
"""Creates a new plugin based on the OctoPrint Plugin cookiecutter template."""
from octoprint.util import tempdir
for key, raw in context["cookiecutter"].items():
if key in options:
val = options[key]
else:
if not isinstance(raw, basestring):
raw = str(raw)
val = env.from_string(raw).render(cookiecutter=cookiecutter_dict)
# deleting a git checkout folder might run into access errors due
# to write-protected sub folders, so we use a custom onerror handler
# that tries to fix such permissions
def onerror(func, path, exc_info):
"""Originally from http://stackoverflow.com/a/2656405/2028598"""
import stat
import os
if not no_input:
val = click.prompt(key, default=val)
if not os.access(path, os.W_OK):
os.chmod(path, stat.S_IWUSR)
func(path)
else:
raise
cookiecutter_dict[key] = val
return cookiecutter_dict
with tempdir(onerror=onerror) as path:
custom = {"cookiecutters_dir": path}
with custom_cookiecutter_config(custom):
raw_options = {"plugin_identifier": identifier,
"plugin_package": package,
"plugin_name": name,
"full_name": author,
"email": email,
"plugin_description": description,
"plugin_license": license,
"plugin_homepage": homepage,
"plugin_source": source,
"plugin_installurl": installurl}
options = dict((k, v) for k, v in raw_options.items() if v is not None)
try:
cookiecutter.main.prompt_for_config = custom_prompt_for_config
yield
finally:
cookiecutter.main.prompt_for_config = original_prompt_for_config
with custom_cookiecutter_prompt(options):
cookiecutter.main.cookiecutter("gh:OctoPrint/cookiecutter-octoprint-plugin")
@click.command("new")
@click.option("--name", "-n", help="The name of the plugin")
@click.option("--package", "-p", help="The plugin package")
@click.option("--author", "-a", help="The plugin author's name")
@click.option("--email", "-e", help="The plugin author's mail address")
@click.option("--license", "-l", help="The plugin's license")
@click.option("--description", "-d", help="The plugin's description")
@click.option("--homepage", help="The plugin's homepage URL")
@click.option("--source", "-s", help="The URL to the plugin's source")
@click.option("--installurl", "-i", help="The plugin's install URL")
@click.argument("identifier", required=False)
def command(
name,
package,
author,
email,
description,
license,
homepage,
source,
installurl,
identifier,
):
"""Creates a new plugin based on the OctoPrint Plugin cookiecutter template."""
from octoprint.util import tempdir
return command
# deleting a git checkout folder might run into access errors due
# to write-protected sub folders, so we use a custom onerror handler
# that tries to fix such permissions
def onerror(func, path, exc_info):
"""Originally from http://stackoverflow.com/a/2656405/2028598"""
import os
import stat
def plugin_install(self):
@click.command("install")
@click.option("--path", help="Path of the local plugin development folder to install")
def command(path):
"""
Installs the local plugin in development mode.
if not os.access(path, os.W_OK):
os.chmod(path, stat.S_IWUSR)
func(path)
else:
raise
Note: This can NOT be used to install plugins from remote locations
such as the plugin repository! It is strictly for local development
of plugins, to ensure the plugin is installed (editable) into the
same python environment that OctoPrint is installed under.
"""
with tempdir(onerror=onerror) as path:
custom = {"cookiecutters_dir": path}
with custom_cookiecutter_config(custom):
raw_options = {
"plugin_identifier": identifier,
"plugin_package": package,
"plugin_name": name,
"full_name": author,
"email": email,
"plugin_description": description,
"plugin_license": license,
"plugin_homepage": homepage,
"plugin_source": source,
"plugin_installurl": installurl,
}
options = dict(
(k, v) for k, v in raw_options.items() if v is not None
)
import os
import sys
with custom_cookiecutter_prompt(options):
cookiecutter.main.cookiecutter(
"gh:OctoPrint/cookiecutter-octoprint-plugin"
)
if not path:
path = os.getcwd()
return command
# check if this really looks like a plugin
if not os.path.isfile(os.path.join(path, "setup.py")):
click.echo("This doesn't look like an OctoPrint plugin folder")
sys.exit(1)
def plugin_install(self):
@click.command("install")
@click.option(
"--path", help="Path of the local plugin development folder to install"
)
def command(path):
"""
Installs the local plugin in development mode.
self.command_caller.call([sys.executable, "-m", "pip", "install", "-e", "."], cwd=path)
Note: This can NOT be used to install plugins from remote locations
such as the plugin repository! It is strictly for local development
of plugins, to ensure the plugin is installed (editable) into the
same python environment that OctoPrint is installed under.
"""
return command
import os
import sys
def plugin_uninstall(self):
@click.command("uninstall")
@click.argument("name")
def command(name):
"""Uninstalls the plugin with the given name."""
import sys
if not path:
path = os.getcwd()
lower_name = name.lower()
if not lower_name.startswith("octoprint_") and not lower_name.startswith("octoprint-"):
click.echo("This doesn't look like an OctoPrint plugin name")
sys.exit(1)
# check if this really looks like a plugin
if not os.path.isfile(os.path.join(path, "setup.py")):
click.echo("This doesn't look like an OctoPrint plugin folder")
sys.exit(1)
call = [sys.executable, "-m", "pip", "uninstall", "--yes", name]
self.command_caller.call(call)
self.command_caller.call(
[sys.executable, "-m", "pip", "install", "-e", "."], cwd=path
)
return command
def plugin_uninstall(self):
@click.command("uninstall")
@click.argument("name")
def command(name):
"""Uninstalls the plugin with the given name."""
import sys
lower_name = name.lower()
if not lower_name.startswith("octoprint_") and not lower_name.startswith(
"octoprint-"
):
click.echo("This doesn't look like an OctoPrint plugin name")
sys.exit(1)
call = [sys.executable, "-m", "pip", "uninstall", "--yes", name]
self.command_caller.call(call)
return command
return command
@click.group()
def dev_commands():
pass
pass
@dev_commands.group(name="dev", cls=OctoPrintDevelCommands)
def dev():
"""Additional commands for development tasks."""
pass
"""Additional commands for development tasks."""
pass
+109 -94
View File
@@ -1,137 +1,152 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
click.disable_unicode_literals_warning = True
import logging
import logging.config
from octoprint.cli import pass_octoprint_ctx, OctoPrintContext, get_ctx_obj_option
import click
from octoprint.cli import OctoPrintContext, get_ctx_obj_option, pass_octoprint_ctx
from octoprint.util import dict_merge
click.disable_unicode_literals_warning = True
LOGGING_CONFIG = {
"version": 1,
"formatters": {
"brief": {
"format": "%(message)s"
}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"formatter": "brief",
"stream": "ext://sys.stdout"
}
},
"loggers": {
"octoprint.plugin.core": {
"level": logging.ERROR
}
},
"root": {
"level": logging.WARNING
}
"version": 1,
"formatters": {"brief": {"format": "%(message)s"}},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"formatter": "brief",
"stream": "ext://sys.stdout",
}
},
"loggers": {"octoprint.plugin.core": {"level": logging.ERROR}},
"root": {"level": logging.WARNING},
}
#~~ "octoprint plugin:command" commands
# ~~ "octoprint plugin:command" commands
class OctoPrintPluginCommands(click.MultiCommand):
"""
Custom `click.MultiCommand <http://click.pocoo.org/5/api/#click.MultiCommand>`_
implementation that collects commands from the plugin hook
:ref:`octoprint.cli.commands <sec-plugins-hook-cli-commands>`.
"""
Custom `click.MultiCommand <http://click.pocoo.org/5/api/#click.MultiCommand>`_
implementation that collects commands from the plugin hook
:ref:`octoprint.cli.commands <sec-plugins-hook-cli-commands>`.
.. attribute:: settings
.. attribute:: settings
The global :class:`~octoprint.settings.Settings` instance.
The global :class:`~octoprint.settings.Settings` instance.
.. attribute:: plugin_manager
.. attribute:: plugin_manager
The :class:`~octoprint.plugin.core.PluginManager` instance.
"""
The :class:`~octoprint.plugin.core.PluginManager` instance.
"""
sep = ":"
sep = ":"
def __init__(self, *args, **kwargs):
click.MultiCommand.__init__(self, *args, **kwargs)
def __init__(self, *args, **kwargs):
click.MultiCommand.__init__(self, *args, **kwargs)
self.settings = None
self.plugin_manager = None
self.hooks = {}
self.settings = None
self.plugin_manager = None
self.hooks = {}
self._logger = logging.getLogger(__name__)
self._initialized = False
self._logger = logging.getLogger(__name__)
self._initialized = False
def _initialize(self, ctx):
if self._initialized:
return
def _initialize(self, ctx):
if self._initialized:
return
click.echo("Initializing settings & plugin subsystem...")
if ctx.obj is None:
ctx.obj = OctoPrintContext()
click.echo("Initializing settings & plugin subsystem...")
if ctx.obj is None:
ctx.obj = OctoPrintContext()
logging_config = dict_merge(LOGGING_CONFIG, {"root": {"level": logging.DEBUG if ctx.obj.verbosity > 0 else logging.WARNING}})
logging.config.dictConfig(logging_config)
logging_config = dict_merge(
LOGGING_CONFIG,
{
"root": {
"level": logging.DEBUG if ctx.obj.verbosity > 0 else logging.WARNING
}
},
)
logging.config.dictConfig(logging_config)
# initialize settings and plugin manager based on provided
# context (basedir and configfile)
from octoprint import init_settings, init_pluginsystem, FatalStartupError
try:
self.settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
self.plugin_manager = init_pluginsystem(self.settings,
safe_mode=get_ctx_obj_option(ctx, "safe_mode", False))
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the settings or the plugin system.", err=True)
ctx.exit(-1)
# initialize settings and plugin manager based on provided
# context (basedir and configfile)
from octoprint import FatalStartupError, init_pluginsystem, init_settings
# fetch registered hooks
self.hooks = self.plugin_manager.get_hooks("octoprint.cli.commands")
try:
self.settings = init_settings(
get_ctx_obj_option(ctx, "basedir", None),
get_ctx_obj_option(ctx, "configfile", None),
)
self.plugin_manager = init_pluginsystem(
self.settings, safe_mode=get_ctx_obj_option(ctx, "safe_mode", False)
)
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo(
"There was a fatal error initializing the settings or the plugin system.",
err=True,
)
ctx.exit(-1)
self._initialized = True
# fetch registered hooks
self.hooks = self.plugin_manager.get_hooks("octoprint.cli.commands")
def list_commands(self, ctx):
self._initialize(ctx)
result = [name for name in self._get_commands()]
result.sort()
return result
self._initialized = True
def get_command(self, ctx, cmd_name):
self._initialize(ctx)
commands = self._get_commands()
return commands.get(cmd_name, None)
def list_commands(self, ctx):
self._initialize(ctx)
result = [name for name in self._get_commands()]
result.sort()
return result
def _get_commands(self):
"""Fetch all commands from plugins providing any."""
def get_command(self, ctx, cmd_name):
self._initialize(ctx)
commands = self._get_commands()
return commands.get(cmd_name, None)
import collections
result = collections.OrderedDict()
def _get_commands(self):
"""Fetch all commands from plugins providing any."""
for name, hook in self.hooks.items():
try:
commands = hook(self, pass_octoprint_ctx)
for command in commands:
if not isinstance(command, click.Command):
self._logger.warning("Plugin {} provided invalid CLI command, ignoring it: {!r}".format(name, command))
continue
result[name + self.sep + command.name] = command
except Exception:
self._logger.exception("Error while retrieving cli commands for plugin {}".format(name),
extra={"plugin": name})
import collections
result = collections.OrderedDict()
for name, hook in self.hooks.items():
try:
commands = hook(self, pass_octoprint_ctx)
for command in commands:
if not isinstance(command, click.Command):
self._logger.warning(
"Plugin {} provided invalid CLI command, ignoring it: {!r}".format(
name, command
)
)
continue
result[name + self.sep + command.name] = command
except Exception:
self._logger.exception(
"Error while retrieving cli commands for plugin {}".format(name),
extra={"plugin": name},
)
return result
return result
@click.group()
@pass_octoprint_ctx
def plugin_commands(obj):
pass
pass
@plugin_commands.group(name="plugins", cls=OctoPrintPluginCommands)
def plugins():
"""Additional commands provided by plugins."""
pass
"""Additional commands provided by plugins."""
pass
+360 -216
View File
@@ -1,180 +1,277 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
click.disable_unicode_literals_warning = True
import logging
import sys
from octoprint.cli import bulk_options, standard_options, set_ctx_obj_option, get_ctx_obj_option
import click
def run_server(basedir, configfile, host, port, v6_only, debug, allow_root, logging_config, verbosity, safe_mode,
ignore_blacklist, octoprint_daemon=None):
"""Initializes the environment and starts up the server."""
from octoprint.cli import (
bulk_options,
get_ctx_obj_option,
set_ctx_obj_option,
standard_options,
)
from octoprint import init_platform, __display_version__, FatalStartupError
click.disable_unicode_literals_warning = True
def log_startup(recorder=None, safe_mode=None, **kwargs):
from octoprint.logging import get_divider_line
from octoprint.logging.handlers import PluginTimingsLogHandler
logger = logging.getLogger("octoprint.startup")
PluginTimingsLogHandler.arm_rollover()
def run_server(
basedir,
configfile,
host,
port,
v6_only,
debug,
allow_root,
logging_config,
verbosity,
safe_mode,
ignore_blacklist,
octoprint_daemon=None,
):
"""Initializes the environment and starts up the server."""
logger.info(get_divider_line("*"))
logger.info("Starting OctoPrint {}".format(__display_version__))
if safe_mode:
logger.info("Starting in SAFE MODE. Third party plugins will be disabled!")
if safe_mode == "flag":
reason = "command line flag"
elif safe_mode == "settings":
reason = "setting in config.yaml"
elif safe_mode == "incomplete_startup":
reason = "problem during last startup"
else:
reason = "unknown"
logger.info("Reason for safe mode: {}".format(reason))
from octoprint import FatalStartupError, __display_version__, init_platform
if recorder and len(recorder):
logger.info(get_divider_line("-", "Logged during platform initialization:"))
def log_startup(recorder=None, safe_mode=None, **kwargs):
from octoprint.logging import get_divider_line
from octoprint.logging.handlers import PluginTimingsLogHandler
from octoprint.logging.handlers import CombinedLogHandler
handler = CombinedLogHandler(*logging.getLogger().handlers)
recorder.setTarget(handler)
recorder.flush()
logger = logging.getLogger("octoprint.startup")
PluginTimingsLogHandler.arm_rollover()
logger.info(get_divider_line("-"))
logger.info(get_divider_line("*"))
logger.info("Starting OctoPrint {}".format(__display_version__))
if safe_mode:
logger.info("Starting in SAFE MODE. Third party plugins will be disabled!")
if safe_mode == "flag":
reason = "command line flag"
elif safe_mode == "settings":
reason = "setting in config.yaml"
elif safe_mode == "incomplete_startup":
reason = "problem during last startup"
else:
reason = "unknown"
logger.info("Reason for safe mode: {}".format(reason))
from octoprint import urllib3_ssl
if not urllib3_ssl:
logging.getLogger("octoprint.server")\
.warning("requests/urllib3 will run in an insecure SSL environment. "
"You might see corresponding warnings logged later "
"(\"InsecurePlatformWarning\"). It is recommended to either "
"update to a Python version >= 2.7.9 or alternatively "
"install PyOpenSSL plus its dependencies. For details see "
"https://urllib3.readthedocs.org/en/latest/security.html#openssl-pyopenssl")
logger.info(get_divider_line("*"))
if recorder and len(recorder):
logger.info(get_divider_line("-", "Logged during platform initialization:"))
def log_register_rollover(safe_mode=None, plugin_manager=None, environment_detector=None, **kwargs):
from octoprint.logging import get_handler, log_to_handler, get_divider_line
from octoprint.logging.handlers import OctoPrintLogHandler
from octoprint.logging.handlers import CombinedLogHandler
def rollover_callback():
handler = get_handler("file")
if handler is None:
return
handler = CombinedLogHandler(*logging.getLogger().handlers)
recorder.setTarget(handler)
recorder.flush()
logger = logging.getLogger("octoprint.server")
logger.info(get_divider_line("-"))
def _log(message, level=logging.INFO):
log_to_handler(logger, handler, level, message)
from octoprint import urllib3_ssl
_log(get_divider_line("-", "Log roll over detected"))
_log("OctoPrint {}".format(__display_version__))
if safe_mode:
_log("SAFE MODE is active. Third party plugins are disabled!")
plugin_manager.log_all_plugins(only_to_handler=handler)
environment_detector.log_detected_environment(only_to_handler=handler)
_log(get_divider_line("-"))
if not urllib3_ssl:
logging.getLogger("octoprint.server").warning(
"requests/urllib3 will run in an insecure SSL environment. "
"You might see corresponding warnings logged later "
'("InsecurePlatformWarning"). It is recommended to either '
"update to a Python version >= 2.7.9 or alternatively "
"install PyOpenSSL plus its dependencies. For details see "
"https://urllib3.readthedocs.org/en/latest/security.html#openssl-pyopenssl"
)
logger.info(get_divider_line("*"))
OctoPrintLogHandler.registerRolloverCallback(rollover_callback)
def log_register_rollover(
safe_mode=None, plugin_manager=None, environment_detector=None, **kwargs
):
from octoprint.logging import get_divider_line, get_handler, log_to_handler
from octoprint.logging.handlers import OctoPrintLogHandler
try:
components = init_platform(basedir, configfile,
logging_file=logging_config,
debug=debug,
verbosity=verbosity,
uncaught_logger=__name__,
safe_mode=safe_mode,
ignore_blacklist=ignore_blacklist,
after_safe_mode=log_startup,
after_environment_detector=log_register_rollover)
settings, _, safe_mode, event_manager, connectivity_checker, plugin_manager, environment_detector = components
def rollover_callback():
handler = get_handler("file")
if handler is None:
return
except FatalStartupError as e:
logger = logging.getLogger("octoprint.startup").fatal
echo = lambda x: click.echo(x, err=True)
logger = logging.getLogger("octoprint.server")
for method in logger, echo:
method(str(e))
method("There was a fatal error starting up OctoPrint.")
def _log(message, level=logging.INFO):
log_to_handler(logger, handler, level, message)
else:
from octoprint.server import Server
octoprint_server = Server(settings=settings,
plugin_manager=plugin_manager,
event_manager=event_manager,
connectivity_checker=connectivity_checker,
environment_detector=environment_detector,
host=host,
port=port,
v6_only=v6_only,
debug=debug,
safe_mode=safe_mode,
allow_root=allow_root,
octoprint_daemon=octoprint_daemon)
octoprint_server.run()
_log(get_divider_line("-", "Log roll over detected"))
_log("OctoPrint {}".format(__display_version__))
if safe_mode:
_log("SAFE MODE is active. Third party plugins are disabled!")
plugin_manager.log_all_plugins(only_to_handler=handler)
environment_detector.log_detected_environment(only_to_handler=handler)
_log(get_divider_line("-"))
#~~ server options
OctoPrintLogHandler.registerRolloverCallback(rollover_callback)
server_options = bulk_options([
click.option("--host", type=click.STRING, callback=set_ctx_obj_option,
help="Specify the host address on which to bind the server."),
click.option("--port", type=click.INT, callback=set_ctx_obj_option,
help="Specify the port on which to bind the server."),
click.option("-4", "--ipv4", "v4", is_flag=True, callback=set_ctx_obj_option,
help="Bind to IPv4 addresses only. Implies '--host 0.0.0.0'. Silently ignored if -6 is present."),
click.option("-6", "--ipv6", "v6", is_flag=True, callback=set_ctx_obj_option,
help="Bind to IPv6 addresses only. Disables dual stack when binding to any v6 addresses. Silently ignored if -4 is present."),
click.option("--logging", type=click.Path(), callback=set_ctx_obj_option,
help="Specify the config file to use for configuring logging."),
click.option("--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option,
help="Allow OctoPrint to run as user root."),
click.option("--debug", is_flag=True, callback=set_ctx_obj_option,
help="Enable debug mode."),
click.option("--ignore-blacklist", "ignore_blacklist", is_flag=True, callback=set_ctx_obj_option,
help="Disable processing of the plugin blacklist.")
])
try:
components = init_platform(
basedir,
configfile,
logging_file=logging_config,
debug=debug,
verbosity=verbosity,
uncaught_logger=__name__,
safe_mode=safe_mode,
ignore_blacklist=ignore_blacklist,
after_safe_mode=log_startup,
after_environment_detector=log_register_rollover,
)
(
settings,
_,
safe_mode,
event_manager,
connectivity_checker,
plugin_manager,
environment_detector,
) = components
except FatalStartupError as e:
logger = logging.getLogger("octoprint.startup").fatal
echo = lambda x: click.echo(x, err=True)
for method in logger, echo:
method(str(e))
method("There was a fatal error starting up OctoPrint.")
else:
from octoprint.server import Server
octoprint_server = Server(
settings=settings,
plugin_manager=plugin_manager,
event_manager=event_manager,
connectivity_checker=connectivity_checker,
environment_detector=environment_detector,
host=host,
port=port,
v6_only=v6_only,
debug=debug,
safe_mode=safe_mode,
allow_root=allow_root,
octoprint_daemon=octoprint_daemon,
)
octoprint_server.run()
# ~~ server options
server_options = bulk_options(
[
click.option(
"--host",
type=click.STRING,
callback=set_ctx_obj_option,
help="Specify the host address on which to bind the server.",
),
click.option(
"--port",
type=click.INT,
callback=set_ctx_obj_option,
help="Specify the port on which to bind the server.",
),
click.option(
"-4",
"--ipv4",
"v4",
is_flag=True,
callback=set_ctx_obj_option,
help="Bind to IPv4 addresses only. Implies '--host 0.0.0.0'. Silently ignored if -6 is present.",
),
click.option(
"-6",
"--ipv6",
"v6",
is_flag=True,
callback=set_ctx_obj_option,
help="Bind to IPv6 addresses only. Disables dual stack when binding to any v6 addresses. Silently ignored if -4 is present.",
),
click.option(
"--logging",
type=click.Path(),
callback=set_ctx_obj_option,
help="Specify the config file to use for configuring logging.",
),
click.option(
"--iknowwhatimdoing",
"allow_root",
is_flag=True,
callback=set_ctx_obj_option,
help="Allow OctoPrint to run as user root.",
),
click.option(
"--debug",
is_flag=True,
callback=set_ctx_obj_option,
help="Enable debug mode.",
),
click.option(
"--ignore-blacklist",
"ignore_blacklist",
is_flag=True,
callback=set_ctx_obj_option,
help="Disable processing of the plugin blacklist.",
),
]
)
"""Decorator to add the options shared among the server commands: ``--host``, ``--port``, ``-4``, ``-6``
``--logging``, ``--iknowwhatimdoing`` and ``--debug``."""
daemon_options = bulk_options([
click.option("--pid", type=click.Path(), default="/tmp/octoprint.pid", callback=set_ctx_obj_option,
help="Pidfile to use for daemonizing.")
])
daemon_options = bulk_options(
[
click.option(
"--pid",
type=click.Path(),
default="/tmp/octoprint.pid",
callback=set_ctx_obj_option,
help="Pidfile to use for daemonizing.",
)
]
)
"""Decorator to add the options for the daemon subcommand: ``--pid``."""
#~~ "octoprint serve" and "octoprint daemon" commands
# ~~ "octoprint serve" and "octoprint daemon" commands
@click.group()
def server_commands():
pass
pass
@server_commands.command(name="safemode")
@standard_options()
@click.pass_context
def enable_safemode(ctx, **kwargs):
"""Sets the safe mode flag for the next start."""
from octoprint import init_settings, FatalStartupError
"""Sets the safe mode flag for the next start."""
from octoprint import FatalStartupError, init_settings
logging.basicConfig(level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN)
try:
settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the settings manager.", err=True)
ctx.exit(-1)
else:
settings.setBoolean(["server", "startOnceInSafeMode"], True)
settings.save()
logging.basicConfig(
level=logging.DEBUG
if get_ctx_obj_option(ctx, "verbosity", 0) > 0
else logging.WARN
)
try:
settings = init_settings(
get_ctx_obj_option(ctx, "basedir", None),
get_ctx_obj_option(ctx, "configfile", None),
)
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the settings manager.", err=True)
ctx.exit(-1)
else:
settings.setBoolean(["server", "startOnceInSafeMode"], True)
settings.save()
click.echo("Safe mode flag set, OctoPrint will start in safe mode on next restart.")
click.echo(
"Safe mode flag set, OctoPrint will start in safe mode on next restart."
)
@server_commands.command(name="serve")
@@ -182,109 +279,156 @@ def enable_safemode(ctx, **kwargs):
@server_options
@click.pass_context
def serve_command(ctx, **kwargs):
"""Starts the OctoPrint server."""
"""Starts the OctoPrint server."""
def get_value(key):
return get_ctx_obj_option(ctx, key, kwargs.get(key))
def get_value(key):
return get_ctx_obj_option(ctx, key, kwargs.get(key))
host = get_value("host")
port = get_value("port")
v4 = get_value("v4")
v6 = get_value("v6")
logging = get_value("logging")
allow_root = get_value("allow_root")
debug = get_value("debug")
host = get_value("host")
port = get_value("port")
v4 = get_value("v4")
v6 = get_value("v6")
logging = get_value("logging")
allow_root = get_value("allow_root")
debug = get_value("debug")
basedir = get_value("basedir")
configfile = get_value("configfile")
verbosity = get_value("verbosity")
safe_mode = "flag" if get_value("safe_mode") else None
ignore_blacklist = get_value("ignore_blacklist")
basedir = get_value("basedir")
configfile = get_value("configfile")
verbosity = get_value("verbosity")
safe_mode = "flag" if get_value("safe_mode") else None
ignore_blacklist = get_value("ignore_blacklist")
if v4 and not host:
host = "0.0.0.0"
if v4 and not host:
host = "0.0.0.0"
run_server(basedir, configfile, host, port, v6, debug,
allow_root, logging, verbosity, safe_mode,
ignore_blacklist)
run_server(
basedir,
configfile,
host,
port,
v6,
debug,
allow_root,
logging,
verbosity,
safe_mode,
ignore_blacklist,
)
if sys.platform != "win32" and sys.platform != "darwin":
# we do not support daemon mode under windows or macosx
# we do not support daemon mode under windows or macosx
@server_commands.command(name="daemon")
@standard_options()
@server_options
@daemon_options
@click.argument("command", type=click.Choice(["start", "stop", "restart", "status"]),
metavar="start|stop|restart|status")
@click.pass_context
def daemon_command(ctx, command, **kwargs):
"""
Starts, stops or restarts in daemon mode.
@server_commands.command(name="daemon")
@standard_options()
@server_options
@daemon_options
@click.argument(
"command",
type=click.Choice(["start", "stop", "restart", "status"]),
metavar="start|stop|restart|status",
)
@click.pass_context
def daemon_command(ctx, command, **kwargs):
"""
Starts, stops or restarts in daemon mode.
Please note that daemon mode is not supported under Windows and MacOSX right now.
"""
Please note that daemon mode is not supported under Windows and MacOSX right now.
"""
def get_value(key):
return get_ctx_obj_option(ctx, key, kwargs.get(key))
def get_value(key):
return get_ctx_obj_option(ctx, key, kwargs.get(key))
host = get_value("host")
port = get_value("port")
v4 = get_value("v4")
v6 = get_value("v6")
logging = get_value("logging")
allow_root = get_value("allow_root")
debug = get_value("debug")
pid = get_value("pid")
host = get_value("host")
port = get_value("port")
v4 = get_value("v4")
v6 = get_value("v6")
logging = get_value("logging")
allow_root = get_value("allow_root")
debug = get_value("debug")
pid = get_value("pid")
basedir = get_value("basedir")
configfile = get_value("configfile")
verbosity = get_value("verbosity")
safe_mode = "flag" if get_value("safe_mode") else None
ignore_blacklist = get_value("ignore_blacklist")
basedir = get_value("basedir")
configfile = get_value("configfile")
verbosity = get_value("verbosity")
safe_mode = "flag" if get_value("safe_mode") else None
ignore_blacklist = get_value("ignore_blacklist")
if v4 and not host:
host = "0.0.0.0"
if v4 and not host:
host = "0.0.0.0"
if pid is None:
click.echo("No path to a pidfile set",
file=sys.stderr)
sys.exit(1)
if pid is None:
click.echo("No path to a pidfile set", file=sys.stderr)
sys.exit(1)
from octoprint.daemon import Daemon
class OctoPrintDaemon(Daemon):
def __init__(self, pidfile, basedir, configfile, host, port, v6_only, debug, allow_root, logging_config,
verbosity, safe_mode, ignore_blacklist):
Daemon.__init__(self, pidfile)
from octoprint.daemon import Daemon
self._basedir = basedir
self._configfile = configfile
self._host = host
self._port = port
self._v6_only = v6_only
self._debug = debug
self._allow_root = allow_root
self._logging_config = logging_config
self._verbosity = verbosity
self._safe_mode = safe_mode
self._ignore_blacklist = ignore_blacklist
class OctoPrintDaemon(Daemon):
def __init__(
self,
pidfile,
basedir,
configfile,
host,
port,
v6_only,
debug,
allow_root,
logging_config,
verbosity,
safe_mode,
ignore_blacklist,
):
Daemon.__init__(self, pidfile)
def run(self):
run_server(self._basedir, self._configfile, self._host, self._port, self._v6_only, self._debug,
self._allow_root, self._logging_config, self._verbosity, self._safe_mode,
self._ignore_blacklist, octoprint_daemon=self)
self._basedir = basedir
self._configfile = configfile
self._host = host
self._port = port
self._v6_only = v6_only
self._debug = debug
self._allow_root = allow_root
self._logging_config = logging_config
self._verbosity = verbosity
self._safe_mode = safe_mode
self._ignore_blacklist = ignore_blacklist
octoprint_daemon = OctoPrintDaemon(pid, basedir, configfile, host, port, v6, debug, allow_root, logging,
verbosity, safe_mode, ignore_blacklist)
if command == "start":
octoprint_daemon.start()
elif command == "stop":
octoprint_daemon.stop()
elif command == "restart":
octoprint_daemon.restart()
elif command == "status":
octoprint_daemon.status()
def run(self):
run_server(
self._basedir,
self._configfile,
self._host,
self._port,
self._v6_only,
self._debug,
self._allow_root,
self._logging_config,
self._verbosity,
self._safe_mode,
self._ignore_blacklist,
octoprint_daemon=self,
)
octoprint_daemon = OctoPrintDaemon(
pid,
basedir,
configfile,
host,
port,
v6,
debug,
allow_root,
logging,
verbosity,
safe_mode,
ignore_blacklist,
)
if command == "start":
octoprint_daemon.start()
elif command == "stop":
octoprint_daemon.stop()
elif command == "restart":
octoprint_daemon.restart()
elif command == "status":
octoprint_daemon.status()
+139 -105
View File
@@ -1,124 +1,152 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
import logging
import click
from octoprint import init_settings
from octoprint.cli import get_ctx_obj_option
from octoprint.access.groups import FilebasedGroupManager
from octoprint.access.users import FilebasedUserManager, UnknownUser, UserAlreadyExists
from octoprint.cli import get_ctx_obj_option
from octoprint.util import get_class, sv
click.disable_unicode_literals_warning = True
#~~ "octoprint user" commands
# ~~ "octoprint user" commands
@click.group()
def user_commands():
pass
pass
@user_commands.group(name="user")
@click.pass_context
def user(ctx):
"""
User management.
"""
User management.
Note that this currently only supports managing user accounts stored in the configured user manager, not any
user managers added through plugins and the "octoprint.users.factory" hook.
"""
try:
logging.basicConfig(level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN)
settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
Note that this currently only supports managing user accounts stored in the configured user manager, not any
user managers added through plugins and the "octoprint.users.factory" hook.
"""
try:
logging.basicConfig(
level=logging.DEBUG
if get_ctx_obj_option(ctx, "verbosity", 0) > 0
else logging.WARN
)
settings = init_settings(
get_ctx_obj_option(ctx, "basedir", None),
get_ctx_obj_option(ctx, "configfile", None),
)
group_manager_name = settings.get(["accessControl", "groupManager"])
try:
clazz = get_class(group_manager_name)
group_manager = clazz()
except AttributeError:
click.echo("Could not instantiate group manager {}, "
"falling back to FilebasedGroupManager!".format(group_manager_name), err=True)
group_manager = FilebasedGroupManager()
group_manager_name = settings.get(["accessControl", "groupManager"])
try:
clazz = get_class(group_manager_name)
group_manager = clazz()
except AttributeError:
click.echo(
"Could not instantiate group manager {}, "
"falling back to FilebasedGroupManager!".format(group_manager_name),
err=True,
)
group_manager = FilebasedGroupManager()
ctx.obj.group_manager = group_manager
ctx.obj.group_manager = group_manager
name = settings.get(["accessControl", "userManager"])
try:
clazz = get_class(name)
user_manager = clazz(group_manager=group_manager, settings=settings)
except Exception:
click.echo("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(name), err=True)
user_manager = FilebasedUserManager(group_manager, settings=settings)
finally:
user_manager.enabled = settings.getBoolean(["accessControl", "enabled"])
name = settings.get(["accessControl", "userManager"])
try:
clazz = get_class(name)
user_manager = clazz(group_manager=group_manager, settings=settings)
except Exception:
click.echo(
"Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(
name
),
err=True,
)
user_manager = FilebasedUserManager(group_manager, settings=settings)
finally:
user_manager.enabled = settings.getBoolean(["accessControl", "enabled"])
ctx.obj.user_manager = user_manager
ctx.obj.user_manager = user_manager
except Exception:
click.echo("Could not instantiate user manager", err=True)
return
except Exception:
click.echo("Could not instantiate user manager", err=True)
return
@user.command(name="list")
@click.pass_context
def list_users_command(ctx):
"""Lists user information"""
users = ctx.obj.user_manager.get_all_users()
_print_list(users)
"""Lists user information"""
users = ctx.obj.user_manager.get_all_users()
_print_list(users)
@user.command(name="add")
@click.argument("username", type=click.STRING, required=True)
@click.password_option("--password", "password", help="Password for the user")
@click.option("-g", "--group", "groups", multiple=True,
help="Groups to set on the user")
@click.option("-p", "--permission", "permissions", multiple=True,
help="Individual permissions to set on the user")
@click.option("--admin", "is_admin", type=click.BOOL, is_flag=True, default=False,
help="Adds user to admin group")
@click.option("-g", "--group", "groups", multiple=True, help="Groups to set on the user")
@click.option(
"-p",
"--permission",
"permissions",
multiple=True,
help="Individual permissions to set on the user",
)
@click.option(
"--admin",
"is_admin",
type=click.BOOL,
is_flag=True,
default=False,
help="Adds user to admin group",
)
@click.pass_context
def add_user_command(ctx, username, password, groups, permissions, is_admin):
"""Add a new user."""
if not groups:
groups = []
"""Add a new user."""
if not groups:
groups = []
if is_admin:
groups.append(ctx.obj.group_manager.admin_group)
if is_admin:
groups.append(ctx.obj.group_manager.admin_group)
try:
ctx.obj.user_manager.add_user(username,
password,
groups=groups,
permissions=permissions,
active=True)
try:
ctx.obj.user_manager.add_user(
username, password, groups=groups, permissions=permissions, active=True
)
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.as_dict())))
except UserAlreadyExists:
click.echo("A user with the name {} does already exist!".format(username), err=True)
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.as_dict())))
except UserAlreadyExists:
click.echo(
"A user with the name {} does already exist!".format(username), err=True
)
@user.command(name="remove")
@click.argument("username", type=click.STRING)
@click.pass_context
def remove_user_command(ctx, username):
"""Remove an existing user."""
confirm = click.prompt("This is will irreversibly destroy the user account! Enter 'yes' to confirm",
type=click.STRING)
"""Remove an existing user."""
confirm = click.prompt(
"This is will irreversibly destroy the user account! Enter 'yes' to confirm",
type=click.STRING,
)
if confirm.lower() == "yes":
ctx.obj.user_manager.remove_user(username)
click.echo("User {} removed.".format(username))
else:
click.echo("User {} not removed.".format(username))
if confirm.lower() == "yes":
ctx.obj.user_manager.remove_user(username)
click.echo("User {} removed.".format(username))
else:
click.echo("User {} not removed.".format(username))
@user.command(name="password")
@@ -126,59 +154,65 @@ def remove_user_command(ctx, username):
@click.password_option("--password", "password", help="New password for user")
@click.pass_context
def change_password_command(ctx, username, password):
"""Change an existing user's password."""
try:
ctx.obj.user_manager.change_user_password(username, password)
click.echo("Password changed for user {}.".format(username))
except UnknownUser:
click.echo("User {} does not exist!".format(username), err=True)
"""Change an existing user's password."""
try:
ctx.obj.user_manager.change_user_password(username, password)
click.echo("Password changed for user {}.".format(username))
except UnknownUser:
click.echo("User {} does not exist!".format(username), err=True)
@user.command(name="activate")
@click.argument("username", type=click.STRING)
@click.pass_context
def activate_command(ctx, username):
"""Activate a user account."""
try:
ctx.obj.user_manager.change_user_activation(username, True)
click.echo("User {} activated.".format(username))
"""Activate a user account."""
try:
ctx.obj.user_manager.change_user_activation(username, True)
click.echo("User {} activated.".format(username))
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.asDict())))
except UnknownUser:
click.echo("User {} does not exist!".format(username), err=True)
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.asDict())))
except UnknownUser:
click.echo("User {} does not exist!".format(username), err=True)
@user.command(name="deactivate")
@click.argument("username", type=click.STRING)
@click.pass_context
def deactivate_command(ctx, username):
"""Activate a user account."""
try:
ctx.obj.user_manager.change_user_activation(username, False)
click.echo("User {} activated.".format(username))
"""Activate a user account."""
try:
ctx.obj.user_manager.change_user_activation(username, False)
click.echo("User {} activated.".format(username))
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.asDict())))
except UnknownUser:
click.echo("User {} does not exist!".format(username), err=True)
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.asDict())))
except UnknownUser:
click.echo("User {} does not exist!".format(username), err=True)
def _print_list(users):
click.echo("{} users registered in the system:".format(len(users)))
for user in sorted(map(lambda x: x.as_dict(), users), key=lambda x: sv(x.get("name"))):
click.echo("\t{}".format(_user_to_line(user)))
click.echo("{} users registered in the system:".format(len(users)))
for user in sorted(
map(lambda x: x.as_dict(), users), key=lambda x: sv(x.get("name"))
):
click.echo("\t{}".format(_user_to_line(user)))
def _user_to_line(user):
return "{name}" \
"\n\t\tactive: {active}" \
"\n\t\tgroups: {groups}" \
"\n\t\tpermissions: {permissions}".format(name=user.get("name"),
active=user.get("active", "False"),
groups=", ".join(user.get("groups", [])),
permissions=", ".join(user.get("permissions", [])))
return (
"{name}"
"\n\t\tactive: {active}"
"\n\t\tgroups: {groups}"
"\n\t\tpermissions: {permissions}".format(
name=user.get("name"),
active=user.get("active", "False"),
groups=", ".join(user.get("groups", [])),
permissions=", ".join(user.get("permissions", [])),
)
)
+147 -134
View File
@@ -7,170 +7,183 @@ Generic linux daemon base class
Originally from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/#c35
"""
import io, sys, os, time, signal
import io
import os
import signal
import sys
import time
class Daemon:
"""
A generic daemon class.
"""
A generic daemon class.
Usage: subclass the daemon class and override the run() method.
Usage: subclass the daemon class and override the run() method.
If you want to log the output to someplace different that stdout and stderr,
also override the echo() and error() methods.
"""
If you want to log the output to someplace different that stdout and stderr,
also override the echo() and error() methods.
"""
def __init__(self, pidfile):
self.pidfile = pidfile
def __init__(self, pidfile):
self.pidfile = pidfile
def _daemonize(self):
"""Daemonize class. UNIX double fork mechanism."""
def _daemonize(self):
"""Daemonize class. UNIX double fork mechanism."""
self._double_fork()
self._redirect_io()
self._double_fork()
self._redirect_io()
# write pidfile
pid = str(os.getpid())
self.set_pid(pid)
# write pidfile
pid = str(os.getpid())
self.set_pid(pid)
def _double_fork(self):
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
except OSError as err:
self.error("First fork failed: {}".format(str(err)))
sys.exit(1)
def _double_fork(self):
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
except OSError as err:
self.error("First fork failed: {}".format(str(err)))
sys.exit(1)
# decouple from parent environment
os.chdir('/')
os.setsid()
os.umask(0o002)
# decouple from parent environment
os.chdir("/")
os.setsid()
os.umask(0o002)
# do second fork
try:
pid = os.fork()
if pid > 0:
# exit from second parent
sys.exit(0)
except OSError as err:
self.error("Second fork failed: {}".format(str(err)))
sys.exit(1)
# do second fork
try:
pid = os.fork()
if pid > 0:
# exit from second parent
sys.exit(0)
except OSError as err:
self.error("Second fork failed: {}".format(str(err)))
sys.exit(1)
def _redirect_io(self):
# redirect standard file descriptors
sys.stdout.flush()
sys.stderr.flush()
si = io.open(os.devnull, 'rt', encoding='utf-8')
so = io.open(os.devnull, 'at+', encoding='utf-8')
se = io.open(os.devnull, 'at+', encoding='utf-8')
def _redirect_io(self):
# redirect standard file descriptors
sys.stdout.flush()
sys.stderr.flush()
si = io.open(os.devnull, "rt", encoding="utf-8")
so = io.open(os.devnull, "at+", encoding="utf-8")
se = io.open(os.devnull, "at+", encoding="utf-8")
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
def terminated(self):
self.remove_pidfile()
def terminated(self):
self.remove_pidfile()
def start(self):
"""Start the daemon."""
def start(self):
"""Start the daemon."""
# Check for a pidfile to see if the daemon already runs
pid = self.get_pid()
if pid:
self.error("pidfile {} already exist. Is the daemon already running?".format(self.pidfile))
sys.exit(1)
# Check for a pidfile to see if the daemon already runs
pid = self.get_pid()
if pid:
self.error(
"pidfile {} already exist. Is the daemon already running?".format(
self.pidfile
)
)
sys.exit(1)
self.echo("Starting daemon...")
self.echo("Starting daemon...")
# Start the daemon
self._daemonize()
self.run()
# Start the daemon
self._daemonize()
self.run()
def stop(self, check_running=True):
"""Stop the daemon."""
pid = self.get_pid()
if not pid:
if not check_running:
return
self.error("pidfile {} does not exist. Is the daemon really running?".format(self.pidfile))
sys.exit(1)
def stop(self, check_running=True):
"""Stop the daemon."""
pid = self.get_pid()
if not pid:
if not check_running:
return
self.error(
"pidfile {} does not exist. Is the daemon really running?".format(
self.pidfile
)
)
sys.exit(1)
self.echo("Stopping daemon...")
self.echo("Stopping daemon...")
# Try killing the daemon process
try:
while 1:
os.kill(pid, signal.SIGTERM)
time.sleep(0.1)
except OSError as err:
e = str(err.args)
if e.find("No such process") > 0:
self.remove_pidfile()
else:
self.error(e)
sys.exit(1)
# Try killing the daemon process
try:
while 1:
os.kill(pid, signal.SIGTERM)
time.sleep(0.1)
except OSError as err:
e = str(err.args)
if e.find("No such process") > 0:
self.remove_pidfile()
else:
self.error(e)
sys.exit(1)
def restart(self):
"""Restart the daemon."""
self.stop(check_running=False)
self.start()
def restart(self):
"""Restart the daemon."""
self.stop(check_running=False)
self.start()
def status(self):
"""Prints the daemon status."""
if self.is_running():
self.echo("Daemon is running")
else:
self.echo("Daemon is not running")
def status(self):
"""Prints the daemon status."""
if self.is_running():
self.echo("Daemon is running")
else:
self.echo("Daemon is not running")
def is_running(self):
"""Check if a process is running under the specified pid."""
pid = self.get_pid()
if pid is None:
return False
def is_running(self):
"""Check if a process is running under the specified pid."""
pid = self.get_pid()
if pid is None:
return False
try:
os.kill(pid, 0)
except OSError:
try:
self.remove_pidfile()
except Exception:
self.error("Daemon found not running, but could not remove stale pidfile")
return False
else:
return True
try:
os.kill(pid, 0)
except OSError:
try:
self.remove_pidfile()
except Exception:
self.error("Daemon found not running, but could not remove stale pidfile")
return False
else:
return True
def get_pid(self):
"""Get the pid from the pidfile."""
try:
with io.open(self.pidfile,'rt', encoding='utf-8') as pf:
pid = int(pf.read().strip())
except (IOError, ValueError):
pid = None
return pid
def get_pid(self):
"""Get the pid from the pidfile."""
try:
with io.open(self.pidfile, "rt", encoding="utf-8") as pf:
pid = int(pf.read().strip())
except (IOError, ValueError):
pid = None
return pid
def set_pid(self, pid):
"""Write the pid to the pidfile."""
with io.open(self.pidfile,'wt+', encoding='utf-8') as f:
f.write(str(pid) + '\n')
def set_pid(self, pid):
"""Write the pid to the pidfile."""
with io.open(self.pidfile, "wt+", encoding="utf-8") as f:
f.write(str(pid) + "\n")
def remove_pidfile(self):
"""Removes the pidfile."""
if os.path.isfile(self.pidfile):
os.remove(self.pidfile)
def remove_pidfile(self):
"""Removes the pidfile."""
if os.path.isfile(self.pidfile):
os.remove(self.pidfile)
def run(self):
"""You should override this method when you subclass Daemon.
def run(self):
"""You should override this method when you subclass Daemon.
It will be called after the process has been daemonized by
start() or restart()."""
It will be called after the process has been daemonized by
start() or restart()."""
raise NotImplementedError()
raise NotImplementedError()
@classmethod
def echo(cls, line):
print(line)
@classmethod
def echo(cls, line):
print(line)
@classmethod
def error(cls, line):
print(line, file=sys.stderr)
@classmethod
def error(cls, line):
print(line, file=sys.stderr)
+147 -127
View File
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
import copy
@@ -9,165 +9,185 @@ import logging
import os
import sys
import threading
import yaml
import psutil
import yaml
from octoprint.plugin import EnvironmentDetectionPlugin
from octoprint.util.platform import get_os
from octoprint.util.version import get_python_version_string
class EnvironmentDetector(object):
def __init__(self, plugin_manager):
self._plugin_manager = plugin_manager
def __init__(self, plugin_manager):
self._plugin_manager = plugin_manager
self._cache = None
self._cache_lock = threading.RLock()
self._cache = None
self._cache_lock = threading.RLock()
self._logger = logging.getLogger(__name__)
self._logger = logging.getLogger(__name__)
try:
self._environment_plugins = self._plugin_manager.get_implementations(
EnvironmentDetectionPlugin
)
except Exception:
# just in case, see #3100...
self._logger.exception(
"There was an error fetching EnvironmentDetectionPlugins from the plugin manager"
)
self._environment_plugins = []
try:
self._environment_plugins = self._plugin_manager.get_implementations(EnvironmentDetectionPlugin)
except Exception:
# just in case, see #3100...
self._logger.exception("There was an error fetching EnvironmentDetectionPlugins from the plugin manager")
self._environment_plugins = []
@property
def environment(self):
with self._cache_lock:
if self._cache is None:
self.run_detection()
return copy.deepcopy(self._cache)
@property
def environment(self):
with self._cache_lock:
if self._cache is None:
self.run_detection()
return copy.deepcopy(self._cache)
def run_detection(self, notify_plugins=True):
try:
environment = {}
environment["os"] = self._detect_os()
environment["python"] = self._detect_python()
environment["hardware"] = self._detect_hardware()
def run_detection(self, notify_plugins=True):
try:
environment = {}
environment["os"] = self._detect_os()
environment["python"] = self._detect_python()
environment["hardware"] = self._detect_hardware()
plugin_result = self._detect_from_plugins()
if plugin_result:
environment["plugins"] = plugin_result
plugin_result = self._detect_from_plugins()
if plugin_result:
environment["plugins"] = plugin_result
with self._cache_lock:
self._cache = environment
with self._cache_lock:
self._cache = environment
if notify_plugins:
self.notify_plugins()
if notify_plugins:
self.notify_plugins()
return environment
except Exception:
self._logger.exception("Unexpected error while detecting environment")
with self._cache_lock:
self._cache = {}
return self._cache
return environment
except Exception:
self._logger.exception("Unexpected error while detecting environment")
with self._cache_lock:
self._cache = {}
return self._cache
def _detect_os(self):
return {"id": get_os(), "platform": sys.platform}
def _detect_os(self):
return {"id": get_os(),
"platform": sys.platform}
def _detect_python(self):
result = {"version": "unknown", "pip": "unknown"}
def _detect_python(self):
result = {"version": "unknown",
"pip": "unknown"}
# determine python version
try:
result["version"] = get_python_version_string()
except Exception:
self._logger.exception("Error detecting python version")
# determine python version
try:
result["version"] = get_python_version_string()
except Exception:
self._logger.exception("Error detecting python version")
# determine if we are running from a virtual environment
try:
if hasattr(sys, "real_prefix") or (
hasattr(sys, "base_prefix")
and os.path.realpath(sys.prefix) != os.path.realpath(sys.base_prefix)
):
result["virtualenv"] = sys.prefix
except Exception:
self._logger.exception(
"Error detecting whether we are running in a virtual environment"
)
# determine if we are running from a virtual environment
try:
if hasattr(sys, "real_prefix") or (hasattr(sys, "base_prefix") and os.path.realpath(sys.prefix) != os.path.realpath(sys.base_prefix)):
result["virtualenv"] = sys.prefix
except Exception:
self._logger.exception("Error detecting whether we are running in a virtual environment")
# try to find pip version
try:
import pkg_resources
# try to find pip version
try:
import pkg_resources
result["pip"] = pkg_resources.get_distribution("pip").version
except Exception:
self._logger.exception("Error detecting pip version")
result["pip"] = pkg_resources.get_distribution("pip").version
except Exception:
self._logger.exception("Error detecting pip version")
return result
return result
def _detect_hardware(self):
result = {"cores": "unknown",
"freq": "unknown",
"ram": "unknown"}
def _detect_hardware(self):
result = {"cores": "unknown", "freq": "unknown", "ram": "unknown"}
try:
cores = psutil.cpu_count()
cpu_freq = psutil.cpu_freq()
ram = psutil.virtual_memory()
if cores:
result["cores"] = cores
if cpu_freq and hasattr(cpu_freq, "max"):
result["freq"] = cpu_freq.max
if ram and hasattr(ram, "total"):
result["ram"] = ram.total
except Exception:
self._logger.exception("Error while detecting hardware environment")
try:
cores = psutil.cpu_count()
cpu_freq = psutil.cpu_freq()
ram = psutil.virtual_memory()
if cores:
result["cores"] = cores
if cpu_freq and hasattr(cpu_freq, "max"):
result["freq"] = cpu_freq.max
if ram and hasattr(ram, "total"):
result["ram"] = ram.total
except Exception:
self._logger.exception("Error while detecting hardware environment")
return result
return result
def _detect_from_plugins(self):
result = {}
def _detect_from_plugins(self):
result = {}
for implementation in self._environment_plugins:
try:
additional = implementation.get_additional_environment()
if additional is not None and isinstance(additional, dict) and len(additional):
result[implementation._identifier] = additional
except Exception:
self._logger.exception("Error while fetching additional "
"environment data from plugin {}".format(implementation._identifier),
extra={"plugin": implementation._identifier})
for implementation in self._environment_plugins:
try:
additional = implementation.get_additional_environment()
if (
additional is not None
and isinstance(additional, dict)
and len(additional)
):
result[implementation._identifier] = additional
except Exception:
self._logger.exception(
"Error while fetching additional "
"environment data from plugin {}".format(implementation._identifier),
extra={"plugin": implementation._identifier},
)
return result
return result
def log_detected_environment(self, only_to_handler=None):
def _log(message, level=logging.INFO):
if only_to_handler is not None:
import octoprint.logging
octoprint.logging.log_to_handler(self._logger, only_to_handler, level, message, [])
else:
self._logger.log(level, message)
def log_detected_environment(self, only_to_handler=None):
def _log(message, level=logging.INFO):
if only_to_handler is not None:
import octoprint.logging
try:
_log(self._format())
except Exception:
self._logger.exception("Error logging detected environment")
octoprint.logging.log_to_handler(
self._logger, only_to_handler, level, message, []
)
else:
self._logger.log(level, message)
def _format(self):
with self._cache_lock:
if self._cache is None:
self.run_detection()
environment = copy.deepcopy(self._cache)
try:
_log(self._format())
except Exception:
self._logger.exception("Error logging detected environment")
dumped_environment = yaml.safe_dump(environment,
default_flow_style=False,
indent=4,
allow_unicode=True).strip()
environment_lines = "\n".join(map(lambda l: "| {}".format(l), dumped_environment.split("\n")))
return "Detected environment is Python {} under {} ({}). Details:\n{}".format(environment["python"]["version"],
environment["os"]["id"].title(),
environment["os"]["platform"],
environment_lines)
def _format(self):
with self._cache_lock:
if self._cache is None:
self.run_detection()
environment = copy.deepcopy(self._cache)
def notify_plugins(self):
with self._cache_lock:
if self._cache is None:
self.run_detection(notify_plugins=False)
environment = copy.deepcopy(self._cache)
dumped_environment = yaml.safe_dump(
environment, default_flow_style=False, indent=4, allow_unicode=True
).strip()
environment_lines = "\n".join(
map(lambda l: "| {}".format(l), dumped_environment.split("\n"))
)
return "Detected environment is Python {} under {} ({}). Details:\n{}".format(
environment["python"]["version"],
environment["os"]["id"].title(),
environment["os"]["platform"],
environment_lines,
)
for implementation in self._environment_plugins:
try:
implementation.on_environment_detected(environment)
except Exception:
self._logger.exception("Error while sending environment "
"detection result to plugin {}".format(implementation._identifier))
def notify_plugins(self):
with self._cache_lock:
if self._cache is None:
self.run_detection(notify_plugins=False)
environment = copy.deepcopy(self._cache)
for implementation in self._environment_plugins:
try:
implementation.on_environment_detected(environment)
except Exception:
self._logger.exception(
"Error while sending environment "
"detection result to plugin {}".format(implementation._identifier)
)
+426 -373
View File
@@ -2,487 +2,540 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>, Lars Norpchen"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import datetime
import logging
import subprocess
try:
import queue
import queue
except ImportError:
import Queue as queue
import threading
import Queue as queue
import collections
import re
import threading
from octoprint.settings import settings
import octoprint.plugin
from octoprint.settings import settings
# singleton
_instance = None
def all_events():
return [getattr(Events, name) for name in Events.__dict__ if not name.startswith("_") and not name in ("register_event",)]
return [
getattr(Events, name)
for name in Events.__dict__
if not name.startswith("_") and name not in ("register_event",)
]
class Events(object):
# server
STARTUP = "Startup"
SHUTDOWN = "Shutdown"
CONNECTIVITY_CHANGED = "ConnectivityChanged"
# server
STARTUP = "Startup"
SHUTDOWN = "Shutdown"
CONNECTIVITY_CHANGED = "ConnectivityChanged"
# connect/disconnect to printer
CONNECTING = "Connecting"
CONNECTED = "Connected"
DISCONNECTING = "Disconnecting"
DISCONNECTED = "Disconnected"
# connect/disconnect to printer
CONNECTING = "Connecting"
CONNECTED = "Connected"
DISCONNECTING = "Disconnecting"
DISCONNECTED = "Disconnected"
# State changes
PRINTER_STATE_CHANGED = "PrinterStateChanged"
PRINTER_RESET = "PrinterReset"
# State changes
PRINTER_STATE_CHANGED = "PrinterStateChanged"
PRINTER_RESET = "PrinterReset"
# connect/disconnect by client
CLIENT_OPENED = "ClientOpened"
CLIENT_CLOSED = "ClientClosed"
CLIENT_AUTHED = "ClientAuthed"
CLIENT_DEAUTHED = "ClientDeauthed"
# connect/disconnect by client
CLIENT_OPENED = "ClientOpened"
CLIENT_CLOSED = "ClientClosed"
CLIENT_AUTHED = "ClientAuthed"
CLIENT_DEAUTHED = "ClientDeauthed"
# user login/logout
USER_LOGGED_IN = "UserLoggedIn"
USER_LOGGED_OUT = "UserLoggedOut"
# user login/logout
USER_LOGGED_IN = "UserLoggedIn"
USER_LOGGED_OUT = "UserLoggedOut"
# File management
UPLOAD = "Upload"
FILE_SELECTED = "FileSelected"
FILE_DESELECTED = "FileDeselected"
UPDATED_FILES = "UpdatedFiles"
METADATA_ANALYSIS_STARTED = "MetadataAnalysisStarted"
METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished"
METADATA_STATISTICS_UPDATED = "MetadataStatisticsUpdated"
# File management
UPLOAD = "Upload"
FILE_SELECTED = "FileSelected"
FILE_DESELECTED = "FileDeselected"
UPDATED_FILES = "UpdatedFiles"
METADATA_ANALYSIS_STARTED = "MetadataAnalysisStarted"
METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished"
METADATA_STATISTICS_UPDATED = "MetadataStatisticsUpdated"
FILE_ADDED = "FileAdded"
FILE_REMOVED = "FileRemoved"
FOLDER_ADDED = "FolderAdded"
FOLDER_REMOVED = "FolderRemoved"
FILE_ADDED = "FileAdded"
FILE_REMOVED = "FileRemoved"
FOLDER_ADDED = "FolderAdded"
FOLDER_REMOVED = "FolderRemoved"
# SD Upload
TRANSFER_STARTED = "TransferStarted"
TRANSFER_DONE = "TransferDone"
TRANSFER_FAILED = "TransferFailed"
# SD Upload
TRANSFER_STARTED = "TransferStarted"
TRANSFER_DONE = "TransferDone"
TRANSFER_FAILED = "TransferFailed"
# print job
PRINT_STARTED = "PrintStarted"
PRINT_DONE = "PrintDone"
PRINT_FAILED = "PrintFailed"
PRINT_CANCELLING = "PrintCancelling"
PRINT_CANCELLED = "PrintCancelled"
PRINT_PAUSED = "PrintPaused"
PRINT_RESUMED = "PrintResumed"
ERROR = "Error"
# print job
PRINT_STARTED = "PrintStarted"
PRINT_DONE = "PrintDone"
PRINT_FAILED = "PrintFailed"
PRINT_CANCELLING = "PrintCancelling"
PRINT_CANCELLED = "PrintCancelled"
PRINT_PAUSED = "PrintPaused"
PRINT_RESUMED = "PrintResumed"
ERROR = "Error"
# print/gcode events
POWER_ON = "PowerOn"
POWER_OFF = "PowerOff"
HOME = "Home"
Z_CHANGE = "ZChange"
WAITING = "Waiting"
DWELL = "Dwelling"
COOLING = "Cooling"
ALERT = "Alert"
CONVEYOR = "Conveyor"
EJECT = "Eject"
E_STOP = "EStop"
POSITION_UPDATE = "PositionUpdate"
FIRMWARE_DATA = "FirmwareData"
TOOL_CHANGE = "ToolChange"
REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived"
# print/gcode events
POWER_ON = "PowerOn"
POWER_OFF = "PowerOff"
HOME = "Home"
Z_CHANGE = "ZChange"
WAITING = "Waiting"
DWELL = "Dwelling"
COOLING = "Cooling"
ALERT = "Alert"
CONVEYOR = "Conveyor"
EJECT = "Eject"
E_STOP = "EStop"
POSITION_UPDATE = "PositionUpdate"
FIRMWARE_DATA = "FirmwareData"
TOOL_CHANGE = "ToolChange"
REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived"
# Timelapse
CAPTURE_START = "CaptureStart"
CAPTURE_DONE = "CaptureDone"
CAPTURE_FAILED = "CaptureFailed"
POSTROLL_START = "PostRollStart"
POSTROLL_END = "PostRollEnd"
MOVIE_RENDERING = "MovieRendering"
MOVIE_DONE = "MovieDone"
MOVIE_FAILED = "MovieFailed"
# Timelapse
CAPTURE_START = "CaptureStart"
CAPTURE_DONE = "CaptureDone"
CAPTURE_FAILED = "CaptureFailed"
POSTROLL_START = "PostRollStart"
POSTROLL_END = "PostRollEnd"
MOVIE_RENDERING = "MovieRendering"
MOVIE_DONE = "MovieDone"
MOVIE_FAILED = "MovieFailed"
# Slicing
SLICING_STARTED = "SlicingStarted"
SLICING_DONE = "SlicingDone"
SLICING_FAILED = "SlicingFailed"
SLICING_CANCELLED = "SlicingCancelled"
SLICING_PROFILE_ADDED = "SlicingProfileAdded"
SLICING_PROFILE_MODIFIED = "SlicingProfileModified"
SLICING_PROFILE_DELETED = "SlicingProfileDeleted"
# Slicing
SLICING_STARTED = "SlicingStarted"
SLICING_DONE = "SlicingDone"
SLICING_FAILED = "SlicingFailed"
SLICING_CANCELLED = "SlicingCancelled"
SLICING_PROFILE_ADDED = "SlicingProfileAdded"
SLICING_PROFILE_MODIFIED = "SlicingProfileModified"
SLICING_PROFILE_DELETED = "SlicingProfileDeleted"
# Printer Profiles
PRINTER_PROFILE_ADDED = "PrinterProfileAdded"
PRINTER_PROFILE_MODIFIED = "PrinterProfileModified"
PRINTER_PROFILE_DELETED = "PrinterProfileDeleted"
# Printer Profiles
PRINTER_PROFILE_ADDED = "PrinterProfileAdded"
PRINTER_PROFILE_MODIFIED = "PrinterProfileModified"
PRINTER_PROFILE_DELETED = "PrinterProfileDeleted"
# Settings
SETTINGS_UPDATED = "SettingsUpdated"
# Settings
SETTINGS_UPDATED = "SettingsUpdated"
@classmethod
def register_event(cls, event, prefix=None):
name = cls._to_identifier(event)
if prefix:
event = prefix + event
name = cls._to_identifier(prefix) + name
setattr(cls, name, event)
return name, event
@classmethod
def register_event(cls, event, prefix=None):
name = cls._to_identifier(event)
if prefix:
event = prefix + event
name = cls._to_identifier(prefix) + name
setattr(cls, name, event)
return name, event
# based on https://stackoverflow.com/a/1176023
_first_cap_re = re.compile('(.)([A-Z][a-z]+)')
_all_cap_re = re.compile('([a-z0-9])([A-Z])')
# based on https://stackoverflow.com/a/1176023
_first_cap_re = re.compile("(.)([A-Z][a-z]+)")
_all_cap_re = re.compile("([a-z0-9])([A-Z])")
@classmethod
def _to_identifier(cls, name):
s1 = cls._first_cap_re.sub(r"\1_\2", name)
return cls._all_cap_re.sub(r"\1_\2", s1).upper()
@classmethod
def _to_identifier(cls, name):
s1 = cls._first_cap_re.sub(r'\1_\2', name)
return cls._all_cap_re.sub(r'\1_\2', s1).upper()
def eventManager():
global _instance
if _instance is None:
_instance = EventManager()
return _instance
global _instance
if _instance is None:
_instance = EventManager()
return _instance
class EventManager(object):
"""
Handles receiving events and dispatching them to subscribers
"""
"""
Handles receiving events and dispatching them to subscribers
"""
def __init__(self):
self._registeredListeners = collections.defaultdict(list)
self._logger = logging.getLogger(__name__)
self._logger_fire = logging.getLogger("{}.fire".format(__name__))
def __init__(self):
self._registeredListeners = collections.defaultdict(list)
self._logger = logging.getLogger(__name__)
self._logger_fire = logging.getLogger("{}.fire".format(__name__))
self._startup_signaled = False
self._shutdown_signaled = False
self._startup_signaled = False
self._shutdown_signaled = False
self._queue = queue.Queue()
self._held_back = queue.Queue()
self._queue = queue.Queue()
self._held_back = queue.Queue()
self._worker = threading.Thread(target=self._work)
self._worker.daemon = True
self._worker.start()
self._worker = threading.Thread(target=self._work)
self._worker.daemon = True
self._worker.start()
def _work(self):
try:
while not self._shutdown_signaled:
event, payload = self._queue.get(True)
if event == Events.SHUTDOWN:
# we've got the shutdown event here, stop event loop processing after this has been processed
self._logger.info("Processing shutdown event, this will be our last event")
self._shutdown_signaled = True
def _work(self):
try:
while not self._shutdown_signaled:
event, payload = self._queue.get(True)
if event == Events.SHUTDOWN:
# we've got the shutdown event here, stop event loop processing after this has been processed
self._logger.info(
"Processing shutdown event, this will be our last event"
)
self._shutdown_signaled = True
eventListeners = self._registeredListeners[event]
self._logger_fire.debug("Firing event: {} (Payload: {!r})".format(event, payload))
eventListeners = self._registeredListeners[event]
self._logger_fire.debug(
"Firing event: {} (Payload: {!r})".format(event, payload)
)
for listener in eventListeners:
self._logger.debug("Sending action to {!r}".format(listener))
try:
listener(event, payload)
except Exception:
self._logger.exception("Got an exception while sending event {} (Payload: {!r}) to {}".format(event, payload, listener))
for listener in eventListeners:
self._logger.debug("Sending action to {!r}".format(listener))
try:
listener(event, payload)
except Exception:
self._logger.exception(
"Got an exception while sending event {} (Payload: {!r}) to {}".format(
event, payload, listener
)
)
octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin,
"on_event",
args=(event, payload))
self._logger.info("Event loop shut down")
except Exception:
self._logger.exception("Ooops, the event bus worker loop crashed")
octoprint.plugin.call_plugin(
octoprint.plugin.types.EventHandlerPlugin,
"on_event",
args=(event, payload),
)
self._logger.info("Event loop shut down")
except Exception:
self._logger.exception("Ooops, the event bus worker loop crashed")
def fire(self, event, payload=None):
"""
Fire an event to anyone subscribed to it
def fire(self, event, payload=None):
"""
Fire an event to anyone subscribed to it
Any object can generate an event and any object can subscribe to the event's name as a string (arbitrary, but
case sensitive) and any extra payload data that may pertain to the event.
Any object can generate an event and any object can subscribe to the event's name as a string (arbitrary, but
case sensitive) and any extra payload data that may pertain to the event.
Callbacks must implement the signature "callback(event, payload)", with "event" being the event's name and
payload being a payload object specific to the event.
"""
Callbacks must implement the signature "callback(event, payload)", with "event" being the event's name and
payload being a payload object specific to the event.
"""
send_held_back = False
if event == Events.STARTUP:
self._logger.info("Processing startup event, this is our first event")
self._startup_signaled = True
send_held_back = True
send_held_back = False
if event == Events.STARTUP:
self._logger.info("Processing startup event, this is our first event")
self._startup_signaled = True
send_held_back = True
self._enqueue(event, payload)
self._enqueue(event, payload)
if send_held_back:
self._logger.info("Adding {} events to queue that "
"were held back before startup event".format(self._held_back.qsize()))
while True:
try:
self._queue.put(self._held_back.get(block=False))
except queue.Empty:
break
if send_held_back:
self._logger.info(
"Adding {} events to queue that "
"were held back before startup event".format(self._held_back.qsize())
)
while True:
try:
self._queue.put(self._held_back.get(block=False))
except queue.Empty:
break
def _enqueue(self, event, payload):
if self._startup_signaled:
q = self._queue
else:
q = self._held_back
def _enqueue(self, event, payload):
if self._startup_signaled:
q = self._queue
else:
q = self._held_back
q.put((event, payload))
q.put((event, payload))
def subscribe(self, event, callback):
"""
Subscribe a listener to an event -- pass in the event name (as a string) and the callback object
"""
def subscribe(self, event, callback):
"""
Subscribe a listener to an event -- pass in the event name (as a string) and the callback object
"""
if callback in self._registeredListeners[event]:
# callback is already subscribed to the event
return
if callback in self._registeredListeners[event]:
# callback is already subscribed to the event
return
self._registeredListeners[event].append(callback)
self._logger.debug("Subscribed listener {!r} for event {}".format(callback, event))
self._registeredListeners[event].append(callback)
self._logger.debug(
"Subscribed listener {!r} for event {}".format(callback, event)
)
def unsubscribe (self, event, callback):
"""
Unsubscribe a listener from an event -- pass in the event name (as string) and the callback object
"""
def unsubscribe(self, event, callback):
"""
Unsubscribe a listener from an event -- pass in the event name (as string) and the callback object
"""
try:
self._registeredListeners[event].remove(callback)
except ValueError:
# not registered
pass
try:
self._registeredListeners[event].remove(callback)
except ValueError:
# not registered
pass
def join(self, timeout=None):
self._worker.join(timeout)
return self._worker.is_alive()
def join(self, timeout=None):
self._worker.join(timeout)
return self._worker.is_alive()
class GenericEventListener(object):
"""
The GenericEventListener can be subclassed to easily create custom event listeners.
"""
"""
The GenericEventListener can be subclassed to easily create custom event listeners.
"""
def __init__(self):
self._logger = logging.getLogger(__name__)
def __init__(self):
self._logger = logging.getLogger(__name__)
def subscribe(self, events):
"""
Subscribes the eventCallback method for all events in the given list.
"""
def subscribe(self, events):
"""
Subscribes the eventCallback method for all events in the given list.
"""
for event in events:
eventManager().subscribe(event, self.eventCallback)
for event in events:
eventManager().subscribe(event, self.eventCallback)
def unsubscribe(self, events):
"""
Unsubscribes the eventCallback method for all events in the given list
"""
def unsubscribe(self, events):
"""
Unsubscribes the eventCallback method for all events in the given list
"""
for event in events:
eventManager().unsubscribe(event, self.eventCallback)
for event in events:
eventManager().unsubscribe(event, self.eventCallback)
def eventCallback(self, event, payload):
"""
Actual event callback called with name of event and optional payload. Not implemented here, override in
child classes.
"""
pass
def eventCallback(self, event, payload):
"""
Actual event callback called with name of event and optional payload. Not implemented here, override in
child classes.
"""
pass
class DebugEventListener(GenericEventListener):
def __init__(self):
GenericEventListener.__init__(self)
def __init__(self):
GenericEventListener.__init__(self)
events = list(filter(lambda x: not x.startswith("__"), dir(Events)))
self.subscribe(events)
events = list(filter(lambda x: not x.startswith("__"), dir(Events)))
self.subscribe(events)
def eventCallback(self, event, payload):
GenericEventListener.eventCallback(self, event, payload)
self._logger.debug("Received event: %s (Payload: %r)" % (event, payload))
def eventCallback(self, event, payload):
GenericEventListener.eventCallback(self, event, payload)
self._logger.debug("Received event: %s (Payload: %r)" % (event, payload))
class CommandTrigger(GenericEventListener):
def __init__(self, printer):
GenericEventListener.__init__(self)
self._printer = printer
self._subscriptions = {}
def __init__(self, printer):
GenericEventListener.__init__(self)
self._printer = printer
self._subscriptions = {}
self._initSubscriptions()
self._initSubscriptions()
def _initSubscriptions(self):
"""
Subscribes all events as defined in "events > $triggerType > subscriptions" in the settings with their
respective commands.
"""
if not settings().get(["events"]):
return
def _initSubscriptions(self):
"""
Subscribes all events as defined in "events > $triggerType > subscriptions" in the settings with their
respective commands.
"""
if not settings().get(["events"]):
return
if not settings().getBoolean(["events", "enabled"]):
return
if not settings().getBoolean(["events", "enabled"]):
return
eventsToSubscribe = []
subscriptions = settings().get(["events", "subscriptions"])
for subscription in subscriptions:
if not isinstance(subscription, dict):
self._logger.info("Invalid subscription definition, not a dictionary: {!r}".format(subscription))
continue
eventsToSubscribe = []
subscriptions = settings().get(["events", "subscriptions"])
for subscription in subscriptions:
if not isinstance(subscription, dict):
self._logger.info(
"Invalid subscription definition, not a dictionary: {!r}".format(
subscription
)
)
continue
if not "event" in subscription or not "command" in subscription \
or not "type" in subscription or not subscription["type"] in ["system", "gcode"]:
self._logger.info("Invalid command trigger, missing either event, type or command or type is invalid: {!r}".format(subscription))
continue
if (
"event" not in subscription
or "command" not in subscription
or "type" not in subscription
or subscription["type"] not in ["system", "gcode"]
):
self._logger.info(
"Invalid command trigger, missing either event, type or command or type is invalid: {!r}".format(
subscription
)
)
continue
if "enabled" in subscription and not subscription["enabled"]:
self._logger.info("Disabled command trigger: {!r}".format(subscription))
continue
if "enabled" in subscription and not subscription["enabled"]:
self._logger.info("Disabled command trigger: {!r}".format(subscription))
continue
events = subscription["event"]
command = subscription["command"]
commandType = subscription["type"]
debug = subscription["debug"] if "debug" in subscription else False
events = subscription["event"]
command = subscription["command"]
commandType = subscription["type"]
debug = subscription["debug"] if "debug" in subscription else False
# "event" in the configuration can be a string, or
# a list of strings. If it's the former, convert it
# into the latter.
if not isinstance(events, (tuple, list, set)):
events = [events]
# "event" in the configuration can be a string, or
# a list of strings. If it's the former, convert it
# into the latter.
if not isinstance(events, (tuple, list, set)):
events = [events]
for event in events:
if event not in self._subscriptions:
self._subscriptions[event] = []
self._subscriptions[event].append((command, commandType, debug))
for event in events:
if event not in self._subscriptions:
self._subscriptions[event] = []
self._subscriptions[event].append((command, commandType, debug))
if event not in eventsToSubscribe:
eventsToSubscribe.append(event)
if event not in eventsToSubscribe:
eventsToSubscribe.append(event)
self.subscribe(eventsToSubscribe)
self.subscribe(eventsToSubscribe)
def eventCallback(self, event, payload):
"""
Event callback, iterates over all subscribed commands for the given event, processes the command
string and then executes the command via the abstract executeCommand method.
"""
def eventCallback(self, event, payload):
"""
Event callback, iterates over all subscribed commands for the given event, processes the command
string and then executes the command via the abstract executeCommand method.
"""
GenericEventListener.eventCallback(self, event, payload)
GenericEventListener.eventCallback(self, event, payload)
if not event in self._subscriptions:
return
if event not in self._subscriptions:
return
for command, commandType, debug in self._subscriptions[event]:
try:
if isinstance(command, (tuple, list, set)):
processedCommand = []
for c in command:
processedCommand.append(self._processCommand(c, event, payload))
else:
processedCommand = self._processCommand(command, event, payload)
self.executeCommand(processedCommand, commandType, debug=debug)
except KeyError:
self._logger.warning("There was an error processing one or more placeholders in the following command: %s" % command)
for command, commandType, debug in self._subscriptions[event]:
try:
if isinstance(command, (tuple, list, set)):
processedCommand = []
for c in command:
processedCommand.append(self._processCommand(c, event, payload))
else:
processedCommand = self._processCommand(command, event, payload)
self.executeCommand(processedCommand, commandType, debug=debug)
except KeyError:
self._logger.warning(
"There was an error processing one or more placeholders in the following command: %s"
% command
)
def executeCommand(self, command, commandType, debug=False):
if commandType == "system":
self._executeSystemCommand(command, debug=debug)
elif commandType == "gcode":
self._executeGcodeCommand(command, debug=debug)
def executeCommand(self, command, commandType, debug=False):
if commandType == "system":
self._executeSystemCommand(command, debug=debug)
elif commandType == "gcode":
self._executeGcodeCommand(command, debug=debug)
def _executeSystemCommand(self, command, debug=False):
def commandExecutioner(cmd):
if debug:
self._logger.info("Executing system command: {}".format(cmd))
else:
self._logger.info("Executing a system command")
# we run this with shell=True since we have to trust whatever
# our admin configured as command and since we want to allow
# shell-alike handling here...
subprocess.check_call(cmd, shell=True)
def _executeSystemCommand(self, command, debug=False):
def commandExecutioner(cmd):
if debug:
self._logger.info("Executing system command: {}".format(cmd))
else:
self._logger.info("Executing a system command")
# we run this with shell=True since we have to trust whatever
# our admin configured as command and since we want to allow
# shell-alike handling here...
subprocess.check_call(cmd, shell=True)
def process():
try:
if isinstance(command, (list, tuple, set)):
for c in command:
commandExecutioner(c)
else:
commandExecutioner(command)
except subprocess.CalledProcessError as e:
if debug:
self._logger.warning("Command failed with return code {}: {}".format(e.returncode, str(e)))
else:
self._logger.warning("Command failed with return code {}, enable debug logging on target 'octoprint.events' for details".format(e.returncode))
except Exception:
self._logger.exception("Command failed")
def process():
try:
if isinstance(command, (list, tuple, set)):
for c in command:
commandExecutioner(c)
else:
commandExecutioner(command)
except subprocess.CalledProcessError as e:
if debug:
self._logger.warning(
"Command failed with return code {}: {}".format(
e.returncode, str(e)
)
)
else:
self._logger.warning(
"Command failed with return code {}, enable debug logging on target 'octoprint.events' for details".format(
e.returncode
)
)
except Exception:
self._logger.exception("Command failed")
t = threading.Thread(target=process)
t.daemon = True
t.start()
t = threading.Thread(target=process)
t.daemon = True
t.start()
def _executeGcodeCommand(self, command, debug=False):
commands = [command]
if isinstance(command, (list, tuple, set)):
commands = list(command)
if debug:
self._logger.info("Executing GCode commands: %r" % command)
self._printer.commands(commands)
def _executeGcodeCommand(self, command, debug=False):
commands = [command]
if isinstance(command, (list, tuple, set)):
commands = list(command)
if debug:
self._logger.info("Executing GCode commands: %r" % command)
self._printer.commands(commands)
def _processCommand(self, command, event, payload):
"""
Performs string substitutions in the command string based on a few current parameters.
def _processCommand(self, command, event, payload):
"""
Performs string substitutions in the command string based on a few current parameters.
The following substitutions are currently supported:
The following substitutions are currently supported:
- {__currentZ} : current Z position of the print head, or -1 if not available
- {__eventname} : the name of the event hook being triggered
- {__filename} : name of currently selected file, or "NO FILE" if no file is selected
- {__filepath} : path in origin location of currently selected file, or "NO FILE" if no file is selected
- {__fileorigin} : origin of currently selected file, or "NO FILE" if no file is selected
- {__progress} : current print progress in percent, 0 if no print is in progress
- {__data} : the string representation of the event's payload
- {__json} : the json representation of the event's payload, "{}" if there is no payload, "" if there was an error on serialization
- {__now} : ISO 8601 representation of the current date and time
- {__currentZ} : current Z position of the print head, or -1 if not available
- {__eventname} : the name of the event hook being triggered
- {__filename} : name of currently selected file, or "NO FILE" if no file is selected
- {__filepath} : path in origin location of currently selected file, or "NO FILE" if no file is selected
- {__fileorigin} : origin of currently selected file, or "NO FILE" if no file is selected
- {__progress} : current print progress in percent, 0 if no print is in progress
- {__data} : the string representation of the event's payload
- {__json} : the json representation of the event's payload, "{}" if there is no payload, "" if there was an error on serialization
- {__now} : ISO 8601 representation of the current date and time
Additionally, the keys of the event's payload can also be used as placeholder.
"""
Additionally, the keys of the event's payload can also be used as placeholder.
"""
json_string = "{}"
if payload:
import json
try:
json_string = json.dumps(payload)
except Exception:
self._logger.exception("JSON: Cannot dump %r", payload)
json_string = ""
json_string = "{}"
if payload:
import json
params = {
"__currentZ": "-1",
"__eventname": event,
"__filename": "NO FILE",
"__filepath": "NO PATH",
"__progress": "0",
"__data": str(payload),
"__json": json_string,
"__now": datetime.datetime.now().isoformat()
}
try:
json_string = json.dumps(payload)
except Exception:
self._logger.exception("JSON: Cannot dump %r", payload)
json_string = ""
currentData = self._printer.get_current_data()
params = {
"__currentZ": "-1",
"__eventname": event,
"__filename": "NO FILE",
"__filepath": "NO PATH",
"__progress": "0",
"__data": str(payload),
"__json": json_string,
"__now": datetime.datetime.now().isoformat(),
}
if "currentZ" in currentData and currentData["currentZ"] is not None:
params["__currentZ"] = str(currentData["currentZ"])
currentData = self._printer.get_current_data()
if "job" in currentData and "file" in currentData["job"] and "name" in currentData["job"]["file"] \
and currentData["job"]["file"]["name"] is not None:
params["__filename"] = currentData["job"]["file"]["name"]
params["__filepath"] = currentData["job"]["file"]["path"]
params["__fileorigin"] = currentData["job"]["file"]["origin"]
if "progress" in currentData and currentData["progress"] is not None \
and "completion" in currentData["progress"] and currentData["progress"]["completion"] is not None:
params["__progress"] = str(round(currentData["progress"]["completion"]))
if "currentZ" in currentData and currentData["currentZ"] is not None:
params["__currentZ"] = str(currentData["currentZ"])
# now add the payload keys as well
if isinstance(payload, dict):
params.update(payload)
if (
"job" in currentData
and "file" in currentData["job"]
and "name" in currentData["job"]["file"]
and currentData["job"]["file"]["name"] is not None
):
params["__filename"] = currentData["job"]["file"]["name"]
params["__filepath"] = currentData["job"]["file"]["path"]
params["__fileorigin"] = currentData["job"]["file"]["origin"]
if (
"progress" in currentData
and currentData["progress"] is not None
and "completion" in currentData["progress"]
and currentData["progress"]["completion"] is not None
):
params["__progress"] = str(round(currentData["progress"]["completion"]))
return command.format(**params)
# now add the payload keys as well
if isinstance(payload, dict):
params.update(payload)
return command.format(**params)
File diff suppressed because it is too large. Load diff
+407 -338
View File
@@ -2,438 +2,507 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
try:
import queue
import queue
except ImportError:
import Queue as queue
import Queue as queue
import collections
import os
import threading
import collections
import time
from octoprint.events import Events, eventManager
from octoprint.settings import settings
from octoprint.util import dict_merge
from octoprint.util import get_fully_qualified_classname as fqcn
from octoprint.util import monotonic_time
from octoprint.util import get_fully_qualified_classname as fqcn, dict_merge
from octoprint.util.platform import CLOSE_FDS
class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile, analysis")):
"""
A :class:`QueueEntry` for processing through the :class:`AnalysisQueue`. Wraps the entry's properties necessary
for processing.
class QueueEntry(
collections.namedtuple(
"QueueEntry",
"name, path, type, location, absolute_path, printer_profile, analysis",
)
):
"""
A :class:`QueueEntry` for processing through the :class:`AnalysisQueue`. Wraps the entry's properties necessary
for processing.
Arguments:
name (str): Name of the file to analyze.
path (str): Storage location specific path to the file to analyze.
type (str): Type of file to analyze, necessary to map to the correct :class:`AbstractAnalysisQueue` sub class.
At the moment, only ``gcode`` is supported here.
location (str): Location the file is located on.
absolute_path (str): Absolute path on disk through which to access the file.
printer_profile (PrinterProfile): :class:`PrinterProfile` which to use for analysis.
analysis (dict): :class:`GcodeAnalysisQueue` results from prior analysis, or ``None`` if there is none.
"""
Arguments:
name (str): Name of the file to analyze.
path (str): Storage location specific path to the file to analyze.
type (str): Type of file to analyze, necessary to map to the correct :class:`AbstractAnalysisQueue` sub class.
At the moment, only ``gcode`` is supported here.
location (str): Location the file is located on.
absolute_path (str): Absolute path on disk through which to access the file.
printer_profile (PrinterProfile): :class:`PrinterProfile` which to use for analysis.
analysis (dict): :class:`GcodeAnalysisQueue` results from prior analysis, or ``None`` if there is none.
"""
def __str__(self):
return "{location}:{path}".format(location=self.location, path=self.path)
def __str__(self):
return "{location}:{path}".format(location=self.location, path=self.path)
class AnalysisAborted(Exception):
def __init__(self, reenqueue=True, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
self.reenqueue = reenqueue
def __init__(self, reenqueue=True, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
self.reenqueue = reenqueue
class AnalysisQueue(object):
"""
OctoPrint's :class:`AnalysisQueue` can manage various :class:`AbstractAnalysisQueue` implementations, mapped
by their machine code type.
"""
OctoPrint's :class:`AnalysisQueue` can manage various :class:`AbstractAnalysisQueue` implementations, mapped
by their machine code type.
By invoking :meth:`register_finish_callback` it is possible to register oneself as a callback to be invoked each
time the analysis of a queue entry finishes. The call parameters will be the finished queue entry as the first
and the analysis result as the second parameter. It is also possible to remove the registration again by invoking
:meth:`unregister_finish_callback`.
By invoking :meth:`register_finish_callback` it is possible to register oneself as a callback to be invoked each
time the analysis of a queue entry finishes. The call parameters will be the finished queue entry as the first
and the analysis result as the second parameter. It is also possible to remove the registration again by invoking
:meth:`unregister_finish_callback`.
:meth:`enqueue` allows enqueuing :class:`QueueEntry` instances to analyze. If the :attr:`QueueEntry.type` is unknown
(no specific child class of :class:`AbstractAnalysisQueue` is registered for it), nothing will happen. Otherwise the
entry will be enqueued with the type specific analysis queue.
"""
:meth:`enqueue` allows enqueuing :class:`QueueEntry` instances to analyze. If the :attr:`QueueEntry.type` is unknown
(no specific child class of :class:`AbstractAnalysisQueue` is registered for it), nothing will happen. Otherwise the
entry will be enqueued with the type specific analysis queue.
"""
def __init__(self, queue_factories):
self._logger = logging.getLogger(__name__)
self._callbacks = []
def __init__(self, queue_factories):
self._logger = logging.getLogger(__name__)
self._callbacks = []
self._queues = {}
for key, queue_factory in queue_factories.items():
self._queues[key] = queue_factory(self._analysis_finished)
self._queues = {}
for key, queue_factory in queue_factories.items():
self._queues[key] = queue_factory(self._analysis_finished)
def register_finish_callback(self, callback):
self._callbacks.append(callback)
def register_finish_callback(self, callback):
self._callbacks.append(callback)
def unregister_finish_callback(self, callback):
self._callbacks.remove(callback)
def unregister_finish_callback(self, callback):
self._callbacks.remove(callback)
def enqueue(self, entry, high_priority=False):
if entry is None:
return False
def enqueue(self, entry, high_priority=False):
if entry is None:
return False
if not entry.type in self._queues:
return False
if entry.type not in self._queues:
return False
self._queues[entry.type].enqueue(entry, high_priority=high_priority)
return True
self._queues[entry.type].enqueue(entry, high_priority=high_priority)
return True
def dequeue(self, entry):
if entry is None:
return False
def dequeue(self, entry):
if entry is None:
return False
if not entry.type in self._queues:
return False
if entry.type not in self._queues:
return False
self._queues[entry.type].dequeue(entry.location, entry.path)
self._queues[entry.type].dequeue(entry.location, entry.path)
def dequeue_folder(self, destination, path):
for q in self._queues.values():
q.dequeue_folder(destination, path)
def dequeue_folder(self, destination, path):
for q in self._queues.values():
q.dequeue_folder(destination, path)
def pause(self):
for q in self._queues.values():
q.pause()
def pause(self):
for q in self._queues.values():
q.pause()
def resume(self):
for q in self._queues.values():
q.resume()
def resume(self):
for q in self._queues.values():
q.resume()
def _analysis_finished(self, entry, result):
for callback in self._callbacks:
try:
callback(entry, result)
except Exception:
self._logger.exception(
"Error while pushing analysis data to callback {}".format(callback),
extra={"callback": fqcn(callback)},
)
eventManager().fire(
Events.METADATA_ANALYSIS_FINISHED,
{
"name": entry.name,
"path": entry.path,
"origin": entry.location,
"result": result,
},
)
def _analysis_finished(self, entry, result):
for callback in self._callbacks:
try:
callback(entry, result)
except:
self._logger.exception(u"Error while pushing analysis data to callback {}".format(callback),
extra={"callback": fqcn(callback)})
eventManager().fire(Events.METADATA_ANALYSIS_FINISHED, {"name": entry.name,
"path": entry.path,
"origin": entry.location,
"result": result})
class AbstractAnalysisQueue(object):
"""
The :class:`AbstractAnalysisQueue` is the parent class of all specific analysis queues such as the
:class:`GcodeAnalysisQueue`. It offers methods to enqueue new entries to analyze and pausing and resuming analysis
processing.
"""
The :class:`AbstractAnalysisQueue` is the parent class of all specific analysis queues such as the
:class:`GcodeAnalysisQueue`. It offers methods to enqueue new entries to analyze and pausing and resuming analysis
processing.
Arguments:
finished_callback (callable): Callback that will be called upon finishing analysis of an entry in the queue.
The callback will be called with the analyzed entry as the first argument and the analysis result as
returned from the queue implementation as the second parameter.
Arguments:
finished_callback (callable): Callback that will be called upon finishing analysis of an entry in the queue.
The callback will be called with the analyzed entry as the first argument and the analysis result as
returned from the queue implementation as the second parameter.
.. automethod:: _do_analysis
.. automethod:: _do_analysis
.. automethod:: _do_abort
"""
.. automethod:: _do_abort
"""
LOW_PRIO = 100
LOW_PRIO_ABORTED = 75
HIGH_PRIO = 50
HIGH_PRIO_ABORTED = 0
LOW_PRIO = 100
LOW_PRIO_ABORTED = 75
HIGH_PRIO = 50
HIGH_PRIO_ABORTED = 0
def __init__(self, finished_callback):
self._logger = logging.getLogger(__name__)
def __init__(self, finished_callback):
self._logger = logging.getLogger(__name__)
self._finished_callback = finished_callback
self._finished_callback = finished_callback
self._active = threading.Event()
self._active.set()
self._active = threading.Event()
self._active.set()
self._done = threading.Event()
self._done.clear()
self._done = threading.Event()
self._done.clear()
self._currentFile = None
self._currentProgress = None
self._currentFile = None
self._currentProgress = None
self._queue = queue.PriorityQueue()
self._current = None
self._current_highprio = False
self._queue = queue.PriorityQueue()
self._current = None
self._current_highprio = False
self._worker = threading.Thread(target=self._work)
self._worker.daemon = True
self._worker.start()
self._worker = threading.Thread(target=self._work)
self._worker.daemon = True
self._worker.start()
def enqueue(self, entry, high_priority=False):
"""
Enqueues an ``entry`` for analysis by the queue.
def enqueue(self, entry, high_priority=False):
"""
Enqueues an ``entry`` for analysis by the queue.
If ``high_priority`` is True (defaults to False), the entry will be prioritized and hence processed before
other entries in the queue with normal priority.
If ``high_priority`` is True (defaults to False), the entry will be prioritized and hence processed before
other entries in the queue with normal priority.
Arguments:
entry (QueueEntry): The :class:`QueueEntry` to analyze.
high_priority (boolean): Whether to process the provided entry with high priority (True) or not
(False, default)
"""
Arguments:
entry (QueueEntry): The :class:`QueueEntry` to analyze.
high_priority (boolean): Whether to process the provided entry with high priority (True) or not
(False, default)
"""
if settings().get(["gcodeAnalysis", "runAt"]) == "never":
self._logger.debug("Ignoring entry {entry} for analysis queue".format(entry=entry))
return
elif high_priority:
self._logger.debug("Adding entry {entry} to analysis queue with high priority".format(entry=entry))
prio = self.__class__.HIGH_PRIO
else:
self._logger.debug("Adding entry {entry} to analysis queue with low priority".format(entry=entry))
prio = self.__class__.LOW_PRIO
if settings().get(["gcodeAnalysis", "runAt"]) == "never":
self._logger.debug(
"Ignoring entry {entry} for analysis queue".format(entry=entry)
)
return
elif high_priority:
self._logger.debug(
"Adding entry {entry} to analysis queue with high priority".format(
entry=entry
)
)
prio = self.__class__.HIGH_PRIO
else:
self._logger.debug(
"Adding entry {entry} to analysis queue with low priority".format(
entry=entry
)
)
prio = self.__class__.LOW_PRIO
self._queue.put((prio, entry, high_priority))
if high_priority and self._current is not None and not self._current_highprio:
self._logger.debug("Aborting current analysis in favor of high priority one")
self._do_abort()
self._queue.put((prio, entry, high_priority))
if high_priority and self._current is not None and not self._current_highprio:
self._logger.debug("Aborting current analysis in favor of high priority one")
self._do_abort()
def dequeue(self, location, path):
if self._current is not None and self._current.location == location \
and self._current.path == path:
self._do_abort(reenqueue=False)
self._done.wait()
self._done.clear()
def dequeue(self, location, path):
if (
self._current is not None
and self._current.location == location
and self._current.path == path
):
self._do_abort(reenqueue=False)
self._done.wait()
self._done.clear()
def dequeue_folder(self, location, path):
if self._current is not None and self._current.location == location \
and self._current.path.startswith(path + "/"):
self._do_abort(reenqueue=False)
self._done.wait()
self._done.clear()
def dequeue_folder(self, location, path):
if (
self._current is not None
and self._current.location == location
and self._current.path.startswith(path + "/")
):
self._do_abort(reenqueue=False)
self._done.wait()
self._done.clear()
def pause(self):
"""
Pauses processing of the queue, e.g. when a print is active.
"""
def pause(self):
"""
Pauses processing of the queue, e.g. when a print is active.
"""
self._logger.debug("Pausing analysis")
self._active.clear()
if self._current is not None:
self._logger.debug("Aborting running analysis, will restart when analyzer is resumed")
self._do_abort()
self._logger.debug("Pausing analysis")
self._active.clear()
if self._current is not None:
self._logger.debug(
"Aborting running analysis, will restart when analyzer is resumed"
)
self._do_abort()
def resume(self):
"""
Resumes processing of the queue, e.g. when a print has finished.
"""
def resume(self):
"""
Resumes processing of the queue, e.g. when a print has finished.
"""
self._logger.debug("Resuming analyzer")
self._active.set()
self._logger.debug("Resuming analyzer")
self._active.set()
def _work(self):
while True:
(priority, entry, high_priority) = self._queue.get()
self._logger.debug("Processing entry {} from queue (priority {})".format(entry, priority))
self._active.wait()
def _work(self):
while True:
(priority, entry, high_priority) = self._queue.get()
self._logger.debug(
"Processing entry {} from queue (priority {})".format(entry, priority)
)
self._active.wait()
try:
self._analyze(entry, high_priority=high_priority)
self._queue.task_done()
self._done.set()
except AnalysisAborted as ex:
if ex.reenqueue:
self._queue.put((self.__class__.HIGH_PRIO_ABORTED if high_priority else self.__class__.LOW_PRIO_ABORTED,
entry,
high_priority))
self._logger.debug("Running analysis of entry {} aborted".format(entry))
self._queue.task_done()
self._done.set()
else:
time.sleep(1.0)
try:
self._analyze(entry, high_priority=high_priority)
self._queue.task_done()
self._done.set()
except AnalysisAborted as ex:
if ex.reenqueue:
self._queue.put(
(
self.__class__.HIGH_PRIO_ABORTED
if high_priority
else self.__class__.LOW_PRIO_ABORTED,
entry,
high_priority,
)
)
self._logger.debug("Running analysis of entry {} aborted".format(entry))
self._queue.task_done()
self._done.set()
else:
time.sleep(1.0)
def _analyze(self, entry, high_priority=False):
path = entry.absolute_path
if path is None or not os.path.exists(path):
return
def _analyze(self, entry, high_priority=False):
path = entry.absolute_path
if path is None or not os.path.exists(path):
return
self._current = entry
self._current_highprio = high_priority
self._current_progress = 0
self._current = entry
self._current_highprio = high_priority
self._current_progress = 0
try:
start_time = monotonic_time()
self._logger.info("Starting analysis of {}".format(entry))
eventManager().fire(Events.METADATA_ANALYSIS_STARTED, {"name": entry.name,
"path": entry.path,
"origin": entry.location,
"type": entry.type})
try:
result = self._do_analysis(high_priority=high_priority)
except TypeError:
result = self._do_analysis()
self._logger.info("Analysis of entry {} finished, needed {:.2f}s".format(entry, monotonic_time() - start_time))
self._finished_callback(self._current, result)
finally:
self._current = None
self._current_progress = None
try:
start_time = monotonic_time()
self._logger.info("Starting analysis of {}".format(entry))
eventManager().fire(
Events.METADATA_ANALYSIS_STARTED,
{
"name": entry.name,
"path": entry.path,
"origin": entry.location,
"type": entry.type,
},
)
try:
result = self._do_analysis(high_priority=high_priority)
except TypeError:
result = self._do_analysis()
self._logger.info(
"Analysis of entry {} finished, needed {:.2f}s".format(
entry, monotonic_time() - start_time
)
)
self._finished_callback(self._current, result)
finally:
self._current = None
self._current_progress = None
def _do_analysis(self, high_priority=False):
"""
Performs the actual analysis of the current entry which can be accessed via ``self._current``. Needs to be
overridden by sub classes.
def _do_analysis(self, high_priority=False):
"""
Performs the actual analysis of the current entry which can be accessed via ``self._current``. Needs to be
overridden by sub classes.
Arguments:
high_priority (bool): Whether the current entry has high priority or not.
Arguments:
high_priority (bool): Whether the current entry has high priority or not.
Returns:
object: The result of the analysis which will be forwarded to the ``finished_callback`` provided during
construction.
"""
return None
Returns:
object: The result of the analysis which will be forwarded to the ``finished_callback`` provided during
construction.
"""
return None
def _do_abort(self, reenqueue=True):
"""
Aborts analysis of the current entry. Needs to be overridden by sub classes.
"""
pass
def _do_abort(self, reenqueue=True):
"""
Aborts analysis of the current entry. Needs to be overridden by sub classes.
"""
pass
class GcodeAnalysisQueue(AbstractAnalysisQueue):
"""
A queue to analyze GCODE files. Analysis results are :class:`dict` instances structured as follows:
"""
A queue to analyze GCODE files. Analysis results are :class:`dict` instances structured as follows:
.. list-table::
:widths: 25 70
.. list-table::
:widths: 25 70
- * **Key**
* **Description**
- * ``estimatedPrintTime``
* Estimated time the file take to print, in seconds
- * ``filament``
* Substructure describing estimated filament usage. Keys are ``tool0`` for the first extruder, ``tool1`` for
the second and so on. For each tool extruded length and volume (based on diameter) are provided.
- * ``filament.toolX.length``
* The extruded length in mm
- * ``filament.toolX.volume``
* The extruded volume in cm³
- * ``printingArea``
* Bounding box of the printed object in the print volume (minimum and maximum coordinates)
- * ``printingArea.minX``
* Minimum X coordinate of the printed object
- * ``printingArea.maxX``
* Maximum X coordinate of the printed object
- * ``printingArea.minY``
* Minimum Y coordinate of the printed object
- * ``printingArea.maxY``
* Maximum Y coordinate of the printed object
- * ``printingArea.minZ``
* Minimum Z coordinate of the printed object
- * ``printingArea.maxZ``
* Maximum Z coordinate of the printed object
- * ``dimensions``
* Dimensions of the printed object in X, Y, Z
- * ``dimensions.width``
* Width of the printed model along the X axis, in mm
- * ``dimensions.depth``
* Depth of the printed model along the Y axis, in mm
- * ``dimensions.height``
* Height of the printed model along the Z axis, in mm
"""
- * **Key**
* **Description**
- * ``estimatedPrintTime``
* Estimated time the file take to print, in seconds
- * ``filament``
* Substructure describing estimated filament usage. Keys are ``tool0`` for the first extruder, ``tool1`` for
the second and so on. For each tool extruded length and volume (based on diameter) are provided.
- * ``filament.toolX.length``
* The extruded length in mm
- * ``filament.toolX.volume``
* The extruded volume in cm³
- * ``printingArea``
* Bounding box of the printed object in the print volume (minimum and maximum coordinates)
- * ``printingArea.minX``
* Minimum X coordinate of the printed object
- * ``printingArea.maxX``
* Maximum X coordinate of the printed object
- * ``printingArea.minY``
* Minimum Y coordinate of the printed object
- * ``printingArea.maxY``
* Maximum Y coordinate of the printed object
- * ``printingArea.minZ``
* Minimum Z coordinate of the printed object
- * ``printingArea.maxZ``
* Maximum Z coordinate of the printed object
- * ``dimensions``
* Dimensions of the printed object in X, Y, Z
- * ``dimensions.width``
* Width of the printed model along the X axis, in mm
- * ``dimensions.depth``
* Depth of the printed model along the Y axis, in mm
- * ``dimensions.height``
* Height of the printed model along the Z axis, in mm
"""
def __init__(self, finished_callback):
AbstractAnalysisQueue.__init__(self, finished_callback)
def __init__(self, finished_callback):
AbstractAnalysisQueue.__init__(self, finished_callback)
self._aborted = False
self._reenqueue = False
self._aborted = False
self._reenqueue = False
def _do_analysis(self, high_priority=False):
import sarge
import sys
import yaml
def _do_analysis(self, high_priority=False):
import sys
if self._current.analysis and all(map(lambda x: x in self._current.analysis, ("printingArea",
"dimensions",
"estimatedPrintTime",
"filament"))):
return self._current.analysis
import sarge
import yaml
try:
throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority \
else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"])
max_extruders = settings().getInt(["gcodeAnalysis", "maxExtruders"])
g90_extruder = settings().getBoolean(["feature", "g90InfluencesExtruder"])
speedx = self._current.printer_profile["axes"]["x"]["speed"]
speedy = self._current.printer_profile["axes"]["y"]["speed"]
offsets = self._current.printer_profile["extruder"]["offsets"]
if self._current.analysis and all(
map(
lambda x: x in self._current.analysis,
("printingArea", "dimensions", "estimatedPrintTime", "filament"),
)
):
return self._current.analysis
command = [sys.executable, "-m", "octoprint", "analysis", "gcode",
"--speed-x={}".format(speedx), "--speed-y={}".format(speedy),
"--max-t={}".format(max_extruders), "--throttle={}".format(throttle),
"--throttle-lines={}".format(throttle_lines)]
for offset in offsets[1:]:
command += ["--offset", str(offset[0]), str(offset[1])]
if g90_extruder:
command += ["--g90-extruder"]
command.append(self._current.absolute_path)
try:
throttle = (
settings().getFloat(["gcodeAnalysis", "throttle_highprio"])
if high_priority
else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
)
throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"])
max_extruders = settings().getInt(["gcodeAnalysis", "maxExtruders"])
g90_extruder = settings().getBoolean(["feature", "g90InfluencesExtruder"])
speedx = self._current.printer_profile["axes"]["x"]["speed"]
speedy = self._current.printer_profile["axes"]["y"]["speed"]
offsets = self._current.printer_profile["extruder"]["offsets"]
self._logger.info("Invoking analysis command: {}".format(" ".join(command)))
command = [
sys.executable,
"-m",
"octoprint",
"analysis",
"gcode",
"--speed-x={}".format(speedx),
"--speed-y={}".format(speedy),
"--max-t={}".format(max_extruders),
"--throttle={}".format(throttle),
"--throttle-lines={}".format(throttle_lines),
]
for offset in offsets[1:]:
command += ["--offset", str(offset[0]), str(offset[1])]
if g90_extruder:
command += ["--g90-extruder"]
command.append(self._current.absolute_path)
self._aborted = False
p = sarge.run(command, close_fds=CLOSE_FDS, async_=True, stdout=sarge.Capture())
self._logger.info("Invoking analysis command: {}".format(" ".join(command)))
while len(p.commands) == 0:
# somewhat ugly... we can't use wait_events because
# the events might not be all set if an exception
# by sarge is triggered within the async process
# thread
time.sleep(0.01)
self._aborted = False
p = sarge.run(
command, close_fds=CLOSE_FDS, async_=True, stdout=sarge.Capture()
)
# by now we should have a command, let's wait for its
# process to have been prepared
p.commands[0].process_ready.wait()
while len(p.commands) == 0:
# somewhat ugly... we can't use wait_events because
# the events might not be all set if an exception
# by sarge is triggered within the async process
# thread
time.sleep(0.01)
if not p.commands[0].process:
# the process might have been set to None in case of any exception
raise RuntimeError("Error while trying to run command {}".format(" ".join(command)))
# by now we should have a command, let's wait for its
# process to have been prepared
p.commands[0].process_ready.wait()
try:
# let's wait for stuff to finish
while p.returncode is None:
if self._aborted:
# oh, we shall abort, let's do so!
p.commands[0].terminate()
raise AnalysisAborted(reenqueue=self._reenqueue)
if not p.commands[0].process:
# the process might have been set to None in case of any exception
raise RuntimeError(
"Error while trying to run command {}".format(" ".join(command))
)
# else continue
p.commands[0].poll()
finally:
p.close()
try:
# let's wait for stuff to finish
while p.returncode is None:
if self._aborted:
# oh, we shall abort, let's do so!
p.commands[0].terminate()
raise AnalysisAborted(reenqueue=self._reenqueue)
output = p.stdout.text
self._logger.debug("Got output: {!r}".format(output))
# else continue
p.commands[0].poll()
finally:
p.close()
if not "RESULTS:" in output:
raise RuntimeError("No analysis result found")
output = p.stdout.text
self._logger.debug("Got output: {!r}".format(output))
_, output = output.split("RESULTS:")
analysis = yaml.safe_load(output)
if "RESULTS:" not in output:
raise RuntimeError("No analysis result found")
result = {}
result["printingArea"] = analysis["printing_area"]
result["dimensions"] = analysis["dimensions"]
if analysis["total_time"]:
result["estimatedPrintTime"] = analysis["total_time"] * 60
if analysis["extrusion_length"]:
result["filament"] = {}
for i in range(len(analysis["extrusion_length"])):
result["filament"]["tool%d" % i] = {
"length": analysis["extrusion_length"][i],
"volume": analysis["extrusion_volume"][i]
}
_, output = output.split("RESULTS:")
analysis = yaml.safe_load(output)
if self._current.analysis and isinstance(self._current.analysis, dict):
return dict_merge(result, self._current.analysis)
else:
return result
finally:
self._gcode = None
result = {}
result["printingArea"] = analysis["printing_area"]
result["dimensions"] = analysis["dimensions"]
if analysis["total_time"]:
result["estimatedPrintTime"] = analysis["total_time"] * 60
if analysis["extrusion_length"]:
result["filament"] = {}
for i in range(len(analysis["extrusion_length"])):
result["filament"]["tool%d" % i] = {
"length": analysis["extrusion_length"][i],
"volume": analysis["extrusion_volume"][i],
}
def _do_abort(self, reenqueue=True):
self._aborted = True
self._reenqueue = reenqueue
if self._current.analysis and isinstance(self._current.analysis, dict):
return dict_merge(result, self._current.analysis)
else:
return result
finally:
self._gcode = None
def _do_abort(self, reenqueue=True):
self._aborted = True
self._reenqueue = reenqueue
+4 -3
View File
@@ -1,9 +1,10 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
class FileDestinations(object):
SDCARD = "sdcard"
LOCAL = "local"
SDCARD = "sdcard"
LOCAL = "local"
File diff suppressed because it is too large. Load diff
+197 -190
View File
@@ -2,7 +2,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import io
@@ -11,247 +11,254 @@ import os
from octoprint import UMASK
from octoprint.util import atomic_write
class AbstractFileWrapper(object):
"""
Wrapper for file representations to save to storages.
"""
Wrapper for file representations to save to storages.
Arguments:
filename (str): The file's name
"""
Arguments:
filename (str): The file's name
"""
DEFAULT_PERMISSIONS = 0o664
DEFAULT_PERMISSIONS = 0o664
def __init__(self, filename):
self.filename = filename
def __init__(self, filename):
self.filename = filename
def save(self, path, permissions=None):
"""
Saves the file's content to the given absolute path.
def save(self, path, permissions=None):
"""
Saves the file's content to the given absolute path.
Arguments:
path (str): The absolute path to where to save the file
permissions (int): The permissions to set on the file
"""
raise NotImplementedError()
Arguments:
path (str): The absolute path to where to save the file
permissions (int): The permissions to set on the file
"""
raise NotImplementedError()
def stream(self):
"""
Returns a Python stream object (subclass of io.IOBase) representing the file's contents.
def stream(self):
"""
Returns a Python stream object (subclass of io.IOBase) representing the file's contents.
Returns:
io.IOBase: The file's contents as a stream.
"""
raise NotImplementedError()
Returns:
io.IOBase: The file's contents as a stream.
"""
raise NotImplementedError()
class DiskFileWrapper(AbstractFileWrapper):
"""
An implementation of :class:`.AbstractFileWrapper` that wraps an actual file on disk. The `save` implementations
will either copy the file to the new path (preserving file attributes) or -- if `move` is `True` (the default) --
move the file.
"""
An implementation of :class:`.AbstractFileWrapper` that wraps an actual file on disk. The `save` implementations
will either copy the file to the new path (preserving file attributes) or -- if `move` is `True` (the default) --
move the file.
Arguments:
filename (str): The file's name
path (str): The file's absolute path
move (boolean): Whether to move the file upon saving (True, default) or copying.
"""
Arguments:
filename (str): The file's name
path (str): The file's absolute path
move (boolean): Whether to move the file upon saving (True, default) or copying.
"""
def __init__(self, filename, path, move=True):
AbstractFileWrapper.__init__(self, filename)
self.path = path
self.move = move
def __init__(self, filename, path, move=True):
AbstractFileWrapper.__init__(self, filename)
self.path = path
self.move = move
def save(self, path, permissions=None):
import shutil
def save(self, path, permissions=None):
import shutil
if self.move:
shutil.move(self.path, path)
else:
shutil.copy2(self.path, path)
if self.move:
shutil.move(self.path, path)
else:
shutil.copy2(self.path, path)
if permissions is None:
permissions = self.DEFAULT_PERMISSIONS & ~UMASK
os.chmod(path, permissions)
if permissions is None:
permissions = self.DEFAULT_PERMISSIONS & ~UMASK
os.chmod(path, permissions)
def stream(self):
return io.open(self.path, "rb")
def stream(self):
return io.open(self.path, 'rb')
class StreamWrapper(AbstractFileWrapper):
"""
A wrapper allowing processing of one or more consecutive streams.
"""
A wrapper allowing processing of one or more consecutive streams.
Arguments:
*streams: One or more :py:`io.IOBase` streams to process one after another to save to storage.
"""
def __init__(self, filename, *streams):
if not len(streams) > 0:
raise ValueError("Need at least one stream to wrap")
Arguments:
*streams: One or more :py:`io.IOBase` streams to process one after another to save to storage.
"""
AbstractFileWrapper.__init__(self, filename)
self.streams = streams
def __init__(self, filename, *streams):
if not len(streams) > 0:
raise ValueError("Need at least one stream to wrap")
def save(self, path, permissions=None):
"""
Will dump the contents of all streams provided during construction into the target file, in the order they were
provided.
"""
import shutil
AbstractFileWrapper.__init__(self, filename)
self.streams = streams
with atomic_write(path, mode='wb') as dest:
for source in self.streams:
shutil.copyfileobj(source, dest)
if permissions is None:
permissions = self.DEFAULT_PERMISSIONS & ~UMASK
os.chmod(path, permissions)
def save(self, path, permissions=None):
"""
Will dump the contents of all streams provided during construction into the target file, in the order they were
provided.
"""
import shutil
with atomic_write(path, mode="wb") as dest:
for source in self.streams:
shutil.copyfileobj(source, dest)
if permissions is None:
permissions = self.DEFAULT_PERMISSIONS & ~UMASK
os.chmod(path, permissions)
def stream(self):
"""
If more than one stream was provided to the constructor, will return a :class:`.MultiStream` wrapping all
provided streams in the order they were provided, else the first and only stream is returned directly.
"""
if len(self.streams) > 1:
return MultiStream(*self.streams)
else:
return self.streams[0]
def stream(self):
"""
If more than one stream was provided to the constructor, will return a :class:`.MultiStream` wrapping all
provided streams in the order they were provided, else the first and only stream is returned directly.
"""
if len(self.streams) > 1:
return MultiStream(*self.streams)
else:
return self.streams[0]
class MultiStream(io.RawIOBase):
"""
A stream implementation which when read reads from multiple streams, one after the other, basically concatenating
their contents in the order they are provided to the constructor.
"""
A stream implementation which when read reads from multiple streams, one after the other, basically concatenating
their contents in the order they are provided to the constructor.
Arguments:
*streams: One or more :py:`io.IOBase` streams to concatenate.
"""
def __init__(self, *streams):
io.RawIOBase.__init__(self)
self.streams = streams
self.current_stream = 0
Arguments:
*streams: One or more :py:`io.IOBase` streams to concatenate.
"""
def read(self, n=-1):
if n == 0:
return b''
def __init__(self, *streams):
io.RawIOBase.__init__(self)
self.streams = streams
self.current_stream = 0
if len(self.streams) == 0:
return b''
def read(self, n=-1):
if n == 0:
return b""
while self.current_stream < len(self.streams):
stream = self.streams[self.current_stream]
if len(self.streams) == 0:
return b""
result = stream.read(n)
if result is None or len(result) != 0:
return result
else:
self.current_stream += 1
while self.current_stream < len(self.streams):
stream = self.streams[self.current_stream]
return b''
result = stream.read(n)
if result is None or len(result) != 0:
return result
else:
self.current_stream += 1
def readinto(self, b):
n = len(b)
read = self.read(n)
b[:len(read)] = read
return len(read)
return b""
def close(self):
for stream in self.streams:
try:
stream.close()
except Exception:
pass
def readinto(self, b):
n = len(b)
read = self.read(n)
b[: len(read)] = read
return len(read)
def readable(self, *args, **kwargs):
return True
def close(self):
for stream in self.streams:
try:
stream.close()
except Exception:
pass
def seekable(self, *args, **kwargs):
return False
def readable(self, *args, **kwargs):
return True
def seekable(self, *args, **kwargs):
return False
def writable(self, *args, **kwargs):
return False
def writable(self, *args, **kwargs):
return False
class LineProcessorStream(io.RawIOBase):
"""
While reading from this stream the provided `input_stream` is read line by line, calling the (overridable) method
:meth:`.process_line` for each read line.
"""
While reading from this stream the provided `input_stream` is read line by line, calling the (overridable) method
:meth:`.process_line` for each read line.
Sub classes can thus modify the contents of the `input_stream` in line, while it is being read. Keep in mind that
``process_line`` will receive the line as a byte stream - if underlying code needs to operate on unicode you'll need
to do the decoding yourself.
Sub classes can thus modify the contents of the `input_stream` in line, while it is being read. Keep in mind that
``process_line`` will receive the line as a byte stream - if underlying code needs to operate on unicode you'll need
to do the decoding yourself.
Arguments:
input_stream (io.RawIOBase): The stream to process on the fly.
"""
Arguments:
input_stream (io.RawIOBase): The stream to process on the fly.
"""
def __init__(self, input_stream):
io.RawIOBase.__init__(self)
self.input_stream = io.BufferedReader(input_stream)
self.leftover = bytearray()
def __init__(self, input_stream):
io.RawIOBase.__init__(self)
self.input_stream = io.BufferedReader(input_stream)
self.leftover = bytearray()
def read(self, n=-1):
if n == 0:
return b''
def read(self, n=-1):
if n == 0:
return b""
result = bytearray()
while len(result) < n or n == -1:
# add left over from previous loop
bytes_left = (n - len(result)) if n != -1 else -1
if bytes_left != -1 and bytes_left < len(self.leftover):
# only s
result += self.leftover[:bytes_left]
self.leftover = self.leftover[bytes_left:]
break
else:
result += self.leftover
self.leftover = bytearray()
result = bytearray()
while len(result) < n or n == -1:
# add left over from previous loop
bytes_left = (n - len(result)) if n != -1 else -1
if bytes_left != -1 and bytes_left < len(self.leftover):
# only s
result += self.leftover[:bytes_left]
self.leftover = self.leftover[bytes_left:]
break
else:
result += self.leftover
self.leftover = bytearray()
# read one line from the underlying stream
processed_line = None
while processed_line is None:
line = self.input_stream.readline()
if not line:
break
processed_line = self.process_line(line)
if processed_line is None:
break
# read one line from the underlying stream
processed_line = None
while processed_line is None:
line = self.input_stream.readline()
if not line:
break
processed_line = self.process_line(line)
if processed_line is None:
break
bytes_left = (n - len(result)) if n != -1 else -1
if bytes_left != -1 and bytes_left < len(processed_line):
result += processed_line[:bytes_left]
self.leftover = processed_line[bytes_left:]
break
else:
result += processed_line
bytes_left = (n - len(result)) if n != -1 else -1
if bytes_left != -1 and bytes_left < len(processed_line):
result += processed_line[:bytes_left]
self.leftover = processed_line[bytes_left:]
break
else:
result += processed_line
return bytes(result)
return bytes(result)
def readinto(self, b):
n = len(b)
read = self.read(n)
b[:len(read)] = read
return len(read)
def readinto(self, b):
n = len(b)
read = self.read(n)
b[: len(read)] = read
return len(read)
def process_line(self, line):
"""
Called from the `read` Method of this stream with each line read from `self.input_stream`.
def process_line(self, line):
"""
Called from the `read` Method of this stream with each line read from `self.input_stream`.
By returning ``None`` the line will not be returned from the read stream, effectively being stripped from the
wrapper `input_stream`.
By returning ``None`` the line will not be returned from the read stream, effectively being stripped from the
wrapper `input_stream`.
Arguments:
line (bytes): The line as read from `self.input_stream` in byte representation (str under Python 2 and
bytes under Python 3)
Arguments:
line (bytes): The line as read from `self.input_stream` in byte representation (str under Python 2 and
bytes under Python 3)
Returns:
bytes or None: The processed version of the line (might also be multiple lines), or None if the line is to be
stripped from the processed stream.
"""
return line
Returns:
bytes or None: The processed version of the line (might also be multiple lines), or None if the line is to be
stripped from the processed stream.
"""
return line
def close(self):
self.input_stream.close()
def close(self):
self.input_stream.close()
def readable(self, *args, **kwargs):
return True
def readable(self, *args, **kwargs):
return True
def seekable(self, *args, **kwargs):
return False
def seekable(self, *args, **kwargs):
return False
def writable(self, *args, **kwargs):
return False
def writable(self, *args, **kwargs):
return False
+129 -122
View File
@@ -1,159 +1,166 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from past.builtins import basestring, unicode
from octoprint.logging import handlers
from typing import Union
from past.builtins import basestring, unicode
from octoprint.logging import handlers # noqa: F401
def log_to_handler(logger, handler, level, msg, exc_info=None, extra=None, *args):
"""
Logs to the provided handler only.
"""
Logs to the provided handler only.
Arguments:
logger: logger to log to
handler: handler to restrict logging to
level: level to log at
msg: message to log
exc_info: optional exception info
extra: optional extra data
*args: log args
"""
import sys
try:
from logging import _srcfile
except ImportError:
_srcfile = None
Arguments:
logger: logger to log to
handler: handler to restrict logging to
level: level to log at
msg: message to log
exc_info: optional exception info
extra: optional extra data
*args: log args
"""
import sys
# this is just the same as logging.Logger._log
try:
from logging import _srcfile
except ImportError:
_srcfile = None
if _srcfile:
# IronPython doesn't track Python frames, so findCaller raises an
# exception on some versions of IronPython. We trap it here so that
# IronPython can use logging.
try:
fn, lno, func = logger.findCaller()
except ValueError:
fn, lno, func = "(unknown file)", 0, "(unknown function)"
else:
fn, lno, func = "(unknown file)", 0, "(unknown function)"
if exc_info:
if not isinstance(exc_info, tuple):
exc_info = sys.exc_info()
# this is just the same as logging.Logger._log
record = logger.makeRecord(logger.name, level, fn, lno, msg, args, exc_info, func, extra)
if _srcfile:
# IronPython doesn't track Python frames, so findCaller raises an
# exception on some versions of IronPython. We trap it here so that
# IronPython can use logging.
try:
fn, lno, func = logger.findCaller()
except ValueError:
fn, lno, func = "(unknown file)", 0, "(unknown function)"
else:
fn, lno, func = "(unknown file)", 0, "(unknown function)"
if exc_info:
if not isinstance(exc_info, tuple):
exc_info = sys.exc_info()
# and this is a mixture of logging.Logger.handle and logging.Logger.callHandlers
record = logger.makeRecord(
logger.name, level, fn, lno, msg, args, exc_info, func, extra
)
if (not logger.disabled) and logger.filter(record):
if record.levelno >= handler.level:
handler.handle(record)
# and this is a mixture of logging.Logger.handle and logging.Logger.callHandlers
if (not logger.disabled) and logger.filter(record):
if record.levelno >= handler.level:
handler.handle(record)
def get_handler(name, logger=None):
"""
Retrieves the handler named ``name``.
"""
Retrieves the handler named ``name``.
If optional ``logger`` is provided, search will be
limited to that logger, otherwise the root logger will be
searched.
If optional ``logger`` is provided, search will be
limited to that logger, otherwise the root logger will be
searched.
Arguments:
name: the name of the handler to look for
logger: (optional) the logger to search in, root logger if not provided
Arguments:
name: the name of the handler to look for
logger: (optional) the logger to search in, root logger if not provided
Returns:
the handler if it could be found, None otherwise
"""
import logging
Returns:
the handler if it could be found, None otherwise
"""
import logging
if logger is None:
logger = logging.getLogger()
if logger is None:
logger = logging.getLogger()
for handler in logger.handlers:
if handler.get_name() == name:
return handler
for handler in logger.handlers:
if handler.get_name() == name:
return handler
return None
return None
def get_divider_line(c, message=None, length=78, indent=3):
"""
Generate a divider line for logging, optionally with included message.
"""
Generate a divider line for logging, optionally with included message.
Examples:
Examples:
>>> get_divider_line("-") # doctest: +ALLOW_UNICODE
'------------------------------------------------------------------------------'
>>> get_divider_line("=", length=10) # doctest: +ALLOW_UNICODE
'=========='
>>> get_divider_line("-", message="Hi", length=10) # doctest: +ALLOW_UNICODE
'--- Hi ---'
>>> get_divider_line("-", message="A slightly longer text") # doctest: +ALLOW_UNICODE
'--- A slightly longer text ---------------------------------------------------'
>>> get_divider_line("-", message="A slightly longer text", indent=5) # doctest: +ALLOW_UNICODE
'----- A slightly longer text -------------------------------------------------'
>>> get_divider_line("-", message="Hello World!", length=10) # doctest: +ALLOW_UNICODE
'--- Hello World!'
>>> get_divider_line(None)
Traceback (most recent call last):
...
AssertionError: c is not text
>>> get_divider_line("´`")
Traceback (most recent call last):
...
AssertionError: c is not a single character
>>> get_divider_line("-", message=3)
Traceback (most recent call last):
...
AssertionError: message is not text
>>> get_divider_line("-", length="hello")
Traceback (most recent call last):
...
AssertionError: length is not an int
>>> get_divider_line("-", indent="hi")
Traceback (most recent call last):
...
AssertionError: indent is not an int
>>> get_divider_line("-") # doctest: +ALLOW_UNICODE
'------------------------------------------------------------------------------'
>>> get_divider_line("=", length=10) # doctest: +ALLOW_UNICODE
'=========='
>>> get_divider_line("-", message="Hi", length=10) # doctest: +ALLOW_UNICODE
'--- Hi ---'
>>> get_divider_line("-", message="A slightly longer text") # doctest: +ALLOW_UNICODE
'--- A slightly longer text ---------------------------------------------------'
>>> get_divider_line("-", message="A slightly longer text", indent=5) # doctest: +ALLOW_UNICODE
'----- A slightly longer text -------------------------------------------------'
>>> get_divider_line("-", message="Hello World!", length=10) # doctest: +ALLOW_UNICODE
'--- Hello World!'
>>> get_divider_line(None)
Traceback (most recent call last):
...
AssertionError: c is not text
>>> get_divider_line("´`")
Traceback (most recent call last):
...
AssertionError: c is not a single character
>>> get_divider_line("-", message=3)
Traceback (most recent call last):
...
AssertionError: message is not text
>>> get_divider_line("-", length="hello")
Traceback (most recent call last):
...
AssertionError: length is not an int
>>> get_divider_line("-", indent="hi")
Traceback (most recent call last):
...
AssertionError: indent is not an int
Arguments:
c: character to use for the line
message: message to print in the line
length: length of the line
indent: indentation of message in line
Arguments:
c: character to use for the line
message: message to print in the line
length: length of the line
indent: indentation of message in line
Returns:
formatted divider line
"""
Returns:
formatted divider line
"""
assert isinstance(c, basestring), "c is not text"
assert len(c) == 1, "c is not a single character"
assert isinstance(length, int), "length is not an int"
assert isinstance(indent, int), "indent is not an int"
assert isinstance(c, basestring), "c is not text"
assert len(c) == 1, "c is not a single character"
assert isinstance(length, int), "length is not an int"
assert isinstance(indent, int), "indent is not an int"
if message is None:
return c * length
if message is None:
return c * length
assert isinstance(message, basestring), "message is not text"
assert isinstance(message, basestring), "message is not text"
space = length - 2 * (indent + 1)
if space >= len(message):
return c * indent + " " + message + " " + c * (length - indent - 2 - len(message))
else:
return c * indent + " " + message
space = length - 2 * (indent + 1)
if space >= len(message):
return c * indent + " " + message + " " + c * (length - indent - 2 - len(message))
else:
return c * indent + " " + message
def prefix_multilines(text, prefix=u": "):
# type: (Union[unicode, bytes], unicode) -> unicode
from octoprint.util import to_unicode
def prefix_multilines(text, prefix=": "):
# type: (Union[unicode, bytes], unicode) -> unicode
from octoprint.util import to_unicode
lines = text.splitlines()
if not lines:
return u""
lines = text.splitlines()
if not lines:
return ""
if len(lines) == 1:
return to_unicode(lines[0])
if len(lines) == 1:
return to_unicode(lines[0])
return to_unicode(lines[0]) + u"\n" + u"\n".join(map(lambda line: prefix + to_unicode(line),
lines[1:]))
return (
to_unicode(lines[0])
+ "\n"
+ "\n".join(map(lambda line: prefix + to_unicode(line), lines[1:]))
)
+134 -134
View File
@@ -1,196 +1,196 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
# noinspection PyCompatibility
import concurrent.futures
import logging.handlers
import os
import re
import time
# noinspection PyCompatibility
import concurrent.futures
class AsyncLogHandlerMixin(logging.Handler):
def __init__(self, *args, **kwargs):
self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
super(AsyncLogHandlerMixin, self).__init__(*args, **kwargs)
def __init__(self, *args, **kwargs):
self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
super(AsyncLogHandlerMixin, self).__init__(*args, **kwargs)
def emit(self, record):
if getattr(self._executor, "_shutdown", False):
return
def emit(self, record):
if getattr(self._executor, "_shutdown", False):
return
try:
self._executor.submit(self._emit, record)
except Exception:
self.handleError(record)
try:
self._executor.submit(self._emit, record)
except Exception:
self.handleError(record)
def _emit(self, record):
# noinspection PyUnresolvedReferences
super(AsyncLogHandlerMixin, self).emit(record)
def _emit(self, record):
# noinspection PyUnresolvedReferences
super(AsyncLogHandlerMixin, self).emit(record)
def close(self):
self._executor.shutdown(wait=True)
super(AsyncLogHandlerMixin, self).close()
def close(self):
self._executor.shutdown(wait=True)
super(AsyncLogHandlerMixin, self).close()
class CleaningTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):
def __init__(self, *args, **kwargs):
kwargs["encoding"] = kwargs.get("encoding", "utf-8")
def __init__(self, *args, **kwargs):
kwargs["encoding"] = kwargs.get("encoding", "utf-8")
super(CleaningTimedRotatingFileHandler, self).__init__(*args, **kwargs)
super(CleaningTimedRotatingFileHandler, self).__init__(*args, **kwargs)
# clean up old files on handler start
if self.backupCount > 0:
for s in self.getFilesToDelete():
os.remove(s)
# clean up old files on handler start
if self.backupCount > 0:
for s in self.getFilesToDelete():
os.remove(s)
class OctoPrintLogHandler(AsyncLogHandlerMixin, CleaningTimedRotatingFileHandler):
rollover_callbacks = []
rollover_callbacks = []
def __init__(self, *args, **kwargs):
kwargs["encoding"] = kwargs.get("encoding", "utf-8")
super(OctoPrintLogHandler, self).__init__(*args, **kwargs)
def __init__(self, *args, **kwargs):
kwargs["encoding"] = kwargs.get("encoding", "utf-8")
super(OctoPrintLogHandler, self).__init__(*args, **kwargs)
@classmethod
def registerRolloverCallback(cls, callback, *args, **kwargs):
cls.rollover_callbacks.append((callback, args, kwargs))
@classmethod
def registerRolloverCallback(cls, callback, *args, **kwargs):
cls.rollover_callbacks.append((callback, args, kwargs))
def doRollover(self):
super(OctoPrintLogHandler, self).doRollover()
def doRollover(self):
super(OctoPrintLogHandler, self).doRollover()
for rcb in self.rollover_callbacks:
callback, args, kwargs = rcb
callback(*args, **kwargs)
for rcb in self.rollover_callbacks:
callback, args, kwargs = rcb
callback(*args, **kwargs)
class OctoPrintStreamHandler(AsyncLogHandlerMixin, logging.StreamHandler):
pass
pass
class TriggeredRolloverLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFileHandler):
class TriggeredRolloverLogHandler(
AsyncLogHandlerMixin, logging.handlers.RotatingFileHandler
):
do_rollover = False
suffix_template = "%Y-%m-%d_%H-%M-%S"
file_pattern = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$")
do_rollover = False
suffix_template = "%Y-%m-%d_%H-%M-%S"
file_pattern = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$")
@classmethod
def arm_rollover(cls):
cls.do_rollover = True
@classmethod
def arm_rollover(cls):
cls.do_rollover = True
def __init__(self, *args, **kwargs):
kwargs["encoding"] = kwargs.get("encoding", "utf-8")
super(TriggeredRolloverLogHandler, self).__init__(*args, **kwargs)
self.cleanupFiles()
def __init__(self, *args, **kwargs):
kwargs["encoding"] = kwargs.get("encoding", "utf-8")
super(TriggeredRolloverLogHandler, self).__init__(*args, **kwargs)
self.cleanupFiles()
def shouldRollover(self, record):
return self.do_rollover
def shouldRollover(self, record):
return self.do_rollover
def getFilesToDelete(self):
"""
Determine the files to delete when rolling over.
"""
dirName, baseName = os.path.split(self.baseFilename)
fileNames = os.listdir(dirName)
result = []
prefix = baseName + "."
plen = len(prefix)
for fileName in fileNames:
if fileName[:plen] == prefix:
suffix = fileName[plen:]
if type(self).file_pattern.match(suffix):
result.append(os.path.join(dirName, fileName))
result.sort()
if len(result) < self.backupCount:
result = []
else:
result = result[:len(result) - self.backupCount]
return result
def getFilesToDelete(self):
"""
Determine the files to delete when rolling over.
"""
dirName, baseName = os.path.split(self.baseFilename)
fileNames = os.listdir(dirName)
result = []
prefix = baseName + "."
plen = len(prefix)
for fileName in fileNames:
if fileName[:plen] == prefix:
suffix = fileName[plen:]
if type(self).file_pattern.match(suffix):
result.append(os.path.join(dirName, fileName))
result.sort()
if len(result) < self.backupCount:
result = []
else:
result = result[: len(result) - self.backupCount]
return result
def cleanupFiles(self):
if self.backupCount > 0:
for path in self.getFilesToDelete():
os.remove(path)
def cleanupFiles(self):
if self.backupCount > 0:
for path in self.getFilesToDelete():
os.remove(path)
def doRollover(self):
self.do_rollover = False
def doRollover(self):
self.do_rollover = False
if self.stream:
self.stream.close()
self.stream = None
if self.stream:
self.stream.close()
self.stream = None
if os.path.exists(self.baseFilename):
# figure out creation date/time to use for file suffix
t = time.localtime(os.stat(self.baseFilename).st_mtime)
dfn = self.baseFilename + "." + time.strftime(type(self).suffix_template, t)
if os.path.exists(dfn):
os.remove(dfn)
os.rename(self.baseFilename, dfn)
if os.path.exists(self.baseFilename):
# figure out creation date/time to use for file suffix
t = time.localtime(os.stat(self.baseFilename).st_mtime)
dfn = self.baseFilename + "." + time.strftime(type(self).suffix_template, t)
if os.path.exists(dfn):
os.remove(dfn)
os.rename(self.baseFilename, dfn)
self.cleanupFiles()
if not self.delay:
self.stream = self._open()
self.cleanupFiles()
if not self.delay:
self.stream = self._open()
class SerialLogHandler(TriggeredRolloverLogHandler):
pass
pass
class PluginTimingsLogHandler(TriggeredRolloverLogHandler):
pass
pass
class RecordingLogHandler(logging.Handler):
def __init__(self, target=None, *args, **kwargs):
super(RecordingLogHandler, self).__init__(*args, **kwargs)
self._buffer = []
self._target = target
def __init__(self, target=None, *args, **kwargs):
super(RecordingLogHandler, self).__init__(*args, **kwargs)
self._buffer = []
self._target = target
def emit(self, record):
self._buffer.append(record)
def emit(self, record):
self._buffer.append(record)
def setTarget(self, target):
self._target = target
def setTarget(self, target):
self._target = target
def flush(self):
if not self._target:
return
def flush(self):
if not self._target:
return
self.acquire()
try:
for record in self._buffer:
self._target.handle(record)
self._buffer = []
finally:
self.release()
self.acquire()
try:
for record in self._buffer:
self._target.handle(record)
self._buffer = []
finally:
self.release()
def close(self):
self.flush()
self.acquire()
try:
self._buffer = []
finally:
self.release()
def close(self):
self.flush()
self.acquire()
try:
self._buffer = []
finally:
self.release()
def __len__(self):
return len(self._buffer)
def __len__(self):
return len(self._buffer)
# noinspection PyAbstractClass
class CombinedLogHandler(logging.Handler):
def __init__(self, *handlers):
logging.Handler.__init__(self)
self._handlers = handlers
def __init__(self, *handlers):
logging.Handler.__init__(self)
self._handlers = handlers
def setHandlers(self, *handlers):
self._handlers = handlers
def setHandlers(self, *handlers):
self._handlers = handlers
def handle(self, record):
self.acquire()
try:
if self._handlers:
for handler in self._handlers:
handler.handle(record)
finally:
self.release()
def handle(self, record):
self.acquire()
try:
if self._handlers:
for handler in self._handlers:
handler.handle(record)
finally:
self.release()
File diff suppressed because it is too large. Load diff
+2321 -1864
View File
File diff suppressed because it is too large. Load diff
+1858 -1794
View File
File diff suppressed because it is too large. Load diff
@@ -1,132 +1,151 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License"
import octoprint.plugin
from octoprint.access import USER_GROUP
from octoprint.access.permissions import Permissions
from octoprint.events import Events
import time
import flask
from flask_babel import gettext
import time
import octoprint.plugin
from octoprint.access import USER_GROUP
from octoprint.access.permissions import Permissions
from octoprint.events import Events
class ActionCommandNotificationPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.EventHandlerPlugin):
def __init__(self):
self._notifications = []
class ActionCommandNotificationPlugin(
octoprint.plugin.AssetPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.EventHandlerPlugin,
):
def __init__(self):
self._notifications = []
# Additional permissions hook
# Additional permissions hook
def get_additional_permissions(self):
return [
{"key": "SHOW",
"name": "Show printer notifications",
"description": gettext("Allows to see printer notifications"),
"default_groups": [USER_GROUP],
"roles": ["show"]},
{"key": "CLEAR",
"name": "Clear printer notifications",
"description": gettext("Allows to clear printer notifications"),
"default_groups": [USER_GROUP],
"roles": ["clear"]}
]
def get_additional_permissions(self):
return [
{
"key": "SHOW",
"name": "Show printer notifications",
"description": gettext("Allows to see printer notifications"),
"default_groups": [USER_GROUP],
"roles": ["show"],
},
{
"key": "CLEAR",
"name": "Clear printer notifications",
"description": gettext("Allows to clear printer notifications"),
"default_groups": [USER_GROUP],
"roles": ["clear"],
},
]
#~ AssetPlugin
# ~ AssetPlugin
def get_assets(self):
return {"js": ["js/action_command_notification.js"],
"clientjs": ["clientjs/action_command_notification.js"],
"css": ["css/action_command_notification.css"]}
def get_assets(self):
return {
"js": ["js/action_command_notification.js"],
"clientjs": ["clientjs/action_command_notification.js"],
"css": ["css/action_command_notification.css"],
}
#~ EventHandlerPlugin
# ~ EventHandlerPlugin
def on_event(self, event, payload):
if event == Events.DISCONNECTED:
self._clear_notifications()
def on_event(self, event, payload):
if event == Events.DISCONNECTED:
self._clear_notifications()
#~ SettingsPlugin
# ~ SettingsPlugin
def get_settings_defaults(self):
return {"enable": True,
"enable_popups": False}
def get_settings_defaults(self):
return {"enable": True, "enable_popups": False}
#~ SimpleApiPlugin
# ~ SimpleApiPlugin
def on_api_get(self, request):
if not Permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW.can():
return flask.abort(403, "Insufficient permissions")
return flask.jsonify(notifications=[{"timestamp": notification[0],
"message": notification[1]} for notification in self._notifications])
def on_api_get(self, request):
if not Permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW.can():
return flask.abort(403, "Insufficient permissions")
return flask.jsonify(
notifications=[
{"timestamp": notification[0], "message": notification[1]}
for notification in self._notifications
]
)
def get_api_commands(self):
return {"clear": []}
def get_api_commands(self):
return {"clear": []}
def on_api_command(self, command, data):
if command == "clear":
if not Permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_CLEAR.can():
return flask.abort(403, "Insufficient permissions")
self._clear_notifications()
def on_api_command(self, command, data):
if command == "clear":
if not Permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_CLEAR.can():
return flask.abort(403, "Insufficient permissions")
self._clear_notifications()
#~ TemplatePlugin
# ~ TemplatePlugin
def get_template_configs(self):
return [
{"type": "settings",
"name": gettext("Printer Notifications"),
"custom_bindings": False},
{"type": "sidebar",
"name": gettext("Printer Notifications"),
"icon": "bell-o",
"styles_wrapper": ["display: none"],
"data_bind": "visible: loginState.hasPermissionKo(access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW)"
" && settings.settings.plugins.action_command_notification.enable()"}
]
def get_template_configs(self):
return [
{
"type": "settings",
"name": gettext("Printer Notifications"),
"custom_bindings": False,
},
{
"type": "sidebar",
"name": gettext("Printer Notifications"),
"icon": "bell-o",
"styles_wrapper": ["display: none"],
"data_bind": "visible: loginState.hasPermissionKo(access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW)"
" && settings.settings.plugins.action_command_notification.enable()",
},
]
#~ action command handler
# ~ action command handler
def action_command_handler(self, comm, line, action, *args, **kwargs):
if not self._settings.get_boolean(["enable"]):
return
def action_command_handler(self, comm, line, action, *args, **kwargs):
if not self._settings.get_boolean(["enable"]):
return
parts = action.split(None, 1)
if len(parts) == 1:
action = parts[0]
parameter = ""
else:
action, parameter = parts
parts = action.split(None, 1)
if len(parts) == 1:
action = parts[0]
parameter = ""
else:
action, parameter = parts
if action != "notification":
return
if action != "notification":
return
message = parameter.strip()
self._notifications.append((time.time(), message))
self._plugin_manager.send_plugin_message(self._identifier, {"message": message})
message = parameter.strip()
self._notifications.append((time.time(), message))
self._plugin_manager.send_plugin_message(self._identifier, {"message": message})
self._logger.info("Got a notification: {}".format(message))
self._logger.info("Got a notification: {}".format(message))
def _clear_notifications(self):
self._notifications = []
self._plugin_manager.send_plugin_message(self._identifier, {})
self._logger.info("Notifications cleared")
def _clear_notifications(self):
self._notifications = []
self._plugin_manager.send_plugin_message(self._identifier, {})
self._logger.info("Notifications cleared")
__plugin_name__ = "Action Command Notification Support"
__plugin_description__ = "Allows your printer to trigger notifications via action commands on the connection"
__plugin_description__ = (
"Allows your printer to trigger notifications via action commands on the connection"
)
__plugin_author__ = "Gina Häußge"
__plugin_disabling_discouraged__ = gettext("Without this plugin your printer will no longer be able to trigger"
" notifications in OctoPrint")
__plugin_disabling_discouraged__ = gettext(
"Without this plugin your printer will no longer be able to trigger"
" notifications in OctoPrint"
)
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = ActionCommandNotificationPlugin()
__plugin_hooks__ = {
"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions,
}
@@ -4,19 +4,30 @@
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var OctoPrintActionCommandNotificationClient = function(base) {
})(this, function (OctoPrintClient) {
var OctoPrintActionCommandNotificationClient = function (base) {
this.base = base;
};
OctoPrintActionCommandNotificationClient.prototype.get = function(refresh, opts) {
return this.base.get(this.base.getSimpleApiUrl("action_command_notification"), opts);
OctoPrintActionCommandNotificationClient.prototype.get = function (refresh, opts) {
return this.base.get(
this.base.getSimpleApiUrl("action_command_notification"),
opts
);
};
OctoPrintActionCommandNotificationClient.prototype.clear = function(opts) {
return this.base.simpleApiCommand("action_command_notification", "clear", {}, opts);
OctoPrintActionCommandNotificationClient.prototype.clear = function (opts) {
return this.base.simpleApiCommand(
"action_command_notification",
"clear",
{},
opts
);
};
OctoPrintClient.registerPluginComponent("action_command_notification", OctoPrintActionCommandNotificationClient);
OctoPrintClient.registerPluginComponent(
"action_command_notification",
OctoPrintActionCommandNotificationClient
);
return OctoPrintActionCommandNotificationClient;
});
@@ -1,4 +1,4 @@
$(function() {
$(function () {
function ActionCommandNotificationViewModel(parameters) {
var self = this;
@@ -8,40 +8,57 @@ $(function() {
self.notifications = ko.observableArray([]);
self.toDateTimeString = function(timestamp) {
self.toDateTimeString = function (timestamp) {
return formatDate(timestamp);
};
self.requestData = function() {
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW)) return;
self.requestData = function () {
if (
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW
)
)
return;
OctoPrint.plugins.action_command_notification.get()
.done(self.fromResponse)
OctoPrint.plugins.action_command_notification.get().done(self.fromResponse);
};
self.fromResponse = function(response) {
self.fromResponse = function (response) {
self.notifications(response.notifications);
};
self.clear = function() {
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_CLEAR)) return;
self.clear = function () {
if (
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_CLEAR
)
)
return;
OctoPrint.plugins.action_command_notification.clear();
};
self.onStartup = self.onUserLoggedIn = self.onUserLoggedOut = function() {
self.onStartup = self.onUserLoggedIn = self.onUserLoggedOut = function () {
self.requestData();
};
self.onDataUpdaterPluginMessage = function(plugin, data) {
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW)) return;
self.onDataUpdaterPluginMessage = function (plugin, data) {
if (
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW
)
)
return;
if (plugin !== "action_command_notification") {
return;
}
self.requestData();
if (data.message && self.settings.settings.plugins.action_command_notification.enable_popups()) {
if (
data.message &&
self.settings.settings.plugins.action_command_notification.enable_popups()
) {
new PNotify({
title: gettext("Printer Notification"),
text: data.message,
@@ -54,7 +71,6 @@ $(function() {
});
}
};
}
OCTOPRINT_VIEWMODELS.push({
@@ -1,245 +1,305 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import octoprint.plugin
from octoprint.server import user_permission
from octoprint.access import USER_GROUP
from octoprint.access.permissions import Permissions
from octoprint.events import Events
import flask
from flask_babel import gettext
import octoprint.plugin
from octoprint.access import USER_GROUP
from octoprint.access.permissions import Permissions
from octoprint.events import Events
class Prompt(object):
def __init__(self, text):
self.text = text
self.choices = []
def __init__(self, text):
self.text = text
self.choices = []
self._active = False
self._active = False
@property
def active(self):
return self._active
@property
def active(self):
return self._active
def add_choice(self, text):
self.choices.append(text)
def add_choice(self, text):
self.choices.append(text)
def activate(self):
self._active = True
def activate(self):
self._active = True
def validate_choice(self, choice):
return 0 <= choice < len(self.choices)
def validate_choice(self, choice):
return 0 <= choice < len(self.choices)
class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.EventHandlerPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin):
class ActionCommandPromptPlugin(
octoprint.plugin.AssetPlugin,
octoprint.plugin.EventHandlerPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin,
):
COMMAND = "M876"
CAP_PROMPT_SUPPORT = "PROMPT_SUPPORT"
COMMAND = "M876"
CAP_PROMPT_SUPPORT = "PROMPT_SUPPORT"
# noinspection PyMissingConstructor
def __init__(self):
self._prompt = None
self._enable = "detected"
self._command = None
self._enable_emergency_sending = True
self._enable_signal_support = True
self._cap_prompt_support = False
# noinspection PyMissingConstructor
def __init__(self):
self._prompt = None
self._enable = "detected"
self._command = None
self._enable_emergency_sending = True
self._enable_signal_support = True
self._cap_prompt_support = False
def initialize(self):
self._enable = self._settings.get(["enable"])
self._command = self._settings.get(["command"])
self._enable_emergency_sending = self._settings.get_boolean(["enable_emergency_sending"])
self._enable_signal_support = self._settings.get_boolean(["enable_signal_support"])
def initialize(self):
self._enable = self._settings.get(["enable"])
self._command = self._settings.get(["command"])
self._enable_emergency_sending = self._settings.get_boolean(
["enable_emergency_sending"]
)
self._enable_signal_support = self._settings.get_boolean(
["enable_signal_support"]
)
# Additional permissions hook
# Additional permissions hook
def get_additional_permissions(self):
return [
{"key": "INTERACT",
"name": "Interact with printer prompts",
"description": gettext("Allows to see and interact with printer prompts"),
"default_groups": [USER_GROUP],
"roles": ["interact"]}
]
def get_additional_permissions(self):
return [
{
"key": "INTERACT",
"name": "Interact with printer prompts",
"description": gettext("Allows to see and interact with printer prompts"),
"default_groups": [USER_GROUP],
"roles": ["interact"],
}
]
#~ AssetPlugin
# ~ AssetPlugin
def get_assets(self):
return {"js": ["js/action_command_prompt.js"],
"clientjs": ["clientjs/action_command_prompt.js"]}
def get_assets(self):
return {
"js": ["js/action_command_prompt.js"],
"clientjs": ["clientjs/action_command_prompt.js"],
}
#~ EventHandlerPlugin
# ~ EventHandlerPlugin
def on_event(self, event, payload):
if event == Events.CONNECTED and self._enable == "always" and self._enable_signal_support:
self._printer.commands(["{command} P1".format(command=self._command)])
elif event == Events.DISCONNECTED:
self._close_prompt()
def on_event(self, event, payload):
if (
event == Events.CONNECTED
and self._enable == "always"
and self._enable_signal_support
):
self._printer.commands(["{command} P1".format(command=self._command)])
elif event == Events.DISCONNECTED:
self._close_prompt()
#~ SettingsPlugin
# ~ SettingsPlugin
def get_settings_defaults(self):
return {"enable": "detected",
"command": self.COMMAND,
"enable_emergency_sending": True,
"enable_signal_support": True}
def get_settings_defaults(self):
return {
"enable": "detected",
"command": self.COMMAND,
"enable_emergency_sending": True,
"enable_signal_support": True,
}
def on_settings_save(self, data):
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
self._enable = self._settings.get(["enable"])
self._command = self._settings.get(["command"])
self._enable_emergency_sending = self._settings.get_boolean(["enable_emergency_sending"])
self._enable_signal_support = self._settings.get_boolean(["enable_signal_support"])
def on_settings_save(self, data):
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
self._enable = self._settings.get(["enable"])
self._command = self._settings.get(["command"])
self._enable_emergency_sending = self._settings.get_boolean(
["enable_emergency_sending"]
)
self._enable_signal_support = self._settings.get_boolean(
["enable_signal_support"]
)
#~ SimpleApiPlugin
# ~ SimpleApiPlugin
def get_api_commands(self):
return {"select": ["choice"]}
def get_api_commands(self):
return {"select": ["choice"]}
def on_api_command(self, command, data):
if command == "select":
if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can():
return flask.abort(403, "Insufficient permissions")
def on_api_command(self, command, data):
if command == "select":
if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can():
return flask.abort(403, "Insufficient permissions")
if self._prompt is None:
return flask.abort(409, "No active prompt")
if self._prompt is None:
return flask.abort(409, "No active prompt")
choice = data["choice"]
if not isinstance(choice, int) or not self._prompt.validate_choice(choice):
return flask.abort(400, "{!r} is not a valid value for choice".format(choice))
choice = data["choice"]
if not isinstance(choice, int) or not self._prompt.validate_choice(choice):
return flask.abort(
400, "{!r} is not a valid value for choice".format(choice)
)
self._answer_prompt(choice)
self._answer_prompt(choice)
def on_api_get(self, request):
if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can():
return flask.abort(403, "Insufficient permissions")
if self._prompt is None:
return flask.jsonify()
else:
return flask.jsonify(text=self._prompt.text, choices=self._prompt.choices)
def on_api_get(self, request):
if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can():
return flask.abort(403, "Insufficient permissions")
if self._prompt is None:
return flask.jsonify()
else:
return flask.jsonify(text=self._prompt.text, choices=self._prompt.choices)
#~ TemplatePlugin
# ~ TemplatePlugin
def get_template_configs(self):
return [{"type": "settings", "name": gettext("Printer Dialogs"), "custom_bindings": False}]
def get_template_configs(self):
return [
{
"type": "settings",
"name": gettext("Printer Dialogs"),
"custom_bindings": False,
}
]
#~ action command handler
# ~ action command handler
def action_command_handler(self, comm, line, action, *args, **kwargs):
if not action.startswith("prompt_"):
return
def action_command_handler(self, comm, line, action, *args, **kwargs):
if not action.startswith("prompt_"):
return
parts = action.split(None, 1)
if len(parts) == 1:
action = parts[0]
parameter = ""
else:
action, parameter = parts
parts = action.split(None, 1)
if len(parts) == 1:
action = parts[0]
parameter = ""
else:
action, parameter = parts
if action == "prompt_begin":
if self._prompt is not None and self._prompt.active:
self._logger.warning("Prompt is already defined")
return
self._prompt = Prompt(parameter.strip())
if action == "prompt_begin":
if self._prompt is not None and self._prompt.active:
self._logger.warning("Prompt is already defined")
return
self._prompt = Prompt(parameter.strip())
elif action == "prompt_choice" or action == "prompt_button":
if self._prompt is None:
return
if self._prompt.active:
self._logger.warning("Prompt is already active")
return
self._prompt.add_choice(parameter.strip())
elif action == "prompt_choice" or action == "prompt_button":
if self._prompt is None:
return
if self._prompt.active:
self._logger.warning("Prompt is already active")
return
self._prompt.add_choice(parameter.strip())
elif action == "prompt_show":
if self._prompt is None:
return
if self._prompt.active:
self._logger.warning("Prompt is already active")
return
self._show_prompt()
elif action == "prompt_show":
if self._prompt is None:
return
if self._prompt.active:
self._logger.warning("Prompt is already active")
return
self._show_prompt()
elif action == "prompt_end":
if self._prompt is None:
return
self._close_prompt()
self._prompt = None
elif action == "prompt_end":
if self._prompt is None:
return
self._close_prompt()
self._prompt = None
#~ queuing handling
# ~ queuing handling
def gcode_queuing_handler(self, comm_instance, phase, cmd, cmd_type, gcode, subcode=None, tags=None, *args, **kwargs):
if gcode != self._command:
return
def gcode_queuing_handler(
self,
comm_instance,
phase,
cmd,
cmd_type,
gcode,
subcode=None,
tags=None,
*args,
**kwargs
):
if gcode != self._command:
return
if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support) or not self._enable_emergency_sending:
return
if (
self._enable == "never"
or (self._enable == "detected" and not self._cap_prompt_support)
or not self._enable_emergency_sending
):
return
if not "S" in cmd:
# we only force-send M876 Sx
return
if "S" not in cmd:
# we only force-send M876 Sx
return
# noinspection PyProtectedMember
return comm_instance._emergency_force_send(cmd, "Force-sending {} to the printer".format(self._command), gcode=gcode)
# noinspection PyProtectedMember
return comm_instance._emergency_force_send(
cmd, "Force-sending {} to the printer".format(self._command), gcode=gcode
)
#~ capability reporting
# ~ capability reporting
def firmware_capability_handler(self, comm_instance, capability, enabled, already_defined, *args, **kwargs):
if capability == self.CAP_PROMPT_SUPPORT and enabled:
self._cap_prompt_support = True
if self._enable == "detected" and self._enable_signal_support:
self._printer.commands(["{command} P1".format(command=self._command)])
def firmware_capability_handler(
self, comm_instance, capability, enabled, already_defined, *args, **kwargs
):
if capability == self.CAP_PROMPT_SUPPORT and enabled:
self._cap_prompt_support = True
if self._enable == "detected" and self._enable_signal_support:
self._printer.commands(["{command} P1".format(command=self._command)])
#~ prompt handling
# ~ prompt handling
def _show_prompt(self):
if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support):
return
def _show_prompt(self):
if self._enable == "never" or (
self._enable == "detected" and not self._cap_prompt_support
):
return
self._prompt.activate()
self._plugin_manager.send_plugin_message(self._identifier, {"action": "show",
"text": self._prompt.text,
"choices": self._prompt.choices})
self._prompt.activate()
self._plugin_manager.send_plugin_message(
self._identifier,
{
"action": "show",
"text": self._prompt.text,
"choices": self._prompt.choices,
},
)
def _close_prompt(self):
if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support):
return
def _close_prompt(self):
if self._enable == "never" or (
self._enable == "detected" and not self._cap_prompt_support
):
return
self._prompt = None
self._plugin_manager.send_plugin_message(self._identifier, {"action": "close"})
self._prompt = None
self._plugin_manager.send_plugin_message(self._identifier, {"action": "close"})
def _answer_prompt(self, choice):
if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support):
return
def _answer_prompt(self, choice):
if self._enable == "never" or (
self._enable == "detected" and not self._cap_prompt_support
):
return
self._close_prompt()
if "{choice}" in self._command:
self._printer.commands([self._command.format(choice=choice)],
force=True)
else:
self._printer.commands(["{command} S{choice}".format(command=self._command,
choice=choice)],
force=True)
self._close_prompt()
if "{choice}" in self._command:
self._printer.commands([self._command.format(choice=choice)], force=True)
else:
self._printer.commands(
["{command} S{choice}".format(command=self._command, choice=choice)],
force=True,
)
__plugin_name__ = "Action Command Prompt Support"
__plugin_description__ = "Allows your printer to trigger prompts via action commands on the connection"
__plugin_description__ = (
"Allows your printer to trigger prompts via action commands on the connection"
)
__plugin_author__ = "Gina Häußge"
__plugin_disabling_discouraged__ = gettext("Without this plugin your printer will no longer be able to trigger"
" confirmation or selection prompts in OctoPrint")
__plugin_disabling_discouraged__ = gettext(
"Without this plugin your printer will no longer be able to trigger"
" confirmation or selection prompts in OctoPrint"
)
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = ActionCommandPromptPlugin()
__plugin_hooks__ = {
"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler,
"octoprint.comm.protocol.gcode.queuing": __plugin_implementation__.gcode_queuing_handler,
"octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.firmware_capability_handler,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler,
"octoprint.comm.protocol.gcode.queuing": __plugin_implementation__.gcode_queuing_handler,
"octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.firmware_capability_handler,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions,
}
@@ -4,22 +4,25 @@
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var OctoPrintActionCommandPromptClient = function(base) {
})(this, function (OctoPrintClient) {
var OctoPrintActionCommandPromptClient = function (base) {
this.base = base;
};
OctoPrintActionCommandPromptClient.prototype.get = function(refresh, opts) {
OctoPrintActionCommandPromptClient.prototype.get = function (refresh, opts) {
return this.base.get(this.base.getSimpleApiUrl("action_command_prompt"), opts);
};
OctoPrintActionCommandPromptClient.prototype.select = function(choice, opts) {
OctoPrintActionCommandPromptClient.prototype.select = function (choice, opts) {
var data = {
choice: choice
};
return this.base.simpleApiCommand("action_command_prompt", "select", data, opts);
};
OctoPrintClient.registerPluginComponent("action_command_prompt", OctoPrintActionCommandPromptClient);
OctoPrintClient.registerPluginComponent(
"action_command_prompt",
OctoPrintActionCommandPromptClient
);
return OctoPrintActionCommandPromptClient;
});
@@ -1,4 +1,4 @@
$(function() {
$(function () {
function ActionCommandPromptViewModel(parameters) {
var self = this;
@@ -10,21 +10,25 @@ $(function() {
self.text = ko.observable();
self.buttons = ko.observableArray([]);
self.active = ko.pureComputed(function() {
self.active = ko.pureComputed(function () {
return self.text() !== undefined;
});
self.visible = ko.pureComputed(function() {
self.visible = ko.pureComputed(function () {
return self.modal() !== undefined;
});
self.requestData = function() {
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT)) return;
self.requestData = function () {
if (
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT
)
)
return;
OctoPrint.plugins.action_command_prompt.get()
.done(self.fromResponse);
OctoPrint.plugins.action_command_prompt.get().done(self.fromResponse);
};
self.fromResponse = function(data) {
self.fromResponse = function (data) {
if (data.hasOwnProperty("text") && data.hasOwnProperty("choices")) {
self.text(data.text);
self.buttons(data.choices);
@@ -35,7 +39,7 @@ $(function() {
}
};
self.showPrompt = function() {
self.showPrompt = function () {
var text = self.text();
var buttons = self.buttons();
@@ -44,12 +48,12 @@ $(function() {
message: text,
selections: buttons,
maycancel: true, // see #3171
onselect: function(index) {
onselect: function (index) {
if (index > -1) {
self._select(index);
}
},
onclose: function() {
onclose: function () {
self.modal(undefined);
}
};
@@ -57,23 +61,28 @@ $(function() {
self.modal(showSelectionDialog(opts));
};
self._select = function(index) {
self._select = function (index) {
OctoPrint.plugins.action_command_prompt.select(index);
};
self._closePrompt = function() {
self._closePrompt = function () {
var modal = self.modal();
if (modal) {
modal.modal("hide");
}
};
self.onStartupComplete = function() {
self.onStartupComplete = function () {
self.requestData();
};
self.onDataUpdaterPluginMessage = function(plugin, data) {
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT)) return;
self.onDataUpdaterPluginMessage = function (plugin, data) {
if (
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT
)
)
return;
if (plugin !== "action_command_prompt") {
return;
}
@@ -92,8 +101,7 @@ $(function() {
break;
}
}
}
};
}
OCTOPRINT_VIEWMODELS.push({
File diff suppressed because it is too large. Load diff
@@ -1,4 +1,4 @@
$(function() {
$(function () {
function AnnouncementsViewModel(parameters) {
var self = this;
@@ -9,15 +9,22 @@ $(function() {
self.channels = new ItemListHelper(
"plugin.announcements.channels",
{
"channel": function (a, b) {
channel: function (a, b) {
// sorts ascending
if (a["channel"].toLocaleLowerCase() < b["channel"].toLocaleLowerCase()) return -1;
if (a["channel"].toLocaleLowerCase() > b["channel"].toLocaleLowerCase()) return 1;
if (
a["channel"].toLocaleLowerCase() <
b["channel"].toLocaleLowerCase()
)
return -1;
if (
a["channel"].toLocaleLowerCase() >
b["channel"].toLocaleLowerCase()
)
return 1;
return 0;
}
},
{
},
{},
"name",
[],
[],
@@ -32,30 +39,34 @@ $(function() {
self.announcementDialogContent = undefined;
self.announcementDialogTabs = undefined;
self.setupTabLink = function(item) {
self.setupTabLink = function (item) {
$("a[data-toggle='tab']", item).on("show", self.resetContentScroll);
};
self.resetContentScroll = function() {
self.resetContentScroll = function () {
self.announcementDialogContent.scrollTop(0);
};
self.toggleButtonCss = function(data) {
self.toggleButtonCss = function (data) {
var icon = data.enabled ? "fa fa-toggle-on" : "fa fa-toggle-off";
var disabled = (self.enableToggle(data)) ? "" : " disabled";
var disabled = self.enableToggle(data) ? "" : " disabled";
return icon + disabled;
};
self.toggleButtonTitle = function(data) {
return data.forced ? gettext("Cannot be toggled") : (data.enabled ? gettext("Disable Channel") : gettext("Enable Channel"));
self.toggleButtonTitle = function (data) {
return data.forced
? gettext("Cannot be toggled")
: data.enabled
? gettext("Disable Channel")
: gettext("Enable Channel");
};
self.enableToggle = function(data) {
self.enableToggle = function (data) {
return !data.forced;
};
self.cleanedLink = function(data) {
self.cleanedLink = function (data) {
// Strips any query parameters from the link and returns it
var link = data.link;
if (!link) return link;
@@ -67,8 +78,13 @@ $(function() {
return link;
};
self.markRead = function(channel, until, reload) {
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
self.markRead = function (channel, until, reload) {
if (
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ
)
)
return;
reload = !!reload;
@@ -85,16 +101,21 @@ $(function() {
dataType: "json",
data: JSON.stringify(payload),
contentType: "application/json; charset=UTF-8",
success: function() {
success: function () {
if (reload) {
self.retrieveData()
self.retrieveData();
}
}
})
});
};
self.toggleChannel = function(channel) {
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_MANAGE)) return;
self.toggleChannel = function (channel) {
if (
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_ANNOUNCEMENTS_MANAGE
)
)
return;
var url = PLUGIN_BASEURL + "announcements/channels/" + channel;
@@ -108,18 +129,23 @@ $(function() {
dataType: "json",
data: JSON.stringify(payload),
contentType: "application/json; charset=UTF-8",
success: function() {
self.retrieveData()
success: function () {
self.retrieveData();
}
})
});
};
self.refreshAnnouncements = function() {
self.refreshAnnouncements = function () {
self.retrieveData(true);
};
self.retrieveData = function(force) {
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
self.retrieveData = function (force) {
if (
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ
)
)
return;
var url = PLUGIN_BASEURL + "announcements/channels";
if (force) {
@@ -130,20 +156,25 @@ $(function() {
url: url,
type: "GET",
dataType: "json",
success: function(data) {
success: function (data) {
self.fromResponse(data);
}
});
};
self.fromResponse = function(data) {
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
self.fromResponse = function (data) {
if (
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ
)
)
return;
var currentTab = $("li.active a", self.announcementDialogTabs).attr("href");
var unread = 0;
var channels = [];
_.each(data.channels, function(value) {
_.each(data.channels, function (value) {
value.last = value.data.length ? value.data[0].published : undefined;
value.count = value.data.length;
unread += value.unread;
@@ -157,8 +188,13 @@ $(function() {
self.selectTab(currentTab);
};
self.showAnnouncementDialog = function(channel) {
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
self.showAnnouncementDialog = function (channel) {
if (
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ
)
)
return;
// lazy load images that still need lazy-loading
$("#plugin_announcements_dialog_content article img").lazyload();
@@ -166,12 +202,18 @@ $(function() {
self.announcementDialogContent.scrollTop(0);
if (!self.announcementDialog.hasClass("in")) {
self.announcementDialog.modal({
minHeight: function() { return Math.max($.fn.modal.defaults.maxHeight() - 80, 250); }
}).css({
width: 'auto',
'margin-left': function() { return -($(this).width() /2); }
});
self.announcementDialog
.modal({
minHeight: function () {
return Math.max($.fn.modal.defaults.maxHeight() - 80, 250);
}
})
.css({
"width": "auto",
"margin-left": function () {
return -($(this).width() / 2);
}
});
}
var tab = undefined;
@@ -183,24 +225,29 @@ $(function() {
return false;
};
self.selectTab = function(tab) {
self.selectTab = function (tab) {
if (tab != undefined) {
if (!_.startsWith(tab, "#")) {
tab = "#" + tab;
}
$('a[href="' + tab + '"]', self.announcementDialogTabs).tab("show");
} else {
$('a:first', self.announcementDialogTabs).tab("show");
$("a:first", self.announcementDialogTabs).tab("show");
}
};
self.displayAnnouncements = function(channels) {
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
self.displayAnnouncements = function (channels) {
if (
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ
)
)
return;
var displayLimit = self.settings.settings.plugins.announcements.display_limit();
var maxLength = self.settings.settings.plugins.announcements.summary_limit();
var cutAfterNewline = function(text) {
var cutAfterNewline = function (text) {
text = text.trim();
var firstNewlinePos = text.indexOf("\n");
@@ -211,7 +258,7 @@ $(function() {
return text;
};
var stripParagraphs = function(text) {
var stripParagraphs = function (text) {
if (_.startsWith(text, "<p>")) {
text = text.substr("<p>".length);
}
@@ -219,10 +266,10 @@ $(function() {
text = text.substr(0, text.length - "</p>".length);
}
return text.replace(/<\/p>\s*<p>/ig, "<br>");
return text.replace(/<\/p>\s*<p>/gi, "<br>");
};
_.each(channels, function(value) {
_.each(channels, function (value) {
var key = value.key;
var channel = value.channel;
var priority = value.priority;
@@ -233,7 +280,9 @@ $(function() {
return;
}
var newItems = _.filter(items, function(entry) { return !entry.read; });
var newItems = _.filter(items, function (entry) {
return !entry.read;
});
if (newItems.length == 0) {
// no new items at all, we don't display anything for this channel
return;
@@ -248,23 +297,48 @@ $(function() {
var rest = newItems.length - displayedItems.length;
var text = "<ul style='margin-top: 10px; margin-bottom: 10px'>";
_.each(displayedItems, function(item) {
var limitedSummary = stripParagraphs(item.summary_without_images.trim());
_.each(displayedItems, function (item) {
var limitedSummary = stripParagraphs(
item.summary_without_images.trim()
);
if (limitedSummary.length > maxLength) {
limitedSummary = limitedSummary.substr(0, maxLength);
limitedSummary = limitedSummary.substr(0, Math.min(limitedSummary.length, limitedSummary.lastIndexOf(" ")));
limitedSummary = limitedSummary.substr(
0,
Math.min(
limitedSummary.length,
limitedSummary.lastIndexOf(" ")
)
);
limitedSummary += "...";
}
text += "<li><a href='" + item.link + "' target='_blank' rel='noreferrer noopener'>" + cutAfterNewline(item.title) + "</a><br><small>" + formatTimeAgo(item.published) + "</small><p>" + limitedSummary + "</p></li>";
text +=
"<li><a href='" +
item.link +
"' target='_blank' rel='noreferrer noopener'>" +
cutAfterNewline(item.title) +
"</a><br><small>" +
formatTimeAgo(item.published) +
"</small><p>" +
limitedSummary +
"</p></li>";
});
text += "</ul>";
if (rest) {
text += "<p>" + gettext(_.sprintf("... and %(rest)d more.", {rest: rest})) + "</p>";
text +=
"<p>" +
gettext(_.sprintf("... and %(rest)d more.", {rest: rest})) +
"</p>";
}
text += "<small>" + gettext("You can edit your announcement subscriptions under Settings > Announcements.") + "</small>";
text +=
"<small>" +
gettext(
"You can edit your announcement subscriptions under Settings > Announcements."
) +
"</small>";
var options = {
title: channel,
@@ -272,27 +346,31 @@ $(function() {
hide: false,
confirm: {
confirm: true,
buttons: [{
text: gettext("Later"),
click: function(notice) {
notice.remove();
self.hiddenChannels.push(key);
buttons: [
{
text: gettext("Later"),
click: function (notice) {
notice.remove();
self.hiddenChannels.push(key);
}
},
{
text: gettext("Mark read"),
click: function (notice) {
notice.remove();
self.markRead(key, value.last);
}
},
{
text: gettext("Read..."),
addClass: "btn-primary",
click: function (notice) {
notice.remove();
self.showAnnouncementDialog(key);
self.markRead(key, value.last);
}
}
}, {
text: gettext("Mark read"),
click: function(notice) {
notice.remove();
self.markRead(key, value.last);
}
}, {
text: gettext("Read..."),
addClass: "btn-primary",
click: function(notice) {
notice.remove();
self.showAnnouncementDialog(key);
self.markRead(key, value.last);
}
}]
]
},
buttons: {
sticker: false,
@@ -311,41 +389,48 @@ $(function() {
});
};
self.hideAnnouncements = function() {
_.each(self.channelNotifications, function(notification, key) {
self.hideAnnouncements = function () {
_.each(self.channelNotifications, function (notification, key) {
notification.remove();
});
self.channelNotifications = {};
};
self.configureAnnouncements = function() {
self.configureAnnouncements = function () {
self.settings.show("settings_plugin_announcements");
};
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) {
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
if (
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ
)
) {
self.hideAnnouncements();
} else {
self.retrieveData();
}
};
self.onStartup = function() {
self.onStartup = function () {
self.announcementDialog = $("#plugin_announcements_dialog");
self.announcementDialogContent = $("#plugin_announcements_dialog_content");
self.announcementDialogTabs = $("#plugin_announcements_dialog_tabs");
};
self.onEventConnectivityChanged = function(payload) {
self.onEventConnectivityChanged = function (payload) {
if (!payload || !payload.new) return;
self.retrieveData();
}
};
}
OCTOPRINT_VIEWMODELS.push({
construct: AnnouncementsViewModel,
dependencies: ["loginStateViewModel", "settingsViewModel", "accessViewModel"],
elements: ["#plugin_announcements_dialog", "#settings_plugin_announcements", "#navbar_plugin_announcements"]
elements: [
"#plugin_announcements_dialog",
"#settings_plugin_announcements",
"#navbar_plugin_announcements"
]
});
});
@@ -1,5 +1,6 @@
table {
th, td {
th,
td {
&.settings_plugin_announcements_channels_name {
text-overflow: ellipsis;
text-align: left;
+463 -411
View File
@@ -1,447 +1,499 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import flask
import threading
import os
import yaml
import io
import time
import uuid
import os
import threading
from collections import defaultdict
import flask
import yaml
from flask_babel import gettext
import octoprint.plugin
from octoprint.settings import valid_boolean_trues
from octoprint.server.util.flask import restricted_access, no_firstrun_access
from octoprint.server import NO_CONTENT, current_user, admin_permission
from octoprint.util import atomic_write, monotonic_time, ResettableTimer, generate_api_key
from octoprint.access import ADMIN_GROUP
from octoprint.access.permissions import Permissions
from octoprint.server import NO_CONTENT, admin_permission, current_user
from octoprint.server.util.flask import no_firstrun_access, restricted_access
from octoprint.settings import valid_boolean_trues
from octoprint.util import ResettableTimer, atomic_write, generate_api_key, monotonic_time
CUTOFF_TIME = 10 * 60 # 10min
POLL_TIMEOUT = 5 # 5 seconds
CUTOFF_TIME = 10 * 60 # 10min
POLL_TIMEOUT = 5 # 5 seconds
class AppAlreadyExists(Exception):
pass
pass
class PendingDecision(object):
def __init__(self, app_id, app_token, user_id, user_token, timeout_callback=None):
self.app_id = app_id
self.app_token = app_token
self.user_id = user_id
self.user_token = user_token
self.created = monotonic_time()
def __init__(self, app_id, app_token, user_id, user_token, timeout_callback=None):
self.app_id = app_id
self.app_token = app_token
self.user_id = user_id
self.user_token = user_token
self.created = monotonic_time()
if callable(timeout_callback):
self.poll_timeout = ResettableTimer(POLL_TIMEOUT, timeout_callback, [user_token])
self.poll_timeout.start()
if callable(timeout_callback):
self.poll_timeout = ResettableTimer(
POLL_TIMEOUT, timeout_callback, [user_token]
)
self.poll_timeout.start()
def external(self):
return {"app_id": self.app_id,
"user_id": self.user_id,
"user_token": self.user_token}
def external(self):
return {
"app_id": self.app_id,
"user_id": self.user_id,
"user_token": self.user_token,
}
def __repr__(self):
return u"PendingDecision({!r}, {!r}, {!r}, {!r}, timeout_callback=...)".format(self.app_id,
self.app_token,
self.user_id,
self.user_token)
def __repr__(self):
return "PendingDecision({!r}, {!r}, {!r}, {!r}, timeout_callback=...)".format(
self.app_id, self.app_token, self.user_id, self.user_token
)
class ReadyDecision(object):
def __init__(self, app_id, app_token, user_id):
self.app_id = app_id
self.app_token = app_token
self.user_id = user_id
def __init__(self, app_id, app_token, user_id):
self.app_id = app_id
self.app_token = app_token
self.user_id = user_id
@classmethod
def for_pending(cls, pending, user_id):
return cls(pending.app_id, pending.app_token, user_id)
@classmethod
def for_pending(cls, pending, user_id):
return cls(pending.app_id, pending.app_token, user_id)
def __repr__(self):
return u"ReadyDecision({!r}, {!r}, {!r})".format(self.app_id,
self.app_token,
self.user_id)
def __repr__(self):
return "ReadyDecision({!r}, {!r}, {!r})".format(
self.app_id, self.app_token, self.user_id
)
class ActiveKey(object):
def __init__(self, app_id, api_key, user_id):
self.app_id = app_id
self.api_key = api_key
self.user_id = user_id
def external(self):
return {"app_id": self.app_id,
"api_key": self.api_key,
"user_id": self.user_id}
def internal(self):
return {"app_id": self.app_id,
"api_key": self.api_key}
@classmethod
def for_internal(cls, internal, user_id):
return cls(internal["app_id"], internal["api_key"], user_id)
def __repr__(self):
return u"ActiveKey({!r}, {!r}, {!r})".format(self.app_id,
self.api_key,
self.user_id)
class AppKeysPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.BlueprintPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin):
def __init__(self):
self._pending_decisions = []
self._pending_lock = threading.RLock()
self._ready_decisions = []
self._ready_lock = threading.RLock()
self._keys = defaultdict(list)
self._keys_lock = threading.RLock()
self._key_path = None
def initialize(self):
self._key_path = os.path.join(self.get_plugin_data_folder(), "keys.yaml")
self._load_keys()
# Additional permissions hook
def get_additional_permissions(self):
return [
{"key": "ADMIN",
"name": "Admin access",
"description": gettext("Allows administrating all application keys"),
"roles": ["admin"],
"dangerous": True,
"default_groups": [ADMIN_GROUP]}
]
##~~ TemplatePlugin
def get_template_configs(self):
return [{"type": "usersettings", "name": gettext("Application Keys")},
{"type": "settings", "name": gettext("Application Keys")}]
##~~ AssetPlugin
def get_assets(self):
return {"js": ["js/appkeys.js"],
"clientjs": ["clientjs/appkeys.js"],
"less": ["less/appkeys.less"],
"css": ["css/appkeys.css"]}
##~~ BlueprintPlugin mixin
@octoprint.plugin.BlueprintPlugin.route("/probe", methods=["GET"])
@no_firstrun_access
def handle_probe(self):
return NO_CONTENT
@octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"])
@no_firstrun_access
def handle_request(self):
data = flask.request.json
if data is None:
return flask.make_response("Missing key request", 400)
if not "app" in data:
return flask.make_response("No app name provided", 400)
app_name = data["app"]
user_id = None
if "user" in data and data["user"]:
user_id = data["user"]
app_token, user_token = self._add_pending_decision(app_name, user_id=user_id)
self._plugin_manager.send_plugin_message(self._identifier, {"type": "request_access",
"app_name": app_name,
"user_token": user_token,
"user_id": user_id})
response = flask.jsonify(app_token=app_token)
response.status_code = 201
response.headers["Location"] = flask.url_for(".handle_decision_poll", app_token=app_token, _external=True)
return response
def __init__(self, app_id, api_key, user_id):
self.app_id = app_id
self.api_key = api_key
self.user_id = user_id
def external(self):
return {"app_id": self.app_id, "api_key": self.api_key, "user_id": self.user_id}
def internal(self):
return {"app_id": self.app_id, "api_key": self.api_key}
@classmethod
def for_internal(cls, internal, user_id):
return cls(internal["app_id"], internal["api_key"], user_id)
def __repr__(self):
return "ActiveKey({!r}, {!r}, {!r})".format(
self.app_id, self.api_key, self.user_id
)
class AppKeysPlugin(
octoprint.plugin.AssetPlugin,
octoprint.plugin.BlueprintPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin,
):
def __init__(self):
self._pending_decisions = []
self._pending_lock = threading.RLock()
self._ready_decisions = []
self._ready_lock = threading.RLock()
self._keys = defaultdict(list)
self._keys_lock = threading.RLock()
self._key_path = None
def initialize(self):
self._key_path = os.path.join(self.get_plugin_data_folder(), "keys.yaml")
self._load_keys()
# Additional permissions hook
def get_additional_permissions(self):
return [
{
"key": "ADMIN",
"name": "Admin access",
"description": gettext("Allows administrating all application keys"),
"roles": ["admin"],
"dangerous": True,
"default_groups": [ADMIN_GROUP],
}
]
##~~ TemplatePlugin
def get_template_configs(self):
return [
{"type": "usersettings", "name": gettext("Application Keys")},
{"type": "settings", "name": gettext("Application Keys")},
]
##~~ AssetPlugin
def get_assets(self):
return {
"js": ["js/appkeys.js"],
"clientjs": ["clientjs/appkeys.js"],
"less": ["less/appkeys.less"],
"css": ["css/appkeys.css"],
}
##~~ BlueprintPlugin mixin
@octoprint.plugin.BlueprintPlugin.route("/probe", methods=["GET"])
@no_firstrun_access
def handle_probe(self):
return NO_CONTENT
@octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"])
@no_firstrun_access
def handle_request(self):
data = flask.request.json
if data is None:
return flask.make_response("Missing key request", 400)
if "app" not in data:
return flask.make_response("No app name provided", 400)
app_name = data["app"]
user_id = None
if "user" in data and data["user"]:
user_id = data["user"]
app_token, user_token = self._add_pending_decision(app_name, user_id=user_id)
self._plugin_manager.send_plugin_message(
self._identifier,
{
"type": "request_access",
"app_name": app_name,
"user_token": user_token,
"user_id": user_id,
},
)
response = flask.jsonify(app_token=app_token)
response.status_code = 201
response.headers["Location"] = flask.url_for(
".handle_decision_poll", app_token=app_token, _external=True
)
return response
@octoprint.plugin.BlueprintPlugin.route("/request/<app_token>")
@no_firstrun_access
def handle_decision_poll(self, app_token):
result = self._get_pending_by_app_token(app_token)
if result:
for pending_decision in result:
pending_decision.poll_timeout.reset()
response = flask.jsonify(message="Awaiting decision")
response.status_code = 202
return response
result = self._get_decision(app_token)
if result:
return flask.jsonify(api_key=result)
return flask.abort(404)
@octoprint.plugin.BlueprintPlugin.route("/decision/<user_token>", methods=["POST"])
@restricted_access
def handle_decision(self, user_token):
data = flask.request.json
if "decision" not in data:
return flask.make_response("No decision provided", 400)
decision = data["decision"] in valid_boolean_trues
user_id = current_user.get_name()
result = self._set_decision(user_token, decision, user_id)
if not result:
return flask.abort(404)
# Close access_request dialog for this request on all open OctoPrint connections
self._plugin_manager.send_plugin_message(
self._identifier, {"type": "end_request", "user_token": user_token}
)
return NO_CONTENT
def is_blueprint_protected(self):
return False # No API key required to request API access
##~~ SimpleApiPlugin mixin
def get_api_commands(self):
return {"generate": ["app"], "revoke": ["key"]}
def on_api_get(self, request):
user_id = current_user.get_name()
if not user_id:
return flask.abort(403)
if (
request.values.get("all") in valid_boolean_trues
and Permissions.PLUGIN_APPKEYS_ADMIN.can()
):
keys = self._all_api_keys()
else:
keys = self._api_keys_for_user(user_id)
return flask.jsonify(
keys=list(map(lambda x: x.external(), keys)),
pending=dict(
(x.user_token, x.external())
for x in self._get_pending_by_user_id(user_id)
),
)
def on_api_command(self, command, data):
user_id = current_user.get_name()
if not user_id:
return flask.abort(403)
if command == "revoke":
api_key = data.get("key")
if not api_key:
return flask.abort(400)
if not admin_permission.can():
user_for_key = self._user_for_api_key(api_key)
if user_for_key is None or user_for_key.user_id != user_id:
return flask.abort(403)
self._delete_api_key(api_key)
elif command == "generate":
# manual generateKey
app_name = data.get("app")
if not app_name:
return flask.abort(400)
selected_user_id = data.get("user", user_id)
if selected_user_id != user_id and not Permissions.PLUGIN_APPKEYS_ADMIN.can():
return flask.abort(403)
key = self._add_api_key(selected_user_id, app_name.strip())
return flask.jsonify(user_id=selected_user_id, app_id=app_name, api_key=key)
return NO_CONTENT
##~~ key validator hook
def validate_api_key(self, api_key, *args, **kwargs):
return self._user_for_api_key(api_key)
##~~ Helpers
def _add_pending_decision(self, app_name, user_id=None):
app_token = self._generate_key()
user_token = self._generate_key()
with self._pending_lock:
self._remove_stale_pending()
self._pending_decisions.append(
PendingDecision(
app_name,
app_token,
user_id,
user_token,
timeout_callback=self._expire_pending,
)
)
return app_token, user_token
def _get_pending_by_app_token(self, app_token):
result = []
with self._pending_lock:
self._remove_stale_pending()
for data in self._pending_decisions:
if data.app_token == app_token:
result.append(data)
return result
def _get_pending_by_user_id(self, user_id):
result = []
with self._pending_lock:
self._remove_stale_pending()
for data in self._pending_decisions:
if data.user_id == user_id or data.user_id is None:
result.append(data)
return result
def _expire_pending(self, user_token):
with self._pending_lock:
len_before = len(self._pending_decisions)
self._pending_decisions = list(
filter(lambda x: x.user_token != user_token, self._pending_decisions)
)
len_after = len(self._pending_decisions)
if len_after < len_before:
self._plugin_manager.send_plugin_message(
self._identifier, {"type": "end_request", "user_token": user_token}
)
def _remove_stale_pending(self):
with self._pending_lock:
cutoff = monotonic_time() - CUTOFF_TIME
len_before = len(self._pending_decisions)
self._pending_decisions = list(
filter(lambda x: x.created >= cutoff, self._pending_decisions)
)
len_after = len(self._pending_decisions)
if len_after < len_before:
self._logger.info(
"Deleted {} stale pending authorization requests".format(
len_before - len_after
)
)
def _set_decision(self, user_token, decision, user_id):
with self._pending_lock:
self._remove_stale_pending()
for data in self._pending_decisions:
if data.user_token == user_token and (
data.user_id == user_id or data.user_id is None
):
pending = data
break
else:
return False # not found
if decision:
with self._ready_lock:
self._ready_decisions.append(ReadyDecision.for_pending(pending, user_id))
with self._pending_lock:
self._pending_decisions = list(
filter(lambda x: x.user_token != user_token, self._pending_decisions)
)
return True
def _get_decision(self, app_token):
self._remove_stale_pending()
with self._ready_lock:
for data in self._ready_decisions:
if data.app_token == app_token:
decision = data
break
else:
return False # not found
api_key = self._add_api_key(decision.user_id, decision.app_id)
with self._ready_lock:
self._ready_decisions = list(
filter(lambda x: x.app_token != app_token, self._ready_decisions)
)
return api_key
def _add_api_key(self, user_id, app_name):
with self._keys_lock:
for key in self._keys[user_id]:
if key.app_id.lower() == app_name.lower():
return key.api_key
key = ActiveKey(app_name, self._generate_key(), user_id)
self._keys[user_id].append(key)
self._save_keys()
return key.api_key
def _delete_api_key(self, api_key):
with self._keys_lock:
for user_id, data in self._keys.items():
self._keys[user_id] = list(filter(lambda x: x.api_key != api_key, data))
self._save_keys()
def _user_for_api_key(self, api_key):
with self._keys_lock:
for user_id, data in self._keys.items():
if any(filter(lambda x: x.api_key == api_key, data)):
if self._user_manager.enabled:
return self._user_manager.find_user(userid=user_id)
elif user_id == "_admin" or user_id == "dummy":
# dummy = backwards compatible
return self._user_manager.anonymous_user_factory()
return None
def _api_keys_for_user(self, user_id):
with self._keys_lock:
return self._keys[user_id]
def _all_api_keys(self):
with self._keys_lock:
result = []
for user_id, keys in self._keys.items():
result += keys
return result
def _generate_key(self):
return generate_api_key()
def _load_keys(self):
with self._keys_lock:
if not os.path.exists(self._key_path):
return
try:
with io.open(
self._key_path, "rt", encoding="utf-8", errors="strict"
) as f:
persisted = yaml.safe_load(f)
except Exception:
self._logger.exception(
"Could not load application keys from {}".format(self._key_path)
)
return
if not isinstance(persisted, dict):
return
keys = defaultdict(list)
for user_id, persisted_keys in persisted.items():
keys[user_id] = [
ActiveKey.for_internal(x, user_id) for x in persisted_keys
]
self._keys = keys
def _save_keys(self):
with self._keys_lock:
to_persist = {}
for user_id, keys in self._keys.items():
to_persist[user_id] = [x.internal() for x in keys]
try:
with atomic_write(self._key_path, mode="wt") as f:
yaml.safe_dump(to_persist, f, allow_unicode=True)
except Exception:
self._logger.exception(
"Could not write application keys to {}".format(self._key_path)
)
@octoprint.plugin.BlueprintPlugin.route("/request/<app_token>")
@no_firstrun_access
def handle_decision_poll(self, app_token):
result = self._get_pending_by_app_token(app_token)
if result:
for pending_decision in result:
pending_decision.poll_timeout.reset()
response = flask.jsonify(message="Awaiting decision")
response.status_code = 202
return response
result = self._get_decision(app_token)
if result:
return flask.jsonify(api_key=result)
return flask.abort(404)
@octoprint.plugin.BlueprintPlugin.route("/decision/<user_token>", methods=["POST"])
@restricted_access
def handle_decision(self, user_token):
data = flask.request.json
if not "decision" in data:
return flask.make_response("No decision provided", 400)
decision = data["decision"] in valid_boolean_trues
user_id = current_user.get_name()
result = self._set_decision(user_token, decision, user_id)
if not result:
return flask.abort(404)
# Close access_request dialog for this request on all open OctoPrint connections
self._plugin_manager.send_plugin_message(self._identifier, {"type": "end_request",
"user_token": user_token})
return NO_CONTENT
def is_blueprint_protected(self):
return False # No API key required to request API access
##~~ SimpleApiPlugin mixin
def get_api_commands(self):
return {"generate": ["app"],
"revoke": ["key"]}
def on_api_get(self, request):
user_id = current_user.get_name()
if not user_id:
return flask.abort(403)
if request.values.get("all") in valid_boolean_trues and Permissions.PLUGIN_APPKEYS_ADMIN.can():
keys = self._all_api_keys()
else:
keys = self._api_keys_for_user(user_id)
return flask.jsonify(keys=list(map(lambda x: x.external(), keys)),
pending=dict((x.user_token, x.external()) for x in self._get_pending_by_user_id(user_id)))
def on_api_command(self, command, data):
user_id = current_user.get_name()
if not user_id:
return flask.abort(403)
if command == "revoke":
api_key = data.get("key")
if not api_key:
return flask.abort(400)
if not admin_permission.can():
user_for_key = self._user_for_api_key(api_key)
if user_for_key is None or user_for_key.user_id != user_id:
return flask.abort(403)
self._delete_api_key(api_key)
elif command == "generate":
# manual generateKey
app_name = data.get("app")
if not app_name:
return flask.abort(400)
selected_user_id = data.get("user", user_id)
if selected_user_id != user_id and not Permissions.PLUGIN_APPKEYS_ADMIN.can():
return flask.abort(403)
key = self._add_api_key(selected_user_id, app_name.strip())
return flask.jsonify(user_id=selected_user_id, app_id=app_name, api_key=key)
return NO_CONTENT
##~~ key validator hook
def validate_api_key(self, api_key, *args, **kwargs):
return self._user_for_api_key(api_key)
##~~ Helpers
def _add_pending_decision(self, app_name, user_id=None):
app_token = self._generate_key()
user_token = self._generate_key()
with self._pending_lock:
self._remove_stale_pending()
self._pending_decisions.append(PendingDecision(app_name, app_token, user_id, user_token,
timeout_callback=self._expire_pending))
return app_token, user_token
def _get_pending_by_app_token(self, app_token):
result = []
with self._pending_lock:
self._remove_stale_pending()
for data in self._pending_decisions:
if data.app_token == app_token:
result.append(data)
return result
def _get_pending_by_user_id(self, user_id):
result = []
with self._pending_lock:
self._remove_stale_pending()
for data in self._pending_decisions:
if data.user_id == user_id or data.user_id is None:
result.append(data)
return result
def _expire_pending(self, user_token):
with self._pending_lock:
len_before = len(self._pending_decisions)
self._pending_decisions = list(filter(lambda x: x.user_token != user_token,
self._pending_decisions))
len_after = len(self._pending_decisions)
if len_after < len_before:
self._plugin_manager.send_plugin_message(self._identifier, {"type": "end_request",
"user_token": user_token})
def _remove_stale_pending(self):
with self._pending_lock:
cutoff = monotonic_time() - CUTOFF_TIME
len_before = len(self._pending_decisions)
self._pending_decisions = list(filter(lambda x: x.created >= cutoff,
self._pending_decisions))
len_after = len(self._pending_decisions)
if len_after < len_before:
self._logger.info("Deleted {} stale pending authorization requests".format(len_before - len_after))
def _set_decision(self, user_token, decision, user_id):
with self._pending_lock:
self._remove_stale_pending()
for data in self._pending_decisions:
if data.user_token == user_token and (data.user_id == user_id or data.user_id is None):
pending = data
break
else:
return False # not found
if decision:
with self._ready_lock:
self._ready_decisions.append(ReadyDecision.for_pending(pending, user_id))
with self._pending_lock:
self._pending_decisions = list(filter(lambda x: x.user_token != user_token,
self._pending_decisions))
return True
def _get_decision(self, app_token):
self._remove_stale_pending()
with self._ready_lock:
for data in self._ready_decisions:
if data.app_token == app_token:
decision = data
break
else:
return False # not found
api_key = self._add_api_key(decision.user_id, decision.app_id)
with self._ready_lock:
self._ready_decisions = list(filter(lambda x: x.app_token != app_token,
self._ready_decisions))
return api_key
def _add_api_key(self, user_id, app_name):
with self._keys_lock:
for key in self._keys[user_id]:
if key.app_id.lower() == app_name.lower():
return key.api_key
key = ActiveKey(app_name, self._generate_key(), user_id)
self._keys[user_id].append(key)
self._save_keys()
return key.api_key
def _delete_api_key(self, api_key):
with self._keys_lock:
for user_id, data in self._keys.items():
self._keys[user_id] = list(filter(lambda x: x.api_key != api_key, data))
self._save_keys()
def _user_for_api_key(self, api_key):
with self._keys_lock:
for user_id, data in self._keys.items():
if any(filter(lambda x: x.api_key == api_key, data)):
if self._user_manager.enabled:
return self._user_manager.find_user(userid=user_id)
elif user_id == "_admin" or user_id == "dummy":
# dummy = backwards compatible
return self._user_manager.anonymous_user_factory()
return None
def _api_keys_for_user(self, user_id):
with self._keys_lock:
return self._keys[user_id]
def _all_api_keys(self):
with self._keys_lock:
result = []
for user_id, keys in self._keys.items():
result += keys
return result
def _generate_key(self):
return generate_api_key()
def _load_keys(self):
with self._keys_lock:
if not os.path.exists(self._key_path):
return
try:
with io.open(self._key_path, 'rt', encoding="utf-8", errors="strict") as f:
persisted = yaml.safe_load(f)
except Exception:
self._logger.exception("Could not load application keys from {}".format(self._key_path))
return
if not isinstance(persisted, dict):
return
keys = defaultdict(list)
for user_id, persisted_keys in persisted.items():
keys[user_id] = [ActiveKey.for_internal(x, user_id) for x in persisted_keys]
self._keys = keys
def _save_keys(self):
with self._keys_lock:
to_persist = {}
for user_id, keys in self._keys.items():
to_persist[user_id] = [x.internal() for x in keys]
try:
with atomic_write(self._key_path, mode='wt') as f:
yaml.safe_dump(to_persist, f, allow_unicode=True)
except Exception:
self._logger.exception("Could not write application keys to {}".format(self._key_path))
__plugin_name__ = "Application Keys Plugin"
__plugin_description__ = "Implements a workflow for third party clients to obtain API keys"
__plugin_description__ = (
"Implements a workflow for third party clients to obtain API keys"
)
__plugin_author__ = "Gina Häußge, Aldo Hoeben"
__plugin_disabling_discouraged__ = gettext("Without this plugin third party clients will no longer be able to "
"obtain an API key without you manually copy-pasting it.")
__plugin_disabling_discouraged__ = gettext(
"Without this plugin third party clients will no longer be able to "
"obtain an API key without you manually copy-pasting it."
)
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = AppKeysPlugin()
__plugin_hooks__ = {
"octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
"octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions,
}
@@ -4,59 +4,80 @@
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var OctoPrintAppKeysClient = function(base) {
})(this, function (OctoPrintClient) {
var OctoPrintAppKeysClient = function (base) {
this.base = base;
};
OctoPrintAppKeysClient.prototype.getKeys = function(opts) {
OctoPrintAppKeysClient.prototype.getKeys = function (opts) {
return this.base.simpleApiGet("appkeys", opts);
};
OctoPrintAppKeysClient.prototype.getAllKeys = function(opts) {
return this.base.get(OctoPrintClient.prototype.getSimpleApiUrl("appkeys") + "?all=true", opts);
OctoPrintAppKeysClient.prototype.getAllKeys = function (opts) {
return this.base.get(
OctoPrintClient.prototype.getSimpleApiUrl("appkeys") + "?all=true",
opts
);
};
OctoPrintAppKeysClient.prototype.generateKey = function(app, opts) {
return this.base.simpleApiCommand("appkeys", "generate", {"app": app}, opts);
OctoPrintAppKeysClient.prototype.generateKey = function (app, opts) {
return this.base.simpleApiCommand("appkeys", "generate", {app: app}, opts);
};
OctoPrintAppKeysClient.prototype.generateKeyForUser = function(user, app, opts) {
return this.base.simpleApiCommand("appkeys", "generate", {"app": app, "user": user}, opts);
OctoPrintAppKeysClient.prototype.generateKeyForUser = function (user, app, opts) {
return this.base.simpleApiCommand(
"appkeys",
"generate",
{app: app, user: user},
opts
);
};
OctoPrintAppKeysClient.prototype.revokeKey = function(key, opts) {
return this.base.simpleApiCommand("appkeys", "revoke", {"key": key}, opts);
OctoPrintAppKeysClient.prototype.revokeKey = function (key, opts) {
return this.base.simpleApiCommand("appkeys", "revoke", {key: key}, opts);
};
OctoPrintAppKeysClient.prototype.decide = function(token, decision, opts) {
return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "decision/" + token, {decision: !!decision}, opts);
OctoPrintAppKeysClient.prototype.decide = function (token, decision, opts) {
return this.base.postJson(
this.base.getBlueprintUrl("appkeys") + "decision/" + token,
{decision: !!decision},
opts
);
};
OctoPrintAppKeysClient.prototype.probe = function(opts) {
OctoPrintAppKeysClient.prototype.probe = function (opts) {
return this.base.get(this.base.getBlueprintUrl("appkeys") + "probe", opts);
};
OctoPrintAppKeysClient.prototype.request = function(app, opts) {
OctoPrintAppKeysClient.prototype.request = function (app, opts) {
return this.requestForUser(app, undefined, opts);
};
OctoPrintAppKeysClient.prototype.requestForUser = function(app, user, opts) {
return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "request", {app: app, user: user}, opts);
OctoPrintAppKeysClient.prototype.requestForUser = function (app, user, opts) {
return this.base.postJson(
this.base.getBlueprintUrl("appkeys") + "request",
{app: app, user: user},
opts
);
};
OctoPrintAppKeysClient.prototype.checkDecision = function(token, opts) {
return this.base.get(this.base.getBlueprintUrl("appkeys") + "request/" + token, opts);
OctoPrintAppKeysClient.prototype.checkDecision = function (token, opts) {
return this.base.get(
this.base.getBlueprintUrl("appkeys") + "request/" + token,
opts
);
};
OctoPrintAppKeysClient.prototype.authenticate = function(app, user) {
OctoPrintAppKeysClient.prototype.authenticate = function (app, user) {
var deferred = $.Deferred();
var client = this;
client.probe()
.done(function() {
client.requestForUser(app, user)
.done(function(response) {
client
.probe()
.done(function () {
client
.requestForUser(app, user)
.done(function (response) {
var token = response.app_token;
if (!token) {
// no token received, something went wrong
@@ -65,9 +86,10 @@
}
var interval = 1000;
var poll = function() {
client.checkDecision(token)
.done(function(response) {
var poll = function () {
client
.checkDecision(token)
.done(function (response) {
if (response.api_key) {
// got a decision, resolve the promise
deferred.resolve(response.api_key);
@@ -77,19 +99,19 @@
window.setTimeout(poll, interval);
}
})
.fail(function() {
.fail(function () {
// something went wrong
deferred.reject();
});
};
window.setTimeout(poll, interval);
})
.fail(function() {
.fail(function () {
// something went wrong
deferred.reject();
});
})
.fail(function() {
.fail(function () {
// workflow unsupported
deferred.reject();
});
+158 -112
View File
@@ -1,14 +1,14 @@
$(function() {
$(function () {
function AppKeysDialogViewModel(parameters) {
var self = this;
self.dialog = undefined;
self.onStartup = function() {
self.onStartup = function () {
self.dialog = $("#plugin_appkeys_keygenerated");
};
self.showDialog = function(title, data) {
self.showDialog = function (title, data) {
if (self.dialog === undefined) return;
var qrcode = {
@@ -27,17 +27,19 @@ $(function() {
self.dialog.find("#plugin_appkeys_keygenerated_user").text(data.user_id);
self.dialog.find("#plugin_appkeys_keygenerated_app").text(data.app_id);
self.dialog.find("#plugin_appkeys_keygenerated_key_text").text(data.api_key);
self.dialog.find("#plugin_appkeys_keygenerated_key_copy")
self.dialog
.find("#plugin_appkeys_keygenerated_key_copy")
.off()
.click(function() {
.click(function () {
copyToClipboard(data.api_key);
});
self.dialog.find("#plugin_appkeys_keygenerated_key_qrcode")
self.dialog
.find("#plugin_appkeys_keygenerated_key_qrcode")
.empty()
.qrcode(qrcode);
self.dialog.modal("show");
}
};
}
function UserAppKeysViewModel(parameters) {
@@ -48,15 +50,14 @@ $(function() {
self.keys = new ItemListHelper(
"plugin.appkeys.userkeys",
{
"app": function (a, b) {
app: function (a, b) {
// sorts ascending
if (a["app_id"].toLowerCase() < b["app_id"].toLowerCase()) return -1;
if (a["app_id"].toLowerCase() > b["app_id"].toLowerCase()) return 1;
return 0;
}
},
{
},
{},
"app",
[],
[],
@@ -67,51 +68,62 @@ $(function() {
self.editorApp = ko.observable();
self.requestData = function() {
OctoPrint.plugins.appkeys.getKeys()
.done(self.fromResponse);
self.requestData = function () {
OctoPrint.plugins.appkeys.getKeys().done(self.fromResponse);
};
self.fromResponse = function(response) {
self.fromResponse = function (response) {
self.keys.updateItems(response.keys);
self.pending = response.pending;
_.each(self.pending, function(data, token) {
_.each(self.pending, function (data, token) {
self.openRequests[token] = self.promptForAccess(data.app_id, token);
})
});
};
self.generateKey = function() {
return OctoPrint.plugins.appkeys.generateKey(self.editorApp())
self.generateKey = function () {
return OctoPrint.plugins.appkeys
.generateKey(self.editorApp())
.done(self.requestData)
.done(function() {
.done(function () {
self.editorApp("");
});
};
self.revokeKey = function(key) {
var perform = function() {
OctoPrint.plugins.appkeys.revokeKey(key)
.done(self.requestData);
self.revokeKey = function (key) {
var perform = function () {
OctoPrint.plugins.appkeys.revokeKey(key).done(self.requestData);
};
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: _.escape(key)}),
perform);
showConfirmationDialog(
_.sprintf(
gettext('You are about to revoke the application key "%(key)s".'),
{key: _.escape(key)}
),
perform
);
};
self.allowApp = function(token) {
return OctoPrint.plugins.appkeys.decide(token, true)
.done(self.requestData);
self.allowApp = function (token) {
return OctoPrint.plugins.appkeys.decide(token, true).done(self.requestData);
};
self.denyApp = function(token) {
return OctoPrint.plugins.appkeys.decide(token, false)
.done(self.requestData);
self.denyApp = function (token) {
return OctoPrint.plugins.appkeys.decide(token, false).done(self.requestData);
};
self.promptForAccess = function(app, token) {
var message = gettext("\"<strong>%(app)s</strong>\" has requested access to control OctoPrint through the API.");
self.promptForAccess = function (app, token) {
var message = gettext(
'"<strong>%(app)s</strong>" has requested access to control OctoPrint through the API.'
);
message = _.sprintf(message, {app: _.escape(app)});
message = "<p>" + message + "</p><p>" + gettext("Do you want to allow access to this application with your user account?") + "</p>";
message =
"<p>" +
message +
"</p><p>" +
gettext(
"Do you want to allow access to this application with your user account?"
) +
"</p>";
return new PNotify({
title: gettext("Access Request"),
text: message,
@@ -119,19 +131,22 @@ $(function() {
icon: "fa fa-key",
confirm: {
confirm: true,
buttons: [{
text: gettext("Allow"),
click: function(notice) {
self.allowApp(token);
notice.remove();
buttons: [
{
text: gettext("Allow"),
click: function (notice) {
self.allowApp(token);
notice.remove();
}
},
{
text: gettext("Deny"),
click: function (notice) {
self.denyApp(token);
notice.remove();
}
}
}, {
text: gettext("Deny"),
click: function(notice) {
self.denyApp(token);
notice.remove();
}
}]
]
},
buttons: {
sticker: false,
@@ -140,15 +155,15 @@ $(function() {
});
};
self.onUserSettingsShown = function() {
self.onUserSettingsShown = function () {
self.requestData();
};
self.onUserLoggedIn = function() {
self.onUserLoggedIn = function () {
self.requestData();
};
self.onDataUpdaterPluginMessage = function(plugin, data) {
self.onDataUpdaterPluginMessage = function (plugin, data) {
if (plugin !== "appkeys") {
return;
}
@@ -169,7 +184,6 @@ $(function() {
}
self.openRequests[token] = self.promptForAccess(app, token);
} else if (data.type === "end_request") {
token = data.user_token;
@@ -178,7 +192,7 @@ $(function() {
if (self.openRequests[token].state !== "closed") {
self.openRequests[token].remove();
}
delete self.openRequests[token]
delete self.openRequests[token];
}
}
};
@@ -193,7 +207,7 @@ $(function() {
self.keys = new ItemListHelper(
"plugin.appkeys.allkeys",
{
"user_app": function (a, b) {
user_app: function (a, b) {
// sorts ascending, first by user, then by app
if (a["user_id"] > b["user_id"]) return 1;
if (a["user_id"] < b["user_id"]) return -1;
@@ -204,8 +218,7 @@ $(function() {
return 0;
}
},
{
},
{},
"user_app",
[],
[],
@@ -219,29 +232,28 @@ $(function() {
self.markedForDeletion = ko.observableArray([]);
self.onSettingsShown = function() {
self.onSettingsShown = function () {
self.requestData();
self.editorUser(self.loginState.username());
self.editorApp("");
};
self.onUserLoggedIn = function() {
self.onUserLoggedIn = function () {
self.requestData();
self.editorUser(self.loginState.username());
self.editorApp("");
};
self.requestData = function() {
OctoPrint.plugins.appkeys.getAllKeys()
.done(self.fromResponse);
self.requestData = function () {
OctoPrint.plugins.appkeys.getAllKeys().done(self.fromResponse);
};
self.fromResponse = function(response) {
self.fromResponse = function (response) {
self.keys.updateItems(response.keys);
var users = [];
var apps = [];
_.each(response.keys, function(key) {
_.each(response.keys, function (key) {
users.push(key.user_id);
apps.push(key.app_id.toLowerCase());
});
@@ -255,77 +267,116 @@ $(function() {
self.apps(apps);
};
self.generateKey = function() {
return OctoPrint.plugins.appkeys.generateKeyForUser(self.editorUser(), self.editorApp())
self.generateKey = function () {
return OctoPrint.plugins.appkeys
.generateKeyForUser(self.editorUser(), self.editorApp())
.done(self.requestData)
.done(function() {
.done(function () {
self.editorUser(self.loginState.username());
self.editorApp("");
})
.done(function(data) {
.done(function (data) {
self.dialog.showDialog(gettext("New key generated!"), data);
});
}
};
self.revokeKey = function(key) {
var perform = function() {
OctoPrint.plugins.appkeys.revokeKey(key)
.done(self.requestData);
self.revokeKey = function (key) {
var perform = function () {
OctoPrint.plugins.appkeys.revokeKey(key).done(self.requestData);
};
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: _.escape(key)}),
perform);
showConfirmationDialog(
_.sprintf(
gettext('You are about to revoke the application key "%(key)s".'),
{key: _.escape(key)}
),
perform
);
};
self.revokeMarked = function() {
var perform = function() {
self._bulkRevoke(self.markedForDeletion())
.done(function() {
self.markedForDeletion.removeAll();
});
self.revokeMarked = function () {
var perform = function () {
self._bulkRevoke(self.markedForDeletion()).done(function () {
self.markedForDeletion.removeAll();
});
};
showConfirmationDialog(_.sprintf(gettext("You are about to revoke %(count)d application keys."), {count: self.markedForDeletion().length}),
perform);
showConfirmationDialog(
_.sprintf(
gettext("You are about to revoke %(count)d application keys."),
{count: self.markedForDeletion().length}
),
perform
);
};
self.markAllOnPageForDeletion = function() {
self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(self.keys.paginatedItems(), "api_key"))));
self.markAllOnPageForDeletion = function () {
self.markedForDeletion(
_.uniq(
self
.markedForDeletion()
.concat(_.map(self.keys.paginatedItems(), "api_key"))
)
);
};
self.markAllForDeletion = function() {
self.markAllForDeletion = function () {
self.markedForDeletion(_.uniq(_.map(self.keys.allItems, "api_key")));
};
self.markAllByUserForDeletion = function(user) {
self.markAllByFilterForDeletion(function(e) { return (e.user_id === user); });
self.markAllByUserForDeletion = function (user) {
self.markAllByFilterForDeletion(function (e) {
return e.user_id === user;
});
};
self.markAllByAppForDeletion = function(app) {
self.markAllByFilterForDeletion(function(e) { return (e.app_id.toLowerCase() === app); })
self.markAllByAppForDeletion = function (app) {
self.markAllByFilterForDeletion(function (e) {
return e.app_id.toLowerCase() === app;
});
};
self.markAllByFilterForDeletion = function(filter) {
self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(_.filter(self.keys.allItems, filter), "api_key"))));
self.markAllByFilterForDeletion = function (filter) {
self.markedForDeletion(
_.uniq(
self
.markedForDeletion()
.concat(_.map(_.filter(self.keys.allItems, filter), "api_key"))
)
);
};
self.clearMarked = function() {
self.clearMarked = function () {
self.markedForDeletion.removeAll();
};
self._bulkRevoke = function(keys) {
self._bulkRevoke = function (keys) {
var title, message, handler;
title = gettext("Revoking application keys");
message = _.sprintf(gettext("Revoking %(count)d application keys..."), {count: keys.length});
handler = function(key) {
return OctoPrint.plugins.appkeys.revokeKey(key)
.done(function() {
deferred.notify(_.sprintf(gettext("Revoked %(key)s..."), {key: _.escape(key)}), true);
message = _.sprintf(gettext("Revoking %(count)d application keys..."), {
count: keys.length
});
handler = function (key) {
return OctoPrint.plugins.appkeys
.revokeKey(key)
.done(function () {
deferred.notify(
_.sprintf(gettext("Revoked %(key)s..."), {
key: _.escape(key)
}),
true
);
})
.fail(function(jqXHR) {
var short = _.sprintf(gettext("Revocation of %(key)s failed, continuing..."), {key: _.escape(key)});
var long = _.sprintf(gettext("Deletion of %(key)s failed: %(error)s"), {key: _.escape(key), error: _.escape(jqXHR.responseText)});
.fail(function (jqXHR) {
var short = _.sprintf(
gettext("Revocation of %(key)s failed, continuing..."),
{key: _.escape(key)}
);
var long = _.sprintf(
gettext("Deletion of %(key)s failed: %(error)s"),
{key: _.escape(key), error: _.escape(jqXHR.responseText)}
);
deferred.notify(short, long, false);
});
};
@@ -343,25 +394,20 @@ $(function() {
showProgressModal(options, promise);
var requests = [];
_.each(keys, function(key) {
_.each(keys, function (key) {
var request = handler(key);
requests.push(request)
requests.push(request);
});
$.when.apply($, _.map(requests, wrapPromiseWithAlways)).done(function () {
deferred.resolve();
self.requestData();
});
$.when.apply($, _.map(requests, wrapPromiseWithAlways))
.done(function() {
deferred.resolve();
self.requestData();
});
return promise;
};
}
OCTOPRINT_VIEWMODELS.push([
AppKeysDialogViewModel,
[],
[]
]);
OCTOPRINT_VIEWMODELS.push([AppKeysDialogViewModel, [], []]);
OCTOPRINT_VIEWMODELS.push([
UserAppKeysViewModel,
@@ -373,5 +419,5 @@ $(function() {
AllAppKeysViewModel,
["appKeysDialogViewModel", "loginStateViewModel", "accessViewModel"],
["#settings_plugin_appkeys"]
])
]);
});
@@ -36,4 +36,3 @@
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</button>
</div>
</div>
File diff suppressed because it is too large. Load diff
@@ -4,17 +4,17 @@
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var OctoPrintBackupClient = function(base) {
})(this, function (OctoPrintClient) {
var OctoPrintBackupClient = function (base) {
this.base = base;
this.url = this.base.getBlueprintUrl("backup");
};
OctoPrintBackupClient.prototype.get = function(refresh, opts) {
OctoPrintBackupClient.prototype.get = function (refresh, opts) {
return this.base.get(this.url, opts);
};
OctoPrintBackupClient.prototype.createBackup = function(exclude, opts) {
OctoPrintBackupClient.prototype.createBackup = function (exclude, opts) {
exclude = exclude || [];
var data = {
@@ -24,11 +24,11 @@
return this.base.postJson(this.url + "backup", data, opts);
};
OctoPrintBackupClient.prototype.deleteBackup = function(backup, opts) {
OctoPrintBackupClient.prototype.deleteBackup = function (backup, opts) {
return this.base.delete(this.url + "backup/" + backup, opts);
};
OctoPrintBackupClient.prototype.restoreBackup = function(backup, opts) {
OctoPrintBackupClient.prototype.restoreBackup = function (backup, opts) {
var data = {
path: backup
};
+179 -86
View File
@@ -1,4 +1,4 @@
$(function() {
$(function () {
function BackupViewModel(parameters) {
var self = this;
@@ -8,15 +8,14 @@ $(function() {
self.backups = new ItemListHelper(
"plugin.backup.backups",
{
"date": function (a, b) {
date: function (a, b) {
// sorts descending
if (a["date"] > b["date"]) return -1;
if (a["date"] < b["date"]) return 1;
return 0;
}
},
{
},
{},
"date",
[],
[],
@@ -37,7 +36,7 @@ $(function() {
maxNumberOfFiles: 1,
autoUpload: false,
headers: OctoPrint.getRequestHeaders(),
add: function(e, data) {
add: function (e, data) {
if (data.files.length === 0) {
// no files? ignore
return false;
@@ -46,7 +45,7 @@ $(function() {
self.backupUploadName(data.files[0].name);
self.backupUploadData = data;
},
done: function(e, data) {
done: function (e, data) {
self.backupUploadName(undefined);
self.backupUploadData = undefined;
}
@@ -63,113 +62,151 @@ $(function() {
self.loglines = ko.observableArray([]);
self.requestData = function() {
OctoPrint.plugins.backup.get()
.done(self.fromResponse);
self.requestData = function () {
OctoPrint.plugins.backup.get().done(self.fromResponse);
};
self.fromResponse = function(response) {
self.fromResponse = function (response) {
self.backups.updateItems(response.backups);
self.unknownPlugins(response.unknown_plugins);
self.restoreSupported(response.restore_supported);
};
self.createBackup = function() {
self.createBackup = function () {
var excluded = self.excludeFromBackup();
OctoPrint.plugins.backup.createBackup(excluded)
.done(function() {
self.excludeFromBackup([]);
})
OctoPrint.plugins.backup.createBackup(excluded).done(function () {
self.excludeFromBackup([]);
});
};
self.removeBackup = function(backup) {
var perform = function() {
OctoPrint.plugins.backup.deleteBackup(backup)
.done(function() {
self.requestData();
});
self.removeBackup = function (backup) {
var perform = function () {
OctoPrint.plugins.backup.deleteBackup(backup).done(function () {
self.requestData();
});
};
showConfirmationDialog(_.sprintf(gettext("You are about to delete backup file \"%(name)s\"."), {name: _.escape(backup)}),
perform);
showConfirmationDialog(
_.sprintf(gettext('You are about to delete backup file "%(name)s".'), {
name: _.escape(backup)
}),
perform
);
};
self.restoreBackup = function(backup) {
self.restoreBackup = function (backup) {
if (!self.restoreSupported()) return;
var perform = function() {
var perform = function () {
self.restoreInProgress(true);
self.loglines.removeAll();
self.loglines.push({line: "Preparing to restore...", stream: "message"});
self.loglines.push({line: " ", stream: "message"});
self.restoreDialog.modal({keyboard: false, backdrop: "static", show: true});
self.restoreDialog.modal({
keyboard: false,
backdrop: "static",
show: true
});
OctoPrint.plugins.backup.restoreBackup(backup);
};
showConfirmationDialog(_.sprintf(gettext("You are about to restore the backup file \"%(name)s\". This cannot be undone."), {name: _.escape(backup)}),
perform);
showConfirmationDialog(
_.sprintf(
gettext(
'You are about to restore the backup file "%(name)s". This cannot be undone.'
),
{name: _.escape(backup)}
),
perform
);
};
self.performRestoreFromUpload = function() {
self.performRestoreFromUpload = function () {
if (self.backupUploadData === undefined) return;
var perform = function() {
var perform = function () {
self.restoreInProgress(true);
self.loglines.removeAll();
self.loglines.push({line: "Uploading backup, this can take a while. Please wait...", stream: "message"});
self.loglines.push({
line: "Uploading backup, this can take a while. Please wait...",
stream: "message"
});
self.loglines.push({line: " ", stream: "message"});
self.restoreDialog.modal({keyboard: false, backdrop: "static", show: true});
self.restoreDialog.modal({
keyboard: false,
backdrop: "static",
show: true
});
self.backupUploadData.submit();
};
showConfirmationDialog(_.sprintf(gettext("You are about to upload and restore the backup file \"%(name)s\". This cannot be undone."), {name: _.escape(self.backupUploadName())}),
perform);
showConfirmationDialog(
_.sprintf(
gettext(
'You are about to upload and restore the backup file "%(name)s". This cannot be undone.'
),
{name: _.escape(self.backupUploadName())}
),
perform
);
};
self.deleteUnknownPluginRecord = function() {
var perform = function() {
OctoPrint.plugins.backup.deleteUnknownPlugins()
.done(function() {
self.requestData();
});
self.deleteUnknownPluginRecord = function () {
var perform = function () {
OctoPrint.plugins.backup.deleteUnknownPlugins().done(function () {
self.requestData();
});
};
showConfirmationDialog(gettext("You are about to delete the record of plugins unknown during the last restore."),
perform);
showConfirmationDialog(
gettext(
"You are about to delete the record of plugins unknown during the last restore."
),
perform
);
};
self.markFilesOnPage = function() {
self.markedForBackupDeletion(_.uniq(self.markedForBackupDeletion().concat(_.map(self.backups.paginatedItems(), "name"))));
self.markFilesOnPage = function () {
self.markedForBackupDeletion(
_.uniq(
self
.markedForBackupDeletion()
.concat(_.map(self.backups.paginatedItems(), "name"))
)
);
};
self.markAllFiles = function() {
self.markAllFiles = function () {
self.markedForBackupDeletion(_.map(self.backups.allItems, "name"));
};
self.clearMarkedFiles = function() {
self.clearMarkedFiles = function () {
self.markedForBackupDeletion.removeAll();
};
self.removeMarkedFiles = function() {
var perform = function() {
self._bulkRemove(self.markedForBackupDeletion())
.done(function() {
self.markedForBackupDeletion.removeAll();
});
self.removeMarkedFiles = function () {
var perform = function () {
self._bulkRemove(self.markedForBackupDeletion()).done(function () {
self.markedForBackupDeletion.removeAll();
});
};
showConfirmationDialog(_.sprintf(gettext("You are about to delete %(count)d backups."), {count: self.markedForBackupDeletion().length}),
perform);
showConfirmationDialog(
_.sprintf(gettext("You are about to delete %(count)d backups."), {
count: self.markedForBackupDeletion().length
}),
perform
);
};
self.onStartup = function() {
self.onStartup = function () {
self.restoreDialog = $("#settings_plugin_backup_restoredialog");
self.restoreOutput = $("#settings_plugin_backup_restoredialog_output");
};
self.onSettingsShown = function() {
self.onSettingsShown = function () {
self.requestData();
};
self.onDataUpdaterPluginMessage = function(plugin, data) {
self.onDataUpdaterPluginMessage = function (plugin, data) {
if (plugin !== "backup") return;
if (data.type === "backup_done") {
@@ -186,74 +223,131 @@ $(function() {
self.backupInProgress(false);
new PNotify({
title: gettext("Creating the backup failed"),
text: _.sprintf(gettext("OctoPrint could not create your backup. Please consult <code>octoprint.log</code> for details. Error: %(error)s"), {error: _.escape(data.error)}),
text: _.sprintf(
gettext(
"OctoPrint could not create your backup. Please consult <code>octoprint.log</code> for details. Error: %(error)s"
),
{error: _.escape(data.error)}
),
type: "error",
hide: false
});
} else if (data.type === "restore_started") {
self.loglines.push({line: gettext("Restoring from backup..."), stream: "message"});
self.loglines.push({
line: gettext("Restoring from backup..."),
stream: "message"
});
self.loglines.push({line: " ", stream: "message"});
} else if (data.type === "restore_failed") {
self.loglines.push({line: " ", stream: "message"});
self.loglines.push({line: gettext("Restore failed! Check the above output and octoprint.log for reasons as to why."), stream: "error"});
self.loglines.push({
line: gettext(
"Restore failed! Check the above output and octoprint.log for reasons as to why."
),
stream: "error"
});
self.restoreInProgress(false);
} else if (data.type === "restore_done") {
self.loglines.push({line: " ", stream: "message"});
self.loglines.push({line: gettext("Restore successful! The server will now be restarted!"), stream: "message"});
self.loglines.push({
line: gettext(
"Restore successful! The server will now be restarted!"
),
stream: "message"
});
self.restoreInProgress(false);
} else if (data.type === "installing_plugin") {
self.loglines.push({line: " ", stream: "message"});
self.loglines.push({
line: _.sprintf(gettext("Installing plugin \"%(plugin)s\"..."), {plugin: _.escape(data.plugin)}),
line: _.sprintf(gettext('Installing plugin "%(plugin)s"...'), {
plugin: _.escape(data.plugin)
}),
stream: "message"
});
} else if (data.type === "plugin_incompatible") {
self.loglines.push({line: " ", stream: "message"});
self.loglines.push({
line: _.sprintf(gettext("Cannot install plugin \"%(plugin)s\" due to it being incompatible to this OctoPrint version and/or underlying operating system"), {plugin: _.escape(data.plugin.key)}),
line: _.sprintf(
gettext(
'Cannot install plugin "%(plugin)s" due to it being incompatible to this OctoPrint version and/or underlying operating system'
),
{plugin: _.escape(data.plugin.key)}
),
stream: "stderr"
});
} else if (data.type === "unknown_plugins") {
if (data.plugins.length > 0) {
self.loglines.push({line: " ", stream: "message"});
self.loglines.push({line: _.sprintf(gettext("There are %(count)d plugins you'll need to install manually since they aren't registered on the repository:"), {count: data.plugins.length}), stream: "message"});
_.each(data.plugins, function(plugin) {
self.loglines.push({line: plugin.name + ": " + plugin.url, stream: "message"});
self.loglines.push({
line: _.sprintf(
gettext(
"There are %(count)d plugins you'll need to install manually since they aren't registered on the repository:"
),
{count: data.plugins.length}
),
stream: "message"
});
_.each(data.plugins, function (plugin) {
self.loglines.push({
line: plugin.name + ": " + plugin.url,
stream: "message"
});
});
self.loglines.push({line: " ", stream: "message"});
self.unknownPlugins(data.plugins);
}
} else if (data.type === "logline") {
self.loglines.push(self._preprocessLine({line: data.line, stream: data.stream}));
self.loglines.push(
self._preprocessLine({line: data.line, stream: data.stream})
);
self._scrollRestoreOutputToEnd();
}
};
self._scrollRestoreOutputToEnd = function() {
self.restoreOutput.scrollTop(self.restoreOutput[0].scrollHeight - self.restoreOutput.height());
self._scrollRestoreOutputToEnd = function () {
self.restoreOutput.scrollTop(
self.restoreOutput[0].scrollHeight - self.restoreOutput.height()
);
};
self._forcedStdoutLine = /You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./;
self._preprocessLine = function(line) {
self._preprocessLine = function (line) {
if (line.stream === "stderr" && line.line.match(self._forcedStdoutLine)) {
line.stream = "stdout";
}
return line;
};
self._bulkRemove = function(files) {
self._bulkRemove = function (files) {
var title, message, handler;
title = gettext("Deleting backups");
message = _.sprintf(gettext("Deleting %(count)d backups..."), {count: files.length});
handler = function(filename) {
return OctoPrint.plugins.backup.deleteBackup(filename)
.done(function() {
deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: _.escape(filename)}), true);
message = _.sprintf(gettext("Deleting %(count)d backups..."), {
count: files.length
});
handler = function (filename) {
return OctoPrint.plugins.backup
.deleteBackup(filename)
.done(function () {
deferred.notify(
_.sprintf(gettext("Deleted %(filename)s..."), {
filename: _.escape(filename)
}),
true
);
})
.fail(function(jqXHR) {
var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: _.escape(filename)});
var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: _.escape(filename), error: _.escape(jqXHR.responseText)});
.fail(function (jqXHR) {
var short = _.sprintf(
gettext("Deletion of %(filename)s failed, continuing..."),
{filename: _.escape(filename)}
);
var long = _.sprintf(
gettext("Deletion of %(filename)s failed: %(error)s"),
{
filename: _.escape(filename),
error: _.escape(jqXHR.responseText)
}
);
deferred.notify(short, long, false);
});
};
@@ -271,15 +365,14 @@ $(function() {
showProgressModal(options, promise);
var requests = [];
_.each(files, function(filename) {
_.each(files, function (filename) {
var request = handler(filename);
requests.push(request)
requests.push(request);
});
$.when.apply($, _.map(requests, wrapPromiseWithAlways)).done(function () {
deferred.resolve();
self.requestData();
});
$.when.apply($, _.map(requests, wrapPromiseWithAlways))
.done(function() {
deferred.resolve();
self.requestData();
});
return promise;
};
+96 -81
View File
@@ -1,125 +1,140 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
from flask_babel import gettext
import octoprint.plugin
from flask_babel import gettext
from .subwizards import Subwizards
class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.WizardPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.BlueprintPlugin,
Subwizards):
class CoreWizardPlugin(
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.WizardPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.BlueprintPlugin,
Subwizards,
):
#~~ TemplatePlugin API
# ~~ TemplatePlugin API
def get_template_configs(self):
required = self._get_subwizard_attrs("_is_", "_wizard_required")
names = self._get_subwizard_attrs("_get_", "_wizard_name")
additional = self._get_subwizard_attrs("_get_", "_additional_wizard_template_data")
def get_template_configs(self):
required = self._get_subwizard_attrs("_is_", "_wizard_required")
names = self._get_subwizard_attrs("_get_", "_wizard_name")
additional = self._get_subwizard_attrs(
"_get_", "_additional_wizard_template_data"
)
firstrunonly = self._get_subwizard_attrs("_is_", "_wizard_firstrunonly")
firstrun = self._settings.global_get(["server", "firstRun"])
firstrunonly = self._get_subwizard_attrs("_is_", "_wizard_firstrunonly")
firstrun = self._settings.global_get(["server", "firstRun"])
if not firstrun:
required = dict((key, value) for key, value in required.items()
if not firstrunonly.get(key, lambda: False)())
if not firstrun:
required = dict(
(key, value)
for key, value in required.items()
if not firstrunonly.get(key, lambda: False)()
)
result = list()
for key, method in required.items():
if not callable(method):
continue
result = list()
for key, method in required.items():
if not callable(method):
continue
if not method():
continue
if not method():
continue
if not key in names:
continue
if key not in names:
continue
name = names[key]()
if not name:
continue
name = names[key]()
if not name:
continue
config = {"type": "wizard",
"name": name,
"template": "corewizard_{}_wizard.jinja2".format(key),
"div": "wizard_plugin_corewizard_{}".format(key),
"suffix": "_{}".format(key)}
if key in additional:
additional_result = additional[key]()
if additional_result:
config.update(additional_result)
result.append(config)
config = {
"type": "wizard",
"name": name,
"template": "corewizard_{}_wizard.jinja2".format(key),
"div": "wizard_plugin_corewizard_{}".format(key),
"suffix": "_{}".format(key),
}
if key in additional:
additional_result = additional[key]()
if additional_result:
config.update(additional_result)
result.append(config)
return result
return result
#~~ AssetPlugin API
# ~~ AssetPlugin API
def get_assets(self):
if self.is_wizard_required():
return {"js": ["js/corewizard.js"],
"css": ["css/corewizard.css"]}
else:
return {}
def get_assets(self):
if self.is_wizard_required():
return {"js": ["js/corewizard.js"], "css": ["css/corewizard.css"]}
else:
return {}
#~~ WizardPlugin API
# ~~ WizardPlugin API
def is_wizard_required(self):
required = self._get_subwizard_attrs("_is_", "_wizard_required")
firstrunonly = self._get_subwizard_attrs("_is_", "_wizard_firstrunonly")
firstrun = self._settings.global_get(["server", "firstRun"])
def is_wizard_required(self):
required = self._get_subwizard_attrs("_is_", "_wizard_required")
firstrunonly = self._get_subwizard_attrs("_is_", "_wizard_firstrunonly")
firstrun = self._settings.global_get(["server", "firstRun"])
if not firstrun:
required = dict((key, value) for key, value in required.items()
if not firstrunonly.get(key, lambda: False)())
any_required = any(map(lambda m: m(), required.values()))
if not firstrun:
required = dict(
(key, value)
for key, value in required.items()
if not firstrunonly.get(key, lambda: False)()
)
any_required = any(map(lambda m: m(), required.values()))
return any_required
return any_required
def get_wizard_details(self):
result = {}
def get_wizard_details(self):
result = {}
def add_result(key, method):
result[key] = method()
self._get_subwizard_attrs("_get_", "_wizard_details", add_result)
def add_result(key, method):
result[key] = method()
return result
self._get_subwizard_attrs("_get_", "_wizard_details", add_result)
def get_wizard_version(self):
return 3
return result
#~~ helpers
def get_wizard_version(self):
return 3
def _get_subwizard_attrs(self, start, end, callback=None):
result = {}
# ~~ helpers
for item in dir(self):
if not item.startswith(start) or not item.endswith(end):
continue
def _get_subwizard_attrs(self, start, end, callback=None):
result = {}
key = item[len(start):-len(end)]
if not key:
continue
for item in dir(self):
if not item.startswith(start) or not item.endswith(end):
continue
attr = getattr(self, item)
if callable(callback):
callback(key, attr)
result[key] = attr
key = item[len(start) : -len(end)]
if not key:
continue
return result
attr = getattr(self, item)
if callable(callback):
callback(key, attr)
result[key] = attr
return result
__plugin_name__ = "Core Wizard"
__plugin_author__ = "Gina Häußge"
__plugin_description__ = "Provides wizard dialogs for core components and functionality"
__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to perform "
"setup steps that might be required after an update.")
__plugin_disabling_discouraged__ = gettext(
"Without this plugin OctoPrint will no longer be able to perform "
"setup steps that might be required after an update."
)
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = CoreWizardPlugin()
@@ -1,4 +1,4 @@
$(function() {
$(function () {
function CoreWizardAclViewModel(parameters) {
var self = this;
@@ -13,84 +13,97 @@ $(function() {
self.required = false;
self.passwordMismatch = ko.pureComputed(function() {
self.passwordMismatch = ko.pureComputed(function () {
return self.password() != self.confirmedPassword();
});
self.validUsername = ko.pureComputed(function() {
self.validUsername = ko.pureComputed(function () {
return self.username() && self.username().trim() != "";
});
self.validPassword = ko.pureComputed(function() {
self.validPassword = ko.pureComputed(function () {
return self.password() && self.password().trim() != "";
});
self.validData = ko.pureComputed(function() {
return !self.passwordMismatch() && self.validUsername() && self.validPassword();
self.validData = ko.pureComputed(function () {
return (
!self.passwordMismatch() && self.validUsername() && self.validPassword()
);
});
self.keepAccessControl = function() {
self.keepAccessControl = function () {
if (!self.validData()) return;
var data = {
"ac": true,
"user": self.username(),
"pass1": self.password(),
"pass2": self.confirmedPassword()
ac: true,
user: self.username(),
pass1: self.password(),
pass2: self.confirmedPassword()
};
self._sendData(data);
};
self.disableAccessControl = function() {
var message = gettext("If you disable Access Control <strong>and</strong> your OctoPrint installation is accessible from the internet, your printer <strong>will be accessible by everyone - that also includes the bad guys!</strong>");
self.disableAccessControl = function () {
var message = gettext(
"If you disable Access Control <strong>and</strong> your OctoPrint installation is accessible from the internet, your printer <strong>will be accessible by everyone - that also includes the bad guys!</strong>"
);
showConfirmationDialog({
message: message,
onproceed: function (e) {
var data = {
"ac": false
ac: false
};
self._sendData(data);
}
});
};
self._sendData = function(data, callback) {
OctoPrint.postJson("plugin/corewizard/acl", data)
.done(function() {
self.setup(true);
self.decision(data.ac);
if (data.ac) {
// we now log the user in
var user = data.user;
var pass = data.pass1;
self.loginStateViewModel.login(user, pass, true)
.done(function() {
if (callback) callback();
});
} else {
self._sendData = function (data, callback) {
OctoPrint.postJson("plugin/corewizard/acl", data).done(function () {
self.setup(true);
self.decision(data.ac);
if (data.ac) {
// we now log the user in
var user = data.user;
var pass = data.pass1;
self.loginStateViewModel.login(user, pass, true).done(function () {
if (callback) callback();
}
});
});
} else {
if (callback) callback();
}
});
};
self.onBeforeWizardTabChange = function(next, current) {
self.onBeforeWizardTabChange = function (next, current) {
if (!self.required) return true;
if (!current || !_.startsWith(current, "wizard_plugin_corewizard_acl_") || self.setup()) {
if (
!current ||
!_.startsWith(current, "wizard_plugin_corewizard_acl_") ||
self.setup()
) {
return true;
}
showMessageDialog({
title: gettext("Please set up Access Control"),
message: gettext("You haven't yet set up access control. You need to either setup a username and password and click \"Keep Access Control Enabled\" or click \"Disable Access Control\" before continuing")
message: gettext(
'You haven\'t yet set up access control. You need to either setup a username and password and click "Keep Access Control Enabled" or click "Disable Access Control" before continuing'
)
});
return false;
};
self.onWizardDetails = function(response) {
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.acl && response.corewizard.details.acl.required;
self.onWizardDetails = function (response) {
self.required =
response &&
response.corewizard &&
response.corewizard.details &&
response.corewizard.details.acl &&
response.corewizard.details.acl.required;
};
self.onWizardFinish = function() {
self.onWizardFinish = function () {
if (!self.required) return;
if (!self.decision()) {
@@ -106,17 +119,25 @@ $(function() {
self.required = false;
self.onWizardDetails = function(response) {
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.webcam && response.corewizard.details.webcam.required;
self.onWizardDetails = function (response) {
self.required =
response &&
response.corewizard &&
response.corewizard.details &&
response.corewizard.details.webcam &&
response.corewizard.details.webcam.required;
};
self.onWizardFinish = function() {
self.onWizardFinish = function () {
if (!self.required) return;
if (self.settingsViewModel.webcam_streamUrl()
|| (self.settingsViewModel.webcam_snapshotUrl() && self.settingsViewModel.webcam_ffmpegPath())) {
if (
self.settingsViewModel.webcam_streamUrl() ||
(self.settingsViewModel.webcam_snapshotUrl() &&
self.settingsViewModel.webcam_ffmpegPath())
) {
return "reload";
}
}
};
}
function CoreWizardServerCommandsViewModel(parameters) {
@@ -136,22 +157,26 @@ $(function() {
self.required = false;
self.active = false;
self.enableOnlineCheck = function() {
self.enableOnlineCheck = function () {
self.settingsViewModel.server_onlineCheck_enabled(true);
self.decision(true);
self._sendData();
};
self.disableOnlineCheck = function() {
self.disableOnlineCheck = function () {
self.settingsViewModel.server_onlineCheck_enabled(false);
self.decision(false);
self._sendData();
};
self.onBeforeWizardTabChange = function(next, current) {
self.onBeforeWizardTabChange = function (next, current) {
if (!self.required) return true;
if (!current || !_.startsWith(current, "wizard_plugin_corewizard_onlinecheck_") || self.setup()) {
if (
!current ||
!_.startsWith(current, "wizard_plugin_corewizard_onlinecheck_") ||
self.setup()
) {
return true;
}
@@ -159,7 +184,7 @@ $(function() {
return false;
};
self.onBeforeWizardFinish = function() {
self.onBeforeWizardFinish = function () {
if (!self.required) return true;
if (self.setup()) {
@@ -170,18 +195,25 @@ $(function() {
return false;
};
self.onWizardDetails = function(response) {
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.onlinecheck && response.corewizard.details.onlinecheck.required;
self.onWizardDetails = function (response) {
self.required =
response &&
response.corewizard &&
response.corewizard.details &&
response.corewizard.details.onlinecheck &&
response.corewizard.details.onlinecheck.required;
};
self._showDecisionNeededDialog = function() {
self._showDecisionNeededDialog = function () {
showMessageDialog({
title: gettext("Please set up the online connectivity check"),
message: gettext("You haven't yet decided on whether to enable or disable the online connectivity check. You need to either enable or disable it before continuing.")
message: gettext(
"You haven't yet decided on whether to enable or disable the online connectivity check. You need to either enable or disable it before continuing."
)
});
};
self._sendData = function() {
self._sendData = function () {
var data = {
server: {
onlineCheck: {
@@ -194,13 +226,11 @@ $(function() {
};
self.active = true;
self.settingsViewModel.saveData(data)
.done(function() {
self.setup(true);
self.active = false;
});
self.settingsViewModel.saveData(data).done(function () {
self.setup(true);
self.active = false;
});
};
}
function CoreWizardPluginBlacklistViewModel(parameters) {
@@ -214,22 +244,26 @@ $(function() {
self.required = false;
self.active = false;
self.enablePluginBlacklist = function() {
self.enablePluginBlacklist = function () {
self.settingsViewModel.server_pluginBlacklist_enabled(true);
self.decision(true);
self._sendData();
};
self.disablePluginBlacklist = function() {
self.disablePluginBlacklist = function () {
self.settingsViewModel.server_pluginBlacklist_enabled(false);
self.decision(false);
self._sendData();
};
self.onBeforeWizardTabChange = function(next, current) {
self.onBeforeWizardTabChange = function (next, current) {
if (!self.required) return true;
if (!current || !_.startsWith(current, "wizard_plugin_corewizard_pluginblacklist_") || self.setup()) {
if (
!current ||
!_.startsWith(current, "wizard_plugin_corewizard_pluginblacklist_") ||
self.setup()
) {
return true;
}
@@ -237,7 +271,7 @@ $(function() {
return false;
};
self.onBeforeWizardFinish = function() {
self.onBeforeWizardFinish = function () {
if (!self.required) return true;
if (self.setup()) {
@@ -248,18 +282,25 @@ $(function() {
return false;
};
self.onWizardDetails = function(response) {
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.pluginblacklist && response.corewizard.details.pluginblacklist.required;
self.onWizardDetails = function (response) {
self.required =
response &&
response.corewizard &&
response.corewizard.details &&
response.corewizard.details.pluginblacklist &&
response.corewizard.details.pluginblacklist.required;
};
self._showDecisionNeededDialog = function() {
self._showDecisionNeededDialog = function () {
showMessageDialog({
title: gettext("Please set up the plugin blacklist processing"),
message: gettext("You haven't yet decided on whether to enable or disable the plugin blacklist processing. You need to either enable or disable it before continuing.")
message: gettext(
"You haven't yet decided on whether to enable or disable the plugin blacklist processing. You need to either enable or disable it before continuing."
)
});
};
self._sendData = function() {
self._sendData = function () {
var data = {
server: {
pluginBlacklist: {
@@ -269,13 +310,11 @@ $(function() {
};
self.active = true;
self.settingsViewModel.saveData(data)
.done(function() {
self.setup(true);
self.active = false;
});
self.settingsViewModel.saveData(data).done(function () {
self.setup(true);
self.active = false;
});
};
}
function CoreWizardPrinterProfileViewModel(parameters) {
@@ -288,54 +327,68 @@ $(function() {
self.editor = self.printerProfiles.createProfileEditor();
self.editorLoaded = ko.observable(false);
self.onWizardDetails = function(response) {
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.printerprofile && response.corewizard.details.printerprofile.required;
self.onWizardDetails = function (response) {
self.required =
response &&
response.corewizard &&
response.corewizard.details &&
response.corewizard.details.printerprofile &&
response.corewizard.details.printerprofile.required;
if (!self.required) return;
OctoPrint.printerprofiles.get("_default")
.done(function(data) {
OctoPrint.printerprofiles
.get("_default")
.done(function (data) {
self.editor.fromProfileData(data);
self.editorLoaded(true);
})
.fail(function() {
.fail(function () {
self.editor.fromProfileData();
self.editorLoaded(true);
});
};
self.onWizardFinish = function() {
self.onWizardFinish = function () {
if (!self.required) return;
OctoPrint.printerprofiles.update("_default", self.editor.toProfileData())
.done(function() {
OctoPrint.printerprofiles
.update("_default", self.editor.toProfileData())
.done(function () {
self.printerProfiles.requestData();
});
};
}
OCTOPRINT_VIEWMODELS.push({
construct: CoreWizardAclViewModel,
dependencies: ["loginStateViewModel"],
elements: ["#wizard_plugin_corewizard_acl"]
}, {
construct: CoreWizardWebcamViewModel,
dependencies: ["settingsViewModel"],
elements: ["#wizard_plugin_corewizard_webcam"]
}, {
construct: CoreWizardServerCommandsViewModel,
dependencies: ["settingsViewModel"],
elements: ["#wizard_plugin_corewizard_servercommands"]
}, {
construct: CoreWizardOnlineCheckViewModel,
dependencies: ["settingsViewModel"],
elements: ["#wizard_plugin_corewizard_onlinecheck"]
}, {
construct: CoreWizardPluginBlacklistViewModel,
dependencies: ["settingsViewModel"],
elements: ["#wizard_plugin_corewizard_pluginblacklist"]
}, {
construct: CoreWizardPrinterProfileViewModel,
dependencies: ["printerProfilesViewModel"],
elements: ["#wizard_plugin_corewizard_printerprofile"]
});
OCTOPRINT_VIEWMODELS.push(
{
construct: CoreWizardAclViewModel,
dependencies: ["loginStateViewModel"],
elements: ["#wizard_plugin_corewizard_acl"]
},
{
construct: CoreWizardWebcamViewModel,
dependencies: ["settingsViewModel"],
elements: ["#wizard_plugin_corewizard_webcam"]
},
{
construct: CoreWizardServerCommandsViewModel,
dependencies: ["settingsViewModel"],
elements: ["#wizard_plugin_corewizard_servercommands"]
},
{
construct: CoreWizardOnlineCheckViewModel,
dependencies: ["settingsViewModel"],
elements: ["#wizard_plugin_corewizard_onlinecheck"]
},
{
construct: CoreWizardPluginBlacklistViewModel,
dependencies: ["settingsViewModel"],
elements: ["#wizard_plugin_corewizard_pluginblacklist"]
},
{
construct: CoreWizardPrinterProfileViewModel,
dependencies: ["printerProfilesViewModel"],
elements: ["#wizard_plugin_corewizard_printerprofile"]
}
);
});
+124 -90
View File
@@ -1,152 +1,186 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import octoprint.plugin
import sys
import inspect
import sys
from flask_babel import gettext
import octoprint.plugin
from octoprint.access import ADMIN_GROUP, USER_GROUP
from octoprint.util import to_native_str
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class ServerCommandsSubwizard(object):
def _is_servercommands_wizard_firstrunonly(self):
return True
def _is_servercommands_wizard_firstrunonly(self):
return True
def _is_servercommands_wizard_required(self):
system_shutdown_command = self._settings.global_get(["server", "commands", "systemShutdownCommand"])
system_restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"])
server_restart_command = self._settings.global_get(["server", "commands", "serverRestartCommand"])
def _is_servercommands_wizard_required(self):
system_shutdown_command = self._settings.global_get(
["server", "commands", "systemShutdownCommand"]
)
system_restart_command = self._settings.global_get(
["server", "commands", "systemRestartCommand"]
)
server_restart_command = self._settings.global_get(
["server", "commands", "serverRestartCommand"]
)
return not (system_shutdown_command and system_restart_command and server_restart_command)
return not (
system_shutdown_command and system_restart_command and server_restart_command
)
def _get_servercommands_wizard_details(self):
return {"required": self._is_servercommands_wizard_required()}
def _get_servercommands_wizard_details(self):
return {"required": self._is_servercommands_wizard_required()}
def _get_servercommands_wizard_name(self):
return gettext("Server Commands")
def _get_servercommands_wizard_name(self):
return gettext("Server Commands")
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class WebcamSubwizard(object):
def _is_webcam_wizard_firstrunonly(self):
return True
def _is_webcam_wizard_firstrunonly(self):
return True
def _is_webcam_wizard_required(self):
webcam_snapshot_url = self._settings.global_get(["webcam", "snapshot"])
webcam_stream_url = self._settings.global_get(["webcam", "stream"])
ffmpeg_path = self._settings.global_get(["webcam", "ffmpeg"])
def _is_webcam_wizard_required(self):
webcam_snapshot_url = self._settings.global_get(["webcam", "snapshot"])
webcam_stream_url = self._settings.global_get(["webcam", "stream"])
ffmpeg_path = self._settings.global_get(["webcam", "ffmpeg"])
return not (webcam_snapshot_url and webcam_stream_url and ffmpeg_path)
return not (webcam_snapshot_url and webcam_stream_url and ffmpeg_path)
def _get_webcam_wizard_details(self):
return {"required": self._is_webcam_wizard_required()}
def _get_webcam_wizard_details(self):
return {"required": self._is_webcam_wizard_required()}
def _get_webcam_wizard_name(self):
return gettext("Webcam & Timelapse")
def _get_webcam_wizard_name(self):
return gettext("Webcam & Timelapse")
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class AclSubwizard(object):
def _is_acl_wizard_firstrunonly(self):
return True
def _is_acl_wizard_firstrunonly(self):
return True
def _is_acl_wizard_required(self):
return self._user_manager.enabled and not self._user_manager.has_been_customized()
def _is_acl_wizard_required(self):
return self._user_manager.enabled and not self._user_manager.has_been_customized()
def _get_acl_wizard_details(self):
return {"required": self._is_acl_wizard_required()}
def _get_acl_wizard_details(self):
return {"required": self._is_acl_wizard_required()}
def _get_acl_wizard_name(self):
return gettext("Access Control")
def _get_acl_wizard_name(self):
return gettext("Access Control")
def _get_acl_additional_wizard_template_data(self):
return {"mandatory": self._is_acl_wizard_required()}
def _get_acl_additional_wizard_template_data(self):
return {"mandatory": self._is_acl_wizard_required()}
@octoprint.plugin.BlueprintPlugin.route("/acl", methods=["POST"])
def acl_wizard_api(self):
from flask import request, abort
from octoprint.server.api import valid_boolean_trues, NO_CONTENT
@octoprint.plugin.BlueprintPlugin.route("/acl", methods=["POST"])
def acl_wizard_api(self):
from flask import abort, request
if not self._settings.global_get(["server", "firstRun"]) or self._user_manager.has_been_customized():
abort(404)
from octoprint.server.api import NO_CONTENT, valid_boolean_trues
data = request.get_json()
if data is None:
data = request.values
if (
not self._settings.global_get(["server", "firstRun"])
or self._user_manager.has_been_customized()
):
abort(404)
if "ac" in data and data["ac"] in valid_boolean_trues and \
"user" in data and "pass1" in data and \
"pass2" in data and data["pass1"] == data["pass2"]:
# configure access control
self._settings.global_set_boolean(["accessControl", "enabled"], True)
self._user_manager.enable()
data = request.get_json()
if data is None:
data = request.values
self._user_manager.add_user(data["user"], data["pass1"], True, [], [USER_GROUP, ADMIN_GROUP], overwrite=True)
elif "ac" in data and not data["ac"] in valid_boolean_trues:
# disable access control
self._settings.global_set_boolean(["accessControl", "enabled"], False)
self._user_manager.disable()
self._settings.save()
return NO_CONTENT
if (
"ac" in data
and data["ac"] in valid_boolean_trues
and "user" in data
and "pass1" in data
and "pass2" in data
and data["pass1"] == data["pass2"]
):
# configure access control
self._settings.global_set_boolean(["accessControl", "enabled"], True)
self._user_manager.enable()
self._user_manager.add_user(
data["user"],
data["pass1"],
True,
[],
[USER_GROUP, ADMIN_GROUP],
overwrite=True,
)
elif "ac" in data and data["ac"] not in valid_boolean_trues:
# disable access control
self._settings.global_set_boolean(["accessControl", "enabled"], False)
self._user_manager.disable()
self._settings.save()
return NO_CONTENT
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class OnlineCheckSubwizard(object):
def _is_onlinecheck_wizard_firstrunonly(self):
return False
def _is_onlinecheck_wizard_firstrunonly(self):
return False
def _is_onlinecheck_wizard_required(self):
return self._settings.global_get(["server", "onlineCheck", "enabled"]) is None
def _is_onlinecheck_wizard_required(self):
return self._settings.global_get(["server", "onlineCheck", "enabled"]) is None
def _get_onlinecheck_wizard_details(self):
return {"required": self._is_onlinecheck_wizard_required()}
def _get_onlinecheck_wizard_details(self):
return {"required": self._is_onlinecheck_wizard_required()}
def _get_onlinecheck_wizard_name(self):
return gettext("Online Connectivity Check")
def _get_onlinecheck_wizard_name(self):
return gettext("Online Connectivity Check")
def _get_onlinecheck_additional_wizard_template_data(self):
return {"mandatory": self._is_onlinecheck_wizard_required()}
def _get_onlinecheck_additional_wizard_template_data(self):
return {"mandatory": self._is_onlinecheck_wizard_required()}
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class PluginBlacklistSubwizard(object):
def _is_pluginblacklist_wizard_firstrunonly(self):
return False
def _is_pluginblacklist_wizard_firstrunonly(self):
return False
def _is_pluginblacklist_wizard_required(self):
return self._settings.global_get(["server", "pluginBlacklist", "enabled"]) is None
def _is_pluginblacklist_wizard_required(self):
return self._settings.global_get(["server", "pluginBlacklist", "enabled"]) is None
def _get_pluginblacklist_wizard_details(self):
return {"required": self._is_pluginblacklist_wizard_required()}
def _get_pluginblacklist_wizard_details(self):
return {"required": self._is_pluginblacklist_wizard_required()}
def _get_pluginblacklist_wizard_name(self):
return gettext("Plugin Blacklist")
def _get_pluginblacklist_wizard_name(self):
return gettext("Plugin Blacklist")
def _get_pluginblacklist_additional_wizard_template_data(self):
return {"mandatory": self._is_pluginblacklist_wizard_required()}
def _get_pluginblacklist_additional_wizard_template_data(self):
return {"mandatory": self._is_pluginblacklist_wizard_required()}
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class PrinterProfileSubwizard(object):
def _is_printerprofile_wizard_firstrunonly(self):
return True
def _is_printerprofile_wizard_firstrunonly(self):
return True
def _is_printerprofile_wizard_required(self):
return self._printer_profile_manager.is_default_unmodified() and self._printer_profile_manager.profile_count == 1
def _is_printerprofile_wizard_required(self):
return (
self._printer_profile_manager.is_default_unmodified()
and self._printer_profile_manager.profile_count == 1
)
def _get_printerprofile_wizard_details(self):
return {"required": self._is_printerprofile_wizard_required()}
def _get_printerprofile_wizard_details(self):
return {"required": self._is_printerprofile_wizard_required()}
def _get_printerprofile_wizard_name(self):
return gettext("Default Printer Profile")
def _get_printerprofile_wizard_name(self):
return gettext("Default Printer Profile")
Subwizards = type(to_native_str("Subwizards"),
tuple(cls for clsname, cls in inspect.getmembers(sys.modules[__name__], inspect.isclass)
if clsname.endswith("Subwizard")),
{})
Subwizards = type(
to_native_str("Subwizards"),
tuple(
cls
for clsname, cls in inspect.getmembers(sys.modules[__name__], inspect.isclass)
if clsname.endswith("Subwizard")
),
{},
)
File diff suppressed because it is too large. Load diff
@@ -19,4 +19,4 @@
</serviceList>
<presentationURL>{{ presentationUrl }}</presentationURL>
</device>
</root>
</root>
+190 -145
View File
@@ -1,208 +1,253 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License"
import octoprint.plugin
import errno
import logging
from octoprint.util import get_fully_qualified_classname as fqcn
from octoprint.util.version import get_octoprint_version_string, is_released_octoprint_version
import requests.exceptions
import serial
import tornado.websocket
from flask import jsonify
from flask_babel import gettext
SENTRY_URL_SERVER = "https://d479a74f172d4ac2b959a9a7d0536a82@o118517.ingest.sentry.io/1373987"
SENTRY_URL_COREUI = "https://040577fb88b241ff985e408c11775720@o118517.ingest.sentry.io/1374096"
import octoprint.plugin
from octoprint.util import get_fully_qualified_classname as fqcn # noqa: F401
from octoprint.util.version import (
get_octoprint_version_string,
is_released_octoprint_version,
)
SETTINGS_DEFAULTS = {"enabled": False,
"enabled_unreleased": False,
"unique_id": None,
"url_server": SENTRY_URL_SERVER,
"url_coreui": SENTRY_URL_COREUI}
SENTRY_URL_SERVER = (
"https://d479a74f172d4ac2b959a9a7d0536a82@o118517.ingest.sentry.io/1373987"
)
SENTRY_URL_COREUI = (
"https://040577fb88b241ff985e408c11775720@o118517.ingest.sentry.io/1374096"
)
import serial
import requests.exceptions
import errno
import tornado.websocket
SETTINGS_DEFAULTS = {
"enabled": False,
"enabled_unreleased": False,
"unique_id": None,
"url_server": SENTRY_URL_SERVER,
"url_coreui": SENTRY_URL_COREUI,
}
IGNORED_EXCEPTIONS = [
# serial exceptions in octoprint.util.comm
(serial.SerialException, lambda exc, logger, plugin, cb: logger == "octoprint.util.comm"),
# KeyboardInterrupts
KeyboardInterrupt,
# IOErrors of any kind due to a full file system
(IOError, lambda exc, logger, plugin, cb: getattr(exc, "errno") and exc.errno in (getattr(errno, "ENOSPC"),)),
# RequestExceptions of any kind
requests.exceptions.RequestException,
# Tornado WebSocketErrors of any kind
tornado.websocket.WebSocketError,
# Anything triggered by or in third party plugin Astroprint
(Exception, lambda exc, logger, plugin, cb: logger.startswith("octoprint.plugins.astroprint")
or plugin == "astroprint"
or cb.startswith("octoprint_astroprint."))
# serial exceptions in octoprint.util.comm
(
serial.SerialException,
lambda exc, logger, plugin, cb: logger == "octoprint.util.comm",
),
# KeyboardInterrupts
KeyboardInterrupt,
# IOErrors of any kind due to a full file system
(
IOError,
lambda exc, logger, plugin, cb: getattr(exc, "errno")
and exc.errno in (getattr(errno, "ENOSPC"),),
),
# RequestExceptions of any kind
requests.exceptions.RequestException,
# Tornado WebSocketErrors of any kind
tornado.websocket.WebSocketError,
# Anything triggered by or in third party plugin Astroprint
(
Exception,
lambda exc, logger, plugin, cb: logger.startswith("octoprint.plugins.astroprint")
or plugin == "astroprint"
or cb.startswith("octoprint_astroprint."),
),
]
try:
# noinspection PyUnresolvedReferences
from octoprint.plugins.backup import InsufficientSpace
# noinspection PyUnresolvedReferences
from octoprint.plugins.backup import InsufficientSpace
# if the backup plugin is enabled, ignore InsufficientSpace errors from it as well
IGNORED_EXCEPTIONS.append(InsufficientSpace)
# if the backup plugin is enabled, ignore InsufficientSpace errors from it as well
IGNORED_EXCEPTIONS.append(InsufficientSpace)
del InsufficientSpace
del InsufficientSpace
except ImportError:
pass
pass
class ErrorTrackingPlugin(octoprint.plugin.SettingsPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.SimpleApiPlugin):
class ErrorTrackingPlugin(
octoprint.plugin.SettingsPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.SimpleApiPlugin,
):
def get_template_configs(self):
return [
{
"type": "settings",
"name": gettext("Error Tracking"),
"template": "errortracking_settings.jinja2",
"custom_bindings": False,
},
{"type": "generic", "template": "errortracking_javascripts.jinja2"},
]
def get_template_configs(self):
return [{"type": "settings",
"name": gettext("Error Tracking"),
"template": "errortracking_settings.jinja2",
"custom_bindings": False},
{"type": "generic",
"template": "errortracking_javascripts.jinja2"}]
def get_template_vars(self):
enabled = self._settings.get_boolean(["enabled"])
enabled_unreleased = self._settings.get_boolean(["enabled_unreleased"])
def get_template_vars(self):
enabled = self._settings.get_boolean(["enabled"])
enabled_unreleased = self._settings.get_boolean(["enabled_unreleased"])
return {
"enabled": _is_enabled(enabled, enabled_unreleased),
"unique_id": self._settings.get(["unique_id"]),
"url_coreui": self._settings.get(["url_coreui"]),
}
return {"enabled": _is_enabled(enabled, enabled_unreleased),
"unique_id": self._settings.get(["unique_id"]),
"url_coreui": self._settings.get(["url_coreui"])}
def get_assets(self):
return {"js": ["js/sentry.min.js", "js/errortracking.js"]}
def get_assets(self):
return {"js": ["js/sentry.min.js", "js/errortracking.js"]}
def get_settings_defaults(self):
return SETTINGS_DEFAULTS
def get_settings_defaults(self):
return SETTINGS_DEFAULTS
def on_settings_save(self, data):
old_enabled = _is_enabled(
self._settings.get_boolean(["enabled"]),
self._settings.get_boolean(["enabled_unreleased"]),
)
def on_settings_save(self, data):
old_enabled = _is_enabled(self._settings.get_boolean(["enabled"]),
self._settings.get_boolean(["enabled_unreleased"]))
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
enabled = _is_enabled(
self._settings.get_boolean(["enabled"]),
self._settings.get_boolean(["enabled_unreleased"]),
)
enabled = _is_enabled(self._settings.get_boolean(["enabled"]),
self._settings.get_boolean(["enabled_unreleased"]))
if old_enabled != enabled:
_enable_errortracking()
if old_enabled != enabled:
_enable_errortracking()
def on_api_get(self, request):
return jsonify(**self.get_template_vars())
def on_api_get(self, request):
return jsonify(**self.get_template_vars())
_enabled = False
def _enable_errortracking():
# this is a bit hackish, but we want to enable error tracking as early in the platform lifecycle as possible
# and hence can't wait until our implementation is initialized and injected with settings
# this is a bit hackish, but we want to enable error tracking as early in the platform lifecycle as possible
# and hence can't wait until our implementation is initialized and injected with settings
from octoprint.settings import settings
global _enabled
from octoprint.settings import settings
if _enabled:
return
global _enabled
version = get_octoprint_version_string()
if _enabled:
return
s = settings()
plugin_defaults = {"plugins": {"errortracking": SETTINGS_DEFAULTS}}
version = get_octoprint_version_string()
enabled = s.getBoolean(["plugins", "errortracking", "enabled"], defaults=plugin_defaults)
enabled_unreleased = s.getBoolean(["plugins", "errortracking", "enabled_unreleased"], defaults=plugin_defaults)
url_server = s.get(["plugins", "errortracking", "url_server"], defaults=plugin_defaults)
unique_id = s.get(["plugins", "errortracking", "unique_id"], defaults=plugin_defaults)
if unique_id is None:
import uuid
unique_id = str(uuid.uuid4())
s.set(["plugins", "errortracking", "unique_id"], unique_id, defaults=plugin_defaults)
s.save()
s = settings()
plugin_defaults = {"plugins": {"errortracking": SETTINGS_DEFAULTS}}
if _is_enabled(enabled, enabled_unreleased):
import sentry_sdk
from octoprint.plugin import plugin_manager
enabled = s.getBoolean(
["plugins", "errortracking", "enabled"], defaults=plugin_defaults
)
enabled_unreleased = s.getBoolean(
["plugins", "errortracking", "enabled_unreleased"], defaults=plugin_defaults
)
url_server = s.get(
["plugins", "errortracking", "url_server"], defaults=plugin_defaults
)
unique_id = s.get(["plugins", "errortracking", "unique_id"], defaults=plugin_defaults)
if unique_id is None:
import uuid
def _before_send(event, hint):
if not "exc_info" in hint:
# we only want exceptions
return None
unique_id = str(uuid.uuid4())
s.set(
["plugins", "errortracking", "unique_id"], unique_id, defaults=plugin_defaults
)
s.save()
handled = True
logger = event.get("logger", "")
plugin = event.get("extra", {}).get("plugin", None)
callback = event.get("extra", {}).get("callback", None)
if _is_enabled(enabled, enabled_unreleased):
import sentry_sdk
for ignore in IGNORED_EXCEPTIONS:
if isinstance(ignore, tuple):
ignored_exc, matcher = ignore
else:
ignored_exc = ignore
matcher = lambda *args: True
from octoprint.plugin import plugin_manager
exc = hint["exc_info"][1]
if isinstance(exc, ignored_exc) and matcher(exc, logger, plugin, callback):
# exception ignored for logger, plugin and/or callback
return None
def _before_send(event, hint):
if "exc_info" not in hint:
# we only want exceptions
return None
elif isinstance(ignore, type):
if isinstance(hint["exc_info"][1], ignore):
# exception ignored
return None
handled = True
logger = event.get("logger", "")
plugin = event.get("extra", {}).get("plugin", None)
callback = event.get("extra", {}).get("callback", None)
if event.get("exception") and event["exception"].get("values"):
handled = not any(map(lambda x: x.get("mechanism") and x["mechanism"].get("handled", True) == False,
event["exception"]["values"]))
for ignore in IGNORED_EXCEPTIONS:
if isinstance(ignore, tuple):
ignored_exc, matcher = ignore
else:
ignored_exc = ignore
matcher = lambda *args: True
if handled:
# error is handled, restrict further based on logger
if logger != "" and not (logger.startswith("octoprint.") or logger.startswith("tornado.")):
# we only want errors logged by loggers octoprint.* or tornado.*
return None
exc = hint["exc_info"][1]
if isinstance(exc, ignored_exc) and matcher(
exc, logger, plugin, callback
):
# exception ignored for logger, plugin and/or callback
return None
if logger.startswith("octoprint.plugins."):
plugin_id = logger.split(".")[2]
plugin_info = plugin_manager().get_plugin_info(plugin_id)
if plugin_info is None or not plugin_info.bundled:
# we only want our active bundled plugins
return None
elif isinstance(ignore, type):
if isinstance(hint["exc_info"][1], ignore):
# exception ignored
return None
if plugin is not None:
plugin_info = plugin_manager().get_plugin_info(plugin)
if plugin_info is None or not plugin_info.bundled:
# we only want our active bundled plugins
return None
if event.get("exception") and event["exception"].get("values"):
handled = not any(
map(
lambda x: x.get("mechanism")
and not x["mechanism"].get("handled", True),
event["exception"]["values"],
)
)
return event
if handled:
# error is handled, restrict further based on logger
if logger != "" and not (
logger.startswith("octoprint.") or logger.startswith("tornado.")
):
# we only want errors logged by loggers octoprint.* or tornado.*
return None
sentry_sdk.init(url_server,
release=version,
before_send=_before_send)
if logger.startswith("octoprint.plugins."):
plugin_id = logger.split(".")[2]
plugin_info = plugin_manager().get_plugin_info(plugin_id)
if plugin_info is None or not plugin_info.bundled:
# we only want our active bundled plugins
return None
with sentry_sdk.configure_scope() as scope:
scope.user = {"id": unique_id}
if plugin is not None:
plugin_info = plugin_manager().get_plugin_info(plugin)
if plugin_info is None or not plugin_info.bundled:
# we only want our active bundled plugins
return None
logging.getLogger("octoprint.plugins.errortracking").info("Initialized error tracking")
_enabled = True
return event
sentry_sdk.init(url_server, release=version, before_send=_before_send)
with sentry_sdk.configure_scope() as scope:
scope.user = {"id": unique_id}
logging.getLogger("octoprint.plugins.errortracking").info(
"Initialized error tracking"
)
_enabled = True
def _is_enabled(enabled, enabled_unreleased):
return enabled and (enabled_unreleased or is_released_octoprint_version())
return enabled and (enabled_unreleased or is_released_octoprint_version())
def __plugin_enable__():
_enable_errortracking()
_enable_errortracking()
__plugin_name__ = "Error Tracking"
@@ -1,4 +1,4 @@
$(function() {
$(function () {
function ErrorTrackingViewModel(parameters) {
var self = this;
@@ -6,7 +6,7 @@ $(function() {
self.loginState = parameters[1];
var notification = undefined;
var performCheck = function() {
var performCheck = function () {
if (!self.loginState.isAdmin()) return;
// already enabled?
@@ -19,7 +19,8 @@ $(function() {
// ignored?
try {
var ignoredString = localStorage["plugin.errortracking.notification_ignored"];
var ignoredString =
localStorage["plugin.errortracking.notification_ignored"];
var ignored = false;
if (ignoredString) {
@@ -28,50 +29,63 @@ $(function() {
if (ignored) return;
} catch (ex) {
log.error("Error while reading plugin.errortracking.notification_ignored from local storage");
log.error(
"Error while reading plugin.errortracking.notification_ignored from local storage"
);
}
// show notification
notification = new PNotify({
title: gettext("Enable error reporting?"),
text: gettext("<p>It looks like you are tracking an OctoPrint RC release channel. It " +
"would be great if you would enable error reporting so that any kind of errors that occur " +
"with an RC can be looked into more easily. Thank you!</p>" +
"<p><small>You can find more information on error reporting " +
"under Settings > Error Tracking</small></p>"),
text: gettext(
"<p>It looks like you are tracking an OctoPrint RC release channel. It " +
"would be great if you would enable error reporting so that any kind of errors that occur " +
"with an RC can be looked into more easily. Thank you!</p>" +
"<p><small>You can find more information on error reporting " +
"under Settings > Error Tracking</small></p>"
),
hide: false,
confirm: {
confirm: true,
buttons: [{
text: gettext("Ignore"),
click: function() {
notification.remove();
notification = undefined;
new PNotify({
text: gettext("You can still enable error tracking via \"Settings\" > \"Error Tracking\"")
});
if (Modernizr.localstorage) {
localStorage["plugin.errortracking.notification_ignored"] = JSON.stringify(true);
}
}
}, {
text: gettext("Enable"),
addClass: "btn-primary",
click: function() {
self.settings.saveData({
plugins: {
errortracking: {
enabled: true
}
}
}).done(function() {
buttons: [
{
text: gettext("Ignore"),
click: function () {
notification.remove();
notification = undefined;
location.reload(true);
});
new PNotify({
text: gettext(
'You can still enable error tracking via "Settings" > "Error Tracking"'
)
});
if (Modernizr.localstorage) {
localStorage[
"plugin.errortracking.notification_ignored"
] = JSON.stringify(true);
}
}
},
{
text: gettext("Enable"),
addClass: "btn-primary",
click: function () {
self.settings
.saveData({
plugins: {
errortracking: {
enabled: true
}
}
})
.done(function () {
notification.remove();
notification = undefined;
location.reload(true);
});
}
}
}]
]
},
buttons: {
closer: false,
@@ -79,7 +93,7 @@ $(function() {
}
});
// not an RC release channel, close notification
// not an RC release channel, close notification
} else if (notification !== undefined) {
notification.remove();
notification = undefined;
@@ -87,11 +101,19 @@ $(function() {
};
var subbed = false;
self.onStartup = self.onUserLoggedIn = self.onUserLoggedOut = function() {
self.onStartup = self.onUserLoggedIn = self.onUserLoggedOut = function () {
performCheck();
if (self.settings && self.settings.settings && self.settings.settings.plugins && self.settings.settings.plugins.softwareupdate && !subbed) {
if (
self.settings &&
self.settings.settings &&
self.settings.settings.plugins &&
self.settings.settings.plugins.softwareupdate &&
!subbed
) {
subbed = true;
self.settings.settings.plugins.softwareupdate.octoprint_release_channel.subscribe(performCheck);
self.settings.settings.plugins.softwareupdate.octoprint_release_channel.subscribe(
performCheck
);
}
};
}
+63 -48
View File
@@ -1,69 +1,84 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License"
import octoprint.plugin
from flask_babel import gettext
class GcodeviewerPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.SettingsPlugin):
import octoprint.plugin
def get_assets(self):
js = ["js/gcodeviewer.js",
"js/viewer/ui.js",
"js/viewer/reader.js",
"js/viewer/renderer.js"
]
return {"js": js,
"less": ["less/gcodeviewer.less"],
"css": ["css/gcodeviewer.css"]}
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",
]
def get_template_configs(self):
return [
{"type": "tab",
"template": "gcodeviewer_tab.jinja2",
"div": "gcode",
"styles": ["display: none;"],
"data_bind": "visible: loginState.hasAllPermissionsKo(access.permissions.GCODE_VIEWER, access.permissions.FILES_DOWNLOAD)"},
{"type": "settings",
"template": "gcodeviewer_settings.jinja2",
"custom_bindings": True},
{"type": "generic",
"template": "gcodeviewer_initscript.jinja2"}
]
return {
"js": js,
"less": ["less/gcodeviewer.less"],
"css": ["css/gcodeviewer.css"],
}
def get_settings_defaults(self):
return {"mobileSizeThreshold": 2 * 1024 * 1024, # 2MB
"sizeThreshold": 20 * 1024 * 1024} # 20MB
def get_template_configs(self):
return [
{
"type": "tab",
"template": "gcodeviewer_tab.jinja2",
"div": "gcode",
"styles": ["display: none;"],
"data_bind": "visible: loginState.hasAllPermissionsKo(access.permissions.GCODE_VIEWER, access.permissions.FILES_DOWNLOAD)",
},
{
"type": "settings",
"template": "gcodeviewer_settings.jinja2",
"custom_bindings": True,
},
{"type": "generic", "template": "gcodeviewer_initscript.jinja2"},
]
def get_settings_version(self):
return 1
def get_settings_defaults(self):
return {
"mobileSizeThreshold": 2 * 1024 * 1024, # 2MB
"sizeThreshold": 20 * 1024 * 1024,
} # 20MB
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"])
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_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
#}
# __plugin_hooks__ = {
# "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
# }
@@ -1,4 +1,4 @@
$(function() {
$(function () {
function GcodeViewModel(parameters) {
var self = this;
@@ -11,15 +11,23 @@ $(function() {
self.ui_progress_percentage = ko.observable();
self.ui_progress_type = ko.observable();
self.ui_progress_text = ko.pureComputed(function() {
self.ui_progress_text = ko.pureComputed(function () {
var text = "";
switch (self.ui_progress_type()) {
case "loading": {
text = gettext("Loading...") + " (" + self.ui_progress_percentage().toFixed(0) + "%)";
text =
gettext("Loading...") +
" (" +
self.ui_progress_percentage().toFixed(0) +
"%)";
break;
}
case "analyzing": {
text = gettext("Analyzing...") + " (" + self.ui_progress_percentage().toFixed(0) + "%)";
text =
gettext("Analyzing...") +
" (" +
self.ui_progress_percentage().toFixed(0) +
"%)";
break;
}
case "done": {
@@ -68,12 +76,18 @@ $(function() {
self.layerUpEnabled = ko.observable(false);
self.layerDownEnabled = ko.observable(false);
self.synchronizeOptionsAndReload = function(additionalRendererOptions, additionalReaderOptions) {
self.synchronizeOptionsAndReload = function (
additionalRendererOptions,
additionalReaderOptions
) {
self.synchronizeOptions(additionalRendererOptions, additionalReaderOptions);
self.reload();
};
self.synchronizeOptions = function(additionalRendererOptions, additionalReaderOptions) {
self.synchronizeOptions = function (
additionalRendererOptions,
additionalReaderOptions
) {
var renderer = {
moveModel: self.renderer_centerModel(),
centerViewport: self.renderer_centerViewport(),
@@ -82,7 +96,9 @@ $(function() {
showHead: self.renderer_showPrinthead(),
showBoundingBox: self.renderer_showBoundingBox(),
showFullSize: self.renderer_showFullSize(),
extrusionWidth: self.renderer_extrusionWidthEnabled() ? self.renderer_extrusionWidth() : 1,
extrusionWidth: self.renderer_extrusionWidthEnabled()
? self.renderer_extrusionWidth()
: 1,
showNextLayer: self.renderer_showNext(),
showCurrentLayer: self.renderer_showCurrent(),
showPreviousLayer: self.renderer_showPrevious(),
@@ -96,7 +112,7 @@ $(function() {
var reader = {
sortLayers: self.reader_sortLayers(),
purgeEmptyLayers: self.reader_hideEmptyLayers(),
ignoreOutsideBed: self.reader_ignoreOutsideBed(),
ignoreOutsideBed: self.reader_ignoreOutsideBed()
};
if (additionalReaderOptions) {
_.extend(reader, additionalReaderOptions);
@@ -108,12 +124,12 @@ $(function() {
});
};
self.rendererOptionUpdated = function() {
self.rendererOptionUpdated = function () {
self.synchronizeOptions();
self._toLocalStorage();
};
self.readerOptionUpdated = function() {
self.readerOptionUpdated = function () {
self.synchronizeOptionsAndReload();
self._toLocalStorage();
};
@@ -137,7 +153,7 @@ $(function() {
self.reader_hideEmptyLayers.subscribe(self.readerOptionUpdated);
self.reader_ignoreOutsideBed.subscribe(self.readerOptionUpdated);
self._printerProfileUpdated = function() {
self._printerProfileUpdated = function () {
if (!self.enabled) return;
var currentProfileData = self.settings.printerProfiles.currentProfileData();
@@ -168,27 +184,43 @@ $(function() {
};
// subscribe to relevant printer settings...
self.settings.printerProfiles.currentProfileData.subscribe(function() {
self.settings.printerProfiles.currentProfileData.subscribe(function () {
self._printerProfileUpdated();
if (self.settings.printerProfiles.currentProfileData()) {
if (self.settings.printerProfiles.currentProfileData().extruder) {
self.settings.printerProfiles.currentProfileData().extruder.count.subscribe(self._printerProfileUpdated);
self.settings.printerProfiles.currentProfileData().extruder.sharedNozzle.subscribe(self._printerProfileUpdated);
self.settings.printerProfiles.currentProfileData().extruder.offsets.subscribe(self._printerProfileUpdated);
self.settings.printerProfiles
.currentProfileData()
.extruder.count.subscribe(self._printerProfileUpdated);
self.settings.printerProfiles
.currentProfileData()
.extruder.sharedNozzle.subscribe(self._printerProfileUpdated);
self.settings.printerProfiles
.currentProfileData()
.extruder.offsets.subscribe(self._printerProfileUpdated);
}
if (self.settings.printerProfiles.currentProfileData().volume) {
self.settings.printerProfiles.currentProfileData().volume.width.subscribe(self._printerProfileUpdated);
self.settings.printerProfiles.currentProfileData().volume.depth.subscribe(self._printerProfileUpdated);
self.settings.printerProfiles.currentProfileData().volume.formFactor.subscribe(self._printerProfileUpdated);
self.settings.printerProfiles
.currentProfileData()
.volume.width.subscribe(self._printerProfileUpdated);
self.settings.printerProfiles
.currentProfileData()
.volume.depth.subscribe(self._printerProfileUpdated);
self.settings.printerProfiles
.currentProfileData()
.volume.formFactor.subscribe(self._printerProfileUpdated);
}
if (self.settings.printerProfiles.currentProfileData().axes) {
self.settings.printerProfiles.currentProfileData().axes.x.inverted.subscribe(self._printerProfileUpdated);
self.settings.printerProfiles.currentProfileData().axes.y.inverted.subscribe(self._printerProfileUpdated);
self.settings.printerProfiles
.currentProfileData()
.axes.x.inverted.subscribe(self._printerProfileUpdated);
self.settings.printerProfiles
.currentProfileData()
.axes.y.inverted.subscribe(self._printerProfileUpdated);
}
}
});
self.settings.feature_g90InfluencesExtruder.subscribe(function() {
self.settings.feature_g90InfluencesExtruder.subscribe(function () {
GCODE.ui.updateOptions({
reader: {
g90InfluencesExtruder: self.settings.feature_g90InfluencesExtruder()
@@ -196,13 +228,23 @@ $(function() {
});
});
self._retrieveBedDimensions = function(currentProfileData) {
self._retrieveBedDimensions = function (currentProfileData) {
if (currentProfileData === undefined) {
currentProfileData = self.settings.printerProfiles.currentProfileData();
}
if (currentProfileData && currentProfileData.volume && currentProfileData.volume.formFactor() && currentProfileData.volume.width() && currentProfileData.volume.depth()) {
var x = undefined, y = undefined, r = undefined, circular = false, centeredOrigin = false;
if (
currentProfileData &&
currentProfileData.volume &&
currentProfileData.volume.formFactor() &&
currentProfileData.volume.width() &&
currentProfileData.volume.depth()
) {
var x = undefined,
y = undefined,
r = undefined,
circular = false,
centeredOrigin = false;
var formFactor = currentProfileData.volume.formFactor();
if (formFactor === "circular") {
@@ -229,32 +271,35 @@ $(function() {
}
};
self._retrieveToolOffsets = function(currentProfileData) {
self._retrieveToolOffsets = function (currentProfileData) {
if (currentProfileData == undefined) {
currentProfileData = self.settings.printerProfiles.currentProfileData();
}
if (currentProfileData && currentProfileData.extruder) {
var offsets = [];
if (currentProfileData.extruder.offsets() && !currentProfileData.extruder.sharedNozzle()) {
_.each(currentProfileData.extruder.offsets(), function(offset) {
offsets.push({x: offset[0], y: offset[1]})
if (
currentProfileData.extruder.offsets() &&
!currentProfileData.extruder.sharedNozzle()
) {
_.each(currentProfileData.extruder.offsets(), function (offset) {
offsets.push({x: offset[0], y: offset[1]});
});
}
return offsets;
} else {
return undefined;
}
};
self._retrieveAxesConfiguration = function(currentProfileData) {
self._retrieveAxesConfiguration = function (currentProfileData) {
if (currentProfileData == undefined) {
currentProfileData = self.settings.printerProfiles.currentProfileData();
}
if (currentProfileData && currentProfileData.axes) {
var invertX = false, invertY = false;
var invertX = false,
invertY = false;
if (currentProfileData.axes.x) {
invertX = currentProfileData.axes.x.inverted();
}
@@ -265,7 +310,7 @@ $(function() {
return {
x: invertX,
y: invertY
}
};
} else {
return undefined;
}
@@ -273,7 +318,7 @@ $(function() {
self.loadedFilepath = undefined;
self.loadedFileDate = undefined;
self.status = 'idle';
self.status = "idle";
self.enabled = false;
self.currentlyPrinting = false;
@@ -287,52 +332,61 @@ $(function() {
self.currentCommand = undefined;
self.maxLayer = undefined;
self.initialize = function() {
self.sizeThresholdStr = sizeObservable(self.settings.settings.plugins.gcodeviewer.sizeThreshold);
self.mobileSizeThresholdStr = sizeObservable(self.settings.settings.plugins.gcodeviewer.mobileSizeThreshold);
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");
if (!(layerSliderElement.length && commandSliderElement.length && containerElement.length)) {
if (
!(
layerSliderElement.length &&
commandSliderElement.length &&
containerElement.length
)
) {
return;
}
self._configureLayerSlider(layerSliderElement);
self._configureLayerCommandSlider(commandSliderElement);
self.settings.firstRequest
.done(function() {
var initResult = GCODE.ui.init({
container: "#gcode_canvas",
onProgress: self._onProgress,
onModelLoaded: self._onModelLoaded,
onLayerSelected: self._onLayerSelected,
bed: self._retrieveBedDimensions(),
toolOffsets: self._retrieveToolOffsets(),
invertAxes: self._retrieveAxesConfiguration()
});
if (!initResult) {
log.info("Could not initialize GCODE viewer component");
return;
}
self.synchronizeOptions();
self.enabled = true;
self._fromLocalStorage();
self.settings.firstRequest.done(function () {
var initResult = GCODE.ui.init({
container: "#gcode_canvas",
onProgress: self._onProgress,
onModelLoaded: self._onModelLoaded,
onLayerSelected: self._onLayerSelected,
bed: self._retrieveBedDimensions(),
toolOffsets: self._retrieveToolOffsets(),
invertAxes: self._retrieveAxesConfiguration()
});
if (!initResult) {
log.info("Could not initialize GCODE viewer component");
return;
}
self.synchronizeOptions();
self.enabled = true;
self._fromLocalStorage();
});
};
self.reset = function() {
self.reset = function () {
self.enableReload(false);
self.loadedFilepath = undefined;
self.loadedFileDate = undefined;
self.clear();
};
self.resetOptions = function() {
self.resetOptions = function () {
self.renderer_centerModel(false);
self.renderer_centerViewport(false);
self.renderer_zoomOnModel(false);
@@ -353,46 +407,59 @@ $(function() {
self.reader_ignoreOutsideBed(true);
};
self.clear = function() {
self.clear = function () {
GCODE.ui.clear();
};
self._configureLayerSlider = function(layerSliderElement) {
self.layerSlider = layerSliderElement.slider({
id: "gcode_layer_slider",
reversed: true,
selection: "after",
orientation: "vertical",
min: 0,
max: 1,
step: 1,
value: 0,
enabled: false,
formatter: function(value) { return "Layer #" + (value + 1) + " (Z = " + GCODE.renderer.getZ(value) + ")"; }
}).on("slide", self.changeLayer);
self._configureLayerSlider = function (layerSliderElement) {
self.layerSlider = layerSliderElement
.slider({
id: "gcode_layer_slider",
reversed: true,
selection: "after",
orientation: "vertical",
min: 0,
max: 1,
step: 1,
value: 0,
enabled: false,
formatter: function (value) {
return (
"Layer #" +
(value + 1) +
" (Z = " +
GCODE.renderer.getZ(value) +
")"
);
}
})
.on("slide", self.changeLayer);
};
self._configureLayerCommandSlider = function(commandSliderElement) {
self.layerCommandSlider = commandSliderElement.slider({
id: "gcode_command_slider",
orientation: "horizontal",
min: 0,
max: 1,
step: 1,
value: [0, 1],
enabled: false,
tooltip: "hide"
}).on("slide", self.changeCommandRange);
self._configureLayerCommandSlider = function (commandSliderElement) {
self.layerCommandSlider = commandSliderElement
.slider({
id: "gcode_command_slider",
orientation: "horizontal",
min: 0,
max: 1,
step: 1,
value: [0, 1],
enabled: false,
tooltip: "hide"
})
.on("slide", self.changeCommandRange);
};
self.loadFile = function(path, date){
self.loadFile = function (path, date) {
self.enableReload(false);
self.needsLoad = false;
if (self.status === "idle" && self.errorCount < 3) {
self.status = "request";
OctoPrint.files.download("local", path)
.done(function(response, rstatus) {
if(rstatus === 'success'){
OctoPrint.files
.download("local", path)
.done(function (response, rstatus) {
if (rstatus === "success") {
self.showGCodeViewer(response, rstatus);
self.loadedFilepath = path;
self.loadedFileDate = date;
@@ -400,14 +467,14 @@ $(function() {
self.enableReload(true);
}
})
.fail(function() {
.fail(function () {
self.status = "idle";
self.errorCount++;
});
}
};
self.showGCodeViewer = function(response, rstatus) {
self.showGCodeViewer = function (response, rstatus) {
var par = {
target: {
result: response
@@ -424,20 +491,20 @@ $(function() {
}
};
self.reload = function() {
self.reload = function () {
if (!self.enableReload()) return;
self.loadFile(self.loadedFilepath, self.loadedFileDate);
};
self.fromHistoryData = function(data) {
self.fromHistoryData = function (data) {
self._processData(data);
};
self.fromCurrentData = function(data) {
self.fromCurrentData = function (data) {
self._processData(data);
};
self._renderPercentage = function(percentage) {
self._renderPercentage = function (percentage) {
var cmdIndex = GCODE.gCodeReader.getCmdIndexForPercentage(percentage);
if (!cmdIndex) return;
@@ -452,8 +519,11 @@ $(function() {
}
};
self._processData = function(data) {
if (!data.job.file || !data.job.file.path && (self.loadedFilepath || self.loadedFileDate)) {
self._processData = function (data) {
if (
!data.job.file ||
(!data.job.file.path && (self.loadedFilepath || self.loadedFileDate))
) {
self.waitForApproval(false);
self.loadedFilepath = undefined;
@@ -466,26 +536,46 @@ $(function() {
return;
}
if (!self.enabled) return;
self.currentlyPrinting = data.state.flags && (data.state.flags.printing || data.state.flags.paused);
self.currentlyPrinting =
data.state.flags &&
(data.state.flags.printing || data.state.flags.paused);
if(self.loadedFilepath
&& self.loadedFilepath === data.job.file.path
&& self.loadedFileDate === data.job.file.date) {
if (OctoPrint.coreui.browserTabVisible && self.tabActive && self.currentlyPrinting && self.renderer_syncProgress() && !self.waitForApproval()) {
if (
self.loadedFilepath &&
self.loadedFilepath === data.job.file.path &&
self.loadedFileDate === data.job.file.date
) {
if (
OctoPrint.coreui.browserTabVisible &&
self.tabActive &&
self.currentlyPrinting &&
self.renderer_syncProgress() &&
!self.waitForApproval()
) {
self._renderPercentage(data.progress.completion);
}
self.errorCount = 0
self.errorCount = 0;
} else {
self.clear();
if (data.job.file.path && data.job.file.origin !== "sdcard"
&& self.status !== "request"
&& (!self.waitForApproval() || self.selectedFile.path() !== data.job.file.path || self.selectedFile.date() !== data.job.file.date)) {
if (
data.job.file.path &&
data.job.file.origin !== "sdcard" &&
self.status !== "request" &&
(!self.waitForApproval() ||
self.selectedFile.path() !== data.job.file.path ||
self.selectedFile.date() !== data.job.file.date)
) {
self.selectedFile.path(data.job.file.path);
self.selectedFile.date(data.job.file.date);
self.selectedFile.size(data.job.file.size);
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())) {
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;
@@ -501,23 +591,23 @@ $(function() {
}
};
self.onEventPrintDone = function() {
self.onEventPrintDone = function () {
if (self.renderer_syncProgress() && !self.waitForApproval()) {
self._renderPercentage(100.0);
}
};
self.approveLargeFile = function() {
self.approveLargeFile = function () {
self.waitForApproval(false);
self.loadFile(self.selectedFile.path(), self.selectedFile.date());
};
self._onProgress = function(type, percentage) {
self._onProgress = function (type, percentage) {
self.ui_progress_type(type);
self.ui_progress_percentage(percentage);
};
self._onModelLoaded = function(model) {
self._onModelLoaded = function (model) {
if (!model) {
self.ui_modelInfo("");
if (self.layerSlider !== undefined) {
@@ -532,10 +622,32 @@ $(function() {
self.maxLayer = 0;
} else {
var output = [];
output.push(gettext("Model size") + ": " + model.width.toFixed(2) + "mm &times; " + model.depth.toFixed(2) + "mm &times; " + model.height.toFixed(2) + "mm");
output.push(gettext("Estimated layer height") + ": " + model.layerHeight.toFixed(2) + gettext("mm"));
output.push(gettext("Estimated total print time") + ": " + formatFuzzyPrintTime(model.printTime));
output.push(gettext("Layers with extrusion") + ": " + model.layersPrinted.toFixed(0));
output.push(
gettext("Model size") +
": " +
model.width.toFixed(2) +
"mm &times; " +
model.depth.toFixed(2) +
"mm &times; " +
model.height.toFixed(2) +
"mm"
);
output.push(
gettext("Estimated layer height") +
": " +
model.layerHeight.toFixed(2) +
gettext("mm")
);
output.push(
gettext("Estimated total print time") +
": " +
formatFuzzyPrintTime(model.printTime)
);
output.push(
gettext("Layers with extrusion") +
": " +
model.layersPrinted.toFixed(0)
);
self.ui_modelInfo(output.join("<br>"));
@@ -551,7 +663,7 @@ $(function() {
}
};
self._onLayerSelected = function(layer) {
self._onLayerSelected = function (layer) {
if (!layer) {
self.ui_layerInfo("");
if (self.layerCommandSlider !== undefined) {
@@ -570,16 +682,34 @@ $(function() {
output.push(gettext("GCODE commands") + ": " + layer.commands);
if (layer.filament !== undefined) {
if (layer.filament.length === 1) {
output.push(gettext("Filament") + ": " + layer.filament[0].toFixed(2) + "mm");
output.push(
gettext("Filament") +
": " +
layer.filament[0].toFixed(2) +
"mm"
);
} else {
for (var i = 0; i < layer.filament.length; i++) {
if (layer.filament[i] !== undefined) {
output.push(gettext("Filament") + " (" + gettext("Tool") + " " + i + "): " + layer.filament[i].toFixed(2) + "mm");
output.push(
gettext("Filament") +
" (" +
gettext("Tool") +
" " +
i +
"): " +
layer.filament[i].toFixed(2) +
"mm"
);
}
}
}
}
output.push(gettext("Estimated print time") + ": " + formatDuration(layer.printTime));
output.push(
gettext("Estimated print time") +
": " +
formatDuration(layer.printTime)
);
self.ui_layerInfo(output.join("<br>"));
@@ -594,23 +724,33 @@ $(function() {
}
};
self._onInternalRendererOptionChange = function(options) {
self._onInternalRendererOptionChange = function (options) {
if (!options) return;
for (var opt in options) {
if (!options.hasOwnProperty(opt)) continue;
if (opt === "zoomInOnModel" && options[opt] !== self.renderer_zoomOnModel()) {
if (
opt === "zoomInOnModel" &&
options[opt] !== self.renderer_zoomOnModel()
) {
self.renderer_zoomOnModel(false);
} else if (opt === "centerViewport" && options[opt] !== self.renderer_centerViewport()) {
} else if (
opt === "centerViewport" &&
options[opt] !== self.renderer_centerViewport()
) {
self.renderer_centerViewport(false);
} else if (opt === "moveModel" && options[opt] !== self.renderer_centerModel()) {
} else if (
opt === "moveModel" &&
options[opt] !== self.renderer_centerModel()
) {
self.renderer_centerModel(false);
}
}
};
self.changeLayer = function(event) {
if (self.currentlyPrinting && self.renderer_syncProgress()) self.renderer_syncProgress(false);
self.changeLayer = function (event) {
if (self.currentlyPrinting && self.renderer_syncProgress())
self.renderer_syncProgress(false);
var value = event.value;
if (self.currentLayer !== undefined && self.currentLayer === value) return;
@@ -619,20 +759,23 @@ $(function() {
GCODE.ui.changeSelectedLayer(value);
};
self.onMouseOver = function(data, event) {
self.onMouseOver = function (data, event) {
if (!self.settings.feature_keyboardControl()) return;
$("#canvas_container").focus();
};
self.onMouseOut = function(data, event) {
self.onMouseOut = function (data, event) {
if (!self.settings.feature_keyboardControl()) return;
$("#canvas_container").blur();
};
self.onKeyDown = function(data, event) {
if (!self.settings.feature_keyboardControl() || self.layerSlider === undefined) return;
self.onKeyDown = function (data, event) {
if (
!self.settings.feature_keyboardControl() ||
self.layerSlider === undefined
)
return;
var value = self.currentLayer;
switch(event.which){
switch (event.which) {
case 33: // Pg up
value = value + 10; // No need to check against max this is done by the Slider anyway
break;
@@ -649,65 +792,75 @@ $(function() {
self.shiftLayer(value);
};
self.changeCommandRange = function(event) {
if (self.currentlyPrinting && self.renderer_syncProgress()) self.renderer_syncProgress(false);
self.changeCommandRange = function (event) {
if (self.currentlyPrinting && self.renderer_syncProgress())
self.renderer_syncProgress(false);
var tuple = event.value;
if (self.currentCommand !== undefined && self.currentCommand[0] === tuple[0] && self.currentCommand[1] === tuple[1]) return;
if (
self.currentCommand !== undefined &&
self.currentCommand[0] === tuple[0] &&
self.currentCommand[1] === tuple[1]
)
return;
self.currentCommand = tuple;
GCODE.ui.changeSelectedCommands(self.layerSlider.slider("getValue"), tuple[0], tuple[1]);
GCODE.ui.changeSelectedCommands(
self.layerSlider.slider("getValue"),
tuple[0],
tuple[1]
);
};
self.onDataUpdaterReconnect = function() {
self.onDataUpdaterReconnect = function () {
self.reset();
};
self.onBeforeBinding = function() {
self.onBeforeBinding = function () {
self.initialize();
};
self.onTabChange = function(current, previous) {
self.onTabChange = function (current, previous) {
self.tabActive = current === "#gcode";
if (self.tabActive && self.needsLoad) {
self.loadFile(self.selectedFile.path(), self.selectedFile.date());
}
};
self.shiftLayer = function(value){
self.shiftLayer = function (value) {
if (value !== self.currentLayer) {
self.layerSlider.slider('setValue', value);
value = self.layerSlider.slider('getValue');
self.layerSlider.slider("setValue", value);
value = self.layerSlider.slider("getValue");
//This sets the scroll bar to the appropriate position.
self.layerSlider
.trigger({
type: 'slideStart',
type: "slideStart",
value: value
})
.trigger({
type: 'slide',
type: "slide",
value: value
}).trigger({
type: 'slideStop',
})
.trigger({
type: "slideStop",
value: value
});
}
};
self.incrementLayer = function() {
var value = self.layerSlider.slider('getValue') + 1;
self.incrementLayer = function () {
var value = self.layerSlider.slider("getValue") + 1;
self.shiftLayer(value);
};
self.decrementLayer = function() {
var value = self.layerSlider.slider('getValue') - 1;
self.decrementLayer = function () {
var value = self.layerSlider.slider("getValue") - 1;
self.shiftLayer(value);
};
var optionsLocalStorageKey = "core.gcodeviewer.options";
self._toLocalStorage = function() {
if (!Modernizr.localstorage)
return;
self._toLocalStorage = function () {
if (!Modernizr.localstorage) return;
var current = {};
current["centerViewport"] = self.renderer_centerViewport();
@@ -725,11 +878,10 @@ $(function() {
localStorage[optionsLocalStorageKey] = JSON.stringify(current);
};
self._fromLocalStorage = function() {
self._fromLocalStorage = function () {
self.resetOptions();
if (!Modernizr.localstorage)
return;
if (!Modernizr.localstorage) return;
var currentString = localStorage[optionsLocalStorageKey];
var current;
@@ -743,18 +895,30 @@ $(function() {
}
}
if (current["centerViewport"] !== undefined) self.renderer_centerViewport(current["centerViewport"]) ;
if (current["zoomOnModel"] !== undefined) self.renderer_zoomOnModel(current["zoomOnModel"]) ;
if (current["showMoves"] !== undefined) self.renderer_showMoves(current["showMoves"]) ;
if (current["showRetracts"] !== undefined) self.renderer_showRetracts(current["showRetracts"]) ;
if (current["showPrinthead"] !== undefined) self.renderer_showPrinthead(current["showPrinthead"]);
if (current["showPrevious"] !== undefined) self.renderer_showPrevious(current["showPrevious"]) ;
if (current["showCurrent"] !== undefined) self.renderer_showCurrent(current["showCurrent"]) ;
if (current["showNext"] !== undefined) self.renderer_showNext(current["showNext"]) ;
if (current["showFullsize"] !== undefined) self.renderer_showFullSize(current["showFullsize"]) ;
if (current["showBoundingBox"] !== undefined) self.renderer_showBoundingBox(current["showBoundingBox"]) ;
if (current["hideEmptyLayers"] !== undefined) self.reader_hideEmptyLayers(current["hideEmptyLayers"]) ;
if (current["sortLayers"] !== undefined) self.reader_sortLayers(current["sortLayers"]) ;
if (current["centerViewport"] !== undefined)
self.renderer_centerViewport(current["centerViewport"]);
if (current["zoomOnModel"] !== undefined)
self.renderer_zoomOnModel(current["zoomOnModel"]);
if (current["showMoves"] !== undefined)
self.renderer_showMoves(current["showMoves"]);
if (current["showRetracts"] !== undefined)
self.renderer_showRetracts(current["showRetracts"]);
if (current["showPrinthead"] !== undefined)
self.renderer_showPrinthead(current["showPrinthead"]);
if (current["showPrevious"] !== undefined)
self.renderer_showPrevious(current["showPrevious"]);
if (current["showCurrent"] !== undefined)
self.renderer_showCurrent(current["showCurrent"]);
if (current["showNext"] !== undefined)
self.renderer_showNext(current["showNext"]);
if (current["showFullsize"] !== undefined)
self.renderer_showFullSize(current["showFullsize"]);
if (current["showBoundingBox"] !== undefined)
self.renderer_showBoundingBox(current["showBoundingBox"]);
if (current["hideEmptyLayers"] !== undefined)
self.reader_hideEmptyLayers(current["hideEmptyLayers"]);
if (current["sortLayers"] !== undefined)
self.reader_sortLayers(current["sortLayers"]);
};
}
@@ -4,30 +4,33 @@
* Time: 7:31 AM
*/
GCODE.gCodeReader = (function(){
// ***** PRIVATE ******
GCODE.gCodeReader = (function () {
// ***** PRIVATE ******
var gcode, lines;
var z_heights = {};
var model = [];
var max = {x: undefined, y: undefined, z: undefined};
var min = {x: undefined, y: undefined, z: undefined};
var modelSize = {x: undefined, y: undefined, z: undefined};
var boundingBox = {minX: undefined, maxX: undefined,
minY: undefined, maxY: undefined,
minZ: undefined, maxZ: undefined};
var boundingBox = {
minX: undefined,
maxX: undefined,
minY: undefined,
maxY: undefined,
minZ: undefined,
maxZ: undefined
};
var filamentByLayer = {};
var printTimeByLayer;
var totalFilament=0;
var printTime=0;
var totalFilament = 0;
var printTime = 0;
var speeds = {};
var speedsByLayer = {};
var gCodeOptions = {
sortLayers: false,
purgeEmptyLayers: true,
analyzeModel: false,
toolOffsets: [
{x: 0, y: 0}
],
toolOffsets: [{x: 0, y: 0}],
bed: {
x: undefined,
y: undefined,
@@ -41,39 +44,39 @@ GCODE.gCodeReader = (function(){
var percentageTree = undefined;
var prepareGCode = function(totalSize){
if(!lines)return;
var prepareGCode = function (totalSize) {
if (!lines) return;
gcode = [];
var i, byteCount;
byteCount = 0;
for(i=0;i<lines.length;i++){
for (i = 0; i < lines.length; i++) {
byteCount += lines[i].length + 1; // line length + line ending
gcode.push({line: lines[i], percentage: byteCount * 100 / totalSize});
gcode.push({line: lines[i], percentage: (byteCount * 100) / totalSize});
}
lines = [];
};
var sortLayers = function(m){
var sortLayers = function (m) {
var sortedZ = [];
var tmpModel = [];
for(var layer in z_heights){
for (var layer in z_heights) {
sortedZ[z_heights[layer]] = layer;
}
sortedZ.sort(function(a,b){
return a-b;
sortedZ.sort(function (a, b) {
return a - b;
});
for(var i=0;i<sortedZ.length;i++){
if(typeof(z_heights[sortedZ[i]]) === 'undefined')continue;
for (var i = 0; i < sortedZ.length; i++) {
if (typeof z_heights[sortedZ[i]] === "undefined") continue;
tmpModel[i] = m[z_heights[sortedZ[i]]];
}
return tmpModel;
};
var prepareLinesIndex = function(m){
var prepareLinesIndex = function (m) {
percentageTree = undefined;
for (var l = 0; l < m.length; l++) {
@@ -90,7 +93,7 @@ GCODE.gCodeReader = (function(){
}
};
var searchInPercentageTree = function(key) {
var searchInPercentageTree = function (key) {
if (percentageTree === undefined) {
return undefined;
}
@@ -103,17 +106,17 @@ GCODE.gCodeReader = (function(){
return elements[0];
};
var purgeLayers = function(m){
if(!m) return;
var purgeLayers = function (m) {
if (!m) return;
var tmpModel = [];
var purge;
for(var i = 0; i < m.length; i++){
for (var i = 0; i < m.length; i++) {
purge = true;
if (typeof(m[i]) !== "undefined") {
if (typeof m[i] !== "undefined") {
for (var j = 0; j < m[i].length; j++) {
if(m[i][j].extrude) {
if (m[i][j].extrude) {
purge = false;
break;
}
@@ -128,20 +131,25 @@ GCODE.gCodeReader = (function(){
return tmpModel;
};
// ***** PUBLIC *******
// ***** PUBLIC *******
return {
clear: function() {
clear: function () {
model = [];
z_heights = [];
max = {x: undefined, y: undefined, z: undefined};
min = {x: undefined, y: undefined, z: undefined};
modelSize = {x: undefined, y: undefined, z: undefined};
boundingBox = {minX: undefined, maxX: undefined,
minY: undefined, maxY: undefined,
minZ: undefined, maxZ: undefined};
boundingBox = {
minX: undefined,
maxX: undefined,
minY: undefined,
maxY: undefined,
minZ: undefined,
maxZ: undefined
};
},
loadFile: function(reader){
loadFile: function (reader) {
this.clear();
var totalSize = reader.target.result.length;
@@ -150,26 +158,25 @@ GCODE.gCodeReader = (function(){
prepareGCode(totalSize);
GCODE.ui.worker.postMessage({
"cmd":"parseGCode",
"msg":{
gcode: gcode,
options: {
firstReport: 5,
toolOffsets: gCodeOptions["toolOffsets"],
bed: gCodeOptions["bed"],
ignoreOutsideBed: gCodeOptions["ignoreOutsideBed"],
g90InfluencesExtruder: gCodeOptions["g90InfluencesExtruder"]
}
cmd: "parseGCode",
msg: {
gcode: gcode,
options: {
firstReport: 5,
toolOffsets: gCodeOptions["toolOffsets"],
bed: gCodeOptions["bed"],
ignoreOutsideBed: gCodeOptions["ignoreOutsideBed"],
g90InfluencesExtruder: gCodeOptions["g90InfluencesExtruder"]
}
}
);
});
},
setOption: function(options){
setOption: function (options) {
var dirty = false;
for(var opt in options){
for (var opt in options) {
if (options[opt] === undefined) continue;
dirty = dirty || (gCodeOptions[opt] != options[opt]);
dirty = dirty || gCodeOptions[opt] != options[opt];
gCodeOptions[opt] = options[opt];
}
if (dirty) {
@@ -177,7 +184,7 @@ GCODE.gCodeReader = (function(){
}
},
passDataToRenderer: function(){
passDataToRenderer: function () {
var m = model;
if (gCodeOptions["sortLayers"]) m = sortLayers(m);
if (gCodeOptions["purgeEmptyLayers"]) m = purgeLayers(m);
@@ -186,19 +193,19 @@ GCODE.gCodeReader = (function(){
return m;
},
processLayerFromWorker: function(msg){
processLayerFromWorker: function (msg) {
model[msg.layerNum] = msg.cmds;
z_heights[msg.zHeightObject.zValue] = msg.zHeightObject.layer;
},
processMultiLayerFromWorker: function(msg){
for(var i=0;i<msg.layerNum.length;i++){
processMultiLayerFromWorker: function (msg) {
for (var i = 0; i < msg.layerNum.length; i++) {
model[msg.layerNum[i]] = msg.model[msg.layerNum[i]];
z_heights[msg.zHeightObject.zValue[i]] = msg.layerNum[i];
}
},
processAnalyzeModelDone: function(msg){
processAnalyzeModelDone: function (msg) {
min = msg.min;
max = msg.max;
modelSize = msg.modelSize;
@@ -211,15 +218,15 @@ GCODE.gCodeReader = (function(){
printTimeByLayer = msg.printTimeByLayer;
},
getLayerFilament: function(z){
getLayerFilament: function (z) {
return filamentByLayer[z];
},
getLayerSpeeds: function(z){
return speedsByLayer[z]?speedsByLayer[z]:{};
getLayerSpeeds: function (z) {
return speedsByLayer[z] ? speedsByLayer[z] : {};
},
getModelInfo: function(){
getModelInfo: function () {
return {
min: min,
max: max,
@@ -233,7 +240,7 @@ GCODE.gCodeReader = (function(){
};
},
getGCodeLines: function(layer, fromSegments, toSegments){
getGCodeLines: function (layer, fromSegments, toSegments) {
var result = {
first: model[layer][fromSegments].gcodeLine,
last: model[layer][toSegments].gcodeLine
@@ -241,13 +248,13 @@ GCODE.gCodeReader = (function(){
return result;
},
getCmdIndexForPercentage: function(percentage) {
getCmdIndexForPercentage: function (percentage) {
var command = searchInPercentageTree(percentage);
if (command === undefined) {
return undefined
return undefined;
} else {
return command.value;
}
}
}
}());
};
})();
@@ -5,9 +5,8 @@
* To change this template use File | Settings | File Templates.
*/
GCODE.renderer = (function(){
// ***** PRIVATE ******
GCODE.renderer = (function () {
// ***** PRIVATE ******
var canvas;
var ctx;
@@ -15,12 +14,14 @@ GCODE.renderer = (function(){
var lineWidthFactor = 1 / 2.8;
var zoomFactorDelta = 0.4;
var gridStep=10;
var gridStep = 10;
var ctxHeight, ctxWidth;
var prevX=0, prevY=0;
var prevX = 0,
prevY = 0;
var pixelRatio = window.devicePixelRatio || 1;
var layerNumStore, progressStore={from: 0, to: -1};
var layerNumStore,
progressStore = {from: 0, to: -1};
var lastX, lastY;
var dragStart;
var scaleFactor = 1.1;
@@ -65,16 +66,20 @@ GCODE.renderer = (function(){
onViewportChange: undefined,
onDragStart: undefined, // Cancellable (return false)
onDrag: undefined, // Cancellable (return false)
onDrag: undefined, // Cancellable (return false)
onDragStop: undefined
};
var offsetModelX = 0, offsetModelY = 0;
var offsetBedX = 0, offsetBedY = 0;
var scaleX = 1, scaleY = 1;
var offsetModelX = 0,
offsetModelY = 0;
var offsetBedX = 0,
offsetBedY = 0;
var scaleX = 1,
scaleY = 1;
var speeds = [];
var speedsByLayer = {};
var currentInvertX = false, currentInvertY = false;
var currentInvertX = false,
currentInvertY = false;
function notifyIfViewportChanged() {
if (viewportChanged) {
@@ -84,30 +89,53 @@ GCODE.renderer = (function(){
viewportChanged = false;
}
}
var reRender = function(){
var reRender = function () {
if (!model) return;
log.debug("Rerendering layer " + layerNumStore + " of " + model.length + " with " + GCODE.renderer.getLayerNumSegments(layerNumStore) + " segments");
log.debug(
"Rerendering layer " +
layerNumStore +
" of " +
model.length +
" with " +
GCODE.renderer.getLayerNumSegments(layerNumStore) +
" segments"
);
notifyIfViewportChanged();
var p1 = ctx.transformedPoint(0,0);
var p2 = ctx.transformedPoint(canvas.width,canvas.height);
ctx.clearRect(p1.x,p1.y,p2.x-p1.x,p2.y-p1.y);
var p1 = ctx.transformedPoint(0, 0);
var p2 = ctx.transformedPoint(canvas.width, canvas.height);
ctx.clearRect(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y);
drawGrid();
drawBoundingBox();
if (model && model.length) {
if (layerNumStore < model.length) {
if (renderOptions['showNextLayer'] && layerNumStore < model.length - 1) {
drawLayer(layerNumStore + 1, 0, GCODE.renderer.getLayerNumSegments(layerNumStore + 1), true);
if (renderOptions["showNextLayer"] && layerNumStore < model.length - 1) {
drawLayer(
layerNumStore + 1,
0,
GCODE.renderer.getLayerNumSegments(layerNumStore + 1),
true
);
}
if (renderOptions['showCurrentLayer'] && layerNumStore < model.length) {
drawLayer(layerNumStore, 0, GCODE.renderer.getLayerNumSegments(layerNumStore), true);
if (renderOptions["showCurrentLayer"] && layerNumStore < model.length) {
drawLayer(
layerNumStore,
0,
GCODE.renderer.getLayerNumSegments(layerNumStore),
true
);
}
if (renderOptions['showPreviousLayer'] && layerNumStore > 0) {
drawLayer(layerNumStore - 1, 0, GCODE.renderer.getLayerNumSegments(layerNumStore - 1), true);
if (renderOptions["showPreviousLayer"] && layerNumStore > 0) {
drawLayer(
layerNumStore - 1,
0,
GCODE.renderer.getLayerNumSegments(layerNumStore - 1),
true
);
}
drawLayer(layerNumStore, progressStore.from, progressStore.to);
} else {
@@ -116,52 +144,59 @@ GCODE.renderer = (function(){
}
};
function trackTransforms(ctx){
var svg = document.createElementNS("http://www.w3.org/2000/svg",'svg');
function trackTransforms(ctx) {
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
var xform = svg.createSVGMatrix();
ctx.getTransform = function(){ return xform; };
ctx.getTransform = function () {
return xform;
};
var savedTransforms = [];
var save = ctx.save;
ctx.save = function(){
savedTransforms.push(xform.translate(0,0));
ctx.save = function () {
savedTransforms.push(xform.translate(0, 0));
return save.call(ctx);
};
var restore = ctx.restore;
ctx.restore = function(){
ctx.restore = function () {
xform = savedTransforms.pop();
viewportChanged = true;
return restore.call(ctx);
};
var scale = ctx.scale;
ctx.scale = function(sx,sy){
xform = xform.scaleNonUniform(sx,sy);
ctx.scale = function (sx, sy) {
xform = xform.scaleNonUniform(sx, sy);
viewportChanged = true;
return scale.call(ctx,sx,sy);
return scale.call(ctx, sx, sy);
};
var rotate = ctx.rotate;
ctx.rotate = function(radians){
xform = xform.rotate(radians*180/Math.PI);
ctx.rotate = function (radians) {
xform = xform.rotate((radians * 180) / Math.PI);
viewportChanged = true;
return rotate.call(ctx,radians);
return rotate.call(ctx, radians);
};
var translate = ctx.translate;
ctx.translate = function(dx,dy){
xform = xform.translate(dx,dy);
ctx.translate = function (dx, dy) {
xform = xform.translate(dx, dy);
viewportChanged = true;
return translate.call(ctx,dx,dy);
return translate.call(ctx, dx, dy);
};
var transform = ctx.transform;
ctx.transform = function(a,b,c,d,e,f){
ctx.transform = function (a, b, c, d, e, f) {
var m2 = svg.createSVGMatrix();
m2.a=a; m2.b=b; m2.c=c; m2.d=d; m2.e=e; m2.f=f;
m2.a = a;
m2.b = b;
m2.c = c;
m2.d = d;
m2.e = e;
m2.f = f;
xform = xform.multiply(m2);
viewportChanged = true;
return transform.call(ctx,a,b,c,d,e,f);
return transform.call(ctx, a, b, c, d, e, f);
};
var setTransform = ctx.setTransform;
ctx.setTransform = function(a,b,c,d,e,f){
ctx.setTransform = function (a, b, c, d, e, f) {
xform.a = a;
xform.b = b;
xform.c = c;
@@ -169,109 +204,127 @@ GCODE.renderer = (function(){
xform.e = e;
xform.f = f;
viewportChanged = true;
return setTransform.call(ctx,a,b,c,d,e,f);
return setTransform.call(ctx, a, b, c, d, e, f);
};
var pt = svg.createSVGPoint();
ctx.transformedPoint = function(x,y){
pt.x=x; pt.y=y;
var pt = svg.createSVGPoint();
ctx.transformedPoint = function (x, y) {
pt.x = x;
pt.y = y;
return pt.matrixTransform(xform.inverse());
}
};
}
var startCanvas = function() {
var startCanvas = function () {
var jqueryCanvas = $(renderOptions["container"]);
//jqueryCanvas.css("background-color", renderOptions["bgColorOffGrid"]);
canvas = jqueryCanvas[0];
ctx = canvas.getContext('2d');
ctx = canvas.getContext("2d");
canvas.style.height = canvas.height + "px";
canvas.style.width = canvas.width + "px";
canvas.height = canvas.height * pixelRatio;
canvas.width = canvas.width * pixelRatio;
ctxHeight = canvas.height;
ctxWidth = canvas.width;
lastX = ctxWidth/2;
lastY = ctxHeight/2;
lastX = ctxWidth / 2;
lastY = ctxHeight / 2;
ctx.lineWidth = 2 * lineWidthFactor;
ctx.lineCap = 'round';
ctx.lineCap = "round";
trackTransforms(ctx);
ctx.scale(1,-1); // Invert y-axis
ctx.scale(1, -1); // Invert y-axis
// dragging => translating
canvas.addEventListener('mousedown', function(event){
document.body.style.mozUserSelect = document.body.style.webkitUserSelect = document.body.style.userSelect = 'none';
canvas.addEventListener(
"mousedown",
function (event) {
document.body.style.mozUserSelect = document.body.style.webkitUserSelect = document.body.style.userSelect =
"none";
// remember starting point of dragging gesture
lastX = (event.offsetX || (event.pageX - canvas.offsetLeft)) * pixelRatio;
lastY = (event.offsetY || (event.pageY - canvas.offsetTop)) * pixelRatio;
// remember starting point of dragging gesture
lastX = (event.offsetX || event.pageX - canvas.offsetLeft) * pixelRatio;
lastY = (event.offsetY || event.pageY - canvas.offsetTop) * pixelRatio;
var pt = ctx.transformedPoint(lastX, lastY);
if (!renderOptions["onDragStart"] || (renderOptions["onDragStart"](pt) !== false))
dragStart = pt;
}, false);
var pt = ctx.transformedPoint(lastX, lastY);
if (
!renderOptions["onDragStart"] ||
renderOptions["onDragStart"](pt) !== false
)
dragStart = pt;
},
false
);
canvas.addEventListener('mousemove', function(event){
// save current mouse coordinates
lastX = (event.offsetX || (event.pageX - canvas.offsetLeft)) * pixelRatio;
lastY = (event.offsetY || (event.pageY - canvas.offsetTop)) * pixelRatio;
canvas.addEventListener(
"mousemove",
function (event) {
// save current mouse coordinates
lastX = (event.offsetX || event.pageX - canvas.offsetLeft) * pixelRatio;
lastY = (event.offsetY || event.pageY - canvas.offsetTop) * pixelRatio;
// mouse movement => dragged
if (dragStart !== undefined) {
// translate
var pt = ctx.transformedPoint(lastX,lastY);
// mouse movement => dragged
if (dragStart !== undefined) {
// translate
var pt = ctx.transformedPoint(lastX, lastY);
if (renderOptions["onDrag"] && (renderOptions["onDrag"](pt) === false))
return;
if (renderOptions["onDrag"] && renderOptions["onDrag"](pt) === false)
return;
ctx.translate(pt.x - dragStart.x, pt.y - dragStart.y);
reRender();
ctx.translate(pt.x - dragStart.x, pt.y - dragStart.y);
reRender();
renderOptions["centerViewport"] = false;
renderOptions["zoomInOnModel"] = false;
renderOptions["zoomInOnBed"] = false;
offsetModelX = 0;
offsetModelY = 0;
offsetBedX = 0;
offsetBedY = 0;
scaleX = 1;
scaleY = 1;
renderOptions["centerViewport"] = false;
renderOptions["zoomInOnModel"] = false;
renderOptions["zoomInOnBed"] = false;
offsetModelX = 0;
offsetModelY = 0;
offsetBedX = 0;
offsetBedY = 0;
scaleX = 1;
scaleY = 1;
if (renderOptions["onInternalOptionChange"] !== undefined) {
renderOptions["onInternalOptionChange"]({
centerViewport: false,
moveModel: false,
zoomInOnModel: false,
zoomInOnBed: false
});
if (renderOptions["onInternalOptionChange"] !== undefined) {
renderOptions["onInternalOptionChange"]({
centerViewport: false,
moveModel: false,
zoomInOnModel: false,
zoomInOnBed: false
});
}
}
}
}, false);
},
false
);
canvas.addEventListener('mouseup', function(event){
// reset dragStart
dragStart = undefined;
canvas.addEventListener(
"mouseup",
function (event) {
// reset dragStart
dragStart = undefined;
if (renderOptions["onDragStop"]) {
var x = (event.offsetX || (event.pageX - canvas.offsetLeft)) * pixelRatio;
var y = (event.offsetY || (event.pageY - canvas.offsetTop)) * pixelRatio;
renderOptions["onDragStop"](ctx.transformedPoint(x,y));
}
}, false);
if (renderOptions["onDragStop"]) {
var x =
(event.offsetX || event.pageX - canvas.offsetLeft) * pixelRatio;
var y =
(event.offsetY || event.pageY - canvas.offsetTop) * pixelRatio;
renderOptions["onDragStop"](ctx.transformedPoint(x, y));
}
},
false
);
// mouse wheel => zooming
var zoom = function(clicks){
var zoom = function (clicks) {
// focus on last mouse position prior to zoom
var pt = ctx.transformedPoint(lastX, lastY);
ctx.translate(pt.x,pt.y);
ctx.translate(pt.x, pt.y);
// determine zooming factor and perform zoom
var factor = Math.pow(scaleFactor,clicks);
ctx.scale(factor,factor);
var factor = Math.pow(scaleFactor, clicks);
ctx.scale(factor, factor);
// return to old position
ctx.translate(-pt.x,-pt.y);
ctx.translate(-pt.x, -pt.y);
// render
reRender();
@@ -293,7 +346,7 @@ GCODE.renderer = (function(){
});
}
};
var handleScroll = function(event){
var handleScroll = function (event) {
var delta;
// determine zoom direction & delta
@@ -306,13 +359,13 @@ GCODE.renderer = (function(){
return event.preventDefault() && false;
};
canvas.addEventListener('DOMMouseScroll',handleScroll,false);
canvas.addEventListener('mousewheel',handleScroll,false);
canvas.addEventListener("DOMMouseScroll", handleScroll, false);
canvas.addEventListener("mousewheel", handleScroll, false);
};
var drawGrid = function() {
var drawGrid = function () {
ctx.translate(offsetBedX, offsetBedY);
if(renderOptions["bed"]["circular"]) {
if (renderOptions["bed"]["circular"]) {
drawCircularGrid();
} else {
drawRectangularGrid();
@@ -320,7 +373,7 @@ GCODE.renderer = (function(){
ctx.translate(-offsetBedX, -offsetBedY);
};
var drawRectangularGrid = function() {
var drawRectangularGrid = function () {
var x, y;
var width = renderOptions["bed"]["x"];
var height = renderOptions["bed"]["y"];
@@ -394,7 +447,7 @@ GCODE.renderer = (function(){
ctx.stroke();
};
var drawCircularGrid = function() {
var drawCircularGrid = function () {
var i;
ctx.strokeStyle = renderOptions["colorGrid"];
@@ -430,7 +483,7 @@ GCODE.renderer = (function(){
ctx.beginPath();
for (i = 0; i <= r; i += gridStep) {
var x = i;
var y = Math.sqrt(r*r - x*x);
var y = Math.sqrt(r * r - x * x);
ctx.moveTo(x, -1 * y);
ctx.lineTo(x, y);
@@ -447,7 +500,7 @@ GCODE.renderer = (function(){
ctx.stroke();
};
var drawBoundingBox = function() {
var drawBoundingBox = function () {
if (!modelInfo) return;
var minX, minY, width, height;
@@ -485,7 +538,7 @@ GCODE.renderer = (function(){
ctx.setLineDash([1, 0]);
};
var drawTriangle = function(centerX, centerY, length, up) {
var drawTriangle = function (centerX, centerY, length, up) {
/*
* (cx,cy)
* * ^
@@ -532,8 +585,18 @@ GCODE.renderer = (function(){
ctx.lineJoin = origLineJoin;
};
var drawLayer = function(layerNum, fromProgress, toProgress, isNotCurrentLayer){
log.trace("Drawing layer " + layerNum + " from " + fromProgress + " to " + toProgress + " (current: " + !isNotCurrentLayer + ")");
var drawLayer = function (layerNum, fromProgress, toProgress, isNotCurrentLayer) {
log.trace(
"Drawing layer " +
layerNum +
" from " +
fromProgress +
" to " +
toProgress +
" (current: " +
!isNotCurrentLayer +
")"
);
var i;
@@ -560,17 +623,15 @@ GCODE.renderer = (function(){
// previous layer exists, use last x/y as prevX/prevY
prevX = undefined;
prevY = undefined;
var prevModelLayer = model[layerNum-1];
for (i = prevModelLayer.length-1; i >= 0; i--) {
var prevModelLayer = model[layerNum - 1];
for (i = prevModelLayer.length - 1; i >= 0; i--) {
if (prevX === undefined && prevModelLayer[i].x !== undefined) {
prevX = prevModelLayer[i].x;
if (prevY !== undefined)
break;
if (prevY !== undefined) break;
}
if (prevY === undefined && prevModelLayer[i].y !== undefined) {
prevY = prevModelLayer[i].y;
if (prevX !== undefined)
break;
if (prevX !== undefined) break;
}
}
}
@@ -586,8 +647,14 @@ GCODE.renderer = (function(){
// alpha value (100% if current layer is being rendered, 30% otherwise)
// Note - If showing currently layer as preview - also render it at 30% and draw the progress over the top at 100%
var alpha = (renderOptions['showNextLayer'] || renderOptions['showCurrentLayer'] || renderOptions['showPreviousLayer']) && isNotCurrentLayer ? 0.3 : 1.0;
var alpha =
(renderOptions["showNextLayer"] ||
renderOptions["showCurrentLayer"] ||
renderOptions["showPreviousLayer"]) &&
isNotCurrentLayer
? 0.3
: 1.0;
var colorLine = {};
var colorMove = {};
var colorRetract = {};
@@ -599,7 +666,11 @@ GCODE.renderer = (function(){
var lineColor = renderOptions["colorLine"][tool];
if (lineColor === undefined) lineColor = renderOptions["colorLine"][0];
var shade = tool * 0.15;
rv = colorLine[tool] = pusher.color(lineColor).shade(shade).alpha(alpha).html();
rv = colorLine[tool] = pusher
.color(lineColor)
.shade(shade)
.alpha(alpha)
.html();
}
return rv;
}
@@ -608,7 +679,11 @@ GCODE.renderer = (function(){
var rv = colorMove[tool];
if (rv === undefined) {
var shade = tool * 0.15;
rv = colorMove[tool] = pusher.color(renderOptions["colorMove"]).shade(shade).alpha(alpha).html();
rv = colorMove[tool] = pusher
.color(renderOptions["colorMove"])
.shade(shade)
.alpha(alpha)
.html();
}
return rv;
}
@@ -617,7 +692,11 @@ GCODE.renderer = (function(){
var rv = colorRetract[tool];
if (rv === undefined) {
var shade = tool * 0.15;
rv = colorRetract[tool] = pusher.color(renderOptions["colorRetract"]).shade(shade).alpha(alpha).html();
rv = colorRetract[tool] = pusher
.color(renderOptions["colorRetract"])
.shade(shade)
.alpha(alpha)
.html();
}
return rv;
}
@@ -626,14 +705,18 @@ GCODE.renderer = (function(){
var rv = colorRestart[tool];
if (rv === undefined) {
var shade = tool * 0.15;
rv = colorRestart[tool] = pusher.color(renderOptions["colorRestart"]).shade(shade).alpha(alpha).html();
rv = colorRestart[tool] = pusher
.color(renderOptions["colorRestart"])
.shade(shade)
.alpha(alpha)
.html();
}
return rv;
}
var prevPathType = "fill";
function strokePathIfNeeded(newPathType, strokeStyle) {
if ((newPathType != prevPathType) || (newPathType == "fill")) {
if (newPathType != prevPathType || newPathType == "fill") {
if (prevPathType != "fill") {
ctx.stroke();
}
@@ -641,8 +724,8 @@ GCODE.renderer = (function(){
ctx.beginPath();
if (newPathType != "fill") {
ctx.strokeStyle = strokeStyle;
ctx.moveTo(prevX, prevY);
ctx.strokeStyle = strokeStyle;
ctx.moveTo(prevX, prevY);
}
}
}
@@ -650,7 +733,7 @@ GCODE.renderer = (function(){
ctx.lineJoin = "round";
for (i = fromProgress; i <= toProgress; i++) {
if (typeof(cmds[i]) === 'undefined') continue;
if (typeof cmds[i] === "undefined") continue;
var cmd = cmds[i];
if (cmd.prevX !== undefined && cmd.prevY !== undefined) {
@@ -689,27 +772,34 @@ GCODE.renderer = (function(){
}
strokePathIfNeeded("move", getColorMoveForTool(tool));
if(renderOptions["showMoves"] && !isNotCurrentLayer) {
if (renderOptions["showMoves"] && !isNotCurrentLayer) {
// move => draw line from (prevX, prevY) to (x, y) in move color
ctx.lineWidth = lineWidthFactor;
ctx.lineTo(x,y);
ctx.lineTo(x, y);
}
} else if(cmd.extrude) {
} else if (cmd.extrude) {
if (cmd.retract == 0) {
// no retraction => real extrusion move, use tool color to draw line
strokePathIfNeeded("extrude", getColorLineForTool(tool));
ctx.lineWidth = renderOptions['extrusionWidth'] * lineWidthFactor;
if (cmd.direction !== undefined && cmd.direction != 0){
ctx.lineWidth = renderOptions["extrusionWidth"] * lineWidthFactor;
if (cmd.direction !== undefined && cmd.direction != 0) {
var di = cmd.i;
var dj = cmd.j;
var centerX = prevX+di;
var centerY = prevY+dj;
var startAngle = Math.atan2(prevY-centerY, prevX - centerX);
var centerX = prevX + di;
var centerY = prevY + dj;
var startAngle = Math.atan2(prevY - centerY, prevX - centerX);
var endAngle = Math.atan2(y - centerY, x - centerX);
var radius=Math.sqrt(di*di+dj*dj);
ctx.arc(centerX,centerY,radius,startAngle,endAngle,cmd.direction<0); // Y-axis is inverted so direction is also inverted
var radius = Math.sqrt(di * di + dj * dj);
ctx.arc(
centerX,
centerY,
radius,
startAngle,
endAngle,
cmd.direction < 0
); // Y-axis is inverted so direction is also inverted
} else {
ctx.lineTo(x,y);
ctx.lineTo(x, y);
}
} else {
// we were previously retracting, now we are restarting => draw dot if configured to do so
@@ -726,22 +816,27 @@ GCODE.renderer = (function(){
prevX = x;
prevY = y;
}
if (prevPathType != "fill") {
ctx.stroke();
}
if (renderOptions["showHead"] && !isNotCurrentLayer) {
var sizeHeadSpot = renderOptions["sizeHeadSpot"] * lineWidthFactor + lineWidthFactor / 2;
var sizeHeadSpot =
renderOptions["sizeHeadSpot"] * lineWidthFactor + lineWidthFactor / 2;
var shade = tool * 0.15;
ctx.fillStyle = pusher.color(renderOptions["colorHead"]).shade(shade).alpha(alpha).html();
ctx.fillStyle = pusher
.color(renderOptions["colorHead"])
.shade(shade)
.alpha(alpha)
.html();
ctx.beginPath();
ctx.arc(prevX, prevY, sizeHeadSpot, 0, Math.PI*2, true);
ctx.arc(prevX, prevY, sizeHeadSpot, 0, Math.PI * 2, true);
ctx.fill();
}
};
var applyOffsets = function() {
var applyOffsets = function () {
var canvasCenter;
// determine bed and model offsets
@@ -749,8 +844,12 @@ GCODE.renderer = (function(){
if (renderOptions["centerViewport"] || renderOptions["zoomInOnModel"]) {
canvasCenter = ctx.transformedPoint(canvas.width / 2, canvas.height / 2);
if (modelInfo) {
offsetModelX = canvasCenter.x - (modelInfo.boundingBox.minX + modelInfo.boundingBox.maxX) / 2;
offsetModelY = canvasCenter.y - (modelInfo.boundingBox.minY + modelInfo.boundingBox.maxY) / 2;
offsetModelX =
canvasCenter.x -
(modelInfo.boundingBox.minX + modelInfo.boundingBox.maxX) / 2;
offsetModelY =
canvasCenter.y -
(modelInfo.boundingBox.minY + modelInfo.boundingBox.maxY) / 2;
} else {
offsetModelX = 0;
offsetModelY = 0;
@@ -758,11 +857,24 @@ GCODE.renderer = (function(){
offsetBedX = 0;
offsetBedY = 0;
} else if (modelInfo && renderOptions["moveModel"]) {
offsetModelX = (renderOptions["bed"]["x"] / 2 - (modelInfo.boundingBox.minX + modelInfo.boundingBox.maxX) / 2);
offsetModelY = (renderOptions["bed"]["y"] / 2 - (modelInfo.boundingBox.minY + modelInfo.boundingBox.maxY) / 2);
offsetBedX = -1 * (renderOptions["bed"]["x"] / 2 - (modelInfo.boundingBox.minX + modelInfo.boundingBox.maxX) / 2);
offsetBedY = -1 * (renderOptions["bed"]["y"] / 2 - (modelInfo.boundingBox.minY + modelInfo.boundingBox.maxY) / 2);
} else if (renderOptions["bed"]["circular"] || renderOptions["bed"]["centeredOrigin"]) {
offsetModelX =
renderOptions["bed"]["x"] / 2 -
(modelInfo.boundingBox.minX + modelInfo.boundingBox.maxX) / 2;
offsetModelY =
renderOptions["bed"]["y"] / 2 -
(modelInfo.boundingBox.minY + modelInfo.boundingBox.maxY) / 2;
offsetBedX =
-1 *
(renderOptions["bed"]["x"] / 2 -
(modelInfo.boundingBox.minX + modelInfo.boundingBox.maxX) / 2);
offsetBedY =
-1 *
(renderOptions["bed"]["y"] / 2 -
(modelInfo.boundingBox.minY + modelInfo.boundingBox.maxY) / 2);
} else if (
renderOptions["bed"]["circular"] ||
renderOptions["bed"]["centeredOrigin"]
) {
canvasCenter = ctx.transformedPoint(canvas.width / 2, canvas.height / 2);
offsetModelX = canvasCenter.x;
offsetModelY = canvasCenter.y;
@@ -777,9 +889,9 @@ GCODE.renderer = (function(){
if (ctx) ctx.translate(offsetModelX, offsetModelY);
};
var applyZoom = function() {
var applyZoom = function () {
// get middle of canvas
var pt = ctx.transformedPoint(canvas.width/2,canvas.height/2);
var pt = ctx.transformedPoint(canvas.width / 2, canvas.height / 2);
// get current transform
var transform = ctx.getTransform();
@@ -797,11 +909,16 @@ GCODE.renderer = (function(){
var width = modelInfo.boundingBox.maxX - modelInfo.boundingBox.minX;
var length = modelInfo.boundingBox.maxY - modelInfo.boundingBox.minY;
var scaleF = width > length ? (canvas.width - 10) / width : (canvas.height - 10) / length;
var scaleF =
width > length
? (canvas.width - 10) / width
: (canvas.height - 10) / length;
if (transform.a && transform.d) {
scaleX = scaleF / transform.a * (renderOptions["invertAxes"]["x"] ? -1 : 1);
scaleY = scaleF / transform.d * (renderOptions["invertAxes"]["y"] ? 1 : -1);
ctx.translate(pt.x,pt.y);
scaleX =
(scaleF / transform.a) * (renderOptions["invertAxes"]["x"] ? -1 : 1);
scaleY =
(scaleF / transform.d) * (renderOptions["invertAxes"]["y"] ? 1 : -1);
ctx.translate(pt.x, pt.y);
ctx.scale(scaleX, scaleY);
ctx.translate(-pt.x, -pt.y);
}
@@ -812,7 +929,7 @@ GCODE.renderer = (function(){
}
};
var applyInversion = function() {
var applyInversion = function () {
var width = canvas.width - 10;
var height = canvas.height - 10;
@@ -837,19 +954,22 @@ GCODE.renderer = (function(){
currentInvertY = invertY;
};
// ***** PUBLIC *******
// ***** PUBLIC *******
return {
init: function(){
init: function () {
startCanvas();
initialized = true;
var bedWidth = renderOptions["bed"]["x"];
var bedHeight = renderOptions["bed"]["y"];
if(renderOptions["bed"]["circular"]) {
if (renderOptions["bed"]["circular"]) {
bedWidth = bedHeight = renderOptions["bed"]["r"] * 2;
}
// Ratio of bed to canvas viewport
var viewportRatio = Math.min((canvas.width - 10) / bedWidth, (canvas.height - 10) / bedHeight);
var viewportRatio = Math.min(
(canvas.width - 10) / bedWidth,
(canvas.height - 10) / bedHeight
);
// Apply initial translation to center the bed in the viewport
var translationX, translationY;
@@ -858,12 +978,14 @@ GCODE.renderer = (function(){
translationY = canvas.height / 2;
} else {
translationX = (canvas.width - bedWidth * viewportRatio) / 2;
translationY = bedHeight * viewportRatio + (canvas.height - bedHeight * viewportRatio) / 2;
translationY =
bedHeight * viewportRatio +
(canvas.height - bedHeight * viewportRatio) / 2;
}
ctx.translate(translationX, -translationY);
ctx.scale(viewportRatio, viewportRatio);
offsetModelX = 0;
offsetModelY = 0;
offsetBedX = 0;
@@ -872,23 +994,33 @@ GCODE.renderer = (function(){
// Scaling to apply to move lines and extrusion/retraction markers
lineWidthFactor = 1 / viewportRatio;
},
setOption: function(options){
setOption: function (options) {
var mustRefresh = false;
var dirty = false;
for (var opt in options) {
if (!renderOptions.hasOwnProperty(opt) || !options.hasOwnProperty(opt)) continue;
if (!renderOptions.hasOwnProperty(opt) || !options.hasOwnProperty(opt))
continue;
if (options[opt] === undefined) continue;
if (renderOptions[opt] == options[opt]) continue;
dirty = true;
renderOptions[opt] = options[opt];
if ($.inArray(opt, ["moveModel", "centerViewport", "zoomInOnModel", "bed", "invertAxes", "onViewportChange"]) > -1) {
if (
$.inArray(opt, [
"moveModel",
"centerViewport",
"zoomInOnModel",
"bed",
"invertAxes",
"onViewportChange"
]) > -1
) {
mustRefresh = true;
}
}
if (!dirty) return;
if(initialized) {
if (initialized) {
if (mustRefresh) {
this.refresh();
} else {
@@ -896,32 +1028,32 @@ GCODE.renderer = (function(){
}
}
},
getOptions: function(){
getOptions: function () {
return renderOptions;
},
debugGetModel: function(){
debugGetModel: function () {
return model;
},
render: function(layerNum, fromProgress, toProgress){
render: function (layerNum, fromProgress, toProgress) {
if (!initialized) this.init();
layerNumStore = layerNum;
progressStore.from = fromProgress;
progressStore.to = toProgress;
reRender();
},
getModelNumLayers: function(){
getModelNumLayers: function () {
return model ? model.length : 1;
},
getLayerNumSegments: function(layer){
if(model){
return model[layer]?model[layer].length:1;
}else{
getLayerNumSegments: function (layer) {
if (model) {
return model[layer] ? model[layer].length : 1;
} else {
return 1;
}
},
clear: function() {
clear: function () {
offsetModelX = 0;
offsetModelY = 0;
offsetBedX = 0;
@@ -934,7 +1066,7 @@ GCODE.renderer = (function(){
this.doRender([], 0);
},
doRender: function(mdl, layerNum){
doRender: function (mdl, layerNum) {
model = mdl;
modelInfo = undefined;
@@ -958,20 +1090,19 @@ GCODE.renderer = (function(){
this.render(layerNum, 0, toProgress);
},
refresh: function(layerNum) {
refresh: function (layerNum) {
if (layerNum === undefined) layerNum = layerNumStore;
this.doRender(model, layerNum);
},
getZ: function(layerNum){
if(!model || !model[layerNum]){
return '-1';
getZ: function (layerNum) {
if (!model || !model[layerNum]) {
return "-1";
}
var cmds = model[layerNum];
for(var i = 0; i < cmds.length; i++){
if(cmds[i].prevZ !== undefined) return cmds[i].prevZ;
for (var i = 0; i < cmds.length; i++) {
if (cmds[i].prevZ !== undefined) return cmds[i].prevZ;
}
return '-1';
return "-1";
}
}
}());
};
})();
@@ -6,7 +6,7 @@
var GCODE = {};
GCODE.ui = (function(){
GCODE.ui = (function () {
var uiOptions = {
container: undefined,
toolOffsets: undefined,
@@ -16,13 +16,13 @@ GCODE.ui = (function(){
onLayerSelected: undefined
};
var setProgress = function(type, progress) {
var setProgress = function (type, progress) {
if (uiOptions["onProgress"]) {
uiOptions.onProgress(type, progress);
}
};
var switchLayer = function(layerNum, onlyInfo) {
var switchLayer = function (layerNum, onlyInfo) {
if (!onlyInfo) {
var segmentCount = GCODE.renderer.getLayerNumSegments(layerNum);
GCODE.renderer.render(layerNum, 0, segmentCount - 1);
@@ -41,17 +41,17 @@ GCODE.ui = (function(){
}
};
var switchCommands = function(layerNum, first, last) {
var switchCommands = function (layerNum, first, last) {
GCODE.renderer.render(layerNum, first, last);
};
var processMessage = function(e){
var processMessage = function (e) {
var data = e.data;
switch (data.cmd) {
case "returnModel":
GCODE.ui.worker.postMessage({
"cmd":"analyzeModel",
"msg":{}
cmd: "analyzeModel",
msg: {}
});
break;
@@ -93,34 +93,36 @@ GCODE.ui = (function(){
}
};
var checkCapabilities = function(){
var checkCapabilities = function () {
var warnings = [];
var fatal = [];
var errorList = document.getElementById("errorList");
if(fatal.length>0){
if (fatal.length > 0) {
if (errorList) {
errorList.innerHTML = '<ul>' + fatal.join('') + '</ul>';
errorList.innerHTML = "<ul>" + fatal.join("") + "</ul>";
}
console.log("Initialization failed: unsupported browser.")
console.log("Initialization failed: unsupported browser.");
return false;
}
if(!Modernizr.webgl && GCODE.renderer3d){
warnings.push("<li>Your browser doesn't seem to support HTML5 Web GL, 3d mode is not recommended, going to be SLOW!</li>");
if (!Modernizr.webgl && GCODE.renderer3d) {
warnings.push(
"<li>Your browser doesn't seem to support HTML5 Web GL, 3d mode is not recommended, going to be SLOW!</li>"
);
GCODE.renderer3d.setOption({rendererType: "canvas"});
}
if(warnings.length>0){
if (warnings.length > 0) {
if (errorList) {
errorList.innerHTML = '<ul>' + warnings.join('') + '</ul>';
errorList.innerHTML = "<ul>" + warnings.join("") + "</ul>";
}
console.log("Initialization succeeded with warnings.", warnings);
}
return true;
};
var setOptions = function(options) {
var setOptions = function (options) {
if (!options) return;
for (var opt in options) {
if (options[opt] === undefined) continue;
@@ -132,7 +134,7 @@ GCODE.ui = (function(){
return {
worker: undefined,
init: function(options){
init: function (options) {
if (options) setOptions(options);
if (!options.container) {
return false;
@@ -146,7 +148,7 @@ GCODE.ui = (function(){
setProgress("", 0);
this.worker = new Worker(GCODE_WORKER);
this.worker.addEventListener('message', processMessage, false);
this.worker.addEventListener("message", processMessage, false);
GCODE.renderer.setOption({
container: options.container,
@@ -161,7 +163,7 @@ GCODE.ui = (function(){
return true;
},
clear: function() {
clear: function () {
GCODE.gCodeReader.clear();
GCODE.renderer.clear();
@@ -174,11 +176,11 @@ GCODE.ui = (function(){
}
},
updateLayerInfo: function(layerNum){
updateLayerInfo: function (layerNum) {
switchLayer(layerNum, true);
},
updateOptions: function(options) {
updateOptions: function (options) {
setOptions(options.ui);
if (options.reader) {
GCODE.gCodeReader.setOption(options.reader);
@@ -188,12 +190,12 @@ GCODE.ui = (function(){
}
},
changeSelectedLayer: function(newLayerNum) {
changeSelectedLayer: function (newLayerNum) {
switchLayer(newLayerNum);
},
changeSelectedCommands: function(layerNum, first, last) {
changeSelectedCommands: function (layerNum, first, last) {
switchCommands(layerNum, first, last);
}
}
}());
};
})();
@@ -6,17 +6,28 @@
var gcode;
var firstReport;
var toolOffsets = [
{x: 0, y: 0}
];
var toolOffsets = [{x: 0, y: 0}];
var g90InfluencesExtruder = false;
var z_heights = {};
var model = [];
var max = {x: undefined, y: undefined, z: undefined};
var min = {x: undefined, y: undefined, z: undefined};
var boundingBox = {minX: undefined, maxX: undefined, minY: undefined, maxY: undefined, minZ: undefined, maxZ: undefined};
var boundingBox = {
minX: undefined,
maxX: undefined,
minY: undefined,
maxY: undefined,
minZ: undefined,
maxZ: undefined
};
var modelSize = {x: undefined, y: undefined, z: undefined};
var bed = {x: undefined, y: undefined, r: undefined, circular: false, centeredOrigin: false};
var bed = {
x: undefined,
y: undefined,
r: undefined,
circular: false,
centeredOrigin: false
};
var ignoreOutsideBed = false;
var filamentByLayer = {};
var totalFilament = [0];
@@ -29,8 +40,8 @@ var speedsByLayer = {extrude: {}, retract: {}, move: {}};
var sendLayerToParent = function (layerNum, z, progress) {
self.postMessage({
"cmd": "returnLayer",
"msg": {
cmd: "returnLayer",
msg: {
cmds: model[layerNum],
layerNum: layerNum,
zHeightObject: {zValue: z, layer: z_heights[z]},
@@ -50,8 +61,8 @@ var sendMultiLayerToParent = function (layerNum, z, progress) {
}
self.postMessage({
"cmd": "returnMultiLayer",
"msg": {
cmd: "returnMultiLayer",
msg: {
model: tmpModel,
layerNum: layerNum,
zHeightObject: {zValue: z, layer: tmpZHeight},
@@ -61,11 +72,10 @@ var sendMultiLayerToParent = function (layerNum, z, progress) {
});
};
var sendSizeProgress = function (progress) {
self.postMessage({
"cmd": "analyzeProgress",
"msg": {
cmd: "analyzeProgress",
msg: {
progress: progress,
printTime: printTime
}
@@ -74,8 +84,8 @@ var sendSizeProgress = function (progress) {
var sendAnalyzeDone = function () {
self.postMessage({
"cmd": "analyzeDone",
"msg": {
cmd: "analyzeDone",
msg: {
max: max,
min: min,
modelSize: modelSize,
@@ -101,7 +111,7 @@ var purgeLayers = function () {
purge = true;
} else {
for (var j = 0; j < model[i].length; j++) {
if (model[i][j].extrude)purge = false;
if (model[i][j].extrude) purge = false;
}
}
if (!purge) {
@@ -110,7 +120,7 @@ var purgeLayers = function () {
}
};
var bedBounds = function() {
var bedBounds = function () {
if (!bed) {
return {xMin: 0, xMax: 0, yMin: 0, yMax: 0};
}
@@ -119,30 +129,36 @@ var bedBounds = function() {
if (bed.circular) {
result = {xMin: -bed.r, xMax: bed.r, yMin: -bed.r, yMax: bed.r};
} else if (bed.centeredOrigin) {
result = {xMin: -bed.x/2.0, xMax: bed.x/2.0, yMin: -bed.y/2.0, yMax: bed.y/2.0};
result = {
xMin: -bed.x / 2.0,
xMax: bed.x / 2.0,
yMin: -bed.y / 2.0,
yMax: bed.y / 2.0
};
} else {
result = {xMin: 0, xMax: bed.x, yMin: 0, yMax: bed.y};
}
return result;
};
var withinBedBounds = function(x, y, bedBounds) {
var withinBedBounds = function (x, y, bedBounds) {
if (!ignoreOutsideBed) return true;
var result = true;
if (x !== undefined && !isNaN(x)) {
result = result && (x >= bedBounds.xMin && x <= bedBounds.xMax);
result = result && x >= bedBounds.xMin && x <= bedBounds.xMax;
}
if (y !== undefined && !isNaN(y)) {
result = result && (y >= bedBounds.yMin && y <= bedBounds.yMax);
result = result && y >= bedBounds.yMin && y <= bedBounds.yMax;
}
return result;
};
var analyzeModel = function () {
var tmp1 = 0, tmp2 = 0;
var tmp1 = 0,
tmp2 = 0;
var speedIndex = 0;
var type;
var printTimeAdd = 0;
@@ -158,38 +174,55 @@ var analyzeModel = function () {
var retract = cmds[j].retract && cmds[j].retract > 0;
var extrude = cmds[j].extrude && cmds[j].extrude > 0 && !retract;
var move = cmds[j].x !== undefined || cmds[j].y !== undefined || cmds[j].z !== undefined;
var move =
cmds[j].x !== undefined ||
cmds[j].y !== undefined ||
cmds[j].z !== undefined;
var prevInBounds = withinBedBounds(cmds[j].prevX, cmds[j].prevY, bounds);
var inBounds = withinBedBounds(cmds[j].x === undefined ? cmds[j].prevX : cmds[j].x,
cmds[j].y === undefined ? cmds[j].prevY : cmds[j].y,
bounds);
var inBounds = withinBedBounds(
cmds[j].x === undefined ? cmds[j].prevX : cmds[j].x,
cmds[j].y === undefined ? cmds[j].prevY : cmds[j].y,
bounds
);
var recordX = function(x, inBounds) {
var recordX = function (x, inBounds) {
if (x === undefined || isNaN(x)) return;
max.x = max.x !== undefined ? Math.max(max.x, x) : x;
min.x = min.x !== undefined ? Math.min(min.x, x) : x;
if (inBounds) {
boundingBox.minX = boundingBox.minX !== undefined ? Math.min(boundingBox.minX, x): x;
boundingBox.maxX = boundingBox.maxX !== undefined ? Math.max(boundingBox.maxX, x): x;
boundingBox.minX =
boundingBox.minX !== undefined
? Math.min(boundingBox.minX, x)
: x;
boundingBox.maxX =
boundingBox.maxX !== undefined
? Math.max(boundingBox.maxX, x)
: x;
}
};
var recordY = function(y, inBounds) {
var recordY = function (y, inBounds) {
if (y === undefined || isNaN(y)) return;
max.y = max.y !== undefined ? Math.max(max.y, y) : y;
min.y = min.y !== undefined ? Math.min(min.y, y) : y;
if (inBounds) {
boundingBox.minY = boundingBox.minY !== undefined ? Math.min(boundingBox.minY, y): y;
boundingBox.maxY = boundingBox.maxY !== undefined ? Math.max(boundingBox.maxY, y): y;
boundingBox.minY =
boundingBox.minY !== undefined
? Math.min(boundingBox.minY, y)
: y;
boundingBox.maxY =
boundingBox.maxY !== undefined
? Math.max(boundingBox.maxY, y)
: y;
}
};
var recordZ = function(z) {
var recordZ = function (z) {
if (z === undefined || isNaN(z)) return;
max.z = max.z !== undefined ? Math.max(max.z, z) : z;
@@ -210,20 +243,27 @@ var analyzeModel = function () {
if (!totalFilament[tool]) totalFilament[tool] = 0;
if (!filamentByLayer[cmds[j].prevZ]) filamentByLayer[cmds[j].prevZ] = [0];
if (!filamentByLayer[cmds[j].prevZ][tool]) filamentByLayer[cmds[j].prevZ][tool] = 0;
if (!filamentByLayer[cmds[j].prevZ][tool])
filamentByLayer[cmds[j].prevZ][tool] = 0;
if (cmds[j].extrusion) {
totalFilament[tool] += cmds[j].extrusion;
filamentByLayer[cmds[j].prevZ][tool] += cmds[j].extrusion;
}
if (cmds[j].x !== undefined && !isNaN(cmds[j].x)
&& cmds[j].y !== undefined && !isNaN(cmds[j].y)) {
if (
cmds[j].x !== undefined &&
!isNaN(cmds[j].x) &&
cmds[j].y !== undefined &&
!isNaN(cmds[j].y)
) {
var diffX = cmds[j].x - cmds[j].prevX;
var diffY = cmds[j].y - cmds[j].prevY;
if (move) {
printTimeAdd = Math.sqrt(diffX * diffX + diffY * diffY) / (cmds[j].speed / 60);
printTimeAdd =
Math.sqrt(diffX * diffX + diffY * diffY) / (cmds[j].speed / 60);
} else if (extrude) {
tmp1 = Math.sqrt(diffX * diffX + diffY * diffY) / (cmds[j].speed / 60);
tmp1 =
Math.sqrt(diffX * diffX + diffY * diffY) / (cmds[j].speed / 60);
tmp2 = Math.abs(cmds[j].extrusion / (cmds[j].speed / 60));
printTimeAdd = Math.max(tmp1, tmp2);
} else if (retract) {
@@ -240,14 +280,14 @@ var analyzeModel = function () {
printTimeByLayer[cmds[j].prevZ] += printTimeAdd;
if (cmds[j].extrude && cmds[j].retract === 0) {
type = 'extrude';
type = "extrude";
} else if (cmds[j].retract !== 0) {
type = 'retract';
type = "retract";
} else if (!cmds[j].extrude && cmds[j].retract === 0) {
type = 'move';
type = "move";
} else {
self.postMessage({cmd: 'unknown type of move'});
type = 'unknown';
self.postMessage({cmd: "unknown type of move"});
type = "unknown";
}
speedIndex = speeds[type].indexOf(cmds[j].speed);
@@ -255,16 +295,14 @@ var analyzeModel = function () {
speeds[type].push(cmds[j].speed);
speedIndex = speeds[type].indexOf(cmds[j].speed);
}
if (typeof(speedsByLayer[type][cmds[j].prevZ]) === 'undefined') {
if (typeof speedsByLayer[type][cmds[j].prevZ] === "undefined") {
speedsByLayer[type][cmds[j].prevZ] = [];
}
if (speedsByLayer[type][cmds[j].prevZ].indexOf(cmds[j].speed) === -1) {
speedsByLayer[type][cmds[j].prevZ][speedIndex] = cmds[j].speed;
}
}
sendSizeProgress(i / model.length * 100);
sendSizeProgress((i / model.length) * 100);
}
purgeLayers();
@@ -285,11 +323,18 @@ var doParse = function () {
var lastSend = 0;
var layer = 0;
var x, y, z = 0;
var x,
y,
z = 0;
var center_i, center_j, direction;
var prevX = 0, prevY = 0, prevZ = 0;
var f, lastF = 4000;
var extrude = false, relativeE = false, retract = 0;
var prevX = 0,
prevY = 0,
prevZ = 0;
var f,
lastF = 4000;
var extrude = false,
relativeE = false,
retract = 0;
var relativeMode = false;
var zLift = false;
var zLiftZ = undefined;
@@ -339,8 +384,8 @@ var doParse = function () {
args = line.split(/\s/);
for (j = 0; j < args.length; j++) {
switch (argChar = args[j].charAt(0).toLowerCase()) {
case 'x':
switch ((argChar = args[j].charAt(0).toLowerCase())) {
case "x":
if (relativeMode) {
x = prevX + Number(args[j].slice(1)) + activeToolOffset.x;
} else {
@@ -349,7 +394,7 @@ var doParse = function () {
break;
case 'y':
case "y":
if (relativeMode) {
y = prevY + Number(args[j].slice(1)) + activeToolOffset.y;
} else {
@@ -358,7 +403,7 @@ var doParse = function () {
break;
case 'z':
case "z":
if (relativeMode) {
z = prevZ + Number(args[j].slice(1));
} else {
@@ -367,10 +412,10 @@ var doParse = function () {
break;
case 'e':
case 'a':
case 'b':
case 'c':
case "e":
case "a":
case "b":
case "c":
assumeNonDC = true;
numSlice = Number(args[j].slice(1));
@@ -379,7 +424,8 @@ var doParse = function () {
prev_extrude[tool][argChar] += numSlice;
} else {
// absolute extrusion positioning
prev_extrude[tool]["abs"] = numSlice - prev_extrude[tool][argChar];
prev_extrude[tool]["abs"] =
numSlice - prev_extrude[tool][argChar];
prev_extrude[tool][argChar] = numSlice;
}
@@ -389,7 +435,10 @@ var doParse = function () {
retract = -1;
} else if (prev_extrude[tool]["abs"] === 0) {
retract = 0;
} else if (prev_extrude[tool]["abs"] > 0 && prev_retract[tool] < 0) {
} else if (
prev_extrude[tool]["abs"] > 0 &&
prev_retract[tool] < 0
) {
prev_retract[tool] = 0;
retract = 1;
} else {
@@ -398,31 +447,36 @@ var doParse = function () {
break;
case 'f':
case "f":
numSlice = parseFloat(args[j].slice(1));
lastF = numSlice;
break;
case 'i':
case "i":
center_i = Number(args[j].slice(1));
break;
case 'j':
case "j":
center_j = Number(args[j].slice(1));
break;
case 'g':
if(args[j].charAt(1).toLowerCase() === '2')
direction=-1;
if(args[j].charAt(1).toLowerCase() === '3')
direction=1;
case "g":
if (args[j].charAt(1).toLowerCase() === "2") direction = -1;
if (args[j].charAt(1).toLowerCase() === "3") direction = 1;
break;
}
}
if (dcExtrude && !assumeNonDC) {
extrude = true;
prev_extrude[tool]["abs"] = Math.sqrt((prevX - x) * (prevX - x) + (prevY - y) * (prevY - y));
prev_extrude[tool]["abs"] = Math.sqrt(
(prevX - x) * (prevX - x) + (prevY - y) * (prevY - y)
);
}
if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined' || retract !== 0) {
if (
typeof x !== "undefined" ||
typeof y !== "undefined" ||
typeof z !== "undefined" ||
retract !== 0
) {
addToModel = true;
move = true;
}
@@ -460,24 +514,24 @@ var doParse = function () {
prev_extrude[tool]["b"] = 0;
prev_extrude[tool]["c"] = 0;
} else {
switch (argChar = args[j].charAt(0).toLowerCase()) {
case 'x':
switch ((argChar = args[j].charAt(0).toLowerCase())) {
case "x":
x = Number(args[j].slice(1)) + activeToolOffset.x;
break;
case 'y':
case "y":
y = Number(args[j].slice(1)) + activeToolOffset.y;
break;
case 'z':
case "z":
z = Number(args[j].slice(1));
prevZ = z;
break;
case 'e':
case 'a':
case 'b':
case 'c':
case "e":
case "a":
case "b":
case "c":
numSlice = Number(args[j].slice(1));
if (relativeMode || relativeE) {
prev_extrude[tool][argChar] = numSlice;
@@ -489,11 +543,14 @@ var doParse = function () {
}
}
if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined') {
if (
typeof x !== "undefined" ||
typeof y !== "undefined" ||
typeof z !== "undefined"
) {
addToModel = true;
move = false;
}
} else if (/^(?:G28)(\.\d+)?/i.test(line)) {
args = line.split(/\s/);
@@ -504,14 +561,14 @@ var doParse = function () {
z = 0;
} else {
for (j = 0; j < args.length; j++) {
switch (argChar = args[j].charAt(0).toLowerCase()) {
case 'x':
switch ((argChar = args[j].charAt(0).toLowerCase())) {
case "x":
x = 0;
break;
case 'y':
case "y":
y = 0;
break;
case 'z':
case "z":
z = 0;
break;
default:
@@ -521,17 +578,23 @@ var doParse = function () {
}
// if it's the first layer and G28 was without z
if (layer === 0 && typeof(z) === 'undefined') {
if (layer === 0 && typeof z === "undefined") {
z = 0;
}
if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined' || retract !== 0) {
if (
typeof x !== "undefined" ||
typeof y !== "undefined" ||
typeof z !== "undefined" ||
retract !== 0
) {
addToModel = true;
move = true;
}
} else if (/^(?:T\d+)/i.test(line)) {
tool = Number(line.split(/\s/)[0].slice(1));
if (!prev_extrude[tool]) prev_extrude[tool] = {a: 0, b: 0, c: 0, e: 0, abs: 0};
if (!prev_extrude[tool])
prev_extrude[tool] = {a: 0, b: 0, c: 0, e: 0, abs: 0};
if (!prev_retract[tool]) prev_retract[tool] = 0;
activeToolOffset = toolOffsets[tool];
@@ -540,7 +603,7 @@ var doParse = function () {
// If move is on a new height and it's not extruding and
// it's not currently already in a Z-lift, assume it's possibly a Z-lift
if (typeof(z) !== 'undefined' && z !== prevZ && !extrude && !zLift) {
if (typeof z !== "undefined" && z !== prevZ && !extrude && !zLift) {
zLift = true;
zLiftZ = prevZ;
}
@@ -549,7 +612,7 @@ var doParse = function () {
zLift = false;
}
if (typeof(z) !== 'undefined' && z !== prevZ) {
if (typeof z !== "undefined" && z !== prevZ) {
if (z_heights[z] !== undefined) {
layer = z_heights[z];
} else {
@@ -560,7 +623,7 @@ var doParse = function () {
sendLayer = layer;
sendLayerZ = z;
prevZ = z;
} else if (typeof(z) === 'undefined' && typeof(prevZ) !== 'undefined') {
} else if (typeof z === "undefined" && typeof prevZ !== "undefined") {
if (z_heights.hasOwnProperty(prevZ)) {
layer = z_heights[prevZ];
} else {
@@ -581,7 +644,10 @@ var doParse = function () {
extrude: extrude,
retract: retract,
noMove: !move,
extrusion: (extrude || retract) && prev_extrude[tool]["abs"] ? prev_extrude[tool]["abs"] : 0,
extrusion:
(extrude || retract) && prev_extrude[tool]["abs"]
? prev_extrude[tool]["abs"]
: 0,
prevX: prevX,
prevY: prevY,
prevZ: prevZ,
@@ -601,7 +667,10 @@ var doParse = function () {
// there's something to be checked in the Z-lift cache
if (prevZ === zLiftZ) {
zLiftMoves.forEach(function (zLiftMove) {
model[zLiftMove.layer].splice(model[layer].indexOf(zLiftMove.command), 1);
model[zLiftMove.layer].splice(
model[layer].indexOf(zLiftMove.command),
1
);
model[z_heights[zLiftZ]].push(zLiftMove.command);
});
}
@@ -610,19 +679,22 @@ var doParse = function () {
zLiftZ = undefined;
}
model[layer].push(command);
}
if (move) {
if (typeof(x) !== 'undefined') prevX = x;
if (typeof(y) !== 'undefined') prevY = y;
if (typeof x !== "undefined") prevX = x;
if (typeof y !== "undefined") prevY = y;
}
if (typeof(sendLayer) !== "undefined") {
if (typeof sendLayer !== "undefined") {
if (i - lastSend > gcode.length * 0.02 && sendMultiLayer.length !== 0) {
lastSend = i;
sendMultiLayerToParent(sendMultiLayer, sendMultiLayerZ, i / gcode.length * 100);
sendMultiLayerToParent(
sendMultiLayer,
sendMultiLayerZ,
(i / gcode.length) * 100
);
sendMultiLayer = [];
sendMultiLayerZ = [];
}
@@ -632,10 +704,9 @@ var doParse = function () {
sendLayerZ = undefined;
}
}
sendMultiLayerToParent(sendMultiLayer, sendMultiLayerZ, i / gcode.length * 100);
sendMultiLayerToParent(sendMultiLayer, sendMultiLayerZ, (i / gcode.length) * 100);
};
var parseGCode = function (message) {
gcode = message.gcode;
firstReport = message.options.firstReport;
@@ -648,8 +719,8 @@ var parseGCode = function (message) {
doParse();
gcode = [];
self.postMessage({
"cmd": "returnModel",
"msg": {}
cmd: "returnModel",
msg: {}
});
};
@@ -664,7 +735,14 @@ var runAnalyze = function (message) {
max = {x: undefined, y: undefined, z: undefined};
min = {x: undefined, y: undefined, z: undefined};
modelSize = {x: undefined, y: undefined, z: undefined};
boundingBox = {minX: undefined, maxX: undefined, minY: undefined, maxY: undefined, minZ: undefined, maxZ: undefined};
boundingBox = {
minX: undefined,
maxX: undefined,
minY: undefined,
maxY: undefined,
minZ: undefined,
maxZ: undefined
};
filamentByLayer = {};
totalFilament = 0;
printTime = 0;
@@ -686,18 +764,17 @@ onmessage = function (e) {
var data = e.data;
// for some reason firefox doesn't garbage collect when something inside closures is deleted, so we delete and recreate whole object eaech time
switch (data.cmd) {
case 'parseGCode':
case "parseGCode":
parseGCode(data.msg);
break;
case 'setOption':
case "setOption":
setOption(data.msg);
break;
case 'analyzeModel':
case "analyzeModel":
runAnalyze(data.msg);
break;
default:
self.postMessage('Unknown command: ' + data.msg);
self.postMessage("Unknown command: " + data.msg);
}
};
@@ -6,15 +6,16 @@
.bar {
-webkit-transition: width 0s linear;
-moz-transition: width 0s linear;
-o-transition: width 0s linear;
transition: width 0s linear;
-moz-transition: width 0s linear;
-o-transition: width 0s linear;
transition: width 0s linear;
}
}
.canvas_container {
position: relative;
&:hover, &:active {
&:hover,
&:active {
outline: 0;
}
}
+228 -187
View File
@@ -1,243 +1,284 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import octoprint.plugin
from octoprint.settings import settings
from octoprint.server import NO_CONTENT
from octoprint.server.util.flask import redirect_to_tornado, no_firstrun_access
from octoprint.access import ADMIN_GROUP
from octoprint.access.permissions import Permissions
from flask import request, jsonify, url_for, make_response
from flask_babel import gettext
from werkzeug.utils import secure_filename
from werkzeug.exceptions import BadRequest
import yaml
import io
import os
import yaml
from flask import jsonify, make_response, request, url_for
from flask_babel import gettext
from werkzeug.exceptions import BadRequest
from werkzeug.utils import secure_filename
import octoprint.plugin
from octoprint.access import ADMIN_GROUP
from octoprint.access.permissions import Permissions
from octoprint.server import NO_CONTENT
from octoprint.server.util.flask import no_firstrun_access, redirect_to_tornado
from octoprint.settings import settings
try:
from os import scandir
from os import scandir
except ImportError:
from scandir import scandir
from scandir import scandir
class LoggingPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.BlueprintPlugin):
# Additional permissions hook
class LoggingPlugin(
octoprint.plugin.AssetPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.BlueprintPlugin,
):
def get_additional_permissions(self):
return [
{"key": "MANAGE",
"name": "Logging management",
"description": gettext("Allows to download and delete log files and list and set log levels."),
"default_groups": [ADMIN_GROUP],
"roles": ["manage"]}
]
# Additional permissions hook
@octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def get_all(self):
files = self._getLogFiles()
free, total = self._get_usage()
loggers = self._get_available_loggers()
levels = self._get_logging_levels()
serial_log_enabled = self._settings.global_get_boolean(["serial", "log"])
plugintimings_log_enabled = self._settings.global_get_boolean(["devel", "pluginTimings"])
return jsonify(logs={"files": files, "free": free, "total": total},
setup={"loggers": loggers, "levels": levels},
serial_log={"enabled": serial_log_enabled},
plugintimings_log={"enabled": plugintimings_log_enabled})
def get_additional_permissions(self):
return [
{
"key": "MANAGE",
"name": "Logging management",
"description": gettext(
"Allows to download and delete log files and list and set log levels."
),
"default_groups": [ADMIN_GROUP],
"roles": ["manage"],
}
]
@octoprint.plugin.BlueprintPlugin.route("/logs", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def get_log_files(self):
files = self._getLogFiles()
free, total = self._get_usage()
return jsonify(files=files, free=free, total=total)
@octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def get_all(self):
files = self._getLogFiles()
free, total = self._get_usage()
loggers = self._get_available_loggers()
levels = self._get_logging_levels()
serial_log_enabled = self._settings.global_get_boolean(["serial", "log"])
plugintimings_log_enabled = self._settings.global_get_boolean(
["devel", "pluginTimings"]
)
return jsonify(
logs={"files": files, "free": free, "total": total},
setup={"loggers": loggers, "levels": levels},
serial_log={"enabled": serial_log_enabled},
plugintimings_log={"enabled": plugintimings_log_enabled},
)
@octoprint.plugin.BlueprintPlugin.route("/logs/<path:filename>", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def download_log(self, filename):
return redirect_to_tornado(request, url_for("index") + "downloads/logs/" + filename)
@octoprint.plugin.BlueprintPlugin.route("/logs", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def get_log_files(self):
files = self._getLogFiles()
free, total = self._get_usage()
return jsonify(files=files, free=free, total=total)
@octoprint.plugin.BlueprintPlugin.route("/logs/<path:filename>", methods=["DELETE"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def delete_log(self, filename):
secure = os.path.join(settings().getBaseFolder("logs"), secure_filename(filename))
if not os.path.exists(secure):
return make_response("File not found: %s" % filename, 404)
@octoprint.plugin.BlueprintPlugin.route("/logs/<path:filename>", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def download_log(self, filename):
return redirect_to_tornado(
request, url_for("index") + "downloads/logs/" + filename
)
os.remove(secure)
@octoprint.plugin.BlueprintPlugin.route("/logs/<path:filename>", methods=["DELETE"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def delete_log(self, filename):
secure = os.path.join(settings().getBaseFolder("logs"), secure_filename(filename))
if not os.path.exists(secure):
return make_response("File not found: %s" % filename, 404)
return NO_CONTENT
os.remove(secure)
@octoprint.plugin.BlueprintPlugin.route("/setup", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def get_logging_setup(self):
loggers = self._get_available_loggers()
levels = self._get_logging_levels()
return jsonify(loggers=loggers, levels=levels)
return NO_CONTENT
@octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def get_logging_levels_api(self):
return jsonify(self._get_logging_levels())
@octoprint.plugin.BlueprintPlugin.route("/setup", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def get_logging_setup(self):
loggers = self._get_available_loggers()
levels = self._get_logging_levels()
return jsonify(loggers=loggers, levels=levels)
@octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["PUT"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def set_logging_levels_api(self):
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
@octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def get_logging_levels_api(self):
return jsonify(self._get_logging_levels())
try:
json_data = request.json
except BadRequest:
return make_response("Malformed JSON body in request", 400)
@octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["PUT"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def set_logging_levels_api(self):
if "application/json" not in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
if not isinstance(json_data, dict):
return make_response("Invalid log level configuration", 400)
try:
json_data = request.json
except BadRequest:
return make_response("Malformed JSON body in request", 400)
# TODO validate further
if not isinstance(json_data, dict):
return make_response("Invalid log level configuration", 400)
self._set_logging_levels(json_data)
return self.get_logging_levels_api()
# TODO validate further
def is_blueprint_protected(self):
return False
self._set_logging_levels(json_data)
return self.get_logging_levels_api()
def _get_usage(self):
import psutil
usage = psutil.disk_usage(settings().getBaseFolder("logs", check_writable=False))
return usage.free, usage.total
def is_blueprint_protected(self):
return False
def _getLogFiles(self):
files = []
basedir = settings().getBaseFolder("logs", check_writable=False)
for entry in scandir(basedir):
files.append({
"name": entry.name,
"date": int(entry.stat().st_mtime),
"size": entry.stat().st_size,
"refs": {
"resource": url_for(".download_log", filename=entry.name, _external=True),
"download": url_for("index", _external=True) + "downloads/logs/" + entry.name
}
})
def _get_usage(self):
import psutil
return files
usage = psutil.disk_usage(settings().getBaseFolder("logs", check_writable=False))
return usage.free, usage.total
def _get_available_loggers(self):
return list(filter(lambda x: self._is_managed_logger(x), self._logger.manager.loggerDict.keys()))
def _getLogFiles(self):
files = []
basedir = settings().getBaseFolder("logs", check_writable=False)
for entry in scandir(basedir):
files.append(
{
"name": entry.name,
"date": int(entry.stat().st_mtime),
"size": entry.stat().st_size,
"refs": {
"resource": url_for(
".download_log", filename=entry.name, _external=True
),
"download": url_for("index", _external=True)
+ "downloads/logs/"
+ entry.name,
},
}
)
def _get_logging_file(self):
# TODO this might not be the logging config we are actually using here (command line parameter...)
return os.path.join(self._settings.getBaseFolder("base"), "logging.yaml")
return files
def _get_logging_config(self):
logging_file = self._get_logging_file()
def _get_available_loggers(self):
return list(
filter(
lambda x: self._is_managed_logger(x),
self._logger.manager.loggerDict.keys(),
)
)
config_from_file = {}
if os.path.exists(logging_file) and os.path.isfile(logging_file):
import yaml
with io.open(logging_file, 'rt', encoding='utf-8') as f:
config_from_file = yaml.safe_load(f)
return config_from_file
def _get_logging_file(self):
# TODO this might not be the logging config we are actually using here (command line parameter...)
return os.path.join(self._settings.getBaseFolder("base"), "logging.yaml")
def _get_logging_levels(self):
config = self._get_logging_config()
if config is None or not isinstance(config, dict):
return {}
def _get_logging_config(self):
logging_file = self._get_logging_file()
return dict((key, value.get("level"))
for key, value in config.get("loggers", {}).items()
if isinstance(value, dict) and "level" in value)
config_from_file = {}
if os.path.exists(logging_file) and os.path.isfile(logging_file):
import yaml
def _set_logging_levels(self, new_levels):
import logging
with io.open(logging_file, "rt", encoding="utf-8") as f:
config_from_file = yaml.safe_load(f)
return config_from_file
config = self._get_logging_config()
def _get_logging_levels(self):
config = self._get_logging_config()
if config is None or not isinstance(config, dict):
return {}
# clear all configured logging levels
if "loggers" in config:
purge = []
for component, data in config["loggers"].items():
if not self._is_managed_logger(component): continue
try:
del data["level"]
self._logger.manager.loggerDict[component].setLevel(logging.INFO)
except KeyError:
pass
if len(data) == 0:
purge.append(component)
for component in purge:
del config["loggers"][component]
else:
config["loggers"] = {}
return dict(
(key, value.get("level"))
for key, value in config.get("loggers", {}).items()
if isinstance(value, dict) and "level" in value
)
# update all logging levels
for logger, level in new_levels.items():
if logger not in config["loggers"]:
config["loggers"][logger] = {}
config["loggers"][logger]["level"] = level
def _set_logging_levels(self, new_levels):
import logging
# delete empty entries
config["loggers"] = {k: v for k, v in config["loggers"].items() if len(v)}
config = self._get_logging_config()
# save
with octoprint.util.atomic_write(self._get_logging_file(), mode='wt', max_permissions=0o666) as f:
yaml.safe_dump(config, f, default_flow_style=False, indent=2, allow_unicode=True)
# clear all configured logging levels
if "loggers" in config:
purge = []
for component, data in config["loggers"].items():
if not self._is_managed_logger(component):
continue
try:
del data["level"]
self._logger.manager.loggerDict[component].setLevel(logging.INFO)
except KeyError:
pass
if len(data) == 0:
purge.append(component)
for component in purge:
del config["loggers"][component]
else:
config["loggers"] = {}
# set runtime logging levels now
for logger, level in new_levels.items():
level = logging.getLevelName(level)
# update all logging levels
for logger, level in new_levels.items():
if logger not in config["loggers"]:
config["loggers"][logger] = {}
config["loggers"][logger]["level"] = level
self._logger.info("Setting logger {} level to {}".format(logger, level))
self._logger.manager.loggerDict[logger].setLevel(level)
# delete empty entries
config["loggers"] = {k: v for k, v in config["loggers"].items() if len(v)}
def _is_managed_logger(self, logger):
return logger and (logger.startswith("octoprint") or logger.startswith("tornado"))
# save
with octoprint.util.atomic_write(
self._get_logging_file(), mode="wt", max_permissions=0o666
) as f:
yaml.safe_dump(
config, f, default_flow_style=False, indent=2, allow_unicode=True
)
def get_template_configs(self):
return [{"type": "navbar",
"template": "logging_navbar_seriallog.jinja2",
"suffix": "_seriallog"},
{"type": "navbar",
"template": "logging_navbar_plugintimingslog.jinja2",
"suffix": "_plugintimingslog"},
{"type": "settings",
"custom_bindings": True}]
# set runtime logging levels now
for logger, level in new_levels.items():
level = logging.getLevelName(level)
self._logger.info("Setting logger {} level to {}".format(logger, level))
self._logger.manager.loggerDict[logger].setLevel(level)
def _is_managed_logger(self, logger):
return logger and (logger.startswith("octoprint") or logger.startswith("tornado"))
def get_template_configs(self):
return [
{
"type": "navbar",
"template": "logging_navbar_seriallog.jinja2",
"suffix": "_seriallog",
},
{
"type": "navbar",
"template": "logging_navbar_plugintimingslog.jinja2",
"suffix": "_plugintimingslog",
},
{"type": "settings", "custom_bindings": True},
]
def get_assets(self):
return {
"js": ["js/logging.js"],
"clientjs": ["clientjs/logging.js"],
"less": ["less/logging.less"],
"css": ["css/logging.css"],
}
def get_assets(self):
return {"js": ["js/logging.js"],
"clientjs": ["clientjs/logging.js"],
"less": ["less/logging.less"],
"css": ["css/logging.css"]}
__plugin_name__ = "Logging"
__plugin_author__ = "Shawn Bruce, based on work by Gina Häußge and Marc Hannappel"
__plugin_description__ = "Provides access to OctoPrint's logs and logging configuration."
__plugin_disabling_discouraged__ = gettext("Without this plugin you will no longer be able to retrieve "
"OctoPrint's logs or modify the current logging levels through "
"the web interface.")
__plugin_disabling_discouraged__ = gettext(
"Without this plugin you will no longer be able to retrieve "
"OctoPrint's logs or modify the current logging levels through "
"the web interface."
)
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = LoggingPlugin()
__plugin_hooks__ = {
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
}
@@ -4,9 +4,8 @@
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var OctoPrintLoggingClient = function(base) {
})(this, function (OctoPrintClient) {
var OctoPrintLoggingClient = function (base) {
this.base = base;
this.baseUrl = this.base.getBlueprintUrl("logging");
@@ -14,47 +13,53 @@
this.setupUrl = this.baseUrl + "setup";
};
OctoPrintLoggingClient.prototype.get = function(opts) {
OctoPrintLoggingClient.prototype.get = function (opts) {
return this.base.get(this.baseUrl, opts);
};
OctoPrintLoggingClient.prototype.listLogs = function(opts) {
OctoPrintLoggingClient.prototype.listLogs = function (opts) {
return this.base.get(this.logsUrl, opts);
};
OctoPrintLoggingClient.prototype.deleteLog = function(file, opts) {
OctoPrintLoggingClient.prototype.deleteLog = function (file, opts) {
var fileUrl = this.logsUrl + "/" + file;
return this.base.delete(fileUrl, opts);
};
OctoPrintLoggingClient.prototype.downloadLog = function(file, opts) {
OctoPrintLoggingClient.prototype.downloadLog = function (file, opts) {
var fileUrl = this.logsUrl + "/" + file;
return this.base.download(fileUrl, opts);
};
OctoPrintLoggingClient.prototype.updateLevels = function(config, opts) {
OctoPrintLoggingClient.prototype.updateLevels = function (config, opts) {
return this.base.putJson(this.setupUrl + "/levels", config, opts);
};
//~~ wrapper for backwards compatibility
var DeprecatedOctoPrintLogsClient = function(base) {
var DeprecatedOctoPrintLogsClient = function (base) {
this.base = base;
this.wrapped = this.base.plugins.logging;
};
DeprecatedOctoPrintLogsClient.prototype.list = function(opts) {
log.warn("OctoPrintClient.logs.list has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.listLogs instead");
DeprecatedOctoPrintLogsClient.prototype.list = function (opts) {
log.warn(
"OctoPrintClient.logs.list has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.listLogs instead"
);
return this.wrapped.listLogs(opts);
};
DeprecatedOctoPrintLogsClient.prototype.delete = function(file, opts) {
log.warn("OctoPrintClient.logs.delete has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.deleteLog instead");
DeprecatedOctoPrintLogsClient.prototype.delete = function (file, opts) {
log.warn(
"OctoPrintClient.logs.delete has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.deleteLog instead"
);
return this.wrapped.deleteLog(file, opts);
};
DeprecatedOctoPrintLogsClient.prototype.download = function(file, opts) {
log.warn("OctoPrintClient.logs.download has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.downloadLog instead");
DeprecatedOctoPrintLogsClient.prototype.download = function (file, opts) {
log.warn(
"OctoPrintClient.logs.download has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.downloadLog instead"
);
return this.wrapped.downloadLog(file, opts);
};
@@ -1,4 +1,4 @@
$(function() {
$(function () {
function LoggingViewModel(parameters) {
var self = this;
@@ -17,11 +17,11 @@ $(function() {
self.markedForDeletion = ko.observableArray([]);
self.availableLoggersSorted = ko.computed(function() {
self.availableLoggersSorted = ko.computed(function () {
return _.sortBy(self.availableLoggers());
});
self.configuredLoggersSorted = ko.computed(function() {
self.configuredLoggersSorted = ko.computed(function () {
return _.sortBy(self.configuredLoggers(), function (o) {
o.level();
return o.component;
@@ -32,54 +32,57 @@ $(function() {
self.listHelper = new ItemListHelper(
"logFiles",
{
"name": function(a, b) {
name: function (a, b) {
// sorts ascending
if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1;
if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1;
if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase())
return -1;
if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase())
return 1;
return 0;
},
"modification": function(a, b) {
modification: function (a, b) {
// sorts descending
if (a["date"] > b["date"]) return -1;
if (a["date"] < b["date"]) return 1;
return 0;
},
"size": function(a, b) {
size: function (a, b) {
// sorts descending
if (a["size"] > b["size"]) return -1;
if (a["size"] < b["size"]) return 1;
return 0;
}
},
{
},
{},
"name",
[],
[],
CONFIG_LOGFILESPERPAGE
);
self.requestData = function() {
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)) {
self.requestData = function () {
if (
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_LOGGING_MANAGE
)
) {
return;
}
OctoPrint.plugins.logging.get()
.done(self.fromResponse);
OctoPrint.plugins.logging.get().done(self.fromResponse);
};
self.fromResponse = function(response) {
self.fromResponse = function (response) {
self.fromLogsResponse(response.logs);
self.fromSetupResponse(response.setup);
self.fromSerialLogResponse(response.serial_log);
self.fromPluginTimingsLogResponse(response.plugintimings_log);
};
self.fromLogsResponse = function(response) {
self.fromLogsResponse = function (response) {
if (!response) return;
var files = response.files;
if (files === undefined)
return;
if (files === undefined) return;
self.listHelper.updateItems(files);
@@ -87,15 +90,15 @@ $(function() {
self.totalSpace(response.total);
};
self.fromSetupResponse = function(response) {
self.fromSetupResponse = function (response) {
if (!response) return;
// levels
var levels = [];
var configuredLoggers = [];
_.each(response.levels, function(level, logger) {
_.each(response.levels, function (level, logger) {
var item = {component: logger, level: ko.observable(level)};
item.level.subscribe(function() {
item.level.subscribe(function () {
self.configuredLoggersHasChanged();
});
levels.push(item);
@@ -108,69 +111,92 @@ $(function() {
self.availableLoggers(availableLoggers);
};
self.fromSerialLogResponse = function(response) {
self.fromSerialLogResponse = function (response) {
if (!response) return;
self.serialLogEnabled(response.enabled);
};
self.fromPluginTimingsLogResponse = function(response) {
self.fromPluginTimingsLogResponse = function (response) {
if (!response) return;
self.pluginTimingsLogEnabled(response.enabled);
};
self.serialLogPopoverContent = function() {
self.serialLogPopoverContent = function () {
return self.popoverContent("serial.log");
};
self.pluginTimingsLogPopoverContent = function() {
self.pluginTimingsLogPopoverContent = function () {
return self.popoverContent("plugintimings.log");
};
self.popoverContent = function(logfile) {
self.popoverContent = function (logfile) {
var free = self.freeSpace();
var total = self.totalSpace();
var content = "<p>"
+ _.sprintf(gettext("You currently have <code>%(logfile)s</code> enabled. Please remember to turn it off " +
"again once your are done debugging whatever issue prompted you to turn it on."), {logfile: logfile})
+ "</p><p>"
+ gettext("It can negatively impact print performance and also take up a lot of storage space " +
"depending on how long you keep it enabled and thus should only be used for " +
"debugging.")
+ "</p>";
var content =
"<p>" +
_.sprintf(
gettext(
"You currently have <code>%(logfile)s</code> enabled. Please remember to turn it off " +
"again once your are done debugging whatever issue prompted you to turn it on."
),
{logfile: logfile}
) +
"</p><p>" +
gettext(
"It can negatively impact print performance and also take up a lot of storage space " +
"depending on how long you keep it enabled and thus should only be used for " +
"debugging."
) +
"</p>";
if (free !== undefined && total !== undefined) {
content += "<p class='muted'><small><strong>" + gettext("Log storage:") + "</strong> "
+ formatSize(free) + " / "
+ formatSize(total)
+ "</small></p>";
content +=
"<p class='muted'><small><strong>" +
gettext("Log storage:") +
"</strong> " +
formatSize(free) +
" / " +
formatSize(total) +
"</small></p>";
}
return content;
}
};
self.configuredLoggersHasChanged = function () {
self.configuredLoggersChanged = true;
};
self.addLogger = function() {
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)) {
self.addLogger = function () {
if (
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_LOGGING_MANAGE
)
) {
return;
}
var component = self.availableLoggersName();
var level = self.availableLoggersLevel();
self.configuredLoggers.push({component: component, level: ko.observable(level)});
self.configuredLoggers.push({
component: component,
level: ko.observable(level)
});
self.availableLoggers.remove(component);
self.configuredLoggersHasChanged();
};
self.removeLogger = function(logger) {
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)) {
self.removeLogger = function (logger) {
if (
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_LOGGING_MANAGE
)
) {
return;
}
@@ -180,64 +206,96 @@ $(function() {
self.configuredLoggersHasChanged();
};
self.removeFile = function(filename) {
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)) {
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);
var perform = function () {
OctoPrint.plugins.logging.deleteLog(filename).done(self.requestData);
};
showConfirmationDialog(_.sprintf(gettext("You are about to delete log file \"%(name)s\"."), {name: _.escape(filename)}),
perform);
showConfirmationDialog(
_.sprintf(gettext('You are about to delete log file "%(name)s".'), {
name: _.escape(filename)
}),
perform
);
};
self.markFilesOnPage = function() {
self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(self.listHelper.paginatedItems(), "name"))));
self.markFilesOnPage = function () {
self.markedForDeletion(
_.uniq(
self
.markedForDeletion()
.concat(_.map(self.listHelper.paginatedItems(), "name"))
)
);
};
self.markAllFiles = function() {
self.markAllFiles = function () {
self.markedForDeletion(_.map(self.listHelper.allItems, "name"));
};
self.clearMarkedFiles = function() {
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)) {
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)) {
self.removeMarkedFiles = function () {
if (
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_LOGGING_MANAGE
)
) {
return;
}
var perform = function() {
self._bulkRemove(self.markedForDeletion(), "files")
.done(function() {
self.markedForDeletion.removeAll();
});
var perform = function () {
self._bulkRemove(self.markedForDeletion(), "files").done(function () {
self.markedForDeletion.removeAll();
});
};
showConfirmationDialog(_.sprintf(gettext("You are about to delete %(count)d log files."), {count: self.markedForDeletion().length}),
perform);
showConfirmationDialog(
_.sprintf(gettext("You are about to delete %(count)d log files."), {
count: self.markedForDeletion().length
}),
perform
);
};
self.onServerReconnect = self.onUserLoggedIn = self.onEventSettingsUpdated = function() {
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)) {
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)) {
if (
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_LOGGING_MANAGE
)
) {
return;
}
if ( self.configuredLoggersChanged ) {
if (self.configuredLoggersChanged) {
console.log("ConfiguredLoggers has changed. Saving!");
var levels = {};
_.each(self.configuredLoggers(), function(data) {
_.each(self.configuredLoggers(), function (data) {
levels[data.component] = data.level();
});
OctoPrint.plugins.logging.updateLevels(levels);
@@ -246,20 +304,41 @@ $(function() {
}
};
self._bulkRemove = function(files) {
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)) {
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) {
return OctoPrint.plugins.logging.deleteLog(filename)
.done(function() {
deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: _.escape(filename)}), true);
var message = _.sprintf(gettext("Deleting %(count)d log files..."), {
count: files.length
});
var handler = function (filename) {
return OctoPrint.plugins.logging
.deleteLog(filename)
.done(function () {
deferred.notify(
_.sprintf(gettext("Deleted %(filename)s..."), {
filename: _.escape(filename)
}),
true
);
})
.fail(function(jqXHR) {
var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: _.escape(filename)});
var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: _.escape(filename), error: _.escape(jqXHR.responseText)});
.fail(function (jqXHR) {
var short = _.sprintf(
gettext("Deletion of %(filename)s failed, continuing..."),
{filename: _.escape(filename)}
);
var long = _.sprintf(
gettext("Deletion of %(filename)s failed: %(error)s"),
{
filename: _.escape(filename),
error: _.escape(jqXHR.responseText)
}
);
deferred.notify(short, long, false);
});
};
@@ -277,15 +356,14 @@ $(function() {
showProgressModal(options, promise);
var requests = [];
_.each(files, function(filename) {
_.each(files, function (filename) {
var request = handler(filename);
requests.push(request)
requests.push(request);
});
$.when.apply($, _.map(requests, wrapPromiseWithAlways)).done(function () {
deferred.resolve();
self.requestData();
});
$.when.apply($, _.map(requests, wrapPromiseWithAlways))
.done(function() {
deferred.resolve();
self.requestData();
});
return promise;
};
@@ -295,6 +373,10 @@ $(function() {
construct: LoggingViewModel,
additionalNames: ["logsViewModel"],
dependencies: ["loginStateViewModel", "accessViewModel"],
elements: ["#settings_plugin_logging", "#navbar_plugin_logging_seriallog", "#navbar_plugin_logging_plugintimingslog"]
elements: [
"#settings_plugin_logging",
"#navbar_plugin_logging_seriallog",
"#navbar_plugin_logging_plugintimingslog"
]
});
});
@@ -1,5 +1,6 @@
table {
th, td {
th,
td {
&.settings_logs_checkbox {
text-align: center;
width: 10px;
+316 -239
View File
@@ -1,23 +1,21 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
import flask
import io
import os
import flask
import sarge
from flask_babel import gettext
from octoprint.util import RepeatedTimer
from octoprint.access.permissions import Permissions
from octoprint.access.groups import USER_GROUP
import octoprint.plugin
import octoprint.events
import octoprint.plugin
from octoprint.access.groups import USER_GROUP
from octoprint.access.permissions import Permissions
from octoprint.util import RepeatedTimer
from octoprint.util.platform import CLOSE_FDS
_PROC_DT_MODEL_PATH = "/proc/device-tree/model"
@@ -30,17 +28,35 @@ _CHECK_INTERVAL_THROTTLED = 30
__LOCAL_DEBUG = False
if __LOCAL_DEBUG:
### mocks & settings for local debugging
import sys
base = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "tests", "plugins", "pi_support", "fakes"))
_PROC_DT_MODEL_PATH = os.path.join(base, "fake_model.txt")
_OCTOPI_VERSION_PATH = os.path.join(base, "fake_octopi.txt")
_VCGENCMD_THROTTLE = "{} {}".format(sys.executable, os.path.join(base, "fake_vcgencmd.py"))
import itertools
_VCGENCMD_OUTPUT = itertools.chain(iter(("0x0", "0x0", "0x50005", "0x50000", "0x70007")), itertools.repeat("0x70005"))
### mocks & settings for local debugging
import sys
_CHECK_INTERVAL_OK = 10
_CHECK_INTERVAL_THROTTLED = 5
base = os.path.realpath(
os.path.join(
os.path.dirname(__file__),
"..",
"..",
"..",
"..",
"tests",
"plugins",
"pi_support",
"fakes",
)
)
_PROC_DT_MODEL_PATH = os.path.join(base, "fake_model.txt")
_OCTOPI_VERSION_PATH = os.path.join(base, "fake_octopi.txt")
_VCGENCMD_THROTTLE = "{} {}".format(
sys.executable, os.path.join(base, "fake_vcgencmd.py")
)
import itertools
_VCGENCMD_OUTPUT = itertools.chain(
iter(("0x0", "0x0", "0x50005", "0x50000", "0x70007")), itertools.repeat("0x70005")
)
_CHECK_INTERVAL_OK = 10
_CHECK_INTERVAL_THROTTLED = 5
# see https://www.raspberrypi.org/forums/viewtopic.php?f=63&t=147781&start=50#p972790
@@ -51,314 +67,375 @@ _FLAG_PAST_UNDERVOLTAGE = 1 << 16
_FLAG_PAST_FREQ_CAPPED = 1 << 17
_FLAG_PAST_THROTTLED = 1 << 18
class ThrottleState(object):
@classmethod
def from_value(cls, value=0):
if value == 0:
return ThrottleState()
@classmethod
def from_value(cls, value=0):
if value == 0:
return ThrottleState()
kwargs = {"undervoltage": _FLAG_UNDERVOLTAGE & value == _FLAG_UNDERVOLTAGE,
"freq_capped": _FLAG_FREQ_CAPPED & value == _FLAG_FREQ_CAPPED,
"throttled": _FLAG_THROTTLED & value == _FLAG_THROTTLED,
"past_undervoltage": _FLAG_PAST_UNDERVOLTAGE & value == _FLAG_PAST_UNDERVOLTAGE,
"past_freq_capped": _FLAG_PAST_FREQ_CAPPED & value == _FLAG_PAST_FREQ_CAPPED,
"past_throttled": _FLAG_PAST_THROTTLED & value == _FLAG_PAST_THROTTLED,
"raw_value": value}
return ThrottleState(**kwargs)
kwargs = {
"undervoltage": _FLAG_UNDERVOLTAGE & value == _FLAG_UNDERVOLTAGE,
"freq_capped": _FLAG_FREQ_CAPPED & value == _FLAG_FREQ_CAPPED,
"throttled": _FLAG_THROTTLED & value == _FLAG_THROTTLED,
"past_undervoltage": _FLAG_PAST_UNDERVOLTAGE & value
== _FLAG_PAST_UNDERVOLTAGE,
"past_freq_capped": _FLAG_PAST_FREQ_CAPPED & value == _FLAG_PAST_FREQ_CAPPED,
"past_throttled": _FLAG_PAST_THROTTLED & value == _FLAG_PAST_THROTTLED,
"raw_value": value,
}
return ThrottleState(**kwargs)
def __init__(self, **kwargs):
self._raw_value = kwargs.get('raw_value', -1)
self._undervoltage = False
self._freq_capped = False
self._throttled = False
self._past_undervoltage = False
self._past_freq_capped = False
self._past_throttled = False
def __init__(self, **kwargs):
self._raw_value = kwargs.get("raw_value", -1)
self._undervoltage = False
self._freq_capped = False
self._throttled = False
self._past_undervoltage = False
self._past_freq_capped = False
self._past_throttled = False
for key, value in kwargs.items():
local_key = "_{}".format(key)
if hasattr(self, local_key) and isinstance(value, bool):
setattr(self, local_key, value)
for key, value in kwargs.items():
local_key = "_{}".format(key)
if hasattr(self, local_key) and isinstance(value, bool):
setattr(self, local_key, value)
@property
def undervoltage(self):
return self.current_undervoltage or self.past_undervoltage
@property
def undervoltage(self):
return self.current_undervoltage or self.past_undervoltage
@property
def current_undervoltage(self):
return self._undervoltage
@property
def current_undervoltage(self):
return self._undervoltage
@property
def past_undervoltage(self):
return self._past_undervoltage
@property
def past_undervoltage(self):
return self._past_undervoltage
@property
def overheat(self):
return self.current_overheat or self.past_overheat
@property
def overheat(self):
return self.current_overheat or self.past_overheat
@property
def current_overheat(self):
return self._freq_capped
@property
def current_overheat(self):
return self._freq_capped
@property
def past_overheat(self):
return self._past_freq_capped
@property
def past_overheat(self):
return self._past_freq_capped
@property
def issue(self):
return self.current_issue or self.past_issue
@property
def issue(self):
return self.current_issue or self.past_issue
@property
def current_issue(self):
return self._undervoltage or self._freq_capped or self._throttled
@property
def current_issue(self):
return self._undervoltage or self._freq_capped or self._throttled
@property
def past_issue(self):
return self._past_undervoltage or self._past_freq_capped or self._past_throttled
@property
def past_issue(self):
return self._past_undervoltage or self._past_freq_capped or self._past_throttled
def __eq__(self, other):
if not isinstance(other, ThrottleState):
return False
def __eq__(self, other):
if not isinstance(other, ThrottleState):
return False
return self._undervoltage == other._undervoltage \
and self._freq_capped == other._freq_capped \
and self._throttled == other._throttled \
and self._past_undervoltage == other._past_undervoltage \
and self._past_freq_capped == other._past_freq_capped \
and self._past_throttled == other._past_throttled
return (
self._undervoltage == other._undervoltage
and self._freq_capped == other._freq_capped
and self._throttled == other._throttled
and self._past_undervoltage == other._past_undervoltage
and self._past_freq_capped == other._past_freq_capped
and self._past_throttled == other._past_throttled
)
def as_dict(self):
return {"raw_value": self._raw_value,
"current_undervoltage": self.current_undervoltage,
"past_undervoltage": self.past_undervoltage,
"current_overheat": self.current_overheat,
"past_overheat": self.past_overheat,
"current_issue": self.current_issue,
"past_issue": self.past_issue}
def as_dict(self):
return {
"raw_value": self._raw_value,
"current_undervoltage": self.current_undervoltage,
"past_undervoltage": self.past_undervoltage,
"current_overheat": self.current_overheat,
"past_overheat": self.past_overheat,
"current_issue": self.current_issue,
"past_issue": self.past_issue,
}
_proc_dt_model = None
def get_proc_dt_model():
global _proc_dt_model
global _proc_dt_model
if _proc_dt_model is None:
with io.open(_PROC_DT_MODEL_PATH, 'rt', encoding='utf-8') as f:
_proc_dt_model = f.readline().strip(" \t\r\n\0")
if _proc_dt_model is None:
with io.open(_PROC_DT_MODEL_PATH, "rt", encoding="utf-8") as f:
_proc_dt_model = f.readline().strip(" \t\r\n\0")
return _proc_dt_model
return _proc_dt_model
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, close_fds=CLOSE_FDS)
if __LOCAL_DEBUG:
output = "throttled={}".format(next(_VCGENCMD_OUTPUT)) # mock for local debugging
else:
output = sarge.get_stdout(command, close_fds=CLOSE_FDS)
if not "throttled=0x" in output:
raise ValueError("cannot parse \"{}\" output: {}".format(command, output))
if "throttled=0x" not in output:
raise ValueError('cannot parse "{}" output: {}'.format(command, output))
value = output[len("throttled="):].strip(" \t\r\n\0")
value = int(value, 0)
return ThrottleState.from_value(value)
value = output[len("throttled=") :].strip(" \t\r\n\0")
value = int(value, 0)
return ThrottleState.from_value(value)
def is_octopi():
return os.path.exists(_OCTOPI_VERSION_PATH)
return os.path.exists(_OCTOPI_VERSION_PATH)
_octopi_version = None
def get_octopi_version():
global _octopi_version
global _octopi_version
if _octopi_version is None:
with io.open(_OCTOPI_VERSION_PATH, 'rt', encoding='utf-8') as f:
_octopi_version = f.readline().strip(" \t\r\n\0")
if _octopi_version is None:
with io.open(_OCTOPI_VERSION_PATH, "rt", encoding="utf-8") as f:
_octopi_version = f.readline().strip(" \t\r\n\0")
return _octopi_version
return _octopi_version
class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.SettingsPlugin):
class PiSupportPlugin(
octoprint.plugin.EnvironmentDetectionPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.SettingsPlugin,
):
# noinspection PyMissingConstructor
def __init__(self):
self._throttle_state = ThrottleState()
self._throttle_check = None
self._throttle_undervoltage = False
self._throttle_overheat = False
self._throttle_functional = True
# noinspection PyMissingConstructor
def __init__(self):
self._throttle_state = ThrottleState()
self._throttle_check = None
self._throttle_undervoltage = False
self._throttle_overheat = False
self._throttle_functional = True
# Additional permissions hook
# Additional permissions hook
def get_additional_permissions(self):
return [{"key": "STATUS",
"name": "Status",
"description": gettext("Allows to check for the Pi's throttling status and environment info"),
"roles": ["check"],
"default_groups": [USER_GROUP]}]
def get_additional_permissions(self):
return [
{
"key": "STATUS",
"name": "Status",
"description": gettext(
"Allows to check for the Pi's throttling status and environment info"
),
"roles": ["check"],
"default_groups": [USER_GROUP],
}
]
#~~ EnvironmentDetectionPlugin
# ~~ EnvironmentDetectionPlugin
def get_additional_environment(self):
result = {"model": get_proc_dt_model()}
def get_additional_environment(self):
result = {"model": get_proc_dt_model()}
if is_octopi():
result.update({"octopi_version": get_octopi_version()})
if is_octopi():
result.update({"octopi_version": get_octopi_version()})
return result
return result
#~~ SimpleApiPlugin
# ~~ SimpleApiPlugin
def on_api_get(self, request):
if not Permissions.PLUGIN_PI_SUPPORT_STATUS.can():
return flask.abort(403)
result = {"throttle_state": self._throttle_state.as_dict()}
result.update(self.get_additional_environment())
return flask.jsonify(**result)
def on_api_get(self, request):
if not Permissions.PLUGIN_PI_SUPPORT_STATUS.can():
return flask.abort(403)
result = {"throttle_state": self._throttle_state.as_dict()}
result.update(self.get_additional_environment())
return flask.jsonify(**result)
#~~ AssetPlugin
# ~~ AssetPlugin
def get_assets(self):
return {"js": ["js/pi_support.js"],
"clientjs": ["clientjs/pi_support.js"],
"css": ["css/pi_support.css"]}
def get_assets(self):
return {
"js": ["js/pi_support.js"],
"clientjs": ["clientjs/pi_support.js"],
"css": ["css/pi_support.css"],
}
#~~ TemplatePlugin
# ~~ TemplatePlugin
def get_template_configs(self):
configs = [{"type": "settings",
"name": gettext("Pi Support"),
"template": "pi_support_settings.jinja2",
"custom_bindings": False}]
def get_template_configs(self):
configs = [
{
"type": "settings",
"name": gettext("Pi Support"),
"template": "pi_support_settings.jinja2",
"custom_bindings": False,
}
]
if is_octopi():
configs.append({"type": "about",
"name": "About OctoPi",
"template": "pi_support_about_octopi.jinja2"})
if is_octopi():
configs.append(
{
"type": "about",
"name": "About OctoPi",
"template": "pi_support_about_octopi.jinja2",
}
)
return configs
return configs
def get_template_vars(self):
return self.get_additional_environment()
def get_template_vars(self):
return self.get_additional_environment()
#~~ StartupPlugin
# ~~ StartupPlugin
def on_startup(self, *args, **kwargs):
if self._settings.get_boolean(["vcgencmd_throttle_check_enabled"]):
self._check_throttled_state()
self._throttle_check = RepeatedTimer(self._check_throttled_state_interval,
self._check_throttled_state,
condition=self._check_throttled_state_condition)
self._throttle_check.start()
def on_startup(self, *args, **kwargs):
if self._settings.get_boolean(["vcgencmd_throttle_check_enabled"]):
self._check_throttled_state()
self._throttle_check = RepeatedTimer(
self._check_throttled_state_interval,
self._check_throttled_state,
condition=self._check_throttled_state_condition,
)
self._throttle_check.start()
#~~ SettingsPlugin
# ~~ SettingsPlugin
def get_settings_defaults(self):
return {"vcgencmd_throttle_check_enabled": True,
"vcgencmd_throttle_check_command": _VCGENCMD_THROTTLE}
def get_settings_defaults(self):
return {
"vcgencmd_throttle_check_enabled": True,
"vcgencmd_throttle_check_command": _VCGENCMD_THROTTLE,
}
def get_settings_restricted_paths(self):
return {"admin": [["vcgencmd_throttle_check_enabled"], ["vcgencmd_throttle_check_command"]]}
def get_settings_restricted_paths(self):
return {
"admin": [
["vcgencmd_throttle_check_enabled"],
["vcgencmd_throttle_check_command"],
]
}
#~~ Helpers
# ~~ Helpers
def _check_throttled_state_interval(self):
if self._throttle_state.current_issue:
return _CHECK_INTERVAL_THROTTLED
else:
return _CHECK_INTERVAL_OK
def _check_throttled_state_interval(self):
if self._throttle_state.current_issue:
return _CHECK_INTERVAL_THROTTLED
else:
return _CHECK_INTERVAL_OK
def _check_throttled_state_condition(self):
return self._throttle_functional
def _check_throttled_state_condition(self):
return self._throttle_functional
def get_throttle_state(self, run_now=False):
"""Exposed as public helper."""
if run_now:
self._check_throttled_state()
def get_throttle_state(self, run_now=False):
"""Exposed as public helper."""
if run_now:
self._check_throttled_state()
if not self._throttle_functional:
return False
if not self._throttle_functional:
return False
return self._throttle_state.as_dict()
return self._throttle_state.as_dict()
def _check_throttled_state(self):
command = self._settings.get(["vcgencmd_throttle_check_command"])
def _check_throttled_state(self):
command = self._settings.get(["vcgencmd_throttle_check_command"])
self._logger.debug("Retrieving throttle state via \"{}\"".format(command))
try:
state = get_vcgencmd_throttled_state(command)
except ValueError:
self._logger.warning("Fetching the current throttle state via \"{}\" doesn't work".format(command))
self._throttle_functional = False
return
self._logger.debug('Retrieving throttle state via "{}"'.format(command))
try:
state = get_vcgencmd_throttled_state(command)
except ValueError:
self._logger.warning(
'Fetching the current throttle state via "{}" doesn\'t work'.format(
command
)
)
self._throttle_functional = False
return
if self._throttle_state == state:
# no change
return
if self._throttle_state == state:
# no change
return
self._throttle_state = state
self._throttle_state = state
if (not self._throttle_undervoltage and self._throttle_state.undervoltage) \
or (not self._throttle_overheat and self._throttle_state.overheat):
message = "This Raspberry Pi is reporting problems that might lead to bad performance or errors caused " \
"by overheating or insufficient power."
if (not self._throttle_undervoltage and self._throttle_state.undervoltage) or (
not self._throttle_overheat and self._throttle_state.overheat
):
message = (
"This Raspberry Pi is reporting problems that might lead to bad performance or errors caused "
"by overheating or insufficient power."
)
if self._throttle_state.undervoltage:
self._throttle_undervoltage = True
message += "\n!!! UNDERVOLTAGE REPORTED !!! Make sure that the power supply and power cable are " \
"capable of supplying enough voltage and current to your Pi."
if self._throttle_state.undervoltage:
self._throttle_undervoltage = True
message += (
"\n!!! UNDERVOLTAGE REPORTED !!! Make sure that the power supply and power cable are "
"capable of supplying enough voltage and current to your Pi."
)
if self._throttle_state.overheat:
self._throttle_overheat = True
message += "\n!!! FREQUENCY CAPPING DUE TO OVERHEATING REPORTED !!! Improve cooling on the Pi's " \
"CPU and GPU."
if self._throttle_state.overheat:
self._throttle_overheat = True
message += (
"\n!!! FREQUENCY CAPPING DUE TO OVERHEATING REPORTED !!! Improve cooling on the Pi's "
"CPU and GPU."
)
self._logger.warning(message)
self._logger.warning(message)
self._plugin_manager.send_plugin_message(self._identifier, {"type": "throttle_state",
"state": self._throttle_state.as_dict()})
self._plugin_manager.send_plugin_message(
self._identifier,
{"type": "throttle_state", "state": self._throttle_state.as_dict()},
)
# noinspection PyUnresolvedReferences
self._event_bus.fire(octoprint.events.Events.PLUGIN_PI_SUPPORT_THROTTLE_STATE, self._throttle_state.as_dict())
# noinspection PyUnresolvedReferences
self._event_bus.fire(
octoprint.events.Events.PLUGIN_PI_SUPPORT_THROTTLE_STATE,
self._throttle_state.as_dict(),
)
def register_custom_events(*args, **kwargs):
return ["throttle_state",]
return [
"throttle_state",
]
__plugin_name__ = "Pi Support Plugin"
__plugin_author__ = "Gina Häußge"
__plugin_description__ = "Provides additional information about your Pi in the UI."
__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to "
"provide additional information about your Pi, "
"which will make it more tricky to help you if you need support.")
__plugin_disabling_discouraged__ = gettext(
"Without this plugin OctoPrint will no longer be able to "
"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:
proc_dt_model = get_proc_dt_model()
if proc_dt_model is None:
return False
except Exception:
return False
return "raspberry pi" in proc_dt_model.lower()
def __plugin_check__():
try:
proc_dt_model = get_proc_dt_model()
if proc_dt_model is None:
return False
except Exception:
return False
return "raspberry pi" in proc_dt_model.lower()
def __plugin_load__():
plugin = PiSupportPlugin()
global __plugin_implementation__
__plugin_implementation__ = plugin
plugin = PiSupportPlugin()
global __plugin_implementation__
__plugin_implementation__ = plugin
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.events.register_custom_events": register_custom_events,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
}
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.events.register_custom_events": register_custom_events,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions,
}
global __plugin_helpers__
__plugin_helpers__ = {"get_throttled": plugin.get_throttle_state}
global __plugin_helpers__
__plugin_helpers__ = {"get_throttled": plugin.get_throttle_state}
@@ -4,16 +4,15 @@
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var OctoPrintPiSupportClient = function(base) {
})(this, function (OctoPrintClient) {
var OctoPrintPiSupportClient = function (base) {
this.base = base;
};
OctoPrintPiSupportClient.prototype.get = function(opts) {
OctoPrintPiSupportClient.prototype.get = function (opts) {
return this.base.get(this.base.getSimpleApiUrl("pi_support"));
};
OctoPrintClient.registerPluginComponent("pi_support", OctoPrintPiSupportClient);
return OctoPrintPiSupportClient;
});
@@ -1,5 +1,4 @@
$(function() {
$(function () {
function PiSupportViewModel(parameters) {
var self = this;
@@ -15,29 +14,39 @@ $(function() {
self.currentIssue = ko.observable(false);
self.pastIssue = ko.observable(false);
self.requestData = function() {
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PI_SUPPORT_STATUS)) {
self.requestData = function () {
if (
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_PI_SUPPORT_STATUS
)
) {
return;
}
OctoPrint.plugins.pi_support.get()
.done(function(response) {
// Raspberry Pi model
self.model(response.model);
OctoPrint.plugins.pi_support.get().done(function (response) {
// Raspberry Pi model
self.model(response.model);
// Throttle state
self.fromThrottleState(response.throttle_state);
// Throttle state
self.fromThrottleState(response.throttle_state);
// OctoPi version
$("#pi_support_footer").remove();
if (!response.octopi_version) return;
// OctoPi version
$("#pi_support_footer").remove();
if (!response.octopi_version) return;
var octoPiVersion = $("<li id='pi_support_footer'><small>" + gettext("OctoPi") + " " + "<span class='octopi_version'>" + response.octopi_version + "</span></small></li>");
$("#footer_version").append(octoPiVersion);
})
var octoPiVersion = $(
"<li id='pi_support_footer'><small>" +
gettext("OctoPi") +
" " +
"<span class='octopi_version'>" +
response.octopi_version +
"</span></small></li>"
);
$("#footer_version").append(octoPiVersion);
});
};
self.fromThrottleState = function(state) {
self.fromThrottleState = function (state) {
self.currentUndervoltage(state.current_undervoltage);
self.pastUndervoltage(state.past_undervoltage);
self.currentOverheat(state.current_overheat);
@@ -46,7 +55,7 @@ $(function() {
self.pastIssue(state.past_issue);
};
self.popoverContent = ko.pureComputed(function() {
self.popoverContent = ko.pureComputed(function () {
var undervoltageParagraphClasses = "muted";
var undervoltageSymbolClasses = "";
@@ -69,24 +78,53 @@ $(function() {
overheatParagraphClasses = "";
}
return "<p class='" + undervoltageParagraphClasses + "'><strong class='" + undervoltageSymbolClasses + "'><i class=\"fa fa-bolt\"></i><i class=\"fa fa-exclamation\"></i></strong></strong> - " + gettext("Undervoltage. Make sure your power supply and cabling are providing enough power to the Pi.") + "</p>"
+ "<p class='" + overheatParagraphClasses + "'><strong class='" + overheatSymbolClasses + "'><i class=\"fa fa-thermometer-full\"></i><i class=\"fa fa-exclamation\"></i></strong> - " + gettext("Frequency capping due to overheating. Improve cooling of the CPU and GPU.") + "</p>"
+ "<p>" + gettext("A blinking symbol indicates a current issue, a non blinking symbol one that was observed some time since the Pi booted up.") + "</p>"
+ "<p><small>" + gettext("Click the symbol in the navbar for more information.") + "</small></p>";
return (
"<p class='" +
undervoltageParagraphClasses +
"'><strong class='" +
undervoltageSymbolClasses +
'\'><i class="fa fa-bolt"></i><i class="fa fa-exclamation"></i></strong></strong> - ' +
gettext(
"Undervoltage. Make sure your power supply and cabling are providing enough power to the Pi."
) +
"</p>" +
"<p class='" +
overheatParagraphClasses +
"'><strong class='" +
overheatSymbolClasses +
'\'><i class="fa fa-thermometer-full"></i><i class="fa fa-exclamation"></i></strong> - ' +
gettext(
"Frequency capping due to overheating. Improve cooling of the CPU and GPU."
) +
"</p>" +
"<p>" +
gettext(
"A blinking symbol indicates a current issue, a non blinking symbol one that was observed some time since the Pi booted up."
) +
"</p>" +
"<p><small>" +
gettext("Click the symbol in the navbar for more information.") +
"</small></p>"
);
});
self.onStartup = self.onServerReconnect = self.onUserLoggedIn = self.onUserLoggedOut = function() {
self.onStartup = self.onServerReconnect = self.onUserLoggedIn = self.onUserLoggedOut = function () {
self.requestData();
};
self.onDataUpdaterPluginMessage = function(plugin, data) {
self.onDataUpdaterPluginMessage = function (plugin, data) {
if (plugin !== "pi_support") return;
if (!data.hasOwnProperty("state") || !data.hasOwnProperty("type")) return;
if (data.type !== "throttle_state") return;
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PI_SUPPORT_STATUS)) return;
if (
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_PI_SUPPORT_STATUS
)
)
return;
self.fromThrottleState(data.state);
}
};
}
OCTOPRINT_VIEWMODELS.push({
@@ -29,4 +29,3 @@
For a copy of the GNU General Public License, see
<a href="https://www.gnu.org/licenses/gpl-3.0.en.html" target="_blank" rel="noreferrer noopener">www.gnu.org/licenses/gpl-3.0.en.html</a>.
</p>
@@ -27,5 +27,3 @@
</div>
</div>
</form>
File diff suppressed because it is too large. Load diff
@@ -4,12 +4,12 @@
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var OctoPrintPluginManagerClient = function(base) {
})(this, function (OctoPrintClient) {
var OctoPrintPluginManagerClient = function (base) {
this.base = base;
};
OctoPrintPluginManagerClient.prototype.get = function(refresh, opts) {
OctoPrintPluginManagerClient.prototype.get = function (refresh, opts) {
var refresh_repo, refresh_notices, refresh_orphans;
if (_.isPlainObject(refresh)) {
refresh_repo = refresh.repo || false;
@@ -26,18 +26,26 @@
if (refresh_notices) query.push("refresh_notices=true");
if (refresh_orphans) query.push("refresh_orphans=true");
return this.base.get(this.base.getSimpleApiUrl("pluginmanager") + ((query.length) ? "?" + query.join("&") : ""), opts);
return this.base.get(
this.base.getSimpleApiUrl("pluginmanager") +
(query.length ? "?" + query.join("&") : ""),
opts
);
};
OctoPrintPluginManagerClient.prototype.getWithRefresh = function(opts) {
OctoPrintPluginManagerClient.prototype.getWithRefresh = function (opts) {
return this.get(true, opts);
};
OctoPrintPluginManagerClient.prototype.getWithoutRefresh = function(opts) {
OctoPrintPluginManagerClient.prototype.getWithoutRefresh = function (opts) {
return this.get(false, opts);
};
OctoPrintPluginManagerClient.prototype.install = function(pluginUrl, dependencyLinks, opts) {
OctoPrintPluginManagerClient.prototype.install = function (
pluginUrl,
dependencyLinks,
opts
) {
var data = {
url: pluginUrl,
dependency_links: !!dependencyLinks
@@ -45,7 +53,12 @@
return this.base.simpleApiCommand("pluginmanager", "install", data, opts);
};
OctoPrintPluginManagerClient.prototype.reinstall = function(plugin, pluginUrl, dependencyLinks, opts) {
OctoPrintPluginManagerClient.prototype.reinstall = function (
plugin,
pluginUrl,
dependencyLinks,
opts
) {
var data = {
url: pluginUrl,
dependency_links: !!dependencyLinks,
@@ -55,7 +68,7 @@
return this.base.simpleApiCommand("pluginmanager", "install", data, opts);
};
OctoPrintPluginManagerClient.prototype.uninstall = function(plugin, cleanup, opts) {
OctoPrintPluginManagerClient.prototype.uninstall = function (plugin, cleanup, opts) {
// backwards compatibility to former argument list (plugin, opts)
if (arguments.length === 2 && typeof cleanup === "object") {
opts = cleanup;
@@ -69,36 +82,42 @@
return this.base.simpleApiCommand("pluginmanager", "uninstall", data, opts);
};
OctoPrintPluginManagerClient.prototype.cleanup = function(plugin, opts) {
OctoPrintPluginManagerClient.prototype.cleanup = function (plugin, opts) {
var data = {
plugin: plugin
};
return this.base.simpleApiCommand("pluginmanager", "cleanup", data, opts);
};
OctoPrintPluginManagerClient.prototype.cleanupAll = function(plugin, opts) {
OctoPrintPluginManagerClient.prototype.cleanupAll = function (plugin, opts) {
var data = {};
return this.base.simpleApiCommand("pluginmanager", "cleanup_all", data, opts);
};
OctoPrintPluginManagerClient.prototype.enable = function(plugin, opts) {
OctoPrintPluginManagerClient.prototype.enable = function (plugin, opts) {
var data = {
plugin: plugin
};
return this.base.simpleApiCommand("pluginmanager", "enable", data, opts);
};
OctoPrintPluginManagerClient.prototype.disable = function(plugin, opts) {
OctoPrintPluginManagerClient.prototype.disable = function (plugin, opts) {
var data = {
plugin: plugin
};
return this.base.simpleApiCommand("pluginmanager", "disable", data, opts);
};
OctoPrintPluginManagerClient.prototype.upload = function(file) {
return this.base.upload(this.base.getBlueprintUrl("pluginmanager") + "upload_archive", file);
OctoPrintPluginManagerClient.prototype.upload = function (file) {
return this.base.upload(
this.base.getBlueprintUrl("pluginmanager") + "upload_archive",
file
);
};
OctoPrintClient.registerPluginComponent("pluginmanager", OctoPrintPluginManagerClient);
OctoPrintClient.registerPluginComponent(
"pluginmanager",
OctoPrintPluginManagerClient
);
return OctoPrintPluginManagerClient;
});
File diff suppressed because it is too large. Load diff
@@ -11,8 +11,8 @@
margin-bottom: 1em;
table {
th, td {
th,
td {
&.settings_plugin_plugin_manager_plugins_name {
text-overflow: ellipsis;
text-align: left;
@@ -50,8 +50,8 @@
margin-bottom: 1em;
table {
th, td {
th,
td {
&.settings_plugin_plugin_manager_orphans_id {
text-overflow: ellipsis;
text-align: left;
@@ -430,4 +430,3 @@
<button class="btn btn-primary" data-bind="click: savePluginSettings" aria-hidden="true">{{ _('Save') }}</button>
</div>
</div>
File diff suppressed because it is too large. Load diff
+210 -182
View File
@@ -1,229 +1,257 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
import click
click.disable_unicode_literals_warning = True
import sys
import requests.exceptions
from octoprint.cli.client import create_client, client_options
import click
@click.command("check")
@click.option("--force", is_flag=True, help="Ignore the cache for the update check")
@click.option("--only-new", is_flag=True, help="Only show entries with updates available")
@client_options
@click.argument("targets", nargs=-1)
def check_command(force, only_new, apikey, host, port, httpuser, httppass, https, prefix, targets):
"""
Check for updates.
click.disable_unicode_literals_warning = True
import sys
If any TARGETs are provided, only those components will be checked.
import requests.exceptions
\b
Examples:
- octoprint plugins softwareupdate:check
This will check all components for available updates,
utilizing cached version information.
- octoprint plugins softwareupdate:check --force
This will check all components for available updates,
ignoring any cached version information even if it's
still valid.
- octoprint plugins softwareupdate:check octoprint
This will only check OctoPrint itself for available
updates.
from octoprint.cli.client import client_options, create_client
Note that the OctoPrint server needs to be running for this
command to work as it utilizes the server API.
"""
params = {"force": force}
if targets:
params["targets"] = ",".join(targets)
@click.command("check")
@click.option("--force", is_flag=True, help="Ignore the cache for the update check")
@click.option(
"--only-new", is_flag=True, help="Only show entries with updates available"
)
@client_options
@click.argument("targets", nargs=-1)
def check_command(
force, only_new, apikey, host, port, httpuser, httppass, https, prefix, targets
):
"""
Check for updates.
client = create_client(settings=cli_group.settings,
apikey=apikey,
host=host,
port=port,
httpuser=httpuser,
httppass=httppass,
https=https,
prefix=prefix)
If any TARGETs are provided, only those components will be checked.
r = client.get("plugin/softwareupdate/check", params=params)
try:
r.raise_for_status()
except requests.exceptions.HTTPError as e:
click.echo("Could not get update information from server, got {}".format(e))
sys.exit(1)
\b
Examples:
- octoprint plugins softwareupdate:check
This will check all components for available updates,
utilizing cached version information.
- octoprint plugins softwareupdate:check --force
This will check all components for available updates,
ignoring any cached version information even if it's
still valid.
- octoprint plugins softwareupdate:check octoprint
This will only check OctoPrint itself for available
updates.
data = r.json()
status = data["status"]
information = data["information"]
Note that the OctoPrint server needs to be running for this
command to work as it utilizes the server API.
"""
params = {"force": force}
if targets:
params["targets"] = ",".join(targets)
lines = []
octoprint_line = None
for key, info in information.items():
status_text = "Up to date"
if info["updateAvailable"]:
if info["updatePossible"]:
status_text = "Update available"
else:
status_text = "Update available (manual)"
client = create_client(
settings=cli_group.settings,
apikey=apikey,
host=host,
port=port,
httpuser=httpuser,
httppass=httppass,
https=https,
prefix=prefix,
)
elif only_new:
continue
r = client.get("plugin/softwareupdate/check", params=params)
try:
r.raise_for_status()
except requests.exceptions.HTTPError as e:
click.echo("Could not get update information from server, got {}".format(e))
sys.exit(1)
line = "{} (target: {})\n\tInstalled: {}\n\tAvailable: {}\n\t=> {}".format(info["displayName"],
key,
info["information"]["local"]["name"],
info["information"]["remote"]["name"],
status_text)
if key == "octoprint":
octoprint_line = line
else:
lines.append(line)
data = r.json()
status = data["status"]
information = data["information"]
lines.sort()
if octoprint_line:
lines = [octoprint_line] + lines
lines = []
octoprint_line = None
for key, info in information.items():
status_text = "Up to date"
if info["updateAvailable"]:
if info["updatePossible"]:
status_text = "Update available"
else:
status_text = "Update available (manual)"
for line in lines:
click.echo(line)
elif only_new:
continue
click.echo()
if status == "current":
click.echo("Everything is up to date")
else:
click.echo("There are updates available!")
line = "{} (target: {})\n\tInstalled: {}\n\tAvailable: {}\n\t=> {}".format(
info["displayName"],
key,
info["information"]["local"]["name"],
info["information"]["remote"]["name"],
status_text,
)
if key == "octoprint":
octoprint_line = line
else:
lines.append(line)
lines.sort()
if octoprint_line:
lines = [octoprint_line] + lines
@click.command("update")
@click.option("--force", is_flag=True, help="Update even if already up to date")
@client_options
@click.argument("targets", nargs=-1)
def update_command(force, apikey, host, port, httpuser, httppass, https, prefix, targets):
"""
Apply updates.
for line in lines:
click.echo(line)
If any TARGETs are provided, only those components will be updated.
click.echo()
if status == "current":
click.echo("Everything is up to date")
else:
click.echo("There are updates available!")
\b
Examples:
- octoprint plugins softwareupdate:update
This will update all components with a pending update
that can be updated.
- octoprint plugins softwareupdate:update --force
This will force an update of all registered components
that can be updated, even if they don't have an updated
pending.
- octoprint plugins softwareupdate:update octoprint
This will only update OctoPrint and leave any further
components with pending updates at their current versions.
@click.command("update")
@click.option("--force", is_flag=True, help="Update even if already up to date")
@client_options
@click.argument("targets", nargs=-1)
def update_command(
force, apikey, host, port, httpuser, httppass, https, prefix, targets
):
"""
Apply updates.
Note that the OctoPrint server needs to be running for this
command to work as it utilizes the server API.
"""
If any TARGETs are provided, only those components will be updated.
data = {"force": force}
if targets:
data["targets"] = targets
\b
Examples:
- octoprint plugins softwareupdate:update
This will update all components with a pending update
that can be updated.
- octoprint plugins softwareupdate:update --force
This will force an update of all registered components
that can be updated, even if they don't have an updated
pending.
- octoprint plugins softwareupdate:update octoprint
This will only update OctoPrint and leave any further
components with pending updates at their current versions.
client = create_client(settings=cli_group.settings,
apikey=apikey,
host=host,
port=port,
httpuser=httpuser,
httppass=httppass,
https=https,
prefix=prefix)
Note that the OctoPrint server needs to be running for this
command to work as it utilizes the server API.
"""
flags = {"waiting_for_restart": False,
"seen_close": False}
data = {"force": force}
if targets:
data["targets"] = targets
def on_message(ws, msg_type, msg):
if msg_type != "plugin" or msg["plugin"] != "softwareupdate":
return
client = create_client(
settings=cli_group.settings,
apikey=apikey,
host=host,
port=port,
httpuser=httpuser,
httppass=httppass,
https=https,
prefix=prefix,
)
plugin_message = msg["data"]
if not "type" in plugin_message:
return
flags = {"waiting_for_restart": False, "seen_close": False}
plugin_message_type = plugin_message["type"]
plugin_message_data = plugin_message["data"]
def on_message(ws, msg_type, msg):
if msg_type != "plugin" or msg["plugin"] != "softwareupdate":
return
if plugin_message_type == "updating":
click.echo("Updating {} to {}...".format(plugin_message_data.get("name", "unknown"), plugin_message_data.get("version", "n/a")))
plugin_message = msg["data"]
if "type" not in plugin_message:
return
elif plugin_message_type == "update_failed":
click.echo("\t... failed :(")
plugin_message_type = plugin_message["type"]
plugin_message_data = plugin_message["data"]
elif plugin_message_type == "loglines" and "loglines" in plugin_message_data:
for entry in plugin_message_data["loglines"]:
prefix = ">>> " if entry["stream"] == "call" else ""
error = entry["stream"] == "stderr"
click.echo("\t{}{}".format(prefix, entry["line"].replace("\n", "\n\t")), err=error)
if plugin_message_type == "updating":
click.echo(
"Updating {} to {}...".format(
plugin_message_data.get("name", "unknown"),
plugin_message_data.get("version", "n/a"),
)
)
elif plugin_message_type == "success" or plugin_message_type == "restart_manually":
results = plugin_message_data["results"] if "results" in plugin_message_data else {}
if results:
click.echo("The update finished successfully.")
if plugin_message_type == "restart_manually":
click.echo("Please restart the OctoPrint server.")
else:
click.echo("No update necessary")
ws.close()
elif plugin_message_type == "update_failed":
click.echo("\t... failed :(")
elif plugin_message_type == "restarting":
flags["waiting_for_restart"] = True
click.echo("Restarting to apply changes...")
elif plugin_message_type == "loglines" and "loglines" in plugin_message_data:
for entry in plugin_message_data["loglines"]:
prefix = ">>> " if entry["stream"] == "call" else ""
error = entry["stream"] == "stderr"
click.echo(
"\t{}{}".format(prefix, entry["line"].replace("\n", "\n\t")),
err=error,
)
elif plugin_message_type == "error":
click.echo("Error")
ws.close()
elif (
plugin_message_type == "success"
or plugin_message_type == "restart_manually"
):
results = (
plugin_message_data["results"]
if "results" in plugin_message_data
else {}
)
if results:
click.echo("The update finished successfully.")
if plugin_message_type == "restart_manually":
click.echo("Please restart the OctoPrint server.")
else:
click.echo("No update necessary")
ws.close()
def on_open(ws):
if flags["waiting_for_restart"] and flags["seen_close"]:
click.echo(" Reconnected!")
else:
click.echo("Connected to server...")
elif plugin_message_type == "restarting":
flags["waiting_for_restart"] = True
click.echo("Restarting to apply changes...")
def on_close(ws):
if flags["waiting_for_restart"] and flags["seen_close"]:
click.echo(".", nl=False)
else:
flags["seen_close"] = True
click.echo("Disconnected from server...")
elif plugin_message_type == "error":
click.echo("Error")
ws.close()
socket = client.create_socket(on_message=on_message,
on_open=on_open,
on_close=on_close)
def on_open(ws):
if flags["waiting_for_restart"] and flags["seen_close"]:
click.echo(" Reconnected!")
else:
click.echo("Connected to server...")
r = client.post_json("plugin/softwareupdate/update", data=data)
try:
r.raise_for_status()
except requests.exceptions.HTTPError as e:
click.echo("Could not get update information from server, got {}".format(e))
sys.exit(1)
def on_close(ws):
if flags["waiting_for_restart"] and flags["seen_close"]:
click.echo(".", nl=False)
else:
flags["seen_close"] = True
click.echo("Disconnected from server...")
data = r.json()
to_be_updated = data["order"]
checks = data["checks"]
click.echo("Update in progress, updating:")
for name in to_be_updated:
click.echo("\t{}".format(name if not name in checks else checks[name]))
socket = client.create_socket(
on_message=on_message, on_open=on_open, on_close=on_close
)
socket.wait()
r = client.post_json("plugin/softwareupdate/update", data=data)
try:
r.raise_for_status()
except requests.exceptions.HTTPError as e:
click.echo("Could not get update information from server, got {}".format(e))
sys.exit(1)
if flags["waiting_for_restart"]:
if socket.reconnect(timeout=60):
click.echo("The update finished successfully.")
else:
click.echo("The update finished successfully but the server apparently didn't restart as expected.")
click.echo("Please restart the OctoPrint server.")
data = r.json()
to_be_updated = data["order"]
checks = data["checks"]
click.echo("Update in progress, updating:")
for name in to_be_updated:
click.echo("\t{}".format(name if name not in checks else checks[name]))
return [check_command, update_command]
socket.wait()
if flags["waiting_for_restart"]:
if socket.reconnect(timeout=60):
click.echo("The update finished successfully.")
else:
click.echo(
"The update finished successfully but the server apparently didn't restart as expected."
)
click.echo("Please restart the OctoPrint server.")
return [check_command, update_command]
@@ -2,55 +2,65 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
class NoUpdateAvailable(Exception):
pass
pass
class UpdateAlreadyInProgress(Exception):
pass
pass
class UnknownUpdateType(Exception):
pass
pass
class UnknownCheckType(Exception):
pass
pass
class NetworkError(Exception):
def __init__(self, message=None, cause=None):
Exception.__init__(self)
self.message = message
self.cause = cause
def __init__(self, message=None, cause=None):
Exception.__init__(self)
self.message = message
self.cause = cause
def __str__(self):
if self.message is not None:
return self.message
elif self.cause is not None:
return "NetworkError caused by {}".format(self.cause)
else:
return "NetworkError"
def __str__(self):
if self.message is not None:
return self.message
elif self.cause is not None:
return "NetworkError caused by {}".format(self.cause)
else:
return "NetworkError"
class UpdateError(Exception):
def __init__(self, message, data):
self.message = message
self.data = data
def __init__(self, message, data):
self.message = message
self.data = data
class ScriptError(Exception):
def __init__(self, returncode, stdout, stderr):
self.returncode = returncode
self.stdout = stdout
self.stderr = stderr
def __init__(self, returncode, stdout, stderr):
self.returncode = returncode
self.stdout = stdout
self.stderr = stderr
class RestartFailed(Exception):
pass
pass
class ConfigurationInvalid(Exception):
pass
pass
class CannotCheckOffline(Exception):
pass
pass
class CannotUpdateOffline(Exception):
pass
pass
Loaded 100 of 367 files, more files were not shown because too many files have changed in this diff. Show more