Compare commits
332
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d99af420ac | ||
|
|
73c2baa39e | ||
|
|
054df68741 | ||
|
|
f7756698e9 | ||
|
|
453ef0cb97 | ||
|
|
5015422086 | ||
|
|
2d85d8acf8 | ||
|
|
2af589a823 | ||
|
|
20c55f4d3d | ||
|
|
b7fdc82d30 | ||
|
|
770ebf2cf9 | ||
|
|
a75c641c18 | ||
|
|
38c09153ac | ||
|
|
e30e18e431 | ||
|
|
249d19f55b | ||
|
|
2e043ecf5b | ||
|
|
831edf234d | ||
|
|
b42c753d3f | ||
|
|
924cd5cb4c | ||
|
|
73f7c4d8a1 | ||
|
|
10079b8d9d | ||
|
|
c31566a626 | ||
|
|
0cfc7a2976 | ||
|
|
de5a10163e | ||
|
|
0a22c4e66c | ||
|
|
a88d95af77 | ||
|
|
010221ab5b | ||
|
|
6471a04a86 | ||
|
|
7b2762c590 | ||
|
|
de0b97b99c | ||
|
|
60d2bd1ac1 | ||
|
|
4d716647e5 | ||
|
|
43ab47a260 | ||
|
|
88ecfbdb65 | ||
|
|
8087967683 | ||
|
|
cb43197105 | ||
|
|
b1b9329614 | ||
|
|
7317814ce0 | ||
|
|
66ef7b66bb | ||
|
|
be3ff5f043 | ||
|
|
c36fa6da90 | ||
|
|
aadcf650c7 | ||
|
|
95c3fa0b04 | ||
|
|
1d0829a1db | ||
|
|
8d31d6687e | ||
|
|
3f3cb556a7 | ||
|
|
4460c8bee0 | ||
|
|
89b597a656 | ||
|
|
e1a25a8913 | ||
|
|
482c2f7115 | ||
|
|
7fa4ebd1ec | ||
|
|
9c3b552aa8 | ||
|
|
3229e65a8d | ||
|
|
7191d39b51 | ||
|
|
58bc5171ee | ||
|
|
74f3bc9ae6 | ||
|
|
464d9c0757 | ||
|
|
94ae90ab80 | ||
|
|
33b89550a4 | ||
|
|
9661469532 | ||
|
|
b06c222a7d | ||
|
|
9f85b54681 | ||
|
|
5d1ad5d75d | ||
|
|
dc32f955b7 | ||
|
|
220592c267 | ||
|
|
0faa6879b4 | ||
|
|
71b5de91bf | ||
|
|
928d62a517 | ||
|
|
78bd3b1a52 | ||
|
|
b9bab0577b | ||
|
|
c41551a643 | ||
|
|
6c92dd1303 | ||
|
|
124f01ca2d | ||
|
|
0dece85fa7 | ||
|
|
caebf90ee9 | ||
|
|
0c77014903 | ||
|
|
231a796200 | ||
|
|
fe755405e8 | ||
|
|
2200f2186c | ||
|
|
b57b7cb606 | ||
|
|
f2b2496e58 | ||
|
|
e603b98d0d | ||
|
|
e235fc299f | ||
|
|
4f25ed546e | ||
|
|
f72b9db6a9 | ||
|
|
80e8e33283 | ||
|
|
00d0396417 | ||
|
|
59e39662f1 | ||
|
|
038e1b9a57 | ||
|
|
bbefeeeb02 | ||
|
|
2801da5c51 | ||
|
|
471dab9406 | ||
|
|
1deb247ce5 | ||
|
|
4469a2d84a | ||
|
|
2da7aa358d | ||
|
|
cbb083d7f6 | ||
|
|
d68de2c3c7 | ||
|
|
454c5e494a | ||
|
|
3b1874ea25 | ||
|
|
e0233dee13 | ||
|
|
84a99e1b53 | ||
|
|
b7e0e89bb4 | ||
|
|
d8c3063813 | ||
|
|
1485050234 | ||
|
|
6d7721f8f5 | ||
|
|
e3ae71eabd | ||
|
|
e88041c59e | ||
|
|
e17db4e1cf | ||
|
|
766a64c8f6 | ||
|
|
8485d2c9a7 | ||
|
|
397e691a6a | ||
|
|
6481f7cf6b | ||
|
|
46c527d24a | ||
|
|
5392f39cc4 | ||
|
|
4a324b4f5e | ||
|
|
2855b0e7a7 | ||
|
|
39e4cd3136 | ||
|
|
8fefa63c8c | ||
|
|
10532b9118 | ||
|
|
7f2eb470e4 | ||
|
|
8955b8e0b6 | ||
|
|
ee9d5048e2 | ||
|
|
09bb74b6c6 | ||
|
|
493dddf66e | ||
|
|
8173f8d0c4 | ||
|
|
01feec47d7 | ||
|
|
2b60dbc7e1 | ||
|
|
32f5f36e5a | ||
|
|
96294df710 | ||
|
|
ef54cbb148 | ||
|
|
9cd597a467 | ||
|
|
2263ebde72 | ||
|
|
1fd8d597ab | ||
|
|
2aec0b3a75 | ||
|
|
47d10a6d3e | ||
|
|
ee216ddc93 | ||
|
|
7756d312e2 | ||
|
|
19e03eeeb2 | ||
|
|
e73aeba03b | ||
|
|
87f3c5acce | ||
|
|
a38a3e67c9 | ||
|
|
547ae9e13e | ||
|
|
b031092f07 | ||
|
|
6e6dd2c34e | ||
|
|
759f4f8ea2 | ||
|
|
bee82bcde9 | ||
|
|
888fb97e66 | ||
|
|
9c775bd899 | ||
|
|
4bf3445eef | ||
|
|
47b3f51a3f | ||
|
|
2e6b85990d | ||
|
|
30a4b9e9ab | ||
|
|
81a259e51b | ||
|
|
e85e9661e0 | ||
|
|
1d60250942 | ||
|
|
e11463f6ce | ||
|
|
1146a1bb6f | ||
|
|
311fdd5aca | ||
|
|
6ddc55bf80 | ||
|
|
2c930ef069 | ||
|
|
3739bbc652 | ||
|
|
8d544e63f4 | ||
|
|
7e4cf6c5dc | ||
|
|
c8d162c999 | ||
|
|
017515dcc1 | ||
|
|
d8bd684f96 | ||
|
|
aad5c70eb0 | ||
|
|
ea2f0a9b17 | ||
|
|
c4131d5e4b | ||
|
|
21127bcf2a | ||
|
|
04da8afb07 | ||
|
|
c38f06cce2 | ||
|
|
968f952f69 | ||
|
|
8409fdaa48 | ||
|
|
f29e736427 | ||
|
|
ac3b6f6df8 | ||
|
|
a4444ccb68 | ||
|
|
270a0dcb1f | ||
|
|
a889bec4d8 | ||
|
|
7ee9bc32eb | ||
|
|
fd62c1fa3d | ||
|
|
a445cfe65e | ||
|
|
e20a9925dd | ||
|
|
09a4fb2515 | ||
|
|
cce7389a42 | ||
|
|
b138ea7a47 | ||
|
|
3b708ce079 | ||
|
|
4441618be5 | ||
|
|
0525c9ab40 | ||
|
|
0035e7c3ff | ||
|
|
073060d253 | ||
|
|
55980a1c2c | ||
|
|
852a2cf157 | ||
|
|
2e6ee57162 | ||
|
|
5c54f16ece | ||
|
|
04a13268ad | ||
|
|
49fdac7528 | ||
|
|
75f6ef4bae | ||
|
|
9fd608691b | ||
|
|
a70a45f062 | ||
|
|
61b0845f19 | ||
|
|
30d618267f | ||
|
|
b9665a8af4 | ||
|
|
204d212323 | ||
|
|
04528a635b | ||
|
|
15522a98b0 | ||
|
|
db1c18075f | ||
|
|
3b556e9d79 | ||
|
|
8761273636 | ||
|
|
08efe80304 | ||
|
|
c4258c5bb0 | ||
|
|
58799888b7 | ||
|
|
fb6d57963b | ||
|
|
03f228c0ef | ||
|
|
93ae368f58 | ||
|
|
378752e155 | ||
|
|
bec307900d | ||
|
|
cc1d88c4c8 | ||
|
|
72eef3e224 | ||
|
|
84f6833597 | ||
|
|
2a94abdc49 | ||
|
|
fab5f34aaa | ||
|
|
76f79e5380 | ||
|
|
1b25029207 | ||
|
|
8df2a5436b | ||
|
|
72f005b7fe | ||
|
|
0eac10d5a6 | ||
|
|
2a42f02aec | ||
|
|
7c48cfd0f7 | ||
|
|
bba796d551 | ||
|
|
a855f3e62c | ||
|
|
5079e7e891 | ||
|
|
ddc948fa94 | ||
|
|
f88f2b25ea | ||
|
|
ea59dab7ab | ||
|
|
f0914c2214 | ||
|
|
b3e76c3ecc | ||
|
|
a4d5acb0b8 | ||
|
|
79b66f17b6 | ||
|
|
bcb6c7a1d4 | ||
|
|
36198c684f | ||
|
|
a3a60c5967 | ||
|
|
6df3cb5c12 | ||
|
|
0611329a6d | ||
|
|
2f90fca5ce | ||
|
|
e4e97190da | ||
|
|
9c748a85b4 | ||
|
|
78c2199d89 | ||
|
|
0e67906d1e | ||
|
|
4c602cba2e | ||
|
|
89255e2ec9 | ||
|
|
372b3662e9 | ||
|
|
e007dbaf4c | ||
|
|
dbe07af426 | ||
|
|
f67f9b9399 | ||
|
|
c6c5328418 | ||
|
|
accbfc2b45 | ||
|
|
9976f2b7a3 | ||
|
|
f249563b2c | ||
|
|
09e023917c | ||
|
|
799b86b287 | ||
|
|
ea1bcf8e5d | ||
|
|
ee93e25ffd | ||
|
|
d25f664be3 | ||
|
|
3bffe4f7cb | ||
|
|
f140dd9d44 | ||
|
|
d44747b39a | ||
|
|
f2da9d8d7d | ||
|
|
5483ef7cd4 | ||
|
|
85d212ba97 | ||
|
|
44af09580a | ||
|
|
530fca95e4 | ||
|
|
59ae7e39f2 | ||
|
|
72167d14d2 | ||
|
|
2c6568acd1 | ||
|
|
e27c216a05 | ||
|
|
7b4c148dd7 | ||
|
|
a924520dd6 | ||
|
|
1c3e463ac6 | ||
|
|
e88eb6dd85 | ||
|
|
59dfa994bd | ||
|
|
6959ce4d38 | ||
|
|
08bc0082cf | ||
|
|
6069d74a54 | ||
|
|
68ee7030f1 | ||
|
|
81342acccc | ||
|
|
e029f33901 | ||
|
|
7bd8cff137 | ||
|
|
055dcfa0e1 | ||
|
|
8acf417383 | ||
|
|
b50e1aee8a | ||
|
|
c714bce17e | ||
|
|
a9a8e48489 | ||
|
|
9dec840818 | ||
|
|
9af125ca6d | ||
|
|
1f4fabe6ef | ||
|
|
121f36704d | ||
|
|
85ff545c07 | ||
|
|
3662c84de5 | ||
|
|
79558fdfbf | ||
|
|
11040f272a | ||
|
|
fa2716c65c | ||
|
|
768b06e35a | ||
|
|
0820c23aea | ||
|
|
361fbaa366 | ||
|
|
a91359f2af | ||
|
|
4bfabf82ae | ||
|
|
c90f556fe9 | ||
|
|
352b190a72 | ||
|
|
e9b0bd9e65 | ||
|
|
c8ea808d93 | ||
|
|
d40c3e6241 | ||
|
|
e94f789b72 | ||
|
|
9ff44c49a6 | ||
|
|
c7b933ba00 | ||
|
|
6765b25803 | ||
|
|
59b60f5dad | ||
|
|
2822992843 | ||
|
|
1b82aa859f | ||
|
|
12be637f85 | ||
|
|
3bd9d11fc3 | ||
|
|
e864d6b03e | ||
|
|
547db7c1f5 | ||
|
|
d6516e4a4c | ||
|
|
2387b4a771 | ||
|
|
b03d43156d | ||
|
|
07423712a6 | ||
|
|
81735d07c9 | ||
|
|
03e328fd13 | ||
|
|
7efcf00baf | ||
|
|
a3254466f7 | ||
|
|
f8dc504773 |
No files matched your search
@@ -0,0 +1,5 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: [foosel]
|
||||
patreon: foosel
|
||||
custom: https://octoprint.org/support-octoprint/
|
||||
@@ -16,8 +16,9 @@ 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, or maintenance if it's
|
||||
a bug fix for an issue present in the current stable version (no PRs
|
||||
* [ ] 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
|
||||
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),
|
||||
|
||||
+12
-9
@@ -18,16 +18,19 @@ prerelease
|
||||
HEAD
|
||||
\(detached.*
|
||||
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.3.12
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.4.1
|
||||
# so are any fix/... and improve/... branches
|
||||
maintenance 1.3.12 73df8c2407f04756261acfe62ac3d72877f8a97d pep440-dev
|
||||
fix/.* 1.3.12 73df8c2407f04756261acfe62ac3d72877f8a97d pep440-dev
|
||||
improve/.* 1.3.12 73df8c2407f04756261acfe62ac3d72877f8a97d pep440-dev
|
||||
maintenance 1.4.1 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev
|
||||
fix/.* 1.4.1 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev
|
||||
improve/.* 1.4.1 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev
|
||||
|
||||
# staging/maintenance is currently the branch for preparation of 1.3.11rc4
|
||||
# staging/maintenance is currently the branch for preparation of 1.4.0rc6
|
||||
# so is regressionfix/...
|
||||
staging/maintenance 1.3.11rc4 af3285854995fb5b910fd2ce869e26c02d57bbc2 pep440-dev
|
||||
regressionfix/.* 1.3.11rc4 af3285854995fb5b910fd2ce869e26c02d57bbc2 pep440-dev
|
||||
staging/maintenance 1.4.0rc6 73f7c4d8a11a7aea7b0ece474d3bf37ad53c65d4 pep440-dev
|
||||
regressionfix/.* 1.4.0rc6 73f7c4d8a11a7aea7b0ece474d3bf37ad53c65d4 pep440-dev
|
||||
|
||||
# every other branch is a development branch and thus gets resolved to 1.4.0-dev for now
|
||||
.* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
|
||||
# staging/devel is currently inactive (but has the 1.4.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
|
||||
+10
@@ -105,6 +105,16 @@ date of first contribution):
|
||||
* [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
|
||||
|
||||
+3
-1172
File diff suppressed because it is too large.
Load diff
@@ -31,7 +31,7 @@ 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
|
||||
might be of more interest for you. You might also want to subscribe to join
|
||||
[the community forum at community.octoprint.org](https://community.octoprint.org) where there are other active users who might be
|
||||
able to help you with any questions you might have.
|
||||
|
||||
@@ -39,7 +39,7 @@ able to help you with any questions you might have.
|
||||
|
||||
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
|
||||
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)
|
||||
and also [financially](https://octoprint.org/support-octoprint/?utm_source=github&utm_medium=readme).
|
||||
|
||||
@@ -65,14 +65,15 @@ you already have Python 2.7, 3.6 or 3.7, pip and virtualenv set up on your syste
|
||||
|
||||
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`
|
||||
3. Create a user-owned virtual environment therein: `virtualenv venv` if your system default python version is
|
||||
python 2.7, otherwise you need to specify the version explicitly, e.g. `virtualenv --python=python2.7 venv`.
|
||||
4. Install OctoPrint *into that virtual environment*: `./venv/bin/pip install .`
|
||||
|
||||
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
|
||||
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
# Security Policy
|
||||
|
||||
## Supported Versions
|
||||
|
||||
Always update to the latest version of OctoPrint to keep up with security patches.
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
Email to security@octoprint.org.
|
||||
|
||||
For the sake of the userbase of OctoPrint please always disclose responsibly and with a 90+ day window.
|
||||
+20
-12
@@ -6,52 +6,60 @@ thanks to everyone who contributed!
|
||||
|
||||
## Patreon Patrons
|
||||
|
||||
* Andre Bubel
|
||||
* Andrew Moorby
|
||||
* Arnljot Arntsen
|
||||
* Bjorn Breckenridge
|
||||
* BigTreeTech
|
||||
* Boris Hussein
|
||||
* Brad Jackson
|
||||
* Christian Petropolis
|
||||
* Christian Wolf
|
||||
* COLLE+McVOY
|
||||
* D Brian Kimmel
|
||||
* DeltaMaker 3D Printers
|
||||
* Dennis Breining
|
||||
* Dorian Gray
|
||||
* E3D BigBox
|
||||
* Eric Betts
|
||||
* Ernesto Martinez
|
||||
* Franziska Kunsmann
|
||||
* GadgetAngel
|
||||
* George Robles
|
||||
* Greg Holloway
|
||||
* Hog Duske
|
||||
* Hugh Blemings
|
||||
* jean-claude migneault
|
||||
* Jeff Renfer
|
||||
* Jefferson Hunt
|
||||
* Jeremiah Avery
|
||||
* Joseph Payne
|
||||
* Joshua Wills
|
||||
* Justin Kaufman
|
||||
* Kaile Riser
|
||||
* Kale Stedman
|
||||
* Kazuhiro Ogura
|
||||
* Kenneth Jiang
|
||||
* Kurt Wubbels
|
||||
* Kyle Menigoz
|
||||
* LA 3D Printer Repair
|
||||
* LulzBot®
|
||||
* Lee Dohm
|
||||
* Makespace Madrid
|
||||
* Mark Walker
|
||||
* Martin Majewski
|
||||
* Michael Aumock
|
||||
* Miles Flavel
|
||||
* Mosaic Manufacturing
|
||||
* OMER MEHMET SUTAS
|
||||
* Neil R. Goldberg
|
||||
* Patrick Glyré
|
||||
* Patrick McGinnis
|
||||
* Prof Yuh Wen Chen
|
||||
* Randy C. Will
|
||||
* Ranjib Dey
|
||||
* Richard Michaud
|
||||
* Rigid3D
|
||||
* Robert Gusek
|
||||
* Samer Najia
|
||||
* Shawn Lewis
|
||||
* Ronald Griehsler
|
||||
* Sacha Telgenhof
|
||||
* sghnsk
|
||||
* Simon Hallam
|
||||
* Stefan Krister
|
||||
* Sven Mueller
|
||||
* TEVO 3D Printers
|
||||
* Trent Shumay
|
||||
* Ulrich Kempken
|
||||
|
||||
and 1544 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
||||
and 1764 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [Github Sponsors](https://github.com/users/foosel/sponsorship)!
|
||||
@@ -0,0 +1,529 @@
|
||||
.. _sec-api-access:
|
||||
|
||||
**************
|
||||
Access control
|
||||
**************
|
||||
|
||||
.. contents::
|
||||
|
||||
.. _sec-api-access-permissions:
|
||||
|
||||
Permissions
|
||||
===========
|
||||
|
||||
.. _sec-api-access-permissions-list:
|
||||
|
||||
List all permissions
|
||||
--------------------
|
||||
|
||||
.. http:get:: /api/access/permissions
|
||||
|
||||
Retrieves all permissions available in the system.
|
||||
|
||||
Will return a :http:statuscode:`200` with a :ref:`permission list <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
|
||||
@@ -16,6 +16,8 @@ Get connection settings
|
||||
Retrieve the current connection settings, including information regarding the available baudrates and
|
||||
serial ports and the current connection state.
|
||||
|
||||
Requires the ``STATUS`` permission.
|
||||
|
||||
**Example**
|
||||
|
||||
.. sourcecode:: http
|
||||
@@ -81,7 +83,7 @@ Issue a connection command
|
||||
for the lost acknowledgment should always be properly investigated and removed instead of depending on this
|
||||
"symptom solver".
|
||||
|
||||
Requires user rights.
|
||||
Requires the ``CONNECTION`` permission.
|
||||
|
||||
**Example Connect Request**
|
||||
|
||||
|
||||
@@ -218,6 +218,17 @@ 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:
|
||||
|
||||
@@ -469,3 +480,173 @@ References
|
||||
- URL
|
||||
- The model from which this file was generated (e.g. an STL, currently not used). Never present for
|
||||
folders.
|
||||
|
||||
.. _sec-api-datamodel-access:
|
||||
|
||||
Access control
|
||||
==============
|
||||
|
||||
.. _sec-api-datamodel-access-users:
|
||||
|
||||
User record
|
||||
-----------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``name``
|
||||
- 1
|
||||
- string
|
||||
- The user's name
|
||||
* - ``active``
|
||||
- 1
|
||||
- bool
|
||||
- Whether the user's account is active (true) or not (false)
|
||||
* - ``user``
|
||||
- 1
|
||||
- bool
|
||||
- Whether the user has user rights. Should always be true. Deprecated as of 1.4.0, use the ``users`` group instead.
|
||||
* - ``admin``
|
||||
- 1
|
||||
- bool
|
||||
- Whether the user has admin rights (true) or not (false). Deprecated as of 1.4.0, use the ``admins`` group instead.
|
||||
* - ``apikey``
|
||||
- 0..1
|
||||
- string
|
||||
- The user's personal API key
|
||||
* - ``settings``
|
||||
- 1
|
||||
- object
|
||||
- The user's personal settings, might be an empty object.
|
||||
* - ``groups``
|
||||
- 1..n
|
||||
- List of string
|
||||
- Groups assigned to the user
|
||||
* - ``needs``
|
||||
- 1
|
||||
- :ref:`Needs object <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
|
||||
+15
-3
@@ -21,6 +21,8 @@ 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.
|
||||
@@ -250,6 +252,8 @@ Retrieve files from specific location
|
||||
|
||||
Returns a :ref:`Retrieve response <sec-api-fileops-datamodel-retrieveresponse>`.
|
||||
|
||||
Requires the ``FILES_LIST`` permission.
|
||||
|
||||
**Example**:
|
||||
|
||||
.. sourcecode:: http
|
||||
@@ -327,7 +331,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 user rights.
|
||||
Requires the ``FILES_UPLOAD`` permission.
|
||||
|
||||
**Example for uploading a file**
|
||||
|
||||
@@ -504,6 +508,8 @@ 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
|
||||
@@ -568,6 +574,8 @@ 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:
|
||||
@@ -598,6 +606,8 @@ Issue a file command
|
||||
Upon success, a status code of :http:statuscode:`202` and a :ref:`sec-api-datamodel-files-fileabridged` in the response
|
||||
body will be returned.
|
||||
|
||||
Requires the ``SLICE`` permission.
|
||||
|
||||
copy
|
||||
Copies the file or folder to a new ``destination`` on the same ``location``. Additional parameters are:
|
||||
|
||||
@@ -609,6 +619,8 @@ Issue a file command
|
||||
Upon success, a status code of :http:statuscode:`201` and a :ref:`sec-api-datamodel-files-fileabridged` in the response
|
||||
body will be returned.
|
||||
|
||||
Requires the ``FILES_UPLOAD`` permission.
|
||||
|
||||
move
|
||||
Moves the file or folder to a new ``destination`` on the same ``location``. Additional parameters are:
|
||||
|
||||
@@ -622,7 +634,7 @@ Issue a file command
|
||||
Upon success, a status code of :http:statuscode:`201` and a :ref:`sec-api-datamodel-files-fileabridged` in the response
|
||||
body will be returned.
|
||||
|
||||
Requires user rights.
|
||||
Requires the ``FILES_UPLOAD`` permission.
|
||||
|
||||
**Example Select Request**
|
||||
|
||||
@@ -773,7 +785,7 @@ Delete file
|
||||
|
||||
Returns a :http:statuscode:`204` after successful deletion.
|
||||
|
||||
Requires user rights.
|
||||
Requires the ``FILES_DELETE`` permission.
|
||||
|
||||
**Example Request**
|
||||
|
||||
|
||||
+56
-33
@@ -148,8 +148,14 @@ 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:`401` in
|
||||
case of a username/password mismatch or unknown user and a :http:statuscode:`403` in case of a deactivated account.
|
||||
login, whether active or passive. The active (username/password) login may also return a :http:statuscode:`403` in
|
||||
case of a username/password mismatch, unknown user or a deactivated account.
|
||||
|
||||
.. warning::
|
||||
|
||||
Previous versions of this API endpoint did return a :http:statuscode:`401` in case of a username/password
|
||||
mismatch or an unknown user. That was incompatible with basic authentication since it was a wrong use of
|
||||
the :http:statuscode:`401` code and got therefore changed as part of a bug fix.
|
||||
|
||||
:json passive: If present, performs a passive login only, returning information about the current user that's
|
||||
active either through an existing session or the used API key
|
||||
@@ -157,8 +163,7 @@ Login
|
||||
:json pass: (active login only) Password
|
||||
:json remember: (active login only) Whether to set a "remember me" cookie on the session
|
||||
:status 200: Successful login
|
||||
:status 401: Username/password mismatch or unknown user
|
||||
:status 403: Deactivated account
|
||||
:status 403: Username/password mismatch, unknown user or deactivated account
|
||||
|
||||
.. _sec-api-general-logout:
|
||||
|
||||
@@ -175,6 +180,20 @@ Logout
|
||||
|
||||
:status 204: No error
|
||||
|
||||
.. _sec-api-general-currentuser:
|
||||
|
||||
Current User
|
||||
============
|
||||
|
||||
.. http:get:: /api/currentuser
|
||||
|
||||
Retrieves information about the current user.
|
||||
|
||||
Will return a :http:statuscode:`200` with a :ref:`current user object <sec-api-general-datamodel-currentuser>`
|
||||
as body.
|
||||
|
||||
:status 200: No error
|
||||
|
||||
.. _sec-api-general-datamodel:
|
||||
|
||||
Data model
|
||||
@@ -185,6 +204,30 @@ 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
|
||||
@@ -196,32 +239,12 @@ Login response
|
||||
* - ``name``
|
||||
- 1
|
||||
- string
|
||||
- the user's name/id
|
||||
* - ``active``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether the user's account is active or not
|
||||
* - ``admin``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether the user has admin rights or not
|
||||
* - ``user``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether the user has user rights or not (always ``true``)
|
||||
* - ``apikey``
|
||||
- 1
|
||||
- string or None
|
||||
- The user's API key, if set
|
||||
* - ``settings``
|
||||
- 1
|
||||
- dict
|
||||
- The user's settings, if any
|
||||
* - ``session``
|
||||
- 1
|
||||
- string
|
||||
- The session key, can be used to authenticate with the ``auth`` message on the :ref:`push API <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.
|
||||
- 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
|
||||
+1
-2
@@ -9,7 +9,6 @@ REST API
|
||||
|
||||
general.rst
|
||||
version.rst
|
||||
apps.rst
|
||||
connection.rst
|
||||
files.rst
|
||||
job.rst
|
||||
@@ -21,7 +20,7 @@ REST API
|
||||
slicing.rst
|
||||
system.rst
|
||||
timelapse.rst
|
||||
users.rst
|
||||
access.rst
|
||||
util.rst
|
||||
wizard.rst
|
||||
push.rst
|
||||
|
||||
+3
-1
@@ -57,7 +57,7 @@ Issue a job command
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
Requires user rights.
|
||||
Requires the ``PRINT`` permission.
|
||||
|
||||
**Example Start Request**
|
||||
|
||||
@@ -180,6 +180,8 @@ Retrieve information about the current job
|
||||
|
||||
Returns a :http:statuscode:`200` with a :ref:`sec-api-job-datamodel-response` in the body.
|
||||
|
||||
Requires the ``STATUS`` permission.
|
||||
|
||||
**Example**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
@@ -6,7 +6,7 @@ Languages
|
||||
|
||||
.. note::
|
||||
|
||||
All language pack management operations require admin rights.
|
||||
All language pack management operations require the ``SETTINGS`` permission.
|
||||
|
||||
.. contents::
|
||||
|
||||
|
||||
+59
-11
@@ -80,6 +80,8 @@ 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.
|
||||
@@ -241,7 +243,7 @@ Issue a print head command
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
Requires user rights.
|
||||
Requires the ``CONTROL`` permission.
|
||||
|
||||
**Example Jog Request**
|
||||
|
||||
@@ -350,7 +352,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.
|
||||
tool's index starting with 0. A value of `0` will turn the heater off.
|
||||
|
||||
offset
|
||||
Sets the given temperature offset on the printer's tools. Additional parameters:
|
||||
@@ -380,7 +382,7 @@ Issue a tool command
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
Requires user rights.
|
||||
Requires the ``CONTROL`` permission.
|
||||
|
||||
**Example Target Temperature Request**
|
||||
|
||||
@@ -555,6 +557,8 @@ Retrieve the current tool state
|
||||
|
||||
Returns a :http:statuscode:`200` with a Temperature Response in the body upon success.
|
||||
|
||||
Requires the ``STATUS`` permission.
|
||||
|
||||
.. note::
|
||||
If you want both tool and bed temperature information at the same time, take a look at
|
||||
:ref:`Retrieve the current printer state <sec-api-printer-state>`.
|
||||
@@ -630,7 +634,7 @@ Issue a bed command
|
||||
target
|
||||
Sets the given target temperature on the printer's bed. Additional parameters:
|
||||
|
||||
* ``target``: Target temperature to set.
|
||||
* ``target``: Target temperature to set. A value of `0` will turn the heater off.
|
||||
|
||||
offset
|
||||
Sets the given temperature offset on the printer's bed. Additional parameters:
|
||||
@@ -645,7 +649,7 @@ Issue a bed command
|
||||
If no heated bed is configured for the currently selected printer profile, the resource will return
|
||||
an :http:statuscode:`409`.
|
||||
|
||||
Requires user rights.
|
||||
Requires the ``CONTROL`` permission.
|
||||
|
||||
**Example Target Temperature Request**
|
||||
|
||||
@@ -714,6 +718,8 @@ Retrieve the current bed state
|
||||
If no heated bed is configured for the currently selected printer profile, the resource will return
|
||||
an :http:statuscode:`409`.
|
||||
|
||||
Requires the ``STATUS`` permission.
|
||||
|
||||
.. note::
|
||||
If you want tool, bed and chamber temperature information at the same time, take a look at
|
||||
:ref:`Retrieve the current printer state <sec-api-printer-state>`.
|
||||
@@ -770,7 +776,7 @@ Retrieve the current bed state
|
||||
Issue a chamber command
|
||||
=======================
|
||||
|
||||
.. http:post:: /api/printer/bed
|
||||
.. http:post:: /api/printer/chamber
|
||||
|
||||
Chamber commands allow setting the temperature and temperature offsets for the printer's heated chamber. Available commands
|
||||
are:
|
||||
@@ -778,7 +784,7 @@ Issue a chamber command
|
||||
target
|
||||
Sets the given target temperature on the printer's chamber. Additional parameters:
|
||||
|
||||
* ``target``: Target temperature to set.
|
||||
* ``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:
|
||||
@@ -790,10 +796,10 @@ Issue a chamber command
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
If no heated chambed is configured for the currently selected printer profile, the resource will return
|
||||
If no heated chamber is configured for the currently selected printer profile, the resource will return
|
||||
an :http:statuscode:`409`.
|
||||
|
||||
Requires user rights.
|
||||
Requires the ``CONTROL`` permission.
|
||||
|
||||
**Example Target Temperature Request**
|
||||
|
||||
@@ -862,6 +868,8 @@ Retrieve the current chamber state
|
||||
If no heated chamber is configured for the currently selected printer profile, the resource will return
|
||||
an :http:statuscode:`409`.
|
||||
|
||||
Requires the ``STATUS`` permission.
|
||||
|
||||
.. note::
|
||||
If you want tool, bed and chamber temperature information at the same time, take a look at
|
||||
:ref:`Retrieve the current printer state <sec-api-printer-state>`.
|
||||
@@ -944,7 +952,7 @@ Issue an SD command
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
Requires user rights.
|
||||
Requires the ``CONTROL`` permission.
|
||||
|
||||
**Example Init Request**
|
||||
|
||||
@@ -1022,6 +1030,8 @@ Retrieve the current SD state
|
||||
Returns a :http:statuscode:`200` with an :ref:`SD State Response <sec-api-printer-datamodel-sdstate>` in the body
|
||||
upon success.
|
||||
|
||||
Requires the ``STATUS`` permission.
|
||||
|
||||
**Example**
|
||||
|
||||
Read the current state of the SD card.
|
||||
@@ -1058,7 +1068,7 @@ Send an arbitrary command to the printer
|
||||
|
||||
If successful returns a :http:statuscode:`204` and an empty body.
|
||||
|
||||
Requires user rights.
|
||||
Requires the ``CONTROL`` permission.
|
||||
|
||||
**Example for sending a single command**
|
||||
|
||||
@@ -1101,6 +1111,26 @@ Send an arbitrary command to the printer
|
||||
:json string commands: List of commands to send to the printer, mutually exclusive with ``command``.
|
||||
:statuscode 204: No error
|
||||
|
||||
.. _sec-api-printer-customcontrols:
|
||||
|
||||
Retrieve custom controls
|
||||
========================
|
||||
|
||||
.. http:get:: /api/printer/command/custom
|
||||
|
||||
Retrieves the :ref:`custom controls <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
|
||||
@@ -1211,3 +1241,21 @@ Arbitrary Command Request
|
||||
- 0..1
|
||||
- Map of key value pairs
|
||||
- (only if ``script`` is set) additional template variables to provide to the script renderer
|
||||
|
||||
.. _sec-api-printer-datamodel-customcontrols:
|
||||
|
||||
Custom Controls Response
|
||||
------------------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``controls``
|
||||
- 0..n
|
||||
- List of :ref:`custom controls <sec-features-custom_controls>`
|
||||
- A list of custom control definitions as defined in ``config.yaml``.
|
||||
@@ -21,6 +21,8 @@ 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
|
||||
@@ -124,6 +126,22 @@ Retrieve all printer profiles
|
||||
}
|
||||
|
||||
|
||||
.. _sec-api-printerprofiles-get:
|
||||
|
||||
Retrieve a single printer profile
|
||||
=================================
|
||||
|
||||
.. http:get:: /api/printerprofiles/(string:identifier)
|
||||
|
||||
Retrieves an existing single printer profile.
|
||||
|
||||
Returns a :http:statuscode:`200` with a :ref:`profile <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
|
||||
@@ -143,7 +161,7 @@ Add a new printer profile
|
||||
Returns a :http:statuscode:`200` with the saved profile as property ``profile``
|
||||
in the JSON body upon success.
|
||||
|
||||
Requires admin rights.
|
||||
Requires the ``SETTINGS`` permission.
|
||||
|
||||
**Example 1**
|
||||
|
||||
@@ -314,7 +332,7 @@ Update an existing printer profile
|
||||
Returns a :http:statuscode:`200` with the saved profile as property ``profile``
|
||||
in the JSON body upon success.
|
||||
|
||||
Requires admin rights.
|
||||
Requires the ``SETTINGS`` permission.
|
||||
|
||||
**Example**
|
||||
|
||||
@@ -400,7 +418,7 @@ Remove an existing printer profile
|
||||
|
||||
Returns a :http:statuscode:`204` an empty body upon success.
|
||||
|
||||
Requires admin rights.
|
||||
Requires the ``SETTINGS`` permission.
|
||||
|
||||
**Example**
|
||||
|
||||
|
||||
+5
-3
@@ -29,6 +29,9 @@ following message types are currently available for usage by 3rd party clients:
|
||||
|
||||
* ``connected``: Initial connection information, sent only right after establishing the socket connection. See
|
||||
:ref:`the payload data model <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.
|
||||
@@ -51,9 +54,8 @@ OctoPrint's SockJS socket also accepts two commands from the client to the serve
|
||||
|
||||
* ``auth`` (since 1.3.10): With the ``auth`` message, clients may associate an
|
||||
existing user session with the socket. That is of special importance to receive
|
||||
any kind of messages if the bundled :ref:`Forcelogin Plugin <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.
|
||||
any kind of messages, since the permission system will prevent any kind of status messages to be sent to connected
|
||||
clients lacking the ``STATUS`` permission.
|
||||
|
||||
The ``auth`` message expects the user id of the user to authenticate followed by ``:`` and a session key to be
|
||||
obtained from the successful payload of a :ref:`(passive or active) login via the API <sec-api-general-login>`.
|
||||
|
||||
@@ -21,6 +21,8 @@ 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
|
||||
@@ -36,7 +38,7 @@ Save settings
|
||||
|
||||
Returns the currently active settings on success, as part of a :http:statuscode:`200` response.
|
||||
|
||||
Requires admin rights.
|
||||
Requires the ``SETTINGS`` permission.
|
||||
|
||||
**Example**
|
||||
|
||||
|
||||
+62
-2
@@ -28,6 +28,8 @@ 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
|
||||
@@ -77,6 +79,8 @@ 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
|
||||
@@ -121,6 +125,8 @@ 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
|
||||
@@ -168,7 +174,7 @@ 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 admin rights.
|
||||
Requires the ``SETTINGS`` permission.
|
||||
|
||||
**Example**
|
||||
|
||||
@@ -206,6 +212,31 @@ Add Slicing Profile
|
||||
:statuscode 201: No error
|
||||
:statuscode 404: If the ``slicer`` was unknown to the system.
|
||||
|
||||
.. _sec-api-slicing-patch:
|
||||
|
||||
Update Slicing Profile
|
||||
======================
|
||||
|
||||
.. http:patch:: /api/slicing/(string:slicer)/profiles/(string:key)
|
||||
|
||||
Updates the slicing profile identified by ``key`` for the slicer ``slicer``.
|
||||
|
||||
Expects a :ref:`profile update request <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
|
||||
@@ -216,7 +247,7 @@ Delete Slicing Profile
|
||||
Delete the slicing profile identified by ``key`` for the slicer ``slicer``. If the profile doesn't exist, the
|
||||
request will succeed anyway.
|
||||
|
||||
Requires admin rights.
|
||||
Requires the ``SETTINGS`` permission.
|
||||
|
||||
:param slicer: The identifying key of the slicer for which to delete the profile
|
||||
:param key: The identifying key of the profile to delete
|
||||
@@ -340,3 +371,32 @@ Profile
|
||||
only the keys differing from the defaults when saving/updating a profile. The keys to be found in here a slicer
|
||||
specific. Will be left out for list responses.
|
||||
|
||||
.. _sec-api-slicing-datamodel-profileupdate:
|
||||
|
||||
Profile Update Request
|
||||
----------------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``data``
|
||||
- 0..1
|
||||
- Object
|
||||
- The profile data
|
||||
* - ``displayName``
|
||||
- 0..1
|
||||
- ``string``
|
||||
- The new display name for the profile
|
||||
* - ``description``
|
||||
- 0..1
|
||||
- ``string``
|
||||
- The new description for the profile
|
||||
* - ``default``
|
||||
- 0..1
|
||||
- ``boolean``
|
||||
- Whether to mark the profile as default for the slicer (true) or not (false)
|
||||
+3
-1
@@ -6,7 +6,7 @@ System
|
||||
|
||||
.. note::
|
||||
|
||||
All system operations require admin rights.
|
||||
All system operations require the ``SYSTEM`` permission.
|
||||
|
||||
.. _sec-api-system-command-list:
|
||||
|
||||
@@ -20,6 +20,8 @@ List all registered system commands
|
||||
A :http:statuscode:`200` with a :ref:`List all response <sec-api-system-commands-listall>`
|
||||
will be returned.
|
||||
|
||||
Requires the ``SYSTEM`` permission.
|
||||
|
||||
**Example**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
@@ -18,6 +18,8 @@ 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:
|
||||
@@ -29,7 +31,7 @@ Delete a timelapse
|
||||
|
||||
Delete the timelapse ``filename``.
|
||||
|
||||
Requires user rights.
|
||||
Requires the ``TIMELAPSE_DELETE`` permission.
|
||||
|
||||
.. _sec-api-timelapse-render:
|
||||
|
||||
@@ -41,7 +43,7 @@ Issue a command for an unrendered timelapse
|
||||
Current only supports to render the unrendered timelapse ``name`` via the
|
||||
``render`` command.
|
||||
|
||||
Requires user rights.
|
||||
Requires the ``TIMELAPSE_ADMIN`` permission.
|
||||
|
||||
:json command: The command to issue, currently only ``render`` is supported
|
||||
|
||||
@@ -54,7 +56,7 @@ Delete an unrendered timelapse
|
||||
|
||||
Delete the unrendered timelapse ``name``.
|
||||
|
||||
Requires user rights.
|
||||
Requires the ``TIMELAPSE_DELETE`` permission.
|
||||
|
||||
.. _sec-api-timelapse-saveconfig:
|
||||
|
||||
@@ -67,7 +69,7 @@ Change current timelapse config
|
||||
|
||||
The configuration is expected as the request body.
|
||||
|
||||
Requires user rights.
|
||||
Requires the ``TIMELAPSE_ADMIN`` permission.
|
||||
|
||||
.. _sec-api-timelapse-datamodel:
|
||||
|
||||
|
||||
+2
-307
@@ -4,311 +4,6 @@
|
||||
User
|
||||
****
|
||||
|
||||
.. contents::
|
||||
.. note::
|
||||
|
||||
.. _sec-api-users-list:
|
||||
|
||||
Retrieve a list of users
|
||||
========================
|
||||
|
||||
.. http:get:: /api/users
|
||||
|
||||
Retrieves a list of all registered users in OctoPrint.
|
||||
|
||||
Will return a :http:statuscode:`200` with a :ref:`user list response <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.
|
||||
This API endpoint has been moved and is now part of :ref:`Access Control <sec-api-access-users>`.
|
||||
+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 admin rights.
|
||||
Requires the ``ADMIN`` permission.
|
||||
|
||||
**Example 1**
|
||||
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ Wizard
|
||||
|
||||
.. note::
|
||||
|
||||
All wizard operations require either admin rights or the ``firstRun`` flag to be ``true``.
|
||||
All wizard operations require either the ``ADMIN`` permission or the ``firstRun`` flag to be ``true``.
|
||||
|
||||
.. contents::
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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 X
|
||||
The ZeroConf support allows OctoPrint to announce itself to Safari on macOS
|
||||
on the same network.
|
||||
|
||||
Linux users should install `Avahi <http://avahi.org>`_ and can then use one
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
.. _sec-bundledplugins-forcelogin:
|
||||
|
||||
ForceLogin Plugin
|
||||
=================
|
||||
|
||||
The ForceLogin Plugin comes bundled with OctoPrint (starting with version 1.3.10). It removes the anonymous
|
||||
read-only access that up until 1.3.10 was standard when accessing OctoPrint instances without being logged in and
|
||||
instead forces users to log in if they want to get any kind of information from OctoPrint.
|
||||
|
||||
.. _fig-bundledplugins-forcelogin:
|
||||
.. figure:: ../images/bundledplugins-forcelogin-dialog.png
|
||||
:align: center
|
||||
:alt: Forced login dialog
|
||||
|
||||
OctoPrint's new forced login dialog.
|
||||
|
||||
.. warning::
|
||||
|
||||
Keep in mind that **OctoPrint does not manage your webcam**, it merely embeds it. If you have a webcam,
|
||||
it will still be accessible to users who are not logged in under its (guessable) URL. If you need to restrict
|
||||
access to your webcam, you'll need to find a way to do so directly on the webcam server which - again -
|
||||
is not OctoPrint itself.
|
||||
|
||||
.. note::
|
||||
|
||||
If you want back the old behaviour of allowing anonymous read-only access to your OctoPrint instance, disable
|
||||
the ForceLogin Plugin in OctoPrint's plugin manager.
|
||||
|
||||
.. _sec-bundledplugins-forcelogin-sourcecode:
|
||||
|
||||
Source code
|
||||
-----------
|
||||
|
||||
The source of the ForceLogin plugin is bundled with OctoPrint and can be found in
|
||||
its source repository under ``src/octoprint/plugins/forcelogin``.
|
||||
@@ -14,8 +14,8 @@ Bundled Plugins
|
||||
backup.rst
|
||||
discovery.rst
|
||||
errortracking.rst
|
||||
forcelogin.rst
|
||||
logging.rst
|
||||
loginui.rst
|
||||
pluginmanager.rst
|
||||
printer_safety_check.rst
|
||||
softwareupdate.rst
|
||||
@@ -0,0 +1,66 @@
|
||||
.. _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``.
|
||||
@@ -196,6 +196,10 @@ 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:
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -290,6 +290,9 @@ 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:
|
||||
|
||||
@@ -425,8 +428,7 @@ 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!
|
||||
- "\x80"
|
||||
- "Marlin: Virtual Marlin!"
|
||||
- "SD card ok"
|
||||
|
||||
# Initial set of prepared oks to use instead of regular ok (e.g. to simulate
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -17,21 +17,30 @@ below.
|
||||
* `Python 3.7 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
|
||||
* `Git <https://git-scm.com>`_
|
||||
|
||||
* Checkout the OctoPrint sources from their Git repository:
|
||||
* Checkout the OctoPrint sources from their Git repository:
|
||||
|
||||
* ``git clone -b devel 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``
|
||||
|
||||
* 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)
|
||||
|
||||
* 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``
|
||||
|
||||
* 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:
|
||||
including its regular *and* development and plugin development dependencies:
|
||||
|
||||
* ``pip install -e .[develop,plugins]``
|
||||
|
||||
When the virtual environment is activated you can then:
|
||||
@@ -197,8 +206,10 @@ PyCharm
|
||||
.......
|
||||
|
||||
- "File" > "Open ...", select OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``)
|
||||
- "File" > "Settings ..." > "Project: OctoPrint" > "Project Interpreter" > "Add local ...", select OctoPrint venv
|
||||
- **(Linux, Windows)** "File" > "Settings ..." > "Project: OctoPrint" > "Project Interpreter" > "Add local ...", select OctoPrint venv
|
||||
folder (e.g. ``~/devel/OctoPrint/venv`` or ``C:\Devel\OctoPrint\venv``)
|
||||
- **(macOS)** "PyCharm" > "Preferences ..." > "Project: OctoPrint" > "Project Interpreter" > "Add ..." >
|
||||
"Virtualenv Environment > "Existing Environment", select OctoPrint venv folder (e.g. ``~/devel/OctoPrint/venv``)
|
||||
- Right click "src" in project tree, mark as source folder
|
||||
- Add Run/Debug Configuration, select "Python":
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
+49
-6
@@ -100,20 +100,44 @@ Shutdown
|
||||
The server is shutting down.
|
||||
|
||||
ClientOpened
|
||||
A client has connected to the web server.
|
||||
A client has connected to the push socket.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``remoteAddress``: the remote address (IP) of the client that connected
|
||||
* ``remoteAddress``: the remote address (IP) of the client that connected. On the push socket only available with
|
||||
a valid login session.
|
||||
|
||||
**Note:** Name changed in version 1.1.0
|
||||
|
||||
ClientClosed
|
||||
A client has disconnected from the webserver
|
||||
ClientAuthed
|
||||
A client has authenticated a user session on the push socket.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``remoteAddress``: the remote address (IP) of the client that disconnected
|
||||
* ``remoteAddress``: the remote address (IP) of the client that authed. On the push socket only available with a
|
||||
valid login session.
|
||||
* ``username``: the name of the user who authed. On the push socket only available with a valid login session.
|
||||
|
||||
ClientClosed
|
||||
A client has disconnected from the push socket.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``remoteAddress``: the remote address (IP) of the client that disconnected. On the push socket only available
|
||||
with a valid login session.
|
||||
|
||||
UserLoggedIn
|
||||
A user logged in. On the push socket only available with a valid login session with admin rights.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``username``: the name of the user who logged in
|
||||
|
||||
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
|
||||
|
||||
ConnectivityChanged
|
||||
The server's internet connectivity changed
|
||||
@@ -151,6 +175,9 @@ Error
|
||||
An unrecoverable error has been encountered, either as reported by the firmware (e.g. a thermal runaway) or
|
||||
on the connection.
|
||||
|
||||
Note that this event will not fire for error messages from the firmware that are handled (and as such recovered from)
|
||||
either by OctoPrint or a plugin.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``error``: the error string
|
||||
@@ -588,6 +615,7 @@ SlicingStarted
|
||||
|
||||
Payload:
|
||||
|
||||
* ``slicer``: the used slicer
|
||||
* ``stl``: the STL's filename
|
||||
* ``stl_location``: the STL's location
|
||||
* ``gcode``: the sliced GCODE's filename
|
||||
@@ -599,6 +627,7 @@ SlicingDone
|
||||
|
||||
Payload:
|
||||
|
||||
* ``slicer``: the used slicer
|
||||
* ``stl``: the STL's filename
|
||||
* ``stl_location``: the STL's location
|
||||
* ``gcode``: the sliced GCODE's filename
|
||||
@@ -611,6 +640,7 @@ SlicingCancelled
|
||||
|
||||
Payload:
|
||||
|
||||
* ``slicer``: the used slicer
|
||||
* ``stl``: the STL's filename
|
||||
* ``stl_location``: the STL's location
|
||||
* ``gcode``: the sliced GCODE's filename
|
||||
@@ -621,6 +651,7 @@ SlicingFailed
|
||||
|
||||
Payload:
|
||||
|
||||
* ``slicer``: the used slicer
|
||||
* ``stl``: the STL's filename
|
||||
* ``stl_location``: the STL's location
|
||||
* ``gcode``: the sliced GCODE's filename
|
||||
@@ -636,7 +667,7 @@ SlicingProfileAdded
|
||||
* ``profile``: the profile that was added
|
||||
|
||||
SlicingProfileModified
|
||||
A new slicing profile was modified.
|
||||
A slicing profile was modified.
|
||||
|
||||
Payload:
|
||||
|
||||
@@ -661,3 +692,15 @@ SettingsUpdated
|
||||
|
||||
This event may also be triggered if calling code of :py:class:`octoprint.settings.Settings.save` or
|
||||
:py:class:`octoprint.plugin.PluginSettings.save` sets the ``trigger_event`` parameter to ``True``.
|
||||
|
||||
.. _sec-events-available_events-printer_profile:
|
||||
|
||||
Printer Profile
|
||||
---------------
|
||||
|
||||
PrinterProfileModified
|
||||
A printer profile was modified.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``identifier``: the identifier of the modified printer profile
|
||||
@@ -3,8 +3,20 @@
|
||||
Access Control
|
||||
==============
|
||||
|
||||
When Access Control is enabled, anonymous users (not logged in) will only see
|
||||
the read-only parts of the UI which are the following:
|
||||
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:
|
||||
|
||||
* printer state
|
||||
* available gcode files and stats (upload is disabled)
|
||||
@@ -16,8 +28,8 @@ the read-only parts of the UI which are the following:
|
||||
* any components provided through plugins which are enabled for anonymous
|
||||
users
|
||||
|
||||
Logged in users will get access to everything besides the Settings and System
|
||||
Commands, which are admin-only.
|
||||
Logged in users without admin flag will be allowed to access 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
|
||||
@@ -39,6 +51,29 @@ 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
|
||||
|
||||
+17
-10
@@ -5,19 +5,20 @@ 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 instead of
|
||||
OctoPrint itself.
|
||||
reported on OctoPrint's bug tracker were actually bugs with installed third party plugins or language
|
||||
packs 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 that are not bundled with OctoPrint, allowing to easier
|
||||
identify most cases where a third party plugin is the culprit of an observed issue.
|
||||
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.
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
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 plugins.
|
||||
ensure it really is an issue in OctoPrint itself and now caused by one of your installed third party additions.
|
||||
|
||||
.. _sec-features-safemode-how:
|
||||
|
||||
@@ -73,11 +74,17 @@ 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`` (Windows) and
|
||||
``~/Library/Application Support/OctoPrint`` (MacOS).
|
||||
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).
|
||||
* 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: 38 KiB After Width: | Height: | Size: 58 KiB |
@@ -42,7 +42,7 @@
|
||||
To register for all message types, provide ``*`` as the type to register for.
|
||||
|
||||
``handler`` is expected to be a function accepting one object parameter ``eventObj``, consisting
|
||||
of the received message as property ``key`` and the received payload (if any) as property ``data``.
|
||||
of the received message as property ``event`` and the received payload (if any) as property ``data``.
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
|
||||
@@ -60,6 +60,7 @@ We'll start at the most basic form a plugin can take - just a few simple lines o
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_version__ = "1.0.0"
|
||||
__plugin_description__ = "A quick \"Hello World\" example plugin for OctoPrint"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
|
||||
Saving this as ``helloworld.py`` in ``~/.octoprint/plugins`` yields you something resembling these log entries upon server startup::
|
||||
|
||||
@@ -75,7 +76,10 @@ Saving this as ``helloworld.py`` in ``~/.octoprint/plugins`` yields you somethin
|
||||
|
||||
OctoPrint found that plugin in the folder and took a look into it. The name and the version it displays in that log
|
||||
entry it got from the ``__plugin_name__`` and ``__plugin_version__`` lines. It also read the description from
|
||||
``__plugin_description__`` and stored it in an internal data structure, but we'll just ignore this for now.
|
||||
``__plugin_description__`` and stored it in an internal data structure, but we'll just ignore this for now. Additionally
|
||||
there is ``__plugin_pythoncompat__`` which tells OctoPrint here that your plugin can be run under any Python versions
|
||||
between 2.7 and 4. That is necessary so that your plugin will be loadable in OctoPrint instances running under either
|
||||
Python 2 or Python 3, and compatibility to both should be your goal.
|
||||
|
||||
.. _sec-plugins-gettingstarted-sayinghello:
|
||||
|
||||
@@ -86,7 +90,7 @@ Apart from being discovered by OctoPrint, our plugin does nothing yet. We want t
|
||||
"Hello World!" to the log upon server startup. Modify our ``helloworld.py`` like this:
|
||||
|
||||
.. code-block:: python
|
||||
:emphasize-lines: 4-8,13
|
||||
:emphasize-lines: 4-8,14
|
||||
:linenos:
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
@@ -101,6 +105,7 @@ Apart from being discovered by OctoPrint, our plugin does nothing yet. We want t
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_version__ = "1.0.0"
|
||||
__plugin_description__ = "A quick \"Hello World\" example plugin for OctoPrint"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
and restart OctoPrint. You now get this output in the log::
|
||||
@@ -284,7 +289,7 @@ of information now defined twice:
|
||||
|
||||
The nice thing about our plugin now being a proper Python package is that OctoPrint can and will access the metadata defined
|
||||
within ``setup.py``! So, we don't really need to define all this data twice. Remove ``__plugin_name__``, ``__plugin_version__``
|
||||
and ``__plugin_description__`` from ``__init__.py``:
|
||||
and ``__plugin_description__`` from ``__init__.py``, but leave ``__plugin_implementation__`` and ``__plugin_pythoncompat__``:
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
@@ -298,6 +303,7 @@ and ``__plugin_description__`` from ``__init__.py``:
|
||||
def on_after_startup(self):
|
||||
self._logger.info("Hello World!")
|
||||
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
and restart OctoPrint::
|
||||
@@ -324,6 +330,7 @@ Our "Hello World" Plugin still gets detected fine, but it's now listed under the
|
||||
self._logger.info("Hello World!")
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
|
||||
@@ -373,6 +380,7 @@ add the :class:`TemplatePlugin` to our ``HelloWorldPlugin`` class:
|
||||
self._logger.info("Hello World!")
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
Next, we'll create a sub folder ``templates`` underneath our ``octoprint_helloworld`` folder, and within that a file
|
||||
@@ -443,6 +451,7 @@ Let's take a look at how all that would look in our plugin's ``__init__.py``:
|
||||
return dict(url="https://en.wikipedia.org/wiki/Hello_world")
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
Restart OctoPrint. You should see something like this::
|
||||
@@ -480,6 +489,7 @@ Adjust your plugin's ``__init__.py`` like this:
|
||||
return dict(url=self._settings.get(["url"]))
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
Also adjust your plugin's ``templates/helloworld_navbar.jinja2`` like this:
|
||||
@@ -590,6 +600,7 @@ again since we don't use that anymore:
|
||||
]
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
Restart OctoPrint and shift-reload your browser. Your link in the navigation bar should still point to the URL we
|
||||
@@ -693,6 +704,7 @@ like so:
|
||||
)
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
Note how we did not add another entry to the return value of :func:`~octoprint.plugin.TemplatePlugin.get_template_configs`.
|
||||
@@ -875,6 +887,7 @@ a reference to our CSS file:
|
||||
)
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
OctoPrint by default bundles all CSS, JavaScript and LESS files to reduce the amount of requests necessary to fully
|
||||
@@ -961,6 +974,7 @@ Then adjust our returned assets to include our LESS file as well:
|
||||
)
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
|
||||
|
||||
+112
-42
@@ -200,6 +200,94 @@ Available plugin hooks
|
||||
.. contents::
|
||||
:local:
|
||||
|
||||
.. _sec-plugins-hook-permissions:
|
||||
|
||||
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
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: user_manager_factory_hook(components, settings, *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.
|
||||
|
||||
The provided ``components`` is a dictionary containing the already initialized system components:
|
||||
|
||||
* ``plugin_manager``: The :class:`~octoprint.plugin.core.PluginManager`
|
||||
* ``printer_profile_manager``: The :class:`~octoprint.printer.profile.PrinterProfileManager`
|
||||
* ``event_bus``: The :class:`~octoprint.events.EventManager`
|
||||
* ``analysis_queue``: The :class:`~octoprint.filemanager.analysis.AnalysisQueue`
|
||||
* ``slicing_manager``: The :class:`~octoprint.slicing.SlicingManager`
|
||||
* ``file_manager``: The :class:`~octoprint.filemanager.FileManager`
|
||||
* ``plugin_lifecycle_manager``: The :class:`~octoprint.server.LifecycleManager`
|
||||
* ``preemptive_cache``: The :class:`~octoprint.server.util.flask.PreemptiveCache`
|
||||
|
||||
If the factory returns anything but ``None``, it will be assigned to the global ``userManager`` instance.
|
||||
|
||||
If none of the registered factories return a user manager instance, the class referenced by the ``config.yaml``
|
||||
entry ``accessControl.userManager`` will be initialized if possible, otherwise a stock
|
||||
:class:`~octoprint.access.users.FilebasedUserManager` will be instantiated, linked to the default user storage
|
||||
file ``~/.octoprint/users.yaml``.
|
||||
|
||||
:param dict components: System components to use for user manager instance initialization
|
||||
:param SettingsManager settings: The global settings manager instance to fetch configuration values from if necessary
|
||||
:return: The ``userManager`` instance to use globally.
|
||||
:rtype: UserManager subclass or None
|
||||
|
||||
|
||||
.. _sec-plugins-hook-accesscontrol-keyvalidator:
|
||||
|
||||
octoprint.accesscontrol.keyvalidator
|
||||
@@ -1014,6 +1102,27 @@ 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
|
||||
@@ -1185,8 +1294,7 @@ 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. See the bundled "Force Login" plugin for a
|
||||
usage example.
|
||||
Your plugin might need this to further restrict access to API methods.
|
||||
|
||||
.. important::
|
||||
|
||||
@@ -1201,8 +1309,7 @@ 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. See the bundled "Force Login" plugin for a
|
||||
usage example.
|
||||
Your plugin might need this to further restrict access to API methods.
|
||||
|
||||
.. important::
|
||||
|
||||
@@ -1217,8 +1324,7 @@ 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. See the bundled
|
||||
"Force Login" plugin for a usage example.
|
||||
Your plugin might need to this to restrict acccess to downloads and webcam snapshots further.
|
||||
|
||||
.. important::
|
||||
|
||||
@@ -1342,8 +1448,6 @@ octoprint.server.sockjs.authed
|
||||
|
||||
Allows plugins to be notified that a user got authenticated or deauthenticated on the socket (e.g. due to logout).
|
||||
|
||||
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
|
||||
|
||||
: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
|
||||
|
||||
@@ -1525,40 +1629,6 @@ octoprint.ui.web.templatetypes
|
||||
:return: a list of 3-tuples (template type, rule, sorting spec)
|
||||
:rtype: list
|
||||
|
||||
.. _sec-plugins-hook-users-factory:
|
||||
|
||||
octoprint.access.users.factory
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: user_manager_factory_hook(components, settings, *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.
|
||||
|
||||
The provided ``components`` is a dictionary containing the already initialized system components:
|
||||
|
||||
* ``plugin_manager``: The :class:`~octoprint.plugin.core.PluginManager`
|
||||
* ``printer_profile_manager``: The :class:`~octoprint.printer.profile.PrinterProfileManager`
|
||||
* ``event_bus``: The :class:`~octoprint.events.EventManager`
|
||||
* ``analysis_queue``: The :class:`~octoprint.filemanager.analysis.AnalysisQueue`
|
||||
* ``slicing_manager``: The :class:`~octoprint.slicing.SlicingManager`
|
||||
* ``file_manager``: The :class:`~octoprint.filemanager.FileManager`
|
||||
* ``plugin_lifecycle_manager``: The :class:`~octoprint.server.LifecycleManager`
|
||||
* ``preemptive_cache``: The :class:`~octoprint.server.util.flask.PreemptiveCache`
|
||||
|
||||
If the factory returns anything but ``None``, it will be assigned to the global ``userManager`` instance.
|
||||
|
||||
If none of the registered factories return a user manager instance, the class referenced by the ``config.yaml``
|
||||
entry ``accessControl.userManager`` will be initialized if possible, otherwise a stock
|
||||
:class:`~octoprint.access.users.FilebasedUserManager` will be instantiated, linked to the default user storage
|
||||
file ``~/.octoprint/users.yaml``.
|
||||
|
||||
:param dict components: System components to use for user manager instance initialization
|
||||
:param SettingsManager settings: The global settings manager instance to fetch configuration values from if necessary
|
||||
:return: The ``userManager`` instance to use globally.
|
||||
:rtype: UserManager subclass or None
|
||||
|
||||
|
||||
.. _sec-plugins-hook-timelapse-capture-pre:
|
||||
|
||||
octoprint.timelapse.capture.pre
|
||||
|
||||
@@ -166,7 +166,7 @@ Now, the execution order of the ``on_after_startup`` method will be determined b
|
||||
|
||||
This will result in the following messages to be generated:
|
||||
|
||||
.. code-block:: plain
|
||||
.. code-block:: none
|
||||
|
||||
Plugin B starting up
|
||||
Plugin C starting up
|
||||
|
||||
@@ -11,7 +11,7 @@ import requests
|
||||
from contextlib import closing
|
||||
|
||||
from sphinx.directives.code import LiteralIncludeReader, LiteralInclude, dedent_lines, \
|
||||
nodes, set_source_info, parselinenos, logger, container_wrapper
|
||||
nodes, parselinenos, logger, container_wrapper
|
||||
|
||||
if False:
|
||||
# For type annotation
|
||||
@@ -39,11 +39,10 @@ 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):
|
||||
@@ -69,7 +68,7 @@ class OnlineIncludeDirective(LiteralInclude):
|
||||
text, lines = reader.read(location=location)
|
||||
|
||||
retnode = nodes.literal_block(text, text, source=url)
|
||||
set_source_info(self, retnode)
|
||||
self.set_source_info(retnode)
|
||||
if self.options.get('diff'): # if diff is set, set udiff
|
||||
retnode['language'] = 'udiff'
|
||||
elif 'language' in self.options:
|
||||
|
||||
+1
-1
@@ -13,5 +13,5 @@ octoprint.init => /etc/init.d/octoprint
|
||||
## systemd
|
||||
|
||||
```
|
||||
octoprint.service => /etc/systemd/service/octoprint.service
|
||||
octoprint.service => /etc/systemd/system/octoprint.service
|
||||
```
|
||||
@@ -17,6 +17,11 @@ import setuptools
|
||||
# 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",
|
||||
]
|
||||
|
||||
# Requirements for our application
|
||||
INSTALL_REQUIRES = [
|
||||
# the following dependencies are non trivial to update since later versions introduce backwards incompatible
|
||||
@@ -27,18 +32,18 @@ INSTALL_REQUIRES = [
|
||||
# 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
|
||||
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
|
||||
|
||||
# anything below this should be checked on releases for new versions
|
||||
|
||||
"Flask-Login>=0.4.1,<0.5",
|
||||
"Flask-Principal>=0.4,<0.5",
|
||||
"Flask-Babel>=0.12,<0.13",
|
||||
"Flask-Assets>=0.12,<0.13",
|
||||
"werkzeug>=0.15.1,<0.16",
|
||||
"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.0,<3.1",
|
||||
"markdown>=3.1,<3.2",
|
||||
"pyserial>=3.4,<3.5",
|
||||
"netaddr>=0.7.19,<0.8",
|
||||
"watchdog>=0.9.0,<0.10",
|
||||
@@ -47,41 +52,42 @@ INSTALL_REQUIRES = [
|
||||
"pylru>=1.2,<1.3",
|
||||
"rsa>=4.0,<5",
|
||||
"pkginfo>=1.5.0.1,<1.6",
|
||||
"requests>=2.21.0,<3",
|
||||
"semantic_version>=2.6,<2.7",
|
||||
"psutil>=5.6.1,<5.7",
|
||||
"requests>=2.22.0,<3",
|
||||
"semantic_version>=2.8,<2.9",
|
||||
"psutil>=5.6.5,<5.7",
|
||||
"Click>=7,<8",
|
||||
"awesome-slugify>=1.6.5,<1.7",
|
||||
"feedparser>=5.2.1,<5.3",
|
||||
"future>=0.17,<0.18",
|
||||
"future>=0.18.2,<0.19",
|
||||
"websocket-client>=0.56,<0.57",
|
||||
"wrapt>=1.11.1,<1.12",
|
||||
"emoji>=0.5.1,<0.6",
|
||||
"wrapt>=1.11.2,<1.12",
|
||||
"emoji>=0.5.4,<0.6",
|
||||
"frozendict>=1.2,<1.3",
|
||||
"sentry-sdk==0.7.7"
|
||||
"sentry-sdk==0.13.2",
|
||||
"filetype>=1.0.5,<2"
|
||||
]
|
||||
|
||||
# Python 2 specific requirements
|
||||
INSTALL_REQUIRES_PYTHON2 = [
|
||||
"futures>=3.2,<3.3",
|
||||
"futures>=3.3,<3.4",
|
||||
"monotonic>=1.5,<1.6",
|
||||
"scandir>=1.10,<1.11",
|
||||
"chainmap>=1.0.3,<1.1",
|
||||
"typing>=3.6.6,<4"
|
||||
"typing>=3.7.4.1,<4"
|
||||
]
|
||||
|
||||
# OSX specific requirements
|
||||
INSTALL_REQUIRES_OSX = [
|
||||
"appdirs>=1.4.0",
|
||||
"appdirs>=1.4.3",
|
||||
]
|
||||
|
||||
# Additional requirements for optional install options
|
||||
EXTRA_REQUIRES = dict(
|
||||
# Dependencies for developing OctoPrint
|
||||
develop=[
|
||||
# Testing dependencies
|
||||
"mock>=2.0.0,<3",
|
||||
"pytest>=4.2.1,<5.0",
|
||||
# Testing dependencies - SEE ALSO tox.ini
|
||||
"mock>=3.0.5,<4",
|
||||
"pytest==4.6.6",
|
||||
"pytest-doctest-custom>=1.0.0,<1.1",
|
||||
"ddt",
|
||||
|
||||
@@ -89,10 +95,11 @@ EXTRA_REQUIRES = dict(
|
||||
"flake8",
|
||||
|
||||
# Documentation dependencies
|
||||
"sphinx>=1.6,<1.7",
|
||||
"sphinx>=1.8.5,<2",
|
||||
"sphinxcontrib-httpdomain",
|
||||
"sphinxcontrib-mermaid>=0.3",
|
||||
"sphinxcontrib-mermaid>=0.3.1",
|
||||
"sphinx_rtd_theme",
|
||||
"readthedocs-sphinx-ext==0.5.17" # Later versions require Jinja >= 2.9
|
||||
],
|
||||
|
||||
# Dependencies for developing OctoPrint plugins
|
||||
@@ -131,14 +138,14 @@ def read_file_contents(path):
|
||||
with codecs.open(path, encoding="utf-8") as f:
|
||||
return f.read()
|
||||
|
||||
def data_copy_build_py_factory(files, baseclass):
|
||||
class data_copy_build_py(baseclass):
|
||||
def md_to_html_build_py_factory(files, baseclass):
|
||||
class md_to_html_build_py(baseclass):
|
||||
files = dict()
|
||||
|
||||
def run(self):
|
||||
import shutil
|
||||
print("RUNNING md_to_html_build_py")
|
||||
if not self.dry_run:
|
||||
for directory, files in self.__class__.files.items():
|
||||
for directory, files in self.files.items():
|
||||
target_dir = os.path.join(self.build_lib, directory)
|
||||
self.mkpath(target_dir)
|
||||
|
||||
@@ -146,16 +153,22 @@ def data_copy_build_py_factory(files, baseclass):
|
||||
if isinstance(entry, tuple):
|
||||
if len(entry) != 2:
|
||||
continue
|
||||
source, dest = entry
|
||||
source, dest = entry[0], os.path.join(target_dir, entry[1])
|
||||
else:
|
||||
source = dest = entry
|
||||
shutil.copy(source, os.path.join(target_dir, dest))
|
||||
source = entry
|
||||
dest = os.path.join(target_dir, source + ".html")
|
||||
|
||||
print("Rendering markdown from {} to {}".format(source, dest))
|
||||
|
||||
from markdown import markdownFromFile
|
||||
markdownFromFile(input=source,
|
||||
output=dest,
|
||||
encoding="utf-8")
|
||||
baseclass.run(self)
|
||||
|
||||
return type(data_copy_build_py)(data_copy_build_py.__name__,
|
||||
(data_copy_build_py,),
|
||||
dict(files=files))
|
||||
return type(md_to_html_build_py)(md_to_html_build_py.__name__,
|
||||
(md_to_html_build_py,),
|
||||
dict(files=files))
|
||||
|
||||
def get_cmdclass():
|
||||
cmdclass = versioneer.get_cmdclass()
|
||||
@@ -169,10 +182,9 @@ 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"] = data_copy_build_py_factory({
|
||||
cmdclass["build_py"] = md_to_html_build_py_factory({
|
||||
"octoprint/templates/_data": [
|
||||
"AUTHORS.md",
|
||||
"CHANGELOG.md",
|
||||
"SUPPORTERS.md",
|
||||
"THIRDPARTYLICENSES.md",
|
||||
]
|
||||
@@ -191,6 +203,7 @@ 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
|
||||
@@ -215,6 +228,7 @@ def params():
|
||||
"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",
|
||||
|
||||
+10
-40
@@ -233,12 +233,6 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
|
||||
},
|
||||
"serial": {
|
||||
"format": "%(asctime)s - %(message)s"
|
||||
},
|
||||
"communication": {
|
||||
"format": "%(asctime)s - %(name)s - %(message)s"
|
||||
},
|
||||
"commdebug": {
|
||||
"format": "%(asctime)s - %(threadName)s - %(message)s"
|
||||
}
|
||||
},
|
||||
"handlers": {
|
||||
@@ -256,45 +250,19 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
|
||||
"backupCount": 6,
|
||||
"filename": os.path.join(settings.getBaseFolder("logs"), "octoprint.log")
|
||||
},
|
||||
"protocolFile": {
|
||||
"class": "octoprint.logging.handlers.CommunicationLogHandler",
|
||||
"serialFile": {
|
||||
"class": "octoprint.logging.handlers.SerialLogHandler",
|
||||
"level": "DEBUG",
|
||||
"formatter": "communication",
|
||||
"formatter": "serial",
|
||||
"backupCount": 3,
|
||||
"filename": os.path.join(settings.getBaseFolder("logs"), "protocol.log"),
|
||||
"delay": True
|
||||
},
|
||||
"transportFile": {
|
||||
"class": "octoprint.logging.handlers.CommunicationLogHandler",
|
||||
"level": "DEBUG",
|
||||
"formatter": "communication",
|
||||
"backupCount": 3,
|
||||
"filename": os.path.join(settings.getBaseFolder("logs"), "transport.log"),
|
||||
"delay": True
|
||||
},
|
||||
"commDebugFile": {
|
||||
"class": "octoprint.logging.handlers.CommunicationLogHandler",
|
||||
"level": "DEBUG",
|
||||
"formatter": "commdebug",
|
||||
"backupCount": 3,
|
||||
"filename": os.path.join(settings.getBaseFolder("logs"), "commdebug.log"),
|
||||
"filename": os.path.join(settings.getBaseFolder("logs"), "serial.log"),
|
||||
"delay": True
|
||||
}
|
||||
},
|
||||
"loggers": {
|
||||
"PROTOCOL": {
|
||||
"level": "DEBUG",
|
||||
"handlers": ["protocolFile"],
|
||||
"propagate": False
|
||||
},
|
||||
"TRANSPORT": {
|
||||
"level": "DEBUG",
|
||||
"handlers": ["transportFile"],
|
||||
"propagate": False
|
||||
},
|
||||
"COMMDEBUG": {
|
||||
"level": "DEBUG",
|
||||
"handlers": ["commDebugFile"],
|
||||
"SERIAL": {
|
||||
"level": "INFO",
|
||||
"handlers": ["serialFile"],
|
||||
"propagate": False
|
||||
},
|
||||
"octoprint": {
|
||||
@@ -442,7 +410,9 @@ def init_pluginsystem(settings, safe_mode=False, ignore_blacklist=True, connecti
|
||||
if not startup:
|
||||
return
|
||||
|
||||
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]))
|
||||
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])))
|
||||
|
||||
disabled_list = pm.plugin_disabled_list
|
||||
already_processed = []
|
||||
|
||||
@@ -2,10 +2,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
#import sys
|
||||
#if sys.version_info[0] >= 3:
|
||||
# raise RuntimeError("Sorry, OctoPrint does not yet support Python 3")
|
||||
|
||||
if __name__ == "__main__":
|
||||
import octoprint
|
||||
octoprint.main()
|
||||
@@ -18,32 +18,7 @@ from octoprint.settings import settings
|
||||
from octoprint.util import atomic_write
|
||||
from octoprint.access import ADMIN_GROUP, USER_GROUP, GUEST_GROUP, READONLY_GROUP
|
||||
from octoprint.access.permissions import Permissions, OctoPrintPermission
|
||||
from flask_principal import Need, Permission
|
||||
|
||||
DEFAULT_ADMIN_PERMISSIONS = [Permissions.ADMIN]
|
||||
"""Default admin permissions are the legacy permissions from before 1.4.0"""
|
||||
|
||||
DEFAULT_USER_PERMISSIONS = [Permissions.STATUS,
|
||||
Permissions.CONNECTION,
|
||||
Permissions.WEBCAM,
|
||||
Permissions.FILES_UPLOAD,
|
||||
Permissions.FILES_DOWNLOAD,
|
||||
Permissions.FILES_DELETE,
|
||||
Permissions.FILES_SELECT,
|
||||
Permissions.PRINT,
|
||||
Permissions.MONITOR_TERMINAL,
|
||||
Permissions.CONTROL,
|
||||
Permissions.SLICE,
|
||||
Permissions.TIMELAPSE_LIST,
|
||||
Permissions.TIMELAPSE_ADMIN]
|
||||
"""Default user permissions are the legacy permissions from before 1.4.0"""
|
||||
|
||||
DEFAULT_GUEST_PERMISSIONS = [Permissions.STATUS,
|
||||
Permissions.WEBCAM,
|
||||
Permissions.FILES_DOWNLOAD,
|
||||
Permissions.TIMELAPSE_LIST,
|
||||
Permissions.MONITOR_TERMINAL]
|
||||
"""Default guest permissions are the legacy permissions from before 1.4.0"""
|
||||
from octoprint.vendor.flask_principal import Need, Permission
|
||||
|
||||
|
||||
GroupNeed = partial(Need, 'group')
|
||||
@@ -151,8 +126,8 @@ class GroupManager(object):
|
||||
return [group.key for group in groups]
|
||||
|
||||
def _to_groups(self, *groups):
|
||||
return filter(lambda x: x is not None,
|
||||
[self._to_group(g) for g in 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
|
||||
|
||||
@@ -8,7 +8,7 @@ __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms
|
||||
from future.utils import with_metaclass
|
||||
from flask import g, abort
|
||||
from flask_babel import gettext
|
||||
from flask_principal import Permission, PermissionDenied, RoleNeed, Need
|
||||
from octoprint.vendor.flask_principal import Permission, PermissionDenied, RoleNeed, Need
|
||||
|
||||
from functools import wraps
|
||||
from collections import OrderedDict, defaultdict
|
||||
@@ -79,6 +79,22 @@ class OctoPrintPermission(Permission):
|
||||
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.
|
||||
@@ -259,8 +275,9 @@ class Permissions(with_metaclass(PermissionsMetaClass)):
|
||||
default_groups=[ADMIN_GROUP])
|
||||
|
||||
STATUS = OctoPrintPermission("Status",
|
||||
gettext("Allows to gather status information, e.g. job progress, "
|
||||
"printer state, temperatures, ..."),
|
||||
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])
|
||||
|
||||
@@ -292,27 +309,26 @@ class Permissions(with_metaclass(PermissionsMetaClass)):
|
||||
FILES_DOWNLOAD = OctoPrintPermission("File Download",
|
||||
gettext("Allows users to download files. The GCODE viewer is "
|
||||
"affected by this as well."),
|
||||
RoleNeed("files_download"), FILES_LIST,
|
||||
RoleNeed("files_download"),
|
||||
default_groups=[USER_GROUP, READONLY_GROUP])
|
||||
FILES_DELETE = OctoPrintPermission("File Delete",
|
||||
gettext("Allows users to delete files"),
|
||||
RoleNeed("files_delete"), FILES_LIST,
|
||||
RoleNeed("files_delete"),
|
||||
default_groups=[USER_GROUP])
|
||||
FILES_SELECT = OctoPrintPermission("File Select",
|
||||
gettext("Allows to select a file for printing"),
|
||||
RoleNeed("files_select"), FILES_LIST,
|
||||
RoleNeed("files_select"),
|
||||
default_groups=[USER_GROUP])
|
||||
|
||||
PRINT = OctoPrintPermission("Print",
|
||||
gettext("Allows to start, pause and cancel a print job. Includes the \"Select\" "
|
||||
"permission"),
|
||||
RoleNeed("print"), FILES_SELECT,
|
||||
gettext("Allows to start, pause and cancel a print job"),
|
||||
RoleNeed("print"),
|
||||
default_groups=[USER_GROUP])
|
||||
|
||||
GCODE_VIEWER = OctoPrintPermission("GCODE viewer",
|
||||
gettext("Allows access to the GCODE viewer. Includes the \"File Download\""
|
||||
"permission."),
|
||||
RoleNeed("gcodeviewer"), FILES_DOWNLOAD,
|
||||
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",
|
||||
@@ -351,8 +367,13 @@ class Permissions(with_metaclass(PermissionsMetaClass)):
|
||||
RoleNeed("timelapse_admin"), TIMELAPSE_LIST, TIMELAPSE_DOWNLOAD,
|
||||
default_groups=[USER_GROUP])
|
||||
|
||||
SETTINGS = OctoPrintPermission("Settings",
|
||||
gettext("Allows to manage settings"),
|
||||
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)
|
||||
|
||||
|
||||
@@ -19,15 +19,18 @@ import logging
|
||||
# noinspection PyCompatibility
|
||||
from builtins import range, bytes
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import atomic_write, to_bytes, deprecated, monotonic_time
|
||||
from octoprint.settings import settings as s
|
||||
|
||||
from octoprint.util import atomic_write, to_bytes, deprecated, monotonic_time, generate_api_key
|
||||
from octoprint.util import get_fully_qualified_classname as fqcn
|
||||
|
||||
from octoprint.access.permissions import Permissions, OctoPrintPermission
|
||||
from octoprint.access.groups import GroupChangeListener, Group
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
class UserManager(GroupChangeListener, object):
|
||||
def __init__(self, group_manager):
|
||||
def __init__(self, group_manager, settings=None):
|
||||
self._group_manager = group_manager
|
||||
self._group_manager.register_listener(self)
|
||||
|
||||
@@ -36,6 +39,10 @@ class UserManager(GroupChangeListener, object):
|
||||
self._sessionids_by_userid = dict()
|
||||
self._enabled = True
|
||||
|
||||
if settings is None:
|
||||
settings = s()
|
||||
self._settings = settings
|
||||
|
||||
self._login_status_listeners = []
|
||||
|
||||
def register_login_status_listener(self, listener):
|
||||
@@ -48,7 +55,10 @@ class UserManager(GroupChangeListener, object):
|
||||
if self.enabled:
|
||||
return AnonymousUser([self._group_manager.guest_group])
|
||||
else:
|
||||
return AdminUser([self._group_manager.admin_group])
|
||||
return AdminUser([self._group_manager.admin_group, self._group_manager.user_group])
|
||||
|
||||
def api_user_factory(self):
|
||||
return ApiUser([self._group_manager.admin_group, self._group_manager.user_group])
|
||||
|
||||
@property
|
||||
def enabled(self):
|
||||
@@ -92,14 +102,15 @@ class UserManager(GroupChangeListener, object):
|
||||
try:
|
||||
listener.on_user_logged_in(user)
|
||||
except Exception:
|
||||
self._logger.exception("Error in on_user_logged_in on {!r}".format(listener))
|
||||
self._logger.exception("Error in on_user_logged_in on {!r}".format(listener),
|
||||
extra=dict(callback=fqcn(listener)))
|
||||
|
||||
self._logger.debug("Logged in user: %r" % user)
|
||||
self._logger.info("Logged in user: {}".format(user.get_id()))
|
||||
|
||||
return user
|
||||
|
||||
def logout_user(self, user):
|
||||
if user is None or user.is_anonymous:
|
||||
def logout_user(self, user, stale=False):
|
||||
if user is None or user.is_anonymous or isinstance(user, AdminUser):
|
||||
return
|
||||
|
||||
if isinstance(user, LocalProxy):
|
||||
@@ -118,34 +129,41 @@ class UserManager(GroupChangeListener, object):
|
||||
pass
|
||||
|
||||
if sessionid in self._session_users_by_session:
|
||||
del self._session_users_by_session[sessionid]
|
||||
try:
|
||||
del self._session_users_by_session[sessionid]
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
for listener in self._login_status_listeners:
|
||||
try:
|
||||
listener.on_user_logged_out(user)
|
||||
listener.on_user_logged_out(user, stale=stale)
|
||||
except Exception:
|
||||
self._logger.exception("Error in on_user_logged_out on {!r}".format(listener))
|
||||
self._logger.exception("Error in on_user_logged_out on {!r}".format(listener),
|
||||
extra=dict(callback=fqcn(listener)))
|
||||
|
||||
self._logger.debug("Logged out user: %r" % user)
|
||||
self._logger.info("Logged out user: {}".format(user.get_id()))
|
||||
|
||||
def _cleanup_sessions(self):
|
||||
for session, user in self._session_users_by_session.items():
|
||||
for session, user in list(self._session_users_by_session.items()):
|
||||
if not isinstance(user, SessionUser):
|
||||
continue
|
||||
if user.created + (24 * 60 * 60) < monotonic_time():
|
||||
self.logout_user(user)
|
||||
self._logger.info("Cleaning up user session {} for user {}".format(session, user.get_id()))
|
||||
self.logout_user(user, stale=True)
|
||||
|
||||
@staticmethod
|
||||
def create_password_hash(password, salt=None):
|
||||
def create_password_hash(password, salt=None, settings=None):
|
||||
if not salt:
|
||||
salt = settings().get(["accessControl", "salt"])
|
||||
if settings is None:
|
||||
settings = s()
|
||||
salt = settings.get(["accessControl", "salt"])
|
||||
if salt is None:
|
||||
import string
|
||||
from random import choice
|
||||
chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
|
||||
salt = "".join(choice(chars) for _ in range(32))
|
||||
settings().set(["accessControl", "salt"], salt)
|
||||
settings().save()
|
||||
settings.set(["accessControl", "salt"], salt)
|
||||
settings.save()
|
||||
|
||||
return hashlib.sha512(to_bytes(password, encoding="utf-8", errors="replace") + to_bytes(salt)).hexdigest()
|
||||
|
||||
@@ -154,13 +172,16 @@ class UserManager(GroupChangeListener, object):
|
||||
if not user:
|
||||
return False
|
||||
|
||||
hash = UserManager.create_password_hash(password)
|
||||
hash = UserManager.create_password_hash(password,
|
||||
settings=self._settings)
|
||||
if user.check_password(hash):
|
||||
# new hash matches, correct password
|
||||
return True
|
||||
else:
|
||||
# new hash doesn't match, but maybe the old one does, so check that!
|
||||
oldHash = UserManager.create_password_hash(password, salt="mvBUTvwzBzD3yPwvnJ4E4tXNf3CGJvvW")
|
||||
oldHash = UserManager.create_password_hash(password,
|
||||
salt="mvBUTvwzBzD3yPwvnJ4E4tXNf3CGJvvW",
|
||||
settings=self._settings)
|
||||
if user.check_password(oldHash):
|
||||
# old hash matches, we migrate the stored password hash to the new one and return True since it's the correct password
|
||||
self.change_user_password(username, password)
|
||||
@@ -261,7 +282,8 @@ class UserManager(GroupChangeListener, object):
|
||||
for user in users:
|
||||
listener.on_user_modified(user)
|
||||
except Exception:
|
||||
self._logger.exception("Error in on_user_modified on {!r}".format(listener))
|
||||
self._logger.exception("Error in on_user_modified on {!r}".format(listener),
|
||||
extra=dict(callback=fqcn(listener)))
|
||||
|
||||
def on_group_subgroups_changed(self, group, added=None, removed=None):
|
||||
users = self.find_sessions_for(lambda u: group in u.groups)
|
||||
@@ -271,7 +293,8 @@ class UserManager(GroupChangeListener, object):
|
||||
for user in users:
|
||||
listener.on_user_modified(user)
|
||||
except Exception:
|
||||
self._logger.exception("Error in on_user_modified on {!r}".format(listener))
|
||||
self._logger.exception("Error in on_user_modified on {!r}".format(listener),
|
||||
extra=dict(callback=fqcn(listener)))
|
||||
|
||||
def _trigger_on_user_modified(self, user):
|
||||
if isinstance(user, basestring):
|
||||
@@ -300,14 +323,16 @@ class UserManager(GroupChangeListener, object):
|
||||
for user in users:
|
||||
listener.on_user_modified(user)
|
||||
except Exception:
|
||||
self._logger.exception("Error in on_user_modified on {!r}".format(listener))
|
||||
self._logger.exception("Error in on_user_modified on {!r}".format(listener),
|
||||
extra=dict(callback=fqcn(listener)))
|
||||
|
||||
def _trigger_on_user_removed(self, username):
|
||||
for listener in self._login_status_listeners:
|
||||
try:
|
||||
listener.on_user_removed(username)
|
||||
except Exception:
|
||||
self._logger.exception("Error in on_user_removed on {!r}".format(listener))
|
||||
self._logger.exception("Error in on_user_removed on {!r}".format(listener),
|
||||
extra=dict(callback=fqcn(listener)))
|
||||
|
||||
#~~ Deprecated methods follow
|
||||
|
||||
@@ -415,7 +440,7 @@ class LoginStatusListener(object):
|
||||
def on_user_logged_in(self, user):
|
||||
pass
|
||||
|
||||
def on_user_logged_out(self, user):
|
||||
def on_user_logged_out(self, user, stale=False):
|
||||
pass
|
||||
|
||||
def on_user_modified(self, user):
|
||||
@@ -428,13 +453,13 @@ class LoginStatusListener(object):
|
||||
##~~ FilebasedUserManager, takes available users from users.yaml file
|
||||
|
||||
class FilebasedUserManager(UserManager):
|
||||
def __init__(self, group_manager, path=None):
|
||||
UserManager.__init__(self, group_manager)
|
||||
def __init__(self, group_manager, path=None, settings=None):
|
||||
UserManager.__init__(self, group_manager, settings=settings)
|
||||
|
||||
if path is None:
|
||||
path = settings().get(["accessControl", "userfile"])
|
||||
path = self._settings.get(["accessControl", "userfile"])
|
||||
if path is None:
|
||||
path = os.path.join(settings().getBaseFolder("base"), "users.yaml")
|
||||
path = os.path.join(s().getBaseFolder("base"), "users.yaml")
|
||||
|
||||
self._userfile = path
|
||||
|
||||
@@ -537,7 +562,13 @@ class FilebasedUserManager(UserManager):
|
||||
if username in self._users and not overwrite:
|
||||
raise UserAlreadyExists(username)
|
||||
|
||||
self._users[username] = User(username, UserManager.create_password_hash(password), active, permissions, groups, apikey=apikey)
|
||||
self._users[username] = User(username,
|
||||
UserManager.create_password_hash(password,
|
||||
settings=self._settings),
|
||||
active,
|
||||
permissions,
|
||||
groups,
|
||||
apikey=apikey)
|
||||
self._dirty = True
|
||||
self._save()
|
||||
|
||||
@@ -670,7 +701,8 @@ class FilebasedUserManager(UserManager):
|
||||
if not username in self._users:
|
||||
raise UnknownUser(username)
|
||||
|
||||
passwordHash = UserManager.create_password_hash(password)
|
||||
passwordHash = UserManager.create_password_hash(password,
|
||||
settings=self._settings)
|
||||
user = self._users[username]
|
||||
if user._passwordHash != passwordHash:
|
||||
user._passwordHash = passwordHash
|
||||
@@ -718,7 +750,7 @@ class FilebasedUserManager(UserManager):
|
||||
raise UnknownUser(username)
|
||||
|
||||
user = self._users[username]
|
||||
user._apikey = ''.join('%02X' % z for z in bytes(uuid.uuid4().bytes))
|
||||
user._apikey = generate_api_key()
|
||||
self._dirty = True
|
||||
self._save()
|
||||
return user._apikey
|
||||
@@ -1097,6 +1129,12 @@ class User(UserMixin):
|
||||
def groups(self):
|
||||
return list(self._groups)
|
||||
|
||||
@property
|
||||
def effective_permissions(self):
|
||||
if self._permissions is None:
|
||||
return []
|
||||
return list(filter(lambda p: p is not None and self.has_permission(p), Permissions.all()))
|
||||
|
||||
@property
|
||||
def needs(self):
|
||||
needs = set()
|
||||
@@ -1115,8 +1153,6 @@ class User(UserMixin):
|
||||
return self.has_needs(*permission.needs)
|
||||
|
||||
def has_needs(self, *needs):
|
||||
if Permissions.ADMIN in self._permissions:
|
||||
return True
|
||||
return set(needs).issubset(self.needs)
|
||||
|
||||
def __repr__(self):
|
||||
|
||||
@@ -138,9 +138,10 @@ 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])
|
||||
sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands, analysis_commands, user_commands])
|
||||
@standard_options()
|
||||
@legacy_options
|
||||
@click.version_option(version=octoprint.__version__, allow_from_autoenv=False)
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
# 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", [])))
|
||||
@@ -1,7 +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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
@@ -1,215 +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 logging
|
||||
import os
|
||||
import io
|
||||
|
||||
try:
|
||||
from os import scandir
|
||||
except ImportError:
|
||||
from scandir import scandir
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import is_hidden_path
|
||||
|
||||
|
||||
class ConnectionProfile(object):
|
||||
|
||||
def __init__(self, id, name=None, printer_profile=None, protocol=None, protocol_parameters=None, transport=None, transport_parameters=None, **kwargs):
|
||||
self.id = id
|
||||
self.name = name if name is not None else id
|
||||
self.printer_profile = printer_profile
|
||||
self.protocol = protocol
|
||||
self.protocol_parameters = protocol_parameters
|
||||
self.transport = transport
|
||||
self.transport_parameters = transport_parameters
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data):
|
||||
identifier = data.pop("id")
|
||||
return ConnectionProfile(identifier, **data)
|
||||
|
||||
def as_dict(self):
|
||||
return dict(id=self.id,
|
||||
name=self.name,
|
||||
printer_profile=self.printer_profile,
|
||||
protocol=self.protocol,
|
||||
protocol_parameters=self.protocol_parameters,
|
||||
transport=self.transport,
|
||||
transport_parameters=self.transport_parameters)
|
||||
|
||||
|
||||
class ConnectionProfileManager(object):
|
||||
|
||||
@classmethod
|
||||
def to_profile(cls, data):
|
||||
return ConnectionProfile.from_dict(data)
|
||||
|
||||
def __init__(self):
|
||||
self._current = None
|
||||
self._folder = settings().getBaseFolder("connectionProfiles")
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
def select(self, identifier):
|
||||
self._current = self.get(identifier)
|
||||
if self._current is None:
|
||||
self._logger.error("Profile {} is invalid, cannot select".format(identifier))
|
||||
return False
|
||||
return True
|
||||
|
||||
def deselect(self):
|
||||
self._current = None
|
||||
|
||||
@property
|
||||
def current(self):
|
||||
return self._current
|
||||
|
||||
def get_all(self):
|
||||
return self._load_all()
|
||||
|
||||
def get(self, identifier):
|
||||
try:
|
||||
if self.exists(identifier):
|
||||
return self._load_from_path(self._get_profile_path(identifier))
|
||||
else:
|
||||
return None
|
||||
except InvalidProfileError:
|
||||
return None
|
||||
|
||||
def remove(self, identifier):
|
||||
return self._remove_from_path(self._get_profile_path(identifier))
|
||||
|
||||
def save(self, profile, allow_overwrite=False, make_default=False):
|
||||
self._save_to_path(self._get_profile_path(profile.id),
|
||||
profile,
|
||||
allow_overwrite=allow_overwrite)
|
||||
|
||||
if make_default:
|
||||
self.set_default(profile.id)
|
||||
|
||||
return self.get(profile.id)
|
||||
|
||||
@property
|
||||
def profile_count(self):
|
||||
return len(self._load_all_identifiers())
|
||||
|
||||
@property
|
||||
def last_modified(self):
|
||||
dates = [os.stat(self._folder).st_mtime]
|
||||
dates += [entry.stat().st_mtime for entry in scandir(self._folder) if entry.name.endswith(".profile")]
|
||||
return max(dates)
|
||||
|
||||
def get_default(self):
|
||||
default = settings().get(["connectionProfiles", "default"])
|
||||
if default is not None and self.exists(default):
|
||||
profile = self.get(default)
|
||||
if profile is not None:
|
||||
return profile
|
||||
else:
|
||||
self._logger.warning("Default profile {} is invalid".format(default))
|
||||
|
||||
return None
|
||||
|
||||
def set_default(self, identifier):
|
||||
all_identifiers = self._load_all_identifiers()
|
||||
if identifier is not None and identifier not in all_identifiers:
|
||||
return
|
||||
|
||||
settings().set(["connectionProfiles", "default"], identifier)
|
||||
settings().save()
|
||||
|
||||
def get_current_or_default(self):
|
||||
if self._current is not None:
|
||||
return self._current
|
||||
else:
|
||||
return self.get_default()
|
||||
|
||||
def get_current(self):
|
||||
return self._current
|
||||
|
||||
def exists(self, identifier):
|
||||
if identifier is None:
|
||||
return False
|
||||
|
||||
path = self._get_profile_path(identifier)
|
||||
return os.path.exists(path) and os.path.isfile(path)
|
||||
|
||||
def _load_all(self):
|
||||
all_identifiers = self._load_all_identifiers()
|
||||
results = dict()
|
||||
for identifier, path in all_identifiers.items():
|
||||
try:
|
||||
profile = self._load_from_path(path)
|
||||
except InvalidProfileError:
|
||||
self._logger.warning("Profile {} is invalid, skipping".format(identifier))
|
||||
continue
|
||||
|
||||
if profile is None:
|
||||
continue
|
||||
|
||||
results[identifier] = profile
|
||||
return results
|
||||
|
||||
def _load_all_identifiers(self):
|
||||
results = dict()
|
||||
for entry in scandir(self._folder):
|
||||
if is_hidden_path(entry.name) or not entry.name.endswith(".profile"):
|
||||
continue
|
||||
|
||||
if not entry.is_file():
|
||||
continue
|
||||
|
||||
identifier = entry.name[:-len(".profile")]
|
||||
results[identifier] = entry.path
|
||||
return results
|
||||
|
||||
def _load_from_path(self, path):
|
||||
if not os.path.exists(path) or not os.path.isfile(path):
|
||||
return None
|
||||
|
||||
import yaml
|
||||
with io.open(path, 'rt', encoding='utf-8') as f:
|
||||
data = yaml.safe_load(f)
|
||||
|
||||
if data is None or not isinstance(data, dict):
|
||||
raise InvalidProfileError("Profile is None or not a dict")
|
||||
|
||||
return ConnectionProfile.from_dict(data)
|
||||
|
||||
def _save_to_path(self, path, profile, allow_overwrite=False):
|
||||
if os.path.exists(path) and not allow_overwrite:
|
||||
raise SaveError("Profile {} already exists and overwriting is not allowed".format(profile["id"]))
|
||||
|
||||
from octoprint.util import atomic_write
|
||||
import yaml
|
||||
try:
|
||||
with atomic_write(path, mode="wt", max_permissions=0o666) as f:
|
||||
yaml.safe_dump(profile.as_dict(), f,
|
||||
default_flow_style=False,
|
||||
indent=2,
|
||||
allow_unicode=True)
|
||||
except Exception as e:
|
||||
self._logger.exception("Error while trying to save profile {}".format(profile["id"]))
|
||||
raise SaveError("Cannot save profile {}: {}".format(profile["id"], e))
|
||||
|
||||
def _remove_from_path(self, path):
|
||||
try:
|
||||
os.remove(path)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def _get_profile_path(self, identifier):
|
||||
return os.path.join(self._folder, "{}.profile".format(identifier))
|
||||
|
||||
|
||||
class InvalidProfileError(Exception):
|
||||
pass
|
||||
|
||||
class SaveError(Exception):
|
||||
pass
|
||||
@@ -1,573 +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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import logging
|
||||
import os
|
||||
import copy
|
||||
|
||||
from octoprint.comm.protocol import ProtocolListener, FileAwareProtocolListener, ProtocolState, FileManagementProtocolMixin
|
||||
|
||||
from octoprint.util.listener import ListenerAware
|
||||
|
||||
from abc import ABCMeta, abstractmethod, abstractproperty
|
||||
|
||||
from octoprint.util import monotonic_time
|
||||
|
||||
from future.utils import with_metaclass
|
||||
|
||||
|
||||
class LastResult(object):
|
||||
def __init__(self):
|
||||
self.elapsed = None
|
||||
self.clean_elapsed = None
|
||||
self.progress = None
|
||||
self.pos = None
|
||||
self.success = None
|
||||
|
||||
self.available = False
|
||||
|
||||
|
||||
class Printjob(with_metaclass(ABCMeta, ProtocolListener, ListenerAware)):
|
||||
|
||||
parallel = False
|
||||
"""Job runs parallel to regular communication."""
|
||||
|
||||
exclusive = False
|
||||
"""Job has exclusive claim to communication channel."""
|
||||
|
||||
def __init__(self, name=None, user=None, event_data=None):
|
||||
if event_data is None:
|
||||
event_data = dict()
|
||||
|
||||
super(Printjob, self).__init__()
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._start = None
|
||||
self._protocol = None
|
||||
self._printer_profile = None
|
||||
self._name = name
|
||||
self._user = user
|
||||
self._event_data = event_data
|
||||
|
||||
self._lost_time = 0
|
||||
self._last_result = LastResult()
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return self._name
|
||||
|
||||
@property
|
||||
def user(self):
|
||||
return self._user
|
||||
|
||||
@property
|
||||
def size(self):
|
||||
return None
|
||||
|
||||
@property
|
||||
def pos(self):
|
||||
return None
|
||||
|
||||
@property
|
||||
def elapsed(self):
|
||||
return monotonic_time() - self._start if self._start is not None else None
|
||||
|
||||
@property
|
||||
def clean_elapsed(self):
|
||||
elapsed = self.elapsed
|
||||
if elapsed is None:
|
||||
return None
|
||||
return elapsed - self._lost_time
|
||||
|
||||
@property
|
||||
def last_result(self):
|
||||
return self._last_result
|
||||
|
||||
@property
|
||||
def progress(self):
|
||||
size = self.size
|
||||
pos = self.pos
|
||||
if pos is None or size is None or size == 0:
|
||||
return None
|
||||
|
||||
return float(pos) / float(size)
|
||||
|
||||
@property
|
||||
def active(self):
|
||||
return self._start is not None
|
||||
|
||||
def add_to_lost_time(self, value):
|
||||
self._lost_time += value
|
||||
|
||||
def can_process(self, protocol):
|
||||
return False
|
||||
|
||||
def process(self, protocol, position=0, user=None, tags=None, **kwargs):
|
||||
self._last_result = LastResult()
|
||||
self._start = monotonic_time()
|
||||
self._user = user
|
||||
self._protocol = protocol
|
||||
self._protocol.register_listener(self)
|
||||
|
||||
def pause(self, user=None, tags=None, **kwargs):
|
||||
self.process_job_paused(user=user, tags=tags, **kwargs)
|
||||
|
||||
def resume(self, user=None, tags=None, **kwargs):
|
||||
self.process_job_resumed(user=user, tags=tags, **kwargs)
|
||||
|
||||
def cancel(self, error=False, user=None, tags=None, **kwargs):
|
||||
if error:
|
||||
self.process_job_failed(**kwargs)
|
||||
else:
|
||||
self.process_job_cancelled(user=user, tags=tags, **kwargs)
|
||||
self._protocol.unregister_listener(self)
|
||||
self._protocol = None
|
||||
|
||||
def get_next(self):
|
||||
return None
|
||||
|
||||
def can_get_content(self):
|
||||
return False
|
||||
|
||||
def get_content_generator(self):
|
||||
return None
|
||||
|
||||
def event_payload(self, incl_last=False):
|
||||
payload = copy.deepcopy(self._event_data)
|
||||
|
||||
payload["owner"] = self._user
|
||||
elapsed = self.elapsed
|
||||
if elapsed is None and incl_last and self.last_result.available:
|
||||
elapsed = self.last_result.elapsed
|
||||
if elapsed is not None:
|
||||
payload["time"] = elapsed
|
||||
|
||||
return payload
|
||||
|
||||
def process_job_started(self, user=None, tags=None, **kwargs):
|
||||
self.notify_listeners("on_job_started", self, user=user, tags=tags, **kwargs)
|
||||
|
||||
def process_job_done(self, user=None, tags=None, **kwargs):
|
||||
self.notify_listeners("on_job_done", self, user=user, tags=tags, **kwargs)
|
||||
self.report_stats()
|
||||
self.reset_job()
|
||||
|
||||
def process_job_failed(self, **kwargs):
|
||||
self.notify_listeners("on_job_failed", self, **kwargs)
|
||||
self.report_stats()
|
||||
self.reset_job(success=False)
|
||||
|
||||
def process_job_cancelled(self, user=None, tags=None, **kwargs):
|
||||
self.notify_listeners("on_job_cancelled", self, user=user, tags=tags, **kwargs)
|
||||
self.report_stats()
|
||||
self.reset_job(success=False)
|
||||
|
||||
def process_job_paused(self, user=None, tags=None, **kwargs):
|
||||
self.notify_listeners("on_job_paused", self, user=user, tags=tags, **kwargs)
|
||||
|
||||
def process_job_resumed(self, user=None, tags=None, **kwargs):
|
||||
self.notify_listeners("on_job_resumed", self, user=user, tags=tags, **kwargs)
|
||||
|
||||
def process_job_progress(self):
|
||||
self.notify_listeners("on_job_progress", self)
|
||||
|
||||
def report_stats(self):
|
||||
elapsed = self.elapsed
|
||||
if elapsed:
|
||||
self._logger.info("Job processed in {}s".format(elapsed))
|
||||
|
||||
def reset_job(self, success=True):
|
||||
self._last_result.progress = 1.0 if success else self.progress
|
||||
self._last_result.pos = self.size if success else self.pos
|
||||
self._last_result.elapsed = self.elapsed
|
||||
self._last_result.clean_elapsed = self.clean_elapsed
|
||||
self._last_result.success = success
|
||||
self._last_result.available = True
|
||||
|
||||
self._start = None
|
||||
self._lost_time = 0
|
||||
|
||||
def on_protocol_state(self, protocol, old_state, new_state, *args, **kwargs):
|
||||
if new_state in (ProtocolState.DISCONNECTED, ProtocolState.DISCONNECTED_WITH_ERROR) and self.active:
|
||||
self.cancel(error=True)
|
||||
|
||||
|
||||
class StoragePrintjob(Printjob):
|
||||
def __init__(self, storage, path_in_storage, *args, **kwargs):
|
||||
Printjob.__init__(self, *args, **kwargs)
|
||||
self._storage = storage
|
||||
self._path_in_storage = path_in_storage
|
||||
|
||||
@property
|
||||
def storage(self):
|
||||
return self._storage
|
||||
|
||||
@property
|
||||
def path_in_storage(self):
|
||||
return self._path_in_storage
|
||||
|
||||
def event_payload(self, incl_last=False):
|
||||
payload = Printjob.event_payload(self, incl_last=incl_last)
|
||||
payload["name"] = self.name
|
||||
payload["path"] = self.path_in_storage
|
||||
payload["origin"] = self.storage
|
||||
return payload
|
||||
|
||||
|
||||
class LocalFilePrintjob(StoragePrintjob):
|
||||
|
||||
def __init__(self, path, *args, **kwargs):
|
||||
encoding = kwargs.pop("encoding", "utf-8")
|
||||
|
||||
StoragePrintjob.__init__(self, *args, **kwargs)
|
||||
|
||||
if path is None or not os.path.exists(path):
|
||||
raise ValueError("path must be set to a local file path")
|
||||
|
||||
self._path = path
|
||||
self._encoding = encoding
|
||||
self._size = os.stat(path).st_size
|
||||
|
||||
self._pos = 0
|
||||
self._read_lines = 0
|
||||
self._actual_lines = 0
|
||||
|
||||
self._cancel_pos = None
|
||||
|
||||
self._handle = None
|
||||
|
||||
@property
|
||||
def size(self):
|
||||
return self._size
|
||||
|
||||
@property
|
||||
def pos(self):
|
||||
return self._pos
|
||||
|
||||
@property
|
||||
def actual_lines(self):
|
||||
return self._actual_lines
|
||||
|
||||
@property
|
||||
def read_lines(self):
|
||||
return self._read_lines
|
||||
|
||||
@property
|
||||
def cancel_pos(self):
|
||||
return self._cancel_pos
|
||||
|
||||
@property
|
||||
def active(self):
|
||||
return self._start is not None and self._handle is not None
|
||||
|
||||
@property
|
||||
def path(self):
|
||||
return self._path
|
||||
|
||||
def event_payload(self, incl_last=False):
|
||||
event_data = StoragePrintjob.event_payload(self, incl_last=incl_last)
|
||||
event_data["size"] = self.size
|
||||
return event_data
|
||||
|
||||
def process(self, protocol, position=0, user=None, tags=None, **kwargs):
|
||||
Printjob.process(self, protocol, position=position, user=user, tags=tags, **kwargs)
|
||||
|
||||
from octoprint.util import bom_aware_open
|
||||
self._handle = bom_aware_open(self._path, encoding=self._encoding, errors="replace")
|
||||
|
||||
if position > 0:
|
||||
self._handle.seek(position)
|
||||
self._pos = position
|
||||
self.process_job_started(user=user, tags=tags)
|
||||
|
||||
def cancel(self, error=False, user=None, tags=None, **kwargs):
|
||||
self._cancel_pos = self.pos
|
||||
super(LocalFilePrintjob, self).cancel(error=error, user=user, tags=tags, **kwargs)
|
||||
|
||||
def get_next(self):
|
||||
from octoprint.util import to_unicode
|
||||
|
||||
if self._handle is None:
|
||||
raise ValueError("File {} is not open for reading" % self._path)
|
||||
|
||||
try:
|
||||
processed = None
|
||||
while processed is None:
|
||||
if self._handle is None:
|
||||
# file got closed just now
|
||||
self.process_job_done()
|
||||
return None
|
||||
line = to_unicode(self._handle.readline())
|
||||
|
||||
# we need to manually keep track of our pos here since
|
||||
# codecs' readline will make our handle's tell not
|
||||
# return the actual number of bytes read, but also the
|
||||
# already buffered bytes (for detecting the newlines)
|
||||
self._pos += len(line)
|
||||
self._actual_lines += 1
|
||||
|
||||
if not line:
|
||||
self.process_job_done()
|
||||
return None
|
||||
processed = self.process_line(line)
|
||||
|
||||
self._read_lines += 1
|
||||
self.process_job_progress()
|
||||
return processed
|
||||
except Exception as e:
|
||||
self.cancel(error=True)
|
||||
self._logger.exception("Exception while processing line")
|
||||
raise e
|
||||
|
||||
def process_line(self, line):
|
||||
return line
|
||||
|
||||
def close(self):
|
||||
if self._handle is not None:
|
||||
try:
|
||||
self._handle.close()
|
||||
except Exception:
|
||||
pass
|
||||
self._handle = None
|
||||
|
||||
def can_get_content(self):
|
||||
return True
|
||||
|
||||
def get_content_generator(self):
|
||||
from octoprint.util import bom_aware_open
|
||||
with bom_aware_open(self._path, encoding=self._encoding, error="replace") as f:
|
||||
for line in f.readline():
|
||||
yield line
|
||||
|
||||
def reset_job(self, success=True):
|
||||
super(LocalFilePrintjob, self).reset_job(success=success)
|
||||
self.close()
|
||||
self._pos = self._read_lines = 0
|
||||
|
||||
def report_stats(self):
|
||||
elapsed = self.elapsed
|
||||
lines = self._read_lines
|
||||
|
||||
if elapsed and lines:
|
||||
self._logger.info("Job processed in {:.3f}s ({} lines)".format(elapsed, lines))
|
||||
|
||||
|
||||
class LocalGcodeFilePrintjob(LocalFilePrintjob):
|
||||
|
||||
def can_process(self, protocol):
|
||||
return LocalGcodeFilePrintjob in protocol.supported_jobs
|
||||
|
||||
def process_line(self, line):
|
||||
# TODO no dependency on protocol module
|
||||
from octoprint.comm.protocol.reprap.util import strip_comment
|
||||
|
||||
# strip line
|
||||
processed = line.strip()
|
||||
|
||||
# strip comments
|
||||
processed = strip_comment(processed)
|
||||
if not len(processed):
|
||||
return None
|
||||
|
||||
# TODO apply offsets
|
||||
|
||||
# return result
|
||||
return processed
|
||||
|
||||
|
||||
class CopyJobMixin(object):
|
||||
pass
|
||||
|
||||
|
||||
class LocalGcodeStreamjob(LocalGcodeFilePrintjob, CopyJobMixin):
|
||||
|
||||
exclusive = True
|
||||
|
||||
@classmethod
|
||||
def from_job(cls, job, remote):
|
||||
if not isinstance(job, LocalGcodeFilePrintjob):
|
||||
raise ValueError("job must be a LocalGcodeFilePrintjob")
|
||||
|
||||
path = job._path
|
||||
storage = job._storage
|
||||
path_in_storage = job._path_in_storage
|
||||
name = job._name
|
||||
user = job._user
|
||||
encoding = job._encoding
|
||||
event_data = job._event_data
|
||||
|
||||
return cls(remote, path, storage, path_in_storage,
|
||||
name=name, user=user, encoding=encoding, event_data=event_data)
|
||||
|
||||
def __init__(self, remote, *args, **kwargs):
|
||||
super(LocalGcodeStreamjob, self).__init__(*args, **kwargs)
|
||||
self._remote = remote
|
||||
|
||||
@property
|
||||
def remote(self):
|
||||
return self._remote
|
||||
|
||||
def process(self, protocol, position=0, user=None, tags=None, **kwargs):
|
||||
super(LocalGcodeStreamjob, self).process(protocol, position=position, user=user, tags=tags, **kwargs)
|
||||
self._protocol.record_file(self._remote)
|
||||
|
||||
def process_job_done(self, user=None, tags=None, **kwargs):
|
||||
self._protocol.stop_recording_file()
|
||||
super(LocalGcodeStreamjob, self).process_job_done(user=user, tags=tags, **kwargs)
|
||||
|
||||
def process_job_failed(self, **kwargs):
|
||||
self._protocol.stop_recording_file()
|
||||
super(LocalGcodeStreamjob, self).process_job_failed(**kwargs)
|
||||
|
||||
def process_job_cancelled(self, user=None, tags=None, **kwargs):
|
||||
self._protocol.stop_recording_file()
|
||||
self._protocol.delete_file(self.remote)
|
||||
super(LocalGcodeStreamjob, self).process_job_cancelled(user=user, tags=tags, **kwargs)
|
||||
|
||||
def can_process(self, protocol):
|
||||
from octoprint.comm.protocol import FileStreamingProtocolMixin
|
||||
return LocalGcodeStreamjob in protocol.supported_jobs and isinstance(protocol, FileStreamingProtocolMixin) and isinstance(protocol, FileManagementProtocolMixin)
|
||||
|
||||
def report_stats(self):
|
||||
elapsed = self.elapsed
|
||||
lines = self._read_lines
|
||||
|
||||
if elapsed and lines:
|
||||
self._logger.info("Job processed in {:.3f}s ({} lines). Approx. {:.3f} lines/s, {:.3f} ms/line".format(elapsed,
|
||||
lines,
|
||||
float(lines) / float(elapsed),
|
||||
float(elapsed) * 1000.0 / float(lines)))
|
||||
|
||||
|
||||
class SDFilePrintjob(StoragePrintjob, FileAwareProtocolListener):
|
||||
|
||||
parallel = True
|
||||
|
||||
def __init__(self, path, status_interval=2.0, *args, **kwargs):
|
||||
name = path
|
||||
if name.startswith("/"):
|
||||
name = name[1:]
|
||||
|
||||
StoragePrintjob.__init__(self,
|
||||
"sdcard",
|
||||
name,
|
||||
name=name,
|
||||
event_data=dict(name=name,
|
||||
path=path,
|
||||
origin="sdcard"))
|
||||
self._filename = path
|
||||
self._status_interval = status_interval
|
||||
|
||||
self._status_timer = None
|
||||
self._active = False
|
||||
|
||||
self._size = None
|
||||
self._last_pos = None
|
||||
|
||||
@property
|
||||
def size(self):
|
||||
return self._size
|
||||
|
||||
@property
|
||||
def pos(self):
|
||||
return self._last_pos
|
||||
|
||||
@property
|
||||
def active(self):
|
||||
return self._start is not None and self._active
|
||||
|
||||
@property
|
||||
def status_interval(self):
|
||||
return self._status_interval
|
||||
|
||||
def can_process(self, protocol):
|
||||
from octoprint.comm.protocol import FileAwareProtocolMixin
|
||||
return SDFilePrintjob in protocol.supported_jobs and isinstance(protocol, FileAwareProtocolMixin)
|
||||
|
||||
def process(self, protocol, position=0, user=None, tags=None, **kwargs):
|
||||
Printjob.process(self, protocol, position=position, user=user, tags=tags, **kwargs)
|
||||
|
||||
self._protocol.register_listener(self)
|
||||
self._active = True
|
||||
self._last_pos = position
|
||||
|
||||
self._protocol.start_file_print(self._filename,
|
||||
position=position,
|
||||
user=user,
|
||||
tags=tags,
|
||||
part_of_job=True,
|
||||
**kwargs)
|
||||
self._protocol.start_file_print_status_monitor()
|
||||
|
||||
def pause(self, user=None, tags=None, **kwargs):
|
||||
super(SDFilePrintjob, self).pause(user=user, tags=tags, **kwargs)
|
||||
self._protocol.pause_file_print(user=user,
|
||||
tags=tags,
|
||||
part_of_job=True,
|
||||
**kwargs)
|
||||
|
||||
def resume(self, user=None, tags=None, **kwargs):
|
||||
super(SDFilePrintjob, self).resume(user=user, tags=tags, **kwargs)
|
||||
self._protocol.resume_file_print(user=user,
|
||||
tags=tags,
|
||||
part_of_job=True,
|
||||
**kwargs)
|
||||
|
||||
def on_protocol_sd_status(self, protocol, pos, total):
|
||||
self._last_pos = pos
|
||||
self._size = total
|
||||
self.process_job_progress()
|
||||
|
||||
def on_protocol_file_print_started(self, protocol, name, long_name, size, *args, **kwargs):
|
||||
self._size = size
|
||||
self.process_job_started(**kwargs)
|
||||
|
||||
def on_protocol_file_print_done(self, protocol, *args, **kwargs):
|
||||
self._protocol.stop_file_print_status_monitor(**kwargs)
|
||||
self.process_job_done(**kwargs)
|
||||
|
||||
def on_protocol_file_print_paused(self, protocol, *args, **kwargs):
|
||||
self._protocol.pause_file_print(**kwargs)
|
||||
|
||||
def on_protocol_file_print_resumed(self, protocol, *args, **kwargs):
|
||||
self._protocol.resume_file_print(**kwargs)
|
||||
|
||||
def reset_job(self, success=True):
|
||||
super(SDFilePrintjob, self).reset_job(success=success)
|
||||
self._active = False
|
||||
self._last_pos = None
|
||||
self._size = None
|
||||
|
||||
def event_payload(self, incl_last=False):
|
||||
payload = Printjob.event_payload(self, incl_last=incl_last)
|
||||
payload["size"] = self.size
|
||||
return payload
|
||||
|
||||
|
||||
class PrintjobListener(object):
|
||||
|
||||
def on_job_started(self, job, suppress_script=False, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def on_job_done(self, job, suppress_script=False, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def on_job_failed(self, job, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def on_job_cancelling(self, job, firmware_error=None, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def on_job_cancelled(self, job, cancel_position=None, suppress_script=False, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def on_job_paused(self, job, pause_position=None, suppress_script=False, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def on_job_resumed(self, job, suppress_script=False, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def on_job_progress(self, job, *args, **kwargs):
|
||||
pass
|
||||
@@ -1,542 +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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from octoprint.comm.transport import TransportListener, TransportState
|
||||
from octoprint.plugin import plugin_manager
|
||||
from octoprint.util import to_unicode, CountedEvent
|
||||
from octoprint.util.listener import ListenerAware
|
||||
from octoprint.settings import SubSettings
|
||||
|
||||
import contextlib
|
||||
import copy
|
||||
import logging
|
||||
|
||||
_registry = dict()
|
||||
|
||||
def register_protocols():
|
||||
from .reprap import ReprapGcodeProtocol
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# stock protocols
|
||||
register_protocol(ReprapGcodeProtocol)
|
||||
|
||||
# more protocols provided by plugins
|
||||
hooks = plugin_manager().get_hooks("octoprint.comm.protocol.register")
|
||||
for name, hook in hooks.items():
|
||||
try:
|
||||
protocols = hook()
|
||||
for protocol in protocols:
|
||||
try:
|
||||
register_protocol(protocol)
|
||||
except Exception:
|
||||
logger.exception("Error while registering protocol class {} for plugin {}".format(protocol, name))
|
||||
except Exception:
|
||||
logger.exception("Error executing octoprint.comm.protocol.register hook for plugin {}".format(name))
|
||||
|
||||
|
||||
def register_protocol(protocol_class):
|
||||
if not hasattr(protocol_class, "key"):
|
||||
raise ValueError("Protocol class {} is missing key".format(protocol_class))
|
||||
_registry[protocol_class.key] = protocol_class
|
||||
|
||||
|
||||
def lookup_protocol(key):
|
||||
return _registry.get(key)
|
||||
|
||||
|
||||
def all_protocols():
|
||||
return _registry.values()
|
||||
|
||||
|
||||
class Protocol(ListenerAware, TransportListener):
|
||||
|
||||
name = None
|
||||
key = None
|
||||
|
||||
supported_jobs = []
|
||||
|
||||
@classmethod
|
||||
def get_connection_options(cls):
|
||||
return []
|
||||
|
||||
@classmethod
|
||||
def get_settings_defaults(cls):
|
||||
return dict()
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(Protocol, self).__init__()
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._protocol_logger = logging.getLogger("PROTOCOL")
|
||||
self._state = ProtocolState.DISCONNECTED
|
||||
self._error = None
|
||||
|
||||
self._printer_profile = kwargs.get("printer_profile")
|
||||
self._plugin_manager = kwargs.get("plugin_manager")
|
||||
self._event_bus = kwargs.get("event_bus")
|
||||
self._settings = kwargs.get("settings")
|
||||
if not isinstance(self._settings, ProtocolSettings):
|
||||
self._settings = ProtocolSettings(self._settings, self)
|
||||
|
||||
self._job = None
|
||||
self._transport = None
|
||||
|
||||
self._job_on_hold = CountedEvent()
|
||||
|
||||
self._args = dict()
|
||||
|
||||
def args(self):
|
||||
return copy.deepcopy(self._args)
|
||||
|
||||
def set_current_args(self, **value):
|
||||
self._args = copy.deepcopy(value)
|
||||
|
||||
@contextlib.contextmanager
|
||||
def job_put_on_hold(self, blocking=True):
|
||||
if not self._job_on_hold.acquire(blocking=blocking):
|
||||
raise RuntimeError("Could not acquire job_on_hold lock")
|
||||
|
||||
self._job_on_hold.set()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
self._job_on_hold.clear()
|
||||
if self._job_on_hold.counter == 0:
|
||||
self._job_on_hold_cleared()
|
||||
self._job_on_hold.release()
|
||||
|
||||
@property
|
||||
def job_on_hold(self):
|
||||
return self._job_on_hold.counter > 0
|
||||
|
||||
def set_job_on_hold(self, value, blocking=True):
|
||||
if not self._job_on_hold.acquire(blocking=blocking):
|
||||
return False
|
||||
|
||||
try:
|
||||
if value:
|
||||
self._job_on_hold.set()
|
||||
else:
|
||||
self._job_on_hold.clear()
|
||||
if self._job_on_hold.counter == 0:
|
||||
self._job_on_hold_cleared()
|
||||
finally:
|
||||
self._job_on_hold.release()
|
||||
|
||||
return True
|
||||
|
||||
@property
|
||||
def transport(self):
|
||||
return self._transport
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
return self._state
|
||||
|
||||
@state.setter
|
||||
def state(self, new_state):
|
||||
old_state = self._state
|
||||
if old_state == new_state:
|
||||
return
|
||||
|
||||
self._state = new_state
|
||||
|
||||
name = "_on_switching_state_{}".format(new_state)
|
||||
method = getattr(self, name, None)
|
||||
if method is not None:
|
||||
method(old_state)
|
||||
|
||||
self.process_protocol_log("--- Protocol state changed from '{}' to '{}'".format(old_state, new_state))
|
||||
self.notify_listeners("on_protocol_state", self, old_state, new_state)
|
||||
|
||||
name = "_on_switched_state_{}".format(new_state)
|
||||
method = getattr(self, name, None)
|
||||
if method is not None:
|
||||
method(old_state)
|
||||
|
||||
@property
|
||||
def error(self):
|
||||
return self._error
|
||||
|
||||
@error.setter
|
||||
def error(self, new_error):
|
||||
self._error = new_error
|
||||
|
||||
def connect(self, transport, transport_args=None, transport_kwargs=None):
|
||||
if self.state not in (ProtocolState.DISCONNECTED, ProtocolState.DISCONNECTED_WITH_ERROR):
|
||||
raise ProtocolAlreadyConnectedError("Already connected, disconnect first")
|
||||
|
||||
self.process_protocol_log("--- Protocol {} connecting via transport {}...".format(self,
|
||||
transport))
|
||||
|
||||
if transport_args is None:
|
||||
transport_args = []
|
||||
if transport_kwargs is None:
|
||||
transport_kwargs = dict()
|
||||
|
||||
self._transport = transport
|
||||
self._transport.register_listener(self)
|
||||
|
||||
if self._transport.state == TransportState.DISCONNECTED:
|
||||
self._transport.connect(*transport_args, **transport_kwargs)
|
||||
self.state = ProtocolState.CONNECTING
|
||||
|
||||
def disconnect(self, error=False):
|
||||
if self.state in (ProtocolState.DISCONNECTED, ProtocolState.DISCONNECTED_WITH_ERROR, ProtocolState.DISCONNECTING, ProtocolState.DISCONNECTING_WITH_ERROR):
|
||||
raise ProtocolNotConnectedError("Already disconnecting or disconnected")
|
||||
|
||||
if error:
|
||||
self.state = ProtocolState.DISCONNECTING_WITH_ERROR
|
||||
else:
|
||||
self.state = ProtocolState.DISCONNECTING
|
||||
|
||||
self.process_protocol_log("--- Protocol {} disconnecting from transport {}...".format(self,
|
||||
self._transport))
|
||||
|
||||
self._transport.unregister_listener(self)
|
||||
if self._transport.state == TransportState.CONNECTED:
|
||||
try:
|
||||
self._transport.disconnect()
|
||||
except Exception:
|
||||
self._logger.exception("Error while disconnecting from transport {}".format(self._transport))
|
||||
error = True
|
||||
|
||||
if error:
|
||||
self.state = ProtocolState.DISCONNECTED_WITH_ERROR
|
||||
else:
|
||||
self.state = ProtocolState.DISCONNECTED
|
||||
|
||||
def process(self, job, position=0, user=None, tags=None, **kwargs):
|
||||
if not job.can_process(self):
|
||||
raise ValueError("Job {} cannot be processed with protocol {}".format(job, self))
|
||||
|
||||
self._job = job
|
||||
self._job.register_listener(self)
|
||||
|
||||
self.state = ProtocolState.STARTING
|
||||
self.notify_listeners("on_protocol_job_starting", self, self._job, user=user, tags=tags, **kwargs)
|
||||
self._job.process(self, position=position, user=user, tags=tags, **kwargs)
|
||||
|
||||
def pause_processing(self, user=None, tags=None, **kwargs):
|
||||
if self._job is None or self.state not in ProtocolState.PROCESSING_STATES:
|
||||
return
|
||||
self.state = ProtocolState.PAUSING
|
||||
self.notify_listeners("on_protocol_job_pausing", self, self._job, user=user, tags=tags, **kwargs)
|
||||
self._job.pause(user=user, tags=tags)
|
||||
|
||||
def resume_processing(self, user=None, tags=None, **kwargs):
|
||||
if self._job is None or self.state not in (ProtocolState.PAUSING, ProtocolState.PAUSED):
|
||||
return
|
||||
self.state = ProtocolState.RESUMING
|
||||
self.notify_listeners("on_protocol_job_resuming", self, self._job, user=user, tags=tags, **kwargs)
|
||||
self._job.resume(user=user, tags=tags, **kwargs)
|
||||
|
||||
def cancel_processing(self, error=False, user=None, tags=None, **kwargs):
|
||||
if self._job is not None and self.state in ProtocolState.PROCESSING_STATES + (ProtocolState.PAUSED,):
|
||||
self.state = ProtocolState.CANCELLING
|
||||
self.notify_listeners("on_protocol_job_cancelling", self, self._job, user=user, tags=tags, **kwargs)
|
||||
self._job.cancel(error=error, user=user, tags=tags, **kwargs)
|
||||
|
||||
def can_send(self):
|
||||
return True
|
||||
|
||||
def send_commands(self, command_type=None, tags=None, *commands):
|
||||
pass
|
||||
|
||||
def send_script(self, script, context=None, user=None, tags=None):
|
||||
"""
|
||||
Sends the specified script/the GCODE script with the specified name.
|
||||
|
||||
Args:
|
||||
script (GcodeScript or unicode): Script or name of the script to send
|
||||
context (dict): Additional render context
|
||||
user (str): The user on whose behalf the script is being sent. May be None
|
||||
tags (set): And tags to send with the script commands. May be None
|
||||
"""
|
||||
pass
|
||||
|
||||
def repair(self):
|
||||
pass
|
||||
|
||||
def on_job_started(self, job, *args, **kwargs):
|
||||
self.notify_listeners("on_protocol_job_started", self, job, *args, **kwargs)
|
||||
self.state = ProtocolState.PROCESSING
|
||||
|
||||
def on_job_paused(self, job, *args, **kwargs):
|
||||
self.notify_listeners("on_protocol_job_paused", self, job, *args, **kwargs)
|
||||
self.state = ProtocolState.PAUSED
|
||||
|
||||
def on_job_resumed(self, job, *args, **kwargs):
|
||||
self.notify_listeners("on_protocol_job_resumed", self, job, *args, **kwargs)
|
||||
self.state = ProtocolState.PROCESSING
|
||||
|
||||
def on_job_done(self, job, *args, **kwargs):
|
||||
self.notify_listeners("on_protocol_job_done", self, job, *args, **kwargs)
|
||||
self._job_processed(job)
|
||||
|
||||
def on_job_cancelled(self, job, *args, **kwargs):
|
||||
self.notify_listeners("on_protocol_job_cancelled", self, job, *args, **kwargs)
|
||||
self._job_processed(job)
|
||||
|
||||
def on_job_failed(self, job, *args, **kwargs):
|
||||
self.notify_listeners("on_protocol_job_failed", self, job, *args, **kwargs)
|
||||
self._job_processed(job)
|
||||
|
||||
def _job_processed(self, job, *args, **kwargs):
|
||||
self._job.unregister_listener(self)
|
||||
self.state = ProtocolState.CONNECTED
|
||||
|
||||
def on_transport_disconnected(self, transport, error=None):
|
||||
self.disconnect(error=error is not None)
|
||||
|
||||
def on_transport_log_received_data(self, transport, data):
|
||||
message = "<<< {}".format(to_unicode(data, errors="replace").strip())
|
||||
self.process_protocol_log(message)
|
||||
|
||||
def on_transport_log_sent_data(self, transport, data):
|
||||
message = ">>> {}".format(to_unicode(data, errors="replace").strip())
|
||||
self.process_protocol_log(message)
|
||||
|
||||
def on_transport_log_message(self, transport, data):
|
||||
message = "--- {}".format(to_unicode(data, errors="replace").strip())
|
||||
self.process_protocol_log(message)
|
||||
|
||||
def process_protocol_log(self, message):
|
||||
self._protocol_logger.info(message)
|
||||
self.notify_listeners("on_protocol_log", self, message)
|
||||
|
||||
def _job_on_hold_cleared(self):
|
||||
pass
|
||||
|
||||
|
||||
def __str__(self):
|
||||
return self.__class__.__name__
|
||||
|
||||
class ProtocolState(object):
|
||||
CONNECTING = "connecting"
|
||||
CONNECTED = "connected"
|
||||
DISCONNECTING = "disconnecting"
|
||||
DISCONNECTED = "disconnected"
|
||||
STARTING = "starting"
|
||||
PROCESSING = "processing"
|
||||
FINISHING = "finishing"
|
||||
CANCELLING = "cancelling"
|
||||
PAUSING = "pausing"
|
||||
RESUMING = "resuming"
|
||||
PAUSED = "paused"
|
||||
ERROR = "error"
|
||||
DISCONNECTING_WITH_ERROR = "disconnecting_with_error"
|
||||
DISCONNECTED_WITH_ERROR = "disconnected_with_error"
|
||||
|
||||
PROCESSING_STATES = (STARTING, PROCESSING, CANCELLING, PAUSING, RESUMING, FINISHING)
|
||||
OPERATIONAL_STATES = (CONNECTED, PAUSED) + PROCESSING_STATES
|
||||
|
||||
class ProtocolSettings(SubSettings):
|
||||
def __init__(self, settings, protocol):
|
||||
SubSettings.__init__(self, settings, ["comm", "protocol", protocol.key],
|
||||
defaults=protocol.get_settings_defaults())
|
||||
|
||||
class ProtocolAlreadyConnectedError(Exception):
|
||||
pass
|
||||
|
||||
class ProtocolNotConnectedError(Exception):
|
||||
pass
|
||||
|
||||
class ThreeAxisProtocolMixin(object):
|
||||
def move(self, x=None, y=None, z=None, feedrate=None, relative=False, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def home(self, x=False, y=False, z=False, *args, **kwargs):
|
||||
pass
|
||||
|
||||
|
||||
class MultiToolProtocolMixin(object):
|
||||
def change_tool(self, tool, *args, **kwargs):
|
||||
pass
|
||||
|
||||
|
||||
class ThreeDPrinterProtocolMixin(ThreeAxisProtocolMixin, MultiToolProtocolMixin):
|
||||
def move(self, x=None, y=None, z=None, e=None, feedrate=None, relative=False, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def set_feedrate_multiplier(self, multiplier, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def set_extrusion_multiplier(self, multiplier, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def set_extruder_temperature(self, temperature, tool=None, wait=False, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def set_bed_temperature(self, temperature, wait=False, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def set_chamber_temperature(self, temperature, wait=False, *args, **kwargs):
|
||||
pass
|
||||
|
||||
|
||||
class FanControlProtocolMixin(object):
|
||||
def set_fan_speed(self, speed, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def get_fan_speed(self, speed, *args, **kwargs):
|
||||
pass
|
||||
|
||||
|
||||
class MotorControlProtocolMixin(object):
|
||||
def enable_motors(self, *args, **kwargs):
|
||||
self.set_motor_state(True)
|
||||
|
||||
def disable_motors(self, *args, **kwargs):
|
||||
self.set_motor_state(False)
|
||||
|
||||
def set_motor_state(self, enabled, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def get_motor_state(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
|
||||
class PowerControlProtocolMixin(object):
|
||||
def enable_power(self, *args, **kwargs):
|
||||
self.set_power_state(True)
|
||||
|
||||
def disable_power(self, *args, **kwargs):
|
||||
self.set_power_state(False)
|
||||
|
||||
def set_power_state(self, enabled, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def get_power_state(self, *args, **kwargs):
|
||||
return None
|
||||
|
||||
|
||||
class FileAwareProtocolMixin(object):
|
||||
def init_file_storage(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def eject_file_storage(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def list_files(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def start_file_print(self, name, position=0, tags=None, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def pause_file_print(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def resume_file_print(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def get_file_print_status(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def start_file_print_status_monitor(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def stop_file_print_status_monitor(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
|
||||
class FileManagementProtocolMixin(FileAwareProtocolMixin):
|
||||
def delete_file(self, name, *args, **kwargs):
|
||||
pass
|
||||
|
||||
|
||||
class FileStreamingProtocolMixin(FileManagementProtocolMixin):
|
||||
def record_file(self, name, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def stop_recording_file(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
|
||||
class ProtocolListener(object):
|
||||
def on_protocol_state(self, protocol, old_state, new_state, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def on_protocol_temperature(self, protocol, temperatures, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def on_protocol_log(self, protocol, message, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def on_protocol_reset(self, protocol, idle, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def on_protocol_job_started(self, protocol, job, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def on_protocol_job_pausing(self, protocol, job, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def on_protocol_job_paused(self, protocol, job, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def on_protocol_job_resuming(self, protocol, job, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def on_protocol_job_resumed(self, protocol, job, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def on_protocol_job_cancelling(self, protocol, job, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def on_protocol_job_cancelled(self, protocol, job, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def on_protocol_job_finishing(self, protocol, job, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def on_protocol_job_done(self, protocol, job, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def on_protocol_job_failed(self, protocol, job, *args, **kwargs):
|
||||
pass
|
||||
|
||||
|
||||
class FileAwareProtocolListener(object):
|
||||
def on_protocol_file_storage_available(self, protocol, available, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def on_protocol_file_list(self, protocol, files, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def on_protocol_file_status(self, protocol, pos, total, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def on_protocol_file_print_started(self, protocol, name, long_name, size, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def on_protocol_file_print_done(self, protocol, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def on_protocol_file_print_paused(self, protocol, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def on_protocol_file_print_resumed(self, protocol, *args, **kwargs):
|
||||
pass
|
||||
|
||||
|
||||
class PositionAwareProtocolListener(object):
|
||||
|
||||
def on_protocol_position_all_update(self, protocol, position, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def on_protocol_position_z_update(self, protocol, z, *args, **kwargs):
|
||||
pass
|
||||
|
||||
|
||||
class FirmwareDataAwareProtocolListener(object):
|
||||
|
||||
def on_protocol_firmware_info(self, protocol, info, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def on_protocol_firmware_capability(self, protocol, capability, enabled, capabilities, *args, **kwargs):
|
||||
pass
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,93 +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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import copy
|
||||
import re
|
||||
|
||||
from future.utils import with_metaclass
|
||||
|
||||
from octoprint.util import pp
|
||||
|
||||
|
||||
_compiled_regex_type = type(re.compile(r"a"))
|
||||
def _is_compiled_regex(obj):
|
||||
return isinstance(obj, _compiled_regex_type)
|
||||
|
||||
|
||||
__registry = dict()
|
||||
|
||||
def _register_command_class(cls):
|
||||
__registry[cls.__name__] = cls
|
||||
|
||||
|
||||
def to_command(line, type=None, tags=None, **kwargs):
|
||||
if isinstance(line, Command):
|
||||
return line
|
||||
|
||||
for cls in __registry.values():
|
||||
if cls.pattern:
|
||||
# noinspection PyUnresolvedReferences,PyProtectedMember
|
||||
if _is_compiled_regex(cls.pattern) and cls.pattern.match(line):
|
||||
return cls.from_line(line, type=type, tags=tags, **kwargs)
|
||||
elif callable(cls.pattern) and cls.pattern(line):
|
||||
return cls.from_line(line, type=type, tags=tags, **kwargs)
|
||||
|
||||
return Command.from_line(line, type=type, tags=tags, **kwargs)
|
||||
|
||||
|
||||
class CommandMetaClass(type):
|
||||
def __new__(mcs, *args, **kwargs):
|
||||
c = type.__new__(mcs, *args, **kwargs)
|
||||
_register_command_class(c)
|
||||
return c
|
||||
|
||||
class Command(with_metaclass(CommandMetaClass, object)):
|
||||
|
||||
pattern = None
|
||||
|
||||
@classmethod
|
||||
def from_line(cls, line, type=None, tags=None, **kwargs):
|
||||
return cls(line, type=type, tags=tags, **kwargs)
|
||||
|
||||
def __init__(self, line, type=None, tags=None, **kwargs):
|
||||
if tags is None:
|
||||
tags = set()
|
||||
|
||||
self.line = line
|
||||
self.bytes = line.encode("ascii", errors="replace")
|
||||
self.type = type
|
||||
self.tags = tags
|
||||
|
||||
def __repr__(self):
|
||||
return "{}({!r},type={!r},tags={})".format(self.__class__.__name__, self.line, self.type, pp(self.tags))
|
||||
|
||||
def __str__(self):
|
||||
return self.line
|
||||
|
||||
def __bytes__(self):
|
||||
return self.bytes
|
||||
|
||||
def __key(self):
|
||||
return self.line, self.type
|
||||
|
||||
def __eq__(self, other):
|
||||
return self.__key() == other.__key()
|
||||
|
||||
def __hash__(self):
|
||||
return hash(self.__key())
|
||||
|
||||
def with_type(self, type):
|
||||
c = copy.deepcopy(self)
|
||||
c.type = type
|
||||
return c
|
||||
|
||||
def with_tags(self, tags):
|
||||
if tags is None:
|
||||
return self
|
||||
|
||||
c = copy.deepcopy(self)
|
||||
c.tags |= tags
|
||||
return c
|
||||
@@ -1,40 +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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from octoprint.comm.protocol.reprap.commands import Command
|
||||
|
||||
from octoprint.util import pp
|
||||
|
||||
class AtCommand(Command):
|
||||
|
||||
pattern = staticmethod(lambda x: x.startswith("@"))
|
||||
|
||||
@staticmethod
|
||||
def from_line(line, **kwargs):
|
||||
split = line.split(None, 1)
|
||||
if len(split) == 2:
|
||||
atcommand = split[0]
|
||||
parameters = split[1]
|
||||
else:
|
||||
atcommand = split[0]
|
||||
parameters = ""
|
||||
|
||||
atcommand = atcommand[1:]
|
||||
|
||||
return AtCommand(line, atcommand, parameters, **kwargs)
|
||||
|
||||
def __init__(self, line, atcommand, parameters, **kwargs):
|
||||
self.atcommand = atcommand
|
||||
self.parameters = parameters
|
||||
super(AtCommand, self).__init__(line, **kwargs)
|
||||
|
||||
def __repr__(self):
|
||||
return "AtCommand({!r},{!r},{!r},type={!r},tags={}".format(self.line,
|
||||
self.atcommand,
|
||||
self.parameters,
|
||||
self.type,
|
||||
pp(self.tags))
|
||||
|
||||
@@ -1,134 +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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from octoprint.comm.protocol.reprap.commands import Command
|
||||
|
||||
import re
|
||||
import string
|
||||
|
||||
from octoprint.util import pp
|
||||
|
||||
class GcodeCommand(Command):
|
||||
|
||||
pattern = staticmethod(lambda x: GcodeCommand.command_regex.match(x))
|
||||
|
||||
command_regex = re.compile(r"^\s*((?P<GM>[GM](?P<number>\d+))(\\.(?P<subcode>\d+))?|(?P<T>T(?P<tool>\d+))|(?P<F>F(?P<feedrate>\d+)))")
|
||||
parameter_regex = re.compile(r"(?P<key>[A-Z])((?P<value>[-+]?[0-9]*\.?[0-9]+)(?!\d)|(\s|$))")
|
||||
|
||||
possible_params = tuple(string.ascii_lowercase) + ("subcode", "param", "tool", "feedrate", "original")
|
||||
|
||||
@staticmethod
|
||||
def from_line(line, **kwargs):
|
||||
if isinstance(line, GcodeCommand):
|
||||
return line
|
||||
|
||||
tags = kwargs.get("tags")
|
||||
if tags is None:
|
||||
tags = set()
|
||||
|
||||
command_type = kwargs.get("type")
|
||||
|
||||
line = line.strip()
|
||||
code = ""
|
||||
|
||||
args = dict(original=line, type=command_type, tags=tags)
|
||||
|
||||
match = GcodeCommand.command_regex.match(line)
|
||||
|
||||
if match is None:
|
||||
# not a gcode command
|
||||
return Command.from_line(line, **kwargs)
|
||||
|
||||
if match.group("GM"):
|
||||
code = match.group("GM")
|
||||
|
||||
if match.group("subcode"):
|
||||
args["subcode"] = int(match.group("subcode"))
|
||||
|
||||
if match.group(0) != line:
|
||||
rest = line[len(match.group(0)):]
|
||||
|
||||
while True:
|
||||
matched_param = GcodeCommand.parameter_regex.search(rest)
|
||||
if not matched_param:
|
||||
break
|
||||
|
||||
key = matched_param.group("key").lower()
|
||||
if matched_param.group("value"):
|
||||
value = matched_param.group("value")
|
||||
if "." in value:
|
||||
value = float(value)
|
||||
else:
|
||||
value = int(value)
|
||||
else:
|
||||
value = True
|
||||
args[key] = value
|
||||
rest = rest[:matched_param.start()] + rest[matched_param.end():]
|
||||
|
||||
rest = rest.lstrip()
|
||||
if rest:
|
||||
args["param"] = rest
|
||||
|
||||
elif match.group("T"):
|
||||
code = "T"
|
||||
args["tool"] = int(match.group("tool"))
|
||||
|
||||
elif match.group("F"):
|
||||
code = "F"
|
||||
args["feedrate"] = int(match.group("feedrate"))
|
||||
|
||||
return GcodeCommand(code, **args)
|
||||
|
||||
def __init__(self, code, **kwargs):
|
||||
self.code = code
|
||||
|
||||
self.subcode = kwargs.pop("subcode", None)
|
||||
self.tool = kwargs.pop("tool", None)
|
||||
self.feedrate = kwargs.pop("feedrate", None)
|
||||
self.param = kwargs.pop("param", None)
|
||||
self.original = kwargs.pop("original", None)
|
||||
|
||||
command_type = kwargs.pop("type", None)
|
||||
tags = kwargs.pop("tags", None)
|
||||
|
||||
self.args = kwargs
|
||||
|
||||
if self.original is None:
|
||||
line = self._to_line()
|
||||
else:
|
||||
line = self.original
|
||||
|
||||
super(GcodeCommand, self).__init__(line, type=command_type, tags=tags)
|
||||
|
||||
self._repr = self._to_repr()
|
||||
|
||||
def __getattr__(self, item):
|
||||
if len(item) == 1:
|
||||
return self.args.get(item, None)
|
||||
raise AttributeError("'GcodeCommand' object has no attribute '{}'".format(item))
|
||||
|
||||
def __repr__(self):
|
||||
return self._repr
|
||||
|
||||
def _to_line(self):
|
||||
attr = []
|
||||
for key in string.ascii_lowercase:
|
||||
value = self.args.get(key, None)
|
||||
if value is not None:
|
||||
if value is True:
|
||||
attr.append(key.upper())
|
||||
else:
|
||||
attr.append("{}{!r}".format(key.upper(), value))
|
||||
attribute_str = " ".join(attr)
|
||||
return "{}{}{}".format(self.code.upper(), " " + attribute_str if attribute_str else "",
|
||||
" " + self.param if self.param else "")
|
||||
|
||||
def _to_repr(self):
|
||||
args = [k + "=" + repr(getattr(self, k)) for k in self.possible_params if getattr(self, k, None) is not None]
|
||||
return "GcodeCommand({!r}{},type={!r},tags={})".format(self.code,
|
||||
"," + ",".join(args) if args else "",
|
||||
self.type,
|
||||
pp(self.tags))
|
||||
@@ -1,44 +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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from .generic import * # noqa: F403
|
||||
from .klipper import * # noqa: F403
|
||||
from .marlin import * # noqa: F403
|
||||
from .repetier import * # noqa: F403
|
||||
from .reprapfirmware import * # noqa: F403
|
||||
from .smoothieware import * # noqa: F403
|
||||
|
||||
from .anet import * # noqa: F403
|
||||
from .malyan import * # noqa: F403
|
||||
|
||||
|
||||
class FlavorOverride(object):
|
||||
|
||||
def __init__(self, flavor, overrides):
|
||||
self._flavor = flavor
|
||||
self._overrides = overrides
|
||||
|
||||
@property
|
||||
def flavor(self):
|
||||
return self._flavor
|
||||
|
||||
@flavor.setter
|
||||
def flavor(self, value):
|
||||
self._flavor = value
|
||||
|
||||
@property
|
||||
def overrides(self):
|
||||
return self._overrides
|
||||
|
||||
@overrides.setter
|
||||
def overrides(self, value):
|
||||
self._overrides = value
|
||||
|
||||
def __getattr__(self, item):
|
||||
try:
|
||||
return self._overrides[item]
|
||||
except KeyError:
|
||||
return getattr(self._flavor, item)
|
||||
@@ -1,17 +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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from .repetier import RepetierFlavor
|
||||
|
||||
class AnetA8RepetierFlavor(RepetierFlavor):
|
||||
|
||||
key = "aneta8repetier"
|
||||
name = "Anet A8"
|
||||
|
||||
@classmethod
|
||||
def identifier(cls, firmware_name, firmware_info):
|
||||
return "anet_a8" in firmware_name.lower()
|
||||
|
||||
@@ -1,706 +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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import re
|
||||
import logging
|
||||
import time
|
||||
|
||||
from octoprint.comm.protocol.reprap.commands.gcode import GcodeCommand
|
||||
from octoprint.comm.protocol.reprap.util import regex_float_pattern, regex_positive_float_pattern, regex_int_pattern
|
||||
|
||||
from octoprint.util import chunks, monotonic_time
|
||||
|
||||
from future.utils import with_metaclass
|
||||
|
||||
_flavor_registry = dict()
|
||||
|
||||
|
||||
def _register_flavor(cls):
|
||||
key = getattr(cls, "key", None)
|
||||
if key and not key in _flavor_registry:
|
||||
_flavor_registry[key] = cls
|
||||
|
||||
|
||||
def all_flavors():
|
||||
return _flavor_registry.values()
|
||||
|
||||
|
||||
def lookup_flavor(key):
|
||||
return _flavor_registry.get(key)
|
||||
|
||||
|
||||
class FlavorMeta(type):
|
||||
def __new__(mcs, name, bases, class_dict):
|
||||
cls = type.__new__(mcs, name, bases, class_dict)
|
||||
_register_flavor(cls)
|
||||
return cls
|
||||
|
||||
|
||||
class GenericFlavor(with_metaclass(FlavorMeta, object)):
|
||||
|
||||
key = "generic"
|
||||
name = "Generic Flavor"
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
unknown_requires_ack = False
|
||||
unknown_with_checksum = False
|
||||
|
||||
always_send_checksum = False
|
||||
never_send_checksum = False
|
||||
|
||||
detect_external_heatups = True
|
||||
block_while_dwelling = False
|
||||
|
||||
trigger_ok_after_resend = "detect"
|
||||
|
||||
sd_relative_path = False
|
||||
|
||||
checksum_requiring_commands = ["M110"]
|
||||
long_running_commands = ["G4", "G28", "G29", "G30", "G32", "M190", "M109", "M400", "M226"]
|
||||
asynchronous_commands = ["G0", "G1", "G2", "G3"]
|
||||
blocked_commands = ["M0", "M1"]
|
||||
pausing_commands = ["M0", "M1", "M25"]
|
||||
emergency_commands = ["M112", "M108", "M410"]
|
||||
|
||||
heatup_abortable = False
|
||||
|
||||
regex_resend_linenumber = re.compile(r"(N|N:)?(?P<n>%s)" % regex_int_pattern)
|
||||
"""Regex to use for request line numbers in resend requests"""
|
||||
|
||||
regex_temp = re.compile(r"(?P<tool>B|T(?P<toolnum>\d*)):\s*(?P<actual>%s)(\s*/?\s*(?P<target>%s))?" % (
|
||||
regex_positive_float_pattern, regex_positive_float_pattern))
|
||||
"""Regex matching temperature entries in line.
|
||||
|
||||
Groups will be as follows:
|
||||
|
||||
* ``tool``: whole tool designator, incl. optional ``toolnum`` (str)
|
||||
* ``toolnum``: tool number, if provided (int)
|
||||
* ``actual``: actual temperature (float)
|
||||
* ``target``: target temperature, if provided (float)
|
||||
"""
|
||||
|
||||
regex_position = re.compile(r"(?P<axis>[XYZE]):(?P<pos>{float})\s*".format(float=regex_float_pattern))
|
||||
"""Regex for matching position entries in line.
|
||||
|
||||
Groups will be as follows:
|
||||
|
||||
* ``axis``: axis designator, either ``X``, ``Y``, ``Z`` or ``E`` (str)
|
||||
* ``pos``: axis position (float)
|
||||
"""
|
||||
|
||||
regex_firmware_splitter = re.compile(r"\s*([A-Z0-9_]+):")
|
||||
"""Regex to use for splitting M115 responses."""
|
||||
|
||||
regex_sd_file_opened = re.compile(r"file opened:\s*(?P<name>.*?)(\s+size:\s*(?P<size>[0-9]+)|$)")
|
||||
|
||||
regex_sd_printing_byte = re.compile(r"sd printing byte (?P<current>[0-9]*)/(?P<total>[0-9]*)")
|
||||
"""Regex matching SD printing status reports.
|
||||
|
||||
Groups will be as follows:
|
||||
|
||||
* ``current``: current byte position in file being printed
|
||||
* ``total``: total size of file being printed
|
||||
"""
|
||||
|
||||
##~~ Overrides
|
||||
|
||||
_overrides = dict()
|
||||
|
||||
@classmethod
|
||||
def with_overrides(cls, overrides):
|
||||
return type(b"{}WithOverrides".format(cls.__name__), (cls,), overrides)
|
||||
|
||||
##~~ Identifier
|
||||
|
||||
@classmethod
|
||||
def identifier(cls, firmware_name, firmware_info):
|
||||
return False
|
||||
|
||||
##~~ Message matchers
|
||||
|
||||
@classmethod
|
||||
def comm_timeout(cls, line, lower_line, state, flags):
|
||||
now = monotonic_time()
|
||||
matches = ((line == "" and now > flags["timeout"]) or (flags["expect_continous_comms"]
|
||||
and not flags["job_on_hold"]
|
||||
and not flags["long_running_command"]
|
||||
and not flags["heating"]
|
||||
and now > flags["ok_timeout"])) and \
|
||||
(not cls.block_while_dwelling or not flags["dwelling_until"] or now > flags["dwelling_until"])
|
||||
continue_further = line != ""
|
||||
return matches, continue_further
|
||||
|
||||
@classmethod
|
||||
def comm_ok(cls, line, lower_line, state, flags):
|
||||
matches = lower_line.startswith("ok")
|
||||
continue_further = not matches \
|
||||
or cls.message_temperature(line, lower_line, state, flags) \
|
||||
or cls.message_position(line, lower_line, state, flags) \
|
||||
or cls.message_firmware_info(line, lower_line, state, flags)
|
||||
return matches, continue_further
|
||||
|
||||
@classmethod
|
||||
def comm_start(cls, line, lower_line, state, flags):
|
||||
return lower_line == "start"
|
||||
|
||||
@classmethod
|
||||
def comm_wait(cls, line, lower_line, state, flags):
|
||||
return lower_line == "wait"
|
||||
|
||||
@classmethod
|
||||
def comm_resend(cls, line, lower_line, state, flags):
|
||||
return lower_line.startswith("resend") or lower_line.startswith("rs")
|
||||
|
||||
@classmethod
|
||||
def comm_action_command(cls, line, lower_line, state, flags):
|
||||
return line.startswith("//") and line[2:].strip().startswith("action:")
|
||||
|
||||
@classmethod
|
||||
def comm_error(cls, line, lower_line, state, flags):
|
||||
return line.startswith("Error:") or line.startswith("!!")
|
||||
|
||||
@classmethod
|
||||
def comm_ignore_ok(cls, line, lower_line, state, flags):
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def comm_busy(cls, line, lower_line, state, flags):
|
||||
return line.startswith("echo:busy:") or line.startswith("busy:")
|
||||
|
||||
@classmethod
|
||||
def error_multiline(cls, line, lower_line, state, flags):
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def error_communication(cls, line, lower_line, state, flags):
|
||||
return "line number" in lower_line or "checksum" in lower_line or "format error" in lower_line or "expected line" in lower_line
|
||||
|
||||
@classmethod
|
||||
def message_temperature(cls, line, lower_line, state, flags):
|
||||
return "T:" in line or "T0:" in line or "B:" in line
|
||||
|
||||
@classmethod
|
||||
def message_position(cls, line, lower_line, state, flags):
|
||||
return 'X:' in line and 'Y:' in line and 'Z:' in line
|
||||
|
||||
@classmethod
|
||||
def message_firmware_info(cls, line, lower_line, state, flags):
|
||||
return "NAME:" in line
|
||||
|
||||
@classmethod
|
||||
def message_firmware_capability(cls, line, lower_line, state, flags):
|
||||
return lower_line.startswith("cap:")
|
||||
|
||||
@classmethod
|
||||
def message_sd_init_ok(cls, line, lower_line, state, flags):
|
||||
return "sd card ok" in lower_line
|
||||
|
||||
@classmethod
|
||||
def message_sd_init_fail(cls, line, lower_line, state, flags):
|
||||
return "sd init fail" in lower_line or "volume.init failed" in lower_line or "openroot failed" in lower_line
|
||||
|
||||
@classmethod
|
||||
def message_sd_file_opened(cls, line, lower_line, state, flags):
|
||||
return lower_line.startswith("file opened")
|
||||
|
||||
@classmethod
|
||||
def message_sd_file_selected(cls, line, lower_line, state, flags):
|
||||
return lower_line.startswith("file selected")
|
||||
|
||||
@classmethod
|
||||
def message_sd_begin_file_list(cls, line, lower_line, state, flags):
|
||||
return lower_line.startswith("begin file list")
|
||||
|
||||
@classmethod
|
||||
def message_sd_end_file_list(cls, line, lower_line, state, flags):
|
||||
return lower_line.startswith("end file list")
|
||||
|
||||
@classmethod
|
||||
def message_sd_printing_byte(cls, line, lower_line, state, flags):
|
||||
return "sd printing byte" in lower_line
|
||||
|
||||
@classmethod
|
||||
def message_sd_not_printing(cls, line, lower_line, state, flags):
|
||||
return "not sd printing" in lower_line
|
||||
|
||||
@classmethod
|
||||
def message_sd_done_printing(cls, line, lower_line, state, flags):
|
||||
return "done printing file" in lower_line
|
||||
|
||||
@classmethod
|
||||
def message_sd_begin_writing(cls, line, lower_line, state, flags):
|
||||
return "writing to file" in lower_line
|
||||
|
||||
@classmethod
|
||||
def message_sd_end_writing(cls, line, lower_line, state, flags):
|
||||
return "done saving file" in lower_line
|
||||
|
||||
@classmethod
|
||||
def message_sd_entry(cls, line, lower_line, state, flags):
|
||||
return flags["sd_files_temp"] is not None
|
||||
|
||||
##~~ Message parsers
|
||||
|
||||
@classmethod
|
||||
def parse_comm_error(cls, line, lower_line, state, flags):
|
||||
return dict(line=line, lower_line=lower_line)
|
||||
|
||||
@classmethod
|
||||
def parse_comm_timeout(cls, line, lower_line, state, flags):
|
||||
return dict(line=line, lower_line=lower_line)
|
||||
|
||||
@classmethod
|
||||
def parse_comm_action_command(cls, line, lower_line, state, flags):
|
||||
action = line[2:].strip()[len("action:"):].strip()
|
||||
return dict(line=line, lower_line=lower_line, action=action)
|
||||
|
||||
@classmethod
|
||||
def parse_error_communication(cls, line, lower_line, state, flags):
|
||||
if "line number" in lower_line or "expected line" in lower_line:
|
||||
error_type = "linenumber"
|
||||
elif "checksum" in lower_line:
|
||||
error_type = "checksum"
|
||||
else:
|
||||
error_type = "other"
|
||||
|
||||
flags["last_communication_error"] = error_type
|
||||
return dict(error_type=error_type)
|
||||
|
||||
@classmethod
|
||||
def parse_comm_resend(cls, line, lower_line, state, flags):
|
||||
line_to_resend = None
|
||||
match = cls.regex_resend_linenumber.search(line)
|
||||
if match is not None:
|
||||
line_to_resend = int(match.group("n"))
|
||||
return dict(linenumber=line_to_resend)
|
||||
|
||||
@classmethod
|
||||
def parse_message_temperature(cls, line, lower_line, state, flags):
|
||||
"""
|
||||
Parses the provided temperature line.
|
||||
|
||||
The result will be a dictionary mapping from the extruder or bed key to
|
||||
a tuple with current and target temperature. The result will be canonicalized
|
||||
with :func:`canonicalize_temperatures` before returning.
|
||||
|
||||
Returns:
|
||||
tuple: a 2-tuple with the maximum tool number and a dict mapping from
|
||||
key to (actual, target) tuples, with key either matching ``Tn`` for ``n >= 0`` or ``B``
|
||||
"""
|
||||
|
||||
current_tool = flags["current_tool"]
|
||||
|
||||
result = {}
|
||||
max_tool_num = 0
|
||||
for match in re.finditer(cls.regex_temp, line):
|
||||
values = match.groupdict()
|
||||
tool = values["tool"]
|
||||
if tool == "T" and "toolnum" in values and values["toolnum"]:
|
||||
tool_num = int(values["toolnum"])
|
||||
if tool_num > max_tool_num:
|
||||
max_tool_num = tool_num
|
||||
|
||||
try:
|
||||
actual = float(values.get("actual", None)) if values.get("actual", None) is not None else None
|
||||
target = float(values.get("target", None)) if values.get("target", None) is not None else None
|
||||
result[tool] = actual, target
|
||||
except ValueError:
|
||||
# catch conversion issues, we'll rather just not get the temperature update instead of killing the connection
|
||||
pass
|
||||
|
||||
heatup_detected = not lower_line.startswith("ok") and not flags["heating"] and not flags["temperature_autoreporting"]
|
||||
|
||||
return dict(max_tool_num=max(max_tool_num, current_tool),
|
||||
temperatures=cls._canonicalize_temperatures(result, current_tool),
|
||||
heatup_detected=heatup_detected)
|
||||
|
||||
@classmethod
|
||||
def parse_message_position(cls, line, lower_line, state, flags):
|
||||
position = dict(x=None, y=None, z=None, e=None)
|
||||
for match in re.finditer(cls.regex_position, line):
|
||||
position[match.group("axis").lower()] = float(match.group("pos"))
|
||||
return dict(position=position)
|
||||
|
||||
@classmethod
|
||||
def parse_message_firmware_info(cls, line, lower_line, state, flags):
|
||||
data = cls._parse_firmware_line(line)
|
||||
firmware_name = data.get("FIRMWARE_NAME")
|
||||
|
||||
if firmware_name is None:
|
||||
# Malyan's "Marlin compatible firmware" isn't actually Marlin compatible and doesn't even
|
||||
# report its firmware name properly in response to M115. Wonderful - why stick to established
|
||||
# protocol when you can do your own thing, right?
|
||||
#
|
||||
# Example: NAME: Malyan VER: 2.9 MODEL: M200 HW: HA02
|
||||
#
|
||||
# We do a bit of manual fiddling around here to circumvent that issue and get ourselves a
|
||||
# reliable firmware name (NAME + VER) out of the Malyan M115 response.
|
||||
name = data.get("NAME")
|
||||
ver = data.get("VER")
|
||||
if "malyan" in name.lower() and ver:
|
||||
firmware_name = name.strip() + " " + ver.strip()
|
||||
|
||||
if firmware_name is not None:
|
||||
firmware_name = firmware_name.strip()
|
||||
|
||||
return dict(firmware_name=firmware_name,
|
||||
data=data)
|
||||
|
||||
@classmethod
|
||||
def parse_message_firmware_capability(cls, line, lower_line, state, flags):
|
||||
result = cls._parse_capability_line(line)
|
||||
if not result:
|
||||
return
|
||||
cap, enabled = result
|
||||
return dict(cap=cap, enabled=enabled)
|
||||
|
||||
@classmethod
|
||||
def parse_message_sd_file_opened(cls, line, lower_line, state, flags):
|
||||
match = cls.regex_sd_file_opened.match(lower_line)
|
||||
if not match:
|
||||
return
|
||||
|
||||
name = match.group("name")
|
||||
size = int(match.group("size"))
|
||||
return dict(name=name, long_name=name, size=size)
|
||||
|
||||
@classmethod
|
||||
def parse_message_sd_entry(cls, line, lower_line, state, flags):
|
||||
fileinfo = lower_line.rsplit(None, 1)
|
||||
if len(fileinfo) > 1:
|
||||
# we might have extended file information here, so let's split filename and size and try to make them a bit nicer
|
||||
filename, size = fileinfo
|
||||
try:
|
||||
size = int(size)
|
||||
except ValueError:
|
||||
# whatever that was, it was not an integer, so we'll just use the whole line as filename and set size to None
|
||||
filename = lower_line
|
||||
size = None
|
||||
else:
|
||||
# no extended file information, so only the filename is there and we set size to None
|
||||
filename = lower_line
|
||||
size = None
|
||||
|
||||
from octoprint.util import filter_non_ascii
|
||||
|
||||
if filter_non_ascii(filename):
|
||||
return None
|
||||
else:
|
||||
if not filename.startswith("/"):
|
||||
# file from the root of the sd -- we'll prepend a /
|
||||
filename = "/" + filename
|
||||
|
||||
return dict(name=filename, long_name=filename, size=int(size) if size is not None else None)
|
||||
|
||||
@classmethod
|
||||
def parse_message_sd_printing_byte(cls, line, lower_line, state, flags):
|
||||
match = cls.regex_sd_printing_byte.match(lower_line)
|
||||
if not match:
|
||||
return None
|
||||
return dict(current=int(match.group("current")), total=int(match.group("total")))
|
||||
|
||||
##~~ Commands
|
||||
|
||||
@classmethod
|
||||
def command_hello(cls):
|
||||
return cls.command_set_line(0)
|
||||
|
||||
@classmethod
|
||||
def command_get_firmware_info(cls):
|
||||
return GcodeCommand("M115")
|
||||
|
||||
@classmethod
|
||||
def command_finish_moving(cls):
|
||||
return GcodeCommand("M400")
|
||||
|
||||
@classmethod
|
||||
def command_get_position(cls):
|
||||
return GcodeCommand("M114")
|
||||
|
||||
@classmethod
|
||||
def command_get_temp(cls):
|
||||
return GcodeCommand("M105")
|
||||
|
||||
@classmethod
|
||||
def command_set_line(cls, n):
|
||||
return GcodeCommand("M110", n=n)
|
||||
|
||||
@classmethod
|
||||
def command_emergency_stop(cls):
|
||||
return GcodeCommand("M112")
|
||||
|
||||
@classmethod
|
||||
def command_abort_heatup(cls):
|
||||
return GcodeCommand("M108")
|
||||
|
||||
@classmethod
|
||||
def command_set_extruder_temp(cls, temperature, tool=None, wait=False):
|
||||
command = "M109" if wait else "M104"
|
||||
args = dict(s=temperature)
|
||||
if tool is not None:
|
||||
args["t"] = tool
|
||||
return GcodeCommand(command, **args)
|
||||
|
||||
@classmethod
|
||||
def command_set_bed_temp(cls, temperature, wait=False):
|
||||
return GcodeCommand("M190" if wait else "M140", s=temperature)
|
||||
|
||||
@classmethod
|
||||
def command_set_chamber_temp(cls, temperature, wait=False):
|
||||
return GcodeCommand("M191" if wait else "M141", s=temperature)
|
||||
|
||||
@classmethod
|
||||
def command_set_relative_positioning(cls):
|
||||
return GcodeCommand("G91")
|
||||
|
||||
@classmethod
|
||||
def command_set_absolute_positioning(cls):
|
||||
return GcodeCommand("G90")
|
||||
|
||||
@classmethod
|
||||
def command_move(cls, x=None, y=None, z=None, e=None, f=None):
|
||||
return GcodeCommand("G1", x=x, y=y, z=z, e=e, f=f)
|
||||
|
||||
@classmethod
|
||||
def command_extrude(cls, e=None, f=None):
|
||||
return cls.command_move(e=e, f=f)
|
||||
|
||||
@classmethod
|
||||
def command_home(cls, x=False, y=False, z=False):
|
||||
return GcodeCommand("G28", x=0 if x else None, y=0 if y else None, z=0 if z else None)
|
||||
|
||||
@classmethod
|
||||
def command_set_tool(cls, tool):
|
||||
return GcodeCommand("T{}".format(tool))
|
||||
|
||||
@classmethod
|
||||
def command_set_feedrate_multiplier(cls, multiplier):
|
||||
return GcodeCommand("M220", s=multiplier)
|
||||
|
||||
@classmethod
|
||||
def command_set_extrusion_multiplier(cls, multiplier):
|
||||
return GcodeCommand("M221", s=multiplier)
|
||||
|
||||
@classmethod
|
||||
def command_set_fan_speed(cls, speed):
|
||||
return GcodeCommand("M106", s=speed)
|
||||
|
||||
@classmethod
|
||||
def command_set_motors(cls, enable):
|
||||
return GcodeCommand("M17") if enable else GcodeCommand("M18")
|
||||
|
||||
@classmethod
|
||||
def command_sd_refresh(cls):
|
||||
return GcodeCommand("M20")
|
||||
|
||||
@classmethod
|
||||
def command_sd_init(cls):
|
||||
return GcodeCommand("M21")
|
||||
|
||||
@classmethod
|
||||
def command_sd_release(cls):
|
||||
return GcodeCommand("M22")
|
||||
|
||||
@classmethod
|
||||
def command_sd_select_file(cls, name):
|
||||
return GcodeCommand("M23", param=name)
|
||||
|
||||
@classmethod
|
||||
def command_sd_start(cls):
|
||||
return GcodeCommand("M24")
|
||||
|
||||
@classmethod
|
||||
def command_sd_pause(cls):
|
||||
return GcodeCommand("M25")
|
||||
|
||||
@classmethod
|
||||
def command_sd_resume(cls):
|
||||
return GcodeCommand("M24")
|
||||
|
||||
@classmethod
|
||||
def command_sd_set_pos(cls, pos):
|
||||
return GcodeCommand("M26", s=pos)
|
||||
|
||||
@classmethod
|
||||
def command_sd_status(cls):
|
||||
return GcodeCommand("M27")
|
||||
|
||||
@classmethod
|
||||
def command_sd_begin_write(cls, name):
|
||||
return GcodeCommand("M28", param=name)
|
||||
|
||||
@classmethod
|
||||
def command_sd_end_write(cls):
|
||||
return GcodeCommand("M29")
|
||||
|
||||
@classmethod
|
||||
def command_sd_delete(cls, name):
|
||||
return GcodeCommand("M30", param=name)
|
||||
|
||||
@classmethod
|
||||
def command_autoreport_temperature(cls, interval):
|
||||
return GcodeCommand("M155", s=interval)
|
||||
|
||||
@classmethod
|
||||
def command_autoreport_sd_status(cls, interval):
|
||||
return GcodeCommand("M27", s=interval)
|
||||
|
||||
@classmethod
|
||||
def command_busy_protocol_interval(cls, interval):
|
||||
return GcodeCommand("M113", s=interval)
|
||||
|
||||
##~~ Helpers
|
||||
|
||||
@classmethod
|
||||
def _canonicalize_temperatures(cls, parsed, current):
|
||||
"""
|
||||
Canonicalizes the temperatures provided in parsed.
|
||||
|
||||
Will make sure that returned result only contains extruder keys
|
||||
like Tn, so always qualified with a tool number.
|
||||
|
||||
The algorithm for cleaning up the parsed keys is the following:
|
||||
|
||||
* If ``T`` is not included with the reported extruders, return
|
||||
* If more than just ``T`` is reported:
|
||||
* If both ``T`` and ``T0`` are reported set ``Tc`` to ``T``, remove
|
||||
``T`` from the result.
|
||||
* Else set ``T0`` to ``T`` and delete ``T`` (Smoothie extra).
|
||||
* If only ``T`` is reported, set ``Tc`` to ``T`` and delete ``T``
|
||||
* return
|
||||
|
||||
Arguments:
|
||||
parsed (dict): the parsed temperatures (mapping tool => (actual, target))
|
||||
to canonicalize
|
||||
current (int): the current active extruder
|
||||
Returns:
|
||||
dict: the canonicalized version of ``parsed``
|
||||
"""
|
||||
|
||||
reported_extruders = list(filter(lambda x: x.startswith("T"), parsed.keys()))
|
||||
if not "T" in reported_extruders:
|
||||
# Our reported_extruders are either empty or consist purely
|
||||
# of Tn keys, no need for any action
|
||||
return parsed
|
||||
|
||||
current_tool_key = "T%d" % current
|
||||
result = dict(parsed)
|
||||
|
||||
if len(reported_extruders) > 1:
|
||||
if "T0" in reported_extruders:
|
||||
# Both T and T0 are present, so T contains the current
|
||||
# extruder's temperature, e.g. for current_tool == 1:
|
||||
#
|
||||
# T:<T1> T0:<T0> T2:<T2> ... B:<B>
|
||||
#
|
||||
# becomes
|
||||
#
|
||||
# T0:<T1> T1:<T1> T2:<T2> ... B:<B>
|
||||
#
|
||||
# Same goes if Tc is already present, it will be overwritten:
|
||||
#
|
||||
# T:<T1> T0:<T0> T1:<T1> T2:<T2> ... B:<B>
|
||||
#
|
||||
# becomes
|
||||
#
|
||||
# T0:<T0> T1:<T1> T2:<T2> ... B:<B>
|
||||
result[current_tool_key] = result["T"]
|
||||
del result["T"]
|
||||
else:
|
||||
# So T is there, but T0 isn't. That looks like Smoothieware which
|
||||
# always reports the first extruder T0 as T:
|
||||
#
|
||||
# T:<T0> T1:<T1> T2:<T2> ... B:<B>
|
||||
#
|
||||
# becomes
|
||||
#
|
||||
# T0:<T0> T1:<T1> T2:<T2> ... B:<B>
|
||||
result["T0"] = result["T"]
|
||||
del result["T"]
|
||||
|
||||
else:
|
||||
# We only have T. That can mean two things:
|
||||
#
|
||||
# * we only have one extruder at all, or
|
||||
# * we are currently parsing a response to M109/M190, which on
|
||||
# some firmwares doesn't report the full M105 output while
|
||||
# waiting for the target temperature to be reached but only
|
||||
# reports the current tool and bed
|
||||
#
|
||||
# In both cases it is however safe to just move our T over
|
||||
# to T<current> in the parsed data, current should always stay
|
||||
# 0 for single extruder printers. E.g. for current_tool == 1:
|
||||
#
|
||||
# T:<T1>
|
||||
#
|
||||
# becomes
|
||||
#
|
||||
# T1:<T1>
|
||||
|
||||
result[current_tool_key] = result["T"]
|
||||
del result["T"]
|
||||
|
||||
return result
|
||||
|
||||
@classmethod
|
||||
def _parse_firmware_line(cls, line):
|
||||
"""
|
||||
Parses the provided firmware info line.
|
||||
|
||||
The result will be a dictionary mapping from the contained keys to the contained
|
||||
values.
|
||||
|
||||
Arguments:
|
||||
line (unicode): the line to parse
|
||||
|
||||
Returns:
|
||||
dict: a dictionary with the parsed data
|
||||
"""
|
||||
|
||||
result = dict()
|
||||
split_line = cls.regex_firmware_splitter.split(line.strip())[1:] # first entry is empty start of trimmed string
|
||||
for key, value in chunks(split_line, 2):
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
@classmethod
|
||||
def _parse_capability_line(cls, line):
|
||||
"""
|
||||
Parses the provided firmware capability line.
|
||||
|
||||
Lines are expected to be of the format
|
||||
|
||||
Cap:<capability name in caps>:<0 or 1>
|
||||
|
||||
e.g.
|
||||
|
||||
Cap:AUTOREPORT_TEMP:1
|
||||
Cap:TOGGLE_LIGHTS:0
|
||||
|
||||
Args:
|
||||
line (unicode): the line to parse
|
||||
|
||||
Returns:
|
||||
tuple: a 2-tuple of the parsed capability name and whether it's on (true) or off (false), or None if the line
|
||||
could not be parsed
|
||||
"""
|
||||
|
||||
line = line.lower()
|
||||
if line.startswith("cap:"):
|
||||
line = line[len("cap:"):]
|
||||
|
||||
parts = line.split(":")
|
||||
if len(parts) != 2:
|
||||
# wrong format, can't parse this
|
||||
return None
|
||||
|
||||
capability, flag = parts
|
||||
if not flag in ("0", "1"):
|
||||
# wrong format, can't parse this
|
||||
return None
|
||||
|
||||
return capability.upper(), flag == "1"
|
||||
@@ -1,19 +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"
|
||||
|
||||
from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor
|
||||
|
||||
class ReprapFirmwareFlavor(GenericFlavor):
|
||||
|
||||
key = "klipper"
|
||||
name = "Klipper"
|
||||
|
||||
unknown_requires_ack = True
|
||||
|
||||
@classmethod
|
||||
def identifier(cls, firmware_name, firmware_info):
|
||||
return "klipper" in firmware_name.lower()
|
||||
|
||||
@@ -1,21 +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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor
|
||||
|
||||
class MalyanFlavor(GenericFlavor):
|
||||
|
||||
key = "malyan"
|
||||
name = "Malyan"
|
||||
|
||||
always_send_checksum = False
|
||||
block_while_dwelling = True
|
||||
sd_always_available = True
|
||||
|
||||
@classmethod
|
||||
def identifier(cls, firmware_name, firmware_info):
|
||||
return "malyan" in firmware_name.lower()
|
||||
|
||||
@@ -1,35 +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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor
|
||||
|
||||
class MarlinFlavor(GenericFlavor):
|
||||
|
||||
key = "marlin"
|
||||
name = "Marlin"
|
||||
|
||||
emergency_commands = ["M112", "M108", "M410"]
|
||||
heatup_abortable = True
|
||||
|
||||
|
||||
class MarlinLegacyFlavor(GenericFlavor):
|
||||
|
||||
key = "marlinlegacy"
|
||||
name = "Legacy Marlin"
|
||||
|
||||
@classmethod
|
||||
def identifier(cls, firmware_name, firmware_info):
|
||||
return "marlin v1" in firmware_name.lower()
|
||||
|
||||
|
||||
class PrusaMarlinFlavor(MarlinFlavor):
|
||||
|
||||
key = "prusamarlin"
|
||||
name = "Marlin: Prusa variant"
|
||||
|
||||
@classmethod
|
||||
def identifier(cls, firmware_name, firmware_info):
|
||||
return "prusa-firmware" in firmware_name.lower() and "marlin" in firmware_name.lower()
|
||||
@@ -1,94 +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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from octoprint.comm.protocol.reprap.flavors import GenericFlavor
|
||||
|
||||
from octoprint.comm.protocol.reprap.util import regex_positive_float_pattern
|
||||
|
||||
import re
|
||||
|
||||
class RepetierFlavor(GenericFlavor):
|
||||
|
||||
key = "repetier"
|
||||
name = "Repetier"
|
||||
|
||||
always_send_checksum = True
|
||||
identical_resends_countdown = 5
|
||||
block_while_dwelling = True
|
||||
detect_external_heatups = False
|
||||
|
||||
regex_tempextr = re.compile("targetextr(?P<toolnum>\d+):(?P<target>%s)" % regex_positive_float_pattern)
|
||||
"""Regex for matching target temp reporting from Repetier.
|
||||
|
||||
Groups will be as follows:
|
||||
|
||||
* ``toolnum``: number of the extruder to which the target temperature
|
||||
report belongs (int)
|
||||
* ``target``: new target temperature (float)
|
||||
"""
|
||||
|
||||
regex_tempbed = re.compile("targetbed:(?P<target>%s)" % regex_positive_float_pattern)
|
||||
"""Regex for matching target temp reporting from Repetier for beds.
|
||||
|
||||
Groups will be as follows:
|
||||
|
||||
* ``target``: new target temperature (float)
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def identifier(cls, firmware_name, firmware_info):
|
||||
return "repetier" in firmware_name.lower()
|
||||
|
||||
@classmethod
|
||||
def message_temperature(cls, line, lower_line, state, flags):
|
||||
return GenericFlavor.message_temperature(line, lower_line, state, flags) or "targetextr" in lower_line or "targetbed" in lower_line
|
||||
|
||||
@classmethod
|
||||
def parse_message_temperature(cls, line, lower_line, state, flags):
|
||||
if "targetextr" in lower_line:
|
||||
match = cls.regex_tempextr.match(lower_line)
|
||||
if match is not None:
|
||||
tool_num = int(match.group("toolnum"))
|
||||
target = float(match.group("target"))
|
||||
tool = "T{}".format(tool_num)
|
||||
temperatures = dict()
|
||||
temperatures[tool] = (None, target)
|
||||
return dict(max_tool_num=max(tool_num, flags.get("current_tool", 0)),
|
||||
temperatures=temperatures,
|
||||
heatup_detected=False)
|
||||
elif "targetbed" in lower_line:
|
||||
match = cls.regex_tempbed.match(lower_line)
|
||||
if match is not None:
|
||||
target = float(match.group("target"))
|
||||
temperatures = dict(bed=(None, target))
|
||||
return dict(max_tool_num=flags.get("current_tool", 0),
|
||||
temperatures=temperatures,
|
||||
heatup_detected=False)
|
||||
else:
|
||||
# Repetier sends temperature output on it's own line, so we can't use the
|
||||
# "no ok in temperature output" metric to detected external heatups
|
||||
result = GenericFlavor.parse_message_temperature(line, lower_line, state, flags)
|
||||
result[b"heatup_detected"] = False
|
||||
return result
|
||||
|
||||
|
||||
##~~ Preprocessors, returning True stops further processing by the protocol
|
||||
|
||||
@classmethod
|
||||
def preprocess_comm_resend(cls, linenumber, state, flags):
|
||||
if flags.get("resend_swallow_repetitions", False) \
|
||||
and flags.get("resend_swallow_repetitions_counter", 0) \
|
||||
and linenumber == flags["resend_requested"] \
|
||||
and flags["resend_swallow_repetitions_counter"] > 0:
|
||||
cls.logger.debug("Ignoring resend request for line {}, that is "
|
||||
"probably a repetition sent by the firmware to "
|
||||
"ensure it arrives, not a real request"
|
||||
.format(linenumber))
|
||||
flags["resend_swallow_repetitions_counter"] -= 1
|
||||
return True
|
||||
|
||||
flags["resend_swallow_repetitions_counter"] = cls.identical_resends_countdown
|
||||
|
||||
@@ -1,19 +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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor
|
||||
|
||||
class ReprapFirmwareFlavor(GenericFlavor):
|
||||
|
||||
key = "reprapfirmware"
|
||||
name = "RepRapFirmware"
|
||||
|
||||
sd_relative_path = True
|
||||
|
||||
@classmethod
|
||||
def identifier(cls, firmware_name, firmware_info):
|
||||
return "reprapfirmware" in firmware_name.lower()
|
||||
|
||||
@@ -1,13 +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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor
|
||||
|
||||
class ReprapFirmwareFlavor(GenericFlavor):
|
||||
|
||||
key = "smoothieware"
|
||||
name = "Smoothieware"
|
||||
|
||||
@@ -1,25 +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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from octoprint.comm.scripts import Script, UnknownScript
|
||||
from octoprint.comm.protocol.reprap.util import process_gcode_line
|
||||
|
||||
class GcodeScript(Script):
|
||||
|
||||
def __init__(self, settings, name, context=None):
|
||||
def renderer(ctx):
|
||||
lines = settings.loadScript("gcode", name, context=ctx)
|
||||
if lines is None:
|
||||
raise UnknownScript(name)
|
||||
return lines
|
||||
|
||||
super(GcodeScript, self).__init__(name, renderer, context=context)
|
||||
|
||||
def render(self, context=None):
|
||||
script = super(GcodeScript, self).render(context)
|
||||
return list(filter(lambda x: x is not None and x.strip() != "",
|
||||
map(lambda x: process_gcode_line(x),
|
||||
script)))
|
||||
@@ -1,398 +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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from octoprint.comm.protocol.reprap.commands import Command, to_command
|
||||
from octoprint.util import PrependableQueue, TypeAlreadyInQueue, CountedEvent
|
||||
|
||||
# noinspection PyCompatibility
|
||||
from past.builtins import basestring
|
||||
|
||||
import contextlib
|
||||
import copy
|
||||
import logging
|
||||
import threading
|
||||
|
||||
try:
|
||||
# noinspection PyCompatibility
|
||||
import queue
|
||||
except Exception:
|
||||
# noinspection PyCompatibility
|
||||
import Queue as queue
|
||||
|
||||
regex_float_pattern = "[-+]?[0-9]*\.?[0-9]+"
|
||||
regex_positive_float_pattern = "[+]?[0-9]*\.?[0-9]+"
|
||||
regex_int_pattern = "\d+"
|
||||
|
||||
|
||||
def strip_comment(line):
|
||||
if not ";" in line:
|
||||
# shortcut
|
||||
return line
|
||||
|
||||
escaped = False
|
||||
result = []
|
||||
for c in line:
|
||||
if c == ";" and not escaped:
|
||||
break
|
||||
result += c
|
||||
escaped = (c == "\\") and not escaped
|
||||
return "".join(result).strip()
|
||||
|
||||
|
||||
def process_gcode_line(line, offsets=None, current_tool=None):
|
||||
line = strip_comment(line).strip()
|
||||
if not len(line):
|
||||
return None
|
||||
|
||||
# if offsets is not None:
|
||||
# line = apply_temperature_offsets(line, offsets, current_tool=current_tool)
|
||||
|
||||
return line
|
||||
|
||||
|
||||
def normalize_command_handler_result(command, handler_results, tags_to_add=None):
|
||||
"""
|
||||
Normalizes a command handler result.
|
||||
|
||||
Handler results can be either ``None``, a single result entry or a list of result
|
||||
entries.
|
||||
|
||||
``None`` results are ignored, the provided ``command``, ``command_type``,
|
||||
``gcode``, ``subcode`` and ``tags`` are returned in that case (as single-entry list with
|
||||
one 5-tuple as entry).
|
||||
|
||||
Single result entries are either:
|
||||
|
||||
* a single string defining a replacement ``command``
|
||||
* a 1-tuple defining a replacement ``command``
|
||||
* a 2-tuple defining a replacement ``command`` and ``command_type``
|
||||
* a 3-tuple defining a replacement ``command`` and ``command_type`` and additional ``tags`` to set
|
||||
|
||||
A ``command`` that is ``None`` will lead to the entry being ignored for
|
||||
the normalized result.
|
||||
|
||||
The method returns a list of normalized result entries. Normalized result
|
||||
entries always are a 4-tuple consisting of ``command``, ``command_type``,
|
||||
``gcode`` and ``subcode``, the latter three being allowed to be ``None``. The list may
|
||||
be empty in which case the command is to be suppressed.
|
||||
|
||||
Examples:
|
||||
>>> from octoprint.comm.protocol.reprap.commands.gcode import GcodeCommand
|
||||
>>> normalize_command_handler_result(GcodeCommand("M105"), None) # doctest: +ALLOW_UNICODE
|
||||
[GcodeCommand('M105',type=None,tags=set())]
|
||||
>>> normalize_command_handler_result(GcodeCommand("M105"), GcodeCommand("M110")) # doctest: +ALLOW_UNICODE
|
||||
[GcodeCommand('M110',type=None,tags=set())]
|
||||
>>> normalize_command_handler_result(GcodeCommand("M105"), ["M110"]) # doctest: +ALLOW_UNICODE
|
||||
[GcodeCommand('M110',original='M110',type=None,tags=set())]
|
||||
>>> normalize_command_handler_result(GcodeCommand("M105"), ["M110", "M117 Foobar"]) # doctest: +ALLOW_UNICODE
|
||||
[GcodeCommand('M110',original='M110',type=None,tags=set()), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags=set())]
|
||||
>>> normalize_command_handler_result(GcodeCommand("M105"), [("M110",), "M117 Foobar"]) # doctest: +ALLOW_UNICODE
|
||||
[GcodeCommand('M110',original='M110',type=None,tags=set()), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags=set())]
|
||||
>>> normalize_command_handler_result(GcodeCommand("M105"), [("M110", "lineno_reset"), "M117 Foobar"]) # doctest: +ALLOW_UNICODE
|
||||
[GcodeCommand('M110',original='M110',type='lineno_reset',tags=set()), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags=set())]
|
||||
>>> normalize_command_handler_result(GcodeCommand("M105"), []) # doctest: +ALLOW_UNICODE
|
||||
[]
|
||||
>>> normalize_command_handler_result(GcodeCommand("M105"), ["M110", None]) # doctest: +ALLOW_UNICODE
|
||||
[GcodeCommand('M110',original='M110',type=None,tags=set())]
|
||||
>>> normalize_command_handler_result(GcodeCommand("M105"), [("M110",), (None, "ignored")]) # doctest: +ALLOW_UNICODE
|
||||
[GcodeCommand('M110',original='M110',type=None,tags=set())]
|
||||
>>> normalize_command_handler_result(GcodeCommand("M105"), [("M110",), ("M117 Foobar", "display_message"), ("tuple", "of", "unexpected", "length"), ("M110", "lineno_reset")]) # doctest: +ALLOW_UNICODE
|
||||
[GcodeCommand('M110',original='M110',type=None,tags=set()), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type='display_message',tags=set()), GcodeCommand('M110',original='M110',type='lineno_reset',tags=set())]
|
||||
>>> normalize_command_handler_result(GcodeCommand("M105",tags={"tag1", "tag2"}), ["M110", "M117 Foobar"]) # doctest: +ALLOW_UNICODE
|
||||
[GcodeCommand('M110',original='M110',type=None,tags={'tag1', 'tag2'}), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags={'tag1', 'tag2'})]
|
||||
>>> normalize_command_handler_result(GcodeCommand("M105",tags={"tag1", "tag2"}), ["M110", "M117 Foobar"], tags_to_add={"tag3"}) # doctest: +ALLOW_UNICODE
|
||||
[GcodeCommand('M110',original='M110',type=None,tags={'tag1', 'tag2', 'tag3'}), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags={'tag1', 'tag2', 'tag3'})]
|
||||
|
||||
Arguments:
|
||||
command (Command): The command for which the handler result was
|
||||
generated
|
||||
handler_results: The handler result(s) to normalized. Can be either
|
||||
a single result entry or a list of result entries.
|
||||
tags_to_add (set of unicode or None): List of tags to add to expanded result
|
||||
entries
|
||||
|
||||
Returns:
|
||||
(list) - A list of normalized handler result entries, which are
|
||||
``Command`` instances
|
||||
"""
|
||||
|
||||
original = command
|
||||
|
||||
if handler_results is None:
|
||||
# handler didn't return anything, we'll just continue
|
||||
return [original]
|
||||
|
||||
if not isinstance(handler_results, list):
|
||||
handler_results = [handler_results, ]
|
||||
|
||||
result = []
|
||||
for handler_result in handler_results:
|
||||
# we iterate over all handler result entries and process each one
|
||||
# individually here
|
||||
|
||||
if handler_result is None:
|
||||
# entry is None, we'll ignore that entry and continue
|
||||
continue
|
||||
|
||||
def expand_tags(tags, tags_to_add):
|
||||
tags = tags.copy()
|
||||
if tags_to_add and isinstance(tags_to_add, set):
|
||||
tags |= tags_to_add
|
||||
return tags
|
||||
|
||||
if isinstance(handler_result, basestring):
|
||||
# entry is just a string, replace command with it
|
||||
if handler_result != original.line:
|
||||
# command changed, swap it
|
||||
command = to_command(handler_result,
|
||||
type=original.type,
|
||||
tags=expand_tags(original.tags, tags_to_add))
|
||||
result.append(command)
|
||||
|
||||
elif isinstance(handler_result, Command):
|
||||
if handler_result != original:
|
||||
command = copy.copy(handler_result)
|
||||
command.tags = expand_tags(original.tags, tags_to_add)
|
||||
result.append(command)
|
||||
|
||||
elif isinstance(handler_result, tuple):
|
||||
# entry is a tuple, extract command and command_type
|
||||
hook_result_length = len(handler_result)
|
||||
|
||||
command_type = original.type
|
||||
command_tags = original.tags
|
||||
|
||||
if hook_result_length == 1:
|
||||
# handler returned just the command
|
||||
command_line, = handler_result
|
||||
elif hook_result_length == 2:
|
||||
# handler returned command and command_type
|
||||
command_line, command_type = handler_result
|
||||
elif hook_result_length == 3:
|
||||
# handler returned command, command type and additional tags
|
||||
command_line, command_type, command_tags = handler_result
|
||||
else:
|
||||
# handler returned a tuple of an unexpected length, ignore
|
||||
# and continue
|
||||
continue
|
||||
|
||||
if command_line is None:
|
||||
# command is None, ignore it and continue
|
||||
continue
|
||||
|
||||
if command_line != original.line or command_type != original.type:
|
||||
# command or command_type changed, tags need to be rewritten
|
||||
command_tags = expand_tags(command_tags, tags_to_add)
|
||||
|
||||
result.append(to_command(command_line, type=command_type, tags=command_tags))
|
||||
|
||||
# reset to original
|
||||
command = original
|
||||
|
||||
return result
|
||||
|
||||
|
||||
class SendToken(CountedEvent):
|
||||
|
||||
def __init__(self, value=0, maximum=None, **kwargs):
|
||||
super(SendToken, self).__init__(value=value, maximum=maximum, **kwargs)
|
||||
self._ignored = 0
|
||||
|
||||
def set(self, ignore=False):
|
||||
with self._mutex:
|
||||
if ignore:
|
||||
self._ignored += 1
|
||||
self._internal_set(self._counter + 1)
|
||||
|
||||
def clear(self, completely=False):
|
||||
with self._mutex:
|
||||
if completely:
|
||||
self._internal_set(0)
|
||||
self._ignored = 0
|
||||
else:
|
||||
if self._ignored > 0:
|
||||
self._ignored -= 1
|
||||
self._internal_set(self._counter - 1)
|
||||
self._internal_set(self._counter - 1)
|
||||
|
||||
|
||||
class LineHistory(object):
|
||||
def __init__(self, max=None):
|
||||
self.max = max
|
||||
|
||||
self._lines = []
|
||||
self._mutex = threading.RLock()
|
||||
self._line_number_lookup = dict()
|
||||
|
||||
@property
|
||||
def lines(self):
|
||||
with self._mutex:
|
||||
return [x[0] for x in self._lines]
|
||||
|
||||
def append(self, line, line_number=None):
|
||||
with self._mutex:
|
||||
self._lines.append((line, line_number))
|
||||
if line_number is not None:
|
||||
self._line_number_lookup[line_number] = line
|
||||
self._cleanup()
|
||||
|
||||
def clear(self):
|
||||
with self._mutex:
|
||||
self._lines = []
|
||||
self._line_number_lookup = dict()
|
||||
|
||||
def __len__(self):
|
||||
with self._mutex:
|
||||
return len(self._lines)
|
||||
|
||||
def __getitem__(self, line_number):
|
||||
with self._mutex:
|
||||
return self._line_number_lookup[line_number]
|
||||
|
||||
def __contains__(self, line_number):
|
||||
with self._mutex:
|
||||
return line_number in self._line_number_lookup
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self.lines)
|
||||
|
||||
def _cleanup(self):
|
||||
if len(self._lines) <= self.max:
|
||||
return
|
||||
|
||||
while len(self._lines) > self.max:
|
||||
_, line_number = self._lines.pop(0)
|
||||
if line_number is not None:
|
||||
try:
|
||||
del self._line_number_lookup[line_number]
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
|
||||
class PositionRecord(object):
|
||||
_standard_attrs = {"x", "y", "z", "e", "f", "t"}
|
||||
|
||||
@classmethod
|
||||
def valid_e(cls, attr):
|
||||
if not attr.startswith("e"):
|
||||
return False
|
||||
|
||||
try:
|
||||
int(attr[1:])
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
attrs = self._standard_attrs | set([key for key in kwargs if self.valid_e(key)])
|
||||
for attr in attrs:
|
||||
setattr(self, attr, kwargs.get(attr))
|
||||
|
||||
def copy_from(self, other):
|
||||
# make sure all standard attrs and attrs from other are set
|
||||
attrs = self._standard_attrs | set([key for key in dir(other) if self.valid_e(key)])
|
||||
for attr in attrs:
|
||||
setattr(self, attr, getattr(other, attr))
|
||||
|
||||
# delete attrs other doesn't have
|
||||
attrs = set([key for key in dir(self) if self.valid_e(key)]) - attrs
|
||||
for attr in attrs:
|
||||
delattr(self, attr)
|
||||
|
||||
def as_dict(self):
|
||||
attrs = self._standard_attrs | set([key for key in dir(self) if self.valid_e(key)])
|
||||
return dict((attr, getattr(self, attr)) for attr in attrs)
|
||||
|
||||
|
||||
class TemperatureRecord(object):
|
||||
def __init__(self):
|
||||
self._tools = dict()
|
||||
self._bed = (None, None)
|
||||
self._chamber = (None, None)
|
||||
|
||||
def copy_from(self, other):
|
||||
self._tools = other.tools
|
||||
self._bed = other.bed
|
||||
self._chamber = other.chamber
|
||||
|
||||
def set_tool(self, tool, actual=None, target=None):
|
||||
current = self._tools.get(tool, (None, None))
|
||||
self._tools[tool] = self._to_new_tuple(current, actual, target)
|
||||
|
||||
def set_bed(self, actual=None, target=None):
|
||||
current = self._bed
|
||||
self._bed = self._to_new_tuple(current, actual, target)
|
||||
|
||||
def set_chamber(self, actual=None, target=None):
|
||||
current = self._chamber()
|
||||
self._chamber = self._to_new_tuple(current, actual, target)
|
||||
|
||||
@property
|
||||
def tools(self):
|
||||
return dict(self._tools)
|
||||
|
||||
@property
|
||||
def bed(self):
|
||||
return self._bed
|
||||
|
||||
@property
|
||||
def chamber(self):
|
||||
return self._chamber
|
||||
|
||||
def as_dict(self):
|
||||
result = dict()
|
||||
|
||||
tools = self.tools
|
||||
for tool, data in tools.items():
|
||||
result["tool{}".format(tool)] = dict(actual=data[0],
|
||||
target=data[1])
|
||||
|
||||
bed = self.bed
|
||||
result["bed"] = dict(actual=bed[0],
|
||||
target=bed[1])
|
||||
|
||||
chamber = self.chamber
|
||||
result["chamber"] = dict(actual=chamber[0],
|
||||
target=chamber[1])
|
||||
|
||||
return result
|
||||
|
||||
def as_script_dict(self):
|
||||
result = self.as_dict()
|
||||
|
||||
# backwards compatibility
|
||||
tools = self.tools
|
||||
for tool, data in tools.items():
|
||||
result[tool] = dict(actual=data[0],
|
||||
target=data[1])
|
||||
|
||||
bed = self.bed
|
||||
result["b"] = dict(actual=bed[0],
|
||||
target=bed[1])
|
||||
|
||||
chamber = self.chamber
|
||||
result["c"] = dict(actual=chamber[0],
|
||||
target=chamber[1])
|
||||
|
||||
return result
|
||||
|
||||
@classmethod
|
||||
def _to_new_tuple(cls, current, actual, target):
|
||||
if current is None or not isinstance(current, tuple) or len(current) != 2:
|
||||
current = (None, None)
|
||||
|
||||
if actual is None and target is None:
|
||||
return current
|
||||
|
||||
old_actual, old_target = current
|
||||
|
||||
if actual is None:
|
||||
return old_actual, target
|
||||
elif target is None:
|
||||
return actual, old_target
|
||||
else:
|
||||
return actual, target
|
||||
@@ -1,194 +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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from octoprint.util import PrependableQueue, TypedQueue, TypeAlreadyInQueue
|
||||
|
||||
try:
|
||||
import queue
|
||||
except ImportError:
|
||||
import Queue as queue
|
||||
|
||||
|
||||
import contextlib
|
||||
import logging
|
||||
import threading
|
||||
|
||||
|
||||
class ScriptQueue(PrependableQueue):
|
||||
pass
|
||||
|
||||
|
||||
class JobQueue(PrependableQueue):
|
||||
pass
|
||||
|
||||
|
||||
class CommandQueue(TypedQueue):
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
TypedQueue.__init__(self, *args, **kwargs)
|
||||
self._unblocked = threading.Event()
|
||||
self._unblocked.set()
|
||||
|
||||
def block(self):
|
||||
self._unblocked.clear()
|
||||
|
||||
def unblock(self):
|
||||
self._unblocked.set()
|
||||
|
||||
@contextlib.contextmanager
|
||||
def blocked(self):
|
||||
self.block()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
self.unblock()
|
||||
|
||||
def get(self, *args, **kwargs):
|
||||
self._unblocked.wait()
|
||||
return TypedQueue.get(self, *args, **kwargs)
|
||||
|
||||
def put(self, *args, **kwargs):
|
||||
self._unblocked.wait()
|
||||
return TypedQueue.put(self, *args, **kwargs)
|
||||
|
||||
def clear(self):
|
||||
cleared = []
|
||||
while True:
|
||||
try:
|
||||
cleared.append(TypedQueue.get(self, False))
|
||||
TypedQueue.task_done(self)
|
||||
except queue.Empty:
|
||||
break
|
||||
return cleared
|
||||
|
||||
|
||||
class SendQueue(PrependableQueue):
|
||||
|
||||
def __init__(self, maxsize=0):
|
||||
PrependableQueue.__init__(self, maxsize=maxsize)
|
||||
|
||||
self._unblocked = threading.Event()
|
||||
self._unblocked.set()
|
||||
|
||||
self._resend_queue = PrependableQueue()
|
||||
self._send_queue = PrependableQueue()
|
||||
self._lookup = set()
|
||||
|
||||
self._resend_active = False
|
||||
|
||||
@property
|
||||
def resend_active(self):
|
||||
return self._resend_active
|
||||
|
||||
@resend_active.setter
|
||||
def resend_active(self, resend_active):
|
||||
with self.mutex:
|
||||
self._resend_active = resend_active
|
||||
|
||||
def block(self):
|
||||
self._unblocked.clear()
|
||||
|
||||
def unblock(self):
|
||||
self._unblocked.set()
|
||||
|
||||
@contextlib.contextmanager
|
||||
def blocked(self):
|
||||
self.block()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
self.unblock()
|
||||
|
||||
def prepend(self, item, item_type=None, target=None, block=True, timeout=None):
|
||||
self._unblocked.wait()
|
||||
PrependableQueue.prepend(self, (item, item_type, target), block=block, timeout=timeout)
|
||||
|
||||
def put(self, item, item_type=None, target=None, block=True, timeout=None):
|
||||
self._unblocked.wait()
|
||||
PrependableQueue.put(self, (item, item_type, target), block=block, timeout=timeout)
|
||||
|
||||
def get(self, block=True, timeout=None):
|
||||
self._unblocked.wait()
|
||||
item, _, _ = PrependableQueue.get(self, block=block, timeout=timeout)
|
||||
return item
|
||||
|
||||
def clear(self):
|
||||
cleared = []
|
||||
while True:
|
||||
try:
|
||||
cleared.append(PrependableQueue.get(self, False))
|
||||
PrependableQueue.task_done(self)
|
||||
except queue.Empty:
|
||||
break
|
||||
return cleared
|
||||
|
||||
def _put(self, item):
|
||||
_, item_type, target = item
|
||||
if item_type is not None:
|
||||
if item_type in self._lookup:
|
||||
raise TypeAlreadyInQueue(item_type, "Type {} is already in queue".format(item_type))
|
||||
else:
|
||||
self._lookup.add(item_type)
|
||||
|
||||
if target == "resend":
|
||||
self._resend_queue.put(item)
|
||||
else:
|
||||
self._send_queue.put(item)
|
||||
|
||||
def _prepend(self, item):
|
||||
_, item_type, target = item
|
||||
if item_type is not None:
|
||||
if item_type in self._lookup:
|
||||
raise TypeAlreadyInQueue(item_type, "Type {} is already in queue".format(item_type))
|
||||
else:
|
||||
self._lookup.add(item_type)
|
||||
|
||||
if target == "resend":
|
||||
self._resend_queue.prepend(item)
|
||||
else:
|
||||
self._send_queue.prepend(item)
|
||||
|
||||
def _get(self):
|
||||
if self.resend_active:
|
||||
item = self._resend_queue.get(block=False)
|
||||
else:
|
||||
try:
|
||||
item = self._resend_queue.get(block=False)
|
||||
except queue.Empty:
|
||||
item = self._send_queue.get(block=False)
|
||||
|
||||
_, item_type, _ = item
|
||||
if item_type is not None:
|
||||
if item_type in self._lookup:
|
||||
self._lookup.remove(item_type)
|
||||
|
||||
return item
|
||||
|
||||
def _qsize(self, len=len):
|
||||
if self.resend_active:
|
||||
return self._resend_queue.qsize()
|
||||
else:
|
||||
return self._resend_queue.qsize() + self._send_queue.qsize()
|
||||
|
||||
|
||||
class QueueMarker(object):
|
||||
|
||||
def __init__(self, callback):
|
||||
self.callback = callback
|
||||
|
||||
def run(self):
|
||||
if callable(self.callback):
|
||||
try:
|
||||
self.callback()
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Error while running callback of QueueMarker")
|
||||
|
||||
|
||||
class SendQueueMarker(QueueMarker):
|
||||
pass
|
||||
|
||||
|
||||
|
||||
@@ -1,37 +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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
class Script(object):
|
||||
|
||||
def __init__(self, name, renderer, context=None):
|
||||
if context is None:
|
||||
context = dict()
|
||||
|
||||
self.name = name
|
||||
self.renderer = renderer
|
||||
self.context = context
|
||||
|
||||
def render(self, context=None):
|
||||
if context is None:
|
||||
context = dict()
|
||||
|
||||
render_context = dict(self.context)
|
||||
render_context.update(context)
|
||||
|
||||
content = self.renderer(render_context)
|
||||
if content is None:
|
||||
return None
|
||||
|
||||
return content.split("\n")
|
||||
|
||||
|
||||
class UnknownScript(Exception):
|
||||
def __init__(self, name, *args, **kwargs):
|
||||
self.name = name
|
||||
|
||||
|
||||
class InvalidScript(Exception):
|
||||
pass
|
||||
@@ -1,350 +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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from octoprint.comm.util.parameters import get_param_dict
|
||||
|
||||
import copy
|
||||
import logging
|
||||
import time
|
||||
|
||||
from octoprint.util import monotonic_time
|
||||
from octoprint.util.listener import ListenerAware
|
||||
from octoprint.plugin import plugin_manager
|
||||
from octoprint.settings import SubSettings
|
||||
|
||||
_registry = dict()
|
||||
|
||||
def register_transports():
|
||||
from .serialtransport import SerialTransport
|
||||
from .sockettransport import TcpTransport, SerialOverTcpTransport
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# stock transports
|
||||
register_transport(SerialTransport)
|
||||
register_transport(TcpTransport)
|
||||
register_transport(SerialOverTcpTransport)
|
||||
|
||||
# more transports provided by plugins
|
||||
hooks = plugin_manager().get_hooks("octoprint.comm.transport.register")
|
||||
for name, hook in hooks.items():
|
||||
try:
|
||||
transports = hook()
|
||||
for transport in transports:
|
||||
try:
|
||||
register_transport(transport)
|
||||
except Exception:
|
||||
logger.exception("Error while registering transport class {} for plugin {}".format(transport, name))
|
||||
except Exception:
|
||||
logger.exception("Error executing octoprint.comm.transport.register hook for plugin {}".format(name))
|
||||
|
||||
|
||||
def register_transport(transport_class):
|
||||
if not hasattr(transport_class, "key"):
|
||||
raise ValueError("Transport class {} is missing key".format(transport_class))
|
||||
_registry[transport_class.key] = transport_class
|
||||
|
||||
|
||||
def lookup_transport(key):
|
||||
return _registry.get(key)
|
||||
|
||||
|
||||
def all_transports():
|
||||
return _registry.values()
|
||||
|
||||
|
||||
class Transport(ListenerAware):
|
||||
|
||||
name = None
|
||||
key = None
|
||||
|
||||
message_integrity = False
|
||||
|
||||
@classmethod
|
||||
def get_connection_options(cls):
|
||||
return []
|
||||
|
||||
@classmethod
|
||||
def get_settings_defaults(cls):
|
||||
return dict()
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(Transport, self).__init__()
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._state = TransportState.DISCONNECTED
|
||||
self._args = dict()
|
||||
|
||||
self._printer_profile = kwargs.get("printer_profile")
|
||||
self._plugin_manager = kwargs.get("plugin_manager")
|
||||
self._event_bus = kwargs.get("event_bus")
|
||||
self._settings = kwargs.get("settings")
|
||||
if not isinstance(self._settings, TransportSettings):
|
||||
self._settings = TransportSettings(self._settings, self)
|
||||
|
||||
def args(self):
|
||||
return copy.deepcopy(self._args)
|
||||
|
||||
def set_current_args(self, **value):
|
||||
self._args = copy.deepcopy(value)
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
return self._state
|
||||
|
||||
@state.setter
|
||||
def state(self, value):
|
||||
old_state = self.state
|
||||
self._state = value
|
||||
self.notify_listeners("on_transport_log_message", self, "Transport state changed from '{}' to '{}'".format(old_state, value))
|
||||
|
||||
def connect(self, **params):
|
||||
if self.state == TransportState.CONNECTED:
|
||||
raise TransportAlreadyConnectedError("Already connected, disconnect first")
|
||||
options = self.get_connection_options()
|
||||
param_dict = get_param_dict(params, options)
|
||||
|
||||
self.create_connection(**param_dict)
|
||||
|
||||
self.state = TransportState.CONNECTED
|
||||
self.notify_listeners("on_transport_connected", self)
|
||||
|
||||
def disconnect(self, error=None):
|
||||
if self.state == TransportState.DISCONNECTED:
|
||||
raise TransportNotConnectedError("Already disconnected")
|
||||
|
||||
success = self.drop_connection()
|
||||
if not success and not error:
|
||||
error = "Error disconnecting transport"
|
||||
|
||||
if error:
|
||||
self.state = TransportState.DISCONNECTED_WITH_ERROR
|
||||
self.notify_listeners("on_transport_log_message", self, error)
|
||||
else:
|
||||
self.state = TransportState.DISCONNECTED
|
||||
|
||||
self.notify_listeners("on_transport_disconnected", self, error=error)
|
||||
|
||||
def create_connection(self, *args, **kwargs):
|
||||
return True
|
||||
|
||||
def drop_connection(self):
|
||||
return True
|
||||
|
||||
def read(self, size=None, timeout=None):
|
||||
data = self.do_read(size=size, timeout=timeout)
|
||||
self.notify_listeners("on_transport_log_received_data", self, data)
|
||||
return data
|
||||
|
||||
def write(self, data):
|
||||
self.do_write(data)
|
||||
self.notify_listeners("on_transport_log_sent_data", self, data)
|
||||
|
||||
@property
|
||||
def in_waiting(self):
|
||||
return 0
|
||||
|
||||
def do_read(self, size=None, timeout=None):
|
||||
return b""
|
||||
|
||||
def do_write(self, data):
|
||||
pass
|
||||
|
||||
def __str__(self):
|
||||
return self.__class__.__name__
|
||||
|
||||
|
||||
class TransportState(object):
|
||||
CONNECTED = "connected"
|
||||
DISCONNECTED = "disconnected"
|
||||
DISCONNECTED_WITH_ERROR = "disconnected_with_error"
|
||||
|
||||
|
||||
class TransportSettings(SubSettings):
|
||||
def __init__(self, settings, transport):
|
||||
self.transport = transport.key
|
||||
SubSettings.__init__(self, settings, ["comm", "transport", transport.key],
|
||||
defaults=transport.get_settings_defaults())
|
||||
|
||||
|
||||
class TransportNotConnectedError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class TransportAlreadyConnectedError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class TransportWrapper(ListenerAware):
|
||||
|
||||
unforwarded_handlers = []
|
||||
"""Allows to explicitly disable certain transport listener handlers on sub classes."""
|
||||
|
||||
def __init__(self, transport):
|
||||
ListenerAware.__init__(self)
|
||||
self.transport = transport
|
||||
self.transport.register_listener(self)
|
||||
|
||||
# make sure we forward any transport listener calls to our own registered listeners
|
||||
|
||||
def forward_handler(name):
|
||||
def f(*args, **kwargs):
|
||||
# replace references to self.transport with self
|
||||
args = [self if arg == self.transport else arg for arg in args]
|
||||
kwargs = dict((key, self if value == self.transport else value) for key, value in kwargs.items())
|
||||
|
||||
# forward
|
||||
self.notify_listeners(name, *args, **kwargs)
|
||||
return f
|
||||
|
||||
for handler in filter(lambda x: x.startswith("on_transport_"), dir(TransportListener)):
|
||||
if handler not in self.__class__.unforwarded_handlers:
|
||||
setattr(self, handler, forward_handler(handler))
|
||||
|
||||
def __getattr__(self, item):
|
||||
return getattr(self.transport, item)
|
||||
|
||||
|
||||
class SeparatorAwareTransportWrapper(TransportWrapper):
|
||||
|
||||
unforwarded_handlers = ["on_transport_log_received_data"]
|
||||
"""We have read overwritten and hence send our own received_data notification."""
|
||||
|
||||
def __init__(self, transport, terminator):
|
||||
TransportWrapper.__init__(self, transport)
|
||||
|
||||
self.terminator = terminator
|
||||
|
||||
self._buffered = bytearray()
|
||||
|
||||
def read(self, size=None, timeout=None):
|
||||
start = monotonic_time()
|
||||
termlen = len(self.terminator)
|
||||
data = self._buffered
|
||||
|
||||
while True:
|
||||
# make sure we always read everything that is waiting
|
||||
data += bytearray(self.transport.read(self.transport.in_waiting))
|
||||
|
||||
# check for terminator, if it's there we have found our line
|
||||
termpos = data.find(self.terminator)
|
||||
if termpos >= 0:
|
||||
# line: everything up to and incl. the terminator
|
||||
line = data[:termpos + termlen]
|
||||
|
||||
# buffered: everything after the terminator
|
||||
self._buffered = data[termpos + termlen:]
|
||||
|
||||
received = bytes(line)
|
||||
self.notify_listeners("on_transport_log_received_data", self, received)
|
||||
return received
|
||||
|
||||
# check if timeout expired
|
||||
if timeout and monotonic_time() > start + timeout:
|
||||
break
|
||||
|
||||
# if we arrive here we so far couldn't read a full line, wait for more data
|
||||
c = self.transport.read(1)
|
||||
if not c:
|
||||
# EOF
|
||||
break
|
||||
|
||||
# add to data and loop
|
||||
data += c
|
||||
|
||||
self._buffered = data
|
||||
|
||||
raise TimeoutTransportException()
|
||||
|
||||
def __str__(self):
|
||||
return "SeparatorAwareTransportWrapper({}, separator={})".format(self.transport, self.terminator)
|
||||
|
||||
class LineAwareTransportWrapper(SeparatorAwareTransportWrapper):
|
||||
|
||||
def __init__(self, transport):
|
||||
SeparatorAwareTransportWrapper.__init__(self, transport, b"\n")
|
||||
|
||||
def __str__(self):
|
||||
return "LineAwareTransportWrapper({})".format(self.transport)
|
||||
|
||||
class PushingTransportWrapper(TransportWrapper):
|
||||
|
||||
def __init__(self, transport, name=b"PushingTransportWrapper.receiver_loop", timeout=None):
|
||||
super(PushingTransportWrapper, self).__init__(transport)
|
||||
self.name = name
|
||||
self.timeout = timeout
|
||||
|
||||
self._receiver_active = False
|
||||
self._receiver_thread = None
|
||||
|
||||
@property
|
||||
def active(self):
|
||||
return self._receiver_active
|
||||
|
||||
def connect(self, **kwargs):
|
||||
self.transport.connect(**kwargs)
|
||||
|
||||
import threading
|
||||
|
||||
self._receiver_active = True
|
||||
self._receiver_thread = threading.Thread(target=self._receiver_loop, name=self.name)
|
||||
self._receiver_thread.daemon = True
|
||||
self._receiver_thread.start()
|
||||
|
||||
def disconnect(self):
|
||||
self._receiver_active = False
|
||||
self.transport.disconnect()
|
||||
|
||||
def wait(self):
|
||||
self._receiver_thread.join()
|
||||
|
||||
def _receiver_loop(self):
|
||||
while self._receiver_active:
|
||||
try:
|
||||
data = self.transport.read(timeout=self.timeout)
|
||||
self.notify_listeners("on_transport_data_pushed", self, data)
|
||||
except TimeoutTransportException as ex:
|
||||
self.notify_listeners("on_transport_data_exception", self, ex)
|
||||
except Exception:
|
||||
if self._receiver_active:
|
||||
raise
|
||||
|
||||
def __str__(self):
|
||||
return "PushingTransportWrapper({})".format(self.transport)
|
||||
|
||||
class TransportListener(object):
|
||||
|
||||
def on_transport_connected(self, transport):
|
||||
pass
|
||||
|
||||
def on_transport_disconnected(self, transport, error=None):
|
||||
pass
|
||||
|
||||
def on_transport_log_sent_data(self, transport, data):
|
||||
pass
|
||||
|
||||
def on_transport_log_received_data(self, transport, data):
|
||||
pass
|
||||
|
||||
def on_transport_log_message(self, transport, data):
|
||||
pass
|
||||
|
||||
class PushingTransportWrapperListener(object):
|
||||
|
||||
def on_transport_data_pushed(self, transport, data):
|
||||
pass
|
||||
|
||||
def on_transport_data_exception(self, transport, exception):
|
||||
pass
|
||||
|
||||
class TransportException(Exception):
|
||||
pass
|
||||
|
||||
class TimeoutTransportException(TransportException):
|
||||
pass
|
||||
|
||||
class EofTransportException(TransportException):
|
||||
pass
|
||||
@@ -1,206 +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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from octoprint.comm.transport import Transport, LineAwareTransportWrapper, PushingTransportWrapper
|
||||
from octoprint.comm.util.parameters import TextType, IntegerType, ChoiceType, SuggestionType, BooleanType, Value
|
||||
|
||||
import serial
|
||||
import logging
|
||||
|
||||
class SerialTransport(Transport):
|
||||
name = "Serial Connection"
|
||||
key = "serial"
|
||||
message_integrity = False
|
||||
|
||||
suggested_baudrates = [250000, 230400, 115200, 57600, 38400, 19200, 9600]
|
||||
unix_port_patterns = ["/dev/ttyUSB*", "/dev/ttyACM*", "/dev/tty.usb*",
|
||||
"/dev/cu.*", "/dev/cuaU*", "/dev/rfcomm*"]
|
||||
|
||||
max_write_passes = 5
|
||||
|
||||
@classmethod
|
||||
def for_additional_ports_and_baudrates(cls, additional_ports, additional_baudrates):
|
||||
patterns = SerialTransport.unix_port_patterns
|
||||
if additional_ports:
|
||||
patterns += additional_ports
|
||||
|
||||
baudrates = SerialTransport.suggested_baudrates
|
||||
if additional_baudrates:
|
||||
baudrates += additional_baudrates
|
||||
|
||||
return type(cls.__name__ + b"WithAdditionalPorts",
|
||||
(cls,),
|
||||
{b"unix_port_patterns": patterns,
|
||||
b"suggested_baudrates": baudrates})
|
||||
|
||||
@classmethod
|
||||
def get_connection_options(cls):
|
||||
return [
|
||||
SuggestionType("port", "Port", cls.get_available_serial_ports(), lambda value: Value(value)),
|
||||
SuggestionType("baudrate", "Baudrate", cls.get_available_baudrates(), lambda value: Value(value), default=0),
|
||||
IntegerType("write_timeout", "Write Timeout (sec)", min=1, default=10, advanced=True),
|
||||
BooleanType("exclusive", "Exclusive access", default=True, advanced=True),
|
||||
ChoiceType("parity", "Parity",
|
||||
[Value(serial.PARITY_NONE, "none"),
|
||||
Value(serial.PARITY_ODD, "odd"),
|
||||
Value(serial.PARITY_EVEN, "even")],
|
||||
default=serial.PARITY_NONE, advanced=True)
|
||||
]
|
||||
|
||||
@classmethod
|
||||
def get_available_serial_ports(cls):
|
||||
import sys
|
||||
|
||||
if sys.platform == "win32":
|
||||
# windows
|
||||
from serial.tools.list_ports import comports
|
||||
ports = comports()
|
||||
|
||||
else:
|
||||
# posix
|
||||
import glob
|
||||
|
||||
devices = [device
|
||||
for pattern in cls.unix_port_patterns
|
||||
for device in glob.glob(pattern)]
|
||||
|
||||
plat = sys.platform.lower()
|
||||
|
||||
if plat[:5] == "linux":
|
||||
# linux
|
||||
from serial.tools.list_ports_linux import SysFS
|
||||
ports = [info
|
||||
for info in [SysFS(d) for d in devices]
|
||||
if info.subsystem != "platform"]
|
||||
else:
|
||||
# other posix systems
|
||||
from serial.tools import list_ports_common
|
||||
ports = [list_ports_common.ListPortInfo(d) for d in devices]
|
||||
|
||||
port_values = [Value(None, title="Auto detect")] + sorted([Value(port.device, title=port.description) for port in ports], key=lambda x: x.title)
|
||||
return port_values
|
||||
|
||||
@classmethod
|
||||
def get_available_baudrates(cls):
|
||||
return [Value(0, title="Auto detect")] + \
|
||||
sorted([Value(baudrate) for baudrate in cls.suggested_baudrates], key=lambda x: x.title, reverse=True)
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(SerialTransport, self).__init__()
|
||||
|
||||
self.serial_factory = kwargs.get("serial_factory", None)
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._serial = None
|
||||
|
||||
self._closing = False
|
||||
|
||||
def create_connection(self, **kwargs):
|
||||
factory = self.serial_factory
|
||||
if self.serial_factory is None:
|
||||
factory = self._default_serial_factory
|
||||
|
||||
self._closing = False
|
||||
self._serial = factory(**kwargs)
|
||||
self.set_current_args(**kwargs)
|
||||
|
||||
return True
|
||||
|
||||
def drop_connection(self):
|
||||
error = False
|
||||
|
||||
if self._serial is not None:
|
||||
self._closing = True
|
||||
|
||||
try:
|
||||
if callable(getattr(self._serial, "cancel_read", None)):
|
||||
self._serial.cancel_read()
|
||||
except Exception:
|
||||
self._logger.exception("Error while cancelling pending reads from the serial port")
|
||||
|
||||
try:
|
||||
if callable(getattr(self._serial, "cancel_write", None)):
|
||||
self._serial.cancel_write()
|
||||
except Exception:
|
||||
self._logger.exception("Error while cancelling pending writes to the serial port")
|
||||
|
||||
try:
|
||||
self._serial.close()
|
||||
except Exception:
|
||||
self._logger.exception("Error while closing the serial port")
|
||||
error = True
|
||||
|
||||
self._serial = None
|
||||
|
||||
return not error
|
||||
|
||||
def do_read(self, size=None, timeout=None):
|
||||
return self._serial.read(size=size)
|
||||
|
||||
def do_write(self, data):
|
||||
written = 0
|
||||
passes = 0
|
||||
|
||||
def try_to_write(d):
|
||||
result = self._serial.write(d)
|
||||
if result is None or not isinstance(result, int):
|
||||
# probably some plugin not returning the written bytes, assuming all of them
|
||||
return len(data)
|
||||
else:
|
||||
return result
|
||||
|
||||
while written < len(data):
|
||||
to_send = data[written:]
|
||||
old_written = written
|
||||
|
||||
try:
|
||||
written += try_to_write(to_send)
|
||||
except serial.SerialTimeoutException:
|
||||
self._logger.warn("Serial timeout while writing to serial port, trying again.")
|
||||
try:
|
||||
# second try
|
||||
written += try_to_write(to_send)
|
||||
except Exception:
|
||||
if not self._closing:
|
||||
message = "Unexpected error while writing to serial port"
|
||||
self._logger.exception(message)
|
||||
self.disconnect(error=message)
|
||||
break
|
||||
except Exception:
|
||||
if not self._closing:
|
||||
message = "Unexpected error while writing to serial port"
|
||||
self._logger.exception(message)
|
||||
self.disconnect(error=message)
|
||||
break
|
||||
|
||||
if old_written == written:
|
||||
passes += 1
|
||||
if passes > self.max_write_passes:
|
||||
message = "Could not write anything to the serial port in {} tries, something appears to be " \
|
||||
"wrong with the printer communication".format(self.max_write_passes)
|
||||
self._logger.error(message)
|
||||
self.disconnect(error=message)
|
||||
break
|
||||
|
||||
@property
|
||||
def in_waiting(self):
|
||||
return getattr(self._serial, "in_waiting", 0)
|
||||
|
||||
def _default_serial_factory(self, **kwargs):
|
||||
return serial.Serial(port=kwargs.get("port"),
|
||||
baudrate=kwargs.get("baudrate"),
|
||||
exclusive=kwargs.get("exclusive"),
|
||||
parity=kwargs.get("parity"),
|
||||
write_timeout=kwargs.get("write_timeout", 10) * 1000)
|
||||
|
||||
def __str__(self):
|
||||
return "SerialTransport"
|
||||
|
||||
if __name__ == "__main__":
|
||||
# list ports
|
||||
ports = SerialTransport.get_available_serial_ports()
|
||||
for port in ports:
|
||||
print(port.title + ": " + port.value)
|
||||
@@ -1,65 +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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from octoprint.comm.transport import Transport, LineAwareTransportWrapper
|
||||
from octoprint.comm.util.parameters import TextType, IntegerType
|
||||
|
||||
import socket
|
||||
|
||||
class TcpTransport(Transport):
|
||||
|
||||
name = "TCP Connection"
|
||||
key = "tcpsocket"
|
||||
message_integrity = True
|
||||
|
||||
@classmethod
|
||||
def get_connection_options(cls):
|
||||
return [
|
||||
TextType("host", "Host"),
|
||||
IntegerType("port", "Port", min=1, max=65535)
|
||||
]
|
||||
|
||||
def __init__(self):
|
||||
super(TcpTransport, self).__init__()
|
||||
|
||||
self._socket = None
|
||||
|
||||
def create_connection(self, host=None, port=None):
|
||||
if host is None:
|
||||
raise ValueError("host must not be None")
|
||||
if port is None:
|
||||
raise ValueError("port must not be None")
|
||||
|
||||
self._socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
|
||||
self._socket.connect((host, port))
|
||||
self.set_current_args(host=host, port=port)
|
||||
|
||||
return True
|
||||
|
||||
def drop_connection(self):
|
||||
try:
|
||||
self._socket.close()
|
||||
return True
|
||||
except Exception:
|
||||
self._logger.exception("Error closing socket")
|
||||
return False
|
||||
|
||||
def do_read(self, size=None, timeout=None):
|
||||
if size is None:
|
||||
size = 16
|
||||
return self._socket.recv(size)
|
||||
|
||||
def do_write(self, data):
|
||||
self._socket.sendall(data)
|
||||
|
||||
def __str__(self):
|
||||
return "TcpTransport"
|
||||
|
||||
class SerialOverTcpTransport(TcpTransport):
|
||||
|
||||
name = "Serial Connection over TCP"
|
||||
key = "serialovertcpsocket"
|
||||
message_integrity = False
|
||||
Whitespace-only changes.
@@ -1,194 +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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from past.builtins import unicode
|
||||
|
||||
def get_param_dict(data, options):
|
||||
options_by_name = dict((option.name, option) for option in options)
|
||||
|
||||
result = dict()
|
||||
for key, value in data.items():
|
||||
if not key in options_by_name:
|
||||
continue
|
||||
option = options_by_name[key]
|
||||
result[key] = option.convert(value)
|
||||
return result
|
||||
|
||||
|
||||
class ParamType(object):
|
||||
type = "generic"
|
||||
|
||||
def __init__(self, name, title, default=None, advanced=False, help=None):
|
||||
self.name = name
|
||||
self.title = title
|
||||
self.default = default
|
||||
self.advanced = advanced
|
||||
self.help = help
|
||||
|
||||
def as_dict(self):
|
||||
return dict(name=self.name,
|
||||
title=self.title,
|
||||
default=self.default,
|
||||
advanced=self.advanced,
|
||||
help=self.help,
|
||||
type=self.type)
|
||||
|
||||
def convert(self, value):
|
||||
return value
|
||||
|
||||
def __repr__(self):
|
||||
return "{}(".format(self.__class__.__name__) \
|
||||
+ ", ".join(["{}={!r}".format(key, value) for key, value in self.__dict__.items() if not key.startswith("_")]) + ")"
|
||||
|
||||
class TextType(ParamType):
|
||||
type = "text"
|
||||
|
||||
def convert(self, value):
|
||||
if isinstance(value, bytes):
|
||||
value = value.decode("utf-8", "replace")
|
||||
return value
|
||||
|
||||
class IntegerType(ParamType):
|
||||
type = "integer"
|
||||
|
||||
def __init__(self, name, title, min=None, max=None, unit=None, **kwargs):
|
||||
self.min = min
|
||||
self.max = max
|
||||
self.unit = unit
|
||||
ParamType.__init__(self, name, title, **kwargs)
|
||||
|
||||
def as_dict(self):
|
||||
result = ParamType.as_dict(self)
|
||||
result.update(dict(min=self.min,
|
||||
max=self.max,
|
||||
unit=self.unit))
|
||||
return result
|
||||
|
||||
def convert(self, value):
|
||||
try:
|
||||
value = int(value)
|
||||
except ValueError:
|
||||
raise ValueError("value {!r} is not a valid integer".format(value))
|
||||
|
||||
if self.min is not None and value < self.min:
|
||||
raise ValueError("value {} is less than minimum valid value {}".format(value, self.min))
|
||||
if self.max is not None and value > self.max:
|
||||
raise ValueError("value {} is greater than maximum valid value {}".format(value, self.max))
|
||||
|
||||
return value
|
||||
|
||||
class FloatType(ParamType):
|
||||
type = "float"
|
||||
|
||||
def __init__(self, name, title, min=None, max=None, unit=None, **kwargs):
|
||||
self.min = min
|
||||
self.max = max
|
||||
self.unit = unit
|
||||
ParamType.__init__(self, name, title, **kwargs)
|
||||
|
||||
def as_dict(self):
|
||||
result = ParamType.as_dict(self)
|
||||
result.update(dict(min=self.min,
|
||||
max=self.max,
|
||||
unit=self.unit))
|
||||
return result
|
||||
|
||||
def convert(self, value):
|
||||
try:
|
||||
value = float(value)
|
||||
except ValueError:
|
||||
raise ValueError("value {!r} is not a valid float".format(value))
|
||||
|
||||
if self.min is not None and value < self.min:
|
||||
raise ValueError("value {} is less than minimum valid value {}".format(value, self.min))
|
||||
if self.max is not None and value > self.max:
|
||||
raise ValueError("value {} is greater than maximum valid value {}".format(value, self.max))
|
||||
|
||||
return value
|
||||
|
||||
class BooleanType(ParamType):
|
||||
type = "boolean"
|
||||
|
||||
def convert(self, value):
|
||||
try:
|
||||
value = bool(value)
|
||||
except ValueError:
|
||||
raise ValueError("value {!r} is not a valid boolean".format(value))
|
||||
|
||||
return value
|
||||
|
||||
class ChoiceType(ParamType):
|
||||
type = "choice"
|
||||
|
||||
def __init__(self, name, title, choices, **kwargs):
|
||||
self.choices = choices
|
||||
ParamType.__init__(self, name, title, **kwargs)
|
||||
|
||||
def as_dict(self):
|
||||
result = ParamType.as_dict(self)
|
||||
result.update(dict(choices=list(map(lambda x: x.as_dict(), self.choices))))
|
||||
return result
|
||||
|
||||
class SmallChoiceType(ChoiceType):
|
||||
type = "smallchoice"
|
||||
|
||||
class SuggestionType(ParamType):
|
||||
type = "suggestion"
|
||||
|
||||
def __init__(self, name, title, suggestions, factory, **kwargs):
|
||||
self.suggestions = suggestions
|
||||
self.factory = factory
|
||||
ParamType.__init__(self, name, title, **kwargs)
|
||||
|
||||
def as_dict(self):
|
||||
result = ParamType.as_dict(self)
|
||||
result.update(dict(suggestions=list(map(lambda x: x.as_dict(), self.suggestions))))
|
||||
return result
|
||||
|
||||
class ListType(ParamType):
|
||||
type = "list"
|
||||
|
||||
def __init__(self, name, title, factory, **kwargs):
|
||||
self.factory = factory
|
||||
ParamType.__init__(self, name, title, **kwargs)
|
||||
|
||||
def convert(self, value):
|
||||
if isinstance(value, unicode):
|
||||
items = map(unicode.strip, value.split(","))
|
||||
elif isinstance(value, list):
|
||||
items = value
|
||||
else:
|
||||
raise ValueError("value {!r} must be either a comma-separated string or a list".format(value))
|
||||
|
||||
return list(map(self.factory, items))
|
||||
|
||||
class ParamGroup(ParamType):
|
||||
type = "group"
|
||||
|
||||
def __init__(self, name, title, params, help=None, advanced=False):
|
||||
ParamType.__init__(self, name, title, help=help, advanced=advanced)
|
||||
self.params = params
|
||||
|
||||
def as_dict(self):
|
||||
result = ParamType.as_dict(self)
|
||||
result["params"] = [x.as_dict() for x in self.params]
|
||||
return result
|
||||
|
||||
def convert(self, value):
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError("value {!r} must be a dict".format(value))
|
||||
return dict((k, v.convert()) for k, v in value.items())
|
||||
|
||||
class Value(object):
|
||||
def __init__(self, value, title=None, help=None):
|
||||
self.value = value
|
||||
self.title = title if title else value
|
||||
self.help = help
|
||||
|
||||
def as_dict(self):
|
||||
return dict(value=self.value,
|
||||
title=self.title,
|
||||
help=self.help)
|
||||
@@ -46,6 +46,12 @@ 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"
|
||||
@@ -227,14 +233,6 @@ 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.4.0 Remove again
|
||||
import copy
|
||||
legacy_payload = copy.deepcopy(payload)
|
||||
legacy_payload["type"] = "gcode"
|
||||
q.put((event, legacy_payload))
|
||||
|
||||
def subscribe(self, event, callback):
|
||||
"""
|
||||
Subscribe a listener to an event -- pass in the event name (as a string) and the callback object
|
||||
|
||||
@@ -16,11 +16,12 @@ from octoprint.events import eventManager, Events
|
||||
|
||||
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
|
||||
|
||||
# noinspection PyCompatibility
|
||||
from past.builtins import basestring
|
||||
|
||||
ContentTypeMapping = namedtuple("ContentTypeMapping", "extensions, content_type")
|
||||
@@ -224,6 +225,7 @@ 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()
|
||||
@@ -231,6 +233,10 @@ 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():
|
||||
@@ -330,16 +336,18 @@ class FileManager(object):
|
||||
printer_profile_id, callback, callback_args, _error=None, _cancelled=False, _analysis=None):
|
||||
try:
|
||||
if _error:
|
||||
eventManager().fire(Events.SLICING_FAILED, dict(stl=source_path,
|
||||
stl_location=source_location,
|
||||
gcode=dest_path,
|
||||
gcode_location=dest_location,
|
||||
reason=_error))
|
||||
eventManager().fire(Events.SLICING_FAILED, dict(slicer=slicer_name,
|
||||
stl=source_path,
|
||||
stl_location=source_location,
|
||||
gcode=dest_path,
|
||||
gcode_location=dest_location,
|
||||
reason=_error))
|
||||
elif _cancelled:
|
||||
eventManager().fire(Events.SLICING_CANCELLED, dict(stl=source_path,
|
||||
stl_location=source_location,
|
||||
gcode=dest_path,
|
||||
gcode_location=dest_location))
|
||||
eventManager().fire(Events.SLICING_CANCELLED, dict(slicer=slicer_name,
|
||||
stl=source_path,
|
||||
stl_location=source_location,
|
||||
gcode=dest_path,
|
||||
gcode_location=dest_location))
|
||||
else:
|
||||
source_meta = self.get_metadata(source_location, source_path)
|
||||
hash = source_meta.get("hash", "n/a")
|
||||
@@ -357,11 +365,12 @@ class FileManager(object):
|
||||
printer_profile=printer_profile, analysis=_analysis)
|
||||
|
||||
end_time = octoprint.util.monotonic_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))
|
||||
eventManager().fire(Events.SLICING_DONE, dict(slicer=slicer_name,
|
||||
stl=source_path,
|
||||
stl_location=source_location,
|
||||
gcode=dest_path,
|
||||
gcode_location=dest_location,
|
||||
time=end_time - start_time))
|
||||
|
||||
if callback is not None:
|
||||
if callback_args is None:
|
||||
@@ -382,7 +391,8 @@ class FileManager(object):
|
||||
slicer = self._slicing_manager.get_slicer(slicer_name)
|
||||
|
||||
start_time = octoprint.util.monotonic_time()
|
||||
eventManager().fire(Events.SLICING_STARTED, {"stl": source_path,
|
||||
eventManager().fire(Events.SLICING_STARTED, {"slicer": slicer_name,
|
||||
"stl": source_path,
|
||||
"stl_location": source_location,
|
||||
"gcode": dest_path,
|
||||
"gcode_location": dest_location,
|
||||
@@ -428,7 +438,8 @@ class FileManager(object):
|
||||
try:
|
||||
callback.sendSlicingProgress(slicer, source_location, source_path, dest_location, dest_path, progress_int)
|
||||
except Exception:
|
||||
self._logger.exception("Exception while pushing slicing progress")
|
||||
self._logger.exception("Exception while pushing slicing progress",
|
||||
extra=dict(callback=fqcn(callback)))
|
||||
|
||||
if progress_int:
|
||||
def call_plugins(slicer, source_location, source_path, dest_location, dest_path, progress):
|
||||
@@ -602,9 +613,6 @@ class FileManager(object):
|
||||
name=dst_name))
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
|
||||
def create_print_job(self, destination, path, user=None):
|
||||
return self._storage(destination).create_print_job(path, user=user)
|
||||
|
||||
def has_analysis(self, destination, path):
|
||||
return self._storage(destination).has_analysis(path)
|
||||
|
||||
@@ -619,13 +627,10 @@ class FileManager(object):
|
||||
|
||||
def log_print(self, destination, path, timestamp, print_time, success, printer_profile):
|
||||
try:
|
||||
try:
|
||||
if success:
|
||||
self._storage(destination).add_history(path, dict(timestamp=timestamp, printTime=print_time, success=success, printerProfile=printer_profile))
|
||||
else:
|
||||
self._storage(destination).add_history(path, dict(timestamp=timestamp, success=success, printerProfile=printer_profile))
|
||||
except NotImplementedError:
|
||||
pass
|
||||
if success:
|
||||
self._storage(destination).add_history(path, dict(timestamp=timestamp, printTime=print_time, success=success, printerProfile=printer_profile))
|
||||
else:
|
||||
self._storage(destination).add_history(path, dict(timestamp=timestamp, success=success, printerProfile=printer_profile))
|
||||
eventManager().fire(Events.METADATA_STATISTICS_UPDATED, dict(storage=destination, path=path))
|
||||
except NoSuchStorage:
|
||||
# if there's no storage configured where to log the print, we'll just not log it
|
||||
@@ -663,6 +668,8 @@ class FileManager(object):
|
||||
try:
|
||||
with io.open(self._recovery_file, 'rt', encoding='utf-8') as f:
|
||||
data = yaml.safe_load(f)
|
||||
if not isinstance(data, dict) or not all(map(lambda x: x in data, ("origin", "path", "pos", "date"))):
|
||||
raise ValueError("Invalid recovery data structure")
|
||||
return data
|
||||
except Exception:
|
||||
self._logger.exception("Could not read recovery data from file {}".format(self._recovery_file))
|
||||
|
||||
@@ -19,6 +19,7 @@ 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")):
|
||||
@@ -109,14 +110,15 @@ class AnalysisQueue(object):
|
||||
|
||||
def _analysis_finished(self, entry, result):
|
||||
for callback in self._callbacks:
|
||||
callback(entry, result)
|
||||
try:
|
||||
callback(entry, result)
|
||||
except:
|
||||
self._logger.exception(u"Error while pushing analysis data to callback {}".format(callback),
|
||||
extra=dict(callback=fqcn(callback)))
|
||||
eventManager().fire(Events.METADATA_ANALYSIS_FINISHED, {"name": entry.name,
|
||||
"path": entry.path,
|
||||
"origin": entry.location,
|
||||
"result": result,
|
||||
|
||||
# TODO: deprecated, remove in a future release
|
||||
"file": entry.path})
|
||||
"result": result})
|
||||
|
||||
class AbstractAnalysisQueue(object):
|
||||
"""
|
||||
@@ -174,7 +176,10 @@ class AbstractAnalysisQueue(object):
|
||||
(False, default)
|
||||
"""
|
||||
|
||||
if high_priority:
|
||||
if settings().get(["gcodeAnalysis", "runAt"]) == "never":
|
||||
self._logger.debug("Ignoring entry {entry} for analysis queue".format(entry=entry))
|
||||
return
|
||||
elif high_priority:
|
||||
self._logger.debug("Adding entry {entry} to analysis queue with high priority".format(entry=entry))
|
||||
prio = self.__class__.HIGH_PRIO
|
||||
else:
|
||||
@@ -255,10 +260,7 @@ class AbstractAnalysisQueue(object):
|
||||
eventManager().fire(Events.METADATA_ANALYSIS_STARTED, {"name": entry.name,
|
||||
"path": entry.path,
|
||||
"origin": entry.location,
|
||||
"type": entry.type,
|
||||
|
||||
# TODO deprecated, remove in 1.4.0
|
||||
"file": entry.path})
|
||||
"type": entry.type})
|
||||
try:
|
||||
result = self._do_analysis(high_priority=high_priority)
|
||||
except TypeError:
|
||||
|
||||
+411
-15
@@ -1,6 +1,7 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
@@ -20,7 +21,6 @@ except ImportError:
|
||||
from octoprint.util import atomic_write
|
||||
from contextlib import contextmanager
|
||||
|
||||
# noinspection PyCompatibility
|
||||
from past.builtins import basestring
|
||||
|
||||
from emoji import demojize
|
||||
@@ -30,10 +30,417 @@ import octoprint.filemanager
|
||||
|
||||
from octoprint.util import is_hidden_path, to_unicode, to_bytes
|
||||
|
||||
from . import Storage, StorageError
|
||||
class StorageInterface(object):
|
||||
"""
|
||||
Interface of storage adapters for OctoPrint.
|
||||
"""
|
||||
|
||||
@property
|
||||
def analysis_backlog(self):
|
||||
"""
|
||||
Get an iterator over all items stored in the storage that need to be analysed by the :class:`~octoprint.filemanager.AnalysisQueue`.
|
||||
|
||||
The yielded elements are expected as storage specific absolute paths to the respective files. Don't forget
|
||||
to recurse into folders if your storage adapter supports those.
|
||||
|
||||
:return: an iterator yielding all un-analysed files in the storage
|
||||
"""
|
||||
# empty generator pattern, yield is intentionally unreachable
|
||||
return
|
||||
yield
|
||||
|
||||
def analysis_backlog_for_path(self, path=None):
|
||||
# empty generator pattern, yield is intentionally unreachable
|
||||
return
|
||||
yield
|
||||
|
||||
def last_modified(self, path=None, recursive=False):
|
||||
"""
|
||||
Get the last modification date of the specified ``path`` or ``path``'s subtree.
|
||||
|
||||
Args:
|
||||
path (str or None): Path for which to determine the subtree's last modification date. If left out or
|
||||
set to None, defatuls to storage root.
|
||||
recursive (bool): Whether to determine only the date of the specified ``path`` (False, default) or
|
||||
the whole ``path``'s subtree (True).
|
||||
|
||||
Returns: (float) The last modification date of the indicated subtree
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def file_in_path(self, path, filepath):
|
||||
"""
|
||||
Returns whether the file indicated by ``file`` is inside ``path`` or not.
|
||||
:param string path: the path to check
|
||||
:param string filepath: path to the file
|
||||
:return: ``True`` if the file is inside the path, ``False`` otherwise
|
||||
"""
|
||||
return NotImplementedError()
|
||||
|
||||
def file_exists(self, path):
|
||||
"""
|
||||
Returns whether the file indicated by ``path`` exists or not.
|
||||
:param string path: the path to check for existence
|
||||
:return: ``True`` if the file exists, ``False`` otherwise
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def folder_exists(self, path):
|
||||
"""
|
||||
Returns whether the folder indicated by ``path`` exists or not.
|
||||
:param string path: the path to check for existence
|
||||
:return: ``True`` if the folder exists, ``False`` otherwise
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def list_files(self, path=None, filter=None, recursive=True):
|
||||
"""
|
||||
List all files in storage starting at ``path``. If ``recursive`` is set to True (the default), also dives into
|
||||
subfolders.
|
||||
|
||||
An optional filter function can be supplied which will be called with a file name and file data and which has
|
||||
to return True if the file is to be included in the result or False if not.
|
||||
|
||||
The data structure of the returned result will be a dictionary mapping from file names to entry data. File nodes
|
||||
will contain their metadata here, folder nodes will contain their contained files and folders. Example::
|
||||
|
||||
{
|
||||
"some_folder": {
|
||||
"name": "some_folder",
|
||||
"path": "some_folder",
|
||||
"type": "folder",
|
||||
"children": {
|
||||
"some_sub_folder": {
|
||||
"name": "some_sub_folder",
|
||||
"path": "some_folder/some_sub_folder",
|
||||
"type": "folder",
|
||||
"typePath": ["folder"],
|
||||
"children": { ... }
|
||||
},
|
||||
"some_file.gcode": {
|
||||
"name": "some_file.gcode",
|
||||
"path": "some_folder/some_file.gcode",
|
||||
"type": "machinecode",
|
||||
"typePath": ["machinecode", "gcode"],
|
||||
"hash": "<sha1 hash>",
|
||||
"links": [ ... ],
|
||||
...
|
||||
},
|
||||
...
|
||||
}
|
||||
"test.gcode": {
|
||||
"name": "test.gcode",
|
||||
"path": "test.gcode",
|
||||
"type": "machinecode",
|
||||
"typePath": ["machinecode", "gcode"],
|
||||
"hash": "<sha1 hash>",
|
||||
"links": [...],
|
||||
...
|
||||
},
|
||||
"test.stl": {
|
||||
"name": "test.stl",
|
||||
"path": "test.stl",
|
||||
"type": "model",
|
||||
"typePath": ["model", "stl"],
|
||||
"hash": "<sha1 hash>",
|
||||
"links": [...],
|
||||
...
|
||||
},
|
||||
...
|
||||
}
|
||||
|
||||
:param string path: base path from which to recursively list all files, optional, if not supplied listing will start
|
||||
from root of base folder
|
||||
:param function filter: a filter that matches the files that are to be returned, may be left out in which case no
|
||||
filtering will take place
|
||||
:param bool recursive: will also step into sub folders for building the complete list if set to True, otherwise will only
|
||||
do one step down into sub folders to be able to populate the ``children``.
|
||||
:return: a dictionary mapping entry names to entry data that represents the whole file list
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def add_folder(self, path, ignore_existing=True, display=None):
|
||||
"""
|
||||
Adds a folder as ``path``
|
||||
|
||||
The ``path`` will be sanitized.
|
||||
|
||||
:param string path: the path of the new folder
|
||||
:param bool ignore_existing: if set to True, no error will be raised if the folder to be added already exists
|
||||
:param unicode display: display name of the folder
|
||||
:return: the sanitized name of the new folder to be used for future references to the folder
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def remove_folder(self, path, recursive=True):
|
||||
"""
|
||||
Removes the folder at ``path``
|
||||
|
||||
:param string path: the path of the folder to remove
|
||||
:param bool recursive: if set to True, contained folders and files will also be removed, otherwise an error will
|
||||
be raised if the folder is not empty (apart from any metadata files) when it's to be removed
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def copy_folder(self, source, destination):
|
||||
"""
|
||||
Copies the folder ``source`` to ``destination``
|
||||
|
||||
:param string source: path to the source folder
|
||||
:param string destination: path to destination
|
||||
|
||||
:return: the path in the storage to the copy of the folder
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def move_folder(self, source, destination):
|
||||
"""
|
||||
Moves the folder ``source`` to ``destination``
|
||||
|
||||
:param string source: path to the source folder
|
||||
:param string destination: path to destination
|
||||
|
||||
:return: the new path in the storage to the folder
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False, display=None):
|
||||
"""
|
||||
Adds the file ``file_object`` as ``path``
|
||||
|
||||
:param string path: the file's new path, will be sanitized
|
||||
:param object file_object: a file object that provides a ``save`` method which will be called with the destination path
|
||||
where the object should then store its contents
|
||||
:param object printer_profile: the printer profile associated with this file (if any)
|
||||
:param list links: any links to add with the file
|
||||
:param bool allow_overwrite: if set to True no error will be raised if the file already exists and the existing file
|
||||
and its metadata will just be silently overwritten
|
||||
:param unicode display: display name of the file
|
||||
:return: the sanitized name of the file to be used for future references to it
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def remove_file(self, path):
|
||||
"""
|
||||
Removes the file at ``path``
|
||||
|
||||
Will also take care of deleting the corresponding entries
|
||||
in the metadata and deleting all links pointing to the file.
|
||||
|
||||
:param string path: path of the file to remove
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def copy_file(self, source, destination):
|
||||
"""
|
||||
Copies the file ``source`` to ``destination``
|
||||
|
||||
:param string source: path to the source file
|
||||
:param string destination: path to destination
|
||||
|
||||
:return: the path in the storage to the copy of the file
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def move_file(self, source, destination):
|
||||
"""
|
||||
Moves the file ``source`` to ``destination``
|
||||
|
||||
:param string source: path to the source file
|
||||
:param string destination: path to destination
|
||||
|
||||
:return: the new path in the storage to the file
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def has_analysis(self, path):
|
||||
"""
|
||||
Returns whether the file at path has been analysed yet
|
||||
|
||||
:param path: virtual path to the file for which to retrieve the metadata
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_metadata(self, path):
|
||||
"""
|
||||
Retrieves the metadata for the file ``path``.
|
||||
|
||||
:param path: virtual path to the file for which to retrieve the metadata
|
||||
:return: the metadata associated with the file
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def add_link(self, path, rel, data):
|
||||
"""
|
||||
Adds a link of relation ``rel`` to file ``path`` with the given ``data``.
|
||||
|
||||
The following relation types are currently supported:
|
||||
|
||||
* ``model``: adds a link to a model from which the file was created/sliced, expected additional data is the ``name``
|
||||
and optionally the ``hash`` of the file to link to. If the link can be resolved against another file on the
|
||||
current ``path``, not only will it be added to the links of ``name`` but a reverse link of type ``machinecode``
|
||||
referring to ``name`` and its hash will also be added to the linked ``model`` file
|
||||
* ``machinecode``: adds a link to a file containing machine code created from the current file (model), expected
|
||||
additional data is the ``name`` and optionally the ``hash`` of the file to link to. If the link can be resolved
|
||||
against another file on the current ``path``, not only will it be added to the links of ``name`` but a reverse
|
||||
link of type ``model`` referring to ``name`` and its hash will also be added to the linked ``model`` file.
|
||||
* ``web``: adds a location on the web associated with this file (e.g. a website where to download a model),
|
||||
expected additional data is a ``href`` attribute holding the website's URL and optionally a ``retrieved``
|
||||
attribute describing when the content was retrieved
|
||||
|
||||
Note that adding ``model`` links to files identifying as models or ``machinecode`` links to files identifying
|
||||
as machine code will be refused.
|
||||
|
||||
:param path: path of the file for which to add a link
|
||||
:param rel: type of relation of the link to add (currently ``model``, ``machinecode`` and ``web`` are supported)
|
||||
:param data: additional data of the link to add
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def remove_link(self, path, rel, data):
|
||||
"""
|
||||
Removes the link consisting of ``rel`` and ``data`` from file ``name`` on ``path``.
|
||||
|
||||
:param path: path of the file from which to remove the link
|
||||
:param rel: type of relation of the link to remove (currently ``model``, ``machinecode`` and ``web`` are supported)
|
||||
:param data: additional data of the link to remove, must match existing link
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):
|
||||
"""
|
||||
Adds additional metadata to the metadata of ``path``. Metadata in ``data`` will be saved under ``key``.
|
||||
|
||||
If ``overwrite`` is set and ``key`` already exists in ``name``'s metadata, the current value will be overwritten.
|
||||
|
||||
If ``merge`` is set and ``key`` already exists and both ``data`` and the existing data under ``key`` are dictionaries,
|
||||
the two dictionaries will be merged recursively.
|
||||
|
||||
:param path: the virtual path to the file for which to add additional metadata
|
||||
:param key: key of metadata to add
|
||||
:param data: metadata to add
|
||||
:param overwrite: if True and ``key`` already exists, it will be overwritten
|
||||
:param merge: if True and ``key`` already exists and both ``data`` and the existing data are dictionaries, they
|
||||
will be merged
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def remove_additional_metadata(self, path, key):
|
||||
"""
|
||||
Removes additional metadata under ``key`` for ``name`` on ``path``
|
||||
|
||||
:param path: the virtual path to the file for which to remove the metadata under ``key``
|
||||
:param key: the key to remove
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def canonicalize(self, path):
|
||||
"""
|
||||
Canonicalizes the given ``path``. The ``path`` may consist of both folder and file name, the underlying
|
||||
implementation must separate those if necessary.
|
||||
|
||||
By default, this calls :func:`~octoprint.filemanager.StorageInterface.sanitize`, which also takes care
|
||||
of stripping any invalid characters.
|
||||
|
||||
Args:
|
||||
path: the path to canonicalize
|
||||
|
||||
Returns:
|
||||
a 2-tuple containing the canonicalized path and file name
|
||||
|
||||
"""
|
||||
return self.sanitize(path)
|
||||
|
||||
def sanitize(self, path):
|
||||
"""
|
||||
Sanitizes the given ``path``, stripping it of all invalid characters. The ``path`` may consist of both
|
||||
folder and file name, the underlying implementation must separate those if necessary and sanitize individually.
|
||||
|
||||
:param string path: the path to sanitize
|
||||
:return: a 2-tuple containing the sanitized path and file name
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def sanitize_path(self, path):
|
||||
"""
|
||||
Sanitizes the given folder-only ``path``, stripping it of all invalid characters.
|
||||
:param string path: the path to sanitize
|
||||
:return: the sanitized path
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def sanitize_name(self, name):
|
||||
"""
|
||||
Sanitizes the given file ``name``, stripping it of all invalid characters.
|
||||
:param string name: the file name to sanitize
|
||||
:return: the sanitized name
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def split_path(self, path):
|
||||
"""
|
||||
Split ``path`` into base directory and file name.
|
||||
:param path: the path to split
|
||||
:return: a tuple (base directory, file name)
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def join_path(self, *path):
|
||||
"""
|
||||
Join path elements together
|
||||
:param path: path elements to join
|
||||
:return: joined representation of the path to be usable as fully qualified path for further operations
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def path_on_disk(self, path):
|
||||
"""
|
||||
Retrieves the path on disk for ``path``.
|
||||
|
||||
Note: if the storage is not on disk and there exists no path on disk to refer to it, this method should
|
||||
raise an :class:`io.UnsupportedOperation`
|
||||
|
||||
Opposite of :func:`path_in_storage`.
|
||||
|
||||
:param string path: the virtual path for which to retrieve the path on disk
|
||||
:return: the path on disk to ``path``
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def path_in_storage(self, path):
|
||||
"""
|
||||
Retrieves the equivalent in the storage adapter for ``path``.
|
||||
|
||||
Opposite of :func:`path_on_disk`.
|
||||
|
||||
:param string path: the path for which to retrieve the storage path
|
||||
:return: the path in storage to ``path``
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
class LocalFileStorage(Storage):
|
||||
class StorageError(Exception):
|
||||
UNKNOWN = "unknown"
|
||||
INVALID_DIRECTORY = "invalid_directory"
|
||||
INVALID_FILE = "invalid_file"
|
||||
INVALID_SOURCE = "invalid_source"
|
||||
INVALID_DESTINATION = "invalid_destination"
|
||||
DOES_NOT_EXIST = "does_not_exist"
|
||||
ALREADY_EXISTS = "already_exists"
|
||||
SOURCE_EQUALS_DESTINATION = "source_equals_destination"
|
||||
NOT_EMPTY = "not_empty"
|
||||
|
||||
def __init__(self, message, code=None, cause=None):
|
||||
BaseException.__init__(self)
|
||||
self.message = message
|
||||
self.cause = cause
|
||||
|
||||
if code is None:
|
||||
code = StorageError.UNKNOWN
|
||||
self.code = code
|
||||
|
||||
|
||||
class LocalFileStorage(StorageInterface):
|
||||
"""
|
||||
The ``LocalFileStorage`` is a storage implementation which holds all files, folders and metadata on disk.
|
||||
|
||||
@@ -59,7 +466,7 @@ class LocalFileStorage(Storage):
|
||||
text = demojize(text, delimiters=("", ""))
|
||||
return cls._SLUGIFY(text)
|
||||
|
||||
def __init__(self, basefolder, create=False, key="local"):
|
||||
def __init__(self, basefolder, create=False):
|
||||
"""
|
||||
Initializes a ``LocalFileStorage`` instance under the given ``basefolder``, creating the necessary folder
|
||||
if necessary and ``create`` is set to ``True``.
|
||||
@@ -442,17 +849,6 @@ class LocalFileStorage(Storage):
|
||||
metadata = self.get_metadata(path)
|
||||
return "analysis" in metadata
|
||||
|
||||
def create_print_job(self, path, user=None):
|
||||
from octoprint.comm.job import LocalGcodeFilePrintjob
|
||||
return LocalGcodeFilePrintjob(self.path_on_disk(path),
|
||||
"local",
|
||||
self.path_in_storage(path),
|
||||
name=self.path_in_storage(path),
|
||||
user=user,
|
||||
event_data=dict(path=path,
|
||||
name=self.split_path(path)[1],
|
||||
origin="local"))
|
||||
|
||||
def get_metadata(self, path):
|
||||
path, name = self.sanitize(path)
|
||||
return self._get_metadata_entry(path, name)
|
||||
@@ -1,457 +0,0 @@
|
||||
# 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"
|
||||
|
||||
try:
|
||||
from os import scandir, walk
|
||||
except ImportError:
|
||||
from scandir import scandir, walk
|
||||
|
||||
|
||||
class Storage(object):
|
||||
"""
|
||||
Interface of storage adapters for OctoPrint.
|
||||
"""
|
||||
@property
|
||||
def analysis_backlog(self):
|
||||
"""
|
||||
Get an iterator over all items stored in the storage that need to be analysed by the :class:`~octoprint.filemanager.AnalysisQueue`.
|
||||
|
||||
The yielded elements are expected as storage specific absolute paths to the respective files. Don't forget
|
||||
to recurse into folders if your storage adapter supports those.
|
||||
|
||||
:return: an iterator yielding all un-analysed files in the storage
|
||||
"""
|
||||
# empty generator pattern, yield is intentionally unreachable
|
||||
return
|
||||
# noinspection PyUnreachableCode
|
||||
yield
|
||||
|
||||
def analysis_backlog_for_path(self, path=None):
|
||||
# empty generator pattern, yield is intentionally unreachable
|
||||
return
|
||||
# noinspection PyUnreachableCode
|
||||
yield
|
||||
|
||||
def last_modified(self, path=None, recursive=False):
|
||||
"""
|
||||
Get the last modification date of the specified ``path`` or ``path``'s subtree.
|
||||
|
||||
Args:
|
||||
path (str or None): Path for which to determine the subtree's last modification date. If left out or
|
||||
set to None, defatuls to storage root.
|
||||
recursive (bool): Whether to determine only the date of the specified ``path`` (False, default) or
|
||||
the whole ``path``'s subtree (True).
|
||||
|
||||
Returns: (float) The last modification date of the indicated subtree
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def file_in_path(self, path, filepath):
|
||||
"""
|
||||
Returns whether the file indicated by ``file`` is inside ``path`` or not.
|
||||
:param string path: the path to check
|
||||
:param string filepath: path to the file
|
||||
:return: ``True`` if the file is inside the path, ``False`` otherwise
|
||||
"""
|
||||
return NotImplementedError()
|
||||
|
||||
def file_exists(self, path):
|
||||
"""
|
||||
Returns whether the file indicated by ``path`` exists or not.
|
||||
:param string path: the path to check for existence
|
||||
:return: ``True`` if the file exists, ``False`` otherwise
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def folder_exists(self, path):
|
||||
"""
|
||||
Returns whether the folder indicated by ``path`` exists or not.
|
||||
:param string path: the path to check for existence
|
||||
:return: ``True`` if the folder exists, ``False`` otherwise
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def list_files(self, path=None, filter=None, recursive=True):
|
||||
"""
|
||||
List all files in storage starting at ``path``. If ``recursive`` is set to True (the default), also dives into
|
||||
subfolders.
|
||||
|
||||
An optional filter function can be supplied which will be called with a file name and file data and which has
|
||||
to return True if the file is to be included in the result or False if not.
|
||||
|
||||
The data structure of the returned result will be a dictionary mapping from file names to entry data. File nodes
|
||||
will contain their metadata here, folder nodes will contain their contained files and folders. Example::
|
||||
|
||||
{
|
||||
"some_folder": {
|
||||
"name": "some_folder",
|
||||
"path": "some_folder",
|
||||
"type": "folder",
|
||||
"children": {
|
||||
"some_sub_folder": {
|
||||
"name": "some_sub_folder",
|
||||
"path": "some_folder/some_sub_folder",
|
||||
"type": "folder",
|
||||
"typePath": ["folder"],
|
||||
"children": { ... }
|
||||
},
|
||||
"some_file.gcode": {
|
||||
"name": "some_file.gcode",
|
||||
"path": "some_folder/some_file.gcode",
|
||||
"type": "machinecode",
|
||||
"typePath": ["machinecode", "gcode"],
|
||||
"hash": "<sha1 hash>",
|
||||
"links": [ ... ],
|
||||
...
|
||||
},
|
||||
...
|
||||
}
|
||||
"test.gcode": {
|
||||
"name": "test.gcode",
|
||||
"path": "test.gcode",
|
||||
"type": "machinecode",
|
||||
"typePath": ["machinecode", "gcode"],
|
||||
"hash": "<sha1 hash>",
|
||||
"links": [...],
|
||||
...
|
||||
},
|
||||
"test.stl": {
|
||||
"name": "test.stl",
|
||||
"path": "test.stl",
|
||||
"type": "model",
|
||||
"typePath": ["model", "stl"],
|
||||
"hash": "<sha1 hash>",
|
||||
"links": [...],
|
||||
...
|
||||
},
|
||||
...
|
||||
}
|
||||
|
||||
:param string path: base path from which to recursively list all files, optional, if not supplied listing will start
|
||||
from root of base folder
|
||||
:param function filter: a filter that matches the files that are to be returned, may be left out in which case no
|
||||
filtering will take place
|
||||
:param bool recursive: will also step into sub folders for building the complete list if set to True, otherwise will only
|
||||
do one step down into sub folders to be able to populate the ``children``.
|
||||
:return: a dictionary mapping entry names to entry data that represents the whole file list
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def add_folder(self, path, ignore_existing=True, display=None):
|
||||
"""
|
||||
Adds a folder as ``path``
|
||||
|
||||
The ``path`` will be sanitized.
|
||||
|
||||
:param string path: the path of the new folder
|
||||
:param bool ignore_existing: if set to True, no error will be raised if the folder to be added already exists
|
||||
:param unicode display: display name of the folder
|
||||
:return: the sanitized name of the new folder to be used for future references to the folder
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def remove_folder(self, path, recursive=True):
|
||||
"""
|
||||
Removes the folder at ``path``
|
||||
|
||||
:param string path: the path of the folder to remove
|
||||
:param bool recursive: if set to True, contained folders and files will also be removed, otherwise an error will
|
||||
be raised if the folder is not empty (apart from any metadata files) when it's to be removed
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def copy_folder(self, source, destination):
|
||||
"""
|
||||
Copies the folder ``source`` to ``destination``
|
||||
|
||||
:param string source: path to the source folder
|
||||
:param string destination: path to destination
|
||||
|
||||
:return: the path in the storage to the copy of the folder
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def move_folder(self, source, destination):
|
||||
"""
|
||||
Moves the folder ``source`` to ``destination``
|
||||
|
||||
:param string source: path to the source folder
|
||||
:param string destination: path to destination
|
||||
|
||||
:return: the new path in the storage to the folder
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False, display=None):
|
||||
"""
|
||||
Adds the file ``file_object`` as ``path``
|
||||
|
||||
:param string path: the file's new path, will be sanitized
|
||||
:param object file_object: a file object that provides a ``save`` method which will be called with the destination path
|
||||
where the object should then store its contents
|
||||
:param object printer_profile: the printer profile associated with this file (if any)
|
||||
:param list links: any links to add with the file
|
||||
:param bool allow_overwrite: if set to True no error will be raised if the file already exists and the existing file
|
||||
and its metadata will just be silently overwritten
|
||||
:param unicode display: display name of the file
|
||||
:return: the sanitized name of the file to be used for future references to it
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def remove_file(self, path):
|
||||
"""
|
||||
Removes the file at ``path``
|
||||
|
||||
Will also take care of deleting the corresponding entries
|
||||
in the metadata and deleting all links pointing to the file.
|
||||
|
||||
:param string path: path of the file to remove
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def copy_file(self, source, destination):
|
||||
"""
|
||||
Copies the file ``source`` to ``destination``
|
||||
|
||||
:param string source: path to the source file
|
||||
:param string destination: path to destination
|
||||
|
||||
:return: the path in the storage to the copy of the file
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def move_file(self, source, destination):
|
||||
"""
|
||||
Moves the file ``source`` to ``destination``
|
||||
|
||||
:param string source: path to the source file
|
||||
:param string destination: path to destination
|
||||
|
||||
:return: the new path in the storage to the file
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def has_analysis(self, path):
|
||||
"""
|
||||
Returns whether the file at path has been analysed yet
|
||||
|
||||
:param path: virtual path to the file for which to retrieve the metadata
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def create_print_job(self, path, user=None):
|
||||
"""
|
||||
Retrieves the :class:`~octoprint.job.PrintJob` instance
|
||||
to use for printing ``path``.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_metadata(self, path):
|
||||
"""
|
||||
Retrieves the metadata for the file ``path``.
|
||||
|
||||
:param path: virtual path to the file for which to retrieve the metadata
|
||||
:return: the metadata associated with the file
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def add_link(self, path, rel, data):
|
||||
"""
|
||||
Adds a link of relation ``rel`` to file ``path`` with the given ``data``.
|
||||
|
||||
The following relation types are currently supported:
|
||||
|
||||
* ``model``: adds a link to a model from which the file was created/sliced, expected additional data is the ``name``
|
||||
and optionally the ``hash`` of the file to link to. If the link can be resolved against another file on the
|
||||
current ``path``, not only will it be added to the links of ``name`` but a reverse link of type ``machinecode``
|
||||
referring to ``name`` and its hash will also be added to the linked ``model`` file
|
||||
* ``machinecode``: adds a link to a file containing machine code created from the current file (model), expected
|
||||
additional data is the ``name`` and optionally the ``hash`` of the file to link to. If the link can be resolved
|
||||
against another file on the current ``path``, not only will it be added to the links of ``name`` but a reverse
|
||||
link of type ``model`` referring to ``name`` and its hash will also be added to the linked ``model`` file.
|
||||
* ``web``: adds a location on the web associated with this file (e.g. a website where to download a model),
|
||||
expected additional data is a ``href`` attribute holding the website's URL and optionally a ``retrieved``
|
||||
attribute describing when the content was retrieved
|
||||
|
||||
Note that adding ``model`` links to files identifying as models or ``machinecode`` links to files identifying
|
||||
as machine code will be refused.
|
||||
|
||||
:param path: path of the file for which to add a link
|
||||
:param rel: type of relation of the link to add (currently ``model``, ``machinecode`` and ``web`` are supported)
|
||||
:param data: additional data of the link to add
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def remove_link(self, path, rel, data):
|
||||
"""
|
||||
Removes the link consisting of ``rel`` and ``data`` from file ``name`` on ``path``.
|
||||
|
||||
:param path: path of the file from which to remove the link
|
||||
:param rel: type of relation of the link to remove (currently ``model``, ``machinecode`` and ``web`` are supported)
|
||||
:param data: additional data of the link to remove, must match existing link
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def add_history(self, path, data):
|
||||
"""
|
||||
Adds a history entry for the given ``path``.
|
||||
|
||||
:param path: path of the file for which to add the history entry
|
||||
:param data: history entry
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def update_history(self, path, index, data):
|
||||
"""
|
||||
Updates the history entry for ``path`` at ``index``.
|
||||
|
||||
:param path: path of the file for which to update the history entry
|
||||
:param index: index
|
||||
:param data: history entry
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def remove_history(self, path, index):
|
||||
"""
|
||||
Removes the history entry for ``path`` at ``index``.
|
||||
:param path: path of the file for which to remove the history entry
|
||||
:param index: index
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):
|
||||
"""
|
||||
Adds additional metadata to the metadata of ``path``. Metadata in ``data`` will be saved under ``key``.
|
||||
|
||||
If ``overwrite`` is set and ``key`` already exists in ``name``'s metadata, the current value will be overwritten.
|
||||
|
||||
If ``merge`` is set and ``key`` already exists and both ``data`` and the existing data under ``key`` are dictionaries,
|
||||
the two dictionaries will be merged recursively.
|
||||
|
||||
:param path: the virtual path to the file for which to add additional metadata
|
||||
:param key: key of metadata to add
|
||||
:param data: metadata to add
|
||||
:param overwrite: if True and ``key`` already exists, it will be overwritten
|
||||
:param merge: if True and ``key`` already exists and both ``data`` and the existing data are dictionaries, they
|
||||
will be merged
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def remove_additional_metadata(self, path, key):
|
||||
"""
|
||||
Removes additional metadata under ``key`` for ``name`` on ``path``
|
||||
|
||||
:param path: the virtual path to the file for which to remove the metadata under ``key``
|
||||
:param key: the key to remove
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def canonicalize(self, path):
|
||||
"""
|
||||
Canonicalizes the given ``path``. The ``path`` may consist of both folder and file name, the underlying
|
||||
implementation must separate those if necessary.
|
||||
|
||||
By default, this calls :func:`~octoprint.filemanager.StorageInterface.sanitize`, which also takes care
|
||||
of stripping any invalid characters.
|
||||
|
||||
Args:
|
||||
path: the path to canonicalize
|
||||
|
||||
Returns:
|
||||
a 2-tuple containing the canonicalized path and file name
|
||||
|
||||
"""
|
||||
return self.sanitize(path)
|
||||
|
||||
def sanitize(self, path):
|
||||
"""
|
||||
Sanitizes the given ``path``, stripping it of all invalid characters. The ``path`` may consist of both
|
||||
folder and file name, the underlying implementation must separate those if necessary and sanitize individually.
|
||||
|
||||
:param string path: the path to sanitize
|
||||
:return: a 2-tuple containing the sanitized path and file name
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def sanitize_path(self, path):
|
||||
"""
|
||||
Sanitizes the given folder-only ``path``, stripping it of all invalid characters.
|
||||
:param string path: the path to sanitize
|
||||
:return: the sanitized path
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def sanitize_name(self, name):
|
||||
"""
|
||||
Sanitizes the given file ``name``, stripping it of all invalid characters.
|
||||
:param string name: the file name to sanitize
|
||||
:return: the sanitized name
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def split_path(self, path):
|
||||
"""
|
||||
Split ``path`` into base directory and file name.
|
||||
:param path: the path to split
|
||||
:return: a tuple (base directory, file name)
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def join_path(self, *path):
|
||||
"""
|
||||
Join path elements together
|
||||
:param path: path elements to join
|
||||
:return: joined representation of the path to be usable as fully qualified path for further operations
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def path_on_disk(self, path):
|
||||
"""
|
||||
Retrieves the path on disk for ``path``.
|
||||
|
||||
Note: if the storage is not on disk and there exists no path on disk to refer to it, this method should
|
||||
raise an :class:`io.UnsupportedOperation`
|
||||
|
||||
Opposite of :func:`path_in_storage`.
|
||||
|
||||
:param string path: the virtual path for which to retrieve the path on disk
|
||||
:return: the path on disk to ``path``
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def path_in_storage(self, path):
|
||||
"""
|
||||
Retrieves the equivalent in the storage adapter for ``path``.
|
||||
|
||||
Opposite of :func:`path_on_disk`.
|
||||
|
||||
:param string path: the path for which to retrieve the storage path
|
||||
:return: the path in storage to ``path``
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
class StorageError(Exception):
|
||||
UNKNOWN = "unknown"
|
||||
INVALID_DIRECTORY = "invalid_directory"
|
||||
INVALID_FILE = "invalid_file"
|
||||
INVALID_SOURCE = "invalid_source"
|
||||
INVALID_DESTINATION = "invalid_destination"
|
||||
DOES_NOT_EXIST = "does_not_exist"
|
||||
ALREADY_EXISTS = "already_exists"
|
||||
SOURCE_EQUALS_DESTINATION = "source_equals_destination"
|
||||
NOT_EMPTY = "not_empty"
|
||||
|
||||
def __init__(self, message, code=None, cause=None):
|
||||
BaseException.__init__(self)
|
||||
self.message = message
|
||||
self.cause = cause
|
||||
|
||||
if code is None:
|
||||
code = StorageError.UNKNOWN
|
||||
self.code = code
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
# 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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
from . import Storage, StorageError
|
||||
|
||||
|
||||
class PrinterSDStorage(Storage):
|
||||
def create_print_job(self, path, user=None):
|
||||
from octoprint.comm.job import SDFilePrintjob
|
||||
return SDFilePrintjob("/" + path, user=user)
|
||||
@@ -107,7 +107,7 @@ class MultiStream(io.RawIOBase):
|
||||
their contents in the order they are provided to the constructor.
|
||||
|
||||
Arguments:
|
||||
*streams (io.IOBase): One or more streams to concatenate.
|
||||
*streams (io.RawIOBase): One or more streams to concatenate.
|
||||
"""
|
||||
def __init__(self, *streams):
|
||||
io.RawIOBase.__init__(self)
|
||||
@@ -159,10 +159,12 @@ class LineProcessorStream(io.RawIOBase):
|
||||
While reading from this stream the provided `input_stream` is read line by line, calling the (overridable) method
|
||||
:meth:`.process_line` for each read line.
|
||||
|
||||
Sub classes can thus modify the contents of the `input_stream` in line, while it is being read.
|
||||
Sub classes can thus modify the contents of the `input_stream` in line, while it is being read. Keep in mind that
|
||||
``process_line`` will receive the line as a byte stream - if underlying code needs to operate on unicode you'll need
|
||||
to do the decoding yourself.
|
||||
|
||||
Arguments:
|
||||
input_stream (io.IOBase): The stream to process on the fly.
|
||||
input_stream (io.RawIOBase): The stream to process on the fly.
|
||||
"""
|
||||
|
||||
def __init__(self, input_stream):
|
||||
@@ -220,10 +222,11 @@ class LineProcessorStream(io.RawIOBase):
|
||||
wrapper `input_stream`.
|
||||
|
||||
Arguments:
|
||||
line (str): The line as read from `self.input_stream`
|
||||
line (bytes): The line as read from `self.input_stream` in byte representation (str under Python 2 and
|
||||
bytes under Python 3)
|
||||
|
||||
Returns:
|
||||
str or None: The processed version of the line (might also be multiple lines), or None if the line is to be
|
||||
bytes or None: The processed version of the line (might also be multiple lines), or None if the line is to be
|
||||
stripped from the processed stream.
|
||||
"""
|
||||
return line
|
||||
|
||||
@@ -62,23 +62,23 @@ class OctoPrintStreamHandler(AsyncLogHandlerMixin, logging.StreamHandler):
|
||||
pass
|
||||
|
||||
|
||||
class CommunicationLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFileHandler):
|
||||
class SerialLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFileHandler):
|
||||
|
||||
do_rollover = dict()
|
||||
do_rollover = False
|
||||
suffix_template = "%Y-%m-%d_%H-%M-%S"
|
||||
file_pattern = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$")
|
||||
|
||||
@classmethod
|
||||
def on_open_connection(cls, logger):
|
||||
cls.do_rollover[logger] = True
|
||||
def on_open_connection(cls):
|
||||
cls.do_rollover = True
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
kwargs["encoding"] = kwargs.get("encoding", "utf-8")
|
||||
super(CommunicationLogHandler, self).__init__(*args, **kwargs)
|
||||
super(SerialLogHandler, self).__init__(*args, **kwargs)
|
||||
self.cleanupFiles()
|
||||
|
||||
def shouldRollover(self, record):
|
||||
return self.do_rollover.pop(record.name, False)
|
||||
return self.do_rollover
|
||||
|
||||
def getFilesToDelete(self):
|
||||
"""
|
||||
@@ -107,6 +107,8 @@ class CommunicationLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFil
|
||||
os.remove(path)
|
||||
|
||||
def doRollover(self):
|
||||
self.do_rollover = False
|
||||
|
||||
if self.stream:
|
||||
self.stream.close()
|
||||
self.stream = None
|
||||
@@ -123,7 +125,6 @@ class CommunicationLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFil
|
||||
if not self.delay:
|
||||
self.stream = self._open()
|
||||
|
||||
|
||||
class RecordingLogHandler(logging.Handler):
|
||||
def __init__(self, target=None, *args, **kwargs):
|
||||
super(RecordingLogHandler, self).__init__(*args, **kwargs)
|
||||
|
||||
@@ -23,7 +23,7 @@ import os
|
||||
import logging
|
||||
import threading
|
||||
|
||||
from octoprint.settings import settings as s, SubSettings
|
||||
from octoprint.settings import settings as s
|
||||
from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin)
|
||||
from octoprint.plugin.types import OctoPrintPlugin, SettingsPlugin
|
||||
from octoprint.plugin.types import * # noqa: F403 ## used by multiple other modules
|
||||
@@ -230,7 +230,7 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
|
||||
error_callback(plugin._identifier, plugin, exc)
|
||||
|
||||
|
||||
class PluginSettings(SubSettings):
|
||||
class PluginSettings(object):
|
||||
"""
|
||||
The :class:`PluginSettings` class is the interface for plugins to their own or globally defined settings.
|
||||
|
||||
@@ -315,15 +315,78 @@ class PluginSettings(SubSettings):
|
||||
"""
|
||||
|
||||
def __init__(self, settings, plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None):
|
||||
self.settings = settings
|
||||
self.plugin_key = plugin_key
|
||||
|
||||
SubSettings.__init__(self, settings, ["plugins", plugin_key],
|
||||
defaults=defaults,
|
||||
get_preprocessors=get_preprocessors,
|
||||
set_preprocessors=set_preprocessors)
|
||||
|
||||
if self.defaults is not None:
|
||||
if defaults is not None:
|
||||
self.defaults = dict(plugins=dict())
|
||||
self.defaults["plugins"][plugin_key] = defaults
|
||||
self.defaults["plugins"][plugin_key]["_config_version"] = None
|
||||
else:
|
||||
self.defaults = None
|
||||
|
||||
if get_preprocessors is None:
|
||||
get_preprocessors = dict()
|
||||
self.get_preprocessors = dict(plugins=dict())
|
||||
self.get_preprocessors["plugins"][plugin_key] = get_preprocessors
|
||||
|
||||
if set_preprocessors is None:
|
||||
set_preprocessors = dict()
|
||||
self.set_preprocessors = dict(plugins=dict())
|
||||
self.set_preprocessors["plugins"][plugin_key] = set_preprocessors
|
||||
|
||||
def prefix_path_in_args(args, index=0):
|
||||
result = []
|
||||
if index == 0:
|
||||
result.append(self._prefix_path(args[0]))
|
||||
result.extend(args[1:])
|
||||
else:
|
||||
args_before = args[:index - 1]
|
||||
args_after = args[index + 1:]
|
||||
result.extend(args_before)
|
||||
result.append(self._prefix_path(args[index]))
|
||||
result.extend(args_after)
|
||||
return result
|
||||
|
||||
def add_getter_kwargs(kwargs):
|
||||
if not "defaults" in kwargs and self.defaults is not None:
|
||||
kwargs.update(defaults=self.defaults)
|
||||
if not "preprocessors" in kwargs:
|
||||
kwargs.update(preprocessors=self.get_preprocessors)
|
||||
return kwargs
|
||||
|
||||
def add_setter_kwargs(kwargs):
|
||||
if not "defaults" in kwargs and self.defaults is not None:
|
||||
kwargs.update(defaults=self.defaults)
|
||||
if not "preprocessors" in kwargs:
|
||||
kwargs.update(preprocessors=self.set_preprocessors)
|
||||
return kwargs
|
||||
|
||||
self.access_methods = dict(
|
||||
has =("has", prefix_path_in_args, add_getter_kwargs),
|
||||
get =("get", prefix_path_in_args, add_getter_kwargs),
|
||||
get_int =("getInt", prefix_path_in_args, add_getter_kwargs),
|
||||
get_float =("getFloat", prefix_path_in_args, add_getter_kwargs),
|
||||
get_boolean=("getBoolean", prefix_path_in_args, add_getter_kwargs),
|
||||
set =("set", prefix_path_in_args, add_setter_kwargs),
|
||||
set_int =("setInt", prefix_path_in_args, add_setter_kwargs),
|
||||
set_float =("setFloat", prefix_path_in_args, add_setter_kwargs),
|
||||
set_boolean=("setBoolean", prefix_path_in_args, add_setter_kwargs),
|
||||
remove =("remove", prefix_path_in_args, lambda x: x)
|
||||
)
|
||||
self.deprecated_access_methods = dict(
|
||||
getInt ="get_int",
|
||||
getFloat ="get_float",
|
||||
getBoolean="get_boolean",
|
||||
setInt ="set_int",
|
||||
setFloat ="set_float",
|
||||
setBoolean="set_boolean"
|
||||
)
|
||||
|
||||
def _prefix_path(self, path=None):
|
||||
if path is None:
|
||||
path = list()
|
||||
return ['plugins', self.plugin_key] + path
|
||||
|
||||
def global_has(self, path, **kwargs):
|
||||
return self.settings.has(path, **kwargs)
|
||||
@@ -415,3 +478,53 @@ class PluginSettings(SubSettings):
|
||||
filename += ".log"
|
||||
return os.path.join(self.settings.getBaseFolder("logs"), filename)
|
||||
|
||||
@deprecated("PluginSettings.get_plugin_data_folder has been replaced by OctoPrintPlugin.get_plugin_data_folder",
|
||||
includedoc="Replaced by :func:`~octoprint.plugin.types.OctoPrintPlugin.get_plugin_data_folder`",
|
||||
since="1.2.0")
|
||||
def get_plugin_data_folder(self):
|
||||
path = os.path.join(self.settings.getBaseFolder("data"), self.plugin_key)
|
||||
if not os.path.isdir(path):
|
||||
os.makedirs(path)
|
||||
return path
|
||||
|
||||
def get_all_data(self, **kwargs):
|
||||
merged = kwargs.get("merged", True)
|
||||
asdict = kwargs.get("asdict", True)
|
||||
defaults = kwargs.get("defaults", self.defaults)
|
||||
preprocessors = kwargs.get("preprocessors", self.get_preprocessors)
|
||||
|
||||
kwargs.update(dict(
|
||||
merged=merged,
|
||||
asdict=asdict,
|
||||
defaults=defaults,
|
||||
preprocessors=preprocessors
|
||||
))
|
||||
|
||||
return self.settings.get(self._prefix_path(), **kwargs)
|
||||
|
||||
def clean_all_data(self):
|
||||
self.settings.remove(self._prefix_path())
|
||||
|
||||
def __getattr__(self, item):
|
||||
all_access_methods = list(self.access_methods.keys()) + list(self.deprecated_access_methods.keys())
|
||||
if item in all_access_methods:
|
||||
decorator = None
|
||||
if item in self.deprecated_access_methods:
|
||||
new = self.deprecated_access_methods[item]
|
||||
decorator = deprecated("{old} has been renamed to {new}".format(old=item, new=new), stacklevel=2)
|
||||
item = new
|
||||
|
||||
settings_name, args_mapper, kwargs_mapper = self.access_methods[item]
|
||||
if hasattr(self.settings, settings_name) and callable(getattr(self.settings, settings_name)):
|
||||
orig_func = getattr(self.settings, settings_name)
|
||||
if decorator is not None:
|
||||
orig_func = decorator(orig_func)
|
||||
|
||||
def _func(*args, **kwargs):
|
||||
return orig_func(*args_mapper(args), **kwargs_mapper(kwargs))
|
||||
_func.__name__ = to_native_str(item)
|
||||
_func.__doc__ = orig_func.__doc__ if "__doc__" in dir(orig_func) else None
|
||||
|
||||
return _func
|
||||
|
||||
return getattr(self.settings, item)
|
||||
@@ -39,7 +39,7 @@ import pkginfo
|
||||
|
||||
from past.builtins import unicode
|
||||
|
||||
from octoprint.util import to_unicode
|
||||
from octoprint.util import to_unicode, sv
|
||||
from octoprint.util.version import is_python_compatible, get_python_version_string
|
||||
|
||||
try:
|
||||
@@ -130,6 +130,14 @@ class PluginInfo(object):
|
||||
Bundled plugins will automatically be assumed to be compatible.
|
||||
"""
|
||||
|
||||
attr_hidden = '__plugin_hidden__'
|
||||
"""
|
||||
Module attribute from which to determine if the plugin's hidden or not.
|
||||
|
||||
Only evaluated for bundled plugins, in order to hide them from the Plugin Manager
|
||||
and similar places.
|
||||
"""
|
||||
|
||||
attr_hooks = '__plugin_hooks__'
|
||||
""" Module attribute from which to retrieve the plugin's provided hooks. """
|
||||
|
||||
@@ -444,10 +452,22 @@ class PluginInfo(object):
|
||||
default=">=2.7,<3",
|
||||
incl_metadata=True)
|
||||
|
||||
@property
|
||||
def hidden(self):
|
||||
"""
|
||||
Hidden flag.
|
||||
|
||||
Returns:
|
||||
bool: Whether the plugin should be flagged as hidden or not
|
||||
"""
|
||||
return self._get_instance_attribute(self.__class__.attr_hidden,
|
||||
default=False,
|
||||
incl_metadata=True)
|
||||
|
||||
@property
|
||||
def hooks(self):
|
||||
"""
|
||||
Hooks provided by the plugin. Will be taken from the hooks attribute of the plugin module as defiend in
|
||||
Hooks provided by the plugin. Will be taken from the hooks attribute of the plugin module as defined in
|
||||
:attr:`attr_hooks` if available, otherwise an empty dictionary is returned.
|
||||
|
||||
Returns:
|
||||
@@ -600,6 +620,16 @@ class PluginInfo(object):
|
||||
result[key] = a.value.args[0].s
|
||||
|
||||
break
|
||||
|
||||
for key in (self.__class__.attr_hidden,):
|
||||
for a in reversed(assignments):
|
||||
targets = extract_target_ids(a)
|
||||
if key in targets:
|
||||
if isinstance(a.value, ast.Name) and a.value.id in ("True", "False"):
|
||||
result[key] = bool(a.value.id)
|
||||
|
||||
break
|
||||
|
||||
except SyntaxError:
|
||||
self._logger.exception("Invalid syntax in {} for plugin {}".format(path, self.key))
|
||||
self.invalid_syntax = True
|
||||
@@ -1008,7 +1038,7 @@ class PluginManager(object):
|
||||
# 1st pass: loading the plugins
|
||||
for name, plugin in added.items():
|
||||
try:
|
||||
if not plugin.blacklisted and not plugin.forced_disabled:
|
||||
if not plugin.blacklisted and not plugin.forced_disabled and not plugin.incompatible:
|
||||
self.load_plugin(name, plugin, startup=startup, initialize_implementation=initialize_implementations)
|
||||
except PluginNeedsRestart:
|
||||
pass
|
||||
@@ -1022,7 +1052,7 @@ class PluginManager(object):
|
||||
# 2nd pass: enabling those plugins that need enabling
|
||||
for name, plugin in added.items():
|
||||
try:
|
||||
if plugin.loaded and not plugin.forced_disabled:
|
||||
if plugin.loaded and not plugin.forced_disabled and not plugin.incompatible:
|
||||
if plugin.blacklisted:
|
||||
self.logger.warning("Plugin {} is blacklisted. Not enabling it.".format(plugin))
|
||||
continue
|
||||
@@ -1585,7 +1615,7 @@ class PluginManager(object):
|
||||
sorting_value = None
|
||||
|
||||
plugin_info = self.get_plugin_info(impl[0], require_enabled=False)
|
||||
return sorting_value is None, sorting_value, not plugin_info.bundled if plugin_info else True, impl[0]
|
||||
return sorting_value is None, sv(sorting_value), not plugin_info.bundled if plugin_info else True, sv(impl[0])
|
||||
|
||||
return [impl[1] for impl in sorted(result, key=sort_func)]
|
||||
|
||||
@@ -1672,7 +1702,7 @@ class PluginManager(object):
|
||||
|
||||
def _sort_hooks(self, hook):
|
||||
self._plugin_hooks[hook] = sorted(self._plugin_hooks[hook],
|
||||
key=lambda x: (x[0] is None, x[0], x[1], x[2]))
|
||||
key=lambda x: (x[0] is None, sv(x[0]), sv(x[1]), sv(x[2])))
|
||||
|
||||
def _get_callback_and_order(self, hook):
|
||||
if callable(hook):
|
||||
|
||||
@@ -1391,9 +1391,12 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def is_blueprint_protected(self):
|
||||
"""
|
||||
Whether a login session is needed to access the blueprint if the forcelogin plugin is enabled or not. Requiring
|
||||
Whether a login session by a registered user is needed to access the blueprint's endpoints. Requiring
|
||||
a session is the default. Note that this only restricts access to the blueprint's dynamic methods, static files
|
||||
are always accessible.
|
||||
|
||||
If you want your blueprint's endpoints to have specific permissions, return ``False`` for this and do your
|
||||
permissions checks explicitly.
|
||||
"""
|
||||
|
||||
return True
|
||||
|
||||
@@ -82,6 +82,8 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
|
||||
def on_event(self, event, payload):
|
||||
if event == Events.CONNECTED and self._enable == "always" and self._enable_signal_support:
|
||||
self._printer.commands(["{command} P1".format(command=self._command)])
|
||||
elif event == Events.DISCONNECTED:
|
||||
self._close_prompt()
|
||||
|
||||
#~ SettingsPlugin
|
||||
|
||||
@@ -218,15 +220,18 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
|
||||
return
|
||||
|
||||
self._close_prompt()
|
||||
self._printer.commands(["{command} S{choice}".format(command=self._command,
|
||||
choice=choice)])
|
||||
if "{choice}" in self._command:
|
||||
self._printer.commands([self._command.format(choice=choice)])
|
||||
else:
|
||||
self._printer.commands(["{command} S{choice}".format(command=self._command,
|
||||
choice=choice)])
|
||||
|
||||
|
||||
__plugin_name__ = "Action Command Prompt Support"
|
||||
__plugin_description__ = "Allows your printer to trigger prompts via action commands on the connection"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin your printer will no longer be able to trigger"
|
||||
"confirmation or selection prompts in OctoPrint")
|
||||
" confirmation or selection prompts in OctoPrint")
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_implementation__ = ActionCommandPromptPlugin()
|
||||
__plugin_hooks__ = {
|
||||
|
||||
@@ -5,7 +5,17 @@ $(function() {
|
||||
self.loginState = parameters[0];
|
||||
self.access = parameters[1];
|
||||
|
||||
self._modal = undefined;
|
||||
self.modal = ko.observable(undefined);
|
||||
|
||||
self.text = ko.observable();
|
||||
self.buttons = ko.observableArray([]);
|
||||
|
||||
self.active = ko.pureComputed(function() {
|
||||
return self.text() !== undefined;
|
||||
});
|
||||
self.visible = ko.pureComputed(function() {
|
||||
return self.modal() !== undefined;
|
||||
});
|
||||
|
||||
self.requestData = function() {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT)) return;
|
||||
@@ -16,26 +26,35 @@ $(function() {
|
||||
|
||||
self.fromResponse = function(data) {
|
||||
if (data.hasOwnProperty("text") && data.hasOwnProperty("choices")) {
|
||||
self._showPrompt(data.text, data.choices);
|
||||
self.text(data.text);
|
||||
self.buttons(data.choices);
|
||||
self.showPrompt();
|
||||
} else {
|
||||
self.text(undefined);
|
||||
self.buttons([]);
|
||||
}
|
||||
};
|
||||
|
||||
self._showPrompt = function(text, buttons) {
|
||||
self.showPrompt = function() {
|
||||
var text = self.text();
|
||||
var buttons = self.buttons();
|
||||
|
||||
var opts = {
|
||||
title: gettext("Message from your printer"),
|
||||
message: text,
|
||||
selections: buttons,
|
||||
maycancel: true, // see #3171
|
||||
onselect: function(index) {
|
||||
if (index > -1) {
|
||||
self._select(index);
|
||||
}
|
||||
},
|
||||
onclose: function() {
|
||||
self._modal = undefined;
|
||||
self.modal(undefined);
|
||||
}
|
||||
};
|
||||
|
||||
self._modal = showSelectionDialog(opts)
|
||||
self.modal(showSelectionDialog(opts));
|
||||
};
|
||||
|
||||
self._select = function(index) {
|
||||
@@ -43,8 +62,9 @@ $(function() {
|
||||
};
|
||||
|
||||
self._closePrompt = function() {
|
||||
if (self._modal) {
|
||||
self._modal.modal("hide");
|
||||
var modal = self.modal();
|
||||
if (modal) {
|
||||
modal.modal("hide");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -60,10 +80,14 @@ $(function() {
|
||||
|
||||
switch (data.action) {
|
||||
case "show": {
|
||||
self._showPrompt(data.text, data.choices);
|
||||
self.text(data.text);
|
||||
self.buttons(data.choices);
|
||||
self.showPrompt();
|
||||
break;
|
||||
}
|
||||
case "close": {
|
||||
self.text(undefined);
|
||||
self.buttons([]);
|
||||
self._closePrompt();
|
||||
break;
|
||||
}
|
||||
@@ -74,6 +98,7 @@ $(function() {
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: ActionCommandPromptViewModel,
|
||||
dependencies: ["loginStateViewModel", "accessViewModel"]
|
||||
dependencies: ["loginStateViewModel", "accessViewModel"],
|
||||
elements: ["#navbar_plugin_action_command_prompt"]
|
||||
});
|
||||
});
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
<a id="navbar_show_prompt" class="pull-right" style="display: none" href="javascript:void(0)" data-bind="click: function() { showPrompt(); }, visible: active() && !visible()" title="{{ _('Message from your printer')|edq }}">
|
||||
<i class="fa fa-commenting-o"></i>
|
||||
</a>
|
||||
@@ -242,6 +242,9 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
def is_blueprint_protected(self):
|
||||
return False
|
||||
|
||||
##~~ EventHandlerPlugin
|
||||
|
||||
def on_event(self, event, payload):
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
<a id="navbar_show_announcements" class="pull-right" href="javascript:void(0)" data-bind="click: function() { showAnnouncementDialog(); }" title="{{ _('Announcements') }}">
|
||||
<a id="navbar_show_announcements" class="pull-right" href="javascript:void(0)" data-bind="click: function() { showAnnouncementDialog(); }" title="{{ _('Announcements')|edq }}">
|
||||
<i class="fa" data-bind="css: {'fa-bell-o': !unread(), 'fa-bell': unread()}"></i>
|
||||
</a>
|
||||
@@ -7,7 +7,7 @@ import os
|
||||
import yaml
|
||||
import io
|
||||
import time
|
||||
from binascii import hexlify
|
||||
import uuid
|
||||
from collections import defaultdict
|
||||
from flask_babel import gettext
|
||||
|
||||
@@ -15,12 +15,11 @@ import octoprint.plugin
|
||||
from octoprint.settings import valid_boolean_trues
|
||||
from octoprint.server.util.flask import restricted_access, no_firstrun_access
|
||||
from octoprint.server import NO_CONTENT, current_user, admin_permission
|
||||
from octoprint.util import atomic_write, monotonic_time, ResettableTimer
|
||||
from octoprint.util import atomic_write, monotonic_time, ResettableTimer, generate_api_key
|
||||
|
||||
from octoprint.access import ADMIN_GROUP
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
|
||||
CUTOFF_TIME = 10 * 60 # 10min
|
||||
POLL_TIMEOUT = 5 # 5 seconds
|
||||
|
||||
@@ -45,6 +44,12 @@ class PendingDecision(object):
|
||||
user_id=self.user_id,
|
||||
user_token=self.user_token)
|
||||
|
||||
def __repr__(self):
|
||||
return u"PendingDecision({!r}, {!r}, {!r}, {!r}, timeout_callback=...)".format(self.app_id,
|
||||
self.app_token,
|
||||
self.user_id,
|
||||
self.user_token)
|
||||
|
||||
|
||||
class ReadyDecision(object):
|
||||
def __init__(self, app_id, app_token, user_id):
|
||||
@@ -56,6 +61,11 @@ class ReadyDecision(object):
|
||||
def for_pending(cls, pending, user_id):
|
||||
return cls(pending.app_id, pending.app_token, user_id)
|
||||
|
||||
def __repr__(self):
|
||||
return u"ReadyDecision({!r}, {!r}, {!r})".format(self.app_id,
|
||||
self.app_token,
|
||||
self.user_id)
|
||||
|
||||
|
||||
class ActiveKey(object):
|
||||
def __init__(self, app_id, api_key, user_id):
|
||||
@@ -76,6 +86,11 @@ class ActiveKey(object):
|
||||
def for_internal(cls, internal, user_id):
|
||||
return cls(internal["app_id"], internal["api_key"], user_id)
|
||||
|
||||
def __repr__(self):
|
||||
return u"ActiveKey({!r}, {!r}, {!r})".format(self.app_id,
|
||||
self.api_key,
|
||||
self.user_id)
|
||||
|
||||
|
||||
class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.BlueprintPlugin,
|
||||
@@ -135,12 +150,15 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
||||
@no_firstrun_access
|
||||
def handle_request(self):
|
||||
data = flask.request.json
|
||||
if data is None:
|
||||
return flask.make_response("Missing key request", 400)
|
||||
|
||||
if not "app" in data:
|
||||
return flask.make_response("No app name provided", 400)
|
||||
|
||||
app_name = data["app"]
|
||||
user_id = None
|
||||
if "user" in data:
|
||||
if "user" in data and data["user"]:
|
||||
user_id = data["user"]
|
||||
|
||||
app_token, user_token = self._add_pending_decision(app_name, user_id=user_id)
|
||||
@@ -362,7 +380,7 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
||||
for user_id, data in self._keys.items():
|
||||
if any(filter(lambda x: x.api_key == api_key, data)):
|
||||
if self._user_manager.enabled:
|
||||
return self._user_manager.findUser(userid=user_id)
|
||||
return self._user_manager.find_user(userid=user_id)
|
||||
elif user_id == "_admin" or user_id == "dummy":
|
||||
# dummy = backwards compatible
|
||||
return self._user_manager.anonymous_user_factory()
|
||||
@@ -380,7 +398,7 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
||||
return result
|
||||
|
||||
def _generate_key(self):
|
||||
return hexlify(os.urandom(16))
|
||||
return generate_api_key()
|
||||
|
||||
def _load_keys(self):
|
||||
with self._keys_lock:
|
||||
|
||||
@@ -52,7 +52,7 @@ $(function() {
|
||||
.done(self.requestData);
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: key}),
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: _.escape(key)}),
|
||||
perform);
|
||||
};
|
||||
|
||||
@@ -68,7 +68,7 @@ $(function() {
|
||||
|
||||
self.promptForAccess = function(app, token) {
|
||||
var message = gettext("\"<strong>%(app)s</strong>\" has requested access to control OctoPrint through the API.");
|
||||
message = _.sprintf(message, {app: app});
|
||||
message = _.sprintf(message, {app: _.escape(app)});
|
||||
message = "<p>" + message + "</p><p>" + gettext("Do you want to allow access to this application with your user account?") + "</p>";
|
||||
return new PNotify({
|
||||
title: gettext("Access Request"),
|
||||
@@ -210,7 +210,7 @@ $(function() {
|
||||
.done(self.requestData);
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: key}),
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: _.escape(key)}),
|
||||
perform);
|
||||
};
|
||||
|
||||
@@ -258,11 +258,11 @@ $(function() {
|
||||
handler = function(key) {
|
||||
return OctoPrint.plugins.appkeys.revokeKey(key)
|
||||
.done(function() {
|
||||
deferred.notify(_.sprintf(gettext("Revoked %(key)s..."), {key: key}), true);
|
||||
deferred.notify(_.sprintf(gettext("Revoked %(key)s..."), {key: _.escape(key)}), true);
|
||||
})
|
||||
.fail(function(jqXHR) {
|
||||
var short = _.sprintf(gettext("Revocation of %(key)s failed, continuing..."), {key: key});
|
||||
var long = _.sprintf(gettext("Deletion of %(key)s failed: %(error)s"), {key: key, error: jqXHR.responseText});
|
||||
var short = _.sprintf(gettext("Revocation of %(key)s failed, continuing..."), {key: _.escape(key)});
|
||||
var long = _.sprintf(gettext("Deletion of %(key)s failed: %(error)s"), {key: _.escape(key), error: _.escape(jqXHR.responseText)});
|
||||
deferred.notify(short, long, false);
|
||||
});
|
||||
};
|
||||
|
||||
Loaded 100 of 285 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user