Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a012c41dad |
No files matched your search
@@ -1,5 +0,0 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: [foosel]
|
||||
patreon: foosel
|
||||
custom: https://octoprint.org/support-octoprint/
|
||||
@@ -1,9 +1,3 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help improve OctoPrint
|
||||
|
||||
---
|
||||
|
||||
<!--
|
||||
READ THE FOLLOWING FIRST:
|
||||
|
||||
@@ -18,7 +12,7 @@ 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
|
||||
community.octoprint.org, NOT here.
|
||||
discourse.octoprint.org, NOT here.
|
||||
|
||||
Mark requests with a "[Request]" prefix in the title please. For bug
|
||||
reports fully fill out the bug reporting template (if you don't know
|
||||
@@ -45,10 +39,9 @@ don't know what you did to get it to happen in the first place.
|
||||
Ideally provide exact steps to follow in order to reproduce your problem:
|
||||
-->
|
||||
|
||||
1. Go to '...'
|
||||
2. Click on '....'
|
||||
3. Scroll down to '....'
|
||||
4. See error
|
||||
1. ...
|
||||
2. ...
|
||||
3. ...
|
||||
|
||||
<!--
|
||||
If you encountered a problem with specific files of any sorts, make sure
|
||||
@@ -1,21 +0,0 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
|
||||
---
|
||||
|
||||
<!--
|
||||
Please make sure to add [Request] to your issue's title. Thank you!
|
||||
-->
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
@@ -16,9 +16,8 @@ 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
|
||||
new feature, or maintenance if it's a bug fix or improvement of
|
||||
existing functionality for the current stable version (no PRs
|
||||
* [ ] Your PR targets OctoPrint's devel branch, or maintenance if it's
|
||||
a bug fix for an issue present in 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),
|
||||
|
||||
@@ -31,12 +31,9 @@ OctoPrint.egg-info
|
||||
*.codekit
|
||||
|
||||
venv
|
||||
venv2
|
||||
venv3
|
||||
venv26
|
||||
venv27
|
||||
venv33
|
||||
venv34
|
||||
venv35
|
||||
venv36
|
||||
venv37
|
||||
+1
-11
@@ -1,22 +1,12 @@
|
||||
---
|
||||
|
||||
language: python
|
||||
dist: xenial
|
||||
|
||||
matrix:
|
||||
include:
|
||||
- python: '3.7'
|
||||
env: RUN_FLAKE8=true
|
||||
|
||||
python:
|
||||
- "3.7"
|
||||
- "3.6"
|
||||
- "2.7"
|
||||
install:
|
||||
- pip install -e .[develop]
|
||||
script:
|
||||
- test -n "$RUN_FLAKE8" || pytest
|
||||
- test -z "$RUN_FLAKE8" || flake8 --ignore=D,E,W,F401 src/ tests setup.py
|
||||
- nosetests --with-doctest
|
||||
sudo: false
|
||||
git:
|
||||
depth: 250
|
||||
+9
-12
@@ -18,19 +18,16 @@ prerelease
|
||||
HEAD
|
||||
\(detached.*
|
||||
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.4.1
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.3.9
|
||||
# so are any fix/... and improve/... branches
|
||||
maintenance 1.4.1 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev
|
||||
fix/.* 1.4.1 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev
|
||||
improve/.* 1.4.1 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev
|
||||
maintenance 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
|
||||
fix/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
|
||||
improve/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
|
||||
|
||||
# staging/maintenance is currently the branch for preparation of 1.4.0rc6
|
||||
# staging/maintenance is currently the branch for preparation of 1.3.9rc5
|
||||
# so is regressionfix/...
|
||||
staging/maintenance 1.4.0rc6 73f7c4d8a11a7aea7b0ece474d3bf37ad53c65d4 pep440-dev
|
||||
regressionfix/.* 1.4.0rc6 73f7c4d8a11a7aea7b0ece474d3bf37ad53c65d4 pep440-dev
|
||||
staging/maintenance 1.3.9rc5 71b2cc87a36d403e09325c90134a002c5229b6aa pep440-dev
|
||||
regressionfix/.* 1.3.9rc5 71b2cc87a36d403e09325c90134a002c5229b6aa pep440-dev
|
||||
|
||||
# staging/devel is currently inactive (but has the 1.4.0rc6 namespace)
|
||||
staging/devel 1.4.0rc6 73f7c4d8a11a7aea7b0ece474d3bf37ad53c65d4 pep440-dev
|
||||
|
||||
# every other branch is a development branch and thus gets resolved to 1.5.0-dev for now
|
||||
.* 1.5.0 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev
|
||||
# every other branch is a development branch and thus gets resolved to 1.4.0-dev for now
|
||||
.* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
|
||||
+1
-24
@@ -69,13 +69,12 @@ date of first contribution):
|
||||
* [Philipp Baum](https://github.com/philphilphil)
|
||||
* [Kyle Evans](https://github.com/kevans91)
|
||||
* [Javier Martínez Arrieta](https://github.com/Javierma)
|
||||
* [Mircea Dan Gheorghe](https://github.com/ByReaL)
|
||||
* ["MirceaDan"](https://github.com/ByReaL)
|
||||
* [Ovidiu Hossu](https://github.com/MoonshineSG)
|
||||
* [Eyck Jentzsch](https://github.com/eyck)
|
||||
* [Mathias Rangel Wulff](https://github.com/mathiasrw)
|
||||
* [Clemens Niemeyer](https://github.com/clemniem)
|
||||
* ["I-am-me"](https://github.com/I-am-me)
|
||||
* [J-J Heinonen](https://github.com/jammi)
|
||||
* [Noah Martin](https://github.com/noahsmartin)
|
||||
* [Eyal Soha](https://github.com/eyal0)
|
||||
* [Greg Hulands](https://github.com/ghulands)
|
||||
@@ -92,29 +91,7 @@ date of first contribution):
|
||||
* [Ganey](https://github.com/ganey)
|
||||
* [Sven Lohrmann](https://github.com/malnvenshorn)
|
||||
* [Andy Castille](https://github.com/klikini)
|
||||
* [Zachary Nofzinger](https://github.com/ZachNo)
|
||||
* [Gaston Dombiak](https://github.com/gdombiak)
|
||||
* [Brad Fisher](https://github.com/bradcfisher)
|
||||
* [Aldo Hoeben](https://github.com/fieldofview)
|
||||
* [Henning Groß](https://github.com/hgross)
|
||||
* [Jubaleth](https://github.com/jubaleth)
|
||||
* [Matthias Urlichs](https://github.com/smurfix)
|
||||
* [Daniel Joyce](https://github.com/DanielJoyce)
|
||||
* [Andy Qua](https://github.com/AndyQ)
|
||||
* [Fabio Santos](https://github.com/Fabi0San)
|
||||
* [Jack Wilsdon](https://github.com/jackwilsdon)
|
||||
* [Ryan Finnie](https://github.com/rfinnie)
|
||||
* [Timur Duehr](https://github.com/tduehr)
|
||||
* [Nicolai Nielsen](https://github.com/dovecode)
|
||||
* [Janne Mäntyharju](https://github.com/JanneMantyharju)
|
||||
* [Steven Spungin](https://github.com/flamenco)
|
||||
* [Piotr Usewicz](https://github.com/pusewicz)
|
||||
* [Aliaksei Pilko](https://github.com/aliaksei135)
|
||||
* [Ben Yarmis](https://github.com/byarmis)
|
||||
* [Florian Heilmann](https://github.com/FHeilmann)
|
||||
* [Ludovico de Nittis](https://github.com/RyuzakiKK)
|
||||
* [Dominik Paľo](https://github.com/DominikPalo)
|
||||
* [Kelly Anderson](https://github.com/cbxbiker61)
|
||||
|
||||
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
|
||||
[Daid Braam](https://github.com/daid). Parts of its communication layer and
|
||||
|
||||
+1902
-3
File diff suppressed because it is too large.
Load diff
+9
-9
@@ -36,14 +36,14 @@ nothing but ticket management.
|
||||
- If you want to post a **feature request** or a **documentation request**, add `[Request]`
|
||||
to your issue's title (e.g. `[Request] Awesome new feature`). A question on how to run/change/setup
|
||||
something is **not** what qualifies as a request here, use the
|
||||
[community forum at community.octoprint.org](https://community.octoprint.org) for
|
||||
[community forum at discourse.octoprint.org](https://discourse.octoprint.org) for
|
||||
such support issues.
|
||||
- If you are a **developer** that wants to brainstorm a pull request or possible
|
||||
changes to the plugin system, please get in touch on the
|
||||
[community forum at community.octoprint.org](https://community.octoprint.org/c/development).
|
||||
[community forum at discourse.octoprint.org](https://discourse.octoprint.org/c/development).
|
||||
- If you need **support**, have a **question** or some **other reason** that
|
||||
doesn't fit any of the above categories, the issue tracker is not the right place.
|
||||
Consult the [community forum at community.octoprint.org](https://community.octoprint.org/c/support) instead.
|
||||
Consult the [community forum at discourse.octoprint.org](https://discourse.octoprint.org/c/support) instead.
|
||||
|
||||
No matter what kind of ticket you create, never mix two or more "ticket reasons"
|
||||
into one ticket: One ticket per bug, request, brainstorming thread please.
|
||||
@@ -75,7 +75,7 @@ following section *completely* and also follow the instructions in the
|
||||
**OctoPrint doesn't manage your network connection or your webcam nor
|
||||
can it fix your printer not getting detected as a serial interface** -
|
||||
if you have any kinds of problems with that, get in touch on the
|
||||
[community forum](https://community.octoprint.org).
|
||||
[community forum](https://discourse.octoprint.org).
|
||||
|
||||
**This is not the bug tracker of OctoPi**, which is the preconfigured
|
||||
Raspberry Pi image including OctoPrint among other things - that one can be found
|
||||
@@ -126,7 +126,7 @@ following section *completely* and also follow the instructions in the
|
||||
there's now also a [red herring](https://en.wikipedia.org/wiki/Red_herring) interfering - so please be
|
||||
very diligent here!
|
||||
|
||||
If in doubt about any of the above - get in touch on the [community forum](https://community.octoprint.org)
|
||||
If in doubt about any of the above - get in touch on the [community forum](https://discourse.octoprint.org)
|
||||
instead of opening a ticket here. If you are actually running into a bug, we'll figure it out together
|
||||
there.
|
||||
|
||||
@@ -153,7 +153,7 @@ 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
|
||||
community.octoprint.org, NOT here.
|
||||
discourse.octoprint.org, NOT here.
|
||||
|
||||
Mark requests with a "[Request]" prefix in the title please. For bug
|
||||
reports fully fill out the bug reporting template (if you don't know
|
||||
@@ -275,11 +275,11 @@ all requested information or your ticket will be closed.
|
||||
|
||||
### Where can I find which version and branch I'm on?
|
||||
|
||||
Please refer to [this FAQ entry](https://community.octoprint.org/t/how-can-i-find-out-the-version-of-octoprint-or-octopi-i-am-running/204/1).
|
||||
Please refer to [this FAQ entry](https://discourse.octoprint.org/t/how-can-i-find-out-the-version-of-octoprint-or-octopi-i-am-running/204/1).
|
||||
|
||||
### Where can I find those log files you keep talking about?
|
||||
|
||||
Please refer to [this FAQ entry](https://community.octoprint.org/t/where-can-i-find-octoprints-and-octopis-log-files/299/1).
|
||||
Please refer to [this FAQ entry](https://discourse.octoprint.org/t/where-can-i-find-octoprints-and-octopis-log-files/299/1).
|
||||
|
||||
### Where can I find my browser's error console?
|
||||
|
||||
@@ -302,7 +302,7 @@ the documentation.
|
||||
system - maybe that's the actual PR you have been waiting for to contribute :)
|
||||
2. If you plan to make **any large or otherwise disruptive changes to the
|
||||
code or appearance, please get in touch on the
|
||||
[forums](https://community.octoprint.org/c/development)** first so
|
||||
[forums](https://discourse.octoprint.org/c/development)** first so
|
||||
that we can determine if it's a good time for your specific pull
|
||||
request. It might be that we're currently in the process of making
|
||||
heavy changes to the code locations you'd target as well, or your
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||

|
||||
[](https://travis-ci.org/foosel/OctoPrint)
|
||||
[](https://community.octoprint.org)
|
||||
[](https://discourse.octoprint.org)
|
||||
[](https://chat.octoprint.org)
|
||||
[](https://twitter.com/OctoPrint3d)
|
||||
|
||||
@@ -13,7 +13,7 @@ and released under the [GNU Affero General Public License V3](http://www.gnu.org
|
||||
|
||||
Its website can be found at [octoprint.org](https://octoprint.org/?utm_source=github&utm_medium=readme).
|
||||
|
||||
The community forum is available at [community.octoprint.org](https://community.octoprint.org/?utm_source=github&utm_medium=readme).
|
||||
The community forum is available at [discourse.octoprint.org](https://discourse.octoprint.org/?utm_source=github&utm_medium=readme).
|
||||
|
||||
The official IRC channel is [#octoprint on freenode](https://chat.octoprint.org). Its logs can be found [here](https://freenode.logbot.info/octoprint).
|
||||
|
||||
@@ -31,16 +31,16 @@ If you enjoy OctoPrint, please consider becoming a regular supporter!**
|
||||
You are currently looking at the source code repository of OctoPrint. If you already installed it
|
||||
(e.g. by using the Raspberry Pi targeted distribution [OctoPi](https://github.com/guysoft/OctoPi)) and only
|
||||
want to find out how to use it, [the documentation](http://docs.octoprint.org/) and [the public wiki](https://github.com/foosel/OctoPrint/wiki)
|
||||
might be of more interest for you. You might also want to subscribe to join
|
||||
[the community forum at community.octoprint.org](https://community.octoprint.org) where there are other active users who might be
|
||||
might be of more interest for you. You might also want to subscribe to join
|
||||
[the community forum at discourse.octoprint.org](https://discourse.octoprint.org) where there are other active users who might be
|
||||
able to help you with any questions you might have.
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributions of all kinds are welcome, not only in the form of code but also with regards to the
|
||||
[official documentation](http://docs.octoprint.org/) or [the public wiki](https://github.com/foosel/OctoPrint/wiki), debugging help
|
||||
in the [bug tracker](https://github.com/foosel/OctoPrint/issues), support of other users on
|
||||
[the community forum at community.octoprint.org](https://community.octoprint.org)
|
||||
in the [bug tracker](https://github.com/foosel/OctoPrint/issues), support of other users on
|
||||
[the community forum at discourse.octoprint.org](https://discourse.octoprint.org)
|
||||
and also [financially](https://octoprint.org/support-octoprint/?utm_source=github&utm_medium=readme).
|
||||
|
||||
If you think something is bad about OctoPrint or its documentation the way it is, please help
|
||||
@@ -61,19 +61,18 @@ which is a custom SD card image that includes OctoPrint plus dependencies.
|
||||
The generic steps that should basically be done regardless of operating system
|
||||
and runtime environment are the following (as *regular
|
||||
user*, please keep your hands *off* of the `sudo` command here!) - this assumes
|
||||
you already have Python 2.7, 3.6 or 3.7, pip and virtualenv set up on your system:
|
||||
you already have Python 2.7, pip and virtualenv set up on your system:
|
||||
|
||||
1. Checkout OctoPrint: `git clone https://github.com/foosel/OctoPrint.git`
|
||||
2. Change into the OctoPrint folder: `cd OctoPrint`
|
||||
3. Create a user-owned virtual environment therein: `virtualenv venv` if your system default python version is
|
||||
python 2.7, otherwise you need to specify the version explicitly, e.g. `virtualenv --python=python2.7 venv`.
|
||||
3. Create a user-owned virtual environment therein: `virtualenv venv`
|
||||
4. Install OctoPrint *into that virtual environment*: `./venv/bin/pip install .`
|
||||
|
||||
You may then start the OctoPrint server via `/path/to/OctoPrint/venv/bin/octoprint`, see [Usage](#usage)
|
||||
for details.
|
||||
|
||||
After installation, please make sure you follow the first-run wizard and set up
|
||||
access control as necessary.
|
||||
access control as necessary.
|
||||
|
||||
## Dependencies
|
||||
|
||||
@@ -84,7 +83,7 @@ OctoPrint via `pip`:
|
||||
|
||||
You should do this every time after pulling from the repository, since the dependencies may have changed.
|
||||
|
||||
OctoPrint currently supports Python 2.7, 3.6 and 3.7.
|
||||
OctoPrint currently only supports Python 2.7.
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -143,8 +142,5 @@ be edited from OctoPrint's settings dialog.
|
||||
|
||||
## Special Thanks
|
||||
|
||||
Cross-browser testing services are kindly provided by [BrowserStack](https://www.browserstack.com/).
|
||||
|
||||
Profiling is done with the help of [PyVmMonitor](https://www.pyvmmonitor.com).
|
||||
|
||||
Error tracking is powered and sponsored by [Sentry](https://sentry.io).
|
||||
Cross-browser testing services are kindly provided by [BrowserStack](http://www.browserstack.com/).
|
||||
Profiling is done with the help of [PyVmMonitor](http://www.pyvmmonitor.com).
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
# Security Policy
|
||||
|
||||
## Supported Versions
|
||||
|
||||
Always update to the latest version of OctoPrint to keep up with security patches.
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
Email to security@octoprint.org.
|
||||
|
||||
For the sake of the userbase of OctoPrint please always disclose responsibly and with a 90+ day window.
|
||||
+26
-29
@@ -6,61 +6,58 @@ thanks to everyone who contributed!
|
||||
|
||||
## Patreon Patrons
|
||||
|
||||
* Alex Krilov
|
||||
* Andrew Moorby
|
||||
* Arnljot Arntsen
|
||||
* BigTreeTech
|
||||
* Boris Hussein
|
||||
* Brad Jackson
|
||||
* Brian E. Tyler
|
||||
* Christian Petropolis
|
||||
* Christian Wolf
|
||||
* COLLE+McVOY
|
||||
* D Brian Kimmel
|
||||
* DeltaMaker 3D Printers
|
||||
* Dennis Breining
|
||||
* Dorian Gray
|
||||
* Eric Betts
|
||||
* E3D BigBox
|
||||
* Ernesto Martinez
|
||||
* Franziska Kunsmann
|
||||
* GadgetAngel
|
||||
* F. Kunsmann
|
||||
* Frank Sander
|
||||
* George Robles
|
||||
* Greg Holloway
|
||||
* Hog Duske
|
||||
* Hugh Blemings
|
||||
* jean-claude migneault
|
||||
* günter weber
|
||||
* Hydra Research LLC
|
||||
* James Seigel
|
||||
* Jeff Moe
|
||||
* Jeff Renfer
|
||||
* Jefferson Hunt
|
||||
* Jeremiah Avery
|
||||
* Joseph Payne
|
||||
* Josh Daniels
|
||||
* Joshua Wills
|
||||
* Justin Kaufman
|
||||
* Kaile Riser
|
||||
* Kale Stedman
|
||||
* Kazuhiro Ogura
|
||||
* Kenneth Jiang
|
||||
* Kurt Wubbels
|
||||
* Kyle Menigoz
|
||||
* LA 3D Printer Repair
|
||||
* Lee Dohm
|
||||
* Kodama Inc.
|
||||
* Lewis Newby
|
||||
* LulzBot®
|
||||
* Makespace Madrid
|
||||
* Mark Walker
|
||||
* Martin Majewski
|
||||
* Martin Beattie
|
||||
* Michael Aumock
|
||||
* Miles Flavel
|
||||
* Mosaic Manufacturing
|
||||
* Neil R. Goldberg
|
||||
* Patrick Glyré
|
||||
* mitchell hirsch
|
||||
* Noe Ruiz
|
||||
* Patrick McGinnis
|
||||
* Prof Yuh Wen Chen
|
||||
* Randy C. Will
|
||||
* Ranjib Dey
|
||||
* Richard Michaud
|
||||
* Rigid3D
|
||||
* Robert Gusek
|
||||
* Ronald Griehsler
|
||||
* Sacha Telgenhof
|
||||
* Roger Strolz
|
||||
* Roy Cortes
|
||||
* Rudolff Vang
|
||||
* Samer Najia
|
||||
* Simon Hallam
|
||||
* Stefan Krister
|
||||
* Steve Thompson
|
||||
* Sven Mueller
|
||||
* Symbiotic Devices
|
||||
* Thomas Hatley
|
||||
* Timothy D Hoogland
|
||||
* Trent Shumay
|
||||
* Ulrich Kempken
|
||||
|
||||
and 1741 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [Github Sponsors](https://github.com/users/foosel/sponsorship)!
|
||||
and 1351 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
||||
@@ -9,7 +9,6 @@
|
||||
* [Bootstrap Slider Knockout Binding](https://github.com/cosminstefanxp/bootstrap-slider-knockout-binding): MIT
|
||||
* [Bootstrap Slider](http://seiyria.com/bootstrap-slider/): Apache License 2.0
|
||||
* [Bootstrap Tabdrop](http://www.eyecon.ro/bootstrap-tabdrop): Apache License 2.0
|
||||
* [css-element-queries](https://github.com/marcj/css-element-queries): MIT
|
||||
* [Detect Mobile Browser](http://detectmobilebrowsers.com/): Public Domain
|
||||
* [Flot](http://www.flotcharts.org/): MIT
|
||||
* [JavaScript MD5](https://github.com/blueimp/JavaScript-MD5): MIT
|
||||
@@ -37,6 +36,7 @@
|
||||
* [Awesome-Slugify](https://pypi.python.org/pypi/awesome-slugify): GPLv3
|
||||
* [chainmap](https://bitbucket.org/jeunice/chainmap): Python
|
||||
* [Click](http://click.pocoo.org/): BSD
|
||||
* [dateutil](https://dateutil.readthedocs.io/): BSD
|
||||
* [emoji](https://github.com/carpedm20/emoji/): BSD
|
||||
* [feedparser](https://github.com/kurtmckee/feedparser): BSD
|
||||
* [Flask](http://flask.pocoo.org/): BSD
|
||||
|
||||
@@ -1,529 +0,0 @@
|
||||
.. _sec-api-access:
|
||||
|
||||
**************
|
||||
Access control
|
||||
**************
|
||||
|
||||
.. contents::
|
||||
|
||||
.. _sec-api-access-permissions:
|
||||
|
||||
Permissions
|
||||
===========
|
||||
|
||||
.. _sec-api-access-permissions-list:
|
||||
|
||||
List all permissions
|
||||
--------------------
|
||||
|
||||
.. http:get:: /api/access/permissions
|
||||
|
||||
Retrieves all permissions available in the system.
|
||||
|
||||
Will return a :http:statuscode:`200` with a :ref:`permission list <sec-api-access-datamodel-permissions-list>`
|
||||
as body.
|
||||
|
||||
:status 200: No error
|
||||
|
||||
.. _sec-api-access-groups:
|
||||
|
||||
Groups
|
||||
======
|
||||
|
||||
.. _sec-api-access-groups-list:
|
||||
|
||||
Get group list
|
||||
--------------
|
||||
|
||||
.. http:get:: /api/access/groups
|
||||
|
||||
Retrieves all groups registered in the system.
|
||||
|
||||
Will return a :http:statuscode:`200` with a :ref:`group list <sec-api-access-datamodel-groups-list>`
|
||||
as body.
|
||||
|
||||
Requires the ``SETTINGS`` permission.
|
||||
|
||||
:status 200: No error
|
||||
|
||||
.. _sec-api-access-groups-add:
|
||||
|
||||
Add a new group
|
||||
---------------
|
||||
|
||||
.. http:post:: /api/access/groups
|
||||
|
||||
Adds a new group to the system.
|
||||
|
||||
Expects a :ref:`group registration request <sec-api-access-datamodel-groups-addgrouprequest>` as request body.
|
||||
|
||||
Will return a :ref:`group list response <sec-api-access-datamodel-groups-list>` on success.
|
||||
|
||||
Requires the ``SETTINGS`` permission.
|
||||
|
||||
:json key: The group's identifier
|
||||
:json name: The user's name
|
||||
:json description: A human readable description of the group
|
||||
:json permissions: The permissions to assign to the group
|
||||
:json subgroups: Subgroups assigned to the group
|
||||
:json default: Whether the group should be assigned to new users by default or not
|
||||
:status 200: No error
|
||||
:status 400: If any of the mandatory fields is missing or the request is otherwise
|
||||
invalid
|
||||
:status 409: A group with the provided key does already exist
|
||||
|
||||
.. _sec-api-access-groups-retrieve:
|
||||
|
||||
Retrieve a group
|
||||
----------------
|
||||
|
||||
.. http:get:: /api/access/groups/(string:key)
|
||||
|
||||
Retrieves an individual group record.
|
||||
|
||||
Will return a :http:statuscode:`200` with a :ref:`group record <sec-api-access-datamodel-groups-grouprecord>`
|
||||
as body.
|
||||
|
||||
Requires the ``SETTINGS`` permission.
|
||||
|
||||
:status 200: No error
|
||||
|
||||
.. _sec-api-access-groups-modify:
|
||||
|
||||
Update a group
|
||||
--------------
|
||||
|
||||
.. http:put:: /api/access/groups/(string:key)
|
||||
|
||||
Updates an existing group.
|
||||
|
||||
Expects a :ref:`group update request <sec-api-access-datamodel-groups-updategrouprequest>` as request body.
|
||||
|
||||
Will return a :ref:`group list response <sec-api-access-datamodel-groups-list>` on success.
|
||||
|
||||
Requires the ``SETTINGS`` permission.
|
||||
|
||||
:json description: A human readable description of the group
|
||||
:json permissions: The permissions to assign to the group
|
||||
:json subgroups: Subgroups assigned to the group
|
||||
:json default: Whether the group should be assigned to new users by default or not
|
||||
:status 200: No error
|
||||
:status 400: If any of the mandatory fields is missing or the request is otherwise
|
||||
invalid
|
||||
|
||||
.. _sec-api-access-groups-delete:
|
||||
|
||||
Delete a group
|
||||
--------------
|
||||
|
||||
.. http:delete:: /api/access/groups/(string:key)
|
||||
|
||||
Deletes a group.
|
||||
|
||||
Will return a :ref:`group list response <sec-api-access-datamodel-groups-list>` on success.
|
||||
|
||||
Requires the ``SETTINGS`` permission.
|
||||
|
||||
:status 200: No error
|
||||
|
||||
.. _sec-api-access-users:
|
||||
|
||||
Users
|
||||
=====
|
||||
|
||||
.. _sec-api-access-users-list:
|
||||
|
||||
Retrieve a list of users
|
||||
========================
|
||||
|
||||
.. http:get:: /api/access/users
|
||||
|
||||
Retrieves a list of all registered users in OctoPrint.
|
||||
|
||||
Will return a :http:statuscode:`200` with a :ref:`user list response <sec-api-access-datamodel-users-userlistresponse>`
|
||||
as body.
|
||||
|
||||
Requires the ``SETTINGS`` permission.
|
||||
|
||||
:status 200: No error
|
||||
|
||||
.. _sec-api-access-users-retrieve:
|
||||
|
||||
Retrieve a user
|
||||
---------------
|
||||
|
||||
.. http:get:: /api/access/users/(string:username)
|
||||
|
||||
Retrieves information about a user.
|
||||
|
||||
Will return a :http:statuscode:`200` with a :ref:`user record <sec-api-access-datamodel-users-userrecord>`
|
||||
as body.
|
||||
|
||||
Requires either the ``SETTINGS`` permission or to be logged in as the user.
|
||||
|
||||
:param username: Name of the user which to retrieve
|
||||
:status 200: No error
|
||||
:status 404: Unknown user
|
||||
|
||||
.. _sec-api-access-users-add:
|
||||
|
||||
Add a new user
|
||||
--------------
|
||||
|
||||
.. http:post:: /api/access/users
|
||||
|
||||
Adds a user to OctoPrint.
|
||||
|
||||
Expects a :ref:`user registration request <sec-api-access-datamodel-users-adduserrequest>`
|
||||
as request body.
|
||||
|
||||
Returns a list of registered users on success, see :ref:`Retrieve a list of users <sec-api-access-users-list>`.
|
||||
|
||||
Requires the ``SETTINGS`` permission.
|
||||
|
||||
:json name: The user's name
|
||||
:json password: The user's password
|
||||
:json active: Whether to activate the account (true) or not (false)
|
||||
:json admin: Whether to give the account admin rights (true) or not (false)
|
||||
:status 200: No error
|
||||
:status 400: If any of the mandatory fields is missing or the request is otherwise
|
||||
invalid
|
||||
:status 409: A user with the provided name does already exist
|
||||
|
||||
.. _sec-api-access-users-modify:
|
||||
|
||||
Update a user
|
||||
-------------
|
||||
|
||||
.. http:put:: /api/access/users/(string:username)
|
||||
|
||||
Updates a user record.
|
||||
|
||||
Expects a :ref:`user update request <sec-api-access-datamodel-users-updateuserrequest>`
|
||||
as request body.
|
||||
|
||||
Returns a list of registered users on success, see :ref:`Retrieve a list of users <sec-api-access-users-list>`.
|
||||
|
||||
Requires the ``SETTINGS`` permission.
|
||||
|
||||
:param username: Name of the user to update
|
||||
:json admin: Whether to mark the user as admin (true) or not (false), can be left out (no change)
|
||||
:json active: Whether to mark the account as activated (true) or deactivated (false), can be left out (no change)
|
||||
:status 200: No error
|
||||
:status 404: Unknown user
|
||||
|
||||
.. _sec-api-access-users-delete:
|
||||
|
||||
Delete a user
|
||||
-------------
|
||||
|
||||
.. http:delete:: /api/access/users/(string:username)
|
||||
|
||||
Delete a user record.
|
||||
|
||||
Returns a list of registered users on success, see :ref:`Retrieve a list of users <sec-api-access-users-list>`.
|
||||
|
||||
Requires the ``SETTINGS`` permission.
|
||||
|
||||
:param username: Name of the user to delete
|
||||
:status 200: No error
|
||||
:status 404: Unknown user
|
||||
|
||||
.. _sec-api-access-users-password:
|
||||
|
||||
Change a user's password
|
||||
------------------------
|
||||
|
||||
.. http:put:: /api/access/users/(string:username)/password
|
||||
|
||||
Changes the password of a user.
|
||||
|
||||
Expects a JSON object with a single property ``password`` as request body.
|
||||
|
||||
Requires the ``SETTINGS`` permission or to be logged in as the user.
|
||||
|
||||
:param username: Name of the user to change the password for
|
||||
:json password: The new password to set
|
||||
:status 200: No error
|
||||
:status 400: If the request doesn't contain a ``password`` property or the request
|
||||
is otherwise invalid
|
||||
:status 403: No admin rights and not logged in as the user
|
||||
:status 404: The user is unknown
|
||||
|
||||
.. _sec-api-access-users-settings-get:
|
||||
|
||||
Get a user's settings
|
||||
---------------------
|
||||
|
||||
.. http:get:: /api/access/users/(string:username)/settings
|
||||
|
||||
Retrieves a user's settings.
|
||||
|
||||
Will return a :http:statuscode:`200` with a JSON object representing the user's
|
||||
personal settings (if any) as body.
|
||||
|
||||
Requires the ``SETTINGS`` permission or to be logged in as the user.
|
||||
|
||||
:param username: Name of the user to retrieve the settings for
|
||||
:status 200: No error
|
||||
:status 403: No admin rights and not logged in as the user
|
||||
:status 404: The user is unknown
|
||||
|
||||
.. _sec-api-access-users-settings-set:
|
||||
|
||||
Update a user's settings
|
||||
------------------------
|
||||
|
||||
.. http:patch:: /api/access/users/(string:username)/settings
|
||||
|
||||
Updates a user's settings.
|
||||
|
||||
Expects a new settings JSON object to merge with the current settings as
|
||||
request body.
|
||||
|
||||
Requires the ``SETTINGS`` permission or to be logged in as the user.
|
||||
|
||||
:param username: Name of the user to retrieve the settings for
|
||||
:status 204: No error
|
||||
:status 403: No admin rights and not logged in as the user
|
||||
:status 404: The user is unknown
|
||||
|
||||
.. _sec-api-access-users-apikey-generate:
|
||||
|
||||
Regenerate a user's api key
|
||||
---------------------------
|
||||
|
||||
.. http:post:: /api/access/users/(string:username)/apikey
|
||||
|
||||
Generates a new API key for the user.
|
||||
|
||||
Does not expect a body. Will return the generated API key as ``apikey``
|
||||
property in the JSON object contained in the response body.
|
||||
|
||||
Requires the ``SETTINGS`` permission or to be logged in as the user.
|
||||
|
||||
:param username: Name of the user to retrieve the settings for
|
||||
:status 200: No error
|
||||
:status 403: No admin rights and not logged in as the user
|
||||
:status 404: The user is unknown
|
||||
|
||||
.. _sec-api-access-users-apikey-delete:
|
||||
|
||||
Delete a user's api key
|
||||
-----------------------
|
||||
|
||||
.. http:delete:: /api/access/users/(string:username)/apikey
|
||||
|
||||
Deletes a user's personal API key.
|
||||
|
||||
Requires the ``SETTINGS`` permission or to be logged in as the user.
|
||||
|
||||
:param username: Name of the user to retrieve the settings for
|
||||
:status 204: No error
|
||||
:status 403: No admin rights and not logged in as the user
|
||||
:status 404: The user is unknown
|
||||
|
||||
.. _sec-api-access-datamodel:
|
||||
|
||||
Data model
|
||||
==========
|
||||
|
||||
.. _sec-api-access-datamodel-permissions:
|
||||
|
||||
Permissions
|
||||
-----------
|
||||
|
||||
.. _sec-api-access-datamodel-permissions-list:
|
||||
|
||||
Permission list response
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``permissions``
|
||||
- 0..n
|
||||
- List of :ref:`permission records <sec-api-datamodel-access-permissions>`
|
||||
- The list of permissions
|
||||
|
||||
|
||||
.. _sec-api-access-datamodel-groups:
|
||||
|
||||
Groups
|
||||
------
|
||||
|
||||
.. _sec-api-access-datamodel-groups-list:
|
||||
|
||||
Group list response
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``groups``
|
||||
- 0..n
|
||||
- List of :ref:`group records <sec-api-datamodel-access-groups>`
|
||||
- The list of groups
|
||||
|
||||
.. _sec-api-access-datamodel-groups-addgrouprequest:
|
||||
|
||||
Group registration request
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``key``
|
||||
- 1
|
||||
- string
|
||||
- The group's identifier
|
||||
* - ``name``
|
||||
- 1
|
||||
- string
|
||||
- The group's name
|
||||
* - ``description``
|
||||
- 0..1
|
||||
- string
|
||||
- The group's description. Set to empty if not provided.
|
||||
* - ``permissions``
|
||||
- 1..n
|
||||
- List of string
|
||||
- A list of identifier's of permissions to assign to the group
|
||||
* - ``subgroups``
|
||||
- 0..n
|
||||
- List of string
|
||||
- A list of identifier's of groups to assign to the group as subgroups
|
||||
* - ``default``
|
||||
- 0..1
|
||||
- boolean
|
||||
- Whether to assign the group to new users by default (true) or not (false, default value)
|
||||
|
||||
.. _sec-api-access-datamodel-groups-updategrouprequest:
|
||||
|
||||
Group update request
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``description``
|
||||
- 0..1
|
||||
- string
|
||||
- The group's description. Set to empty if not provided.
|
||||
* - ``permissions``
|
||||
- 1..n
|
||||
- List of string
|
||||
- A list of identifier's of permissions to assign to the group
|
||||
* - ``subgroups``
|
||||
- 0..n
|
||||
- List of string
|
||||
- A list of identifier's of groups to assign to the group as subgroups
|
||||
* - ``default``
|
||||
- 0..1
|
||||
- boolean
|
||||
- Whether to assign the group to new users by default (true) or not (false, default value)
|
||||
|
||||
|
||||
.. _sec-api-access-datamodel-users:
|
||||
|
||||
Users
|
||||
-----
|
||||
|
||||
.. _sec-api-access-datamodel-users-userlistresponse:
|
||||
|
||||
User list response
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``users``
|
||||
- 0..n
|
||||
- List of :ref:`user records <sec-api-datamodel-access-users>`
|
||||
- The list of users
|
||||
|
||||
.. _sec-api-access-datamodel-users-adduserrequest:
|
||||
|
||||
User registration request
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``name``
|
||||
- 1
|
||||
- string
|
||||
- The user's name
|
||||
* - ``password``
|
||||
- 1
|
||||
- string
|
||||
- The user's password
|
||||
* - ``active``
|
||||
- 1
|
||||
- bool
|
||||
- Whether to activate the account (true) or not (false)
|
||||
* - ``groups``
|
||||
- 0..n
|
||||
- List of string
|
||||
- A list of identifiers of groups to assign to the user
|
||||
* - ``permissions``
|
||||
- 0..n
|
||||
- List of string
|
||||
- A list of identifiers of permissions to assign to the user
|
||||
|
||||
.. _sec-api-access-datamodel-users-updateuserrequest:
|
||||
|
||||
User update request
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``active``
|
||||
- 0..1
|
||||
- bool
|
||||
- If present will set the user's active flag to the provided value. True for
|
||||
activating the account, false for deactivating it.
|
||||
* - ``groups``
|
||||
- 0..n
|
||||
- List of string
|
||||
- A list of identifiers of groups to assign to the user
|
||||
* - ``permissions``
|
||||
- 0..n
|
||||
- List of string
|
||||
- A list of identifiers of permissions to assign to the user
|
||||
@@ -0,0 +1,170 @@
|
||||
.. _sec-api-apps:
|
||||
|
||||
****
|
||||
Apps
|
||||
****
|
||||
|
||||
.. contents::
|
||||
|
||||
.. _sec-api-apps-sessionkey:
|
||||
|
||||
Session Keys
|
||||
============
|
||||
|
||||
OctoPrint offers a special API key type for apps to use, the so called App Session Key. These keys have a time based
|
||||
validity and are generated by OctoPrint for requesting apps.
|
||||
|
||||
Obtaining those keys is based on a handshake procedure backed by cryptographic signatures using RSA. OctoPrint needs to
|
||||
be aware of apps and their associated public keys (this can be achieved either via entries in ``config.yaml`` or by
|
||||
installing app specific plugins which implement the ``AppPlugin`` type).
|
||||
|
||||
Apps can be registered within OctoPrint via ``config.yaml`` by adding them to the ``api`` > ``apps`` section, using the
|
||||
application's id concatenated with its version as key, with the public key provided as item ``pubkey`` (stripped of the
|
||||
``BEGIN RSA PUBLIC KEY`` and ``END RSA PUBLIC KEY`` separators and also newlines) and optionally also whether the app is
|
||||
enabled or not (defaults to enabled, so can be left out if it's not to be set to disabled explicitly).
|
||||
|
||||
Example:
|
||||
|
||||
.. sourcecode:: yaml
|
||||
|
||||
api:
|
||||
apps:
|
||||
"com.example.my_octoprint_app:0.9":
|
||||
pubkey: MEgCQQDYkr5Fv/YXK5ZL1uwRN4A61IagZaYLGqJ5JJGFo8wDrmpAMRqE9kK4+5hIDblC5DzfEr5oP7OA3tRO48Rf5yInAgMBAAE=
|
||||
enabled: false
|
||||
"com.example.my_octoprint_app:1.0":
|
||||
pubkey: MEgCQQCIWfi7Nc8bcnfZJJtA6a4RyMC+sKBlMOb25OVNNB4L2v0TiGO72jVKR4osvb4oztlbRW5GkdiY0T2LJcfDYvkJAgMBAAE=
|
||||
|
||||
In the example, the app ``com.example.my_octoprint_app`` in version 0.9 has been disabled (e.g. due to the key having
|
||||
leaked) whereas version 1.0 is fully registered with OctoPrint and may verify app session keys.
|
||||
|
||||
|
||||
.. _sec-api-apps-sessionkey-workflow:
|
||||
|
||||
Workflow
|
||||
--------
|
||||
|
||||
Apps perform the handshake by first requesting a temporary key with very limited validity,
|
||||
then sending a message back to OctoPrint containing their id, version, the temporary key and a signature created with their
|
||||
private key over these three pieces of data. OctoPrint then tries to verify the signature and if successful unlocks the
|
||||
key to be used as a fully recognized API key.
|
||||
|
||||
For performing the handshake a special API exists within OctoPrint for which no API key is needed which is described below.
|
||||
|
||||
.. _sec-api-apps-sessionkey-get:
|
||||
|
||||
Obtaining a temporary session key
|
||||
---------------------------------
|
||||
|
||||
.. http:get:: /apps/auth
|
||||
|
||||
Retrieve a temporary session key with a minimum validity. It can only be used as a proper API key after having been
|
||||
:ref:`verified <sec-api-apps-sessionkey-verify>`.
|
||||
|
||||
Returns the temporary session key and the timestamp until it's valid.
|
||||
|
||||
**Example**:
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /apps/auth HTTP/1.1
|
||||
Host: example.com
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"unverifiedKey": "F43A844750F74AD080FE9F438D47B33C",
|
||||
"validUntil": 1416220357.011
|
||||
}
|
||||
|
||||
:statuscode 200: No error
|
||||
|
||||
.. _sec-api-apps-sessionkey-verify:
|
||||
|
||||
Verifying a temporary session key
|
||||
---------------------------------
|
||||
|
||||
.. http:post:: /apps/auth
|
||||
|
||||
Verify a formerly :ref:`retrieved <sec-api-apps-sessionkey-get>` temporary session key by providing credentials and a
|
||||
cryptographic signature over these credentials and the temporary key.
|
||||
|
||||
Returns the now verified session key and the new validity.
|
||||
|
||||
**Example**:
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /apps/auth HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"appid": "com.example.my_octoprint_app",
|
||||
"appversion": "1.0",
|
||||
"key": "F43A844750F74AD080FE9F438D47B33C",
|
||||
"_sig": "LGVCiolQWDc4AVn1DOcWljY0cFQxWF4pldVveUjjmL9JhiL0LnCKBbGwZ/CwKBWswFAxPaxQ0kDusVdOmCUa/w=="
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"key": "F43A844750F74AD080FE9F438D47B33C",
|
||||
"validUntil": 1416227497.011
|
||||
}
|
||||
|
||||
.. _sec-api-apps-sessionkey-signature:
|
||||
|
||||
Creating the signature
|
||||
----------------------
|
||||
|
||||
The signature is created by concatenating the ``appid``, ``appversion`` and ``key`` fields, separated by a ``:`` (colon),
|
||||
signing the result with the app's private key using SHA-1 and then BASE64-encoding the result, stripping newlines.
|
||||
|
||||
Example for signature generation using Python and the `Python RSA library <https://pypi.python.org/pypi/rsa>`_:
|
||||
|
||||
.. sourcecode:: python
|
||||
|
||||
import base64
|
||||
import rsa
|
||||
|
||||
appid = "com.example.my_octoprint_app"
|
||||
version = "1.0"
|
||||
unverified_key = "F43A844750F74AD080FE9F438D47B33C"
|
||||
message_to_sign = appid + ":" + version + ":" + unverified_key
|
||||
// => "com.example.my_octoprint_app:1.0:F43A844750F74AD080FE9F438D47B33C"
|
||||
|
||||
private_key = rsa.PrivateKey.load_pkcs1("...")
|
||||
signature = base64.encodestring(rsa.sign(message_to_sign, private_key, "SHA-1")).replace("\n", "")
|
||||
// => "LGVCiolQWDc4AVn1DOcWljY0cFQxWF4pldVveUjjmL9JhiL0LnCKBbGwZ/CwKBWswFAxPaxQ0kDusVdOmCUa/w=="
|
||||
|
||||
|
||||
.. _sec-api-apps-sessionkey-testing:
|
||||
|
||||
Testing your implementation
|
||||
---------------------------
|
||||
|
||||
If you want to use app session keys, here is the key pair with which the above examples were created, in order for you
|
||||
to verify your signature implementation::
|
||||
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIBPQIBAAJBAIhZ+Ls1zxtyd9kkm0DprhHIwL6woGUw5vbk5U00Hgva/ROIY7va
|
||||
NUpHiiy9vijO2VtFbkaR2JjRPYslx8Ni+QkCAwEAAQJARK4lFo+FEcs3yR2iQjEy
|
||||
p+yaAbNQJ4hZXlVvltLAYICzOM3kyKx53/eKU59NjskLz9q6QxfleymYPWAgl4NW
|
||||
fQIjAJVH8MjwNcaAquTM9z2OiFi3OC8WgaKOi5W/T+r2+B70wG8CHwDp08dqOZ/u
|
||||
xcBiy4Wzpcme9bckqoVuS3gWMm+YqgcCIwCMFU07kkY0NyumtzxPdIA4F/7OGSWf
|
||||
IHqWFEfvasAddHlbAh8A5UgkB3Zf7Bt+7aFSBnlvve6FWm/XDPL12xYztYgrAiIa
|
||||
W3miN6FjIm+8TDowrk+nyYXG2GZefeY7QXOjYr6tlDn0
|
||||
-----END RSA PRIVATE KEY-----
|
||||
|
||||
-----BEGIN RSA PUBLIC KEY-----
|
||||
MEgCQQCIWfi7Nc8bcnfZJJtA6a4RyMC+sKBlMOb25OVNNB4L2v0TiGO72jVKR4os
|
||||
vb4oztlbRW5GkdiY0T2LJcfDYvkJAgMBAAE=
|
||||
-----END RSA PUBLIC KEY-----
|
||||
|
||||
@@ -16,8 +16,6 @@ Get connection settings
|
||||
Retrieve the current connection settings, including information regarding the available baudrates and
|
||||
serial ports and the current connection state.
|
||||
|
||||
Requires the ``STATUS`` permission.
|
||||
|
||||
**Example**
|
||||
|
||||
.. sourcecode:: http
|
||||
@@ -61,7 +59,7 @@ Issue a connection command
|
||||
Issue a connection command. Currently available command are:
|
||||
|
||||
connect
|
||||
Instructs OctoPrint to connect or, if already connected, reconnect to the printer. Additional parameters are:
|
||||
Instructs OctoPrint to connect to the printer. Additional parameters are:
|
||||
|
||||
* ``port``: Optional, specific port to connect to. If not set the current ``portPreference`` will be used, or if
|
||||
no preference is available auto detection will be attempted.
|
||||
@@ -83,7 +81,7 @@ Issue a connection command
|
||||
for the lost acknowledgment should always be properly investigated and removed instead of depending on this
|
||||
"symptom solver".
|
||||
|
||||
Requires the ``CONNECTION`` permission.
|
||||
Requires user rights.
|
||||
|
||||
**Example Connect Request**
|
||||
|
||||
|
||||
@@ -218,17 +218,6 @@ Progress information
|
||||
- 1
|
||||
- Integer
|
||||
- Estimate of time left to print, in seconds
|
||||
* - ``printTimeLeftOrigin``
|
||||
- 1
|
||||
- String
|
||||
- Origin of the current time left estimate. Can currently be either of:
|
||||
|
||||
* ``linear``: based on an linear approximation of the progress in file in bytes vs time
|
||||
* ``analysis``: based on an analysis of the file
|
||||
* ``estimate``: calculated estimate after stabilization of linear estimation
|
||||
* ``average``: based on the average total from past prints of the same model against the same printer profile
|
||||
* ``mixed-analysis``: mixture of ``estimate`` and ``analysis``
|
||||
* ``mixed-average``: mixture of ``estimate`` and ``average``
|
||||
|
||||
.. _sec-api-datamodel-files:
|
||||
|
||||
@@ -480,173 +469,3 @@ References
|
||||
- URL
|
||||
- The model from which this file was generated (e.g. an STL, currently not used). Never present for
|
||||
folders.
|
||||
|
||||
.. _sec-api-datamodel-access:
|
||||
|
||||
Access control
|
||||
==============
|
||||
|
||||
.. _sec-api-datamodel-access-users:
|
||||
|
||||
User record
|
||||
-----------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``name``
|
||||
- 1
|
||||
- string
|
||||
- The user's name
|
||||
* - ``active``
|
||||
- 1
|
||||
- bool
|
||||
- Whether the user's account is active (true) or not (false)
|
||||
* - ``user``
|
||||
- 1
|
||||
- bool
|
||||
- Whether the user has user rights. Should always be true. Deprecated as of 1.4.0, use the ``users`` group instead.
|
||||
* - ``admin``
|
||||
- 1
|
||||
- bool
|
||||
- Whether the user has admin rights (true) or not (false). Deprecated as of 1.4.0, use the ``admins`` group instead.
|
||||
* - ``apikey``
|
||||
- 0..1
|
||||
- string
|
||||
- The user's personal API key
|
||||
* - ``settings``
|
||||
- 1
|
||||
- object
|
||||
- The user's personal settings, might be an empty object.
|
||||
* - ``groups``
|
||||
- 1..n
|
||||
- List of string
|
||||
- Groups assigned to the user
|
||||
* - ``needs``
|
||||
- 1
|
||||
- :ref:`Needs object <sec-api-datamodel-access-needs>`
|
||||
- Effective needs of the user
|
||||
* - ``permissions``
|
||||
- 0..n
|
||||
- List of :ref:`Permissions <sec-api-datamodel-access-permissions>`
|
||||
- The list of permissions assigned to the user (note: this does not include implicit permissions inherit from groups).
|
||||
|
||||
.. _sec-api-datamodel-access-permissions:
|
||||
|
||||
Permission record
|
||||
-----------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``key``
|
||||
- 1
|
||||
- string
|
||||
- The permission's identifier
|
||||
* - ``name``
|
||||
- 1
|
||||
- string
|
||||
- The permission's name
|
||||
* - ``dangerous``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether the permission should be considered dangerous due to a high reponsibility (true) or not (false).
|
||||
* - ``default_groups``
|
||||
- 1
|
||||
- List of string
|
||||
- List of group identifiers for which this permission is enabled by default
|
||||
* - ``description``
|
||||
- 1
|
||||
- string
|
||||
- Human readable description of the permission
|
||||
* - ``needs``
|
||||
- 1
|
||||
- :ref:`Needs object <sec-api-access-datamodel-general-needs>`
|
||||
- Needs assigned to the permission
|
||||
|
||||
.. _sec-api-datamodel-access-groups:
|
||||
|
||||
Group record
|
||||
------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``key``
|
||||
- 1
|
||||
- string
|
||||
- The group's identifier
|
||||
* - ``name``
|
||||
- 1
|
||||
- string
|
||||
- The group's name
|
||||
* - ``description``
|
||||
- 1
|
||||
- string
|
||||
- A human readable description of the group
|
||||
* - ``permissions``
|
||||
- 0..n
|
||||
- List of :ref:`Permissions <sec-api-datamodel-access-permissions>`
|
||||
- The list of permissions assigned to the group (note: this does not include implicit permissions inherited from
|
||||
subgroups).
|
||||
* - ``subgroups``
|
||||
- 0..n
|
||||
- List of :ref:`Groups <sec-api-datamodel-access-groups>`
|
||||
- Subgroups assigned to the group
|
||||
* - ``needs``
|
||||
- 1
|
||||
- :ref:`Needs object <sec-api-datamodel-access-needs>`
|
||||
- Effective needs of the group
|
||||
* - ``default``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether this is a default group (true) or not (false)
|
||||
* - ``removable``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether this group can be removed (true) or not (false)
|
||||
* - ``changeable``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether this group can be modified (true) or not (false)
|
||||
* - ``toggleable``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether this group can be assigned to users or other groups (true) or not (false)
|
||||
|
||||
.. _sec-api-datamodel-access-needs:
|
||||
|
||||
Needs
|
||||
-----
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``role``
|
||||
- 0..1
|
||||
- List of string
|
||||
- List of ``role`` needs
|
||||
* - ``group``
|
||||
- 0..1
|
||||
- List of string
|
||||
- List of ``group`` needs
|
||||
+3
-15
@@ -21,8 +21,6 @@ Retrieve all files
|
||||
|
||||
Returns a :ref:`Retrieve response <sec-api-fileops-datamodel-retrieveresponse>`.
|
||||
|
||||
Requires the ``FILES_LIST`` permission.
|
||||
|
||||
**Example 1**:
|
||||
|
||||
Fetch only the files and folders from the root folder.
|
||||
@@ -252,8 +250,6 @@ Retrieve files from specific location
|
||||
|
||||
Returns a :ref:`Retrieve response <sec-api-fileops-datamodel-retrieveresponse>`.
|
||||
|
||||
Requires the ``FILES_LIST`` permission.
|
||||
|
||||
**Example**:
|
||||
|
||||
.. sourcecode:: http
|
||||
@@ -331,7 +327,7 @@ Upload file or create folder
|
||||
Returns a :http:statuscode:`201` response with a ``Location`` header set to the management URL of the uploaded
|
||||
file and an :ref:`Upload Response <sec-api-fileops-datamodel-uploadresponse>` as the body upon successful completion.
|
||||
|
||||
Requires the ``FILES_UPLOAD`` permission.
|
||||
Requires user rights.
|
||||
|
||||
**Example for uploading a file**
|
||||
|
||||
@@ -508,8 +504,6 @@ Retrieve a specific file's or folder's information
|
||||
On success, a :http:statuscode:`200` is returned, with a :ref:`file information item <sec-api-datamodel-files-file>`
|
||||
as the response body.
|
||||
|
||||
Requires the ``FILES_LIST`` permission.
|
||||
|
||||
**Example**
|
||||
|
||||
.. sourcecode:: http
|
||||
@@ -574,8 +568,6 @@ Issue a file command
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
Requires the ``FILES_SELECT`` permission.
|
||||
|
||||
slice
|
||||
Slices an STL file into GCODE. Note that this is an asynchronous operation that will take place in the background
|
||||
after the response has been sent back to the client. Additional parameters are:
|
||||
@@ -606,8 +598,6 @@ Issue a file command
|
||||
Upon success, a status code of :http:statuscode:`202` and a :ref:`sec-api-datamodel-files-fileabridged` in the response
|
||||
body will be returned.
|
||||
|
||||
Requires the ``SLICE`` permission.
|
||||
|
||||
copy
|
||||
Copies the file or folder to a new ``destination`` on the same ``location``. Additional parameters are:
|
||||
|
||||
@@ -619,8 +609,6 @@ Issue a file command
|
||||
Upon success, a status code of :http:statuscode:`201` and a :ref:`sec-api-datamodel-files-fileabridged` in the response
|
||||
body will be returned.
|
||||
|
||||
Requires the ``FILES_UPLOAD`` permission.
|
||||
|
||||
move
|
||||
Moves the file or folder to a new ``destination`` on the same ``location``. Additional parameters are:
|
||||
|
||||
@@ -634,7 +622,7 @@ Issue a file command
|
||||
Upon success, a status code of :http:statuscode:`201` and a :ref:`sec-api-datamodel-files-fileabridged` in the response
|
||||
body will be returned.
|
||||
|
||||
Requires the ``FILES_UPLOAD`` permission.
|
||||
Requires user rights.
|
||||
|
||||
**Example Select Request**
|
||||
|
||||
@@ -785,7 +773,7 @@ Delete file
|
||||
|
||||
Returns a :http:statuscode:`204` after successful deletion.
|
||||
|
||||
Requires the ``FILES_DELETE`` permission.
|
||||
Requires user rights.
|
||||
|
||||
**Example Request**
|
||||
|
||||
|
||||
+43
-77
@@ -11,9 +11,9 @@ General information
|
||||
Authorization
|
||||
=============
|
||||
|
||||
If :ref:`Access Control <sec-features-access_control>` is enabled OctoPrint's API expects an API key to be supplied with each request. This API
|
||||
key can be either the globally configured one, a user specific one or an app and user specific one as generated by the
|
||||
authorization workflow implemented by the bundled :ref:`Application Keys Plugin <sec-bundledplugins-appkeys>` (since 1.3.10).
|
||||
OctoPrint's API expects an API key to be supplied with each request. This API key can be either the globally
|
||||
configured one, a user specific one if "Access Control" is enabled or an app and user specific one as generated
|
||||
by the authorization workflow implemented by the bundled :ref:`Application Keys Plugin <sec-bundledplugins-appkeys>` (since 1.3.10).
|
||||
|
||||
Clients are advised to implement the :ref:`Application Keys Plugin workflow <sec-bundledplugins-appkeys-workflow>` first and
|
||||
fallback on directing the user to manually supply the the user specific API key. The global key should rarely be used.
|
||||
@@ -26,6 +26,8 @@ The API key must be supplied in the custom HTTP header ``X-Api-Key``, e.g.
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
If it is missing or included but invalid, OctoPrint will directly return a response with status :http:statuscode:`403`.
|
||||
|
||||
For testing purposes it is also possible to supply the API key via a query parameter ``apikey``, e.g.
|
||||
|
||||
.. sourcecode:: http
|
||||
@@ -35,24 +37,6 @@ For testing purposes it is also possible to supply the API key via a query param
|
||||
|
||||
Please be advised that clients should use the header field variant if at all possible.
|
||||
|
||||
If the key is missing or invalid, OctoPrint will treat the request as it would any unauthenticated anonymous request to the endpoint.
|
||||
Consequently, if the bundled :ref:`ForceLogin plugin <sec-bundledplugins-forcelogin>` is active (which is the default), that means
|
||||
that any requests without or with an invalid API key targeting other API endpoints than :ref:`Login <sec-api-general-login>`
|
||||
will be denied with a :http:statuscode:`403`.
|
||||
|
||||
.. warning::
|
||||
|
||||
If :ref:`Access Control <sec-features-access_control>` is disabled, OctoPrint will treat any unauthenticated anonymous requests and thus also requests
|
||||
with an invalid or outright missing API key as requests with full admin rights!
|
||||
|
||||
.. note::
|
||||
|
||||
The API key requirements changed in 1.3.11. Up to that version, even if Access Control was disabled, all requests needed to
|
||||
be supplied with an API Key. To make the webinterface work under these circumstances, an unauthenticated anonymous API key was injected into the
|
||||
HTML page and also available on the :ref:`Push API <sec-api-push>`. The presence and ready availability of this unauthenticated
|
||||
anonymous "UI API key" caused confusion and false alarm among users and didn't contribute to the security of the platform in a
|
||||
meaningful way, so it was finally abandoned in 1.3.11.
|
||||
|
||||
.. _fig-api-general-globalapikey:
|
||||
.. figure:: ../images/settings-global-api-key.png
|
||||
:align: center
|
||||
@@ -74,6 +58,11 @@ will be denied with a :http:statuscode:`403`.
|
||||
|
||||
The API key options in the "Change password" dialog. Users can generate and revoke their custom API key here.
|
||||
|
||||
.. note::
|
||||
OctoPrint's web interface uses a custom API key that is freshly generated on every server start. This key is not
|
||||
intended to be used by any other client and would not be very useful in any case, since it basically represents
|
||||
a completely anonymous client.
|
||||
|
||||
.. _sec-api-general-contenttype:
|
||||
|
||||
Content Type
|
||||
@@ -148,14 +137,8 @@ Login
|
||||
via the ``passive`` flag.
|
||||
|
||||
Will return a :http:statuscode:`200` with a :ref:`login response <sec-api-general-datamodel-login>` on successful
|
||||
login, whether active or passive. The active (username/password) login may also return a :http:statuscode:`403` in
|
||||
case of a username/password mismatch, unknown user or a deactivated account.
|
||||
|
||||
.. warning::
|
||||
|
||||
Previous versions of this API endpoint did return a :http:statuscode:`401` in case of a username/password
|
||||
mismatch or an unknown user. That was incompatible with basic authentication since it was a wrong use of
|
||||
the :http:statuscode:`401` code and got therefore changed as part of a bug fix.
|
||||
login, whether active or passive. The active (username/password) login may also return a :http:statuscode:`401` in
|
||||
case of a username/password mismatch or unknown user and a :http:statuscode:`403` in case of a deactivated account.
|
||||
|
||||
:json passive: If present, performs a passive login only, returning information about the current user that's
|
||||
active either through an existing session or the used API key
|
||||
@@ -163,7 +146,8 @@ Login
|
||||
:json pass: (active login only) Password
|
||||
:json remember: (active login only) Whether to set a "remember me" cookie on the session
|
||||
:status 200: Successful login
|
||||
:status 403: Username/password mismatch, unknown user or deactivated account
|
||||
:status 401: Username/password mismatch or unknown user
|
||||
:status 403: Deactivated account
|
||||
|
||||
.. _sec-api-general-logout:
|
||||
|
||||
@@ -180,20 +164,6 @@ Logout
|
||||
|
||||
:status 204: No error
|
||||
|
||||
.. _sec-api-general-currentuser:
|
||||
|
||||
Current User
|
||||
============
|
||||
|
||||
.. http:get:: /api/currentuser
|
||||
|
||||
Retrieves information about the current user.
|
||||
|
||||
Will return a :http:statuscode:`200` with a :ref:`current user object <sec-api-general-datamodel-currentuser>`
|
||||
as body.
|
||||
|
||||
:status 200: No error
|
||||
|
||||
.. _sec-api-general-datamodel:
|
||||
|
||||
Data model
|
||||
@@ -204,30 +174,6 @@ Data model
|
||||
Login response
|
||||
--------------
|
||||
|
||||
The Login response is a :ref:`user record <sec-api-datamodel-access-users>` extended by the following fields:
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``session``
|
||||
- 1
|
||||
- string
|
||||
- The session key, can be used to authenticate with the ``auth`` message on the :ref:`push API <sec-api-push>`.
|
||||
* - ``_is_external_client``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether the client that made the request got detected as external from the local network or not.
|
||||
|
||||
.. _sec-api-general-datamodel-currentuser:
|
||||
|
||||
Current user
|
||||
------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
@@ -239,12 +185,32 @@ Current user
|
||||
* - ``name``
|
||||
- 1
|
||||
- string
|
||||
- The id of the current user. Unset if guest.
|
||||
* - ``permissions``
|
||||
- 0..n
|
||||
- List of :ref:`permission records <sec-api-datamodel-access-permissions>`
|
||||
- The effective list of permissions assigned to the user
|
||||
* - ``groups``
|
||||
- 0..n
|
||||
- List of :ref:`permission records <sec-api-datamodel-access-groups>`
|
||||
- The list of groups assigned to the user
|
||||
- the user's name/id
|
||||
* - ``active``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether the user's account is active or not
|
||||
* - ``admin``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether the user has admin rights or not
|
||||
* - ``user``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether the user has user rights or not (always ``true``)
|
||||
* - ``apikey``
|
||||
- 1
|
||||
- string or None
|
||||
- The user's API key, if set
|
||||
* - ``settings``
|
||||
- 1
|
||||
- dict
|
||||
- The user's settings, if any
|
||||
* - ``session``
|
||||
- 1
|
||||
- string
|
||||
- The session key, can be used to authenticate with the ``auth`` message on the :ref:`push API <sec-api-push>`.
|
||||
* - ``_is_external_client``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether the client that made the request got detected as external from the local network or not.
|
||||
+2
-1
@@ -9,6 +9,7 @@ REST API
|
||||
|
||||
general.rst
|
||||
version.rst
|
||||
apps.rst
|
||||
connection.rst
|
||||
files.rst
|
||||
job.rst
|
||||
@@ -20,7 +21,7 @@ REST API
|
||||
slicing.rst
|
||||
system.rst
|
||||
timelapse.rst
|
||||
access.rst
|
||||
users.rst
|
||||
util.rst
|
||||
wizard.rst
|
||||
push.rst
|
||||
|
||||
+3
-10
@@ -57,7 +57,7 @@ Issue a job command
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
Requires the ``PRINT`` permission.
|
||||
Requires user rights.
|
||||
|
||||
**Example Start Request**
|
||||
|
||||
@@ -180,8 +180,6 @@ Retrieve information about the current job
|
||||
|
||||
Returns a :http:statuscode:`200` with a :ref:`sec-api-job-datamodel-response` in the body.
|
||||
|
||||
Requires the ``STATUS`` permission.
|
||||
|
||||
**Example**
|
||||
|
||||
.. sourcecode:: http
|
||||
@@ -214,8 +212,7 @@ Retrieve information about the current job
|
||||
"filepos": 337942,
|
||||
"printTime": 276,
|
||||
"printTimeLeft": 912
|
||||
},
|
||||
"state": "Printing"
|
||||
}
|
||||
}
|
||||
|
||||
:statuscode 200: No error
|
||||
@@ -246,8 +243,4 @@ Job information response
|
||||
- 1
|
||||
- :ref:`sec-api-datamodel-jobs-progress`
|
||||
- Information regarding the progress of the current print job
|
||||
* - ``state``
|
||||
- 1
|
||||
- String
|
||||
- A textual representation of the current state of the job, i.e. "Operational", "Printing", "Pausing", "Paused",
|
||||
"Cancelling", "Error" or "Offline".
|
||||
|
||||
@@ -6,7 +6,7 @@ Languages
|
||||
|
||||
.. note::
|
||||
|
||||
All language pack management operations require the ``SETTINGS`` permission.
|
||||
All language pack management operations require admin rights.
|
||||
|
||||
.. contents::
|
||||
|
||||
|
||||
+11
-214
@@ -22,11 +22,6 @@ Bed
|
||||
corresponding resource returns temperature information including an optional history. Note that Bed commands
|
||||
are only available if the currently selected printer profile has a heated bed.
|
||||
See :ref:`sec-api-printer-bedcommand`.
|
||||
Chamber
|
||||
Chamber commands allow setting the temperature and temperature offset for the printer's heated chamber. Querying
|
||||
the corresponding resource returns temperature information including an option history. Note that Chamber commands
|
||||
are only available if the currently selected printer profile has a heated chamber.
|
||||
See :ref:`sec-api-printer-chambercommand`.
|
||||
SD card
|
||||
SD commands allow initialization, refresh and release of the printer's SD card (if available). Querying the
|
||||
corresponding resource returns the current SD card state.
|
||||
@@ -80,8 +75,6 @@ Retrieve the current printer state
|
||||
Returns a :http:statuscode:`200` with a :ref:`Full State Response <sec-api-printer-datamodel-fullstate>` in the
|
||||
body upon success.
|
||||
|
||||
Requires the ``STATUS`` permission.
|
||||
|
||||
**Example 1**
|
||||
|
||||
Include temperature history data, but limit it to two entries.
|
||||
@@ -226,7 +219,7 @@ Issue a print head command
|
||||
axes values are relative amounts) or to absolute position (provided axes values are coordinates)
|
||||
* ``speed``: Optional. Speed at which to move. If not provided, minimum speed for all selected axes from printer
|
||||
profile will be used. If provided but ``false``, no speed parameter will be appended to the command. Otherwise
|
||||
interpreted as an integer signifying the speed in mm/min, to append to the command.
|
||||
interpreted as an integer signifying the speed in mm/s, to append to the command.
|
||||
|
||||
home
|
||||
Homes the print head in all of the given axes. Additional parameters are:
|
||||
@@ -243,7 +236,7 @@ Issue a print head command
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
Requires the ``CONTROL`` permission.
|
||||
Requires user rights.
|
||||
|
||||
**Example Jog Request**
|
||||
|
||||
@@ -352,7 +345,7 @@ Issue a tool command
|
||||
Sets the given target temperature on the printer's tools. Additional parameters:
|
||||
|
||||
* ``targets``: Target temperature(s) to set, properties must match the format ``tool{n}`` with ``n`` being the
|
||||
tool's index starting with 0. A value of `0` will turn the heater off.
|
||||
tool's index starting with 0.
|
||||
|
||||
offset
|
||||
Sets the given temperature offset on the printer's tools. Additional parameters:
|
||||
@@ -369,8 +362,6 @@ Issue a tool command
|
||||
Extrudes the given amount of filament from the currently selected tool. Additional parameters:
|
||||
|
||||
* ``amount``: The amount of filament to extrude in mm. May be negative to retract.
|
||||
* ``speed``: Optional. Speed at which to extrude. If not provided, maximum speed for E axis from printer
|
||||
profile will be used. Otherwise interpreted as an integer signifying the speed in mm/min, to append to the command.
|
||||
|
||||
flowrate
|
||||
Changes the flow rate factor to apply to extrusion of the tool.
|
||||
@@ -382,7 +373,7 @@ Issue a tool command
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
Requires the ``CONTROL`` permission.
|
||||
Requires user rights.
|
||||
|
||||
**Example Target Temperature Request**
|
||||
|
||||
@@ -557,8 +548,6 @@ Retrieve the current tool state
|
||||
|
||||
Returns a :http:statuscode:`200` with a Temperature Response in the body upon success.
|
||||
|
||||
Requires the ``STATUS`` permission.
|
||||
|
||||
.. note::
|
||||
If you want both tool and bed temperature information at the same time, take a look at
|
||||
:ref:`Retrieve the current printer state <sec-api-printer-state>`.
|
||||
@@ -632,12 +621,12 @@ Issue a bed command
|
||||
are:
|
||||
|
||||
target
|
||||
Sets the given target temperature on the printer's bed. Additional parameters:
|
||||
Sets the given target temperature on the printer's tools. Additional parameters:
|
||||
|
||||
* ``target``: Target temperature to set. A value of `0` will turn the heater off.
|
||||
* ``target``: Target temperature to set.
|
||||
|
||||
offset
|
||||
Sets the given temperature offset on the printer's bed. Additional parameters:
|
||||
Sets the given temperature offset on the printer's tools. Additional parameters:
|
||||
|
||||
* ``offset``: Offset to set.
|
||||
|
||||
@@ -649,7 +638,7 @@ Issue a bed command
|
||||
If no heated bed is configured for the currently selected printer profile, the resource will return
|
||||
an :http:statuscode:`409`.
|
||||
|
||||
Requires the ``CONTROL`` permission.
|
||||
Requires user rights.
|
||||
|
||||
**Example Target Temperature Request**
|
||||
|
||||
@@ -718,10 +707,8 @@ Retrieve the current bed state
|
||||
If no heated bed is configured for the currently selected printer profile, the resource will return
|
||||
an :http:statuscode:`409`.
|
||||
|
||||
Requires the ``STATUS`` permission.
|
||||
|
||||
.. note::
|
||||
If you want tool, bed and chamber temperature information at the same time, take a look at
|
||||
If you want both tool and bed temperature information at the same time, take a look at
|
||||
:ref:`Retrieve the current printer state <sec-api-printer-state>`.
|
||||
|
||||
**Example**
|
||||
@@ -771,156 +758,6 @@ Retrieve the current bed state
|
||||
:statuscode 409: If the printer is not operational or the selected printer profile
|
||||
does not have a heated bed.
|
||||
|
||||
.. _sec-api-printer-chambercommand:
|
||||
|
||||
Issue a chamber command
|
||||
=======================
|
||||
|
||||
.. http:post:: /api/printer/chamber
|
||||
|
||||
Chamber commands allow setting the temperature and temperature offsets for the printer's heated chamber. Available commands
|
||||
are:
|
||||
|
||||
target
|
||||
Sets the given target temperature on the printer's chamber. Additional parameters:
|
||||
|
||||
* ``target``: Target temperature to set. A value of `0` will turn the heater off.
|
||||
|
||||
offset
|
||||
Sets the given temperature offset on the printer's chamber. Additional parameters:
|
||||
|
||||
* ``offset``: Offset to set.
|
||||
|
||||
All of these commands may only be sent if the printer is currently operational. Otherwise a :http:statuscode:`409`
|
||||
is returned.
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
If no heated chamber is configured for the currently selected printer profile, the resource will return
|
||||
an :http:statuscode:`409`.
|
||||
|
||||
Requires the ``CONTROL`` permission.
|
||||
|
||||
**Example Target Temperature Request**
|
||||
|
||||
Set the target temperature for the printer's heated chamber to 50°C.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/chamber HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "target",
|
||||
"target": 50
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
**Example Offset Temperature Request**
|
||||
|
||||
Set the temperature offset for the heated chamber to -5°C.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/chamber HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "offset",
|
||||
"offset": -5
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
:json string command: The command to issue, either ``target`` or ``offset``.
|
||||
:json object target: ``target`` command: The target temperature to set.
|
||||
:json object offset: ``offset`` command: The offset temperature to set.
|
||||
:statuscode 204: No error
|
||||
:statuscode 400: If ``target`` or ``offset`` is not a valid number or outside of the supported range, or if the
|
||||
request is otherwise invalid.
|
||||
:statuscode 409: If the printer is not operational or the selected printer profile
|
||||
does not have a heated chamber.
|
||||
|
||||
.. _sec-api-printer-chamberstate:
|
||||
|
||||
Retrieve the current chamber state
|
||||
==================================
|
||||
|
||||
.. http:get:: /api/printer/chamber
|
||||
|
||||
Retrieves the current temperature data (actual, target and offset) plus optionally a (limited) history (actual, target,
|
||||
timestamp) for the printer's heated chamber.
|
||||
|
||||
It's also possible to retrieve the temperature history by supplying the ``history`` query parameter set to ``true``. The
|
||||
amount of returned history data points can be limited using the ``limit`` query parameter.
|
||||
|
||||
Returns a :http:statuscode:`200` with a Temperature Response in the body upon success.
|
||||
|
||||
If no heated chamber is configured for the currently selected printer profile, the resource will return
|
||||
an :http:statuscode:`409`.
|
||||
|
||||
Requires the ``STATUS`` permission.
|
||||
|
||||
.. note::
|
||||
If you want tool, bed and chamber temperature information at the same time, take a look at
|
||||
:ref:`Retrieve the current printer state <sec-api-printer-state>`.
|
||||
|
||||
**Example**
|
||||
|
||||
Query the chamber temperature data and also include the temperature history but limit it to two entries.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/printer/chamber?history=true&limit=2 HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"chamber": {
|
||||
"actual": 50.221,
|
||||
"target": 70.0,
|
||||
"offset": 5
|
||||
},
|
||||
"history": [
|
||||
{
|
||||
"time": 1395651928,
|
||||
"chamber": {
|
||||
"actual": 50.221,
|
||||
"target": 70.0
|
||||
}
|
||||
},
|
||||
{
|
||||
"time": 1395651926,
|
||||
"chamber": {
|
||||
"actual": 49.1123,
|
||||
"target": 70.0
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
:query history: If set to ``true`` (or: ``yes``, ``y``, ``1``), history information will be included in the response
|
||||
too. If no ``limit`` parameter is given, all available temperature history data will be returned.
|
||||
:query limit: If set to an integer (``n``), only the last ``n`` data points from the printer's temperature history
|
||||
will be returned. Will be ignored if ``history`` is not enabled.
|
||||
:statuscode 200: No error
|
||||
:statuscode 409: If the printer is not operational or the selected printer profile
|
||||
does not have a heated chamber.
|
||||
|
||||
.. _sec-api-printer-sdcommand:
|
||||
|
||||
Issue an SD command
|
||||
@@ -952,7 +789,7 @@ Issue an SD command
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
Requires the ``CONTROL`` permission.
|
||||
Requires user rights.
|
||||
|
||||
**Example Init Request**
|
||||
|
||||
@@ -1030,8 +867,6 @@ Retrieve the current SD state
|
||||
Returns a :http:statuscode:`200` with an :ref:`SD State Response <sec-api-printer-datamodel-sdstate>` in the body
|
||||
upon success.
|
||||
|
||||
Requires the ``STATUS`` permission.
|
||||
|
||||
**Example**
|
||||
|
||||
Read the current state of the SD card.
|
||||
@@ -1068,7 +903,7 @@ Send an arbitrary command to the printer
|
||||
|
||||
If successful returns a :http:statuscode:`204` and an empty body.
|
||||
|
||||
Requires the ``CONTROL`` permission.
|
||||
Requires user rights.
|
||||
|
||||
**Example for sending a single command**
|
||||
|
||||
@@ -1111,26 +946,6 @@ Send an arbitrary command to the printer
|
||||
:json string commands: List of commands to send to the printer, mutually exclusive with ``command``.
|
||||
:statuscode 204: No error
|
||||
|
||||
.. _sec-api-printer-customcontrols:
|
||||
|
||||
Retrieve custom controls
|
||||
========================
|
||||
|
||||
.. http:get:: /api/printer/command/custom
|
||||
|
||||
Retrieves the :ref:`custom controls <sec-features-custom_controls>` as configured in
|
||||
:ref:`config.yaml <sec-configuration-config_yaml>`.
|
||||
|
||||
Please refer to the documentation of :ref:`custom controls <sec-features-custom_controls>` on what
|
||||
data structure to expect here.
|
||||
|
||||
Returns a :http:statuscode:`200` with an :ref:`Custom Controls Response <sec-api-printer-datamodel-customcontrols>`
|
||||
in the body upon success.
|
||||
|
||||
Requires the ``CONTROL`` permission.
|
||||
|
||||
:statuscode 200: No error
|
||||
|
||||
.. _sec-api-printer-datamodel:
|
||||
|
||||
Data model
|
||||
@@ -1241,21 +1056,3 @@ Arbitrary Command Request
|
||||
- 0..1
|
||||
- Map of key value pairs
|
||||
- (only if ``script`` is set) additional template variables to provide to the script renderer
|
||||
|
||||
.. _sec-api-printer-datamodel-customcontrols:
|
||||
|
||||
Custom Controls Response
|
||||
------------------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``controls``
|
||||
- 0..n
|
||||
- List of :ref:`custom controls <sec-features-custom_controls>`
|
||||
- A list of custom control definitions as defined in ``config.yaml``.
|
||||
@@ -21,8 +21,6 @@ Retrieve all printer profiles
|
||||
|
||||
Returns a :http:statuscode:`200` with a list of :ref:`profiles <sec-api-printerprofiles-datamodel-profile>`.
|
||||
|
||||
Requires the ``CONNECTION`` permission.
|
||||
|
||||
**Example**
|
||||
|
||||
.. sourcecode:: http
|
||||
@@ -54,7 +52,6 @@ Retrieve all printer profiles
|
||||
"height": 200
|
||||
},
|
||||
"heatedBed": true,
|
||||
"heatedChamber": false,
|
||||
"axes": {
|
||||
"x": {
|
||||
"speed": 6000,
|
||||
@@ -96,7 +93,6 @@ Retrieve all printer profiles
|
||||
"height": 200
|
||||
},
|
||||
"heatedBed": true,
|
||||
"heatedChamber": true,
|
||||
"axes": {
|
||||
"x": {
|
||||
"speed": 6000,
|
||||
@@ -126,22 +122,6 @@ Retrieve all printer profiles
|
||||
}
|
||||
|
||||
|
||||
.. _sec-api-printerprofiles-get:
|
||||
|
||||
Retrieve a single printer profile
|
||||
=================================
|
||||
|
||||
.. http:get:: /api/printerprofiles/(string:identifier)
|
||||
|
||||
Retrieves an existing single printer profile.
|
||||
|
||||
Returns a :http:statuscode:`200` with a :ref:`profile <sec-api-printerprofiles-datamodel-profile>`.
|
||||
|
||||
Requires the ``CONNECTION`` permission.
|
||||
|
||||
:statuscode 200: No error
|
||||
:statuscode 404: The profile does not exist
|
||||
|
||||
.. _sec-api-printerprofiles-add:
|
||||
|
||||
Add a new printer profile
|
||||
@@ -161,7 +141,7 @@ Add a new printer profile
|
||||
Returns a :http:statuscode:`200` with the saved profile as property ``profile``
|
||||
in the JSON body upon success.
|
||||
|
||||
Requires the ``SETTINGS`` permission.
|
||||
Requires admin rights.
|
||||
|
||||
**Example 1**
|
||||
|
||||
@@ -204,7 +184,6 @@ Add a new printer profile
|
||||
"height": 200
|
||||
},
|
||||
"heatedBed": true,
|
||||
"heatedChamber": false,
|
||||
"axes": {
|
||||
"x": {
|
||||
"speed": 6000,
|
||||
@@ -288,7 +267,6 @@ Add a new printer profile
|
||||
"height": 300
|
||||
},
|
||||
"heatedBed": false,
|
||||
"heatedChamber": false,
|
||||
"axes": {
|
||||
"x": {
|
||||
"speed": 6000,
|
||||
@@ -332,7 +310,7 @@ Update an existing printer profile
|
||||
Returns a :http:statuscode:`200` with the saved profile as property ``profile``
|
||||
in the JSON body upon success.
|
||||
|
||||
Requires the ``SETTINGS`` permission.
|
||||
Requires admin rights.
|
||||
|
||||
**Example**
|
||||
|
||||
@@ -374,7 +352,6 @@ Update an existing printer profile
|
||||
"height": 200
|
||||
},
|
||||
"heatedBed": true,
|
||||
"heatedChamber": false,
|
||||
"axes": {
|
||||
"x": {
|
||||
"speed": 6000,
|
||||
@@ -418,7 +395,7 @@ Remove an existing printer profile
|
||||
|
||||
Returns a :http:statuscode:`204` an empty body upon success.
|
||||
|
||||
Requires the ``SETTINGS`` permission.
|
||||
Requires admin rights.
|
||||
|
||||
**Example**
|
||||
|
||||
@@ -601,10 +578,6 @@ Profile
|
||||
- 0..1
|
||||
- ``boolean``
|
||||
- Whether the printer has a heated bed (``true``) or not (``false``)
|
||||
* - ``heatedChamber``
|
||||
- 0..1
|
||||
- ``boolean``
|
||||
- Whether the printer has a heated chamber (``true``) or not (``false``)
|
||||
* - ``axes``
|
||||
- 0..1
|
||||
- Object
|
||||
|
||||
+3
-5
@@ -29,9 +29,6 @@ following message types are currently available for usage by 3rd party clients:
|
||||
|
||||
* ``connected``: Initial connection information, sent only right after establishing the socket connection. See
|
||||
:ref:`the payload data model <sec-api-push-datamodel-connected>`.
|
||||
* ``reauthRequired``: A reauthentication of the current login session is required. The ``reason`` parameter in the
|
||||
payload defines whether a full active login is necessary (values ``logout`` and ``removed``) or a simple passive
|
||||
login will suffice (all other values).
|
||||
* ``current``: Rate limited general state update, payload contains information about the printer's state, job progress,
|
||||
accumulated temperature points and log lines since last update. OctoPrint will send these updates when new information
|
||||
is available, but not more often than twice per second in order to not flood the client with messages (e.g.
|
||||
@@ -54,8 +51,9 @@ OctoPrint's SockJS socket also accepts two commands from the client to the serve
|
||||
|
||||
* ``auth`` (since 1.3.10): With the ``auth`` message, clients may associate an
|
||||
existing user session with the socket. That is of special importance to receive
|
||||
any kind of messages, since the permission system will prevent any kind of status messages to be sent to connected
|
||||
clients lacking the ``STATUS`` permission.
|
||||
any kind of messages if the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` is enabled
|
||||
(as it is by default), since it will prevent any kind of status messages to be sent to connected unauthenticated
|
||||
clients.
|
||||
|
||||
The ``auth`` message expects the user id of the user to authenticate followed by ``:`` and a session key to be
|
||||
obtained from the successful payload of a :ref:`(passive or active) login via the API <sec-api-general-login>`.
|
||||
|
||||
@@ -21,8 +21,6 @@ Retrieve current settings
|
||||
The :ref:`data model <sec-api-settings-datamodel>` is similar to what can be found in
|
||||
:ref:`config.yaml <sec-configuration-config_yaml>`, see below for details.
|
||||
|
||||
Requires the ``SETTINGS_READ`` permission.
|
||||
|
||||
.. _sec-api-settings-save:
|
||||
|
||||
Save settings
|
||||
@@ -38,7 +36,7 @@ Save settings
|
||||
|
||||
Returns the currently active settings on success, as part of a :http:statuscode:`200` response.
|
||||
|
||||
Requires the ``SETTINGS`` permission.
|
||||
Requires admin rights.
|
||||
|
||||
**Example**
|
||||
|
||||
@@ -276,10 +274,10 @@ Fetch template data
|
||||
"plugin_name": "Action Command Prompt Support"
|
||||
},
|
||||
{
|
||||
"id": "plugin_curalegacy",
|
||||
"name": "Cura Legacy",
|
||||
"plugin_id": "curalegacy",
|
||||
"plugin_name": "Cura Legacy"
|
||||
"id": "plugin_cura",
|
||||
"name": "CuraEngine (<= 15.04)",
|
||||
"plugin_id": "cura",
|
||||
"plugin_name": "CuraEngine (<= 15.04)"
|
||||
}
|
||||
],
|
||||
"sidebar": [
|
||||
@@ -516,8 +514,6 @@ mapped from the same fields in ``config.yaml`` unless otherwise noted:
|
||||
-
|
||||
* - ``webcam.ffmpegThreads``
|
||||
-
|
||||
* - ``webcam.ffmpegVideoCodec``
|
||||
-
|
||||
* - ``webcam.watermark``
|
||||
-
|
||||
* - ``webcam.flipH``
|
||||
|
||||
+16
-76
@@ -28,8 +28,6 @@ List All Slicers and Slicing Profiles
|
||||
Returns a :http:statuscode:`200` response with a :ref:`Slicer list <sec-api-slicing-datamodel-slicerlist>`
|
||||
as the body upon successful completion.
|
||||
|
||||
Requires the ``SLICE`` permission.
|
||||
|
||||
**Example**
|
||||
|
||||
.. sourcecode:: http
|
||||
@@ -44,22 +42,22 @@ List All Slicers and Slicing Profiles
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"curalegacy": {
|
||||
"key": "curalegacy",
|
||||
"displayName": "Cura Legacy",
|
||||
"cura": {
|
||||
"key": "cura",
|
||||
"displayName": "CuraEngine",
|
||||
"default": true,
|
||||
"profiles": {
|
||||
"high_quality": {
|
||||
"key": "high_quality",
|
||||
"displayName": "High Quality",
|
||||
"default": false,
|
||||
"resource": "http://example.com/api/slicing/curalegacy/profiles/high_quality"
|
||||
"resource": "http://example.com/api/slicing/cura/profiles/high_quality"
|
||||
},
|
||||
"medium_quality": {
|
||||
"key": "medium_quality",
|
||||
"displayName": "Medium Quality",
|
||||
"default": true,
|
||||
"resource": "http://example.com/api/slicing/curalegacy/profiles/medium_quality"
|
||||
"resource": "http://example.com/api/slicing/cura/profiles/medium_quality"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -79,13 +77,11 @@ List Slicing Profiles of a Specific Slicer
|
||||
Returns a :http:statuscode:`200` response with a :ref:`Profile list <sec-api-slicing-datamodel-profilelist>`
|
||||
as the body upon successful completion.
|
||||
|
||||
Requires the ``SLICE`` permission.
|
||||
|
||||
**Example**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/slicing/curalegacy/profiles HTTP/1.1
|
||||
GET /api/slicing/cura/profiles HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
@@ -99,13 +95,13 @@ List Slicing Profiles of a Specific Slicer
|
||||
"key": "high_quality",
|
||||
"displayName": "High Quality",
|
||||
"default": false,
|
||||
"resource": "http://example.com/api/slicing/curalegacy/profiles/high_quality"
|
||||
"resource": "http://example.com/api/slicing/cura/profiles/high_quality"
|
||||
},
|
||||
"medium_quality": {
|
||||
"key": "medium_quality",
|
||||
"displayName": "Medium Quality",
|
||||
"default": true,
|
||||
"resource": "http://example.com/api/slicing/curalegacy/profiles/medium_quality"
|
||||
"resource": "http://example.com/api/slicing/cura/profiles/medium_quality"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,13 +121,11 @@ Retrieve Specific Profile
|
||||
Returns a :http:statuscode:`200` response with a :ref:`full Profile <sec-api-slicing-datamodel-profile>`
|
||||
as the body upon successful completion.
|
||||
|
||||
Requires the ``SLICE`` permission.
|
||||
|
||||
**Example**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/slicing/curalegacy/profiles/quick_test HTTP/1.1
|
||||
GET /api/slicing/cura/profiles/quick_test HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
@@ -143,7 +137,7 @@ Retrieve Specific Profile
|
||||
{
|
||||
"displayName": "Just a test",
|
||||
"description": "This is just a test",
|
||||
"resource": "http://example.com/api/slicing/curalegacy/profiles/quick_test",
|
||||
"resource": "http://example.com/api/slicing/cura/profiles/quick_test",
|
||||
"data": {
|
||||
"bottom_layer_speed": 20.0,
|
||||
"bottom_thickness": 0.3,
|
||||
@@ -174,20 +168,20 @@ Add Slicing Profile
|
||||
Returns a :http:statuscode:`201` and an :ref:`abridged Profile <sec-api-slicing-datamodel-profile>` in the body
|
||||
upon successful completion.
|
||||
|
||||
Requires the ``SETTINGS`` permission.
|
||||
Requires admin rights.
|
||||
|
||||
**Example**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
PUT /api/slicing/curalegacy/profiles/quick_test HTTP/1.1
|
||||
PUT /api/slicing/cura/profiles/quick_test HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"displayName": "Just a test",
|
||||
"description": "This is just a test to show how to create a curalegacy profile with a different layer height and skirt count",
|
||||
"description": "This is just a test to show how to create a cura profile with a different layer height and skirt count",
|
||||
"data": {
|
||||
"layer_height": 0.2,
|
||||
"skirt_line_count": 3
|
||||
@@ -203,8 +197,8 @@ Add Slicing Profile
|
||||
|
||||
{
|
||||
"displayName": "Just a test",
|
||||
"description": "This is just a test to show how to create a curalegacy profile with a different layer height and skirt count",
|
||||
"resource": "http://example.com/api/slicing/curalegacy/profiles/quick_test"
|
||||
"description": "This is just a test to show how to create a cura profile with a different layer height and skirt count",
|
||||
"resource": "http://example.com/api/slicing/cura/profiles/quick_test"
|
||||
}
|
||||
|
||||
:param slicer: The identifying key of the slicer for which to add the profile
|
||||
@@ -212,31 +206,6 @@ Add Slicing Profile
|
||||
:statuscode 201: No error
|
||||
:statuscode 404: If the ``slicer`` was unknown to the system.
|
||||
|
||||
.. _sec-api-slicing-patch:
|
||||
|
||||
Update Slicing Profile
|
||||
======================
|
||||
|
||||
.. http:patch:: /api/slicing/(string:slicer)/profiles/(string:key)
|
||||
|
||||
Updates the slicing profile identified by ``key`` for the slicer ``slicer``.
|
||||
|
||||
Expects a :ref:`profile update request <sec-api-slicing-datamodel-profileupdate>` as body.
|
||||
|
||||
Returns a :http:statuscode:`201` and an :ref:`abridged Profile <sec-api-slicing-datamodel-profile>` in the body
|
||||
upon successful completion.
|
||||
|
||||
Requires the ``SETTINGS`` permission.
|
||||
|
||||
:param slicer: The identifying key of the slicer for which to update the profile
|
||||
:param key: The identifying key of the profile to update
|
||||
:json data: New profile overrides to apply
|
||||
:json displayName: New display name
|
||||
:json description: New description
|
||||
:json default: Whether to make the profile default (true) or not (false) for the slicer
|
||||
:statuscode 200: No error
|
||||
:statuscode 404: Slicer or profile do not exist
|
||||
|
||||
.. _sec-api-slicing-delete:
|
||||
|
||||
Delete Slicing Profile
|
||||
@@ -247,7 +216,7 @@ Delete Slicing Profile
|
||||
Delete the slicing profile identified by ``key`` for the slicer ``slicer``. If the profile doesn't exist, the
|
||||
request will succeed anyway.
|
||||
|
||||
Requires the ``SETTINGS`` permission.
|
||||
Requires admin rights.
|
||||
|
||||
:param slicer: The identifying key of the slicer for which to delete the profile
|
||||
:param key: The identifying key of the profile to delete
|
||||
@@ -371,32 +340,3 @@ Profile
|
||||
only the keys differing from the defaults when saving/updating a profile. The keys to be found in here a slicer
|
||||
specific. Will be left out for list responses.
|
||||
|
||||
.. _sec-api-slicing-datamodel-profileupdate:
|
||||
|
||||
Profile Update Request
|
||||
----------------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``data``
|
||||
- 0..1
|
||||
- Object
|
||||
- The profile data
|
||||
* - ``displayName``
|
||||
- 0..1
|
||||
- ``string``
|
||||
- The new display name for the profile
|
||||
* - ``description``
|
||||
- 0..1
|
||||
- ``string``
|
||||
- The new description for the profile
|
||||
* - ``default``
|
||||
- 0..1
|
||||
- ``boolean``
|
||||
- Whether to mark the profile as default for the slicer (true) or not (false)
|
||||
+24
-50
@@ -6,7 +6,7 @@ System
|
||||
|
||||
.. note::
|
||||
|
||||
All system operations require the ``SYSTEM`` permission.
|
||||
All system operations require admin rights.
|
||||
|
||||
.. _sec-api-system-command-list:
|
||||
|
||||
@@ -20,8 +20,6 @@ List all registered system commands
|
||||
A :http:statuscode:`200` with a :ref:`List all response <sec-api-system-commands-listall>`
|
||||
will be returned.
|
||||
|
||||
Requires the ``SYSTEM`` permission.
|
||||
|
||||
**Example**
|
||||
|
||||
.. sourcecode:: http
|
||||
@@ -40,21 +38,30 @@ List all registered system commands
|
||||
{
|
||||
"action": "shutdown",
|
||||
"name": "Shutdown",
|
||||
"command": "sudo shutdown -h now",
|
||||
"confirm": "<strong>You are about to shutdown the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
|
||||
"async": true,
|
||||
"ignore": true,
|
||||
"source": "core",
|
||||
"resource": "http://example.com/api/system/commands/core/shutdown"
|
||||
},
|
||||
{
|
||||
"action": "reboot",
|
||||
"name": "Reboot",
|
||||
"command": "sudo reboot",
|
||||
"confirm": "<strong>You are about to reboot the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
|
||||
"async": true,
|
||||
"ignore": true,
|
||||
"source": "core",
|
||||
"resource": "http://example.com/api/system/commands/core/reboot"
|
||||
},
|
||||
{
|
||||
"action": "restart",
|
||||
"name": "Restart OctoPrint",
|
||||
"command": "sudo service octoprint restart",
|
||||
"confirm": "<strong>You are about to restart the OctoPrint server.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
|
||||
"async": true,
|
||||
"ignore": true,
|
||||
"source": "core",
|
||||
"resource": "http://example.com/api/system/commands/core/restart"
|
||||
}
|
||||
@@ -92,21 +99,30 @@ List all registered system commands for a source
|
||||
{
|
||||
"action": "shutdown",
|
||||
"name": "Shutdown",
|
||||
"confirm": "<strong>You are about to shutdown the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
|
||||
"command": "sudo shutdown -h now",
|
||||
"confirm": "<b>You are about to shutdown the system.</b></p><p> This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
|
||||
"async": true,
|
||||
"ignore": true,
|
||||
"source": "core",
|
||||
"resource": "http://example.com/api/system/commands/core/shutdown"
|
||||
},
|
||||
{
|
||||
"action": "reboot",
|
||||
"name": "Reboot",
|
||||
"confirm": "<strong>You are about to reboot the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
|
||||
"command": "sudo reboot",
|
||||
"confirm": "<b>You are about to reboot the system.</b></p><p> This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
|
||||
"async": true,
|
||||
"ignore": true,
|
||||
"source": "core",
|
||||
"resource": "http://example.com/api/system/commands/core/reboot"
|
||||
},
|
||||
{
|
||||
"action": "restart",
|
||||
"name": "Restart OctoPrint",
|
||||
"confirm": "<strong>You are about to restart the OctoPrint server.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
|
||||
"command": "sudo service octoprint restart",
|
||||
"confirm": "<b>You are about to restart the OctoPrint server.</b></p><p> This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
|
||||
"async": true,
|
||||
"ignore": true,
|
||||
"source": "core",
|
||||
"resource": "http://example.com/api/system/commands/core/restart"
|
||||
}
|
||||
@@ -168,60 +184,18 @@ List all response
|
||||
- Description
|
||||
* - ``core``
|
||||
- 0..n
|
||||
- List of :ref:`client command definitions <sec-api-client-system-commands-definiton>`
|
||||
- List of :ref:`command definitions <sec-api-system-commands-definiton>`
|
||||
- List of all core commands defined.
|
||||
* - ``custom``
|
||||
- 0..n
|
||||
- List of :ref:`client command definitions <sec-api-client-system-commands-definiton>`
|
||||
- List of :ref:`command definitions <sec-api-system-commands-definiton>`
|
||||
- List of all custom commands defined in ``config.yaml``.
|
||||
|
||||
.. _sec-api-client-system-commands-definiton:
|
||||
|
||||
Client command definitions
|
||||
--------------------------
|
||||
|
||||
A restricted form of the full :ref:`command definition <sec-api-system-commands-definiton>`.
|
||||
For exposing via the API.
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``name``
|
||||
- 1
|
||||
- string
|
||||
- The name of the command to display in the System menu.
|
||||
* - ``action``
|
||||
- 1
|
||||
- string
|
||||
- An identifier to refer to the command programmatically. The special ``action`` string
|
||||
``divider`` signifies a divider in the menu.
|
||||
* - ``confirm``
|
||||
- 0..1
|
||||
- string
|
||||
- If present and set, this text will be displayed to the user in a confirmation dialog
|
||||
they have to acknowledge in order to really execute the command.
|
||||
* - ``source``
|
||||
- 1
|
||||
- string
|
||||
- Source of the command definition, currently either ``core`` (for system actions defined by
|
||||
OctoPrint itself) or ``custom`` (for custom system commands defined by the user through ``config.yaml``).
|
||||
* - ``resource``
|
||||
- 1
|
||||
- string
|
||||
- The URL of the command to use for executing it.
|
||||
|
||||
.. _sec-api-system-commands-definiton:
|
||||
|
||||
Command definition
|
||||
------------------
|
||||
|
||||
The full command definition is not available via the API.
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
@@ -18,8 +18,6 @@ Retrieve a list of timelapses and the current config
|
||||
Returns a :ref:`timelapse list <sec-api-timelapse-datamodel-list>` in the
|
||||
response body.
|
||||
|
||||
Requires the ``TIMELAPSE_LIST`` permission.
|
||||
|
||||
:param unrendered: If provided and true, also include unrendered timelapses
|
||||
|
||||
.. _sec-api-timelapse-delete:
|
||||
@@ -31,7 +29,7 @@ Delete a timelapse
|
||||
|
||||
Delete the timelapse ``filename``.
|
||||
|
||||
Requires the ``TIMELAPSE_DELETE`` permission.
|
||||
Requires user rights.
|
||||
|
||||
.. _sec-api-timelapse-render:
|
||||
|
||||
@@ -43,7 +41,7 @@ Issue a command for an unrendered timelapse
|
||||
Current only supports to render the unrendered timelapse ``name`` via the
|
||||
``render`` command.
|
||||
|
||||
Requires the ``TIMELAPSE_ADMIN`` permission.
|
||||
Requires user rights.
|
||||
|
||||
:json command: The command to issue, currently only ``render`` is supported
|
||||
|
||||
@@ -56,7 +54,7 @@ Delete an unrendered timelapse
|
||||
|
||||
Delete the unrendered timelapse ``name``.
|
||||
|
||||
Requires the ``TIMELAPSE_DELETE`` permission.
|
||||
Requires user rights.
|
||||
|
||||
.. _sec-api-timelapse-saveconfig:
|
||||
|
||||
@@ -69,7 +67,7 @@ Change current timelapse config
|
||||
|
||||
The configuration is expected as the request body.
|
||||
|
||||
Requires the ``TIMELAPSE_ADMIN`` permission.
|
||||
Requires user rights.
|
||||
|
||||
.. _sec-api-timelapse-datamodel:
|
||||
|
||||
|
||||
+307
-2
@@ -4,6 +4,311 @@
|
||||
User
|
||||
****
|
||||
|
||||
.. note::
|
||||
.. contents::
|
||||
|
||||
This API endpoint has been moved and is now part of :ref:`Access Control <sec-api-access-users>`.
|
||||
.. _sec-api-users-list:
|
||||
|
||||
Retrieve a list of users
|
||||
========================
|
||||
|
||||
.. http:get:: /api/users
|
||||
|
||||
Retrieves a list of all registered users in OctoPrint.
|
||||
|
||||
Will return a :http:statuscode:`200` with a :ref:`user list response <sec-api-users-datamodel-userlistresponse>`
|
||||
as body.
|
||||
|
||||
Requires admin rights.
|
||||
|
||||
:status 200: No error
|
||||
|
||||
.. _sec-api-users-retrieve:
|
||||
|
||||
Retrieve a user
|
||||
===============
|
||||
|
||||
.. http:get:: /api/users/(string:username)
|
||||
|
||||
Retrieves information about a user.
|
||||
|
||||
Will return a :http:statuscode:`200` with a :ref:`user record <sec-api-users-datamodel-userrecord>`
|
||||
as body.
|
||||
|
||||
Requires either admin rights or to be logged in as the user.
|
||||
|
||||
:param username: Name of the user which to retrieve
|
||||
:status 200: No error
|
||||
:status 404: Unknown user
|
||||
|
||||
.. _sec-api-users-add:
|
||||
|
||||
Add a user
|
||||
==========
|
||||
|
||||
.. http:post:: /api/users
|
||||
|
||||
Adds a user to OctoPrint.
|
||||
|
||||
Expects a :ref:`user registration request <sec-api-users-datamodel-adduserrequest>`
|
||||
as request body.
|
||||
|
||||
Returns a list of registered users on success, see :ref:`Retrieve a list of users <sec-api-users-list>`.
|
||||
|
||||
Requires admin rights.
|
||||
|
||||
:json name: The user's name
|
||||
:json password: The user's password
|
||||
:json active: Whether to activate the account (true) or not (false)
|
||||
:json admin: Whether to give the account admin rights (true) or not (false)
|
||||
:status 200: No error
|
||||
:status 400: If any of the mandatory fields is missing or the request is otherwise
|
||||
invalid
|
||||
:status 409: A user with the provided name does already exist
|
||||
|
||||
.. _sec-api-users-update:
|
||||
|
||||
Update a user
|
||||
=============
|
||||
|
||||
.. http:put:: /api/users/(string:username)
|
||||
|
||||
Updates a user record.
|
||||
|
||||
Expects a :ref:`user update request <sec-api-users-datamodel-updateuserrequest>`
|
||||
as request body.
|
||||
|
||||
Returns a list of registered users on success, see :ref:`Retrieve a list of users <sec-api-users-list>`.
|
||||
|
||||
Requires admin rights.
|
||||
|
||||
:param username: Name of the user to update
|
||||
:json admin: Whether to mark the user as admin (true) or not (false), can be left out (no change)
|
||||
:json active: Whether to mark the account as activated (true) or deactivated (false), can be left out (no change)
|
||||
:status 200: No error
|
||||
:status 404: Unknown user
|
||||
|
||||
.. _sec-api-users-delete:
|
||||
|
||||
Delete a user
|
||||
=============
|
||||
|
||||
.. http:delete:: /api/users/(string:username)
|
||||
|
||||
Delete a user record.
|
||||
|
||||
Returns a list of registered users on success, see :ref:`Retrieve a list of users <sec-api-users-list>`.
|
||||
|
||||
Requires admin rights.
|
||||
|
||||
:param username: Name of the user to delete
|
||||
:status 200: No error
|
||||
:status 404: Unknown user
|
||||
|
||||
.. _sec-api-users-resetpassword:
|
||||
|
||||
Reset a user's password
|
||||
=======================
|
||||
|
||||
.. http:put:: /api/users/(string:username)/password
|
||||
|
||||
Changes the password of a user.
|
||||
|
||||
Expects a JSON object with a single property ``password`` as request body.
|
||||
|
||||
Requires admin rights or to be logged in as the user.
|
||||
|
||||
:param username: Name of the user to change the password for
|
||||
:json password: The new password to set
|
||||
:status 200: No error
|
||||
:status 400: If the request doesn't contain a ``password`` property or the request
|
||||
is otherwise invalid
|
||||
:status 403: No admin rights and not logged in as the user
|
||||
:status 404: The user is unknown
|
||||
|
||||
.. _sec-api-users-getsettings:
|
||||
|
||||
Retrieve a user's settings
|
||||
==========================
|
||||
|
||||
.. http:get:: /api/users/(string:username)/settings
|
||||
|
||||
Retrieves a user's settings.
|
||||
|
||||
Will return a :http:statuscode:`200` with a JSON object representing the user's
|
||||
personal settings (if any) as body.
|
||||
|
||||
Requires admin rights or to be logged in as the user.
|
||||
|
||||
:param username: Name of the user to retrieve the settings for
|
||||
:status 200: No error
|
||||
:status 403: No admin rights and not logged in as the user
|
||||
:status 404: The user is unknown
|
||||
|
||||
.. _sec-api-users-updatesettings:
|
||||
|
||||
Update a user's settings
|
||||
========================
|
||||
|
||||
.. http:patch:: /api/users/(string:username)/settings
|
||||
|
||||
Updates a user's settings.
|
||||
|
||||
Expects a new settings JSON object to merge with the current settings as
|
||||
request body.
|
||||
|
||||
Requires admin rights or to be logged in as the user.
|
||||
|
||||
:param username: Name of the user to retrieve the settings for
|
||||
:status 204: No error
|
||||
:status 403: No admin rights and not logged in as the user
|
||||
:status 404: The user is unknown
|
||||
|
||||
.. _sec-api-users-generateapikey:
|
||||
|
||||
Regenerate a user's personal API key
|
||||
====================================
|
||||
|
||||
.. http:post:: /api/users/(string:username)/apikey
|
||||
|
||||
Generates a new API key for the user.
|
||||
|
||||
Does not expect a body. Will return the generated API key as ``apikey``
|
||||
property in the JSON object contained in the response body.
|
||||
|
||||
Requires admin rights or to be logged in as the user.
|
||||
|
||||
:param username: Name of the user to retrieve the settings for
|
||||
:status 200: No error
|
||||
:status 403: No admin rights and not logged in as the user
|
||||
:status 404: The user is unknown
|
||||
|
||||
.. _sec-api-users-deleteapikey:
|
||||
|
||||
Delete a user's personal API key
|
||||
================================
|
||||
|
||||
.. http:delete:: /api/users/(string:username)/apikey
|
||||
|
||||
Deletes a user's personal API key.
|
||||
|
||||
Requires admin rights or to be logged in as the user.
|
||||
|
||||
:param username: Name of the user to retrieve the settings for
|
||||
:status 204: No error
|
||||
:status 403: No admin rights and not logged in as the user
|
||||
:status 404: The user is unknown
|
||||
|
||||
.. _sec-api-users-datamodel:
|
||||
|
||||
Data model
|
||||
==========
|
||||
|
||||
.. _sec-api-users-datamodel-userlistresponse:
|
||||
|
||||
User list response
|
||||
------------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``users``
|
||||
- 0..n
|
||||
- List of :ref:`user records <sec-api-users-datamodel-userrecord>`
|
||||
- The list of registered users
|
||||
|
||||
.. _sec-api-users-datamodel-userrecord:
|
||||
|
||||
User record
|
||||
-----------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``name``
|
||||
- 1
|
||||
- string
|
||||
- The user's name
|
||||
* - ``active``
|
||||
- 1
|
||||
- bool
|
||||
- Whether the user's account is active (true) or not (false)
|
||||
* - ``user``
|
||||
- 1
|
||||
- bool
|
||||
- Whether the user has user rights. Should always be true.
|
||||
* - ``admin``
|
||||
- 1
|
||||
- bool
|
||||
- Whether the user has admin rights (true) or not (false)
|
||||
* - ``apikey``
|
||||
- 0..1
|
||||
- string
|
||||
- The user's personal API key
|
||||
* - ``settings``
|
||||
- 1
|
||||
- object
|
||||
- The user's personal settings, might be an empty object.
|
||||
|
||||
.. _sec-api-users-datamodel-adduserrequest:
|
||||
|
||||
User registration request
|
||||
-------------------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``name``
|
||||
- 1
|
||||
- string
|
||||
- The user's name
|
||||
* - ``password``
|
||||
- 1
|
||||
- string
|
||||
- The user's password
|
||||
* - ``active``
|
||||
- 1
|
||||
- bool
|
||||
- Whether to activate the account (true) or not (false)
|
||||
* - ``admin``
|
||||
- 0..1
|
||||
- bool
|
||||
- Whether to give the user admin rights (true) or not (false or not present)
|
||||
|
||||
.. _sec-api-users-datamodel-updateuserrequest:
|
||||
|
||||
User update request
|
||||
-------------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``active``
|
||||
- 0..1
|
||||
- bool
|
||||
- If present will set the user's active flag to the provided value. True for
|
||||
activating the account, false for deactivating it.
|
||||
* - ``admin``
|
||||
- 0..1
|
||||
- bool
|
||||
- If present will set the user's admin flag to the provided value. True for
|
||||
admin rights, false for no admin rights.
|
||||
+1
-1
@@ -99,7 +99,7 @@ Test paths or URLs
|
||||
The ``server`` command returns :http:statuscode:`200` with a :ref:`Server test result <sec-api-util-datamodel-servertestresult>`
|
||||
when the test could be performed. The status code of the response does NOT reflect the test result!
|
||||
|
||||
Requires the ``ADMIN`` permission.
|
||||
Requires admin rights.
|
||||
|
||||
**Example 1**
|
||||
|
||||
|
||||
@@ -7,8 +7,7 @@ Version information
|
||||
.. http:get:: /api/version
|
||||
|
||||
Retrieve information regarding server and API version. Returns a JSON object with two keys, ``api`` containing
|
||||
the API version, ``server`` containing the server version, ``text`` containing the server version including
|
||||
the prefix ``OctoPrint `` (to determine that this is indeed a genuine OctoPrint instance).
|
||||
the API version, ``server`` containing the server version.
|
||||
|
||||
**Example Request**
|
||||
|
||||
@@ -27,8 +26,7 @@ Version information
|
||||
|
||||
{
|
||||
"api": "0.1",
|
||||
"server": "1.3.10",
|
||||
"text": "OctoPrint 1.3.10"
|
||||
"server": "1.1.0"
|
||||
}
|
||||
|
||||
:statuscode 200: No error
|
||||
+1
-1
@@ -6,7 +6,7 @@ Wizard
|
||||
|
||||
.. note::
|
||||
|
||||
All wizard operations require either the ``ADMIN`` permission or the ``firstRun`` flag to be ``true``.
|
||||
All wizard operations require either admin rights or the ``firstRun`` flag to be ``true``.
|
||||
|
||||
.. contents::
|
||||
|
||||
|
||||
@@ -40,18 +40,15 @@ of the following steps:
|
||||
|
||||
1. The User opens the App and gets prompted to enter or select an instance URL. Optionally (recommended!) the User also
|
||||
enters their username which is also their user ID into the App.
|
||||
2. The App :ref:`probes for workflow support <sec-bundledplugins-appkeys-api-probe>` on the Server. If this request
|
||||
doesn't get an HTTP :http:statuscode:`204` the App needs to direct the user to an alternative manual workflow
|
||||
(copy-paste API key) and abort this one. Otherwise it proceeds to the next step.
|
||||
3. The App sends a :ref:`key request <sec-bundledplugins-appkey-datamodel-keyrequest>` to the Server to start the
|
||||
2. The App sends a :ref:`key request <sec-bundledplugins-appkey-datamodel-keyrequest>` to the Server to start the
|
||||
authorization process.
|
||||
4. The Server triggers a confirmation dialog for the User on the Webinterface and returns an endpoint to the
|
||||
3. The Server triggers a confirmation dialog for the User on the Webinterface and returns an endpoint to the
|
||||
App to poll for a decision in the ``Location`` header of an HTTP :http:statuscode:`201`.
|
||||
5. The App uses the obtained request specific endpoint to poll for a decision every second. An HTTP :http:statuscode:`202`
|
||||
4. The App uses the obtained request specific endpoint to poll for a decision every second. An HTTP :http:statuscode:`202`
|
||||
signals that no decision has been made yet.
|
||||
6. The User either accepts or denies the access request which makes the Webinterface send a
|
||||
5. The User either accepts or denies the access request which makes the Webinterface send a
|
||||
:ref:`decision request <sec-bundledplugins-appkey-datamodel-decisionrequest>` to the Server.
|
||||
7. If the User accepted the request, the App receives an HTTP :http:statuscode:`200` with an attached
|
||||
6. If the User accepted the request, the App receives an HTTP :http:statuscode:`200` with an attached
|
||||
:ref:`API key response <sec-bundledplugins-appkey-datamodel-keyresponse>`. If they deny it, the App will receive
|
||||
an HTTP :http:statuscode:`404`.
|
||||
|
||||
@@ -64,35 +61,31 @@ of the following steps:
|
||||
participant Webinterface
|
||||
participant Server
|
||||
|
||||
note over User, Server: Step 1, 2 & 3
|
||||
note over User, Server: Step 1 & 2
|
||||
|
||||
User->>App: enters URL of instance to connect to and optional user_id
|
||||
|
||||
App->>Server: GET /plugin/appkeys/probe
|
||||
|
||||
alt Workflow unsupported
|
||||
|
||||
Server->>App: 404
|
||||
App->>User: alternative workflow, copy-paste key manually
|
||||
|
||||
else Workflow supported
|
||||
User->>App: enters URL of instance to connect to
|
||||
|
||||
alt Limit to specific user
|
||||
User->>App: enters user_id
|
||||
App->>Server: POST /plugin/appkeys/request, (app_name, user_id)
|
||||
else
|
||||
App->>Server: POST /plugin/appkeys/request, (app_name)
|
||||
end
|
||||
|
||||
note over User, Server: Step 4
|
||||
note over User, Server: Step 3
|
||||
|
||||
Server-->>Webinterface: plugin message for "appkeys" w/ (app_name, user_token, user_id)
|
||||
Webinterface-->>User: Display confirmation dialog
|
||||
Server->>App: 201, Location: /plugin/appkeys/request/<app_token>
|
||||
|
||||
note over User, Server: Step 5
|
||||
note over User, Server: Step 4
|
||||
|
||||
loop Poll for decision
|
||||
loop
|
||||
App->>Server: GET /plugin/appkeys/request/<app_token>
|
||||
Server->>App: 202
|
||||
end
|
||||
|
||||
note over User, Server: Step 6 & 7
|
||||
note over User, Server: Step 5 & 6
|
||||
|
||||
alt User accepts
|
||||
|
||||
@@ -112,27 +105,11 @@ of the following steps:
|
||||
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api:
|
||||
|
||||
API
|
||||
---
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api-probe:
|
||||
|
||||
Probe for workflow support
|
||||
..........................
|
||||
|
||||
.. http:get:: /plugin/appkeys/probe
|
||||
|
||||
Probes for support of the workflow.
|
||||
|
||||
Normally returns an HTTP :http:statuscode:`204`, indicating workflow availability. If a different status code is returned
|
||||
(usually an HTTP :http:statuscode:`404`), the plugin is disabled or not installed. Fall back to manual api key exchange.
|
||||
|
||||
:status 204: the workflow is supported
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api-startauthprocess:
|
||||
|
||||
Start authorization process
|
||||
@@ -154,6 +131,12 @@ Start authorization process
|
||||
it in the ``user`` parameter. OctoPrint will then only display the authorization request on browsers the user ``me``
|
||||
is logged in on.
|
||||
|
||||
.. note::
|
||||
|
||||
If this endpoint produces an HTTP :http:statuscode:`404` and the instance URL is correct, the bundled
|
||||
Application Keys Plugin has in all likelihood been disabled by the user. Fall back on manual API key copy-pasting
|
||||
by the user.
|
||||
|
||||
:json app: application identifier to use for the request, case insensitive
|
||||
:json user: optional user id to restrict the decision to the specified user
|
||||
:status 201: authorization process started, polling URL to query can be found in ``Location`` header
|
||||
@@ -171,11 +154,6 @@ Poll for decision on existing request
|
||||
a :ref:`Key response <sec-bundledplugins-appkey-datamodel-keyresponse>` if access has been granted and an
|
||||
HTTP :http:statuscode:`404` if the request has been denied or timed out.
|
||||
|
||||
.. note::
|
||||
|
||||
The request will be considered stale and deleted internally if the polling endpoint for it isn't called
|
||||
for more than 5s.
|
||||
|
||||
:status 200: access granted, API key in response body
|
||||
:status 202: no decision has been made yet, continue polling
|
||||
:status 404: access denied or request timed out
|
||||
@@ -474,15 +452,6 @@ JavaScript Client Library
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.probe(opts)
|
||||
|
||||
Probes for workflow support.
|
||||
|
||||
See :ref:`Probe for workflow support <sec-bundledplugins-appkeys-api-probe>` for more details.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.request(app, opts)
|
||||
|
||||
Starts a new authorization request for the provided ``app`` identifier.
|
||||
@@ -512,10 +481,9 @@ JavaScript Client Library
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.authenticate(app, user, opts)
|
||||
|
||||
Convenience function that probes for support, issues a request and then automatically starts polling for a decision
|
||||
on the returned polling endpoint every 1s, until either a positive or negative decision is returned. On success the
|
||||
returned promise is resolved with the generated API key as argument. If anything goes wrong or there is no support
|
||||
for the workflow, the promise is rejected.
|
||||
Convenience function that issues a request and then automatically starts polling for a decision on the returned
|
||||
polling endpoint every 1s, until either a positive or negative decision is returned. On success the returned
|
||||
promise is resolved with the generated API key as argument.
|
||||
|
||||
**Example usage**
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ Command line usage
|
||||
------------------
|
||||
|
||||
The Backup Plugin implements a command line interface that allows creation and restoration of backups.
|
||||
It adds two new commands, ``backup:backup`` and ``backup:restore``.
|
||||
It adds two new commands, ``backup:backup`` and ``backup_restore``.
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
.. _sec-bundledplugins-cura:
|
||||
|
||||
Cura
|
||||
====
|
||||
|
||||
The Cura Plugin allows slicing of STL files uploaded to OctoPrint directly via
|
||||
the `CuraEngine <http://github.com/Ultimaker/CuraEngine>`_ **up to and
|
||||
including version 15.04.x** and supersedes the slicing support integrated into
|
||||
OctoPrint so far. It comes bundled with OctoPrint starting with version 1.2.0.
|
||||
|
||||
.. note::
|
||||
|
||||
Versions of CuraEngine later than 15.04.x have changed their calling
|
||||
parameters in such a way that the current implementation of OctoPrint's Cura plugin
|
||||
is not compatible to it. For this reason, please use only CuraEngine versions up to
|
||||
and including 15.04 for now, as available in the ``legacy`` branch of the CuraEngine
|
||||
repository on Github.
|
||||
|
||||
The plugin offers a settings module that allows configuring the path to the
|
||||
CuraEngine executable to use, as well as importing and managing slicing
|
||||
profiles to be used. Please note that the Cura Plugin will use the printer
|
||||
parameters you configured within OctoPrint (meaning bed size and extruder
|
||||
count and offsets) for slicing.
|
||||
|
||||
.. _sec-bundledplugins-cura-firststeps:
|
||||
|
||||
First Steps
|
||||
-----------
|
||||
|
||||
Before you can slice from within OctoPrint, you'll need to
|
||||
|
||||
#. :ref:`Install CuraEngine <sec-bundledplugins-cura-installing>`
|
||||
#. :ref:`Configure the path to CuraEngine within OctoPrint <sec-bundledplugins-cura-configuring>`
|
||||
#. :ref:`Export a slicing profile from Cura and import it within OctoPrint <sec-bundledplugins-cura-profiles>`
|
||||
|
||||
.. note::
|
||||
|
||||
OctoPi 0.12.0 and later ships with steps 1 and 2 already done, you only need to
|
||||
supply one or more slicing profiles to get going :)
|
||||
|
||||
.. _sec-bundledplugins-cura-installing:
|
||||
|
||||
Installing CuraEngine
|
||||
---------------------
|
||||
|
||||
You'll need a build of ``legacy`` branch of `CuraEngine <http://github.com/Ultimaker/CuraEngine>`_
|
||||
in order to be able to use the Cura OctoPrint plugin. You can find the ``legacy`` branch
|
||||
`here <https://github.com/ultimaker/curaengine/tree/legacy>`__.
|
||||
|
||||
If you previously used the `old variant of the Cura integration <https://github.com/foosel/OctoPrint/wiki/Cura-Integration>`_,
|
||||
you probably still have a fully functional binary lying around in the
|
||||
installation folder of the full install of Cura you used then -- just put the
|
||||
path to that in the plugin settings.
|
||||
|
||||
.. _sec-bundledplugins-cura-installing-raspbian:
|
||||
|
||||
Compiling for Raspbian
|
||||
++++++++++++++++++++++
|
||||
|
||||
Raspbian Jessie and later
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Building on Raspbian Jessie and later is as easy as::
|
||||
|
||||
sudo apt-get -y install gcc-4.7 g++-4.7
|
||||
git clone -b legacy https://github.com/Ultimaker/CuraEngine.git
|
||||
cd CuraEngine
|
||||
make
|
||||
|
||||
After this has completed, you'll find your shiny new build of CuraEngine in
|
||||
the `build` folder (full path for above example:
|
||||
``~/CuraEngine/build/CuraEngine``).
|
||||
|
||||
Raspbian Wheezy
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
You'll need to install a new version of gcc and g++ and patch CuraEngine's
|
||||
Makefile (see `this post <http://umforum.ultimaker.com/index.php?/topic/5943-recent-build-of-curaengine-wont-compile-on-raspberry-pi/#entry58539>`_)
|
||||
in order for the compilation to work on current Raspbian builds (e.g. OctoPi)::
|
||||
|
||||
sudo apt-get -y install gcc-4.7 g++-4.7
|
||||
git clone -b legacy https://github.com/Ultimaker/CuraEngine.git
|
||||
cd CuraEngine
|
||||
wget http://bit.ly/curaengine_makefile_patch -O CuraEngine.patch
|
||||
patch < CuraEngine.patch
|
||||
make CXX=g++-4.7
|
||||
|
||||
After this has completed, you'll find your shiny new build of CuraEngine in
|
||||
the `build` folder (full path for above example:
|
||||
``~/CuraEngine/build/CuraEngine``).
|
||||
|
||||
.. _sec-bundledplugins-cura-configuring:
|
||||
|
||||
Configuring the plugin
|
||||
----------------------
|
||||
|
||||
The Cura plugin needs to be configured with the full path to your copy of the
|
||||
CuraEngine executable that it's supposed to use. You can do this either via
|
||||
the Cura plugin settings dialog or by manually configuring the path to the
|
||||
executable via ``config.yaml``, example:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
plugins:
|
||||
cura:
|
||||
cura_engine: /path/to/CuraEngine
|
||||
|
||||
.. _sec-bundledplugins-cura-profiles:
|
||||
|
||||
Using Cura Profiles
|
||||
-------------------
|
||||
|
||||
The Cura Plugin supports importing your existing profiles for Cura **up to and
|
||||
including Cura 15.04.x**. Newer Cura releases (e.g. 15.06 or 2.x) use a different
|
||||
internal format that will *not* work with the current version of the Cura Plugin.
|
||||
|
||||
You can find downloads of Cura 15.04.x for Windows, Mac and Linux `on Ultimaker's download page <https://ultimaker.com/en/products/cura-software/list>`_.
|
||||
|
||||
In order to export a slicing profile from the Cura desktop UI, open it,
|
||||
set up your profile, then click on "File" and there on "Save Profile". You can
|
||||
import the .ini-file this creates via the "Import Profile" button in the
|
||||
Cura Settings within OctoPrint.
|
||||
|
||||
.. _sec-bundledplugins-cura-sourcecode:
|
||||
|
||||
Source code
|
||||
-----------
|
||||
|
||||
The source of the Cura plugin is bundled with OctoPrint and can be found in
|
||||
its source repository under ``src/octoprint/plugins/cura``.
|
||||
@@ -14,7 +14,7 @@ network running Microsoft Windows. You will be able to just double click on the
|
||||
OctoPrint instance icon in "Networks > Other Devices" in your Windows Explorer,
|
||||
which will take you directly to the web frontend.
|
||||
|
||||
The ZeroConf support allows OctoPrint to announce itself to Safari on macOS
|
||||
The ZeroConf support allows OctoPrint to announce itself to Safari on MacOS X
|
||||
on the same network.
|
||||
|
||||
Linux users should install `Avahi <http://avahi.org>`_ and can then use one
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
.. _sec-bundledplugins-errortracking:
|
||||
|
||||
Error Tracking Plugin
|
||||
=====================
|
||||
|
||||
The Error Tracking plugin will cause any logged exceptions in the server and the browser interface to be sent to
|
||||
OctoPrint's `Sentry instance <https://sentry.io/>`_.
|
||||
|
||||
By enabling it you help to gather detailed information on the cause of bugs or other issues. This is especially
|
||||
valuable on release candidates, which is why this plugin will also prompt you to enable error tracking if it detects
|
||||
that you are subscribed to an RC release channel.
|
||||
|
||||
By default, even when enabled it will only be active if you are running a released OctoPrint version, so either a stable
|
||||
release or a release candidate.
|
||||
|
||||
The Error Tracking plugin is using a Sentry instance kindly provided by `sentry.io <https://sentry.io/>`_. For information on their service
|
||||
please refer to their `Security & Compliance documentation <https://sentry.io/security/>`_
|
||||
and their `Privacy Policy <https://sentry.io/privacy/>`_.
|
||||
|
||||
The Error Tracking plugin has been bundled with OctoPrint since version 1.3.11.
|
||||
|
||||
.. _sec-bundledplugins-errortracking-configuration:
|
||||
|
||||
Configuring the plugin
|
||||
----------------------
|
||||
|
||||
The plugin supports the following configuration keys:
|
||||
|
||||
* ``enabled``: Whether to enable error tracking. Defaults to ``false``.
|
||||
* ``enabled_unreleased``: Whether to also enable tracking on unreleased OctoPrint versions (anything not stable releases
|
||||
or release candidates). Defaults to ``false``.
|
||||
* ``unique_id``: Unique instance identifier, auto generated on first activation
|
||||
|
||||
.. _sec-bundledplugins-errortracking-sourcecode:
|
||||
|
||||
Source Code
|
||||
-----------
|
||||
|
||||
The source of the Error Tracking plugin is bundled with OctoPrint and can be
|
||||
found in its source repository under ``src/octoprint/plugins/errortracking``.
|
||||
@@ -0,0 +1,35 @@
|
||||
.. _sec-bundledplugins-forcelogin:
|
||||
|
||||
ForceLogin Plugin
|
||||
=================
|
||||
|
||||
The ForceLogin Plugin comes bundled with OctoPrint (starting with version 1.3.10). It removes the anonymous
|
||||
read-only access that up until 1.3.10 was standard when accessing OctoPrint instances without being logged in and
|
||||
instead forces users to log in if they want to get any kind of information from OctoPrint.
|
||||
|
||||
.. _fig-bundledplugins-forcelogin:
|
||||
.. figure:: ../images/bundledplugins-forcelogin-dialog.png
|
||||
:align: center
|
||||
:alt: Forced login dialog
|
||||
|
||||
OctoPrint's new forced login dialog.
|
||||
|
||||
.. warning::
|
||||
|
||||
Keep in mind that **OctoPrint does not manage your webcam**, it merely embeds it. If you have a webcam,
|
||||
it will still be accessible to users who are not logged in under its (guessable) URL. If you need to restrict
|
||||
access to your webcam, you'll need to find a way to do so directly on the webcam server which - again -
|
||||
is not OctoPrint itself.
|
||||
|
||||
.. note::
|
||||
|
||||
If you want back the old behaviour of allowing anonymous read-only access to your OctoPrint instance, disable
|
||||
the ForceLogin Plugin in OctoPrint's plugin manager.
|
||||
|
||||
.. _sec-bundledplugins-forcelogin-sourcecode:
|
||||
|
||||
Source code
|
||||
-----------
|
||||
|
||||
The source of the ForceLogin plugin is bundled with OctoPrint and can be found in
|
||||
its source repository under ``src/octoprint/plugins/forcelogin``.
|
||||
@@ -9,13 +9,12 @@ Bundled Plugins
|
||||
|
||||
action_command_prompt.rst
|
||||
announcements.rst
|
||||
tracking.rst
|
||||
appkeys.rst
|
||||
backup.rst
|
||||
cura.rst
|
||||
discovery.rst
|
||||
errortracking.rst
|
||||
forcelogin.rst
|
||||
logging.rst
|
||||
loginui.rst
|
||||
pluginmanager.rst
|
||||
printer_safety_check.rst
|
||||
softwareupdate.rst
|
||||
@@ -1,66 +0,0 @@
|
||||
.. _sec-bundledplugins-loginui:
|
||||
|
||||
Login UI
|
||||
========
|
||||
|
||||
The Login UI plugin has been bundled since OctoPrint 1.4.0 and replaces the ForceLogin plugin bundled with prior
|
||||
versions since 1.3.10.
|
||||
|
||||
If anonymous read-only access is disabled in the :ref:`Access Control settings <sec-features-access_control>`
|
||||
it provides a stand alone login dialog that gets displayed instead of OctoPrint's regular UI.
|
||||
|
||||
.. _fig-bundledplugins-loginui:
|
||||
.. figure:: ../images/bundledplugins-loginui-dialog.png
|
||||
:align: center
|
||||
:alt: Login dialog
|
||||
|
||||
OctoPrint's login dialog.
|
||||
|
||||
The plugin allows theming of the dialog through :ref:`a plugin hook <sec-bundledplugins-loginui-hooks-theming>`.
|
||||
|
||||
.. warning::
|
||||
|
||||
Since the plugin is absolutely required for the case of anonymous read-only access because in this case the
|
||||
UI itself could not even fully initialize due to a lack of permissions required to do so, it is hidden in the plugin
|
||||
manager and cannot be disabled through that.
|
||||
|
||||
.. _sec-bundledplugins-loginui-hooks:
|
||||
|
||||
Hooks
|
||||
-----
|
||||
|
||||
.. _sec-bundledplugins-loginui-hooks-theming:
|
||||
|
||||
octoprint.plugin.loginui.theming
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: loginui_theming_hook(*args, **kwargs)
|
||||
|
||||
Support theming of the login dialog, just in case the core UI is themed as well. Use to return a list of additional
|
||||
CSS file URLs to inject into the login dialog HTML.
|
||||
|
||||
Example usage by a plugin:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def loginui_theming():
|
||||
from flask import url_for
|
||||
return [url_for("plugin.myplugin.static", filename="css/loginui_theme.css")]
|
||||
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.plugin.loginui.theming": loginui_theming
|
||||
}
|
||||
|
||||
Only a list of ready-made URLs to CSS files is supported, neither LESS nor JS. Best use
|
||||
url_for like in the example above to be prepared for any configured prefix URLs.
|
||||
|
||||
:return: A list of additional CSS URLs to inject into the login dialog.
|
||||
:rtype: A list of strings.
|
||||
|
||||
.. _sec-bundledplugins-loginui-sourcecode:
|
||||
|
||||
Source Code
|
||||
-----------
|
||||
|
||||
The source of the Anonymous Usage Tracking plugin is bundled with OctoPrint and can be
|
||||
found in its source repository under ``src/octoprint/plugins/loginui``.
|
||||
@@ -82,45 +82,6 @@ under Settings > Plugin Manager, or by directly editing ``config.yaml``:
|
||||
- hidden
|
||||
- plugins
|
||||
|
||||
.. _sec-bundledplugins-pluginmanager-events:
|
||||
|
||||
Events
|
||||
------
|
||||
|
||||
plugin_pluginmanager_install_plugin
|
||||
A plugin was installed.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``id``: the identifier of the installed plugin
|
||||
* ``version``: the version of the installed plugin
|
||||
* ``source``: source from which the plugin was installed, can be an URL or a path in the local file system
|
||||
* ``source_type``: type of source from which the plugin was installed, can be ``url`` or ``path``
|
||||
|
||||
plugin_pluginmanager_uninstall_plugin
|
||||
A plugin was uninstalled.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``id``: the identifier of the uninstalled plugin
|
||||
* ``version``: the version of the uninstalled plugin
|
||||
|
||||
plugin_pluginmanager_enable_plugin
|
||||
A plugin was enabled.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``id``: the identifier of the enabled plugin
|
||||
* ``version``: the version of the enabled plugin
|
||||
|
||||
plugin_pluginmanager_disabled_plugin
|
||||
A plugin was disabled.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``id``: the identifier of the disabled plugin
|
||||
* ``version``: the version of the disabled plugin
|
||||
|
||||
.. _sec-bundledplugins-pluginmanager-hooks:
|
||||
|
||||
Hooks
|
||||
|
||||
@@ -29,20 +29,6 @@ If you know of further printers/printer firmwares that need to be added here, pl
|
||||
unexpectedly and with `catastrophic <https://www.thissmarthouse.net/dont-burn-your-house-down-3d-printing-a-cautionary-tale/>`_
|
||||
`results <https://www.reddit.com/r/3Dprinting/comments/6cekgk/house_fire_thanks_to_cheap_printer_from_china/>`_.
|
||||
|
||||
.. _sec-bundledplugins-printer_safety_check-events:
|
||||
|
||||
Events
|
||||
------
|
||||
|
||||
warning
|
||||
A printer safety warning was triggered.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``check_type``: type of check that was triggered (e.g. ``m115``, ``received`` or ``cap``)
|
||||
* ``check_name``: name of check that was triggered (e.g. ``aneta8``)
|
||||
* ``warning_type``: type of warning that was triggered (e.g. ``firmware-unsafe``)
|
||||
|
||||
.. _sec-bundledplugins-printer_safety_check-source:
|
||||
|
||||
Source Code
|
||||
|
||||
@@ -196,10 +196,6 @@ Version checks
|
||||
* ``checkout_folder``: (mandatory) The full path to the folder with a valid git
|
||||
repository to check.
|
||||
|
||||
* ``pypi_release``: Checks `pypi.org <https://pypi.org>`_ for new releases of a specified package.
|
||||
|
||||
* ``package``: (mandatory) Name of the package which to check.
|
||||
|
||||
* ``command_line``: Uses a provided script to determine whether an update
|
||||
is available. Additional config parameters:
|
||||
|
||||
@@ -329,29 +325,6 @@ The same, but tracking all commits pushed to branch ``devel`` (thus allowing
|
||||
branch: devel
|
||||
pip: 'https://github.com/someUser/OctoPrint-SomePlugin/archive/{target}.zip'
|
||||
|
||||
.. _sec-bundledplugins-softwareupdate-events:
|
||||
|
||||
Events
|
||||
------
|
||||
|
||||
plugin_softwareupdate_update_succeeded
|
||||
An update succeeded.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``target``: update target
|
||||
* ``from_version``: version from which was updated
|
||||
* ``to_version``: version to which was updated
|
||||
|
||||
plugin_softwareupdate_update_failed
|
||||
An update failed.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``target``: update target
|
||||
* ``from_version``: version from which was updated
|
||||
* ``to_version``: version to which was updated
|
||||
|
||||
.. _sec-bundledplugins-softwareupdate-hooks:
|
||||
|
||||
Hooks
|
||||
@@ -389,8 +362,8 @@ octoprint.plugin.softwareupdate.check_config
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
def get_update_information(*args, **kwargs):
|
||||
return dict(
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
.. _sec-bundledplugins-tracking:
|
||||
|
||||
Anonymous Usage Tracking Plugin
|
||||
===============================
|
||||
|
||||
The Anonymous Usage Tracking plugin provides valuable insights into how many instances running what versions of
|
||||
OctoPrint are out there, whether they are successfully completing print jobs and various other metrics.
|
||||
|
||||
By enabling it you help to identify problems with new releases and release candidates early on, and to better tailor
|
||||
OctoPrint's future development to actual use.
|
||||
|
||||
For details on what gets tracked, please refer to `tracking.octoprint.org <https://tracking.octoprint.org>`_
|
||||
and also the `Privacy Policy at tracking.octoprint.org <https://tracking.octoprint.org/privacy>`_.
|
||||
|
||||
The Anonymous Usage Tracking plugin has been bundled with OctoPrint since version 1.3.10.
|
||||
|
||||
.. _sec-bundledplugins-tracking-configuration:
|
||||
|
||||
Configuring the plugin
|
||||
----------------------
|
||||
|
||||
The plugin supports the following configuration keys:
|
||||
|
||||
* ``enabled``: Whether to enable usage tracking. Defaults to ``false``.
|
||||
* ``unique_id``: Unique instance identifier, auto generated on first activation
|
||||
* ``server``: The tracking server to track against. Defaults to a tracking endpoint on ``https://tracking.octoprint.org``.
|
||||
* ``ping``: How often to send a ``ping`` tracking event, in seconds. Defaults to a 15min interval.
|
||||
* ``events``: Granular configuration of enabled tracking events. All default to ``true``.
|
||||
|
||||
* ``startup``: Whether to track startup/shutdown events
|
||||
* ``printjob``: Whether to track print job related events (start, completion, cancel, ...)
|
||||
* ``commerror``: Whether to track communication errors with the printer
|
||||
* ``plugin``: Whether to track plugin related events (install, uninstall, ...)
|
||||
* ``update``: Whether to track update related events (update successful or not, ...)
|
||||
* ``printer``: Whether to track printer related events (connected, firmware, ...)
|
||||
* ``printer_safety_check``: Whether to track warnings of the :ref:`Printer Safety Check <sec-bundledplugins-printer_safety_check>`
|
||||
* ``throttled``: Whether to track throttle events detected on the underlying system
|
||||
|
||||
.. _sec-bundledplugins-tracking-sourcecode:
|
||||
|
||||
Source Code
|
||||
-----------
|
||||
|
||||
The source of the Anonymous Usage Tracking plugin is bundled with OctoPrint and can be
|
||||
found in its source repository under ``src/octoprint/plugins/tracking``.
|
||||
+8
-10
@@ -1,6 +1,4 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
#
|
||||
# OctoPrint documentation build configuration file, created by
|
||||
# sphinx-quickstart on Mon Dec 02 17:08:50 2013.
|
||||
@@ -51,8 +49,8 @@ source_suffix = '.rst'
|
||||
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 = u'OctoPrint'
|
||||
copyright = u'%d-%d, Gina Häußge' % (year_since, year_current) if year_current > year_since else u'%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
|
||||
@@ -209,8 +207,8 @@ htmlhelp_basename = 'OctoPrintdoc'
|
||||
# Grouping the document tree into LaTeX files. List of tuples
|
||||
# (source start file, target name, title, author, documentclass [howto/manual]).
|
||||
#latex_documents = [
|
||||
# ('index', 'OctoPrint.tex', 'OctoPrint Documentation',
|
||||
# 'Gina Häußge', 'manual'),
|
||||
# ('index', 'OctoPrint.tex', u'OctoPrint Documentation',
|
||||
# u'Gina Häußge', 'manual'),
|
||||
#]
|
||||
|
||||
# The name of an image file (relative to this directory) to place at the top of
|
||||
@@ -239,8 +237,8 @@ htmlhelp_basename = 'OctoPrintdoc'
|
||||
# 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)
|
||||
('index', 'octoprint', u'OctoPrint Documentation',
|
||||
[u'Gina Häußge'], 1)
|
||||
]
|
||||
|
||||
# If true, show URL addresses after external links.
|
||||
@@ -253,8 +251,8 @@ 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.',
|
||||
('index', 'OctoPrint', u'OctoPrint Documentation',
|
||||
u'Gina Häußge', 'OctoPrint', 'One line description of project.',
|
||||
'Miscellaneous'),
|
||||
]
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ config.yaml
|
||||
|
||||
If not specified via the command line, the main configuration file ``config.yaml`` for OctoPrint is expected in its
|
||||
settings folder, which unless defined differently via the command line is located at ``~/.octoprint`` on Linux, at
|
||||
``%APPDATA%/OctoPrint`` on Windows and at ``~/Library/Application Support/OctoPrint`` on macOS. If the file is not there,
|
||||
``%APPDATA%/OctoPrint`` on Windows and at ``~/Library/Application Support/OctoPrint`` on MacOS. If the file is not there,
|
||||
you can just create it - it will only get created by OctoPrint once you save settings that deviate from the default
|
||||
settings.
|
||||
|
||||
@@ -29,7 +29,7 @@ Use the following settings to enable access control:
|
||||
# The user manager implementation to use for accessing user information. Currently only a filebased
|
||||
# user manager is implemented which stores configured accounts in a YAML file (Default: users.yaml
|
||||
# in the default configuration folder, see below)
|
||||
userManager: octoprint.access.users.FilebasedUserManager
|
||||
userManager: octoprint.users.FilebasedUserManager
|
||||
|
||||
# The YAML user file to use. If left out defaults to users.yaml in the default configuration folder.
|
||||
userFile: /path/to/users.yaml
|
||||
@@ -62,18 +62,6 @@ Use the following settings to enable access control:
|
||||
# header and login the user without further checks. Use with caution.
|
||||
checkBasicAuthenticationPassword: true
|
||||
|
||||
# Whether to trust remote user headers. If you have setup authentication in front of
|
||||
# OctoPrint and the user names you use there match OctoPrint accounts, by setting this to true users will
|
||||
# be logged into OctoPrint as the user provided in the header. Your should ONLY ENABLE THIS if your
|
||||
# OctoPrint instance is only accessible through a connection locked down through an authenticating reverse proxy!
|
||||
trustRemoteUser: false
|
||||
|
||||
# Header used by the reverse proxy to convey the authenticated user.
|
||||
remoteUserHeader: REMOTE_USER
|
||||
|
||||
# If a remote user is not found, add them. Use this only if all users from the remote system can use OctoPrint.
|
||||
addRemoteUsers: false
|
||||
|
||||
.. _sec-configuration-config_yaml-api:
|
||||
|
||||
API
|
||||
@@ -93,8 +81,7 @@ Settings for the REST API:
|
||||
# Whether to allow cross origin access to the API or not
|
||||
allowCrossOrigin: false
|
||||
|
||||
# Additional app api keys, see REST API > Apps in the docs.
|
||||
# Deprecated since 1.3.11, to be removed in 1.4.0!
|
||||
# Additional app api keys, see REST API > Apps in the docs
|
||||
apps:
|
||||
"some.app.identifier:some_version":
|
||||
pubkey: <RSA pubkey>
|
||||
@@ -290,9 +277,6 @@ The following settings are only relevant to you if you want to do OctoPrint deve
|
||||
# Whether to delete generated web assets on server startup (forcing a regeneration)
|
||||
clean_on_startup: true
|
||||
|
||||
# enable or disable the loading animation
|
||||
showLoadingAnimation: true
|
||||
|
||||
# Settings for the virtual printer
|
||||
virtualPrinter:
|
||||
|
||||
@@ -338,9 +322,6 @@ The following settings are only relevant to you if you want to do OctoPrint deve
|
||||
# Whether the simulated printer should also simulate a heated bed or not
|
||||
hasBed: true
|
||||
|
||||
# Whether the simulated printer should also simulate a heated chamber or not
|
||||
hasChamber: false
|
||||
|
||||
# If enabled, reports the set target temperatures as separate messages from the firmware
|
||||
#
|
||||
# True: > M109 S220.0
|
||||
@@ -428,7 +409,8 @@ The following settings are only relevant to you if you want to do OctoPrint deve
|
||||
# Lines to send on simulated reset
|
||||
resetLines:
|
||||
- start
|
||||
- "Marlin: Virtual Marlin!"
|
||||
- Marlin: Virtual Marlin!
|
||||
- "\x80"
|
||||
- "SD card ok"
|
||||
|
||||
# Initial set of prepared oks to use instead of regular ok (e.g. to simulate
|
||||
@@ -580,9 +562,6 @@ Use the following settings to enable or disable OctoPrint features:
|
||||
- M117
|
||||
- M118
|
||||
|
||||
# whether G90/G91 also influence absolute/relative mode of extruders
|
||||
g90InfluencesExtruder: false
|
||||
|
||||
.. _sec-configuration-config_yaml-folder:
|
||||
|
||||
Folder
|
||||
@@ -687,11 +666,6 @@ plugins are tracked:
|
||||
_disabled:
|
||||
- ...
|
||||
|
||||
# Identifiers of plugins for which python compatibility information will be ignored and
|
||||
# the plugin considered compatible in any case. Only for development, do NOT use in production.
|
||||
_forcedCompatible:
|
||||
- ...
|
||||
|
||||
# The rest are individual plugin settings, each tracked by their identifier, e.g.:
|
||||
some_plugin:
|
||||
some_setting: true
|
||||
@@ -832,19 +806,6 @@ Use the following settings to configure the serial connection to the printer:
|
||||
additionalBaudrates:
|
||||
- 123456
|
||||
|
||||
# Commands which should not be sent to the printer, e.g. because they are known to block serial
|
||||
# communication until physical interaction with the printer as is the case on most firmwares with
|
||||
# the default M0 and M1.
|
||||
blockedCommands:
|
||||
- M0
|
||||
- M1
|
||||
|
||||
# Commands which should cause OctoPrint to pause any ongoing prints.
|
||||
pausingCommands:
|
||||
- M0
|
||||
- M1
|
||||
- M25
|
||||
|
||||
# Commands which are known to take a long time to be acknowledged by the firmware. E.g.
|
||||
# homing, dwelling, auto leveling etc. Defaults to the below commands.
|
||||
longRunningCommands:
|
||||
@@ -971,13 +932,6 @@ Use the following settings to configure the server:
|
||||
# reset the setting to false
|
||||
startOnceInSafeMode: false
|
||||
|
||||
# Signals to OctoPrint that the last startup was incomplete. OctoPrint will then startup
|
||||
# in safe mode
|
||||
incompleteStartup: false
|
||||
|
||||
# Set this to true to make OctoPrint ignore incomplete startups. Helpful for development.
|
||||
ignoreIncompleteStartup: false
|
||||
|
||||
# Secret key for encrypting cookies and such, randomly generated on first run
|
||||
secretKey: someSecretKey
|
||||
|
||||
@@ -1104,15 +1058,6 @@ Use the following settings to configure the server:
|
||||
# How many days to leave unused entries in the preemptive cache config
|
||||
until: 7
|
||||
|
||||
# Configuration of the client IP check to warn about connections from external networks
|
||||
ipCheck:
|
||||
|
||||
# whether to enable the check, defaults to true
|
||||
enabled: true
|
||||
|
||||
# additional non-local subnets to consider trusted, in CIDR notation, e.g. "192.168.1.0/24"
|
||||
trustedSubnets: []
|
||||
|
||||
|
||||
.. note::
|
||||
|
||||
@@ -1142,14 +1087,14 @@ Settings for the built-in slicing support:
|
||||
slicing:
|
||||
|
||||
# Whether to enable slicing support or not
|
||||
enabled: true
|
||||
enabled:
|
||||
|
||||
# Default slicer to use
|
||||
defaultSlicer: null
|
||||
defaultSlicer: cura
|
||||
|
||||
# Default slicing profiles per slicer
|
||||
defaultProfiles:
|
||||
curalegacy: ...
|
||||
cura: ...
|
||||
|
||||
.. _sec-configuration-config_yaml-system:
|
||||
|
||||
@@ -1252,9 +1197,6 @@ Use the following settings to configure webcam support:
|
||||
# Should be left at 1 for RPi1.
|
||||
ffmpegThreads: 1
|
||||
|
||||
# Videocodec to be used for encoding. Defaults to mpeg2video.
|
||||
ffmpegVideoCodec: mpeg2video
|
||||
|
||||
# The bitrate to use for rendering the timelapse video. This gets directly passed to ffmpeg.
|
||||
bitrate: 5000k
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ logging.yaml
|
||||
|
||||
The logging configuration file ``logging.yaml`` for OctoPrint is expected in its settings folder, which unless defined
|
||||
differently on the command line is located at ``~/.octoprint`` on Linux, at ``%APPDATA%/OctoPrint`` on Windows and at
|
||||
``~/Library/Application Support/OctoPrint`` on macOS.
|
||||
``~/Library/Application Support/OctoPrint`` on MacOS.
|
||||
|
||||
You can use it to change the log levels of the individual components within OctoPrint, which might be necessary to help
|
||||
in debugging issues you are experiencing, or to change the configuration of the logging handlers themselves, e.g. in
|
||||
@@ -39,8 +39,8 @@ A list of important components for which an increase in logging might be interes
|
||||
* ``octoprint.filemanager``: the file management layer
|
||||
* ``octoprint.plugin``: the plugin sub system
|
||||
* ``octoprint.plugins.<plugin>``: the plugin ``<plugin>``, e.g. ``octoprint.plugins.discovery`` to change the log level of
|
||||
the :ref:`Discovery plugin <sec-bundledplugins-discovery>` or ``octoprint.plugins.backup``
|
||||
to change the log level of the :ref:`Backup plugin <sec-bundledplugins-backup>`.
|
||||
the `Discovery plugin <https://github.com/foosel/OctoPrint/wiki/Plugin:-Discovery>`_ or ``octoprint.plugins.cura``
|
||||
to change the log level of the `Cura plugin <https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura>`_.
|
||||
* ``octoprint.slicing``: the slicing sub system
|
||||
|
||||
This list will be expanded when deemed necessary.
|
||||
|
||||
@@ -14,34 +14,18 @@ below.
|
||||
* Prerequisites:
|
||||
|
||||
* `Python 2.7 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
|
||||
* `Python 3.7 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
|
||||
* `Git <https://git-scm.com>`_
|
||||
|
||||
* Checkout the OctoPrint sources from their Git repository:
|
||||
|
||||
* ``git clone -b devel https://github.com/foosel/OctoPrint.git``
|
||||
|
||||
* Checkout the OctoPrint sources from their Git repository: ``git clone https://github.com/foosel/OctoPrint.git``
|
||||
* Enter the checked out source folder: ``cd OctoPrint``
|
||||
* Create virtual environments in the checked out source folder for both Python 2.7 and Python 3.7 to use for
|
||||
installing and running OctoPrint and its dependencies (this avoids potential versioning issues for the dependencies
|
||||
with system wide installed instances):
|
||||
|
||||
* PY2: ``virtualenv --python=python2 venv2``
|
||||
* PY3: ``virtualenv --python=python3 venv3``
|
||||
|
||||
* Activate one of the virtual environments:
|
||||
|
||||
* PY2: ``source venv2/bin/activate`` (Linux, macOS) or ``source venv2/Scripts/activate`` (Git Bash under Windows, see below)
|
||||
* PY3: ``source venv3/bin/activate`` (Linux, macOS) or ``source venv3/Scripts/activate`` (Git Bash under Windows, see below)
|
||||
|
||||
* Update ``pip`` in the virtual environment:
|
||||
|
||||
* ``pip install --upgrade pip``
|
||||
|
||||
* Create a virtual environment in the checked out source folder to use for installing and running OctoPrint and its
|
||||
dependencies (this avoids potential versioning issues for the dependencies with system wide installed
|
||||
instances): ``virtualenv venv``
|
||||
* Activate the virtual environment: ``source venv/bin/activate`` (Linux, MacOS) or
|
||||
``source venv/Scripts/activate`` (Git Bash under Windows, see below)
|
||||
* Update ``pip`` in the virtual environment: ``pip install --upgrade pip``
|
||||
* Install OctoPrint in `"editable" mode <https://pip.pypa.io/en/stable/reference/pip_install/#editable-installs>`_,
|
||||
including its regular *and* development and plugin development dependencies:
|
||||
|
||||
* ``pip install -e .[develop,plugins]``
|
||||
including its regular *and* development and plugin development dependencies: ``pip install -e .[develop,plugins]``
|
||||
|
||||
When the virtual environment is activated you can then:
|
||||
|
||||
@@ -49,19 +33,11 @@ When the virtual environment is activated you can then:
|
||||
* run the test suite from the checked out source folder via ``nosetests --with-doctest``
|
||||
* build the documentation from the ``docs`` sub folder of the checked out sources via ``sphinx-build -b html . _build``
|
||||
|
||||
To switch the activated virtual environment, simply activate the new environment as described above.
|
||||
|
||||
To deactivate the virtual environment and return to the system's default Python: ``deactivate``.
|
||||
|
||||
.. _sec-development-environment-source-linux:
|
||||
|
||||
Linux
|
||||
.....
|
||||
|
||||
.. todo::
|
||||
|
||||
This guide is not yet adapted to the concurrent use of Python 2.7 and 3.7 environments during development.
|
||||
|
||||
This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different
|
||||
location, please substitute accordingly.
|
||||
|
||||
@@ -94,7 +70,7 @@ Then:
|
||||
.. code-block:: none
|
||||
|
||||
cd ~/devel
|
||||
git clone -b devel https://github.com/foosel/OctoPrint.git
|
||||
git clone https://github.com/foosel/OctoPrint.git
|
||||
cd OctoPrint
|
||||
virtualenv venv
|
||||
source ./venv/bin/activate
|
||||
@@ -109,16 +85,12 @@ environment.
|
||||
Windows
|
||||
.......
|
||||
|
||||
.. todo::
|
||||
|
||||
This guide is not yet adapted to the concurrent use of Python 2.7 and 3.7 environments during development.
|
||||
|
||||
This assumes you'll host your OctoPrint development checkout at ``C:\Devel\OctoPrint``. If you want to use a different
|
||||
location, please substitute accordingly.
|
||||
|
||||
First download & install:
|
||||
|
||||
* `Python 2.7.15 Windows x86 MSI installer <https://www.python.org/downloads/release/python-2715/>`_
|
||||
* `Python 2.7.12 Windows x86 MSI installer <https://www.python.org/downloads/release/python-2712/>`_
|
||||
|
||||
* make sure to have the installer add Python to the ``PATH`` and have it install ``pip`` too
|
||||
|
||||
@@ -148,10 +120,6 @@ Mac OS X
|
||||
This guide is based on the `Setup Guide for Mac OS X on OctoPrint's wiki <https://github.com/foosel/OctoPrint/wiki/Setup-on-Mac/>`_.
|
||||
Please report back if it works for you, due to lack of access to a Mac I cannot test it myself. Thanks.
|
||||
|
||||
.. todo::
|
||||
|
||||
This guide is not yet adapted to the concurrent use of Python 2.7 and 3.7 environments during development.
|
||||
|
||||
This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different
|
||||
location, please substitute accordingly.
|
||||
|
||||
@@ -190,10 +158,6 @@ You'll need a user account with administrator privileges.
|
||||
IDE Setup
|
||||
---------
|
||||
|
||||
.. todo::
|
||||
|
||||
This guide is not yet adapted to the concurrent use of Python 2.7 and 3.7 environments during development.
|
||||
|
||||
.. todo::
|
||||
|
||||
Using another IDE than the ones below? Please send a
|
||||
@@ -206,10 +170,8 @@ PyCharm
|
||||
.......
|
||||
|
||||
- "File" > "Open ...", select OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``)
|
||||
- **(Linux, Windows)** "File" > "Settings ..." > "Project: OctoPrint" > "Project Interpreter" > "Add local ...", select OctoPrint venv
|
||||
- "File" > "Settings ..." > "Project: OctoPrint" > "Project Interpreter" > "Add local ...", select OctoPrint venv
|
||||
folder (e.g. ``~/devel/OctoPrint/venv`` or ``C:\Devel\OctoPrint\venv``)
|
||||
- **(macOS)** "PyCharm" > "Preferences ..." > "Project: OctoPrint" > "Project Interpreter" > "Add ..." >
|
||||
"Virtualenv Environment > "Existing Environment", select OctoPrint venv folder (e.g. ``~/devel/OctoPrint/venv``)
|
||||
- Right click "src" in project tree, mark as source folder
|
||||
- Add Run/Debug Configuration, select "Python":
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ be found in the full :ref:`config.yaml documentation <sec-configuration-config_y
|
||||
|
||||
The steps to take are as follows:
|
||||
|
||||
* Find config.yaml in the OctoPrint settings folder. Usually in ``~/.octoprint`` on Linux, in ``%APPDATA%/OctoPrint`` on Windows and in ``~/Library/Application Support/OctoPrint`` on macOS.
|
||||
* Find config.yaml in the OctoPrint settings folder. Usually in ``~/.octoprint`` on Linux, in ``%APPDATA%/OctoPrint`` on Windows and in ``~/Library/Application Support/OctoPrint`` on MacOS.
|
||||
* Add or extend the ``devel`` section with:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
+54
-124
@@ -6,6 +6,15 @@ Events
|
||||
|
||||
.. contents::
|
||||
|
||||
|
||||
.. note::
|
||||
|
||||
With release of OctoPrint 1.1.0, the payload data has been harmonized, it is now a key-value-map for all events.
|
||||
Additionally, the format of the placeholders in both system command and gcode command triggers has been changed to
|
||||
accommodate for this new format. Last but not least, the way of specifying event hooks has changed, OctoPrint no longer
|
||||
separates hooks into two sections (gcodeCommandTrigger and systemCommandTrigger) but instead event hooks are now typed
|
||||
to indicate what to do with the command contained.
|
||||
|
||||
.. _sec-events-configuration:
|
||||
|
||||
Configuration
|
||||
@@ -38,13 +47,6 @@ Example
|
||||
- event: PrintDone
|
||||
command: python ~/growl.py -t mygrowlserver -d "Completed {file}" -a OctoPrint -i http://raspi/Octoprint_logo.png
|
||||
type: system
|
||||
- event:
|
||||
- PrintStarted
|
||||
- PrintFailed
|
||||
- PrintDone
|
||||
- PrintCancelled
|
||||
command: python ~/growl.py -t mygrowlserver -d "Event {__eventname} ({name})" -a OctoPrint -i http://raspi/Octoprint_logo.png
|
||||
type: system
|
||||
- event: Connected
|
||||
command:
|
||||
- M115
|
||||
@@ -60,7 +62,6 @@ Placeholders
|
||||
You can use the following generic placeholders in your event hooks:
|
||||
|
||||
* ``{__currentZ}``: the current Z position of the head if known, -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
|
||||
@@ -84,12 +85,6 @@ and its origin via the placeholder ``{origin}``.
|
||||
Available Events
|
||||
================
|
||||
|
||||
.. note::
|
||||
|
||||
Plugins may add additional events via the :ref:`octoprint.events.register_custom_events hook <sec-plugins-hook-events-register_custom_events>`.
|
||||
|
||||
.. _sec-events-available_events-server:
|
||||
|
||||
Server
|
||||
------
|
||||
|
||||
@@ -100,44 +95,20 @@ Shutdown
|
||||
The server is shutting down.
|
||||
|
||||
ClientOpened
|
||||
A client has connected to the push socket.
|
||||
A client has connected to the web server.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``remoteAddress``: the remote address (IP) of the client that connected. On the push socket only available with
|
||||
a valid login session.
|
||||
* ``remoteAddress``: the remote address (IP) of the client that connected
|
||||
|
||||
**Note:** Name changed in version 1.1.0
|
||||
|
||||
ClientAuthed
|
||||
A client has authenticated a user session on the push socket.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``remoteAddress``: the remote address (IP) of the client that authed. On the push socket only available with a
|
||||
valid login session.
|
||||
* ``username``: the name of the user who authed. On the push socket only available with a valid login session.
|
||||
|
||||
ClientClosed
|
||||
A client has disconnected from the push socket.
|
||||
A client has disconnected from the webserver
|
||||
|
||||
Payload:
|
||||
|
||||
* ``remoteAddress``: the remote address (IP) of the client that disconnected. On the push socket only available
|
||||
with a valid login session.
|
||||
|
||||
UserLoggedIn
|
||||
A user logged in. On the push socket only available with a valid login session with admin rights.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``username``: the name of the user who logged in
|
||||
|
||||
UserLoggedOut
|
||||
A user logged out. On the push socket only available with a valid login session with admin rights.
|
||||
|
||||
Payload:
|
||||
* ``username``: the name of the user who logged out
|
||||
* ``remoteAddress``: the remote address (IP) of the client that disconnected
|
||||
|
||||
ConnectivityChanged
|
||||
The server's internet connectivity changed
|
||||
@@ -147,8 +118,6 @@ ConnectivityChanged
|
||||
* ``old``: Old connectivity value (true for online, false for offline)
|
||||
* ``new``: New connectivity value (true for online, false for offline)
|
||||
|
||||
.. _sec-events-available_events-printer_commmunication:
|
||||
|
||||
Printer communication
|
||||
---------------------
|
||||
|
||||
@@ -172,11 +141,7 @@ Disconnected
|
||||
The server has disconnected from the printer
|
||||
|
||||
Error
|
||||
An unrecoverable error has been encountered, either as reported by the firmware (e.g. a thermal runaway) or
|
||||
on the connection.
|
||||
|
||||
Note that this event will not fire for error messages from the firmware that are handled (and as such recovered from)
|
||||
either by OctoPrint or a plugin.
|
||||
An error has occurred in the printer communication.
|
||||
|
||||
Payload:
|
||||
|
||||
@@ -191,8 +156,6 @@ PrinterStateChanged
|
||||
:func:`~octoprint.printer.PrinterInterface.get_state_id` for possible values.
|
||||
* ``state_string``: Text representation of the new state.
|
||||
|
||||
.. _sec-events-available_events-file_handling:
|
||||
|
||||
File handling
|
||||
-------------
|
||||
|
||||
@@ -206,7 +169,9 @@ Upload
|
||||
|
||||
.. deprecated:: 1.3.0
|
||||
|
||||
* ``file``: the file's path within its storage location. To be removed in 1.4.0.
|
||||
* ``file``: the file's path within its storage location
|
||||
|
||||
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
|
||||
|
||||
FileAdded
|
||||
A file has been added to a storage.
|
||||
@@ -288,7 +253,9 @@ MetadataAnalysisStarted
|
||||
|
||||
.. deprecated:: 1.3.0
|
||||
|
||||
* ``file``: the file's path within its storage location. To be removed in 1.4.0.
|
||||
* ``file``: the file's path within its storage location
|
||||
|
||||
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
|
||||
|
||||
MetadataAnalysisFinished
|
||||
The metadata analysis of a file has finished.
|
||||
@@ -302,7 +269,9 @@ MetadataAnalysisFinished
|
||||
|
||||
.. deprecated:: 1.3.0
|
||||
|
||||
* ``file``: the file's path within its storage location. To be removed in 1.4.0.
|
||||
* ``file``: the file's path within its storage location
|
||||
|
||||
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
|
||||
|
||||
FileSelected
|
||||
A file has been selected for printing.
|
||||
@@ -315,8 +284,10 @@ FileSelected
|
||||
|
||||
.. deprecated:: 1.3.0
|
||||
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
|
||||
* ``filename``: the file's name. To be removed in 1.4.0.
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``)
|
||||
* ``filename``: the file's name
|
||||
|
||||
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
|
||||
|
||||
FileDeselected
|
||||
No file is selected any more for printing.
|
||||
@@ -340,8 +311,6 @@ TransferDone
|
||||
* ``local``: the file's name as stored locally
|
||||
* ``remote``: the file's name as stored on SD
|
||||
|
||||
.. _sec-events-available_events-printing:
|
||||
|
||||
Printing
|
||||
--------
|
||||
|
||||
@@ -353,14 +322,13 @@ PrintStarted
|
||||
* ``name``: the file's name
|
||||
* ``path``: the file's path within its storage location
|
||||
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
|
||||
* ``size``: the file's size in bytes (if available)
|
||||
* ``owner``: the user who started the print job (if available)
|
||||
* ``user``: the user who started the print job (if available)
|
||||
|
||||
.. deprecated:: 1.3.0
|
||||
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
|
||||
* ``filename``: the file's name. To be removed in 1.4.0.
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``)
|
||||
* ``filename``: the file's name
|
||||
|
||||
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
|
||||
|
||||
PrintFailed
|
||||
A print failed.
|
||||
@@ -370,15 +338,13 @@ PrintFailed
|
||||
* ``name``: the file's name
|
||||
* ``path``: the file's path within its storage location
|
||||
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
|
||||
* ``size``: the file's size in bytes (if available)
|
||||
* ``owner``: the user who started the print job (if available)
|
||||
* ``time``: the elapsed time of the print when it failed, in seconds (float)
|
||||
* ``reason``: the reason the print failed, either ``cancelled`` or ``error``
|
||||
|
||||
.. deprecated:: 1.3.0
|
||||
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
|
||||
* ``filename``: the file's name. To be removed in 1.4.0.
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``)
|
||||
* ``filename``: the file's name
|
||||
|
||||
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
|
||||
|
||||
PrintDone
|
||||
A print completed successfully.
|
||||
@@ -388,14 +354,14 @@ PrintDone
|
||||
* ``name``: the file's name
|
||||
* ``path``: the file's path within its storage location
|
||||
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
|
||||
* ``size``: the file's size in bytes (if available)
|
||||
* ``owner``: the user who started the print job (if available)
|
||||
* ``time``: the time needed for the print, in seconds (float)
|
||||
|
||||
.. deprecated:: 1.3.0
|
||||
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
|
||||
* ``filename``: the file's name. To be removed in 1.4.0.
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``)
|
||||
* ``filename``: the file's name
|
||||
|
||||
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
|
||||
|
||||
PrintCancelling
|
||||
The print is about to be cancelled.
|
||||
@@ -405,9 +371,6 @@ PrintCancelling
|
||||
* ``name``: the file's name
|
||||
* ``path``: the file's path within its storage location
|
||||
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
|
||||
* ``size``: the file's size in bytes (if available)
|
||||
* ``owner``: the user who started the print job (if available)
|
||||
* ``user``: the user who cancelled the print job (if available)
|
||||
* ``firmwareError``: the firmware error that caused cancelling the print job, if any
|
||||
|
||||
PrintCancelled
|
||||
@@ -418,12 +381,7 @@ PrintCancelled
|
||||
* ``name``: the file's name
|
||||
* ``path``: the file's path within its storage location
|
||||
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
|
||||
* ``size``: the file's size in bytes (if available)
|
||||
* ``owner``: the user who started the print job (if available)
|
||||
* ``time``: the elapsed time of the print when it was cancelled, in seconds (float)
|
||||
* ``user``: the user who cancelled the print job (if available)
|
||||
* ``position``: the print head position at the time of cancelling (if available, not available if recording of the
|
||||
position on cancel is disabled)
|
||||
* ``position``: the print head position at the time of cancelling, if available
|
||||
* ``position.x``: x coordinate, as reported back from the firmware through `M114`
|
||||
* ``position.y``: y coordinate, as reported back from the firmware through `M114`
|
||||
* ``position.z``: z coordinate, as reported back from the firmware through `M114`
|
||||
@@ -437,8 +395,10 @@ PrintCancelled
|
||||
|
||||
.. deprecated:: 1.3.0
|
||||
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
|
||||
* ``filename``: the file's name. To be removed in 1.4.0.
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``)
|
||||
* ``filename``: the file's name
|
||||
|
||||
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
|
||||
|
||||
PrintPaused
|
||||
The print has been paused.
|
||||
@@ -448,11 +408,7 @@ PrintPaused
|
||||
* ``name``: the file's name
|
||||
* ``path``: the file's path within its storage location
|
||||
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
|
||||
* ``size``: the file's size in bytes (if available)
|
||||
* ``owner``: the user who started the print job (if available)
|
||||
* ``user``: the user who paused the print job (if available)
|
||||
* ``position``: the print head position at the time of pausing (if available, not available if the recording of
|
||||
the position on pause is disabled or the pause is completely handled by the printer's firmware)
|
||||
* ``position``: the print head position at the time of pausing, if available
|
||||
* ``position.x``: x coordinate, as reported back from the firmware through `M114`
|
||||
* ``position.y``: y coordinate, as reported back from the firmware through `M114`
|
||||
* ``position.z``: z coordinate, as reported back from the firmware through `M114`
|
||||
@@ -466,8 +422,10 @@ PrintPaused
|
||||
|
||||
.. deprecated:: 1.3.0
|
||||
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
|
||||
* ``filename``: the file's name. To be removed in 1.4.0.
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``)
|
||||
* ``filename``: the file's name
|
||||
|
||||
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
|
||||
|
||||
PrintResumed
|
||||
The print has been resumed.
|
||||
@@ -477,16 +435,13 @@ PrintResumed
|
||||
* ``name``: the file's name
|
||||
* ``path``: the file's path within its storage location
|
||||
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
|
||||
* ``size``: the file's size in bytes (if available)
|
||||
* ``owner``: the user who started the print job (if available)
|
||||
* ``user``: the user who resumed the print job (if available)
|
||||
|
||||
.. deprecated:: 1.3.0
|
||||
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
|
||||
* ``filename``: the file's name. To be removed in 1.4.0.
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``)
|
||||
* ``filename``: the file's name
|
||||
|
||||
.. _sec-events-available_events-gcode_processing:
|
||||
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
|
||||
|
||||
GCODE processing
|
||||
----------------
|
||||
@@ -549,8 +504,6 @@ ToolChange
|
||||
* ``old``: old tool index
|
||||
* ``new``: new tool index
|
||||
|
||||
.. _sec-events-available_events-timelapses:
|
||||
|
||||
Timelapses
|
||||
----------
|
||||
|
||||
@@ -605,8 +558,6 @@ MovieFailed
|
||||
returned a non-0 return code, ``no_frames`` if no frames were captured that could be rendered
|
||||
to a timelapse, or ``unknown`` for any other reason of failure to render.
|
||||
|
||||
.. _sec-events-available_events-slicing:
|
||||
|
||||
Slicing
|
||||
-------
|
||||
|
||||
@@ -615,7 +566,6 @@ SlicingStarted
|
||||
|
||||
Payload:
|
||||
|
||||
* ``slicer``: the used slicer
|
||||
* ``stl``: the STL's filename
|
||||
* ``stl_location``: the STL's location
|
||||
* ``gcode``: the sliced GCODE's filename
|
||||
@@ -627,7 +577,6 @@ SlicingDone
|
||||
|
||||
Payload:
|
||||
|
||||
* ``slicer``: the used slicer
|
||||
* ``stl``: the STL's filename
|
||||
* ``stl_location``: the STL's location
|
||||
* ``gcode``: the sliced GCODE's filename
|
||||
@@ -640,7 +589,6 @@ SlicingCancelled
|
||||
|
||||
Payload:
|
||||
|
||||
* ``slicer``: the used slicer
|
||||
* ``stl``: the STL's filename
|
||||
* ``stl_location``: the STL's location
|
||||
* ``gcode``: the sliced GCODE's filename
|
||||
@@ -651,7 +599,6 @@ SlicingFailed
|
||||
|
||||
Payload:
|
||||
|
||||
* ``slicer``: the used slicer
|
||||
* ``stl``: the STL's filename
|
||||
* ``stl_location``: the STL's location
|
||||
* ``gcode``: the sliced GCODE's filename
|
||||
@@ -667,7 +614,7 @@ SlicingProfileAdded
|
||||
* ``profile``: the profile that was added
|
||||
|
||||
SlicingProfileModified
|
||||
A slicing profile was modified.
|
||||
A new slicing profile was modified.
|
||||
|
||||
Payload:
|
||||
|
||||
@@ -682,25 +629,8 @@ SlicingProfileDeleted
|
||||
* ``slicer``: the slicer for which the profile was deleted
|
||||
* ``profile``: the profile that was deleted
|
||||
|
||||
.. _sec-events-available_events-settings:
|
||||
|
||||
Settings
|
||||
--------
|
||||
|
||||
SettingsUpdated
|
||||
The settings were updated via the REST API.
|
||||
|
||||
This event may also be triggered if calling code of :py:class:`octoprint.settings.Settings.save` or
|
||||
:py:class:`octoprint.plugin.PluginSettings.save` sets the ``trigger_event`` parameter to ``True``.
|
||||
|
||||
.. _sec-events-available_events-printer_profile:
|
||||
|
||||
Printer Profile
|
||||
---------------
|
||||
|
||||
PrinterProfileModified
|
||||
A printer profile was modified.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``identifier``: the identifier of the modified printer profile
|
||||
The internal settings were updated.
|
||||
@@ -3,20 +3,8 @@
|
||||
Access Control
|
||||
==============
|
||||
|
||||
OctoPrint's bundled access control feature allows granular permission control
|
||||
over which users or user groups are allowed to access which parts of OctoPrint.
|
||||
|
||||
The default permissions will deny any kind of access to anonymous (not logged in)
|
||||
users out of the box.
|
||||
|
||||
.. warning::
|
||||
|
||||
Please note that OctoPrint does *not* control the webcam and merely embeds it, and
|
||||
thus also cannot limit access to it. If an anonymous user correctly guesses the
|
||||
webcam URL, they will thus be able to see it.
|
||||
|
||||
If read-only access for anonymous users is enabled, anonymous users will have
|
||||
read-only access to the following parts of the UI:
|
||||
When Access Control is enabled, anonymous users (not logged in) will only see
|
||||
the read-only parts of the UI which are the following:
|
||||
|
||||
* printer state
|
||||
* available gcode files and stats (upload is disabled)
|
||||
@@ -28,17 +16,17 @@ read-only access to the following parts of the UI:
|
||||
* any components provided through plugins which are enabled for anonymous
|
||||
users
|
||||
|
||||
Logged in users without admin flag will be allowed to access everything besides the
|
||||
Settings and System Commands, which are admin-only.
|
||||
Logged in users will get access to everything besides the Settings and System
|
||||
Commands, which are admin-only.
|
||||
|
||||
If Access Control is disabled, everything is directly accessible. **That also
|
||||
includes all administrative functionality as well as full control over the
|
||||
printer**, and without the need for an :ref:`API key <sec-api-general-authorization>`!
|
||||
printer!**
|
||||
|
||||
Upon first start a configuration wizard is provided which allows configuration
|
||||
of the first administrator account or alternatively disabling Access Control
|
||||
(which is **NOT** recommended for systems that are directly accessible via the
|
||||
internet or other untrusted networks!).
|
||||
Internet!).
|
||||
|
||||
.. hint::
|
||||
|
||||
@@ -51,29 +39,6 @@ internet or other untrusted networks!).
|
||||
publicly reachable by everyone with an internet connection, even with access
|
||||
control enabled.
|
||||
|
||||
.. _sec-features-access_control-hooks:
|
||||
|
||||
Available Extension Hooks
|
||||
-------------------------
|
||||
|
||||
There are two hooks for plugins to utilize in order to
|
||||
add new configurable permissions into the system and/or adjust the styling of the
|
||||
login dialog.
|
||||
|
||||
.. _sec-features-access_control-hooks-permissions:
|
||||
|
||||
octoprint.access.permissions
|
||||
............................
|
||||
|
||||
See :ref:`here <sec-plugins-hook-permissions>`.
|
||||
|
||||
.. _sec-features-access_control-hooks-loginui:
|
||||
|
||||
octoprint.plugin.loginui.theming
|
||||
................................
|
||||
|
||||
See :ref:`here <sec-bundledplugins-loginui-hooks-theming>`.
|
||||
|
||||
.. _sec-features-access_control-rerunning_wizard:
|
||||
|
||||
Rerunning the wizard
|
||||
|
||||
@@ -11,7 +11,7 @@ is clicked.
|
||||
|
||||
Unless :ref:`configured otherwise <sec-configuration-config_yaml-folder>`, OctoPrint expects scripts to be located in
|
||||
the ``scripts/gcode`` folder in OctoPrint configuration directory (per default ``~/.octoprint`` on Linux, ``%APPDATA%\OctoPrint``
|
||||
on Windows and ``~/Library/Application Support/OctoPrint`` on macOS).
|
||||
on Windows and ``~/Library/Application Support/OctoPrint`` on MacOS).
|
||||
|
||||
These GCODE scripts are backed by the templating engine Jinja2, allowing more than just
|
||||
simple "send-as-is" scripts but making use of a full blown templating language in order to create your scripts. To
|
||||
@@ -157,13 +157,9 @@ The ``disable_hotends`` snippet is defined as follows:
|
||||
.. code-block:: jinja
|
||||
:caption: Default ``disable_hotends`` snippet
|
||||
|
||||
{% if printer_profile.extruder.sharedNozzle %}
|
||||
M104 T0 S0
|
||||
{% else %}
|
||||
{% for tool in range(printer_profile.extruder.count) %}
|
||||
M104 T{{ tool }} S0
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
||||
The ``disable_bed`` snippet is defined as follows:
|
||||
|
||||
|
||||
+10
-17
@@ -5,20 +5,19 @@ Safe mode
|
||||
*********
|
||||
|
||||
With the advent of support for plugins in OctoPrint, it quickly became apparent that some of the bugs
|
||||
reported on OctoPrint's bug tracker were actually bugs with installed third party plugins or language
|
||||
packs instead of OctoPrint itself.
|
||||
reported on OctoPrint's bug tracker were actually bugs with installed third party plugins instead of
|
||||
OctoPrint itself.
|
||||
|
||||
To allow an easier identification of these cases, OctoPrint 1.3.0 introduced safe mode. Starting
|
||||
OctoPrint in safe mode disables all plugins (and starting with 1.3.13 also all language packs) that are
|
||||
not bundled with OctoPrint, allowing to easier identify most cases where a third party plugin or language
|
||||
pack is the culprit of an observed issue.
|
||||
OctoPrint in safe mode disables all plugins that are not bundled with OctoPrint, allowing to easier
|
||||
identify most cases where a third party plugin is the culprit of an observed issue.
|
||||
|
||||
Additionally, OctoPrint allows uninstalling plugins and language packs in this mode, allowing recovery
|
||||
from cases where a third party addition causes the server to not start up or the web interface to not
|
||||
render or function correctly anymore.
|
||||
Additionally, OctoPrint allows uninstalling plugins in this mode, allowing recovery from cases where
|
||||
a third party plugin causes the server to not start up or the web interface to not render or function
|
||||
correctly anymore.
|
||||
|
||||
Whenever reporting an issue with OctoPrint, please always attempt to reproduce it in safe mode as well to
|
||||
ensure it really is an issue in OctoPrint itself and now caused by one of your installed third party additions.
|
||||
ensure it really is an issue in OctoPrint itself and now caused by one of your installed third party plugins.
|
||||
|
||||
.. _sec-features-safemode-how:
|
||||
|
||||
@@ -74,17 +73,11 @@ When OctoPrint is running in safe mode the following changes to its normal opera
|
||||
|
||||
* OctoPrint will not enable any of the installed third party plugins. OctoPrint considers all plugins third
|
||||
party plugins that do not ship with OctoPrint's sources, so any plugins installed either via `pip` or
|
||||
into OctoPrint's plugin folder at ``~/.octoprint/plugins`` (Linux), ``%APPDATA%/OctoPrint/plugins`` (Windows) and
|
||||
``~/Library/Application Support/OctoPrint/plugins`` (macOS).
|
||||
* OctoPrint will not enable any of the installed third party language packs. OctoPrint considers all language packs
|
||||
third party language packs that do not ship with OctoPrint's sources, so any language plugins installed
|
||||
through the language pack manager within settings and/or stored in the language pack folder at
|
||||
``~/.octoprint/translations`` (Linux), ``%APPDATA%/OctoPrint/translations`` (Windows) or
|
||||
``~/Library/Application Support/OctoPrint/translations`` (macOS).
|
||||
into OctoPrint's plugin folder at ``~/.octoprint/plugins`` (Linux), ``%APPDATA%/OctoPrint`` (Windows) and
|
||||
``~/Library/Application Support/OctoPrint`` (MacOS).
|
||||
* OctoPrint will still allow to uninstall third party plugins through the built-in Plugin Manager.
|
||||
* OctoPrint will still allow to disable (bundled) plugins that are still enabled.
|
||||
* OctoPrint will not allow to enable third party plugins.
|
||||
* OctoPrint will still allow to manage language packs.
|
||||
* OctoPrint's web interface will display a notification to remind you that it is running in
|
||||
safe mode.
|
||||
|
||||
|
||||
File renamed without changes.
|
Before Width: | Height: | Size: 9.6 KiB After Width: | Height: | Size: 9.6 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 58 KiB After Width: | Height: | Size: 38 KiB |
+2
-2
@@ -11,7 +11,7 @@ and released under the `GNU Affero General Public License V3 <http://www.gnu.org
|
||||
|
||||
Its website can be found at `octoprint.org <https://octoprint.org/>`_.
|
||||
|
||||
The community forum is available at `community.octoprint.org <https://community.octoprint.org/>`_.
|
||||
The community forum is available at `discourse.octoprint.org <https://discourse.octoprint.org/>`_.
|
||||
|
||||
The FAQ can be accessed by following `faq.octoprint.org <https://faq.octoprint.org/>`_.
|
||||
|
||||
@@ -23,7 +23,7 @@ If you enjoy OctoPrint, please consider becoming a regular supporter!
|
||||
.. note::
|
||||
|
||||
This documentation currently focuses primarily on developers and less on end users. If you are interested in
|
||||
helping to change this, please get in touch `on the forum <https://community.octoprint.org/>`_!
|
||||
helping to change this, please get in touch `on the forum <https://discourse.octoprint.org/>`_!
|
||||
|
||||
Contents
|
||||
========
|
||||
|
||||
@@ -210,64 +210,6 @@
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.printer.getChamberState(data, opts)
|
||||
|
||||
Retrieves the current printer chamber state/temperature information, and optionally also the temperature
|
||||
history.
|
||||
|
||||
The ``flags`` object can be used to specify the data to retrieve further via the following
|
||||
properties:
|
||||
|
||||
* ``history``: a boolean value to specify whether the temperature history should be included (``true``)
|
||||
or not (``false``), defaults to it not being included
|
||||
* ``limit``: an integer value to specify how many history entries to include
|
||||
|
||||
See :ref:`Retrieve the current bed state <sec-api-printer-chamberstate>` for more details.
|
||||
|
||||
:param object flags: Flags that further specify which data to retrieve, see above for details
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.printer.setChamberTargetTemperature(target, opts)
|
||||
|
||||
Sets the given temperature on the printer's heated chamber (if available).
|
||||
|
||||
``target`` is expected to be the target temperature as a float value.
|
||||
|
||||
**Example:**
|
||||
|
||||
Set the chamber to 50°C.
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
OctoPrint.printer.setChamberTargetTemperature(50.0);
|
||||
|
||||
See the ``target`` command in :ref:`Issue a chamber command <sec-api-printer-chambercommand>` for more details.
|
||||
|
||||
:param float target: The target to set
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.printer.setChamberTemperatureOffset(offset, opts)
|
||||
|
||||
Sets the given temperature offset for the printer's heated chamber (if available).
|
||||
|
||||
``offset`` is expected to be the temperature offset to set.
|
||||
|
||||
**Example:**
|
||||
|
||||
Set the offset for the chamber to -5°C.
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
OctoPrint.printer.setChamberTemperatureOffset(-5);
|
||||
|
||||
See the ``offset`` command in :ref:`Issue a chamber command <sec-api-printer-chambercommand>` for more details.
|
||||
|
||||
:param object offsets: The offsets to set
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.printer.jog(amounts, opts)
|
||||
|
||||
Jogs the specified axes by the specified ``amounts``.
|
||||
|
||||
@@ -42,7 +42,7 @@
|
||||
To register for all message types, provide ``*`` as the type to register for.
|
||||
|
||||
``handler`` is expected to be a function accepting one object parameter ``eventObj``, consisting
|
||||
of the received message as property ``event`` and the received payload (if any) as property ``data``.
|
||||
of the received message as property ``key`` and the received payload (if any) as property ``data``.
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
.. _sec-modules-users:
|
||||
|
||||
octoprint.access.users
|
||||
----------------------
|
||||
octoprint.users
|
||||
---------------
|
||||
|
||||
.. automodule:: octoprint.access.users
|
||||
.. automodule:: octoprint.users
|
||||
:members:
|
||||
|
||||
|
||||
@@ -6,10 +6,4 @@ octoprint.util
|
||||
.. automodule:: octoprint.util
|
||||
:members:
|
||||
|
||||
.. _sec-modules-util-commandline:
|
||||
|
||||
octoprint.util.commandline
|
||||
--------------------------
|
||||
|
||||
.. automodule:: octoprint.util.commandline
|
||||
:members:
|
||||
@@ -13,7 +13,6 @@ plugin subsystem about themselves. These are simple package attributes defined i
|
||||
# ...
|
||||
|
||||
__plugin_name__ = "My Plugin"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
def __plugin_load__():
|
||||
# whatever you need to do to load your plugin, if anything at all
|
||||
pass
|
||||
@@ -53,20 +52,6 @@ The following properties are recognized:
|
||||
``__plugin_license__``
|
||||
License of your plugin, optional, overrides the license specified in ``setup.py`` if provided.
|
||||
|
||||
.. _sec-plugins-controlproperties-plugin_pythoncompat:
|
||||
|
||||
``__plugin_pythoncompat__``
|
||||
Python compatibility string of your plugin, optional, defaults to ``>=2.7,<3`` if not set and thus Python 2 but no
|
||||
Python 3 compatibility.
|
||||
|
||||
If your plugin is compatible to Python 3, you should set this to ``>=2.7,<4``, otherwise your plugin will not load
|
||||
on OctoPrint instances installed under Python 3.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
|
||||
|
||||
.. _sec-plugins-controlproperties-plugin_implementation:
|
||||
|
||||
``__plugin_implementation__``
|
||||
|
||||
@@ -41,9 +41,6 @@ development environment::
|
||||
|
||||
[...]
|
||||
|
||||
Setting up a local development environment will most likely be less painful than developing directly
|
||||
on the Pi. So do yourself the favor and do that instead where possible.
|
||||
|
||||
.. important::
|
||||
|
||||
This tutorial assumes you are running OctoPrint 1.3.0 and up. Please make sure your version of
|
||||
@@ -57,13 +54,12 @@ We'll start at the most basic form a plugin can take - just a few simple lines o
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_version__ = "1.0.0"
|
||||
__plugin_description__ = "A quick \"Hello World\" example plugin for OctoPrint"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
|
||||
Saving this as ``helloworld.py`` in ``~/.octoprint/plugins`` yields you something resembling these log entries upon server startup::
|
||||
|
||||
@@ -79,10 +75,7 @@ Saving this as ``helloworld.py`` in ``~/.octoprint/plugins`` yields you somethin
|
||||
|
||||
OctoPrint found that plugin in the folder and took a look into it. The name and the version it displays in that log
|
||||
entry it got from the ``__plugin_name__`` and ``__plugin_version__`` lines. It also read the description from
|
||||
``__plugin_description__`` and stored it in an internal data structure, but we'll just ignore this for now. Additionally
|
||||
there is ``__plugin_pythoncompat__`` which tells OctoPrint here that your plugin can be run under any Python versions
|
||||
between 2.7 and 4. That is necessary so that your plugin will be loadable in OctoPrint instances running under either
|
||||
Python 2 or Python 3, and compatibility to both should be your goal.
|
||||
``__plugin_description__`` and stored it in an internal data structure, but we'll just ignore this for now.
|
||||
|
||||
.. _sec-plugins-gettingstarted-sayinghello:
|
||||
|
||||
@@ -93,11 +86,11 @@ Apart from being discovered by OctoPrint, our plugin does nothing yet. We want t
|
||||
"Hello World!" to the log upon server startup. Modify our ``helloworld.py`` like this:
|
||||
|
||||
.. code-block:: python
|
||||
:emphasize-lines: 4-8,14
|
||||
:emphasize-lines: 4-8,13
|
||||
:linenos:
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -108,7 +101,6 @@ Apart from being discovered by OctoPrint, our plugin does nothing yet. We want t
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_version__ = "1.0.0"
|
||||
__plugin_description__ = "A quick \"Hello World\" example plugin for OctoPrint"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
and restart OctoPrint. You now get this output in the log::
|
||||
@@ -292,13 +284,13 @@ of information now defined twice:
|
||||
|
||||
The nice thing about our plugin now being a proper Python package is that OctoPrint can and will access the metadata defined
|
||||
within ``setup.py``! So, we don't really need to define all this data twice. Remove ``__plugin_name__``, ``__plugin_version__``
|
||||
and ``__plugin_description__`` from ``__init__.py``, but leave ``__plugin_implementation__`` and ``__plugin_pythoncompat__``:
|
||||
and ``__plugin_description__`` from ``__init__.py``:
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -306,7 +298,6 @@ and ``__plugin_description__`` from ``__init__.py``, but leave ``__plugin_implem
|
||||
def on_after_startup(self):
|
||||
self._logger.info("Hello World!")
|
||||
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
and restart OctoPrint::
|
||||
@@ -323,8 +314,8 @@ Our "Hello World" Plugin still gets detected fine, but it's now listed under the
|
||||
:emphasize-lines: 10
|
||||
:linenos:
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -333,7 +324,6 @@ Our "Hello World" Plugin still gets detected fine, but it's now listed under the
|
||||
self._logger.info("Hello World!")
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
|
||||
@@ -372,8 +362,8 @@ add the :class:`TemplatePlugin` to our ``HelloWorldPlugin`` class:
|
||||
:emphasize-lines: 7
|
||||
:linenos:
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -383,7 +373,6 @@ add the :class:`TemplatePlugin` to our ``HelloWorldPlugin`` class:
|
||||
self._logger.info("Hello World!")
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
Next, we'll create a sub folder ``templates`` underneath our ``octoprint_helloworld`` folder, and within that a file
|
||||
@@ -439,8 +428,8 @@ Let's take a look at how all that would look in our plugin's ``__init__.py``:
|
||||
:emphasize-lines: 8, 10, 12-13
|
||||
:linenos:
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -454,7 +443,6 @@ Let's take a look at how all that would look in our plugin's ``__init__.py``:
|
||||
return dict(url="https://en.wikipedia.org/wiki/Hello_world")
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
Restart OctoPrint. You should see something like this::
|
||||
@@ -474,8 +462,8 @@ Adjust your plugin's ``__init__.py`` like this:
|
||||
:emphasize-lines: 15-16
|
||||
:linenos:
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -492,7 +480,6 @@ Adjust your plugin's ``__init__.py`` like this:
|
||||
return dict(url=self._settings.get(["url"]))
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
Also adjust your plugin's ``templates/helloworld_navbar.jinja2`` like this:
|
||||
@@ -582,8 +569,8 @@ again since we don't use that anymore:
|
||||
:emphasize-lines: 15-19
|
||||
:linenos:
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -603,7 +590,6 @@ again since we don't use that anymore:
|
||||
]
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
Restart OctoPrint and shift-reload your browser. Your link in the navigation bar should still point to the URL we
|
||||
@@ -680,8 +666,8 @@ like so:
|
||||
:emphasize-lines: 9,22-25
|
||||
:linenos:
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -707,7 +693,6 @@ like so:
|
||||
)
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
Note how we did not add another entry to the return value of :func:`~octoprint.plugin.TemplatePlugin.get_template_configs`.
|
||||
@@ -861,8 +846,8 @@ a reference to our CSS file:
|
||||
:emphasize-lines: 26
|
||||
:linenos:
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -890,7 +875,6 @@ a reference to our CSS file:
|
||||
)
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
OctoPrint by default bundles all CSS, JavaScript and LESS files to reduce the amount of requests necessary to fully
|
||||
@@ -947,8 +931,8 @@ Then adjust our returned assets to include our LESS file as well:
|
||||
:emphasize-lines: 27
|
||||
:linenos:
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -977,7 +961,6 @@ Then adjust our returned assets to include our LESS file as well:
|
||||
)
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
|
||||
|
||||
+63
-273
@@ -28,7 +28,6 @@ or as ``postfix`` (after the existing lines).
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
from past import basestring
|
||||
self._gcode_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.scripts")
|
||||
|
||||
# ...
|
||||
@@ -36,7 +35,7 @@ or as ``postfix`` (after the existing lines).
|
||||
for hook in self._gcodescript_hooks:
|
||||
try:
|
||||
retval = self._gcodescript_hooks[hook](self, "gcode", scriptName)
|
||||
except Exception:
|
||||
except:
|
||||
self._logger.exception("Error while processing gcodescript hook %s" % hook)
|
||||
else:
|
||||
if retval is None:
|
||||
@@ -45,8 +44,10 @@ or as ``postfix`` (after the existing lines).
|
||||
continue
|
||||
|
||||
def to_list(data):
|
||||
if isinstance(data, basestring):
|
||||
data = map(x.strip() for x in data.split("\n"))
|
||||
if isinstance(data, str):
|
||||
data = map(str.strip, data.split("\n"))
|
||||
elif isinstance(data, unicode):
|
||||
data = map(unicode.strip, data.split("\n"))
|
||||
|
||||
if isinstance(data, (list, tuple)):
|
||||
return list(data)
|
||||
@@ -200,93 +201,30 @@ Available plugin hooks
|
||||
.. contents::
|
||||
:local:
|
||||
|
||||
.. _sec-plugins-hook-permissions:
|
||||
.. _sec-plugins-hook-accesscontrol-appkey:
|
||||
|
||||
octoprint.access.permissions
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: additional_permissions_hook(*args, **kwargs)
|
||||
|
||||
Return a list of additional permissions to register in the system on behalf of the plugin. Use this
|
||||
to add granular permissions to your plugin which can be configured for users and user groups in the general
|
||||
access control settings of OctoPrint.
|
||||
|
||||
Additional permissions must be modelled as ``dict``s with at least a ``key`` and ``name`` field. Possible
|
||||
fields are as follows:
|
||||
|
||||
* ``key``: A key for the permission to be used for referring to it from source code. This will turned uppercase
|
||||
and prefixed with ``PLUGIN_<PLUGIN IDENTIFIER>_`` before being made available on ``octoprint.access.permissions.Permissions``,
|
||||
e.g. ``my_permission`` on the plugin with identifier ``example`` turns into ``PLUGIN_EXAMPLE_MY_PERMISSION`` and
|
||||
can be accessed as ``octoprint.access.permissions.Permissions.PLUGIN_EXAMPLE_MY_PERMISSION`` on the server and
|
||||
``permissions.PLUGIN_EXAMPLE_MY_PERMISSION`` on the ``AccessViewModel`` on the client. Must only contain a-z, A-Z, 0-9 and _.
|
||||
* ``name``: A human readable name for the permission.
|
||||
* ``description``: A human readable description of the permission.
|
||||
* ``permissions``: A list of permissions this permission includes, by key.
|
||||
* ``roles``: A list of roles this permission includes. Roles are simple strings you define. Usually one role will
|
||||
suffice.
|
||||
* ``dangerous``: Whether this permission should be considered dangerous (``True``) or not (``False``)
|
||||
* ``default_groups``: A list of standard groups this permission should be apply to by default. Standard groups
|
||||
are ``admins``, ``users``, ``readonly`` and ``guests``
|
||||
|
||||
The following example is based on some actual code included in the bundled Application Keys plugin and defines
|
||||
one additional permission called ``ADMIN`` with a role ``admin`` which is marked as dangerous (since it gives
|
||||
access to the management to other user's application keys) and by default will only be given to the standard admin
|
||||
group:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def get_additional_permissions(*args, **kwargs):
|
||||
return [
|
||||
dict(key="ADMIN",
|
||||
name="Admin access",
|
||||
description=gettext("Allows administrating all application keys"),
|
||||
roles=["admin"],
|
||||
dangerous=True,
|
||||
default_groups=[ADMIN_GROUP])
|
||||
]
|
||||
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.access.permissions": get_additional_permissions
|
||||
}
|
||||
|
||||
Once registered it can be referenced under the key ``PLUGIN_APPKEYS_ADMIN``.
|
||||
|
||||
:return: A list of additional permissions to register in the system.
|
||||
:rtype: A list of dicts.
|
||||
|
||||
.. _sec-plugins-hook-users-factory:
|
||||
|
||||
octoprint.access.users.factory
|
||||
octoprint.accesscontrol.appkey
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: user_manager_factory_hook(components, settings, *args, **kwargs)
|
||||
.. py:function:: acl_appkey_hook(*args, **kwargs)
|
||||
|
||||
Return a :class:`~octoprint.access.users.UserManager` instance to use as global user manager object. This will
|
||||
be called only once during initial server startup.
|
||||
By handling this hook plugins may register additional :ref:`App session key providers <sec-api-apps-sessionkey>`
|
||||
within the system.
|
||||
|
||||
The provided ``components`` is a dictionary containing the already initialized system components:
|
||||
Overrides this to return your additional app information to be used for validating app session keys. You'll
|
||||
need to return a list of 3-tuples of the format (id, version, public key).
|
||||
|
||||
* ``plugin_manager``: The :class:`~octoprint.plugin.core.PluginManager`
|
||||
* ``printer_profile_manager``: The :class:`~octoprint.printer.profile.PrinterProfileManager`
|
||||
* ``event_bus``: The :class:`~octoprint.events.EventManager`
|
||||
* ``analysis_queue``: The :class:`~octoprint.filemanager.analysis.AnalysisQueue`
|
||||
* ``slicing_manager``: The :class:`~octoprint.slicing.SlicingManager`
|
||||
* ``file_manager``: The :class:`~octoprint.filemanager.FileManager`
|
||||
* ``plugin_lifecycle_manager``: The :class:`~octoprint.server.LifecycleManager`
|
||||
* ``preemptive_cache``: The :class:`~octoprint.server.util.flask.PreemptiveCache`
|
||||
The ``id`` should be the (unique) identifier of the app. Using a domain prefix might make sense here, e.g.
|
||||
``org.octoprint.example.MyApp``.
|
||||
|
||||
If the factory returns anything but ``None``, it will be assigned to the global ``userManager`` instance.
|
||||
``version`` should be a string specifying the version of the app for which the public key is valid. You can
|
||||
provide the string ``any`` here, in which case the provided public key will be valid for all versions of the
|
||||
app for which no specific public key is defined.
|
||||
|
||||
If none of the registered factories return a user manager instance, the class referenced by the ``config.yaml``
|
||||
entry ``accessControl.userManager`` will be initialized if possible, otherwise a stock
|
||||
:class:`~octoprint.access.users.FilebasedUserManager` will be instantiated, linked to the default user storage
|
||||
file ``~/.octoprint/users.yaml``.
|
||||
|
||||
:param dict components: System components to use for user manager instance initialization
|
||||
:param SettingsManager settings: The global settings manager instance to fetch configuration values from if necessary
|
||||
:return: The ``userManager`` instance to use globally.
|
||||
:rtype: UserManager subclass or None
|
||||
Finally, the public key is expected to be provided as a PKCS1 string without newlines.
|
||||
|
||||
:return: A list of 3-tuples as described above
|
||||
:rtype: list
|
||||
|
||||
.. _sec-plugins-hook-accesscontrol-keyvalidator:
|
||||
|
||||
@@ -299,7 +237,7 @@ octoprint.accesscontrol.keyvalidator
|
||||
|
||||
``apikey`` will be the API key as read from the request headers.
|
||||
|
||||
Hook handlers are expected to return a :class:`~octoprint.access.users.User` instance here that will then be considered that
|
||||
Hook handlers are expected to return a :class:`~octoprint.users.User` instance here that will then be considered that
|
||||
user making the request. By returning ``None`` or nothing at all, hook handlers signal that they do not handle the
|
||||
provided key.
|
||||
|
||||
@@ -317,7 +255,7 @@ octoprint.accesscontrol.keyvalidator
|
||||
|
||||
:param str apikey: The API key to validate
|
||||
:return: The user in whose name the request will be processed further
|
||||
:rtype: :class:`~octoprint.access.users.User`
|
||||
:rtype: :class:`~octoprint.users.User`
|
||||
|
||||
.. _sec-plugins-hook-cli-commands:
|
||||
|
||||
@@ -442,10 +380,10 @@ octoprint.cli.commands
|
||||
OctoPrint's CLI.
|
||||
:rtype: list
|
||||
|
||||
.. _sec-plugins-hook-comm-protocol-firmware-info:
|
||||
.. _sec-plugins-hook-comm-firmware-info:
|
||||
|
||||
octoprint.comm.protocol.firmware.info
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
octoprint.comm.firmware.info
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: firmware_info_hook(comm_instance, firmware_name, firmware_data, *args, **kwargs)
|
||||
|
||||
@@ -475,10 +413,10 @@ octoprint.comm.protocol.firmware.info
|
||||
:param str firmware_name: The name of the parsed capability
|
||||
:param dict firmware_data: All data contained in the ``M115`` report
|
||||
|
||||
.. _sec-plugins-hook-comm-protocol-firmware-capabilities:
|
||||
.. _sec-plugins-hook-comm-firmware-capabilities:
|
||||
|
||||
octoprint.comm.firmware.protocol.capabilities
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
octoprint.comm.firmware.capabilities
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: firmware_capability_hook(comm_instance, capability, enabled, already_defined, *args, **kwargs)
|
||||
|
||||
@@ -824,10 +762,9 @@ octoprint.comm.protocol.scripts
|
||||
make sure to only proceed with returning additional scripts if the ``script_type`` and ``script_name`` match
|
||||
handled scripts. If not, None should be returned directly.
|
||||
|
||||
If the hook handler has something to add to the specified script, it may return a 2-tuple, a 3-tuple or a 4-tuple with the first entry
|
||||
If the hook handler has something to add to the specified script, it may return a 2-tuple or a 3-tuple with the first entry
|
||||
defining the prefix (what to *prepend* to the script in question), the second entry defining the postfix (what to
|
||||
*append* to the script in question), and finally if desired a dictionary of variables to be made available to the script on third and additional tags to set on the
|
||||
commands on fourth position. Both prefix and postfix can be None to signify that nothing should be prepended
|
||||
*append* to the script in question), and finally if desired a dictionary of variables to be made available to the script. Both prefix and postfix can be None to signify that nothing should be prepended
|
||||
respectively appended.
|
||||
|
||||
The returned prefix and postfix entries may be either iterables of script lines or a string including newlines of the script lines (which
|
||||
@@ -966,34 +903,6 @@ octoprint.comm.transport.serial.factory
|
||||
:rtype: A serial instance implementing implementing the methods ``readline(...)``, ``write(...)``, ``close()`` and
|
||||
optionally ``baudrate`` and ``timeout`` attributes as described above.
|
||||
|
||||
.. _sec-plugins-hook-events-register_custom_events:
|
||||
|
||||
octoprint.events.register_custom_events
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: register_custom_events_hook(*args, **kwargs)
|
||||
|
||||
Return a list of custom :ref:`events <sec-events>` to register in the system for your plugin.
|
||||
|
||||
Should return a list of strings which represent the custom events. Their name on the `octoprint.events.Events` object
|
||||
will be the returned value transformed into upper case ``CAMEL_CASE`` and prefixed with ``PLUGIN_<IDENTIFIER>``. Their
|
||||
value will be prefixed with ``plugin_<identifier>_``.
|
||||
|
||||
Example:
|
||||
|
||||
Consider the following hook part of a plugin with the identifier ``myplugin``. It will register two custom events
|
||||
in the system, ``octoprint.events.Events.PLUGIN_MYPLUGIN_MY_CUSTOM_EVENT`` with value ``plugin_myplugin_my_custom_event``
|
||||
and ``octoprint.events.Events.PLUGIN_MYPLUGIN_MY_OTHER_CUSTOM_EVENT`` with value ``plugin_myplugin_my_other_custom_event``.
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
def register_custom_events(*args, **kwargs):
|
||||
return ["my_custom_event", "my_other_custom_event"]
|
||||
|
||||
:return: A list of custom events to register
|
||||
:rtype: list
|
||||
|
||||
.. _sec-plugins-hook-filemanager-analysis-factory:
|
||||
|
||||
octoprint.filemanager.analysis.factory
|
||||
@@ -1102,27 +1011,6 @@ octoprint.filemanager.preprocessor
|
||||
:return: The `file_object` as passed in or None, or a replaced version to use instead for further processing.
|
||||
:rtype: AbstractFileWrapper or None
|
||||
|
||||
.. _sec-plugins-hook-plugin-loginui-theming:
|
||||
|
||||
octoprint.plugin.loginui.theming
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
See :ref:`here <sec-bundledplugins-loginui-hooks-theming>`.
|
||||
|
||||
.. _sec-plugins-hook-plugin-pluginmanager-reconnect:
|
||||
|
||||
octoprint.plugin.pluginmanager.reconnect_hooks
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
See :ref:`here <sec-bundledplugins-pluginmanager-hooks-reconnect_hooks>`.
|
||||
|
||||
.. _sec-plugins-hook-plugin-softwareupdate-check_config:
|
||||
|
||||
octoprint.plugin.softwareupdate.check_config
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
See :ref:`here <sec-bundledplugins-softwareupdate-hooks-check_config>`.
|
||||
|
||||
.. _sec-plugins-hook-printer-factory:
|
||||
|
||||
octoprint.printer.factory
|
||||
@@ -1141,8 +1029,9 @@ octoprint.printer.factory
|
||||
* ``analysis_queue``: The :class:`~octoprint.filemanager.analysis.AnalysisQueue`
|
||||
* ``slicing_manager``: The :class:`~octoprint.slicing.SlicingManager`
|
||||
* ``file_manager``: The :class:`~octoprint.filemanager.FileManager`
|
||||
* ``app_session_manager``: The :class:`~octoprint.server.util.flask.AppSessionManager`
|
||||
* ``plugin_lifecycle_manager``: The :class:`~octoprint.server.LifecycleManager`
|
||||
* ``user_manager``: The :class:`~octoprint.access.users.UserManager`
|
||||
* ``user_manager``: The :class:`~octoprint.users.UserManager`
|
||||
* ``preemptive_cache``: The :class:`~octoprint.server.util.flask.PreemptiveCache`
|
||||
|
||||
If the factory returns anything but ``None``, it will be assigned to the global ``printer`` instance.
|
||||
@@ -1200,91 +1089,6 @@ octoprint.printer.estimation.factory
|
||||
:return: The :class:`~octoprint.printer.estimation.PrintTimeEstimator` class to use, or a factory method
|
||||
:rtype: class or function
|
||||
|
||||
.. _sec-plugins-hook-octoprint-printer-sdcardupload:
|
||||
|
||||
octoprint.printer.sdcardupload
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: sd_card_upload_hook(printer, filename, path, start_callback, success_callback, failure_callback, *args, **kwargs)
|
||||
|
||||
Via this hook plugins can change the way files are being uploaded to the sd card of the printer.
|
||||
|
||||
Implementations **must** call the provided ``start_callback`` on start of the file transfer and either the ``success_callback``
|
||||
or ``failure_callback`` on the end of the file transfer, depending on whether it was successful or not.
|
||||
|
||||
The ``start_callback`` has the following signature:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def start_callback(local_filename, remote_filename):
|
||||
# ...
|
||||
|
||||
``local_filename`` must be the name of the file on the ``local`` storage, ``remote_filename`` the name of the file
|
||||
to be created on the ``sdcard`` storage.
|
||||
|
||||
``success_callback`` and ``failure_callback`` both have the following signature:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def success_or_failure_callback(local_filename, remote_filename, elapsed):
|
||||
# ...
|
||||
|
||||
``local_filename`` must be the name of the file on the ``local`` storage, ``remote_filename`` the name of the file
|
||||
to be created on the ``sdcard`` storage. ``elapsed`` is the elapsed time in seconds.
|
||||
|
||||
If the hook is going to handle the upload, it must return the (future) remote filename of the file on the ``sdcard``
|
||||
storage. If it returns ``None`` (or an otherwise falsy value), OctoPrint will interpret this as the hook not going to
|
||||
handle the file upload, in which case the next hook or - if no other hook is registered - the default implementation
|
||||
will be called.
|
||||
|
||||
**Example**
|
||||
|
||||
The following example creates a dummy SD card uploader that does nothing but sleep for ten seconds when a file
|
||||
is supposed to be uploaded. Note that the long running process of sleeping for ten seconds is extracted into its
|
||||
own thread, which is important in order to not block the main application!
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
import threading
|
||||
import logging
|
||||
import time
|
||||
|
||||
def nop_upload_to_sd(printer, filename, path, sd_upload_started, sd_upload_succeeded, sd_upload_failed, *args, **kwargs):
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
remote_name = printer._get_free_remote_name(filename)
|
||||
logger.info("Starting dummy SDCard upload from {} to {}".format(filename, remote_name))
|
||||
|
||||
sd_upload_started(filename, remote_name)
|
||||
|
||||
def process():
|
||||
logger.info("Sleeping 10s...")
|
||||
time.sleep(10)
|
||||
logger.info("And done!")
|
||||
sd_upload_succeeded(filename, remote_name, 10)
|
||||
|
||||
thread = threading.Thread(target=process)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
return remote_name
|
||||
|
||||
__plugin_name__ = "No-op SDCard Upload Test"
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.printer.sdcardupload": nop_upload_to_sd
|
||||
}
|
||||
|
||||
.. versionadded:: 1.3.11
|
||||
|
||||
:param object printer: the :py:class:`~octoprint.printer.PrinterInterface` instance the hook was called from
|
||||
:param str filename: filename on the ``local`` storage
|
||||
:param str path: path of the file in the local file system
|
||||
:param function sd_upload_started: callback for when the upload started
|
||||
:param function sd_upload_success: callback for successful finish of upload
|
||||
:param function sd_upload_failure: callback for failure of upload
|
||||
:return: the name of the file on the ``sdcard`` storage or ``None``
|
||||
:rtype: string or ``None``
|
||||
|
||||
.. _sec-plugins-hook-server-http-after_request:
|
||||
|
||||
octoprint.server.api.after_request
|
||||
@@ -1294,7 +1098,8 @@ octoprint.server.api.after_request
|
||||
|
||||
Allows adding additional after-request-handlers to API endpoints defined by OctoPrint itself and installed plugins.
|
||||
|
||||
Your plugin might need this to further restrict access to API methods.
|
||||
Your plugin might need this to further restrict access to API methods. See the bundled "Force Login" plugin for a
|
||||
usage example.
|
||||
|
||||
.. important::
|
||||
|
||||
@@ -1309,7 +1114,8 @@ octoprint.server.api.before_request
|
||||
|
||||
Allows adding additional before-request-handlers to API endpoints defined by OctoPrint itself and installed plugins.
|
||||
|
||||
Your plugin might need this to further restrict access to API methods.
|
||||
Your plugin might need this to further restrict access to API methods. See the bundled "Force Login" plugin for a
|
||||
usage example.
|
||||
|
||||
.. important::
|
||||
|
||||
@@ -1324,7 +1130,8 @@ octoprint.server.http.access_validator
|
||||
|
||||
Allows adding additional access validators to the default tornado routers.
|
||||
|
||||
Your plugin might need to this to restrict acccess to downloads and webcam snapshots further.
|
||||
Your plugin might need to this to restrict acccess to downloads and webcam snapshots further. See the bundled
|
||||
"Force Login" plugin for a usage example.
|
||||
|
||||
.. important::
|
||||
|
||||
@@ -1404,14 +1211,6 @@ octoprint.server.http.routes
|
||||
view of the blueprint will thus not be reachable since processing of the request will directly be handed over
|
||||
to your defined handler class.
|
||||
|
||||
.. important::
|
||||
|
||||
If you want your route to support CORS if it's enabled in OctoPrint, your `RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>`_
|
||||
needs to implement the :class:`~octoprint.server.util.tornado.CorsSupportMixin` for this to work. Note that all of
|
||||
:class:`~octoprint.server.util.tornado.LargeResponseHandler`, :class:`~octoprint.server.util.tornado.UrlProxyHandler`,
|
||||
:class:`~octoprint.server.util.tornado.StaticDataHandler` and :class:`~octoprint.server.util.tornado.DeprecatedEndpointHandler`
|
||||
already implement this mixin.
|
||||
|
||||
.. important::
|
||||
|
||||
Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully.
|
||||
@@ -1439,18 +1238,6 @@ octoprint.server.http.routes
|
||||
:return: a list of 3-tuples with additional routes as defined above
|
||||
:rtype: list
|
||||
|
||||
.. _sec-plugins-hook-server-sockjs-authed:
|
||||
|
||||
octoprint.server.sockjs.authed
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: socket_authed_hook(socket, user, *args, **kwargs):
|
||||
|
||||
Allows plugins to be notified that a user got authenticated or deauthenticated on the socket (e.g. due to logout).
|
||||
|
||||
:param object socket: the socket object which is about to be registered
|
||||
:param object user: the user that got authenticated on the socket, or None if the user got deauthenticated
|
||||
|
||||
.. _sec-plugins-hook-server-sockjs-register:
|
||||
|
||||
octoprint.server.sockjs.register
|
||||
@@ -1629,34 +1416,37 @@ octoprint.ui.web.templatetypes
|
||||
:return: a list of 3-tuples (template type, rule, sorting spec)
|
||||
:rtype: list
|
||||
|
||||
.. _sec-plugins-hook-timelapse-capture-pre:
|
||||
.. _sec-plugins-hook-users-factory:
|
||||
|
||||
octoprint.timelapse.capture.pre
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
octoprint.users.factory
|
||||
~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: capture_pre_hook(filename)
|
||||
.. py:function:: user_manager_factory_hook(components, settings, *args, **kwargs)
|
||||
|
||||
Perform specific actions prior to capturing a timelapse frame.
|
||||
Return a :class:`~octoprint.users.UserManager` instance to use as global user manager object. This will
|
||||
be called only once during initial server startup.
|
||||
|
||||
``filename`` will be the future path of the frame to be saved.
|
||||
The provided ``components`` is a dictionary containing the already initialized system components:
|
||||
|
||||
:param str filename: The future path of the frame to be saved.
|
||||
:return: None
|
||||
:rtype: None
|
||||
* ``plugin_manager``: The :class:`~octoprint.plugin.core.PluginManager`
|
||||
* ``printer_profile_manager``: The :class:`~octoprint.printer.profile.PrinterProfileManager`
|
||||
* ``event_bus``: The :class:`~octoprint.events.EventManager`
|
||||
* ``analysis_queue``: The :class:`~octoprint.filemanager.analysis.AnalysisQueue`
|
||||
* ``slicing_manager``: The :class:`~octoprint.slicing.SlicingManager`
|
||||
* ``file_manager``: The :class:`~octoprint.filemanager.FileManager`
|
||||
* ``app_session_manager``: The :class:`~octoprint.server.util.flask.AppSessionManager`
|
||||
* ``plugin_lifecycle_manager``: The :class:`~octoprint.server.LifecycleManager`
|
||||
* ``preemptive_cache``: The :class:`~octoprint.server.util.flask.PreemptiveCache`
|
||||
|
||||
.. _sec-plugins-hook-timelapse-capture-post:
|
||||
If the factory returns anything but ``None``, it will be assigned to the global ``userManager`` instance.
|
||||
|
||||
octoprint.timelapse.capture.post
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
If none of the registered factories return a user manager instance, the class referenced by the ``config.yaml``
|
||||
entry ``accessControl.userManager`` will be initialized if possible, otherwise a stock
|
||||
:class:`~octoprint.users.FilebasedUserManager` will be instantiated, linked to the default user storage
|
||||
file ``~/.octoprint/users.yaml``.
|
||||
|
||||
.. py:function:: capture_post_hook(filename, success)
|
||||
:param dict components: System components to use for user manager instance initialization
|
||||
:param SettingsManager settings: The global settings manager instance to fetch configuration values from if necessary
|
||||
:return: The ``userManager`` instance to use globally.
|
||||
:rtype: UserManager subclass or None
|
||||
|
||||
Perform specific actions after capturing a timelapse frame.
|
||||
|
||||
``filename`` will be the path of the frame that should have been saved.
|
||||
``sucesss`` indicates whether the capture was successful or not.
|
||||
|
||||
:param str filename: The path of the frame that should have been saved.
|
||||
:param boolean success: Indicates whether the capture was successful or not.
|
||||
:return: None
|
||||
:rtype: None
|
||||
@@ -16,4 +16,3 @@ Developing Plugins
|
||||
viewmodels.rst
|
||||
gettingstarted.rst
|
||||
distributing.rst
|
||||
python3_migration.rst
|
||||
@@ -41,8 +41,10 @@ An overview of these properties follows.
|
||||
OctoPrint's file manager, an instance of :class:`octoprint.filemanager.FileManager`.
|
||||
``self._printer``
|
||||
OctoPrint's printer management object, an instance of :class:`octoprint.printer.PrinterInterface`.
|
||||
``self._app_session_manager``
|
||||
OctoPrint's application session manager, an instance of :class:`octoprint.server.util.flask.AppSessionManager`.
|
||||
``self._user_manager``
|
||||
OctoPrint's user manager, an instance of :class:`octoprint.access.users.UserManager`.
|
||||
OctoPrint's user manager, an instance of :class:`octoprint.users.UserManager`.
|
||||
``self._connectivity_checker``
|
||||
OctoPrint's connectivity checker, an instance of :class:`octoprint.util.ConnectivityChecker`.
|
||||
|
||||
|
||||
+9
-44
@@ -68,14 +68,11 @@ calls are done is as follows:
|
||||
|
||||
* Plugins with a return value that is not ``None`` for :meth:`~octoprint.plugin.core.SortablePlugin.get_sorting_key`
|
||||
for the provided sorting context will be ordered among each other first. If the returned order number is equal for
|
||||
two or more implementations, they will be sorted first by whether they come bundled with OctoPrint or not, then by
|
||||
their identifier.
|
||||
* After that follow plugins which returned ``None`` (the default). They are first sorted by whether they come bundled
|
||||
with OctoPrint or not, then by their identifier.
|
||||
two or more implementations, the plugin's identifier will be the next sorting criteria.
|
||||
* After that follow plugins which returned ``None`` (the default). They are sorted by their identifier.
|
||||
|
||||
Example: Consider four plugin implementations implementing the :class:`~octoprint.plugin.StartupPlugin` mixin, called
|
||||
``plugin_a``, ``plugin_b``, ``plugin_c`` and ``plugin_d``, the latter coming bundled with OctoPrint. ``plugin_a``
|
||||
and ``plugin_d`` don't override :meth:`~octoprint.plugin.core.SortablePlugin.get_sorting_key`.
|
||||
Example: Consider three plugin implementations implementing the :class:`~octoprint.plugin.StartupPlugin` mixin, called
|
||||
``plugin_a``, ``plugin_b`` and ``plugin_c``. ``plugin_a`` doesn't override :meth:`~octoprint.plugin.core.SortablePlugin.get_sorting_key`.
|
||||
``plugin_b`` and ``plugin_c`` both return ``1`` for the sorting context ``StartupPlugin.on_startup``, ``None`` otherwise:
|
||||
|
||||
.. code-block:: python
|
||||
@@ -102,7 +99,7 @@ and ``plugin_d`` don't override :meth:`~octoprint.plugin.core.SortablePlugin.get
|
||||
|
||||
class PluginB(octoprint.plugin.StartupPlugin):
|
||||
|
||||
def get_sorting_key(self, context):
|
||||
def get_sorting_key(context):
|
||||
if context == "StartupPlugin.on_startup":
|
||||
return 1
|
||||
return None
|
||||
@@ -123,7 +120,7 @@ and ``plugin_d`` don't override :meth:`~octoprint.plugin.core.SortablePlugin.get
|
||||
|
||||
class PluginC(octoprint.plugin.StartupPlugin):
|
||||
|
||||
def get_sorting_key(self, context):
|
||||
def get_sorting_key(context):
|
||||
if context == "StartupPlugin.on_startup":
|
||||
return 1
|
||||
return None
|
||||
@@ -137,45 +134,13 @@ and ``plugin_d`` don't override :meth:`~octoprint.plugin.core.SortablePlugin.get
|
||||
|
||||
__plugin_implementation__ = PluginC()
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
:caption: plugin_d.py
|
||||
|
||||
# in this example this is bundled with OctoPrint
|
||||
import octoprint.plugin
|
||||
|
||||
class PluginD(octoprint.plugin.StartupPlugin):
|
||||
|
||||
def on_startup(self, *args, **kwargs):
|
||||
self._logger.info("PluginD starting up")
|
||||
|
||||
def on_after_startup(self, *args, **kwargs):
|
||||
self._logger.info("PluginD started up")
|
||||
|
||||
__plugin_implementation__ = PluginD()
|
||||
|
||||
OctoPrint will detect that ``plugin_b`` and ``plugin_c`` define a order number, and since it's identical for both (``1``)
|
||||
will order both plugins based first on their bundling status and then on their plugin identifier.
|
||||
``plugin_a`` and ``plugin_d`` don't define a sort key and hence will be
|
||||
put after the other two, with ``plugin_d`` coming *before* ``plugin_a`` since it comes bundled with OctoPrint.
|
||||
The execution order of the ``on_startup`` method will hence be ``plugin_b``, ``plugin_c``, ``plugin_d``, ``plugin_a``.
|
||||
will order both plugins based on their plugin identifier. ``plugin_a`` doesn't define a sort key and hence will be
|
||||
put after the other two. The execution order of the ``on_startup`` method will hence be ``plugin_b``, ``plugin_c``, ``plugin_a``.
|
||||
|
||||
Now, the execution order of the ``on_after_startup`` method will be determined based on another sorting context,
|
||||
``StartupPlugin.on_after_startup`` for which all of the plugins return ``None``. Hence, the execution order of the
|
||||
``on_after_startup`` method will be ordered first by bundle status, then by plugin identifier: ``plugin_d``, ``plugin_a``, ``plugin_b``, ``plugin_c``.
|
||||
|
||||
This will result in the following messages to be generated:
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
Plugin B starting up
|
||||
Plugin C starting up
|
||||
Plugin D starting up
|
||||
Plugin A starting up
|
||||
Plugin D started up
|
||||
Plugin A started up
|
||||
Plugin B started up
|
||||
Plugin C started up
|
||||
``on_after_startup`` method will be purely ordered by plugin identifier, ``plugin_a``, ``plugin_b``, ``plugin_c``.
|
||||
|
||||
.. _sec-plugins-mixins-injectedproperties:
|
||||
|
||||
|
||||
@@ -1,349 +0,0 @@
|
||||
.. _sec-plugins-python3:
|
||||
|
||||
Migrating to Python 3
|
||||
=====================
|
||||
|
||||
Python 2 is now EOL as of January 1st 2020. With the release of 1.4.0 OctoPrint will be compatible to both Python 2 and
|
||||
Python 3.
|
||||
|
||||
However, the same doesn't automatically hold true for all of the third party plugins for OctoPrint out there - it will
|
||||
fall to their authors to ensure compatibility to both Python versions.
|
||||
|
||||
This guide is supposed to help plugin authors in making sure their plugins run under Python 2 as well as Python 3,
|
||||
which for now is the goal for OctoPrint's ecosystem, as we'll have to live with existing legacy Python 2 installations
|
||||
for a while to come (the plan is to stay Python 2 compatible until roughly a year after the release of 1.4.0).
|
||||
|
||||
.. contents::
|
||||
:local:
|
||||
|
||||
.. _sec-plugins-python3-venv:
|
||||
|
||||
How to get a Python 3 virtual environment with OctoPrint
|
||||
--------------------------------------------------------
|
||||
|
||||
In order to test your plugins for Python 3 compatibility and also to allow for ongoing maintenance against both Python
|
||||
versions, you should create a Python 3 virtual environment next to your Python 2 one. You can then quickly switch between
|
||||
Python 2 and Python 3 simply by ``activate``-ing whichever one you need.
|
||||
|
||||
You can create a Python 3 virtualenv next to your (existing) Python 2 virtualenv and then just activate which one you
|
||||
currently want to use.
|
||||
|
||||
After installing Python 3 on your development system it's as easy as supplying ``--python=/path/to/python3executable``
|
||||
to ``virtualenv``, e.g.:
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
virtualenv --python=/usr/bin/python3 venv3
|
||||
|
||||
That will have the virtualenv be created based on Python 3, regardless of whether it's currently running under Python
|
||||
2 or 3. The same works for Python 2 btw:
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
virtualenv --python=/usr/bin/python2 venv2
|
||||
|
||||
After creating the virtual environment, make sure to activate & install OctoPrint into it:
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
source venv3/bin/activate
|
||||
pip install "OctoPrint>=1.4.0rc1"
|
||||
|
||||
Then create an editable install of your plugin, start the server and start testing:
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
pip install -e path/to/your/plugin
|
||||
octoprint serve --debug
|
||||
|
||||
.. note::
|
||||
|
||||
On Windows that will probably look something like this instead:
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
virtualenv --python=C:/Python37/python.exe venv37
|
||||
venv3/Script/activate.bat
|
||||
pip install "OctoPrint>=1.4.0rc1"
|
||||
pip install -e path/to/your/plugin
|
||||
octoprint serve --debug
|
||||
|
||||
.. note::
|
||||
|
||||
If you want to migrate your existing OctoPrint install *on OctoPi* to Python 3, I suggest to first make a
|
||||
:ref:`backup <sec-bundledplugins-backup>`, then move the existing venv ``/home/pi/oprint`` out of the way and
|
||||
create a new one based on Python 3 (which should already be present on current OctoPi images):
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
mv ~/oprint ~/oprint.py2
|
||||
virtualenv --python=/usr/bin/python3 oprint
|
||||
source ~/oprint/bin/activate
|
||||
pip install "OctoPrint>=1.4.0rc1"
|
||||
sudo service octoprint restart
|
||||
|
||||
.. _sec-plugins-python3-markup:
|
||||
|
||||
Telling OctoPrint your plugin is Python 3 ready
|
||||
-----------------------------------------------
|
||||
|
||||
In order for OctoPrint to even load your plugin when it's running under Python 3, it first needs to know your plugin is
|
||||
compatible to a Python 3 environment. By default OctoPrint will assume your plugin isn't and refuse to load it when
|
||||
running under Python 3 itself.
|
||||
|
||||
To tell OctoPrint about this, all you need is to set the ``__plugin_pythoncompat__`` property in your plugins's ``__init__.py``
|
||||
accordingly, e.g.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
|
||||
This would tell OctoPrint that your plugin is compatible to all Python versions between 2.7 and 3.x. This should be
|
||||
your target compatibility range for now.
|
||||
|
||||
If at a later date you want to go all-in on Python 3 and mark your plugin as no longer supporting Python 2, tell
|
||||
OctoPrint about this as well:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
__plugin_pythoncompat__ = ">=3,<4"
|
||||
|
||||
.. note::
|
||||
|
||||
You can also tell OctoPrint to ignore the Python compatibility flags for a specific plugin via `config.yaml`:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
plugins:
|
||||
_forcedCompatible:
|
||||
- "myplugin"
|
||||
- "anotherplugin"
|
||||
|
||||
Note that this should only be used temporarily during testing and migration, or to mark an important plugin
|
||||
not under your own control that actually works fine under Python 3 out of the box as compatible while waiting
|
||||
until the plugin author has pushed an update including the needed flags. Do not just blindly mark third party
|
||||
plugins as compatible and then open support requests if that causes issues in your setup.
|
||||
|
||||
Once your plugin is ensured to be compatible and you've released a new version that includes the necessary compatibility
|
||||
flag and changes, is done you also need to mark up your plugin in the Official Plugin Repository (if it's registered
|
||||
therein) so that OctoPrint's built-in Plugin Manager will see that your plugin is compatible as well and allow users
|
||||
to install it through it. In order to do that, you need to add a new flag compatibility.python to the front matter in
|
||||
your plugin registration file and file a pull request for that. Adjust the markdown file so that it contains this:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
compatibility:
|
||||
python: ">=2.7,<3"
|
||||
|
||||
The value here follows the same mechanism as the ``__plugin_pythoncompat__`` property, so ``>=2.7,<3`` for 2 and 3
|
||||
support and ``>=3,<4`` for 3+ support.
|
||||
|
||||
.. warning::
|
||||
|
||||
Do **not** just mark your plugin as compatible without diligent testing that it actually does work as expected and
|
||||
without flooding ``octoprint.log`` with warnings and errors!
|
||||
|
||||
.. _sec-plugins-python3-pitfalls:
|
||||
|
||||
Common pitfalls during migration
|
||||
--------------------------------
|
||||
|
||||
Some of the changes in Python 3 compared to Python 2 are sadly backwards incompatible and usually cause a number of
|
||||
common issues in code written for Python 2 when run under Python 3. By now they are pretty well documented and there
|
||||
exist a number of helpful and comprehensive migration guides, three of which I want to mention here.
|
||||
|
||||
One is the official Python 3 porting guide `Porting Python 2 Code to Python 3 <https://docs.python.org/3/howto/pyporting.html>`__
|
||||
which sums up all the important changes and also gives hints on how best to go about running a project which supports
|
||||
both versions for now.
|
||||
|
||||
The second is the `Writing Python 2-3 compatible code <https://python-future.org/compatible_idioms.html>`__ cheat sheet
|
||||
from the Python-Future project, which is a comprehensive list of idioms that are compatible to both Python 2 and 3 and
|
||||
will make your code run under both, utilizing `future <https://python-future.org/>`__ and `six <https://six.readthedocs.io/>`__.
|
||||
I can strongly recommend this cheat sheet, it's what primarily guided me during the migration phase as well.
|
||||
|
||||
The third one is the free online book `Support Python 3: An in-depth guide <http://python3porting.com/toc.html>`__, and
|
||||
especially its chapter on `Common migration problems <http://python3porting.com/problems.html>`__ in which you'll find
|
||||
extensive descriptions of the most troublesome changes in Python 3 and how to overcome them. Please note that with
|
||||
regards to the contents of this book, we are aiming for the "Python 2 and Python 3 without conversion" strategy, so
|
||||
code that runs in both environments. Sadly this book is a bit outdated by now and still references some long-out versions
|
||||
as "upcoming", so with regards to compatible idioms to use, best stick to the Python-Future cheat sheet.
|
||||
|
||||
Looking at the issues encountered by some plugin authors and also my own experiences during the Python 3 migration of
|
||||
OctoPrint's code, the most common problems for these scenarios seem to be byte vs unicode issues, trouble with absolute
|
||||
imports, changes in integer division behaviour and the switch of map, filter and zip to return iterators instead of
|
||||
lists and causing issues in the following code due to that.
|
||||
|
||||
.. _sec-plugins-python3-pitfalls-strings:
|
||||
|
||||
Bytes vs unicode
|
||||
................
|
||||
|
||||
One of if not the most problematic change between Python 2 and 3 surely must be the change in string handling. Under
|
||||
Python 2 your basic string was a byte string, but it could also magically turn into a unicode string depending on what
|
||||
you wrote into it. That did cause some confusion, especially in APIs, and caused quite a mess, which is why the decision
|
||||
was made to go for distinct text and binary types instead, and making the string literal always be a (unicode) text.
|
||||
|
||||
.. note::
|
||||
|
||||
Please note that these changes in string handling also affect several Python APIs that operate on files and streams
|
||||
and thus might also affect parts of OctoPrint's plugin interface that inherit from these APIs. Currently only one such
|
||||
case has been reported, as OctoPrint's :py:class:`~octoprint.filemanager.util.LineProcessorStream` will return bytes
|
||||
instead of str on its ``process_line`` function under Python 3 - so here's a heads-up if your plugin happens to utilize that.
|
||||
|
||||
Obviously, that will lead to issues in code using "just strings" when run under Python 2 vs 3. The first step to solve
|
||||
these problems would be to make your scripts behave the same under Python 2 and 3 by putting this right at the top of
|
||||
all your plugin's python files:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from __future__ import unicode_literals
|
||||
|
||||
That will make your files behave as if they were running under Python 3, even when run under Python 2, and your string
|
||||
literals will now be the text data type, which - annoyingly - is a different one under Python 2 vs 3, ``unicode`` vs ``str`` to
|
||||
be exact. Heads-up here - under Python 2 there's also a ``str`` type, but that one is for binary data. Yes, I know, this
|
||||
ain't fun.
|
||||
|
||||
In any case, once you've done this, make sure that everything in your code that should be text is text (``unicode`` under
|
||||
Python 2, ``str`` under Python 3), and everything that should be binary is binary (``str`` under Python 2, ``bytes`` under Python 3).
|
||||
A good rule of thumb is that you usually want to use text as much as possible within your application and only convert
|
||||
to/from bytes at the outskirts, e.g. when writing to a file, a socket or something else machine like. Note that you do
|
||||
NOT need to convert to bytes when implementing API endpoints that return JSON, as that should use text with unicode
|
||||
anyhow.
|
||||
|
||||
OctoPrint includes two utility methods you should use to ensure your strings enter/exit your code in the right format,
|
||||
under both Python versions: :py:func:`octoprint.util.to_bytes` and :py:func:`octoprint.util.to_unicode`. Use them to ensure the correct data
|
||||
types and to avoid weird conversion and encoding issues during runtime.
|
||||
|
||||
You can read more about this specific issue in the corresponding section of the
|
||||
`Python porting guide <https://docs.python.org/3/howto/pyporting.html#text-versus-binary-data>`__ and also in the
|
||||
`cheat sheet <https://python-future.org/compatible_idioms.html#strings-and-bytes>`__.
|
||||
|
||||
.. _sec-plugins-python3-pitfalls-imports:
|
||||
|
||||
Absolute imports
|
||||
................
|
||||
|
||||
Python 3 now defaults to absolute imports, meaning that trying to import a sub package with a
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
import my_sub_package
|
||||
|
||||
will now fail with an error. You'll need to explicitly make the import a relative one:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from . import my_sub_package
|
||||
|
||||
To make your code behave the same in that regard unter both Python 2 and Python 3, you should add the corresponding
|
||||
future import:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from __future__ import absolute_imports
|
||||
|
||||
You can read more about this specific issue in the
|
||||
`cheat sheet <https://python-future.org/compatible_idioms.html#imports-relative-to-a-package>`__ and also in
|
||||
`the book <http://python3porting.com/problems.html#relative-import-problems>`__.
|
||||
|
||||
.. _sec-plugins-python3-pitfalls-intdiv:
|
||||
|
||||
Integer division
|
||||
................
|
||||
|
||||
When you divide two integers in Python 2 you'll get back an integer, rounded down. In Python 3 however you'll now get
|
||||
a float. That means you might have to revisit some places where you do integer divisions and might rely on the result
|
||||
to be an integer as well (e.g. when using a calculation result as an index in an array or something like that).
|
||||
|
||||
Yet again there's a future-import to apply to your files in order to at least have them behave the same in that regard
|
||||
under both Python 2 and Python 3:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from __future__ import division
|
||||
|
||||
You can read more about this specific issue in the `Python porting guide <https://docs.python.org/3/howto/pyporting.html#division>`__
|
||||
and in the `cheat sheet <https://python-future.org/compatible_idioms.html#division>`__.
|
||||
|
||||
.. _sec-plugins-python3-pitfalls-iterators:
|
||||
|
||||
Iterators instead of list from map, filter, zip
|
||||
...............................................
|
||||
|
||||
The built-in functions ``map``, ``filter`` and ``zip`` return a ``list`` with their result in Python 2. In Python 3 they have been
|
||||
switched to returning iterators. That can cause trouble with code handling the result (e.g. if you try to return it as
|
||||
part of a JSON response on an API endpoint).
|
||||
|
||||
The easiest way to solve this is to make sure to wrap any ``map``/``filter``/``zip`` calls into a ``list`` constructor if the result is
|
||||
to be used outside of the calling code (even though that comes with a small performance penalty under Python 2):
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
result1 = filter(lambda x: x is not None, my_collection)
|
||||
result2 = list(filter(lambda x: x is not None, my_collection))
|
||||
|
||||
assert(isinstance(result1, list)) # Python 2 passes, Python 3 fails
|
||||
assert(isinstance(result2, list)) # Python 2 and 3 pass
|
||||
|
||||
There also exist further options, take a look at the `cheat sheet <https://python-future.org/compatible_idioms.html#map>`__.
|
||||
|
||||
.. _sec-plugins-python3-checklist:
|
||||
|
||||
Checklist
|
||||
---------
|
||||
|
||||
As a summary, follow this checklist to migrate your plugin to be compatible to both Python 2 and 3:
|
||||
|
||||
* Create a Python 3 virtualenv and install OctoPrint and your plugin into it for testing.
|
||||
* Tell OctoPrint your plugin is Python 2 and 3 compatible by adding a new property ``__plugin_pycompat__`` to its
|
||||
``__init__.py``:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
|
||||
* Add a compatibility header to all `py` files to ensure similar basic behaviour under Python 2 and Python 3:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
* Thorougly test your plugin under Python 3. Pay special attention to any kind of string handling issues, integer
|
||||
division, relative imports from your plugin package and how the results of ``map``, ``filter`` and ``zip`` are
|
||||
used in your code, as those have proven to be the biggest issues during past migrations.
|
||||
* Once everything works under both Python versions and you've prepared a new release of your plugin, update your
|
||||
registration file in the Official Plugin Repository to include the correct Python compatibility information as well:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
compatibility:
|
||||
python: ">=2.7,<3"
|
||||
|
||||
.. _sec-plugins-python3-furtherreading:
|
||||
|
||||
Further reading
|
||||
---------------
|
||||
|
||||
.. seealso::
|
||||
|
||||
`Porting Python 2 Code to Python 3 <https://docs.python.org/3/howto/pyporting.html>`__
|
||||
The official Python 3 porting guide which sums up all the important changes and also gives hints on how best to
|
||||
go about running a project which supports both versions for now.
|
||||
|
||||
`Cheat Sheet: Writing Python 2-3 compatible code <https://python-future.org/compatible_idioms.html>`__
|
||||
A comprehensive list of idioms that are compatible to both Python 2 and 3 and will make your code run under both,
|
||||
utilizing `future <https://python-future.org/>`__ and `six <https://six.readthedocs.io/>`__. Strongly recommended.
|
||||
|
||||
`Supporting Python 3: An in-depth guide <http://python3porting.com/bookindex.html>`__
|
||||
A free online book on the switch to Python 3. Sadly seems a bit outdated by now, so with regards to compatible
|
||||
idioms to use, best stick to the cheat sheet. Gives some interesting background however.
|
||||
|
||||
`Towards Python 3 and OctoPrint 1.4.0 <https://community.octoprint.org/t/towards-python-3-and-octoprint-1-4-0/12382?u=foosel>`__
|
||||
Forum topic discussing OctoPrint 1.4.0's roadmap including Python 3 compatibility and time frame.
|
||||
|
||||
`Migrating plugins to Python 2 & 3 compatibility - experiences? <https://community.octoprint.org/t/migrating-plugins-to-python-2-3-compatibility-experiences/16294?u=foosel>`__
|
||||
Forum topic collecting experiences by plugin developers in migrating their plugins to achieve Python 2 & 3
|
||||
compatibility.
|
||||
|
||||
|
||||
+30
-43
@@ -220,11 +220,6 @@ onUserLoggedIn(user)
|
||||
onUserLoggedOut()
|
||||
Called when a user gets logged out of the web app.
|
||||
|
||||
onUserPermissionsChanged(user)
|
||||
Called when a change in the permissions of the current user is detected. The user data of the just logged in user
|
||||
will be provided as only parameter. Note that this may also be triggered for not logged in guests if the guest
|
||||
group is modified. In this case ``user`` will be undefined.
|
||||
|
||||
onTabChange(next, current)
|
||||
Called before the main tab view switches to a new tab, so `before` the new tab becomes visible. Called with the
|
||||
next (changed to) and current (still visible) tab's hash (e.g. ``#control``). Note that ``current`` might be undefined
|
||||
@@ -318,13 +313,13 @@ Web interface startup
|
||||
|
||||
sequenceDiagram
|
||||
participant Main
|
||||
participant onServerConnect
|
||||
participant fetchSettings
|
||||
participant bindViewModels
|
||||
participant DataUpdater
|
||||
participant LoginStateViewModel
|
||||
participant SettingsViewModel
|
||||
participant UiStateViewModel
|
||||
|
||||
Note over DataUpdater: connectCallback = undefined
|
||||
Note over UiStateViewModel: loaded = false
|
||||
Note right of DataUpdater: connectCallback = undefined
|
||||
|
||||
activate Main
|
||||
|
||||
@@ -342,60 +337,52 @@ Web interface startup
|
||||
Main->>+DataUpdater: connectCallback = onServerConnect
|
||||
Note right of DataUpdater: connectCallback = onServerConnect
|
||||
DataUpdater-->>-Main: ok
|
||||
Main->>+Main: onServerConnect
|
||||
Main->>+LoginStateViewModel: passiveLogin
|
||||
LoginStateViewModel-->>Main: ok
|
||||
Main-->>Main: ok
|
||||
deactivate Main
|
||||
Main->>+onServerConnect: call
|
||||
onServerConnect->>+LoginStateViewModel: passiveLogin
|
||||
LoginStateViewModel-->>onServerConnect: ok
|
||||
onServerConnect-->>Main: ok
|
||||
deactivate onServerConnect
|
||||
deactivate Main
|
||||
|
||||
LoginStateViewModel->>+LoginStateViewModel: asynchronous passive login
|
||||
Note over Main,UiStateViewModel: Session available!
|
||||
LoginStateViewModel-X+Main: done
|
||||
Note over Main,LoginStateViewModel: Session available!
|
||||
LoginStateViewModel-X+onServerConnect: done
|
||||
deactivate LoginStateViewModel
|
||||
deactivate LoginStateViewModel
|
||||
|
||||
Main->>+DataUpdater: initialized
|
||||
onServerConnect->>+DataUpdater: initialized
|
||||
Note right of DataUpdater: initialized = true
|
||||
DataUpdater->DataUpdater: trigger stored callbacks
|
||||
DataUpdater-->>-Main: ok
|
||||
DataUpdater-->>-onServerConnect: ok
|
||||
onServerConnect-X+Main: done
|
||||
deactivate onServerConnect
|
||||
|
||||
Main->>+Main: fetchSettings
|
||||
Note right of Main: trigger onStartup
|
||||
Main->>+fetchSettings: call
|
||||
Note right of fetchSettings: trigger onStartup
|
||||
|
||||
Main->>+SettingsViewModel: requestData
|
||||
SettingsViewModel-->>Main: ok
|
||||
deactivate Main
|
||||
fetchSettings-->>Main: ok
|
||||
deactivate Main
|
||||
|
||||
SettingsViewModel->>+SettingsViewModel: asynchronous settings fetch
|
||||
Note over Main,UiStateViewModel: Settings available!
|
||||
SettingsViewModel-X+Main: done
|
||||
deactivate SettingsViewModel
|
||||
deactivate SettingsViewModel
|
||||
|
||||
Main->>+Main: bindViewModels
|
||||
fetchSettings->>+fetchSettings: asynchronous settings fetch
|
||||
fetchSettings->>+bindViewModels: call
|
||||
|
||||
loop for each view model
|
||||
Main->Main: trigger onBeforeBinding
|
||||
Main->Main: trigger onBoundTo
|
||||
Main->Main: trigger onAfterBinding
|
||||
bindViewModels->bindViewModels: trigger onBeforeBinding
|
||||
bindViewModels->bindViewModels: trigger onBoundTo
|
||||
bindViewModels->bindViewModels: trigger onAfterBinding
|
||||
end
|
||||
|
||||
Main->Main: trigger onAllBound
|
||||
bindViewModels->bindViewModels: trigger onAllBound
|
||||
opt User is logged in
|
||||
Main->>+LoginStateViewModel: onAllBound
|
||||
bindViewModels->>+LoginStateViewModel: onAllBound
|
||||
LoginStateViewModel->LoginStateViewModel: trigger onUserLoggedIn
|
||||
LoginStateViewModel-->>-Main: ok
|
||||
LoginStateViewModel-->>-bindViewModels: ok
|
||||
end
|
||||
bindViewModels->bindViewModels: trigger onStartupComplete
|
||||
bindViewModels-->>-fetchSettings: ok
|
||||
|
||||
Main->>+UiStateViewModel: loaded
|
||||
Note right of UiStateViewModel: loaded = true
|
||||
UiStateViewModel-->>-Main: ok
|
||||
|
||||
Main->Main: trigger onStartupComplete
|
||||
deactivate Main
|
||||
deactivate Main
|
||||
deactivate fetchSettings
|
||||
deactivate fetchSettings
|
||||
|
||||
|
||||
.. _sec-plugins-viewmodels-reconnect:
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'The MIT License <http://opensource.org/licenses/MIT>'
|
||||
@@ -84,7 +84,7 @@ class CodeBlockExt(CodeBlock):
|
||||
return node
|
||||
|
||||
# replace all created literal_blocks with literal_block_ext instances
|
||||
return list(map(find_and_wrap_literal_block, code_block))
|
||||
return map(find_and_wrap_literal_block, code_block)
|
||||
|
||||
def _wrap_literal_block(self, node):
|
||||
literal = literal_block_ext.from_literal_block(node)
|
||||
@@ -160,10 +160,10 @@ class PygmentsBridgeExt(object):
|
||||
# for py3, recognize interactive sessions, but do not try parsing...
|
||||
lexer = sphinx.highlighting.lexers['pycon3']
|
||||
elif lang == 'guess':
|
||||
# try:
|
||||
try:
|
||||
lexer = sphinx.highlighting.guess_lexer(source)
|
||||
# except Exception:
|
||||
# lexer = sphinx.highlighting.lexers['none']
|
||||
except Exception:
|
||||
lexer = sphinx.highlighting.lexers['none']
|
||||
else:
|
||||
if lang in sphinx.highlighting.lexers:
|
||||
lexer = sphinx.highlighting.lexers[lang]
|
||||
@@ -255,4 +255,4 @@ def setup(app):
|
||||
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 dict(version="0.1")
|
||||
@@ -1,5 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'The MIT License <http://opensource.org/licenses/MIT>'
|
||||
@@ -11,7 +11,7 @@ import requests
|
||||
from contextlib import closing
|
||||
|
||||
from sphinx.directives.code import LiteralIncludeReader, LiteralInclude, dedent_lines, \
|
||||
nodes, parselinenos, logger, container_wrapper
|
||||
nodes, set_source_info, parselinenos, logger, container_wrapper
|
||||
|
||||
if False:
|
||||
# For type annotation
|
||||
@@ -39,10 +39,11 @@ class OnlineIncludeReader(LiteralIncludeReader):
|
||||
|
||||
return lines
|
||||
except (IOError, OSError):
|
||||
raise IOError('Include file %r not found or reading it failed' % filename)
|
||||
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))
|
||||
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):
|
||||
@@ -68,7 +69,7 @@ class OnlineIncludeDirective(LiteralInclude):
|
||||
text, lines = reader.read(location=location)
|
||||
|
||||
retnode = nodes.literal_block(text, text, source=url)
|
||||
self.set_source_info(retnode)
|
||||
set_source_info(self, retnode)
|
||||
if self.options.get('diff'): # if diff is set, set udiff
|
||||
retnode['language'] = 'udiff'
|
||||
elif 'language' in self.options:
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
[pytest]
|
||||
testpaths = src tests
|
||||
addopts = --doctest-modules
|
||||
--doctest-repr=octoprint.util:pp
|
||||
--ignore=src/octoprint/vendor
|
||||
@@ -1,6 +1,4 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
#!/usr/bin/env python2
|
||||
|
||||
import os
|
||||
import sys
|
||||
@@ -10,17 +8,15 @@ 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
|
||||
if len(sys.argv) == 1:
|
||||
sys.argv.append("serve")
|
||||
octoprint.main()
|
||||
@@ -1,17 +0,0 @@
|
||||
# init/systemd files for OctoPrint.
|
||||
|
||||
Assumes OctoPrint is installed under user pi at /home/pi/OctoPrint/venv/bin/octoprint. If you have a different
|
||||
setup you'll need to adjust octoprint.default (init) or octoprint.service (systemd) accordingly.
|
||||
|
||||
## init
|
||||
|
||||
```
|
||||
octoprint.default => /etc/default/octoprint
|
||||
octoprint.init => /etc/init.d/octoprint
|
||||
```
|
||||
|
||||
## systemd
|
||||
|
||||
```
|
||||
octoprint.service => /etc/systemd/system/octoprint.service
|
||||
```
|
||||
@@ -1,12 +0,0 @@
|
||||
[Unit]
|
||||
Description=The snappy web interface for your 3D printer
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=pi
|
||||
ExecStart=/home/pi/OctoPrint/venv/bin/octoprint
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -1,9 +1,6 @@
|
||||
[metadata]
|
||||
license_file = LICENSE.txt
|
||||
|
||||
[bdist_wheel]
|
||||
universal = 1
|
||||
|
||||
[versioneer]
|
||||
VCS = git
|
||||
style = pep440-tag
|
||||
|
||||
@@ -9,97 +9,75 @@ import versioneer
|
||||
import sys
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "src"))
|
||||
import octoprint_setuptools
|
||||
import setuptools
|
||||
|
||||
#-----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
# 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",
|
||||
]
|
||||
PYTHON_REQUIRES = ">=2.7.3,<3" # TODO change to >=2.7.9,<3 in 1.3.11
|
||||
|
||||
# Requirements for our application
|
||||
INSTALL_REQUIRES = [
|
||||
# the following dependencies are non trivial to update since later versions introduce backwards incompatible
|
||||
# changes that might affect plugins, or due to other observed problems
|
||||
|
||||
"flask>=0.12,<0.13", # newer versions require newer Jinja versions
|
||||
"flask>=0.10.1,<0.11", # newer versions require newer Jinja versions
|
||||
"Jinja2>=2.8.1,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't
|
||||
# guarantee backwards compatibility for plugins and such with that
|
||||
# version, hence we need to pin to a lower version for now. See #1697
|
||||
"tornado==4.5.3", # a memory leak was observed in tornado >= 5, see #2585
|
||||
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
|
||||
"Flask-Login>=0.2.11,<0.3", # some functions changed to properties in 0.3
|
||||
|
||||
# anything below this should be checked on releases for new versions
|
||||
|
||||
"Flask-Login>=0.4.1,<0.5",
|
||||
"Flask-Principal>=0.4,<0.5",
|
||||
"Flask-Babel>=0.12,<0.13",
|
||||
"Flask-Assets>=0.12,<0.13",
|
||||
"blinker>=1.4,<1.5", # dependency of the now vendor bundled flask_principal
|
||||
"werkzeug>=0.16,<0.17",
|
||||
"cachelib>=0.1,<0.2",
|
||||
"PyYAML>=5.1,<6",
|
||||
"markdown>=3.1,<3.2",
|
||||
"werkzeug>=0.14.1,<0.15",
|
||||
"PyYAML>=3.13,<4",
|
||||
"markdown>=3.0,<3.1",
|
||||
"pyserial>=3.4,<3.5",
|
||||
"netaddr>=0.7.19,<0.8",
|
||||
"watchdog>=0.9.0,<0.10",
|
||||
"sarge==0.1.5post0",
|
||||
"netifaces>=0.10.9,<0.11",
|
||||
"pylru>=1.2,<1.3",
|
||||
"netifaces>=0.10.7,<0.11",
|
||||
"pylru>=1.1,<1.2",
|
||||
"rsa>=4.0,<5",
|
||||
"pkginfo>=1.5.0.1,<1.6",
|
||||
"requests>=2.22.0,<3",
|
||||
"semantic_version>=2.8,<2.9",
|
||||
"psutil>=5.6.5,<5.7",
|
||||
"pkginfo>=1.4.2,<1.5",
|
||||
"requests>=2.20.0,<3",
|
||||
"semantic_version>=2.6,<2.7",
|
||||
"psutil>=5.4.8,<5.5",
|
||||
"Click>=7,<8",
|
||||
"awesome-slugify>=1.6.5,<1.7",
|
||||
"feedparser>=5.2.1,<5.3",
|
||||
"future>=0.18.2,<0.19",
|
||||
"websocket-client>=0.56,<0.57",
|
||||
"wrapt>=1.11.2,<1.12",
|
||||
"emoji>=0.5.4,<0.6",
|
||||
"frozendict>=1.2,<1.3",
|
||||
"sentry-sdk==0.13.2",
|
||||
"filetype>=1.0.5,<2"
|
||||
]
|
||||
|
||||
# Python 2 specific requirements
|
||||
INSTALL_REQUIRES_PYTHON2 = [
|
||||
"futures>=3.3,<3.4",
|
||||
"chainmap>=1.0.2,<1.1",
|
||||
"future>=0.17,<0.18",
|
||||
"scandir>=1.9,<1.10",
|
||||
"websocket-client>=0.53,<0.54",
|
||||
"python-dateutil>=2.7.5,<2.8",
|
||||
"wrapt>=1.10.11,<1.11",
|
||||
"futures>=3.2,<3.3",
|
||||
"emoji>=0.5.1,<0.6",
|
||||
"monotonic>=1.5,<1.6",
|
||||
"scandir>=1.10,<1.11",
|
||||
"chainmap>=1.0.3,<1.1",
|
||||
"typing>=3.7.4.1,<4"
|
||||
"frozendict>=1.2,<1.3"
|
||||
]
|
||||
|
||||
# OSX specific requirements
|
||||
INSTALL_REQUIRES_OSX = [
|
||||
"appdirs>=1.4.3",
|
||||
]
|
||||
if sys.platform == "darwin":
|
||||
INSTALL_REQUIRES.append("appdirs>=1.4.0")
|
||||
|
||||
# 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.6",
|
||||
"pytest-doctest-custom>=1.0.0,<1.1",
|
||||
# Testing dependencies
|
||||
"mock>=2.0.0,<3",
|
||||
"nose>=1.3.7,<1.4",
|
||||
"ddt",
|
||||
|
||||
# linter
|
||||
"flake8",
|
||||
|
||||
# Documentation dependencies
|
||||
"sphinx>=1.8.5,<2",
|
||||
"sphinx>=1.8.1,<1.9",
|
||||
"sphinxcontrib-httpdomain",
|
||||
"sphinxcontrib-mermaid>=0.3.1",
|
||||
"sphinxcontrib-mermaid>=0.3",
|
||||
"sphinx_rtd_theme",
|
||||
"readthedocs-sphinx-ext==0.5.17" # Later versions require Jinja >= 2.9
|
||||
],
|
||||
|
||||
# Dependencies for developing OctoPrint plugins
|
||||
@@ -111,23 +89,6 @@ EXTRA_REQUIRES = dict(
|
||||
# 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
|
||||
|
||||
# add optional dependencies for setuptools versions < 18 that don't yet support environment markers
|
||||
if sys.version_info[0] < 3:
|
||||
INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON2
|
||||
|
||||
if sys.platform == "darwin":
|
||||
INSTALL_REQUIRES += INSTALL_REQUIRES_OSX
|
||||
else:
|
||||
# environment markers supported
|
||||
EXTRA_REQUIRES[":python_version < '3'"] = INSTALL_REQUIRES_PYTHON2
|
||||
EXTRA_REQUIRES[":sys_platform == 'darwin'"] = INSTALL_REQUIRES_OSX
|
||||
|
||||
#-----------------------------------------------------------------------------------------------------------------------
|
||||
# Anything below here is just command setup and general setup configuration
|
||||
|
||||
@@ -138,14 +99,14 @@ def read_file_contents(path):
|
||||
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):
|
||||
def data_copy_build_py_factory(files, baseclass):
|
||||
class data_copy_build_py(baseclass):
|
||||
files = dict()
|
||||
|
||||
def run(self):
|
||||
print("RUNNING md_to_html_build_py")
|
||||
import shutil
|
||||
if not self.dry_run:
|
||||
for directory, files in self.files.items():
|
||||
for directory, files in self.__class__.files.items():
|
||||
target_dir = os.path.join(self.build_lib, directory)
|
||||
self.mkpath(target_dir)
|
||||
|
||||
@@ -153,22 +114,16 @@ def md_to_html_build_py_factory(files, baseclass):
|
||||
if isinstance(entry, tuple):
|
||||
if len(entry) != 2:
|
||||
continue
|
||||
source, dest = entry[0], os.path.join(target_dir, entry[1])
|
||||
source, dest = entry
|
||||
else:
|
||||
source = entry
|
||||
dest = os.path.join(target_dir, source + ".html")
|
||||
source = dest = entry
|
||||
shutil.copy(source, os.path.join(target_dir, dest))
|
||||
|
||||
print("Rendering markdown from {} to {}".format(source, dest))
|
||||
|
||||
from markdown import markdownFromFile
|
||||
markdownFromFile(input=source,
|
||||
output=dest,
|
||||
encoding="utf-8")
|
||||
baseclass.run(self)
|
||||
|
||||
return type(md_to_html_build_py)(md_to_html_build_py.__name__,
|
||||
(md_to_html_build_py,),
|
||||
dict(files=files))
|
||||
return type(data_copy_build_py)(data_copy_build_py.__name__,
|
||||
(data_copy_build_py,),
|
||||
dict(files=files))
|
||||
|
||||
def get_cmdclass():
|
||||
cmdclass = versioneer.get_cmdclass()
|
||||
@@ -182,9 +137,10 @@ def get_cmdclass():
|
||||
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({
|
||||
cmdclass["build_py"] = data_copy_build_py_factory({
|
||||
"octoprint/templates/_data": [
|
||||
"AUTHORS.md",
|
||||
"CHANGELOG.md",
|
||||
"SUPPORTERS.md",
|
||||
"THIRDPARTYLICENSES.md",
|
||||
]
|
||||
@@ -203,7 +159,6 @@ def params():
|
||||
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
|
||||
@@ -225,10 +180,6 @@ def params():
|
||||
"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",
|
||||
@@ -241,7 +192,7 @@ def params():
|
||||
keywords = "3dprinting 3dprinter 3d-printing 3d-printer octoprint"
|
||||
|
||||
project_urls={
|
||||
"Community Forum": "https://community.octoprint.org",
|
||||
"Community Forum": "https://discourse.octoprint.org",
|
||||
"Bug Reports": "https://github.com/foosel/OctoPrint/issues",
|
||||
"Source": "https://github.com/foosel/OctoPrint",
|
||||
"Funding": "https://donate.octoprint.org"
|
||||
|
||||
+17
-33
@@ -1,8 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
#!/usr/bin/env python2
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
import io
|
||||
import sys
|
||||
import logging as log
|
||||
|
||||
@@ -104,12 +103,8 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
|
||||
if callable(after_logging):
|
||||
after_logging(**kwargs)
|
||||
|
||||
settings_start_once_in_safemode = "settings" if settings.getBoolean(["server", "startOnceInSafeMode"]) else None
|
||||
settings_incomplete_startup_safemode = "incomplete_startup" \
|
||||
if settings.getBoolean(["server", "incompleteStartup"]) \
|
||||
and not settings.getBoolean(["server", "ignoreIncompleteStartup"]) \
|
||||
else None
|
||||
safe_mode = safe_mode or settings_start_once_in_safemode or settings_incomplete_startup_safemode
|
||||
settings_safe_mode = settings.getBoolean(["server", "startOnceInSafeMode"])
|
||||
safe_mode = safe_mode or settings_safe_mode
|
||||
kwargs["safe_mode"] = safe_mode
|
||||
if callable(after_safe_mode):
|
||||
after_safe_mode(**kwargs)
|
||||
@@ -146,7 +141,7 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
|
||||
ignore_blacklist=ignore_blacklist,
|
||||
connectivity_checker=connectivity_checker)
|
||||
except Exception as ex:
|
||||
raise FatalStartupError("Could not initialize plugin manager", cause=ex)
|
||||
raise FatalStartupError("Could not initialize settings manager", cause=ex)
|
||||
|
||||
kwargs["plugin_manager"] = plugin_manager
|
||||
if callable(after_plugin_manager):
|
||||
@@ -298,7 +293,7 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
|
||||
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:
|
||||
with open(logging_file, "r") as f:
|
||||
config_from_file = yaml.safe_load(f)
|
||||
|
||||
# we merge that with the default config
|
||||
@@ -347,12 +342,9 @@ def init_pluginsystem(settings, safe_mode=False, ignore_blacklist=True, connecti
|
||||
|
||||
import os
|
||||
|
||||
# we need this so that octoprint.plugins is in sys.modules and no warnings are caused when loading bundled plugins
|
||||
import octoprint.plugins
|
||||
|
||||
logger = log.getLogger(__name__ + ".startup")
|
||||
|
||||
plugin_folders = [(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "plugins")), "octoprint.plugins", True),
|
||||
plugin_folders = [(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "plugins")), True),
|
||||
settings.getBaseFolder("plugins")]
|
||||
plugin_entry_points = ["octoprint.plugin"]
|
||||
plugin_disabled_list = settings.get(["plugins", "_disabled"])
|
||||
@@ -371,16 +363,13 @@ def init_pluginsystem(settings, safe_mode=False, ignore_blacklist=True, connecti
|
||||
return True
|
||||
plugin_validators.append(validator)
|
||||
|
||||
compatibility_ignored_list = settings.get(["plugins", "_forcedCompatible"])
|
||||
|
||||
from octoprint.plugin import plugin_manager
|
||||
pm = plugin_manager(init=True,
|
||||
plugin_folders=plugin_folders,
|
||||
plugin_entry_points=plugin_entry_points,
|
||||
plugin_disabled_list=plugin_disabled_list,
|
||||
plugin_blacklist=plugin_blacklist,
|
||||
plugin_validators=plugin_validators,
|
||||
compatibility_ignored_list=compatibility_ignored_list)
|
||||
plugin_validators=plugin_validators)
|
||||
|
||||
settings_overlays = dict()
|
||||
disabled_from_overlays = dict()
|
||||
@@ -410,9 +399,7 @@ def init_pluginsystem(settings, safe_mode=False, ignore_blacklist=True, connecti
|
||||
if not startup:
|
||||
return
|
||||
|
||||
from octoprint.util import sv
|
||||
|
||||
sorted_disabled_from_overlays = sorted([(key, value[0], value[1]) for key, value in disabled_from_overlays.items()], key=lambda x: (x[2] is None, sv(x[2]), sv(x[0])))
|
||||
sorted_disabled_from_overlays = sorted([(key, value[0], value[1]) for key, value in disabled_from_overlays.items()], key=lambda x: (x[2] is None, x[2], x[0]))
|
||||
|
||||
disabled_list = pm.plugin_disabled_list
|
||||
already_processed = []
|
||||
@@ -495,7 +482,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
|
||||
if os.stat(path).st_mtime + ttl < time.time():
|
||||
return None
|
||||
|
||||
with bom_aware_open(path, encoding="utf-8", mode='rt') as f:
|
||||
with bom_aware_open(path, encoding="utf-8", mode="r") as f:
|
||||
result = yaml.safe_load(f)
|
||||
|
||||
if isinstance(result, list):
|
||||
@@ -509,12 +496,12 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
|
||||
|
||||
if cache is not None:
|
||||
try:
|
||||
with bom_aware_open(cache, encoding="utf-8", mode='wt') as f:
|
||||
with bom_aware_open(cache, encoding="utf-8", mode="w") as f:
|
||||
yaml.safe_dump(result, f)
|
||||
except Exception as e:
|
||||
logger.info("Fetched plugin blacklist but couldn't write it to its cache file: %s", e)
|
||||
except Exception as e:
|
||||
logger.info("Unable to fetch plugin blacklist from {}, proceeding without it: {}".format(url, e))
|
||||
except:
|
||||
logger.info("Fetched plugin blacklist but couldn't write it to its cache file.")
|
||||
except:
|
||||
logger.info("Unable to fetch plugin blacklist from {}, proceeding without it.".format(url))
|
||||
return result
|
||||
|
||||
try:
|
||||
@@ -541,7 +528,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
|
||||
logger.info("Blacklist processing done")
|
||||
|
||||
return blacklist
|
||||
except Exception:
|
||||
except:
|
||||
logger.exception("Something went wrong while processing the plugin blacklist. Proceeding without it.")
|
||||
|
||||
|
||||
@@ -608,9 +595,6 @@ def main():
|
||||
# cut off stuff from the beginning
|
||||
args = args[-1 * sys_args_length:] if sys_args_length else []
|
||||
|
||||
from octoprint.util.fixes import patch_sarge_async_on_py2
|
||||
patch_sarge_async_on_py2()
|
||||
|
||||
from octoprint.cli import octo
|
||||
octo(args=args, prog_name="octoprint", auto_envvar_prefix="OCTOPRINT")
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
#!/usr/bin/env python2
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
if __name__ == "__main__":
|
||||
import octoprint
|
||||
|
||||
+11
-46
@@ -1,5 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
# This file helps to compute a version number in source trees obtained from
|
||||
# git-archive tarball (such as those provided by githubs download-from-tag
|
||||
@@ -11,14 +9,13 @@ from __future__ import absolute_import, division, print_function, unicode_litera
|
||||
# versioneer-0.15+dev (https://github.com/warner/python-versioneer)
|
||||
|
||||
"""Git implementation of _version.py."""
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
import errno
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import logging
|
||||
|
||||
|
||||
def get_keywords():
|
||||
@@ -44,7 +41,7 @@ def get_config():
|
||||
# _version.py
|
||||
cfg = VersioneerConfig()
|
||||
cfg.VCS = "git"
|
||||
cfg.style = "pep440-tag"
|
||||
cfg.style = "pep440-post"
|
||||
cfg.tag_prefix = ""
|
||||
cfg.parentdir_prefix = ""
|
||||
cfg.versionfile_source = "src/octoprint/_version.py"
|
||||
@@ -133,7 +130,7 @@ def git_get_keywords(versionfile_abs):
|
||||
# _version.py.
|
||||
keywords = {}
|
||||
try:
|
||||
f = io.open(versionfile_abs, "rt", encoding="utf-8")
|
||||
f = open(versionfile_abs, "r")
|
||||
for line in f.readlines():
|
||||
if line.strip().startswith("git_refnames ="):
|
||||
mo = re.search(r'=\s*"(.*)"', line)
|
||||
@@ -159,11 +156,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
|
||||
if verbose:
|
||||
print("keywords are unexpanded, not using")
|
||||
raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
|
||||
refs = set(r.strip() for r in refnames.strip("()").split(","))
|
||||
refs = set([r.strip() for r in refnames.strip("()").split(",")])
|
||||
# starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
|
||||
# just "foo-1.0". If we see a "tag: " prefix, prefer those.
|
||||
TAG = "tag: "
|
||||
tags = set(r[len(TAG):] for r in refs if r.startswith(TAG))
|
||||
tags = set([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,7 +169,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
|
||||
# between branches and tags. By ignoring refnames without digits, we
|
||||
# filter out many common branch names like "release" and
|
||||
# "stabilization", as well as "HEAD" and "master".
|
||||
tags = set(r for r in refs if re.search(r'\d', r))
|
||||
tags = set([r for r in refs if re.search(r'\d', r)])
|
||||
if verbose:
|
||||
print("discarding '%s', no digits" % ",".join(refs-tags))
|
||||
|
||||
@@ -257,7 +254,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
|
||||
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":
|
||||
if abbrev_ref_out is not None:
|
||||
pieces["branch"] = abbrev_ref_out.strip()
|
||||
|
||||
# now we have TAG-NUM-gHEX or HEX
|
||||
@@ -308,18 +305,17 @@ def git_parse_lookup_file(path):
|
||||
if not os.path.exists(path):
|
||||
return []
|
||||
|
||||
import re
|
||||
lookup = []
|
||||
with io.open(path, "rt", encoding="utf-8") as f:
|
||||
with open(path, "r") as f:
|
||||
for line in f:
|
||||
if '#' in line:
|
||||
line = line[:line.index("#")]
|
||||
line = line[:line.rindex("#")]
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
|
||||
try:
|
||||
split_line = list(map(lambda x: x.strip(), line.split()))
|
||||
split_line = map(lambda x: x.strip(), line.split())
|
||||
if not len(split_line):
|
||||
continue
|
||||
|
||||
@@ -340,8 +336,7 @@ def git_parse_lookup_file(path):
|
||||
continue
|
||||
|
||||
lookup.append(entry)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Versioneer problem")
|
||||
except:
|
||||
break
|
||||
return lookup
|
||||
|
||||
@@ -359,9 +354,6 @@ def git_pieces_from_lookup(lookup, root, verbose, run_command=run_command):
|
||||
raise NotThisMethod("git rev-parse --abbrev-ref HEAD failed")
|
||||
|
||||
current_branch = stdout.strip()
|
||||
if current_branch == "HEAD":
|
||||
raise NotThisMethod("not on a branch")
|
||||
|
||||
for matcher, render, tag, ref_commit in lookup:
|
||||
if matcher.match(current_branch):
|
||||
if tag is None or ref_commit is None:
|
||||
@@ -449,31 +441,6 @@ def render_pep440(pieces):
|
||||
return rendered
|
||||
|
||||
|
||||
def render_pep440_tag(pieces):
|
||||
"""TAG[[.postDISTANCE].dev0+gHEX] -- Just the tag if not dirty, else more info
|
||||
|
||||
Useful for projects that want commit based tracking on some branches
|
||||
but have the master branch only report tags, to allow for commits that
|
||||
do not modify actual code (e.g. to .github/* or docs).
|
||||
|
||||
Exceptions:
|
||||
1: no tags. 0.postDISTANCE[.dev0]+gHEX
|
||||
"""
|
||||
if pieces["closest-tag"]:
|
||||
rendered = pieces["closest-tag"]
|
||||
if pieces["dirty"]:
|
||||
rendered += ".post%d" % pieces["distance"]
|
||||
rendered += ".dev0"
|
||||
rendered += "+g%s" % pieces["short"]
|
||||
else:
|
||||
# exception #1
|
||||
rendered = "0.post%d" % pieces["distance"]
|
||||
if pieces["dirty"]:
|
||||
rendered += ".dev0"
|
||||
rendered += "+g%s" % pieces["short"]
|
||||
return rendered
|
||||
|
||||
|
||||
def render_pep440_pre(pieces):
|
||||
"""TAG[.post.devDISTANCE] -- No -dirty.
|
||||
|
||||
@@ -624,8 +591,6 @@ def render(pieces, style):
|
||||
rendered = render_pep440_old(pieces)
|
||||
elif style == "pep440-dev":
|
||||
rendered = render_pep440_dev(pieces)
|
||||
elif style == "pep440-tag":
|
||||
rendered = render_pep440_tag(pieces)
|
||||
elif style == "git-describe":
|
||||
rendered = render_git_describe(pieces)
|
||||
elif style == "git-describe-long":
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
ADMIN_GROUP = "admins"
|
||||
USER_GROUP = "users"
|
||||
GUEST_GROUP = "guests"
|
||||
READONLY_GROUP = "readonly"
|
||||
@@ -1,576 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
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'
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
from functools import partial
|
||||
|
||||
import yaml
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import atomic_write
|
||||
from octoprint.access import ADMIN_GROUP, USER_GROUP, GUEST_GROUP, READONLY_GROUP
|
||||
from octoprint.access.permissions import Permissions, OctoPrintPermission
|
||||
from octoprint.vendor.flask_principal import Need, Permission
|
||||
|
||||
|
||||
GroupNeed = partial(Need, 'group')
|
||||
GroupNeed.__doc__ = """A need with the method preset to `"group"`."""
|
||||
|
||||
|
||||
class GroupPermission(Permission):
|
||||
def __init__(self, key):
|
||||
need = GroupNeed(key)
|
||||
super(GroupPermission, self).__init__(need)
|
||||
|
||||
|
||||
class GroupManager(object):
|
||||
@classmethod
|
||||
def default_permissions_for_group(cls, group):
|
||||
result = []
|
||||
for permission in Permissions.all():
|
||||
if group in permission.default_groups:
|
||||
result.append(permission)
|
||||
return result
|
||||
|
||||
def __init__(self):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._group_change_listeners = []
|
||||
self._init_defaults()
|
||||
|
||||
@property
|
||||
def groups(self):
|
||||
return []
|
||||
|
||||
@property
|
||||
def admin_group(self):
|
||||
return self.find_group(ADMIN_GROUP)
|
||||
|
||||
@property
|
||||
def user_group(self):
|
||||
return self.find_group(USER_GROUP)
|
||||
|
||||
@property
|
||||
def guest_group(self):
|
||||
return self.find_group(GUEST_GROUP)
|
||||
|
||||
def _init_defaults(self):
|
||||
self.add_group(ADMIN_GROUP,
|
||||
"Admins",
|
||||
"Administrators",
|
||||
self.default_permissions_for_group(ADMIN_GROUP),
|
||||
[],
|
||||
changeable=False,
|
||||
removable=False,
|
||||
save=False)
|
||||
self.add_group(USER_GROUP,
|
||||
"Users",
|
||||
"All logged in users",
|
||||
self.default_permissions_for_group(USER_GROUP),
|
||||
[],
|
||||
default=True,
|
||||
removable=False,
|
||||
toggleable=False,
|
||||
save=False)
|
||||
self.add_group(GUEST_GROUP,
|
||||
"Guests",
|
||||
"Anyone who is not currently logged in",
|
||||
self.default_permissions_for_group(GUEST_GROUP),
|
||||
[],
|
||||
removable=False,
|
||||
toggleable=False,
|
||||
save=False),
|
||||
self.add_group(READONLY_GROUP,
|
||||
"Read-only Access",
|
||||
"Group to gain read-only access",
|
||||
self.default_permissions_for_group(READONLY_GROUP),
|
||||
[],
|
||||
changeable=False,
|
||||
removable=False,
|
||||
save=False)
|
||||
|
||||
def register_listener(self, listener):
|
||||
self._group_change_listeners.append(listener)
|
||||
|
||||
def unregister_listener(self, listener):
|
||||
self._group_change_listeners.remove(listener)
|
||||
|
||||
def add_group(self, key, name, description, permissions, subgroups,
|
||||
default=False, removable=True, changeable=True, toggleable=True, save=True, notify=True):
|
||||
pass
|
||||
|
||||
def update_group(self, key, description=None, permissions=None, subgroups=None, default=None, save=True, notify=True):
|
||||
pass
|
||||
|
||||
def remove_group(self, key, save=True, notify=True):
|
||||
pass
|
||||
|
||||
def find_group(self, key):
|
||||
return None
|
||||
|
||||
def _to_permissions(self, *permissions):
|
||||
return list(filter(lambda x: x is not None,
|
||||
[Permissions.find(permission) for permission in permissions]))
|
||||
|
||||
def _from_permissions(self, *permissions):
|
||||
return [permission.key for permission in permissions]
|
||||
|
||||
def _from_groups(self, *groups):
|
||||
return [group.key for group in groups]
|
||||
|
||||
def _to_groups(self, *groups):
|
||||
return list(filter(lambda x: x is not None,
|
||||
[self._to_group(g) for g in groups]))
|
||||
|
||||
def _to_group(self, group):
|
||||
# noinspection PyCompatibility
|
||||
if isinstance(group, Group):
|
||||
return group
|
||||
elif isinstance(group, basestring):
|
||||
return self.find_group(group)
|
||||
elif isinstance(group, dict):
|
||||
return self.find_group(group.get("key"))
|
||||
else:
|
||||
return None
|
||||
|
||||
def _notify_listeners(self, action, group, *args, **kwargs):
|
||||
method = "on_group_{}".format(action)
|
||||
for listener in self._group_change_listeners:
|
||||
try:
|
||||
getattr(listener, method)(group, *args, **kwargs)
|
||||
except Exception:
|
||||
self._logger.exception("Error notifying listener {!r} via {}".format(listener, method))
|
||||
|
||||
class GroupChangeListener(object):
|
||||
|
||||
def on_group_added(self, group):
|
||||
pass
|
||||
|
||||
def on_group_removed(self, group):
|
||||
pass
|
||||
|
||||
def on_group_permissions_changed(self, group, added=None, removed=None):
|
||||
pass
|
||||
|
||||
def on_group_subgroups_changed(self, group, added=None, removed=None):
|
||||
pass
|
||||
|
||||
|
||||
class FilebasedGroupManager(GroupManager):
|
||||
def __init__(self, path=None):
|
||||
if path is None:
|
||||
path = settings().get(["accessControl", "groupfile"])
|
||||
if path is None:
|
||||
path = os.path.join(settings().getBaseFolder("base"), "groups.yaml")
|
||||
|
||||
self._groupfile = path
|
||||
self._groups = dict()
|
||||
self._dirty = False
|
||||
|
||||
GroupManager.__init__(self)
|
||||
|
||||
self._load()
|
||||
|
||||
def _load(self):
|
||||
if os.path.exists(self._groupfile) and os.path.isfile(self._groupfile):
|
||||
try:
|
||||
with io.open(self._groupfile, 'rt', encoding='utf-8') as f:
|
||||
data = yaml.safe_load(f)
|
||||
|
||||
if not "groups" in data:
|
||||
groups = data
|
||||
data = dict(groups=groups)
|
||||
|
||||
groups = data.get("groups", dict())
|
||||
tracked_permissions = data.get("tracked", list())
|
||||
|
||||
for key, attributes in groups.items():
|
||||
if key in self._groups:
|
||||
# group is already there (from the defaults most likely)
|
||||
if not self._groups[key].is_changeable():
|
||||
# group may not be changed -> bail
|
||||
continue
|
||||
|
||||
removable = self._groups[key].is_removable()
|
||||
changeable = self._groups[key].is_changeable()
|
||||
toggleable = self._groups[key].is_toggleable()
|
||||
else:
|
||||
removable = True
|
||||
changeable = True
|
||||
toggleable = True
|
||||
|
||||
permissions = self._to_permissions(*attributes.get("permissions", []))
|
||||
default_permissions = self.default_permissions_for_group(key)
|
||||
for permission in default_permissions:
|
||||
if not permission.key in tracked_permissions and not permission in permissions:
|
||||
permissions.append(permission)
|
||||
|
||||
subgroups = attributes.get("subgroups", [])
|
||||
|
||||
group = Group(key, attributes.get("name", ""),
|
||||
description=attributes.get("description", ""),
|
||||
permissions=permissions,
|
||||
subgroups=subgroups,
|
||||
default=attributes.get("default", False),
|
||||
removable=removable,
|
||||
changeable=changeable,
|
||||
toggleable=toggleable)
|
||||
self._groups[key] = group
|
||||
|
||||
for group in self._groups.values():
|
||||
group._subgroups = self._to_groups(*group._subgroups)
|
||||
|
||||
except Exception:
|
||||
self._logger.exception("Error while loading groups from file {}".format(self._groupfile))
|
||||
|
||||
def _save(self, force=False):
|
||||
if self._groupfile is None or not self._dirty and not force:
|
||||
return
|
||||
|
||||
groups = dict()
|
||||
for key in self._groups.keys():
|
||||
group = self._groups[key]
|
||||
groups[key] = dict(
|
||||
name=group._name,
|
||||
description=group._description,
|
||||
permissions=self._from_permissions(*group._permissions),
|
||||
subgroups=self._from_groups(*group._subgroups),
|
||||
default=group._default
|
||||
)
|
||||
|
||||
data = dict(groups=groups,
|
||||
tracked=[x.key for x in Permissions.all()])
|
||||
|
||||
with atomic_write(self._groupfile, mode='wt', permissions=0o600, max_permissions=0o666) as f:
|
||||
import yaml
|
||||
yaml.safe_dump(data, f, default_flow_style=False, indent=4, allow_unicode=True)
|
||||
self._dirty = False
|
||||
self._load()
|
||||
|
||||
@property
|
||||
def groups(self):
|
||||
return list(self._groups.values())
|
||||
|
||||
@property
|
||||
def default_groups(self):
|
||||
return [group for group in self._groups.values() if group.is_default()]
|
||||
|
||||
def find_group(self, key):
|
||||
if key is None:
|
||||
return None
|
||||
return self._groups.get(key)
|
||||
|
||||
def add_group(self, key, name, description, permissions, subgroups, default=False, removable=True,
|
||||
changeable=True, toggleable=True, overwrite=False, notify=True, save=True):
|
||||
if key in self._groups and not overwrite:
|
||||
raise GroupAlreadyExists(key)
|
||||
|
||||
if not permissions:
|
||||
permissions = []
|
||||
|
||||
permissions = self._to_permissions(*permissions)
|
||||
assert(all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)))
|
||||
|
||||
subgroups = self._to_groups(*subgroups)
|
||||
assert(all(map(lambda g: isinstance(g, Group), subgroups)))
|
||||
|
||||
group = Group(key, name,
|
||||
description=description,
|
||||
permissions=permissions,
|
||||
subgroups=subgroups,
|
||||
default=default,
|
||||
changeable=changeable,
|
||||
removable=removable,
|
||||
toggleable=toggleable)
|
||||
self._groups[key] = group
|
||||
|
||||
if save:
|
||||
self._dirty = True
|
||||
self._save()
|
||||
|
||||
if notify:
|
||||
self._notify_listeners("added", group)
|
||||
|
||||
def remove_group(self, key, save=True, notify=True):
|
||||
"""Removes a Group by key"""
|
||||
group = self._to_group(key)
|
||||
if group is None:
|
||||
raise UnknownGroup(key)
|
||||
|
||||
if not group.is_removable():
|
||||
raise GroupUnremovable(key)
|
||||
|
||||
del self._groups[key]
|
||||
self._dirty = True
|
||||
|
||||
if save:
|
||||
self._save()
|
||||
|
||||
if notify:
|
||||
self._notify_listeners("removed", group)
|
||||
|
||||
def update_group(self, key, description=None, permissions=None, subgroups=None, default=None, save=True, notify=True):
|
||||
group = self._to_group(key)
|
||||
if group is None:
|
||||
raise UnknownGroup(key)
|
||||
|
||||
if not group.is_changeable():
|
||||
raise GroupCantBeChanged(key)
|
||||
|
||||
if description is not None and description != group.get_description():
|
||||
group.change_description(description)
|
||||
self._dirty = True
|
||||
|
||||
notifications = []
|
||||
|
||||
if permissions is not None:
|
||||
permissions = self._to_permissions(*permissions)
|
||||
assert (all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)))
|
||||
|
||||
removed_permissions = list(set(group._permissions) - set(permissions))
|
||||
added_permissions = list(set(permissions) - set(group._permissions))
|
||||
|
||||
if removed_permissions:
|
||||
self._dirty |= group.remove_permissions_from_group(removed_permissions)
|
||||
if added_permissions:
|
||||
self._dirty |= group.add_permissions_to_group(added_permissions)
|
||||
|
||||
notifications.append((("permissions_changed", group),
|
||||
dict(added=added_permissions, removed=removed_permissions)))
|
||||
|
||||
if subgroups is not None:
|
||||
subgroups = self._to_groups(*subgroups)
|
||||
assert(all(map(lambda g: isinstance(g, Group), subgroups)))
|
||||
|
||||
removed_subgroups = list(set(group._subgroups) - set(subgroups))
|
||||
added_subgroups = list(set(subgroups) - set(group._subgroups))
|
||||
|
||||
if removed_subgroups:
|
||||
self._dirty = group.remove_subgroups_from_group(removed_subgroups)
|
||||
if added_subgroups:
|
||||
self._dirty = group.add_subgroups_to_group(added_subgroups)
|
||||
|
||||
notifications.append((("subgroups_changed", group),
|
||||
dict(added=added_subgroups, removed=removed_subgroups)))
|
||||
|
||||
if default is not None:
|
||||
group.change_default(default)
|
||||
self._dirty = True
|
||||
|
||||
if self._dirty:
|
||||
if save:
|
||||
self._save()
|
||||
|
||||
if notify:
|
||||
for args, kwargs in notifications:
|
||||
self._notify_listeners(*args, **kwargs)
|
||||
|
||||
|
||||
class GroupAlreadyExists(Exception):
|
||||
def __init__(self, key):
|
||||
Exception.__init__(self, "Group %s already exists" % key)
|
||||
|
||||
|
||||
class UnknownGroup(Exception):
|
||||
def __init__(self, key):
|
||||
Exception.__init__(self, "Unknown group: %s" % key)
|
||||
|
||||
|
||||
class GroupUnremovable(Exception):
|
||||
def __init__(self, key):
|
||||
Exception.__init__(self, "Group can't be removed: %s" % key)
|
||||
|
||||
|
||||
class GroupCantBeChanged(Exception):
|
||||
def __init__(self, key):
|
||||
Exception.__init__(self, "Group can't be changed: %s" % key)
|
||||
|
||||
|
||||
class Group(object):
|
||||
def __init__(self, key, name, description="", permissions=None, subgroups=None, default=False, removable=True, changeable=True, toggleable=True):
|
||||
self._key = key
|
||||
self._name = name
|
||||
self._description = description
|
||||
self._permissions = permissions
|
||||
self._subgroups = subgroups
|
||||
self._default = default
|
||||
self._removable = removable
|
||||
self._changeable = changeable
|
||||
self._toggleable = toggleable
|
||||
|
||||
def as_dict(self):
|
||||
from octoprint.access.permissions import OctoPrintPermission
|
||||
return dict(
|
||||
key=self.key,
|
||||
name=self.get_name(),
|
||||
description=self._description,
|
||||
permissions=list(map(lambda p: p.key, self._permissions)),
|
||||
subgroups=list(map(lambda g: g.key, self._subgroups)),
|
||||
needs=OctoPrintPermission.convert_needs_to_dict(self.needs),
|
||||
default=self._default,
|
||||
removable=self._removable,
|
||||
changeable=self._changeable,
|
||||
toggleable=self._toggleable
|
||||
)
|
||||
|
||||
@property
|
||||
def key(self):
|
||||
return self._key
|
||||
|
||||
def get_name(self):
|
||||
return self._name
|
||||
|
||||
def get_description(self):
|
||||
return self._description
|
||||
|
||||
def is_default(self):
|
||||
return self._default
|
||||
|
||||
def is_changeable(self):
|
||||
return self._changeable
|
||||
|
||||
def is_removable(self):
|
||||
return self._removable
|
||||
|
||||
def is_toggleable(self):
|
||||
return self._toggleable
|
||||
|
||||
def add_permissions_to_group(self, permissions):
|
||||
"""Adds a list of permissions to a group"""
|
||||
if not self.is_changeable():
|
||||
raise GroupCantBeChanged(self.key)
|
||||
|
||||
# Make sure the permissions variable is of type list
|
||||
if not isinstance(permissions, list):
|
||||
permissions = [permissions]
|
||||
|
||||
assert(all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)))
|
||||
|
||||
dirty = False
|
||||
for permission in permissions:
|
||||
if permissions not in self.permissions:
|
||||
self._permissions.append(permission)
|
||||
dirty = True
|
||||
|
||||
return dirty
|
||||
|
||||
def remove_permissions_from_group(self, permissions):
|
||||
"""Removes a list of permissions from a group"""
|
||||
if not self.is_changeable():
|
||||
raise GroupCantBeChanged(self.key)
|
||||
|
||||
# Make sure the permissions variable is of type list
|
||||
if not isinstance(permissions, list):
|
||||
permissions = [permissions]
|
||||
|
||||
assert(all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)))
|
||||
|
||||
dirty = False
|
||||
for permission in permissions:
|
||||
if permission in self._permissions:
|
||||
self._permissions.remove(permission)
|
||||
dirty = True
|
||||
|
||||
return dirty
|
||||
|
||||
def add_subgroups_to_group(self, subgroups):
|
||||
"""Adds a list of subgroups to a group"""
|
||||
if not self.is_changeable():
|
||||
raise GroupCantBeChanged(self.key)
|
||||
|
||||
# Make sure the subgroups variable is of type list
|
||||
if not isinstance(subgroups, list):
|
||||
subgroups = [subgroups]
|
||||
|
||||
assert(all(map(lambda g: isinstance(g, Group), subgroups)))
|
||||
|
||||
dirty = False
|
||||
for group in subgroups:
|
||||
if group.is_toggleable() and group not in self._subgroups:
|
||||
self._subgroups.append(group)
|
||||
dirty = True
|
||||
|
||||
return dirty
|
||||
|
||||
def remove_subgroups_from_group(self, subgroups):
|
||||
"""Removes a list of subgroups from a group"""
|
||||
"""Adds a list of subgroups to a group"""
|
||||
if not self.is_changeable():
|
||||
raise GroupCantBeChanged(self.key)
|
||||
|
||||
# Make sure the subgroups variable is of type list
|
||||
if not isinstance(subgroups, list):
|
||||
subgroups = [subgroups]
|
||||
|
||||
assert (all(map(lambda g: isinstance(g, Group), subgroups)))
|
||||
|
||||
dirty = False
|
||||
for group in subgroups:
|
||||
if group.is_toggleable() and group in self._subgroups:
|
||||
self._subgroups.remove(group)
|
||||
dirty = True
|
||||
|
||||
return dirty
|
||||
|
||||
def change_default(self, default):
|
||||
"""Changes the default flag of a Group"""
|
||||
if not self.is_changeable():
|
||||
raise GroupCantBeChanged(self.key)
|
||||
|
||||
self._default = default
|
||||
|
||||
def change_description(self, description):
|
||||
"""Changes the description of a group"""
|
||||
self._description = description
|
||||
|
||||
@property
|
||||
def permissions(self):
|
||||
if Permissions.ADMIN in self._permissions:
|
||||
return Permissions.all()
|
||||
|
||||
return list(filter(lambda p: p is not None, self._permissions))
|
||||
|
||||
@property
|
||||
def subgroups(self):
|
||||
return filter(lambda g: g is not None, self._subgroups)
|
||||
|
||||
@property
|
||||
def needs(self):
|
||||
needs = set()
|
||||
needs.add(GroupNeed(self.key))
|
||||
for p in self.permissions:
|
||||
needs = needs.union(p.needs)
|
||||
for g in self.subgroups:
|
||||
needs = needs.union(g.needs)
|
||||
|
||||
return needs
|
||||
|
||||
def has_permission(self, permission):
|
||||
if Permissions.ADMIN.get_name() in self._permissions:
|
||||
return True
|
||||
|
||||
return permission.needs.issubset(self.needs)
|
||||
|
||||
def __repr__(self):
|
||||
return '{}("{}", "{}", description="{}", permissions={!r}, ' \
|
||||
'default={}, removable={}, changeable={})'.format(self.__class__.__name__,
|
||||
self._key,
|
||||
self._name,
|
||||
self._description,
|
||||
self._permissions,
|
||||
bool(self._default),
|
||||
bool(self._removable),
|
||||
bool(self._changeable))
|
||||
|
||||
def __hash__(self):
|
||||
return self.key.__hash__()
|
||||
|
||||
def __eq__(self, other):
|
||||
return isinstance(other, Group) and other.key == self.key
|
||||
@@ -1,389 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
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'
|
||||
__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
|
||||
|
||||
# noinspection PyCompatibility
|
||||
from past.builtins import basestring
|
||||
|
||||
from octoprint.access import ADMIN_GROUP, USER_GROUP, READONLY_GROUP
|
||||
|
||||
|
||||
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_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", [])
|
||||
|
||||
self._key = None
|
||||
|
||||
Permission.__init__(self, *self.convert_to_needs(needs))
|
||||
|
||||
def as_dict(self):
|
||||
return dict(
|
||||
key=self.key,
|
||||
name=self.get_name(),
|
||||
dangerous=self._dangerous,
|
||||
default_groups=self._default_groups,
|
||||
description=self.get_description(),
|
||||
needs=self.convert_needs_to_dict(self.needs)
|
||||
)
|
||||
|
||||
@property
|
||||
def key(self):
|
||||
return self._key
|
||||
|
||||
@key.setter
|
||||
def key(self, value):
|
||||
self._key = value
|
||||
|
||||
@property
|
||||
def default_groups(self):
|
||||
return self._default_groups
|
||||
|
||||
def get_name(self):
|
||||
return self._name
|
||||
|
||||
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.
|
||||
|
||||
: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
|
||||
|
||||
return True
|
||||
|
||||
|
||||
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
|
||||
|
||||
def difference(self, other):
|
||||
"""Create a new OctoPrintPermission consisting of requirements in this
|
||||
permission and not in the other.
|
||||
"""
|
||||
|
||||
p = self.__class__(self._name, self._description, *self.needs.difference(other.needs))
|
||||
p.excludes.update(self.excludes.difference(other.excludes))
|
||||
return p
|
||||
|
||||
def __repr__(self):
|
||||
return '{}({!r}, {!r}, {})'.format(self.__class__.__name__,
|
||||
self.get_name(),
|
||||
self.get_description(),
|
||||
', '.join(map(repr, self.needs)))
|
||||
|
||||
def __hash__(self):
|
||||
return self.get_name().__hash__()
|
||||
|
||||
def __eq__(self, other):
|
||||
return isinstance(other, OctoPrintPermission) and other.get_name() == self.get_name()
|
||||
|
||||
|
||||
class PluginOctoPrintPermission(OctoPrintPermission):
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.plugin = kwargs.pop("plugin", None)
|
||||
OctoPrintPermission.__init__(self, *args, **kwargs)
|
||||
|
||||
def as_dict(self):
|
||||
result = OctoPrintPermission.as_dict(self)
|
||||
result["plugin"] = self.plugin
|
||||
return result
|
||||
|
||||
|
||||
class PluginIdentityContext(object):
|
||||
"""Identity context for not initialized Permissions
|
||||
|
||||
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
|
||||
"""
|
||||
|
||||
@property
|
||||
def identity(self):
|
||||
"""The identity of this principal
|
||||
"""
|
||||
return g.identity
|
||||
|
||||
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)
|
||||
|
||||
return permission.can()
|
||||
|
||||
def __call__(self, f):
|
||||
@wraps(f)
|
||||
def _decorated(*args, **kw):
|
||||
with self:
|
||||
rv = f(*args, **kw)
|
||||
return rv
|
||||
|
||||
return _decorated
|
||||
|
||||
def __enter__(self):
|
||||
permission = getattr(Permissions, self.key)
|
||||
if permission is None or isinstance(permission, PluginPermissionDecorator):
|
||||
raise UnknownPermission(self.key)
|
||||
|
||||
# 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
|
||||
|
||||
Needed to support @Permissions.PLUGIN_X_Y.require()
|
||||
"""
|
||||
def __init__(self, key):
|
||||
self.key = key
|
||||
|
||||
def require(self, http_exception=None):
|
||||
return PluginIdentityContext(self.key, http_exception)
|
||||
|
||||
|
||||
class PermissionsMetaClass(type):
|
||||
permissions = OrderedDict()
|
||||
|
||||
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)
|
||||
|
||||
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 __getattr__(cls, key):
|
||||
permission = cls.permissions.get(key)
|
||||
|
||||
if key.startswith("PLUGIN_") and permission is None:
|
||||
return PluginPermissionDecorator(key)
|
||||
|
||||
return permission
|
||||
|
||||
def all(cls):
|
||||
return list(cls.permissions.values())
|
||||
|
||||
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
|
||||
|
||||
if key is None:
|
||||
return None
|
||||
|
||||
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()
|
||||
|
||||
for permission in permissions:
|
||||
if match(permission):
|
||||
return permission
|
||||
|
||||
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])
|
||||
|
||||
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])
|
||||
|
||||
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)
|
||||
|
||||
FILES_LIST = OctoPrintPermission("File List",
|
||||
gettext("Allows to retrieve a list of all uploaded files, including"
|
||||
"their metadata (e.g. date, file size, analysis results, ...)"),
|
||||
RoleNeed("files_list"),
|
||||
default_groups=[USER_GROUP, READONLY_GROUP])
|
||||
FILES_UPLOAD = OctoPrintPermission("File Upload",
|
||||
gettext("Allows users to upload new files"),
|
||||
RoleNeed("files_upload"),
|
||||
default_groups=[USER_GROUP])
|
||||
FILES_DOWNLOAD = OctoPrintPermission("File Download",
|
||||
gettext("Allows users to download files. The GCODE viewer is "
|
||||
"affected by this as well."),
|
||||
RoleNeed("files_download"),
|
||||
default_groups=[USER_GROUP, READONLY_GROUP])
|
||||
FILES_DELETE = OctoPrintPermission("File Delete",
|
||||
gettext("Allows users to delete files"),
|
||||
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])
|
||||
|
||||
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])
|
||||
|
||||
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])
|
||||
|
||||
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)
|
||||
|
||||
|
||||
class UnknownPermission(Exception):
|
||||
def __init__(self, permissionname):
|
||||
Exception.__init__(self, "Unknown permission: %s" % permissionname)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,12 +1,11 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__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
|
||||
|
||||
@@ -138,10 +137,9 @@ 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
|
||||
|
||||
@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])
|
||||
sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands, analysis_commands])
|
||||
@standard_options()
|
||||
@legacy_options
|
||||
@click.version_option(version=octoprint.__version__, allow_from_autoenv=False)
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__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
|
||||
|
||||
@@ -35,7 +34,6 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle
|
||||
|
||||
import time
|
||||
import yaml
|
||||
from octoprint.util import monotonic_time
|
||||
from octoprint.util.gcodeInterpreter import gcode
|
||||
|
||||
throttle_callback = None
|
||||
@@ -54,7 +52,7 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle
|
||||
if len(offsets) < maxt:
|
||||
offsets += [(0, 0)] * (maxt - len(offsets))
|
||||
|
||||
start_time = monotonic_time()
|
||||
start_time = time.time()
|
||||
|
||||
progress_callback = None
|
||||
if progress:
|
||||
@@ -70,9 +68,9 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle
|
||||
max_extruders=maxt,
|
||||
g90_extruder=g90_extruder)
|
||||
|
||||
click.echo("DONE:{}s".format(monotonic_time() - start_time))
|
||||
click.echo("DONE:{}s".format(time.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(yaml.safe_dump(interpreter.get_result(), default_flow_style=False, indent=" ", allow_unicode=True))
|
||||
|
||||
if __name__ == "__main__":
|
||||
gcode_command()
|
||||
@@ -1,13 +1,10 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__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
|
||||
@@ -15,7 +12,6 @@ import octoprint_client
|
||||
from octoprint.cli import get_ctx_obj_option, bulk_options
|
||||
from octoprint import init_settings, FatalStartupError
|
||||
|
||||
from past.builtins import unicode
|
||||
|
||||
class JsonStringParamType(click.ParamType):
|
||||
name = "json"
|
||||
@@ -23,7 +19,7 @@ class JsonStringParamType(click.ParamType):
|
||||
def convert(self, value, param, ctx):
|
||||
try:
|
||||
return json.loads(value)
|
||||
except Exception:
|
||||
except:
|
||||
self.fail("%s is not a valid json string" % value, param, ctx)
|
||||
|
||||
|
||||
@@ -147,16 +143,16 @@ 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:
|
||||
with open(file_path, "rb") as fp:
|
||||
data = json.load(fp)
|
||||
else:
|
||||
import yaml
|
||||
with io.open(file_path, 'rt') as fp:
|
||||
with open(file_path, "rb") as fp:
|
||||
data = yaml.safe_load(fp)
|
||||
|
||||
r = ctx.obj.client.post_json(path, data, timeout=timeout)
|
||||
else:
|
||||
with io.open(file_path, 'rb') as fp:
|
||||
with open(file_path, "rb") as fp:
|
||||
data = fp.read()
|
||||
|
||||
r = ctx.obj.client.post(path, data, timeout=timeout)
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__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
|
||||
@@ -18,7 +17,7 @@ import pprint
|
||||
|
||||
def _to_settings_path(path):
|
||||
if not isinstance(path, (list, tuple)):
|
||||
path = list(filter(lambda x: x, map(lambda x: x.strip(), path.split("."))))
|
||||
path = filter(lambda x: x, map(lambda x: x.strip(), path.split(".")))
|
||||
return path
|
||||
|
||||
def _set_helper(settings, path, value, data_type=None):
|
||||
@@ -208,7 +207,7 @@ def get_command(ctx, path, as_json=False, as_yaml=False, as_raw=False):
|
||||
if as_json:
|
||||
output = json.dumps(value)
|
||||
elif as_yaml:
|
||||
output = yaml.safe_dump(value, default_flow_style=False, indent=4, allow_unicode=True)
|
||||
output = yaml.safe_dump(value, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
elif as_raw:
|
||||
output = value
|
||||
else:
|
||||
@@ -233,7 +232,7 @@ def effective_command(ctx, as_json=False, as_yaml=False, as_raw=False):
|
||||
if as_json:
|
||||
output = json.dumps(value)
|
||||
elif as_yaml:
|
||||
output = yaml.safe_dump(value, default_flow_style=False, indent=4, allow_unicode=True)
|
||||
output = yaml.safe_dump(value, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
elif as_raw:
|
||||
output = value
|
||||
else:
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
@@ -7,7 +7,6 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
|
||||
|
||||
|
||||
import click
|
||||
click.disable_unicode_literals_warning = True
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
@@ -117,8 +116,7 @@ class OctoPrintDevelCommands(click.MultiCommand):
|
||||
if key in options:
|
||||
val = options[key]
|
||||
else:
|
||||
if not isinstance(raw, basestring):
|
||||
raw = str(raw)
|
||||
raw = raw if isinstance(raw, basestring) else str(raw)
|
||||
val = env.from_string(raw).render(cookiecutter=cookiecutter_dict)
|
||||
|
||||
if not no_input:
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__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.cli import pass_octoprint_ctx, OctoPrintContext, get_ctx_obj_option
|
||||
@@ -89,12 +88,11 @@ class OctoPrintPluginCommands(click.MultiCommand):
|
||||
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))
|
||||
self._logger.warn("Plugin {} provided invalid CLI command, ignoring it: {!r}".format(name, command))
|
||||
continue
|
||||
result[name + self.sep + command.name] = command
|
||||
except Exception:
|
||||
self._logger.exception("Error while retrieving cli commands for plugin {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
except:
|
||||
self._logger.exception("Error while retrieving cli commands for plugin {}".format(name))
|
||||
|
||||
return result
|
||||
|
||||
|
||||
+17
-43
@@ -1,18 +1,17 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__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
|
||||
|
||||
def run_server(basedir, configfile, host, port, v6_only, debug, allow_root, logging_config, verbosity, safe_mode,
|
||||
def run_server(basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode,
|
||||
ignore_blacklist, octoprint_daemon=None):
|
||||
"""Initializes the environment and starts up the server."""
|
||||
|
||||
@@ -27,15 +26,6 @@ def run_server(basedir, configfile, host, port, v6_only, debug, allow_root, logg
|
||||
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))
|
||||
|
||||
if recorder and len(recorder):
|
||||
logger.info(get_divider_line("-", "Logged during platform initialization:"))
|
||||
@@ -111,7 +101,6 @@ def run_server(basedir, configfile, host, port, v6_only, debug, allow_root, logg
|
||||
environment_detector=environment_detector,
|
||||
host=host,
|
||||
port=port,
|
||||
v6_only=v6_only,
|
||||
debug=debug,
|
||||
safe_mode=safe_mode,
|
||||
allow_root=allow_root,
|
||||
@@ -122,13 +111,9 @@ def run_server(basedir, configfile, host, port, v6_only, debug, allow_root, logg
|
||||
|
||||
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."),
|
||||
help="Specify the host 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,
|
||||
@@ -138,7 +123,7 @@ server_options = bulk_options([
|
||||
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``
|
||||
"""Decorator to add the options shared among the server commands: ``--host``, ``--port``,
|
||||
``--logging``, ``--iknowwhatimdoing`` and ``--debug``."""
|
||||
|
||||
daemon_options = bulk_options([
|
||||
@@ -168,11 +153,11 @@ def enable_safemode(ctx, **kwargs):
|
||||
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.")
|
||||
settings.setBoolean(["server", "startOnceInSafeMode"], True)
|
||||
settings.save()
|
||||
|
||||
click.echo("Safe mode flag set, OctoPrint will start in safe mode on next restart.")
|
||||
|
||||
|
||||
@server_commands.command(name="serve")
|
||||
@@ -187,8 +172,6 @@ def serve_command(ctx, **kwargs):
|
||||
|
||||
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")
|
||||
@@ -196,13 +179,10 @@ def serve_command(ctx, **kwargs):
|
||||
basedir = get_value("basedir")
|
||||
configfile = get_value("configfile")
|
||||
verbosity = get_value("verbosity")
|
||||
safe_mode = "flag" if get_value("safe_mode") else None
|
||||
safe_mode = get_value("safe_mode")
|
||||
ignore_blacklist = get_value("ignore_blacklist")
|
||||
|
||||
if v4 and not host:
|
||||
host = "0.0.0.0"
|
||||
|
||||
run_server(basedir, configfile, host, port, v6, debug,
|
||||
run_server(basedir, configfile, host, port, debug,
|
||||
allow_root, logging, verbosity, safe_mode,
|
||||
ignore_blacklist)
|
||||
|
||||
@@ -229,8 +209,6 @@ if sys.platform != "win32" and sys.platform != "darwin":
|
||||
|
||||
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")
|
||||
@@ -239,12 +217,9 @@ if sys.platform != "win32" and sys.platform != "darwin":
|
||||
basedir = get_value("basedir")
|
||||
configfile = get_value("configfile")
|
||||
verbosity = get_value("verbosity")
|
||||
safe_mode = "flag" if get_value("safe_mode") else None
|
||||
safe_mode = get_value("safe_mode")
|
||||
ignore_blacklist = get_value("ignore_blacklist")
|
||||
|
||||
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)
|
||||
@@ -252,15 +227,14 @@ if sys.platform != "win32" and sys.platform != "darwin":
|
||||
|
||||
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):
|
||||
def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity,
|
||||
safe_mode, ignore_blacklist):
|
||||
Daemon.__init__(self, pidfile)
|
||||
|
||||
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
|
||||
@@ -269,12 +243,12 @@ if sys.platform != "win32" and sys.platform != "darwin":
|
||||
self._ignore_blacklist = ignore_blacklist
|
||||
|
||||
def run(self):
|
||||
run_server(self._basedir, self._configfile, self._host, self._port, self._v6_only, self._debug,
|
||||
run_server(self._basedir, self._configfile, self._host, self._port, 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)
|
||||
octoprint_daemon = OctoPrintDaemon(pid, basedir, configfile, host, port, debug, allow_root, logging, verbosity,
|
||||
safe_mode, ignore_blacklist)
|
||||
|
||||
if command == "start":
|
||||
octoprint_daemon.start()
|
||||
|
||||
@@ -1,184 +0,0 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import click
|
||||
import logging
|
||||
|
||||
from octoprint import init_settings
|
||||
from octoprint.cli import get_ctx_obj_option
|
||||
from octoprint.access.groups import FilebasedGroupManager
|
||||
from octoprint.access.users import FilebasedUserManager, UnknownUser, UserAlreadyExists
|
||||
from octoprint.util import get_class, sv
|
||||
|
||||
click.disable_unicode_literals_warning = True
|
||||
|
||||
#~~ "octoprint user" commands
|
||||
|
||||
|
||||
@click.group()
|
||||
def user_commands():
|
||||
pass
|
||||
|
||||
|
||||
@user_commands.group(name="user")
|
||||
@click.pass_context
|
||||
def user(ctx):
|
||||
"""
|
||||
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))
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
|
||||
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)
|
||||
|
||||
|
||||
@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.pass_context
|
||||
def add_user_command(ctx, username, password, groups, permissions, is_admin):
|
||||
"""Add a new user."""
|
||||
if not groups:
|
||||
groups = []
|
||||
|
||||
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)
|
||||
|
||||
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)
|
||||
|
||||
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")
|
||||
@click.argument("username", type=click.STRING)
|
||||
@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)
|
||||
|
||||
|
||||
@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))
|
||||
|
||||
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))
|
||||
|
||||
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)))
|
||||
|
||||
|
||||
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", [])))
|
||||
+9
-10
@@ -1,13 +1,12 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
# coding=utf-8
|
||||
"""
|
||||
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
|
||||
from __future__ import absolute_import, division, print_function
|
||||
import sys, os, time, signal
|
||||
|
||||
class Daemon:
|
||||
"""
|
||||
@@ -61,9 +60,9 @@ class Daemon:
|
||||
# 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')
|
||||
si = open(os.devnull, 'r')
|
||||
so = open(os.devnull, 'a+')
|
||||
se = open(os.devnull, 'a+')
|
||||
|
||||
os.dup2(si.fileno(), sys.stdin.fileno())
|
||||
os.dup2(so.fileno(), sys.stdout.fileno())
|
||||
@@ -134,7 +133,7 @@ class Daemon:
|
||||
except OSError:
|
||||
try:
|
||||
self.remove_pidfile()
|
||||
except Exception:
|
||||
except:
|
||||
self.error("Daemon found not running, but could not remove stale pidfile")
|
||||
return False
|
||||
else:
|
||||
@@ -143,7 +142,7 @@ class Daemon:
|
||||
def get_pid(self):
|
||||
"""Get the pid from the pidfile."""
|
||||
try:
|
||||
with io.open(self.pidfile,'rt', encoding='utf-8') as pf:
|
||||
with open(self.pidfile,'r') as pf:
|
||||
pid = int(pf.read().strip())
|
||||
except (IOError, ValueError):
|
||||
pid = None
|
||||
@@ -151,7 +150,7 @@ class Daemon:
|
||||
|
||||
def set_pid(self, pid):
|
||||
"""Write the pid to the pidfile."""
|
||||
with io.open(self.pidfile,'wt+', encoding='utf-8') as f:
|
||||
with open(self.pidfile,'w+') as f:
|
||||
f.write(str(pid) + '\n')
|
||||
|
||||
def remove_pidfile(self):
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__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"
|
||||
@@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms
|
||||
import copy
|
||||
import logging
|
||||
import os
|
||||
import platform
|
||||
import sys
|
||||
import threading
|
||||
import yaml
|
||||
@@ -15,7 +16,6 @@ import psutil
|
||||
|
||||
from octoprint.plugin import EnvironmentDetectionPlugin
|
||||
from octoprint.util.platform import get_os
|
||||
from octoprint.util.version import get_python_version_string
|
||||
|
||||
class EnvironmentDetector(object):
|
||||
|
||||
@@ -25,14 +25,9 @@ class EnvironmentDetector(object):
|
||||
self._cache = None
|
||||
self._cache_lock = threading.RLock()
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._environment_plugins = self._plugin_manager.get_implementations(EnvironmentDetectionPlugin)
|
||||
|
||||
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 = []
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
@property
|
||||
def environment(self):
|
||||
@@ -59,7 +54,7 @@ class EnvironmentDetector(object):
|
||||
self.notify_plugins()
|
||||
|
||||
return environment
|
||||
except Exception:
|
||||
except:
|
||||
self._logger.exception("Unexpected error while detecting environment")
|
||||
with self._cache_lock:
|
||||
self._cache = dict()
|
||||
@@ -75,22 +70,22 @@ class EnvironmentDetector(object):
|
||||
|
||||
# determine python version
|
||||
try:
|
||||
result["version"] = get_python_version_string()
|
||||
except Exception:
|
||||
result["version"] = platform.python_version()
|
||||
except:
|
||||
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:
|
||||
except:
|
||||
self._logger.exception("Error detecting whether we are running in a virtual environment")
|
||||
|
||||
# try to find pip version
|
||||
try:
|
||||
import pkg_resources
|
||||
result["pip"] = pkg_resources.get_distribution("pip").version
|
||||
except Exception:
|
||||
except:
|
||||
self._logger.exception("Error detecting pip version")
|
||||
|
||||
return result
|
||||
@@ -110,7 +105,7 @@ class EnvironmentDetector(object):
|
||||
result["freq"] = cpu_freq.max
|
||||
if ram and hasattr(ram, "total"):
|
||||
result["ram"] = ram.total
|
||||
except Exception:
|
||||
except:
|
||||
self._logger.exception("Error while detecting hardware environment")
|
||||
|
||||
return result
|
||||
@@ -123,10 +118,9 @@ class EnvironmentDetector(object):
|
||||
additional = implementation.get_additional_environment()
|
||||
if additional is not None and isinstance(additional, dict) and len(additional):
|
||||
result[implementation._identifier] = additional
|
||||
except Exception:
|
||||
except:
|
||||
self._logger.exception("Error while fetching additional "
|
||||
"environment data from plugin {}".format(implementation._identifier),
|
||||
extra=dict(plugin=implementation._identifier))
|
||||
"environment data from plugin {}".format(implementation._identifier))
|
||||
|
||||
return result
|
||||
|
||||
@@ -140,7 +134,7 @@ class EnvironmentDetector(object):
|
||||
|
||||
try:
|
||||
_log(self._format())
|
||||
except Exception:
|
||||
except:
|
||||
self._logger.exception("Error logging detected environment")
|
||||
|
||||
def _format(self):
|
||||
@@ -151,10 +145,10 @@ class EnvironmentDetector(object):
|
||||
|
||||
dumped_environment = yaml.safe_dump(environment,
|
||||
default_flow_style=False,
|
||||
indent=4,
|
||||
indent=" ",
|
||||
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"],
|
||||
return u"Detected environment is Python {} under {} ({}). Details:\n{}".format(environment["python"]["version"],
|
||||
environment["os"]["id"].title(),
|
||||
environment["os"]["platform"],
|
||||
environment_lines)
|
||||
@@ -168,6 +162,6 @@ class EnvironmentDetector(object):
|
||||
for implementation in self._environment_plugins:
|
||||
try:
|
||||
implementation.on_environment_detected(environment)
|
||||
except Exception:
|
||||
except:
|
||||
self._logger.exception("Error while sending environment "
|
||||
"detection result to plugin {}".format(implementation._identifier))
|
||||
+44
-69
@@ -1,5 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>, Lars Norpchen"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
@@ -14,7 +14,6 @@ except ImportError:
|
||||
import Queue as queue
|
||||
import threading
|
||||
import collections
|
||||
import re
|
||||
|
||||
from octoprint.settings import settings
|
||||
import octoprint.plugin
|
||||
@@ -24,7 +23,7 @@ _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("__")]
|
||||
|
||||
|
||||
class Events(object):
|
||||
@@ -46,12 +45,6 @@ class Events(object):
|
||||
# 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"
|
||||
|
||||
# File management
|
||||
UPLOAD = "Upload"
|
||||
@@ -126,23 +119,6 @@ class Events(object):
|
||||
# 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
|
||||
|
||||
# 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()
|
||||
|
||||
def eventManager():
|
||||
global _instance
|
||||
@@ -159,7 +135,6 @@ class EventManager(object):
|
||||
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
|
||||
@@ -181,20 +156,21 @@ class EventManager(object):
|
||||
self._shutdown_signaled = True
|
||||
|
||||
eventListeners = self._registeredListeners[event]
|
||||
self._logger_fire.debug("Firing event: {} (Payload: {!r})".format(event, payload))
|
||||
self._logger.debug("Firing event: %s (Payload: %r)" % (event, payload))
|
||||
|
||||
for listener in eventListeners:
|
||||
self._logger.debug("Sending action to {!r}".format(listener))
|
||||
self._logger.debug("Sending action to %r" % listener)
|
||||
try:
|
||||
listener(event, payload)
|
||||
except Exception:
|
||||
self._logger.exception("Got an exception while sending event {} (Payload: {!r}) to {}".format(event, payload, listener))
|
||||
except:
|
||||
self._logger.exception("Got an exception while sending event %s (Payload: %r) to %s" % (event, payload, listener))
|
||||
|
||||
octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin,
|
||||
"on_event",
|
||||
args=(event, payload))
|
||||
args=(event, payload),
|
||||
initialized=True)
|
||||
self._logger.info("Event loop shut down")
|
||||
except Exception:
|
||||
except:
|
||||
self._logger.exception("Ooops, the event bus worker loop crashed")
|
||||
|
||||
def fire(self, event, payload=None):
|
||||
@@ -233,6 +209,14 @@ class EventManager(object):
|
||||
|
||||
q.put((event, payload))
|
||||
|
||||
if event == Events.UPDATED_FILES and "type" in payload and payload["type"] == "printables":
|
||||
# when sending UpdatedFiles with type "printables", also send another event with deprecated type "gcode"
|
||||
# TODO v1.3.0 Remove again
|
||||
import copy
|
||||
legacy_payload = copy.deepcopy(payload)
|
||||
legacy_payload["type"] = "gcode"
|
||||
q.put((event, legacy_payload))
|
||||
|
||||
def subscribe(self, event, callback):
|
||||
"""
|
||||
Subscribe a listener to an event -- pass in the event name (as a string) and the callback object
|
||||
@@ -243,18 +227,19 @@ class EventManager(object):
|
||||
return
|
||||
|
||||
self._registeredListeners[event].append(callback)
|
||||
self._logger.debug("Subscribed listener {!r} for event {}".format(callback, event))
|
||||
self._logger.debug("Subscribed listener %r for event %s" % (callback, event))
|
||||
|
||||
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
|
||||
if not callback in self._registeredListeners[event]:
|
||||
# callback not subscribed to event, just return
|
||||
return
|
||||
|
||||
self._registeredListeners[event].remove(callback)
|
||||
self._logger.debug("Unsubscribed listener %r for event %s" % (callback, event))
|
||||
|
||||
def join(self, timeout=None):
|
||||
self._worker.join(timeout)
|
||||
@@ -297,7 +282,7 @@ class DebugEventListener(GenericEventListener):
|
||||
def __init__(self):
|
||||
GenericEventListener.__init__(self)
|
||||
|
||||
events = list(filter(lambda x: not x.startswith("__"), dir(Events)))
|
||||
events = filter(lambda x: not x.startswith("__"), dir(Events))
|
||||
self.subscribe(events)
|
||||
|
||||
def eventCallback(self, event, payload):
|
||||
@@ -331,33 +316,26 @@ class CommandTrigger(GenericEventListener):
|
||||
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"]:
|
||||
if not "event" in subscription.keys() or not "command" in subscription.keys() \
|
||||
or not "type" in subscription.keys() 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 "enabled" in subscription and not subscription["enabled"]:
|
||||
if "enabled" in subscription.keys() and not subscription["enabled"]:
|
||||
self._logger.info("Disabled command trigger: {!r}".format(subscription))
|
||||
continue
|
||||
|
||||
events = subscription["event"]
|
||||
event = 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]
|
||||
if not event in self._subscriptions.keys():
|
||||
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 not event in eventsToSubscribe:
|
||||
eventsToSubscribe.append(event)
|
||||
|
||||
self.subscribe(eventsToSubscribe)
|
||||
|
||||
@@ -377,12 +355,12 @@ class CommandTrigger(GenericEventListener):
|
||||
if isinstance(command, (tuple, list, set)):
|
||||
processedCommand = []
|
||||
for c in command:
|
||||
processedCommand.append(self._processCommand(c, event, payload))
|
||||
processedCommand.append(self._processCommand(c, payload))
|
||||
else:
|
||||
processedCommand = self._processCommand(command, event, payload)
|
||||
processedCommand = self._processCommand(command, 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)
|
||||
except KeyError as e:
|
||||
self._logger.warn("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":
|
||||
@@ -410,10 +388,10 @@ class CommandTrigger(GenericEventListener):
|
||||
commandExecutioner(command)
|
||||
except subprocess.CalledProcessError as e:
|
||||
if debug:
|
||||
self._logger.warning("Command failed with return code {}: {}".format(e.returncode, str(e)))
|
||||
self._logger.warn("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.warn("Command failed with return code {}, enable debug logging on target 'octoprint.events' for details".format(e.returncode))
|
||||
except:
|
||||
self._logger.exception("Command failed")
|
||||
|
||||
t = threading.Thread(target=process)
|
||||
@@ -428,14 +406,13 @@ class CommandTrigger(GenericEventListener):
|
||||
self._logger.info("Executing GCode commands: %r" % command)
|
||||
self._printer.commands(commands)
|
||||
|
||||
def _processCommand(self, command, event, payload):
|
||||
def _processCommand(self, command, payload):
|
||||
"""
|
||||
Performs string substitutions in the command string based on a few current parameters.
|
||||
|
||||
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
|
||||
@@ -452,13 +429,11 @@ class CommandTrigger(GenericEventListener):
|
||||
import json
|
||||
try:
|
||||
json_string = json.dumps(payload)
|
||||
except Exception:
|
||||
self._logger.exception("JSON: Cannot dump %r", payload)
|
||||
except:
|
||||
json_string = ""
|
||||
|
||||
params = {
|
||||
"__currentZ": "-1",
|
||||
"__eventname": event,
|
||||
"__filename": "NO FILE",
|
||||
"__filepath": "NO PATH",
|
||||
"__progress": "0",
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import logging
|
||||
import io
|
||||
import os
|
||||
|
||||
import octoprint.plugin
|
||||
@@ -18,7 +17,6 @@ from .destinations import FileDestinations
|
||||
from .analysis import QueueEntry, AnalysisQueue
|
||||
from .storage import LocalFileStorage
|
||||
from .util import AbstractFileWrapper, StreamWrapper, DiskFileWrapper
|
||||
from octoprint.util import get_fully_qualified_classname as fqcn
|
||||
|
||||
from collections import namedtuple
|
||||
|
||||
@@ -32,6 +30,10 @@ extensions = dict(
|
||||
|
||||
def full_extension_tree():
|
||||
result = dict(
|
||||
# extensions for 3d model files
|
||||
model=dict(
|
||||
stl=ContentTypeMapping(["stl"], "application/sla")
|
||||
),
|
||||
# extensions for printable machine code
|
||||
machinecode=dict(
|
||||
gcode=ContentTypeMapping(["gcode", "gco", "g"], "text/plain")
|
||||
@@ -72,18 +74,6 @@ def full_extension_tree():
|
||||
else:
|
||||
return merged
|
||||
|
||||
slicer_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SlicerPlugin)
|
||||
for plugin in slicer_plugins:
|
||||
try:
|
||||
plugin_result = plugin.get_slicer_extension_tree()
|
||||
if plugin_result is None or not isinstance(plugin_result, dict):
|
||||
continue
|
||||
result = octoprint.util.dict_merge(result, plugin_result, leaf_merger=leaf_merger)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Exception while retrieving additional extension "
|
||||
"tree entries from SlicerPlugin {name}".format(name=plugin._identifier),
|
||||
extra=dict(plugin=plugin._identifier))
|
||||
|
||||
extension_tree_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.filemanager.extension_tree")
|
||||
for name, hook in extension_tree_hooks.items():
|
||||
try:
|
||||
@@ -91,15 +81,13 @@ def full_extension_tree():
|
||||
if hook_result is None or not isinstance(hook_result, dict):
|
||||
continue
|
||||
result = octoprint.util.dict_merge(result, hook_result, leaf_merger=leaf_merger)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Exception while retrieving additional extension "
|
||||
"tree entries from hook {name}".format(name=name),
|
||||
extra=dict(plugin=name))
|
||||
except:
|
||||
logging.getLogger(__name__).exception("Exception while retrieving additional extension tree entries from hook {name}".format(name=name))
|
||||
|
||||
return result
|
||||
|
||||
def get_extensions(type, subtree=None):
|
||||
if subtree is None:
|
||||
if not subtree:
|
||||
subtree = full_extension_tree()
|
||||
|
||||
for key, value in subtree.items():
|
||||
@@ -113,7 +101,7 @@ def get_extensions(type, subtree=None):
|
||||
return None
|
||||
|
||||
def get_all_extensions(subtree=None):
|
||||
if subtree is None:
|
||||
if not subtree:
|
||||
subtree = full_extension_tree()
|
||||
|
||||
result = []
|
||||
@@ -132,7 +120,7 @@ def get_all_extensions(subtree=None):
|
||||
return result
|
||||
|
||||
def get_path_for_extension(extension, subtree=None):
|
||||
if subtree is None:
|
||||
if not subtree:
|
||||
subtree = full_extension_tree()
|
||||
|
||||
for key, value in subtree.items():
|
||||
@@ -148,11 +136,11 @@ def get_path_for_extension(extension, subtree=None):
|
||||
return None
|
||||
|
||||
def get_content_type_mapping_for_extension(extension, subtree=None):
|
||||
if subtree is None:
|
||||
if not subtree:
|
||||
subtree = full_extension_tree()
|
||||
|
||||
for key, value in subtree.items():
|
||||
content_extension_matches = isinstance(value, (ContentTypeMapping, ContentTypeDetector)) and extension in value.extensions
|
||||
content_extension_matches = isinstance(value, (ContentTypeMapping, ContentTypeDetector)) and extension in value. extensions
|
||||
list_extension_matches = isinstance(value, (list, tuple)) and extension in value
|
||||
|
||||
if content_extension_matches or list_extension_matches:
|
||||
@@ -225,7 +213,6 @@ class FileManager(object):
|
||||
|
||||
import octoprint.settings
|
||||
self._recovery_file = os.path.join(octoprint.settings.settings().getBaseFolder("data"), "print_recovery_data.yaml")
|
||||
self._analyzeGcode = octoprint.settings.settings().get(["gcodeAnalysis", "runAt"])
|
||||
|
||||
def initialize(self, process_backlog=False):
|
||||
self.reload_plugins()
|
||||
@@ -233,10 +220,6 @@ class FileManager(object):
|
||||
self.process_backlog()
|
||||
|
||||
def process_backlog(self):
|
||||
# only check for a backlog if gcodeAnalysis is 'idle' or 'always'
|
||||
if self._analyzeGcode == "never":
|
||||
return
|
||||
|
||||
def worker():
|
||||
self._logger.info("Adding backlog items from all storage types to analysis queue...".format(**locals()))
|
||||
for storage_type, storage_manager in self._storage_managers.items():
|
||||
@@ -336,41 +319,38 @@ class FileManager(object):
|
||||
printer_profile_id, callback, callback_args, _error=None, _cancelled=False, _analysis=None):
|
||||
try:
|
||||
if _error:
|
||||
eventManager().fire(Events.SLICING_FAILED, dict(slicer=slicer_name,
|
||||
stl=source_path,
|
||||
stl_location=source_location,
|
||||
gcode=dest_path,
|
||||
gcode_location=dest_location,
|
||||
reason=_error))
|
||||
eventManager().fire(Events.SLICING_FAILED, dict(stl=source_path,
|
||||
stl_location=source_location,
|
||||
gcode=dest_path,
|
||||
gcode_location=dest_location,
|
||||
reason=_error))
|
||||
elif _cancelled:
|
||||
eventManager().fire(Events.SLICING_CANCELLED, dict(slicer=slicer_name,
|
||||
stl=source_path,
|
||||
stl_location=source_location,
|
||||
gcode=dest_path,
|
||||
gcode_location=dest_location))
|
||||
eventManager().fire(Events.SLICING_CANCELLED, dict(stl=source_path,
|
||||
stl_location=source_location,
|
||||
gcode=dest_path,
|
||||
gcode_location=dest_location))
|
||||
else:
|
||||
source_meta = self.get_metadata(source_location, source_path)
|
||||
hash = source_meta.get("hash", "n/a")
|
||||
hash = source_meta["hash"]
|
||||
|
||||
import io
|
||||
links = [("model", dict(name=source_path))]
|
||||
_, stl_name = self.split_path(source_location, source_path)
|
||||
file_obj = StreamWrapper(os.path.basename(dest_path),
|
||||
io.BytesIO(";Generated from {stl_name} (hash: {hash})\n".format(**locals()).encode("ascii", "replace")),
|
||||
io.FileIO(tmp_path, 'rb'))
|
||||
io.BytesIO(u";Generated from {stl_name} {hash}\n".format(**locals()).encode("ascii", "replace")),
|
||||
io.FileIO(tmp_path, "rb"))
|
||||
|
||||
printer_profile = self._printer_profile_manager.get(printer_profile_id)
|
||||
self.add_file(dest_location, dest_path, file_obj,
|
||||
display=display, links=links, allow_overwrite=True,
|
||||
printer_profile=printer_profile, analysis=_analysis)
|
||||
|
||||
end_time = octoprint.util.monotonic_time()
|
||||
eventManager().fire(Events.SLICING_DONE, dict(slicer=slicer_name,
|
||||
stl=source_path,
|
||||
stl_location=source_location,
|
||||
gcode=dest_path,
|
||||
gcode_location=dest_location,
|
||||
time=end_time - start_time))
|
||||
end_time = time.time()
|
||||
eventManager().fire(Events.SLICING_DONE, dict(stl=source_path,
|
||||
stl_location=source_location,
|
||||
gcode=dest_path,
|
||||
gcode_location=dest_location,
|
||||
time=end_time - start_time))
|
||||
|
||||
if callback is not None:
|
||||
if callback_args is None:
|
||||
@@ -390,9 +370,9 @@ class FileManager(object):
|
||||
|
||||
slicer = self._slicing_manager.get_slicer(slicer_name)
|
||||
|
||||
start_time = octoprint.util.monotonic_time()
|
||||
eventManager().fire(Events.SLICING_STARTED, {"slicer": slicer_name,
|
||||
"stl": source_path,
|
||||
import time
|
||||
start_time = time.time()
|
||||
eventManager().fire(Events.SLICING_STARTED, {"stl": source_path,
|
||||
"stl_location": source_location,
|
||||
"gcode": dest_path,
|
||||
"gcode_location": dest_location,
|
||||
@@ -435,20 +415,16 @@ class FileManager(object):
|
||||
if self._last_slicing_progress != progress_int:
|
||||
self._last_slicing_progress = progress_int
|
||||
for callback in self._slicing_progress_callbacks:
|
||||
try:
|
||||
callback.sendSlicingProgress(slicer, source_location, source_path, dest_location, dest_path, progress_int)
|
||||
except Exception:
|
||||
self._logger.exception("Exception while pushing slicing progress",
|
||||
extra=dict(callback=fqcn(callback)))
|
||||
try: callback.sendSlicingProgress(slicer, source_location, source_path, dest_location, dest_path, progress_int)
|
||||
except: self._logger.exception("Exception while pushing slicing progress")
|
||||
|
||||
if progress_int:
|
||||
def call_plugins(slicer, source_location, source_path, dest_location, dest_path, progress):
|
||||
for plugin in self._progress_plugins:
|
||||
try:
|
||||
plugin.on_slicing_progress(slicer, source_location, source_path, dest_location, dest_path, progress)
|
||||
except Exception:
|
||||
self._logger.exception("Exception while sending slicing progress to plugin %s" % plugin._identifier,
|
||||
extra=dict(plugin=plugin._identifier))
|
||||
except:
|
||||
self._logger.exception("Exception while sending slicing progress to plugin %s" % plugin._identifier)
|
||||
|
||||
import threading
|
||||
thread = threading.Thread(target=call_plugins, args=(slicer, source_location, source_path, dest_location, dest_path, progress_int))
|
||||
@@ -470,8 +446,8 @@ class FileManager(object):
|
||||
|
||||
def list_files(self, destinations=None, path=None, filter=None, recursive=None):
|
||||
if not destinations:
|
||||
destinations = list(self._storage_managers.keys())
|
||||
if isinstance(destinations, basestring):
|
||||
destinations = self._storage_managers.keys()
|
||||
if isinstance(destinations, (str, unicode, basestring)):
|
||||
destinations = [destinations]
|
||||
|
||||
result = dict()
|
||||
@@ -483,11 +459,11 @@ class FileManager(object):
|
||||
if printer_profile is None:
|
||||
printer_profile = self._printer_profile_manager.get_current_or_default()
|
||||
|
||||
for name, hook in self._preprocessor_hooks.items():
|
||||
for hook in self._preprocessor_hooks.values():
|
||||
try:
|
||||
hook_file_object = hook(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
|
||||
except Exception:
|
||||
self._logger.exception("Error when calling preprocessor hook for plugin {}, ignoring".format(name), extra=dict(plugin=name))
|
||||
except:
|
||||
self._logger.exception("Error when calling preprocessor hook {}, ignoring".format(hook))
|
||||
continue
|
||||
|
||||
if hook_file_object is not None:
|
||||
@@ -646,9 +622,9 @@ class FileManager(object):
|
||||
pos=pos,
|
||||
date=time.time())
|
||||
try:
|
||||
with atomic_write(self._recovery_file, mode='wt', max_permissions=0o666) as f:
|
||||
yaml.safe_dump(data, stream=f, default_flow_style=False, indent=2, allow_unicode=True)
|
||||
except Exception:
|
||||
with atomic_write(self._recovery_file, max_permissions=0o666) as f:
|
||||
yaml.safe_dump(data, stream=f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
except:
|
||||
self._logger.exception("Could not write recovery data to file {}".format(self._recovery_file))
|
||||
|
||||
def delete_recovery_data(self):
|
||||
@@ -657,7 +633,7 @@ class FileManager(object):
|
||||
|
||||
try:
|
||||
os.remove(self._recovery_file)
|
||||
except Exception:
|
||||
except:
|
||||
self._logger.exception("Error deleting recovery data file {}".format(self._recovery_file))
|
||||
|
||||
def get_recovery_data(self):
|
||||
@@ -666,12 +642,10 @@ class FileManager(object):
|
||||
|
||||
import yaml
|
||||
try:
|
||||
with io.open(self._recovery_file, 'rt', encoding='utf-8') as f:
|
||||
with open(self._recovery_file) as f:
|
||||
data = yaml.safe_load(f)
|
||||
if not isinstance(data, dict) or not all(map(lambda x: x in data, ("origin", "path", "pos", "date"))):
|
||||
raise ValueError("Invalid recovery data structure")
|
||||
return data
|
||||
except Exception:
|
||||
except:
|
||||
self._logger.exception("Could not read recovery data from file {}".format(self._recovery_file))
|
||||
self.delete_recovery_data()
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
@@ -18,8 +18,6 @@ import time
|
||||
|
||||
from octoprint.events import Events, eventManager
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import monotonic_time
|
||||
from octoprint.util import get_fully_qualified_classname as fqcn
|
||||
|
||||
|
||||
class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile, analysis")):
|
||||
@@ -97,28 +95,27 @@ class AnalysisQueue(object):
|
||||
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)
|
||||
for queue in self._queues.values():
|
||||
queue.dequeue_folder(destination, path)
|
||||
|
||||
def pause(self):
|
||||
for q in self._queues.values():
|
||||
q.pause()
|
||||
for queue in self._queues.values():
|
||||
queue.pause()
|
||||
|
||||
def resume(self):
|
||||
for q in self._queues.values():
|
||||
q.resume()
|
||||
for queue in self._queues.values():
|
||||
queue.resume()
|
||||
|
||||
def _analysis_finished(self, entry, result):
|
||||
for callback in self._callbacks:
|
||||
try:
|
||||
callback(entry, result)
|
||||
except:
|
||||
self._logger.exception(u"Error while pushing analysis data to callback {}".format(callback),
|
||||
extra=dict(callback=fqcn(callback)))
|
||||
callback(entry, result)
|
||||
eventManager().fire(Events.METADATA_ANALYSIS_FINISHED, {"name": entry.name,
|
||||
"path": entry.path,
|
||||
"origin": entry.location,
|
||||
"result": result})
|
||||
"result": result,
|
||||
|
||||
# TODO: deprecated, remove in a future release
|
||||
"file": entry.path})
|
||||
|
||||
class AbstractAnalysisQueue(object):
|
||||
"""
|
||||
@@ -176,10 +173,7 @@ class AbstractAnalysisQueue(object):
|
||||
(False, default)
|
||||
"""
|
||||
|
||||
if settings().get(["gcodeAnalysis", "runAt"]) == "never":
|
||||
self._logger.debug("Ignoring entry {entry} for analysis queue".format(entry=entry))
|
||||
return
|
||||
elif high_priority:
|
||||
if high_priority:
|
||||
self._logger.debug("Adding entry {entry} to analysis queue with high priority".format(entry=entry))
|
||||
prio = self.__class__.HIGH_PRIO
|
||||
else:
|
||||
@@ -255,17 +249,20 @@ class AbstractAnalysisQueue(object):
|
||||
self._current_progress = 0
|
||||
|
||||
try:
|
||||
start_time = monotonic_time()
|
||||
start_time = time.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})
|
||||
"type": entry.type,
|
||||
|
||||
# TODO deprecated, remove in 1.4.0
|
||||
"file": entry.path})
|
||||
try:
|
||||
result = self._do_analysis(high_priority=high_priority)
|
||||
except TypeError:
|
||||
result = self._do_analysis()
|
||||
self._logger.info("Analysis of entry {} finished, needed {:.2f}s".format(entry, monotonic_time() - start_time))
|
||||
self._logger.info("Analysis of entry {} finished, needed {:.2f}s".format(entry, time.time() - start_time))
|
||||
self._finished_callback(self._current, result)
|
||||
finally:
|
||||
self._current = None
|
||||
@@ -385,7 +382,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
|
||||
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)))
|
||||
raise RuntimeError(u"Error while trying to run command {}".format(" ".join(command)))
|
||||
|
||||
try:
|
||||
# let's wait for stuff to finish
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
class FileDestinations(object):
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__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 io
|
||||
|
||||
import logging
|
||||
import os
|
||||
import pylru
|
||||
import shutil
|
||||
import re
|
||||
import pylru
|
||||
import copy
|
||||
|
||||
try:
|
||||
from os import scandir, walk
|
||||
@@ -20,6 +19,7 @@ except ImportError:
|
||||
|
||||
from octoprint.util import atomic_write
|
||||
from contextlib import contextmanager
|
||||
from copy import deepcopy
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
@@ -28,7 +28,7 @@ from slugify import Slugify
|
||||
|
||||
import octoprint.filemanager
|
||||
|
||||
from octoprint.util import is_hidden_path, to_unicode, to_bytes
|
||||
from octoprint.util import is_hidden_path, to_unicode
|
||||
|
||||
class StorageInterface(object):
|
||||
"""
|
||||
@@ -450,11 +450,11 @@ class LocalFileStorage(StorageInterface):
|
||||
This storage type implements :func:`path_on_disk`.
|
||||
"""
|
||||
|
||||
_UNICODE_VARIATIONS = re.compile("[\uFE00-\uFE0F]", re.U)
|
||||
_UNICODE_VARIATIONS = re.compile(u"[\uFE00-\uFE0F]")
|
||||
|
||||
@classmethod
|
||||
def _no_unicode_variations(cls, text):
|
||||
return cls._UNICODE_VARIATIONS.sub("", text)
|
||||
return cls._UNICODE_VARIATIONS.sub(u"", text)
|
||||
|
||||
_SLUGIFY = Slugify()
|
||||
_SLUGIFY.safe_chars = "-_.()[] "
|
||||
@@ -463,7 +463,7 @@ class LocalFileStorage(StorageInterface):
|
||||
def _slugify(cls, text):
|
||||
text = to_unicode(text)
|
||||
text = cls._no_unicode_variations(text)
|
||||
text = demojize(text, delimiters=("", ""))
|
||||
text = demojize(text, delimiters=(u"", u""))
|
||||
return cls._SLUGIFY(text)
|
||||
|
||||
def __init__(self, basefolder, create=False):
|
||||
@@ -485,8 +485,6 @@ class LocalFileStorage(StorageInterface):
|
||||
import threading
|
||||
self._metadata_lock_mutex = threading.RLock()
|
||||
self._metadata_locks = dict()
|
||||
self._persisted_metadata_lock_mutex = threading.RLock()
|
||||
self._persisted_metadata_locks = dict()
|
||||
|
||||
self._metadata_cache = pylru.lrucache(10)
|
||||
|
||||
@@ -502,10 +500,10 @@ class LocalFileStorage(StorageInterface):
|
||||
if os.path.exists(old_metadata_path):
|
||||
# load the old metadata file
|
||||
try:
|
||||
with io.open(old_metadata_path, 'rt', encoding='utf-8') as f:
|
||||
with open(old_metadata_path) as f:
|
||||
import yaml
|
||||
self._old_metadata = yaml.safe_load(f)
|
||||
except Exception:
|
||||
except:
|
||||
self._logger.exception("Error while loading old metadata file")
|
||||
|
||||
# make sure the metadata is initialized as far as possible
|
||||
@@ -516,7 +514,7 @@ class LocalFileStorage(StorageInterface):
|
||||
try:
|
||||
import shutil
|
||||
shutil.move(old_metadata_path, backup_path)
|
||||
except Exception:
|
||||
except:
|
||||
self._logger.exception("Could not rename old metadata.yaml file")
|
||||
|
||||
else:
|
||||
@@ -599,10 +597,10 @@ class LocalFileStorage(StorageInterface):
|
||||
path = self.sanitize_path(to_unicode(path))
|
||||
base = self.path_in_storage(path)
|
||||
if base:
|
||||
base += "/"
|
||||
base += u"/"
|
||||
else:
|
||||
path = self.basefolder
|
||||
base = ""
|
||||
base = u""
|
||||
return self._list_folder(path, base=base, entry_filter=filter, recursive=recursive)
|
||||
|
||||
def add_folder(self, path, ignore_existing=True, display=None):
|
||||
@@ -885,8 +883,6 @@ class LocalFileStorage(StorageInterface):
|
||||
if not name in metadata:
|
||||
return
|
||||
|
||||
metadata = self._copied_metadata(metadata, name)
|
||||
|
||||
if not key in metadata[name] or overwrite:
|
||||
metadata[name][key] = data
|
||||
metadata_dirty = True
|
||||
@@ -911,20 +907,19 @@ class LocalFileStorage(StorageInterface):
|
||||
if not key in metadata[name]:
|
||||
return
|
||||
|
||||
metadata = self._copied_metadata(metadata, name)
|
||||
del metadata[name][key]
|
||||
self._save_metadata(path, metadata)
|
||||
|
||||
def split_path(self, path):
|
||||
path = to_unicode(path)
|
||||
split = path.split("/")
|
||||
split = path.split(u"/")
|
||||
if len(split) == 1:
|
||||
return "", split[0]
|
||||
return u"", split[0]
|
||||
else:
|
||||
return self.join_path(*split[:-1]), split[-1]
|
||||
|
||||
def join_path(self, *path):
|
||||
return "/".join(map(to_unicode, path))
|
||||
return u"/".join(map(to_unicode, path))
|
||||
|
||||
def sanitize(self, path):
|
||||
"""
|
||||
@@ -953,23 +948,23 @@ class LocalFileStorage(StorageInterface):
|
||||
path = to_unicode(path)
|
||||
if path.startswith(self.basefolder):
|
||||
path = path[len(self.basefolder):]
|
||||
path = path.replace(os.path.sep, "/")
|
||||
path = path.split("/")
|
||||
path = path.replace(os.path.sep, u"/")
|
||||
path = path.split(u"/")
|
||||
if isinstance(path, (list, tuple)):
|
||||
if len(path) == 1:
|
||||
name = to_unicode(path[0])
|
||||
path = ""
|
||||
path = u""
|
||||
else:
|
||||
name = to_unicode(path[-1])
|
||||
path = self.join_path(*map(to_unicode, path[:-1]))
|
||||
if not path:
|
||||
path = ""
|
||||
path = u""
|
||||
|
||||
return path, name
|
||||
|
||||
def sanitize_name(self, name):
|
||||
"""
|
||||
Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\\``. Otherwise
|
||||
Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\``. Otherwise
|
||||
slugifies the given ``name`` by converting it to ASCII, leaving ``-``, ``_``, ``.``,
|
||||
``(``, and ``)`` as is.
|
||||
"""
|
||||
@@ -978,11 +973,11 @@ class LocalFileStorage(StorageInterface):
|
||||
if name is None:
|
||||
return None
|
||||
|
||||
if "/" in name or "\\" in name:
|
||||
if u"/" in name or u"\\" in name:
|
||||
raise ValueError("name must not contain / or \\")
|
||||
|
||||
result = self._slugify(name).replace(" ", "_")
|
||||
if result and result != "." and result != ".." and result[0] == ".":
|
||||
result = self._slugify(name).replace(u" ", u"_")
|
||||
if result and result != u"." and result != u".." and result[0] == u".":
|
||||
# hidden files under *nix
|
||||
result = result[1:]
|
||||
return result
|
||||
@@ -996,12 +991,12 @@ class LocalFileStorage(StorageInterface):
|
||||
path = to_unicode(path)
|
||||
|
||||
if len(path):
|
||||
if path[0] == "/":
|
||||
if path[0] == u"/":
|
||||
path = path[1:]
|
||||
elif path[0] == "." and path[1] == "/":
|
||||
elif path[0] == u"." and path[1] == u"/":
|
||||
path = path[2:]
|
||||
|
||||
path_elements = path.split("/")
|
||||
path_elements = path.split(u"/")
|
||||
joined_path = self.basefolder
|
||||
for path_element in path_elements:
|
||||
joined_path = os.path.join(joined_path, self.sanitize_name(path_element))
|
||||
@@ -1021,16 +1016,16 @@ class LocalFileStorage(StorageInterface):
|
||||
counter = 1
|
||||
while os.path.exists(sanitized_path):
|
||||
counter += 1
|
||||
sanitized = self.sanitize_name("{}_({}){}".format(sanitized_name, counter, sanitized_ext))
|
||||
sanitized = self.sanitize_name(u"{}_({}){}".format(sanitized_name, counter, sanitized_ext))
|
||||
sanitized_path = os.path.join(path, sanitized)
|
||||
|
||||
try:
|
||||
shutil.move(entry_path, sanitized_path)
|
||||
|
||||
self._logger.info("Sanitized \"{}\" to \"{}\"".format(entry_path, sanitized_path))
|
||||
self._logger.info(u"Sanitized \"{}\" to \"{}\"".format(entry_path, sanitized_path))
|
||||
return sanitized, sanitized_path
|
||||
except Exception:
|
||||
self._logger.exception("Error while trying to rename \"{}\" to \"{}\", ignoring file".format(entry_path, sanitized_path))
|
||||
except:
|
||||
self._logger.exception(u"Error while trying to rename \"{}\" to \"{}\", ignoring file".format(entry_path, sanitized_path))
|
||||
raise
|
||||
|
||||
return entry, entry_path
|
||||
@@ -1038,12 +1033,12 @@ class LocalFileStorage(StorageInterface):
|
||||
def path_in_storage(self, path):
|
||||
if isinstance(path, (tuple, list)):
|
||||
path = self.join_path(*path)
|
||||
if isinstance(path, basestring):
|
||||
if isinstance(path, (str, unicode, basestring)):
|
||||
path = to_unicode(path)
|
||||
if path.startswith(self.basefolder):
|
||||
path = path[len(self.basefolder):]
|
||||
path = path.replace(os.path.sep, "/")
|
||||
if path.startswith("/"):
|
||||
path = path.replace(os.path.sep, u"/")
|
||||
if path.startswith(u"/"):
|
||||
path = path[1:]
|
||||
|
||||
return path
|
||||
@@ -1055,7 +1050,10 @@ class LocalFileStorage(StorageInterface):
|
||||
##~~ internals
|
||||
|
||||
def _add_history(self, name, path, data):
|
||||
metadata = self._copied_metadata(self._get_metadata(path), name)
|
||||
metadata = self._get_metadata(path)
|
||||
|
||||
if not name in metadata:
|
||||
metadata[name] = dict()
|
||||
|
||||
if not "hash" in metadata[name]:
|
||||
metadata[name]["hash"] = self._create_hash(os.path.join(path, name))
|
||||
@@ -1073,8 +1071,6 @@ class LocalFileStorage(StorageInterface):
|
||||
if not name in metadata or not "history" in metadata[name]:
|
||||
return
|
||||
|
||||
metadata = self._copied_metadata(metadata, name)
|
||||
|
||||
try:
|
||||
metadata[name]["history"][index].update(data)
|
||||
self._calculate_stats_from_history(name, path, metadata=metadata, save=False)
|
||||
@@ -1088,8 +1084,6 @@ class LocalFileStorage(StorageInterface):
|
||||
if not name in metadata or not "history" in metadata[name]:
|
||||
return
|
||||
|
||||
metadata = self._copied_metadata(metadata, name)
|
||||
|
||||
try:
|
||||
del metadata[name]["history"][index]
|
||||
self._calculate_stats_from_history(name, path, metadata=metadata, save=False)
|
||||
@@ -1099,9 +1093,9 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
def _calculate_stats_from_history(self, name, path, metadata=None, save=True):
|
||||
if metadata is None:
|
||||
metadata = self._copied_metadata(self._get_metadata(path), name)
|
||||
metadata = self._get_metadata(path)
|
||||
|
||||
if not "history" in metadata[name]:
|
||||
if not name in metadata or not "history" in metadata[name]:
|
||||
return
|
||||
|
||||
# collect data from history
|
||||
@@ -1120,8 +1114,8 @@ class LocalFileStorage(StorageInterface):
|
||||
print_time = history_entry["printTime"]
|
||||
try:
|
||||
print_time = float(print_time)
|
||||
except Exception:
|
||||
self._logger.warning("Invalid print time value found in print history for {} in {}/.metadata.json: {!r}".format(name, path, print_time))
|
||||
except:
|
||||
self._logger.warn("Invalid print time value found in print history for {} in {}/.metadata.json: {!r}".format(name, path, print_time))
|
||||
continue
|
||||
|
||||
if not printer_profile in former_print_times:
|
||||
@@ -1170,9 +1164,12 @@ class LocalFileStorage(StorageInterface):
|
||||
if file_type:
|
||||
file_type = file_type[0]
|
||||
|
||||
metadata = self._copied_metadata(self._get_metadata(path), name)
|
||||
metadata = self._get_metadata(path)
|
||||
metadata_dirty = False
|
||||
|
||||
if not name in metadata:
|
||||
metadata[name] = dict()
|
||||
|
||||
if not "hash" in metadata[name]:
|
||||
metadata[name]["hash"] = self._create_hash(os.path.join(path, name))
|
||||
|
||||
@@ -1244,10 +1241,13 @@ class LocalFileStorage(StorageInterface):
|
||||
self._save_metadata(path, metadata)
|
||||
|
||||
def _remove_links(self, name, path, links):
|
||||
metadata = self._copied_metadata(self._get_metadata(path), name)
|
||||
metadata = self._get_metadata(path)
|
||||
metadata_dirty = False
|
||||
|
||||
hash = metadata[name].get("hash", self._create_hash(os.path.join(path, name)))
|
||||
if not name in metadata or not "hash" in metadata[name]:
|
||||
hash = self._create_hash(os.path.join(path, name))
|
||||
else:
|
||||
hash = metadata[name]["hash"]
|
||||
|
||||
for rel, data in links:
|
||||
if (rel == "model" or rel == "machinecode") and "name" in data:
|
||||
@@ -1255,7 +1255,6 @@ class LocalFileStorage(StorageInterface):
|
||||
ref_rel = "model" if rel == "machinecode" else "machinecode"
|
||||
for link in metadata[data["name"]]["links"]:
|
||||
if link["rel"] == ref_rel and "name" in link and link["name"] == name and "hash" in link and link["hash"] == hash:
|
||||
metadata[data["name"]] = copy.deepcopy(metadata[data["name"]])
|
||||
metadata[data["name"]]["links"].remove(link)
|
||||
metadata_dirty = True
|
||||
|
||||
@@ -1300,7 +1299,7 @@ class LocalFileStorage(StorageInterface):
|
||||
entry_is_file = entry.is_file()
|
||||
entry_is_dir = entry.is_dir()
|
||||
entry_stat = entry.stat()
|
||||
except Exception:
|
||||
except:
|
||||
# error while trying to fetch file metadata, that might be thanks to file already having
|
||||
# been moved or deleted - ignore it and continue
|
||||
continue
|
||||
@@ -1312,7 +1311,7 @@ class LocalFileStorage(StorageInterface):
|
||||
entry_name = new_entry_name
|
||||
entry_path = new_entry_path
|
||||
entry_stat = os.stat(entry_path)
|
||||
except Exception:
|
||||
except:
|
||||
# error while trying to rename the file, we'll continue here and ignore it
|
||||
continue
|
||||
|
||||
@@ -1331,14 +1330,10 @@ class LocalFileStorage(StorageInterface):
|
||||
if entry_name in metadata and isinstance(metadata[entry_name], dict):
|
||||
entry_metadata = metadata[entry_name]
|
||||
if not "display" in entry_metadata and entry_display != entry_name:
|
||||
if not metadata_dirty:
|
||||
metadata = self._copied_metadata(metadata, entry_name)
|
||||
metadata[entry_name]["display"] = entry_display
|
||||
entry_metadata["display"] = entry_display
|
||||
metadata_dirty = True
|
||||
else:
|
||||
if not metadata_dirty:
|
||||
metadata = self._copied_metadata(metadata, entry_name)
|
||||
entry_metadata = self._add_basic_metadata(path, entry_name,
|
||||
display_name=entry_display,
|
||||
save=False,
|
||||
@@ -1368,14 +1363,10 @@ class LocalFileStorage(StorageInterface):
|
||||
if entry_name in metadata and isinstance(metadata[entry_name], dict):
|
||||
entry_metadata = metadata[entry_name]
|
||||
if not "display" in entry_metadata and entry_display != entry_name:
|
||||
if not metadata_dirty:
|
||||
metadata = self._copied_metadata(metadata, entry_name)
|
||||
metadata[entry_name]["display"] = entry_display
|
||||
entry_metadata["display"] = entry_display
|
||||
metadata_dirty = True
|
||||
elif entry_name != entry_display:
|
||||
if not metadata_dirty:
|
||||
metadata = self._copied_metadata(metadata, entry_name)
|
||||
entry_metadata = self._add_basic_metadata(path, entry_name,
|
||||
display_name=entry_display,
|
||||
save=False,
|
||||
@@ -1417,7 +1408,7 @@ class LocalFileStorage(StorageInterface):
|
||||
extended_entry_data["size"] = get_size()
|
||||
|
||||
result[entry_name] = extended_entry_data
|
||||
except Exception:
|
||||
except:
|
||||
# So something went wrong somewhere while processing this file entry - log that and continue
|
||||
self._logger.exception("Error while processing entry {}".format(entry_path))
|
||||
continue
|
||||
@@ -1459,8 +1450,6 @@ class LocalFileStorage(StorageInterface):
|
||||
entry_data["display"] = display_name
|
||||
|
||||
entry_data.update(additional_metadata)
|
||||
|
||||
metadata = copy.copy(metadata)
|
||||
metadata[entry] = entry_data
|
||||
|
||||
if save:
|
||||
@@ -1473,7 +1462,7 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
blocksize = 65536
|
||||
hash = hashlib.sha1()
|
||||
with io.open(path, 'rb') as f:
|
||||
with open(path, "rb") as f:
|
||||
buffer = f.read(blocksize)
|
||||
while len(buffer) > 0:
|
||||
hash.update(buffer)
|
||||
@@ -1492,8 +1481,6 @@ class LocalFileStorage(StorageInterface):
|
||||
if not name in metadata:
|
||||
return
|
||||
|
||||
metadata = copy.copy(metadata)
|
||||
|
||||
if "hash" in metadata[name]:
|
||||
hash = metadata[name]["hash"]
|
||||
for m in metadata.values():
|
||||
@@ -1507,7 +1494,7 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
def _update_metadata_entry(self, path, name, data):
|
||||
with self._get_metadata_lock(path):
|
||||
metadata = copy.copy(self._get_metadata(path))
|
||||
metadata = self._get_metadata(path)
|
||||
metadata[name] = data
|
||||
self._save_metadata(path, metadata)
|
||||
|
||||
@@ -1526,91 +1513,58 @@ class LocalFileStorage(StorageInterface):
|
||||
with self._get_metadata_lock(destination_path):
|
||||
self._update_metadata_entry(destination_path, destination_name, source_data)
|
||||
|
||||
def _get_metadata(self, path, force=False):
|
||||
import json
|
||||
def _get_metadata(self, path):
|
||||
with self._get_metadata_lock(path):
|
||||
if path in self._metadata_cache:
|
||||
return deepcopy(self._metadata_cache[path])
|
||||
|
||||
if not force:
|
||||
metadata = self._metadata_cache.get(path)
|
||||
if metadata:
|
||||
return metadata
|
||||
self._migrate_metadata(path)
|
||||
|
||||
self._migrate_metadata(path)
|
||||
|
||||
metadata_path = os.path.join(path, ".metadata.json")
|
||||
|
||||
metadata = None
|
||||
with self._get_persisted_metadata_lock(path):
|
||||
metadata_path = os.path.join(path, ".metadata.json")
|
||||
if os.path.exists(metadata_path):
|
||||
with io.open(metadata_path, 'rt', encoding='utf-8') as f:
|
||||
with open(metadata_path) as f:
|
||||
try:
|
||||
import json
|
||||
metadata = json.load(f)
|
||||
except Exception:
|
||||
except:
|
||||
self._logger.exception("Error while reading .metadata.json from {path}".format(**locals()))
|
||||
|
||||
def valid_json(value):
|
||||
try:
|
||||
json.dumps(value, allow_nan=False)
|
||||
return True
|
||||
except:
|
||||
return False
|
||||
|
||||
if isinstance(metadata, dict):
|
||||
old_size = len(metadata)
|
||||
metadata = { k: v for k, v in metadata.items() if valid_json(v) }
|
||||
metadata = { k: v for k, v in metadata.items() if os.path.exists(os.path.join(path, k)) }
|
||||
new_size = len(metadata)
|
||||
if new_size != old_size:
|
||||
self._logger.info("Deleted {} stale or invalid entries from metadata for path {}".format(old_size - new_size,
|
||||
path))
|
||||
self._save_metadata(path, metadata)
|
||||
else:
|
||||
with self._get_metadata_lock(path):
|
||||
self._metadata_cache[path] = metadata
|
||||
return metadata
|
||||
else:
|
||||
else:
|
||||
if isinstance(metadata, dict):
|
||||
self._metadata_cache[path] = deepcopy(metadata)
|
||||
return metadata
|
||||
return dict()
|
||||
|
||||
def _save_metadata(self, path, metadata):
|
||||
import json
|
||||
|
||||
with self._get_metadata_lock(path):
|
||||
self._metadata_cache[path] = metadata
|
||||
|
||||
with self._get_persisted_metadata_lock(path):
|
||||
metadata_path = os.path.join(path, ".metadata.json")
|
||||
try:
|
||||
with atomic_write(metadata_path, mode='wb') as f:
|
||||
f.write(to_bytes(json.dumps(metadata, indent=4, separators=(",", ": "))))
|
||||
except Exception:
|
||||
import json
|
||||
with atomic_write(metadata_path) as f:
|
||||
json.dump(metadata, f, indent=4, separators=(",", ": "))
|
||||
except:
|
||||
self._logger.exception("Error while writing .metadata.json to {path}".format(**locals()))
|
||||
else:
|
||||
self._metadata_cache[path] = deepcopy(metadata)
|
||||
|
||||
def _delete_metadata(self, path):
|
||||
with self._get_metadata_lock(path):
|
||||
if path in self._metadata_cache:
|
||||
del self._metadata_cache[path]
|
||||
|
||||
with self._get_persisted_metadata_lock(path):
|
||||
metadata_files = (".metadata.json", ".metadata.yaml")
|
||||
for metadata_file in metadata_files:
|
||||
metadata_path = os.path.join(path, metadata_file)
|
||||
if os.path.exists(metadata_path):
|
||||
try:
|
||||
os.remove(metadata_path)
|
||||
except Exception:
|
||||
except:
|
||||
self._logger.exception("Error while deleting {metadata_file} from {path}".format(**locals()))
|
||||
|
||||
@staticmethod
|
||||
def _copied_metadata(metadata, name):
|
||||
metadata = copy.copy(metadata)
|
||||
metadata[name] = copy.deepcopy(metadata.get(name, dict()))
|
||||
return metadata
|
||||
if path in self._metadata_cache:
|
||||
del self._metadata_cache[path]
|
||||
|
||||
def _migrate_metadata(self, path):
|
||||
# we switched to json in 1.3.9 - if we still have yaml here, migrate it now
|
||||
import yaml
|
||||
import json
|
||||
|
||||
with self._get_persisted_metadata_lock(path):
|
||||
with self._get_metadata_lock(path):
|
||||
metadata_path_yaml = os.path.join(path, ".metadata.yaml")
|
||||
metadata_path_json = os.path.join(path, ".metadata.json")
|
||||
|
||||
@@ -1620,16 +1574,13 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
if os.path.exists(metadata_path_json):
|
||||
# already migrated
|
||||
try:
|
||||
os.remove(metadata_path_yaml)
|
||||
except Exception:
|
||||
self._logger.exception("Error while removing .metadata.yaml from {path}".format(**locals()))
|
||||
# TODO 1.3.10 Remove ".metadata.yaml" files
|
||||
return
|
||||
|
||||
with io.open(metadata_path_yaml, 'rt', encoding='utf-8') as f:
|
||||
with open(metadata_path_yaml) as f:
|
||||
try:
|
||||
metadata = yaml.safe_load(f)
|
||||
except Exception:
|
||||
except:
|
||||
self._logger.exception("Error while reading .metadata.yaml from {path}".format(**locals()))
|
||||
return
|
||||
|
||||
@@ -1637,13 +1588,10 @@ class LocalFileStorage(StorageInterface):
|
||||
# looks invalid, ignore it
|
||||
return
|
||||
|
||||
with atomic_write(metadata_path_json, mode='wb') as f:
|
||||
f.write(to_bytes(json.dumps(metadata, indent=4, separators=(",", ": "))))
|
||||
with atomic_write(metadata_path_json) as f:
|
||||
json.dump(metadata, f, indent=4, separators=(",", ": "))
|
||||
|
||||
try:
|
||||
os.remove(metadata_path_yaml)
|
||||
except Exception:
|
||||
self._logger.exception("Error while removing .metadata.yaml from {path}".format(**locals()))
|
||||
# TODO 1.3.10 Remove ".metadata.yaml" files
|
||||
|
||||
@contextmanager
|
||||
def _get_metadata_lock(self, path):
|
||||
@@ -1665,24 +1613,3 @@ class LocalFileStorage(StorageInterface):
|
||||
del self._metadata_locks[path]
|
||||
else:
|
||||
self._metadata_locks[path] = (counter, lock)
|
||||
|
||||
@contextmanager
|
||||
def _get_persisted_metadata_lock(self, path):
|
||||
with self._persisted_metadata_lock_mutex:
|
||||
if path not in self._persisted_metadata_locks:
|
||||
import threading
|
||||
self._persisted_metadata_locks[path] = (0, threading.RLock())
|
||||
|
||||
counter, lock = self._persisted_metadata_locks[path]
|
||||
counter += 1
|
||||
self._persisted_metadata_locks[path] = (counter, lock)
|
||||
|
||||
yield lock
|
||||
|
||||
with self._persisted_metadata_lock_mutex:
|
||||
counter = self._persisted_metadata_locks[path][0]
|
||||
counter -= 1
|
||||
if counter <= 0:
|
||||
del self._persisted_metadata_locks[path]
|
||||
else:
|
||||
self._persisted_metadata_locks[path] = (counter, lock)
|
||||
Loaded 100 of 466 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user