Compare commits
251
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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.3.13
|
||||
# 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.3.13 2a42f02aecaedf2c55579984e0bc94e44402cc15 pep440-dev
|
||||
fix/.* 1.3.13 2a42f02aecaedf2c55579984e0bc94e44402cc15 pep440-dev
|
||||
improve/.* 1.3.13 2a42f02aecaedf2c55579984e0bc94e44402cc15 pep440-dev
|
||||
|
||||
# staging/maintenance is currently the branch for preparation of 1.3.11rc4
|
||||
# staging/maintenance is currently the branch for preparation of 1.3.12rc4
|
||||
# so is regressionfix/...
|
||||
staging/maintenance 1.3.11rc4 af3285854995fb5b910fd2ce869e26c02d57bbc2 pep440-dev
|
||||
regressionfix/.* 1.3.11rc4 af3285854995fb5b910fd2ce869e26c02d57bbc2 pep440-dev
|
||||
staging/maintenance 1.3.12rc4 a70a45f062687beb510fb3192e4227754e1dff39 pep440-dev
|
||||
regressionfix/.* 1.3.12rc4 a70a45f062687beb510fb3192e4227754e1dff39 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 the branch for preparation of 1.4.0rc2
|
||||
staging/devel 1.4.0rc2 2da7aa358d950b4567aaab8f18d6b5779193e077 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.
|
||||
+10
-5
@@ -8,8 +8,8 @@ thanks to everyone who contributed!
|
||||
|
||||
* Andre Bubel
|
||||
* Andrew Moorby
|
||||
* ANTONIO AUGUSTO DE LIMA PONTES
|
||||
* Arnljot Arntsen
|
||||
* Bjorn Breckenridge
|
||||
* Boris Hussein
|
||||
* Brad Jackson
|
||||
* Christian Petropolis
|
||||
@@ -22,36 +22,41 @@ thanks to everyone who contributed!
|
||||
* Eric Betts
|
||||
* Ernesto Martinez
|
||||
* Franziska Kunsmann
|
||||
* GadgetAngel
|
||||
* George Robles
|
||||
* jean-claude migneault
|
||||
* Jeff Renfer
|
||||
* Jefferson Hunt
|
||||
* Jeremiah Avery
|
||||
* Joseph Payne
|
||||
* John Robinson (JRo)
|
||||
* Joshua Wills
|
||||
* Justin Kaufman
|
||||
* Kaile Riser
|
||||
* Kale Stedman
|
||||
* Kazuhiro Ogura
|
||||
* Kyle Menigoz
|
||||
* LA 3D Printer Repair
|
||||
* Lee Dohm
|
||||
* LulzBot®
|
||||
* Makespace Madrid
|
||||
* Mark Walker
|
||||
* Martin Majewski
|
||||
* Michael Aumock
|
||||
* Miles Flavel
|
||||
* Mosaic Manufacturing
|
||||
* OMER MEHMET SUTAS
|
||||
* Patrick Glyré
|
||||
* Patrick McGinnis
|
||||
* Prof Yuh Wen Chen
|
||||
* Randy C. Will
|
||||
* Ranjib Dey
|
||||
* Robert Gusek
|
||||
* Samer Najia
|
||||
* Shawn Lewis
|
||||
* Simon Hallam
|
||||
* Stefan Krister
|
||||
* Sven Mueller
|
||||
* TEVO 3D Printers
|
||||
* Trent Shumay
|
||||
* Ulrich Kempken
|
||||
* Vladislav Kuzemchik
|
||||
|
||||
and 1544 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
||||
and 1653 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [Github Sponsors](https://github.com/users/foosel/sponsorship)!
|
||||
@@ -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:
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ REST API
|
||||
|
||||
general.rst
|
||||
version.rst
|
||||
apps.rst
|
||||
connection.rst
|
||||
files.rst
|
||||
job.rst
|
||||
|
||||
@@ -350,7 +350,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:
|
||||
@@ -630,7 +630,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:
|
||||
@@ -770,7 +770,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 +778,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,7 +790,7 @@ 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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
+35
-2
@@ -104,7 +104,8 @@ ClientOpened
|
||||
|
||||
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
|
||||
|
||||
@@ -115,6 +116,19 @@ ClientClosed
|
||||
|
||||
* ``remoteAddress``: the remote address (IP) of the client that disconnected
|
||||
|
||||
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 +165,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 +605,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 +617,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 +630,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 +641,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 +657,7 @@ SlicingProfileAdded
|
||||
* ``profile``: the profile that was added
|
||||
|
||||
SlicingProfileModified
|
||||
A new slicing profile was modified.
|
||||
A slicing profile was modified.
|
||||
|
||||
Payload:
|
||||
|
||||
@@ -661,3 +682,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
|
||||
@@ -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.
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
@@ -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,7 +32,7 @@ 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
|
||||
|
||||
@@ -35,10 +40,10 @@ INSTALL_REQUIRES = [
|
||||
"Flask-Principal>=0.4,<0.5",
|
||||
"Flask-Babel>=0.12,<0.13",
|
||||
"Flask-Assets>=0.12,<0.13",
|
||||
"werkzeug>=0.15.1,<0.16",
|
||||
"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 = []
|
||||
|
||||
@@ -19,15 +19,18 @@ import logging
|
||||
# noinspection PyCompatibility
|
||||
from builtins import range, bytes
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.settings import settings as s
|
||||
|
||||
from octoprint.util import atomic_write, to_bytes, deprecated, monotonic_time
|
||||
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):
|
||||
@@ -92,14 +99,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)
|
||||
|
||||
return user
|
||||
|
||||
def logout_user(self, user):
|
||||
if user is None or user.is_anonymous:
|
||||
if user is None or user.is_anonymous or isinstance(user, AdminUser):
|
||||
return
|
||||
|
||||
if isinstance(user, LocalProxy):
|
||||
@@ -124,28 +132,31 @@ class UserManager(GroupChangeListener, object):
|
||||
try:
|
||||
listener.on_user_logged_out(user)
|
||||
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)
|
||||
|
||||
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)
|
||||
|
||||
@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 +165,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 +275,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 +286,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 +316,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
|
||||
|
||||
@@ -428,13 +446,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 +555,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 +694,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
|
||||
|
||||
@@ -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)
|
||||
@@ -47,6 +47,10 @@ class Events(object):
|
||||
CLIENT_OPENED = "ClientOpened"
|
||||
CLIENT_CLOSED = "ClientClosed"
|
||||
|
||||
# user login/logout
|
||||
USER_LOGGED_IN = "UserLoggedIn"
|
||||
USER_LOGGED_OUT = "UserLoggedOut"
|
||||
|
||||
# File management
|
||||
UPLOAD = "Upload"
|
||||
FILE_SELECTED = "FileSelected"
|
||||
@@ -227,14 +231,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)
|
||||
@@ -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:
|
||||
@@ -447,7 +447,7 @@ class PluginInfo(object):
|
||||
@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:
|
||||
@@ -1585,7 +1585,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 +1672,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):
|
||||
|
||||
@@ -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>
|
||||
@@ -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
|
||||
|
||||
@@ -45,6 +45,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 +62,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 +87,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 +151,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 +381,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 +399,7 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
||||
return result
|
||||
|
||||
def _generate_key(self):
|
||||
return hexlify(os.urandom(16))
|
||||
return ''.join('%02X' % z for z in bytes(uuid.uuid4().bytes))
|
||||
|
||||
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);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -40,8 +40,8 @@
|
||||
<tr>
|
||||
<td class="settings_plugin_appkeys_checkbox"><input type="checkbox" data-bind="value: api_key, checked: $root.markedForDeletion"></td>
|
||||
<td class="settings_plugin_appkeys_user"><span data-bind="text: user_id"></span></td>
|
||||
<td class="settings_plugin_appkeys_app"><span data-bind="text: app_id"></span><br /><small class="muted">{{ _('API Key') }}: <span data-bind="text: api_key"></span> <a href="javascript:void(0)" title="{{ _('Copy API Key to clipboard') }}" data-bind="click: function() { copyToClipboard(api_key) }"><i class="fa fa-copy"></i></a></small></td>
|
||||
<td class="settings_plugin_appkeys_actions"><a href="javascript:void(0)" title="{{ _('Revoke') }}" class="fa fa-trash-o" data-bind="click: function() { $parent.revokeKey($data.api_key, $data.user_id) }"></a></td>
|
||||
<td class="settings_plugin_appkeys_app"><span data-bind="text: app_id"></span><br /><small class="muted">{{ _('API Key') }}: <span data-bind="text: api_key"></span> <a href="javascript:void(0)" title="{{ _('Copy API Key to clipboard')|edq }}" data-bind="click: function() { copyToClipboard(api_key) }"><i class="fa fa-copy"></i></a></small></td>
|
||||
<td class="settings_plugin_appkeys_actions"><a href="javascript:void(0)" title="{{ _('Revoke')|edq }}" class="fa fa-trash-o" data-bind="click: function() { $parent.revokeKey($data.api_key, $data.user_id) }"></a></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
@@ -13,8 +13,8 @@
|
||||
</thead>
|
||||
<tbody data-bind="foreach: keys.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_appkeys_app"><span data-bind="text: app_id"></span><br /><small class="muted">{{ _('API Key') }}: <span data-bind="text: api_key"></span> <a href="javascript:void(0)" title="{{ _('Copy API Key to clipboard') }}" data-bind="click: function() { copyToClipboard(api_key) }"><i class="fa fa-copy"></i></a></small></td>
|
||||
<td class="settings_plugin_appkeys_actions"><a href="javascript:void(0)" title="{{ _('Revoke') }}" class="fa fa-trash-o" data-bind="click: function() { $parent.revokeKey($data.api_key) }"></a></td>
|
||||
<td class="settings_plugin_appkeys_app"><span data-bind="text: app_id"></span><br /><small class="muted">{{ _('API Key') }}: <span data-bind="text: api_key"></span> <a href="javascript:void(0)" title="{{ _('Copy API Key to clipboard')|edq }}" data-bind="click: function() { copyToClipboard(api_key) }"><i class="fa fa-copy"></i></a></small></td>
|
||||
<td class="settings_plugin_appkeys_actions"><a href="javascript:void(0)" title="{{ _('Revoke')|edq }}" class="fa fa-trash-o" data-bind="click: function() { $parent.revokeKey($data.api_key) }"></a></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
@@ -633,6 +633,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
try:
|
||||
if exclude is None:
|
||||
exclude = []
|
||||
if not isinstance(exclude, list):
|
||||
exclude = list(exclude)
|
||||
|
||||
if "timelapse" in exclude:
|
||||
exclude.append("timelapse_tmp")
|
||||
|
||||
@@ -85,7 +85,7 @@ $(function() {
|
||||
self.requestData();
|
||||
});
|
||||
};
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to delete backup file \"%(name)s\"."), {name: backup}),
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to delete backup file \"%(name)s\"."), {name: _.escape(backup)}),
|
||||
perform);
|
||||
};
|
||||
|
||||
@@ -101,7 +101,7 @@ $(function() {
|
||||
|
||||
OctoPrint.plugins.backup.restoreBackup(backup);
|
||||
};
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to restore the backup file \"%(name)s\". This cannot be undone."), {name: backup}),
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to restore the backup file \"%(name)s\". This cannot be undone."), {name: _.escape(backup)}),
|
||||
perform);
|
||||
};
|
||||
|
||||
@@ -117,7 +117,7 @@ $(function() {
|
||||
|
||||
self.backupUploadData.submit();
|
||||
};
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to upload and restore the backup file \"%(name)s\". This cannot be undone."), {name: self.backupUploadName()}),
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to upload and restore the backup file \"%(name)s\". This cannot be undone."), {name: _.escape(self.backupUploadName())}),
|
||||
perform);
|
||||
};
|
||||
|
||||
@@ -182,7 +182,7 @@ $(function() {
|
||||
self.backupInProgress(false);
|
||||
new PNotify({
|
||||
title: gettext("Creating the backup failed"),
|
||||
text: _.sprintf(gettext("OctoPrint could not create your backup. Please consult <code>octoprint.log</code> for details. Error: %(error)s"), {error:data.error}),
|
||||
text: _.sprintf(gettext("OctoPrint could not create your backup. Please consult <code>octoprint.log</code> for details. Error: %(error)s"), {error: _.escape(data.error)}),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
@@ -197,16 +197,16 @@ $(function() {
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.loglines.push({line: gettext("Restore successful! The server will now be restarted!"), stream: "message"});
|
||||
self.restoreInProgress(false);
|
||||
} else if (data.type === "install_plugin") {
|
||||
} else if (data.type === "installing_plugin") {
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.loglines.push({
|
||||
line: _.sprintf(gettext("Installing plugin \"%(plugin)s}\"..."), {plugin: data.plugin.name}),
|
||||
line: _.sprintf(gettext("Installing plugin \"%(plugin)s\"..."), {plugin: _.escape(data.plugin)}),
|
||||
stream: "message"
|
||||
});
|
||||
} else if (data.type === "plugin_incompatible") {
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.loglines.push({
|
||||
line: _.sprintf(gettext("Cannot install plugin \"%(plugin)s\" due to it being incompatible to this OctoPrint version and/or underlying operating system"), {plugin: data.plugin.key}),
|
||||
line: _.sprintf(gettext("Cannot install plugin \"%(plugin)s\" due to it being incompatible to this OctoPrint version and/or underlying operating system"), {plugin: _.escape(data.plugin.key)}),
|
||||
stream: "stderr"
|
||||
});
|
||||
} else if (data.type === "unknown_plugins") {
|
||||
@@ -245,11 +245,11 @@ $(function() {
|
||||
handler = function(filename) {
|
||||
return OctoPrint.plugins.backup.deleteBackup(filename)
|
||||
.done(function() {
|
||||
deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: filename}), true);
|
||||
deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: _.escape(filename)}), true);
|
||||
})
|
||||
.fail(function(jqXHR) {
|
||||
var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: filename});
|
||||
var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: filename, error: jqXHR.responseText});
|
||||
var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: _.escape(filename)});
|
||||
var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: _.escape(filename), error: _.escape(jqXHR.responseText)});
|
||||
deferred.notify(short, long, false);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -46,7 +46,7 @@
|
||||
<td class="settings_plugin_backup_name" data-bind="text: name"></td>
|
||||
<td class="settings_plugin_backup_date" data-bind="text: formatDate(date)"></td>
|
||||
<td class="settings_plugin_backup_size" data-bind="text: formatSize(size)"></td>
|
||||
<td class="settings_plugin_backup_actions"><a href="javascript:void(0)" title="{{ _('Delete') }}" class="fa fa-trash-o" data-bind="click: function() { $parent.removeBackup($data.name) }, css: {disabled: $root.backupInProgress() || $root.restoreInProgress()"></a> | <a href="javascript:void(0)" title="{{ _('Download') }}" class="fa fa-download" data-bind="attr: {href: url}"></a><span data-bind="visible: $parent.restoreSupported()"> | <a href="javascript:void(0)" title="{{ _('Restore') }}" data-bind="click: function() { $parent.restoreBackup($data.name) }, css: {disabled: $root.backupInProgress() || $root.restoreInProgress()"><i class="fa fa-refresh"></i></a></span></td>
|
||||
<td class="settings_plugin_backup_actions"><a href="javascript:void(0)" title="{{ _('Delete')|edq }}" class="fa fa-trash-o" data-bind="click: function() { $parent.removeBackup($data.name) }, css: {disabled: $root.backupInProgress() || $root.restoreInProgress()"></a> | <a href="javascript:void(0)" title="{{ _('Download')|edq }}" class="fa fa-download" data-bind="attr: {href: url}"></a><span data-bind="visible: $parent.restoreSupported()"> | <a href="javascript:void(0)" title="{{ _('Restore')|edq }}" data-bind="click: function() { $parent.restoreBackup($data.name) }, css: {disabled: $root.backupInProgress() || $root.restoreInProgress()"><i class="fa fa-refresh"></i></a></span></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
|
||||
<p>{% trans %}
|
||||
Finally, please decide on whether to enable or disable the connectivity check. You may change the configuration at
|
||||
any time to a later date through Settings > Server right from within OctoPrint.
|
||||
any time through Settings > Server right from within OctoPrint.
|
||||
{% endtrans %}</p>
|
||||
|
||||
<div class="row-fluid">
|
||||
|
||||
@@ -212,7 +212,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
|
||||
def zeroconf_unregister(self, reg_type, port=None):
|
||||
"""
|
||||
Unregisteres a previously registered Zeroconf/Bonjour/Avahi service identified by service and port.
|
||||
Unregisters a previously registered Zeroconf/Bonjour/Avahi service identified by service and port.
|
||||
|
||||
:param reg_type: the type of the service to be unregistered
|
||||
:param port: the port of the service to be unregistered, defaults to OctoPrint's (public) port if not given
|
||||
|
||||
@@ -7,13 +7,14 @@ __copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms
|
||||
import octoprint.plugin
|
||||
import logging
|
||||
|
||||
from octoprint.util import get_fully_qualified_classname as fqcn
|
||||
from octoprint.util.version import get_octoprint_version_string, is_released_octoprint_version
|
||||
|
||||
from flask import jsonify
|
||||
from flask_babel import gettext
|
||||
|
||||
SENTRY_URL_SERVER = "https://4069187705ab4e76921eb19db2e9ccbb@sentry.io/1373987"
|
||||
SENTRY_URL_COREUI = "https://a4ab48f27daf4c129392b78be15412b8@sentry.io/1374096"
|
||||
SENTRY_URL_SERVER = "https://bcd62166a2b145aa9818947bfb76706f@sentry.io/1373987"
|
||||
SENTRY_URL_COREUI = "https://217a5d75940b443eaaec347bb30c128d@sentry.io/1374096"
|
||||
|
||||
SETTINGS_DEFAULTS = dict(enabled=False,
|
||||
enabled_unreleased=False,
|
||||
@@ -29,19 +30,24 @@ import tornado.websocket
|
||||
|
||||
IGNORED_EXCEPTIONS = [
|
||||
# serial exceptions in octoprint.util.comm
|
||||
(serial.SerialException, lambda exc, logger, plugin: logger == "octoprint.util.comm"),
|
||||
(serial.SerialException, lambda exc, logger, plugin, cb: logger == "octoprint.util.comm"),
|
||||
|
||||
# isp errors during port auto detection in octoprint.util.comm
|
||||
(octoprint.util.avr_isp.ispBase.IspError, lambda exc, logger, plugin: logger == "octoprint.util.comm"),
|
||||
(octoprint.util.avr_isp.ispBase.IspError, lambda exc, logger, plugin, cb: logger == "octoprint.util.comm"),
|
||||
|
||||
# IOErrors of any kind due to a full file system
|
||||
(IOError, lambda exc, logger, plugin: getattr(exc, "errno") and exc.errno in (getattr(errno, "ENOSPC"),)),
|
||||
(IOError, lambda exc, logger, plugin, cb: getattr(exc, "errno") and exc.errno in (getattr(errno, "ENOSPC"),)),
|
||||
|
||||
# RequestExceptions of any kind
|
||||
requests.exceptions.RequestException,
|
||||
|
||||
# Tornado WebSocketErrors of any kind
|
||||
tornado.websocket.WebSocketError
|
||||
tornado.websocket.WebSocketError,
|
||||
|
||||
# Anything triggered by or in third party plugin Astroprint
|
||||
(Exception, lambda exc, logger, plugin, cb: logger.startswith("octoprint.plugins.astroprint")
|
||||
or plugin == "astroprint"
|
||||
or cb.startswith("octoprint_astroprint."))
|
||||
]
|
||||
|
||||
try:
|
||||
@@ -138,6 +144,7 @@ def _enable_errortracking():
|
||||
handled = True
|
||||
logger = event.get("logger", "")
|
||||
plugin = event.get("extra", dict()).get("plugin", None)
|
||||
callback = event.get("extra", dict()).get("callback", None)
|
||||
|
||||
for ignore in IGNORED_EXCEPTIONS:
|
||||
if isinstance(ignore, tuple):
|
||||
@@ -147,8 +154,8 @@ def _enable_errortracking():
|
||||
matcher = lambda *args: True
|
||||
|
||||
exc = hint["exc_info"][1]
|
||||
if isinstance(exc, ignored_exc) and matcher(exc, logger, plugin):
|
||||
# exception ignored for logger
|
||||
if isinstance(exc, ignored_exc) and matcher(exc, logger, plugin, callback):
|
||||
# exception ignored for logger, plugin and/or callback
|
||||
return None
|
||||
|
||||
elif isinstance(ignore, type):
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label" title="{{ _('Random unique instance ID') }}">{{ _('Instance ID') }}</label>
|
||||
<label class="control-label" title="{{ _('Random unique instance ID')|edq }}">{{ _('Instance ID') }}</label>
|
||||
<div class="controls">
|
||||
<span style="padding-top: 5px; margin-bottom: 5px; display: inline-block" data-bind="text: settings.plugins.errortracking.unique_id() || 'N/A'"></span>
|
||||
</div>
|
||||
|
||||
@@ -121,7 +121,7 @@ $(function() {
|
||||
.done(self.requestData);
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to delete log file \"%(name)s\"."), {name: filename}),
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to delete log file \"%(name)s\"."), {name: _.escape(filename)}),
|
||||
perform);
|
||||
};
|
||||
|
||||
@@ -172,11 +172,11 @@ $(function() {
|
||||
var handler = function(filename) {
|
||||
return OctoPrint.plugins.logging.deleteLog(filename)
|
||||
.done(function() {
|
||||
deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: filename}), true);
|
||||
deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: _.escape(filename)}), true);
|
||||
})
|
||||
.fail(function(jqXHR) {
|
||||
var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: filename});
|
||||
var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: filename, error: jqXHR.responseText});
|
||||
var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: _.escape(filename)});
|
||||
var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: _.escape(filename), error: _.escape(jqXHR.responseText)});
|
||||
deferred.notify(short, long, false);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -84,7 +84,7 @@
|
||||
</select>
|
||||
</div>
|
||||
<div class="span1">
|
||||
<a title="{{ _('Remove') }}" class="btn btn-danger" data-bind="click: $parent.removeLogger"><i class="icon-trash"></i></a>
|
||||
<a title="{{ _('Remove')|edq }}" class="btn btn-danger" data-bind="click: $parent.removeLogger"><i class="icon-trash"></i></a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -103,7 +103,7 @@
|
||||
</select>
|
||||
</div>
|
||||
<div class="span1">
|
||||
<a title="{{ _('Add') }}" class="btn btn-primary" data-bind="click: $root.addLogger"><i class="icon-plus"></i></a>
|
||||
<a title="{{ _('Add')|edq }}" class="btn btn-primary" data-bind="click: $root.addLogger"><i class="icon-plus"></i></a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -19,14 +19,23 @@ _PROC_DT_MODEL_PATH = "/proc/device-tree/model"
|
||||
_OCTOPI_VERSION_PATH = "/etc/octopi_version"
|
||||
_VCGENCMD_THROTTLE = "/usr/bin/vcgencmd get_throttled"
|
||||
|
||||
### uncomment for local debugging
|
||||
#import sys
|
||||
#base = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "tests", "plugins", "pi_support", "fakes"))
|
||||
#_PROC_DT_MODEL_PATH = os.path.join(base, "fake_model.txt")
|
||||
#_OCTOPI_VERSION_PATH = os.path.join(base, "fake_octopi.txt")
|
||||
#_VCGENCMD_THROTTLE = "{} {}".format(sys.executable, os.path.join(base, "fake_vcgencmd.py"))
|
||||
#import itertools
|
||||
#_VCGENCMD_OUTPUT = itertools.chain(iter(("0x0", "0x0", "0x50005", "0x50000", "0x70007")), itertools.repeat("0x70000"))
|
||||
_CHECK_INTERVAL_OK = 300
|
||||
_CHECK_INTERVAL_THROTTLED = 30
|
||||
|
||||
__LOCAL_DEBUG = False
|
||||
|
||||
if __LOCAL_DEBUG:
|
||||
### mocks & settings for local debugging
|
||||
import sys
|
||||
base = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "tests", "plugins", "pi_support", "fakes"))
|
||||
_PROC_DT_MODEL_PATH = os.path.join(base, "fake_model.txt")
|
||||
_OCTOPI_VERSION_PATH = os.path.join(base, "fake_octopi.txt")
|
||||
_VCGENCMD_THROTTLE = "{} {}".format(sys.executable, os.path.join(base, "fake_vcgencmd.py"))
|
||||
import itertools
|
||||
_VCGENCMD_OUTPUT = itertools.chain(iter(("0x0", "0x0", "0x50005", "0x50000", "0x70007")), itertools.repeat("0x70005"))
|
||||
|
||||
_CHECK_INTERVAL_OK = 10
|
||||
_CHECK_INTERVAL_THROTTLED = 5
|
||||
|
||||
|
||||
# see https://www.raspberrypi.org/forums/viewtopic.php?f=63&t=147781&start=50#p972790
|
||||
@@ -135,8 +144,11 @@ def get_proc_dt_model():
|
||||
|
||||
|
||||
def get_vcgencmd_throttled_state(command):
|
||||
output = sarge.get_stdout(command)
|
||||
#output = "throttled={}".format(next(_VCGENCMD_OUTPUT)) # for local debugging
|
||||
if __LOCAL_DEBUG:
|
||||
output = "throttled={}".format(next(_VCGENCMD_OUTPUT)) # mock for local debugging
|
||||
else:
|
||||
output = sarge.get_stdout(command)
|
||||
|
||||
if not "throttled=0x" in output:
|
||||
raise ValueError("cannot parse \"{}\" output: {}".format(command, output))
|
||||
|
||||
@@ -237,11 +249,9 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
|
||||
|
||||
def _check_throttled_state_interval(self):
|
||||
if self._throttle_state.current_issue:
|
||||
# check state every 30s if something's currently amiss
|
||||
return 30
|
||||
return _CHECK_INTERVAL_THROTTLED
|
||||
else:
|
||||
# check state every 5min if nothing's currently amiss
|
||||
return 300
|
||||
return _CHECK_INTERVAL_OK
|
||||
|
||||
def _check_throttled_state_condition(self):
|
||||
return self._throttle_functional
|
||||
@@ -305,7 +315,7 @@ __plugin_name__ = "Pi Support Plugin"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_description__ = "Provides additional information about your Pi in the UI."
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to "
|
||||
"provide additional information about your Pi,"
|
||||
"provide additional information about your Pi, "
|
||||
"which will make it more tricky to help you if you need support.")
|
||||
__plugin_license__ = "AGPLv3"
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<a href="https://faq.octoprint.org/pi-issues" target="_blank" rel="noopener noreferrer" data-bind="visible: currentIssue() || pastIssue(), popover: { placement: 'bottom', title: '{{ _('What do the symbols mean?') }}', html: true, content: popoverContent, trigger: 'hover' }" style="display: none">
|
||||
<span data-bind="visible: currentUndervoltage() || pastUndervoltage(), css: {'pi_support_state_pulsate': currentUndervoltage}" title="{{ _('Undervoltage') }}"><i class="fa fa-bolt"></i><i class="fa fa-exclamation"></i></span>
|
||||
<span data-bind="visible: currentOverheat() || pastOverheat(), css: {'pi_support_state_pulsate': currentOverheat}" title="{{ _('Overheat') }}"><i class="fa fa-thermometer-full"></i><i class="fa fa-exclamation"></i></span>
|
||||
<a href="https://faq.octoprint.org/pi-issues" target="_blank" rel="noopener noreferrer" data-bind="visible: currentIssue() || pastIssue(), popover: { placement: 'bottom', title: '{{ _('What do the symbols mean?')|esq }}', html: true, content: popoverContent, trigger: 'hover' }" style="display: none">
|
||||
<span data-bind="visible: currentUndervoltage() || pastUndervoltage(), css: {'pi_support_state_pulsate': currentUndervoltage}" title="{{ _('Undervoltage')|edq }}"><i class="fa fa-bolt"></i><i class="fa fa-exclamation"></i></span>
|
||||
<span data-bind="visible: currentOverheat() || pastOverheat(), css: {'pi_support_state_pulsate': currentOverheat}" title="{{ _('Overheat')|edq }}"><i class="fa fa-thermometer-full"></i><i class="fa fa-exclamation"></i></span>
|
||||
</a>
|
||||
@@ -36,10 +36,18 @@ import threading
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
_DATA_FORMAT_VERSION = "v2"
|
||||
try:
|
||||
from os import scandir
|
||||
except:
|
||||
from scandir import scandir
|
||||
|
||||
_DATA_FORMAT_VERSION = "v3"
|
||||
|
||||
|
||||
def map_repository_entry(entry):
|
||||
if not isinstance(entry, dict):
|
||||
return None
|
||||
|
||||
result = copy.deepcopy(entry)
|
||||
|
||||
if not "follow_dependency_links" in result:
|
||||
@@ -113,20 +121,27 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._repository_plugins = []
|
||||
self._repository_cache_path = None
|
||||
self._repository_cache_ttl = 0
|
||||
self._repository_mtime = None
|
||||
|
||||
self._notices = dict()
|
||||
self._notices_available = False
|
||||
self._notices_cache_path = None
|
||||
self._notices_cache_ttl = 0
|
||||
self._notices_mtime = None
|
||||
|
||||
self._orphans = None
|
||||
|
||||
self._console_logger = None
|
||||
|
||||
self._get_throttled = lambda: False
|
||||
|
||||
def initialize(self):
|
||||
self._console_logger = logging.getLogger("octoprint.plugins.pluginmanager.console")
|
||||
self._repository_cache_path = os.path.join(self.get_plugin_data_folder(), "plugins.json")
|
||||
self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60
|
||||
self._notices_cache_path = os.path.join(self.get_plugin_data_folder(), "notices.json")
|
||||
self._notices_cache_ttl = self._settings.get_int(["notices_ttl"]) * 60
|
||||
self._confirm_disable = self._settings.global_get_boolean(["confirm_disable"])
|
||||
|
||||
self._pip_caller = LocalPipCaller(force_user=self._settings.get_boolean(["pip_force_user"]))
|
||||
self._pip_caller.on_log_call = self._log_call
|
||||
@@ -169,6 +184,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._console_logger.setLevel(logging.DEBUG)
|
||||
self._console_logger.propagate = False
|
||||
|
||||
helpers = self._plugin_manager.get_helpers("pi_support", "get_throttled")
|
||||
if helpers and "get_throttled" in helpers:
|
||||
self._get_throttled = helpers["get_throttled"]
|
||||
if self._settings.get_boolean(["ignore_throttled"]):
|
||||
self._logger.warn("!!! THROTTLE STATE IGNORED !!! You have configured the Plugin Manager plugin to ignore an active throttle state of the underlying system. You might run into stability issues or outright corrupt your install. Consider fixing the throttling issue instead of suppressing it.")
|
||||
|
||||
# decouple repository fetching from server startup
|
||||
self._fetch_all_data(do_async=True)
|
||||
|
||||
@@ -182,8 +203,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
notices_ttl=6*60,
|
||||
pip_args=None,
|
||||
pip_force_user=False,
|
||||
confirm_disable=False,
|
||||
dependency_links=False,
|
||||
hidden=[]
|
||||
hidden=[],
|
||||
ignore_throttled=False
|
||||
)
|
||||
|
||||
def on_settings_save(self, data):
|
||||
@@ -192,6 +215,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60
|
||||
self._notices_cache_ttl = self._settings.get_int(["notices_ttl"]) * 60
|
||||
self._pip_caller.force_user = self._settings.get_boolean(["pip_force_user"])
|
||||
self._confirm_disable = self._settings.global_get_boolean(["confirm_disable"])
|
||||
|
||||
##~~ AssetPlugin
|
||||
|
||||
@@ -278,6 +302,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
"uninstall": ["plugin"],
|
||||
"enable": ["plugin"],
|
||||
"disable": ["plugin"],
|
||||
"cleanup": ["plugin"],
|
||||
"cleanup_all": [],
|
||||
"refresh_repository": []
|
||||
}
|
||||
|
||||
@@ -288,19 +314,22 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
from octoprint.server import safe_mode
|
||||
|
||||
refresh_repository = request.values.get("refresh_repository", "false") in valid_boolean_trues
|
||||
if refresh_repository:
|
||||
if refresh_repository or not self._is_repository_cache_valid():
|
||||
self._repository_available = self._refresh_repository()
|
||||
|
||||
refresh_notices = request.values.get("refresh_notices", "false") in valid_boolean_trues
|
||||
if refresh_notices:
|
||||
if refresh_notices or not self._is_notices_cache_valid():
|
||||
self._notices_available = self._refresh_notices()
|
||||
|
||||
refresh_orphan = request.values.get("refresh_orphans", "false") in valid_boolean_trues
|
||||
|
||||
def view():
|
||||
return jsonify(plugins=self._get_plugins(),
|
||||
repository=dict(
|
||||
available=self._repository_available,
|
||||
plugins=self._repository_plugins
|
||||
),
|
||||
orphan_data=self._get_orphans(refresh=refresh_orphan),
|
||||
os=get_os(),
|
||||
octoprint=get_octoprint_version_string(),
|
||||
pip=dict(
|
||||
@@ -327,6 +356,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
hash_update(repr(self._repository_plugins))
|
||||
hash_update(str(self._notices_available))
|
||||
hash_update(repr(self._notices))
|
||||
hash_update(repr(self._get_orphans()))
|
||||
hash_update(repr(safe_mode))
|
||||
hash_update(repr(self._connectivity_checker.online))
|
||||
hash_update(repr(_DATA_FORMAT_VERSION))
|
||||
@@ -337,7 +367,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
return with_revalidation_checking(etag_factory=lambda *args, **kwargs: etag(),
|
||||
condition=lambda *args, **kwargs: condition(),
|
||||
unless=lambda: refresh_repository or refresh_notices)(view)()
|
||||
unless=lambda: refresh_repository or refresh_notices or refresh_orphan)(view)()
|
||||
|
||||
def on_api_command(self, command, data):
|
||||
if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can():
|
||||
@@ -364,7 +394,20 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
return make_response("Unknown plugin: %s" % plugin_name, 404)
|
||||
|
||||
plugin = self._plugin_manager.plugins[plugin_name]
|
||||
return self.command_uninstall(plugin)
|
||||
return self.command_uninstall(plugin, cleanup=data.get("cleanup", False))
|
||||
|
||||
elif command == "cleanup":
|
||||
plugin = data["plugin"]
|
||||
try:
|
||||
plugin = self._plugin_manager.plugins[plugin]
|
||||
except KeyError:
|
||||
# not installed, we are cleaning up left overs, that's ok
|
||||
pass
|
||||
|
||||
return self.command_cleanup(plugin, include_disabled=True)
|
||||
|
||||
elif command == "cleanup_all":
|
||||
return self.command_cleanup_all()
|
||||
|
||||
elif command == "enable" or command == "disable":
|
||||
plugin_name = data["plugin"]
|
||||
@@ -375,6 +418,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
return self.command_toggle(plugin, command)
|
||||
|
||||
def command_install(self, url=None, path=None, force=False, reinstall=None, dependency_links=False):
|
||||
throttled = self._get_throttled()
|
||||
if throttled and isinstance(throttled, dict) and throttled.get("current_issue", False) and not self._settings.get_boolean(["ignore_throttled"]):
|
||||
# currently throttled, we refuse to run
|
||||
return make_response("System is currently throttled, refusing to install "
|
||||
"anything due to possible stability issues", 409)
|
||||
|
||||
if url is not None:
|
||||
if not any(map(lambda scheme: url.startswith(scheme + "://"), self.URL_SCHEMES)):
|
||||
raise ValueError("Invalid URL to pip install from")
|
||||
@@ -539,7 +588,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._send_result_notification("install", result)
|
||||
return jsonify(result)
|
||||
|
||||
def command_uninstall(self, plugin):
|
||||
def command_uninstall(self, plugin, cleanup=False):
|
||||
if plugin.key == "pluginmanager":
|
||||
return make_response("Can't uninstall Plugin Manager", 403)
|
||||
|
||||
@@ -588,7 +637,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._logger.warning("Trying to uninstall plugin {plugin} but origin is unknown ({plugin.origin.type})".format(**locals()))
|
||||
return make_response("Could not uninstall plugin, its origin is unknown")
|
||||
|
||||
needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin)
|
||||
needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin) or cleanup
|
||||
needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
|
||||
needs_reconnect = self._plugin_manager.has_any_of_hooks(plugin, self._reconnect_hooks) and self._printer.is_operational()
|
||||
|
||||
@@ -628,8 +677,108 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
needs_reconnect=needs_reconnect,
|
||||
plugin=self._to_external_plugin(plugin))
|
||||
self._send_result_notification("uninstall", result)
|
||||
self._logger.info("Plugin {} uninstalled".format(plugin.key))
|
||||
|
||||
self._cleanup_disabled(plugin.key)
|
||||
if cleanup:
|
||||
self.command_cleanup(plugin.key, result_notifications=False)
|
||||
|
||||
return jsonify(result)
|
||||
|
||||
def command_cleanup(self, plugin, include_disabled=False, result_notifications=True, settings_save=True):
|
||||
if isinstance(plugin, basestring):
|
||||
key = result_value = plugin
|
||||
else:
|
||||
key = plugin.key
|
||||
result_value = self._to_external_plugin(plugin)
|
||||
|
||||
message = "Cleaning up plugin {}...".format(key)
|
||||
self._logger.info(message)
|
||||
self._log_stdout(message)
|
||||
|
||||
# delete plugin settings
|
||||
self._cleanup_settings(key)
|
||||
|
||||
# delete plugin disabled entry
|
||||
if include_disabled:
|
||||
self._cleanup_disabled(key)
|
||||
|
||||
# delete plugin data folder
|
||||
result_data = True
|
||||
if not self._cleanup_data(key):
|
||||
message = "Could not delete data folder of plugin {}".format(key)
|
||||
self._logger.exception(message)
|
||||
self._log_stderr(message)
|
||||
result_data = False
|
||||
|
||||
if settings_save:
|
||||
self._settings.save()
|
||||
|
||||
result = dict(result=result_data,
|
||||
needs_restart=True,
|
||||
plugin=result_value)
|
||||
if result_notifications:
|
||||
self._send_result_notification("cleanup", result)
|
||||
|
||||
# cleaning orphan cache
|
||||
self._orphans = None
|
||||
|
||||
return jsonify(result)
|
||||
|
||||
def command_cleanup_all(self):
|
||||
orphans = self._get_orphans()
|
||||
cleaned_up = set()
|
||||
|
||||
for orphan in sorted(orphans.keys()):
|
||||
self.command_cleanup(orphan,
|
||||
include_disabled=True,
|
||||
result_notifications=False,
|
||||
settings_save=False)
|
||||
cleaned_up.add(orphan)
|
||||
|
||||
self._settings.save()
|
||||
|
||||
result = dict(result=True,
|
||||
needs_restart=len(cleaned_up) > 0,
|
||||
cleaned_up=sorted(list(cleaned_up)))
|
||||
self._send_result_notification("cleanup_all", result)
|
||||
self._logger.info("Cleaned up all data, {} left overs removed".format(len(cleaned_up)))
|
||||
|
||||
# cleaning orphan cache
|
||||
self._orphans = None
|
||||
|
||||
return jsonify(result)
|
||||
|
||||
def _cleanup_disabled(self, plugin):
|
||||
# delete from disabled list
|
||||
disabled = self._settings.global_get(["plugins", "_disabled"])
|
||||
try:
|
||||
disabled.remove(plugin)
|
||||
except ValueError:
|
||||
# not in list, ok
|
||||
pass
|
||||
self._settings.global_set(["plugins", "_disabled"], disabled)
|
||||
|
||||
def _cleanup_settings(self, plugin):
|
||||
# delete plugin settings
|
||||
self._settings.global_set(["plugins", plugin], None)
|
||||
return True
|
||||
|
||||
def _cleanup_data(self, plugin):
|
||||
import os
|
||||
import shutil
|
||||
|
||||
data_folder = os.path.join(self._settings.getBaseFolder("data"), plugin)
|
||||
if os.path.exists(data_folder):
|
||||
try:
|
||||
shutil.rmtree(data_folder)
|
||||
return True
|
||||
except Exception:
|
||||
self._logger.exception("Could not delete plugin data folder at {}".format(data_folder))
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
def command_toggle(self, plugin, command):
|
||||
if plugin.key == "pluginmanager":
|
||||
return make_response("Can't enable/disable Plugin Manager", 400)
|
||||
@@ -717,7 +866,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
inapplicable_arguments = self.__class__.PIP_INAPPLICABLE_ARGUMENTS.get(args[0], list())
|
||||
for inapplicable_argument in inapplicable_arguments:
|
||||
additional_args = re.sub("(^|\s)" + re.escape(inapplicable_argument) + "\\b", "", additional_args)
|
||||
additional_args = re.sub(r"(^|\s)" + re.escape(inapplicable_argument) + r"\\b", "", additional_args)
|
||||
|
||||
if additional_args:
|
||||
args.append(additional_args)
|
||||
@@ -801,16 +950,25 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
else:
|
||||
run()
|
||||
|
||||
def _is_repository_cache_valid(self, mtime=None):
|
||||
import time
|
||||
if mtime is None:
|
||||
mtime = self._repository_mtime
|
||||
if mtime is None:
|
||||
return False
|
||||
return mtime + self._repository_cache_ttl >= time.time() > mtime
|
||||
|
||||
def _fetch_repository_from_disk(self):
|
||||
repo_data = None
|
||||
if os.path.isfile(self._repository_cache_path):
|
||||
import time
|
||||
mtime = os.path.getmtime(self._repository_cache_path)
|
||||
if mtime + self._repository_cache_ttl >= time.time() > mtime:
|
||||
if self._is_repository_cache_valid(mtime=mtime):
|
||||
try:
|
||||
import json
|
||||
with io.open(self._repository_cache_path, 'rt', encoding='utf-8') as f:
|
||||
repo_data = json.load(f)
|
||||
self._repository_mtime = mtime
|
||||
self._logger.info("Loaded plugin repository data from disk, was still valid")
|
||||
except Exception:
|
||||
self._logger.exception("Error while loading repository data from {}".format(self._repository_cache_path))
|
||||
@@ -828,17 +986,27 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
r.raise_for_status()
|
||||
self._logger.info("Loaded plugin repository data from {}".format(repository_url))
|
||||
except Exception as e:
|
||||
self._logger.exception("Could not fetch plugins from repository at {repository_url}: {message}".format(repository_url=repository_url, message=str(e)))
|
||||
self._logger.exception("Could not fetch plugins from repository at {repository_url}: {message}".format(repository_url=repository_url, message=e))
|
||||
return None
|
||||
|
||||
repo_data = r.json()
|
||||
try:
|
||||
repo_data = r.json()
|
||||
except Exception as e:
|
||||
self._logger.exception("Error while reading repository data: {}".format(e))
|
||||
return None
|
||||
|
||||
# validation
|
||||
if not isinstance(repo_data, (list, tuple)):
|
||||
self._logger.warn("Invalid repository data: expected a list, got {!r}".format(repo_data))
|
||||
return None
|
||||
|
||||
try:
|
||||
import json
|
||||
with octoprint.util.atomic_write(self._repository_cache_path, mode='wb') as f:
|
||||
f.write(to_bytes(json.dumps(repo_data)))
|
||||
self._repository_mtime = os.path.getmtime(self._repository_cache_path)
|
||||
except Exception as e:
|
||||
self._logger.exception("Error while saving repository data to {}: {}".format(self._repository_cache_path, str(e)))
|
||||
self._logger.exception("Error while saving repository data to {}: {}".format(self._repository_cache_path, e))
|
||||
|
||||
return repo_data
|
||||
|
||||
@@ -848,19 +1016,29 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
if repo_data is None:
|
||||
return False
|
||||
|
||||
self._repository_plugins = list(map(map_repository_entry, repo_data))
|
||||
self._repository_plugins = list(filter(lambda x: x is not None,
|
||||
map(map_repository_entry, repo_data)))
|
||||
return True
|
||||
|
||||
def _is_notices_cache_valid(self, mtime=None):
|
||||
import time
|
||||
if mtime is None:
|
||||
mtime = self._notices_mtime
|
||||
if mtime is None:
|
||||
return False
|
||||
return mtime + self._notices_cache_ttl >= time.time() > mtime
|
||||
|
||||
def _fetch_notices_from_disk(self):
|
||||
notice_data = None
|
||||
if os.path.isfile(self._notices_cache_path):
|
||||
import time
|
||||
mtime = os.path.getmtime(self._notices_cache_path)
|
||||
if mtime + self._notices_cache_ttl >= time.time() > mtime:
|
||||
if self._is_notices_cache_valid(mtime=mtime):
|
||||
try:
|
||||
import json
|
||||
with io.open(self._notices_cache_path, 'rt', encoding='utf-8') as f:
|
||||
notice_data = json.load(f)
|
||||
self._notices_mtime = mtime
|
||||
self._logger.info("Loaded notice data from disk, was still valid")
|
||||
except Exception:
|
||||
self._logger.exception("Error while loading notices from {}".format(self._notices_cache_path))
|
||||
@@ -887,6 +1065,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
import json
|
||||
with octoprint.util.atomic_write(self._notices_cache_path, mode="wb") as f:
|
||||
f.write(to_bytes(json.dumps(notice_data)))
|
||||
self._notices_mtime = os.path.getmtime(self._notices_cache_path)
|
||||
except Exception as e:
|
||||
self._logger.exception("Error while saving notices to {}: {}".format(self._notices_cache_path, str(e)))
|
||||
return notice_data
|
||||
@@ -924,6 +1103,41 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._notices = notices
|
||||
return True
|
||||
|
||||
def _get_orphans(self, refresh=False):
|
||||
from collections import defaultdict
|
||||
|
||||
if self._orphans is not None and not refresh:
|
||||
return self._orphans
|
||||
|
||||
installed_keys = self._plugin_manager.plugins.keys()
|
||||
orphans = defaultdict(lambda: dict(settings=False, data=False, disabled=False))
|
||||
|
||||
# settings
|
||||
for key in list(self._settings.global_get(["plugins"]).keys()):
|
||||
if key.startswith("_"):
|
||||
# internal key, like _disabled
|
||||
continue
|
||||
|
||||
if key not in installed_keys:
|
||||
orphans[key]["settings"] = True
|
||||
|
||||
# data
|
||||
for entry in scandir(self._settings.getBaseFolder("data")):
|
||||
if not entry.is_dir():
|
||||
continue
|
||||
|
||||
if entry.name not in installed_keys:
|
||||
orphans[entry.name]["data"] = True
|
||||
|
||||
# disabled
|
||||
disabled = self._settings.global_get(["plugins", "_disabled"])
|
||||
for key in disabled:
|
||||
if key not in installed_keys:
|
||||
orphans[key]["disabled"] = True
|
||||
|
||||
self._orphans = dict(**orphans)
|
||||
return self._orphans
|
||||
|
||||
@property
|
||||
def _reconnect_hooks(self):
|
||||
reconnect_hooks = self.__class__.RECONNECT_HOOKS
|
||||
|
||||
@@ -10,18 +10,21 @@
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.get = function(refresh, opts) {
|
||||
var refresh_repo, refresh_notices;
|
||||
var refresh_repo, refresh_notices, refresh_orphans;
|
||||
if (_.isPlainObject(refresh)) {
|
||||
refresh_repo = refresh.repo || false;
|
||||
refresh_notices = refresh.notices || false;
|
||||
refresh_orphans = refresh.orphans || false;
|
||||
} else {
|
||||
refresh_repo = refresh;
|
||||
refresh_notices = false;
|
||||
refresh_orphans = false;
|
||||
}
|
||||
|
||||
var query = [];
|
||||
if (refresh_repo) query.push("refresh_repository=true");
|
||||
if (refresh_notices) query.push("refresh_notices=true");
|
||||
if (refresh_orphans) query.push("refresh_orphans=true");
|
||||
|
||||
return this.base.get(this.base.getSimpleApiUrl("pluginmanager") + ((query.length) ? "?" + query.join("&") : ""), opts);
|
||||
};
|
||||
@@ -52,11 +55,30 @@
|
||||
return this.base.simpleApiCommand("pluginmanager", "install", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.uninstall = function(plugin, opts) {
|
||||
OctoPrintPluginManagerClient.prototype.uninstall = function(plugin, cleanup, opts) {
|
||||
// backwards compatibility to former argument list (plugin, opts)
|
||||
if (arguments.length === 2 && typeof cleanup === "object") {
|
||||
opts = cleanup;
|
||||
cleanup = false;
|
||||
}
|
||||
|
||||
var data = {
|
||||
plugin: plugin,
|
||||
cleanup: !!cleanup
|
||||
};
|
||||
return this.base.simpleApiCommand("pluginmanager", "uninstall", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.cleanup = function(plugin, opts) {
|
||||
var data = {
|
||||
plugin: plugin
|
||||
};
|
||||
return this.base.simpleApiCommand("pluginmanager", "uninstall", data, opts);
|
||||
return this.base.simpleApiCommand("pluginmanager", "cleanup", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.cleanupAll = function(plugin, opts) {
|
||||
var data = {};
|
||||
return this.base.simpleApiCommand("pluginmanager", "cleanup_all", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.enable = function(plugin, opts) {
|
||||
|
||||
@@ -1 +1 @@
|
||||
#settings_plugin_pluginmanager_pluginlist{display:block;width:auto;height:500px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty div,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:300px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
|
||||
#settings_plugin_pluginmanager_pluginlist{display:block;width:auto;max-height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_orphanlist{display:block;width:auto;max-height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_id,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_id{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a.disabled,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty div,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:300px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
|
||||
@@ -8,12 +8,17 @@ $(function() {
|
||||
self.systemViewModel = parameters[3];
|
||||
self.access = parameters[4];
|
||||
|
||||
// optional
|
||||
self.piSupport = parameters[5];
|
||||
|
||||
self.config_repositoryUrl = ko.observable();
|
||||
self.config_repositoryTtl = ko.observable();
|
||||
self.config_noticesUrl = ko.observable();
|
||||
self.config_noticesTtl = ko.observable();
|
||||
self.config_pipAdditionalArgs = ko.observable();
|
||||
self.config_pipForceUser = ko.observable();
|
||||
self.config_confirmUninstall = ko.observable();
|
||||
self.config_confirmDisable = ko.observable();
|
||||
|
||||
self.configurationDialog = $("#settings_plugin_pluginmanager_configurationdialog");
|
||||
|
||||
@@ -28,10 +33,22 @@ $(function() {
|
||||
}
|
||||
},
|
||||
{
|
||||
"bundled": function(item) {
|
||||
return item.bundled;
|
||||
},
|
||||
"3rdparty": function(item) {
|
||||
return !item.bundled;
|
||||
},
|
||||
"enabled": function(item) {
|
||||
return item.enabled;
|
||||
},
|
||||
"disabled": function(item) {
|
||||
return !item.enabled;
|
||||
}
|
||||
},
|
||||
"name",
|
||||
[],
|
||||
[],
|
||||
[["bundled", "3rdparty"], ["enabled", "disabled"]],
|
||||
0
|
||||
);
|
||||
|
||||
@@ -65,6 +82,23 @@ $(function() {
|
||||
0
|
||||
);
|
||||
|
||||
self.orphans = new ItemListHelper(
|
||||
"plugin.pluginmanager.orphans",
|
||||
{
|
||||
"identifier": function (a, b) {
|
||||
// sorts ascending
|
||||
if (a["identifier"].toLocaleLowerCase() < b["identifier"].toLocaleLowerCase()) return -1;
|
||||
if (a["identifier"].toLocaleLowerCase() > b["identifier"].toLocaleLowerCase()) return 1;
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
{},
|
||||
"identifier",
|
||||
[],
|
||||
[],
|
||||
0
|
||||
);
|
||||
|
||||
self.uploadElement = $("#settings_plugin_pluginmanager_repositorydialog_upload");
|
||||
self.uploadButton = $("#settings_plugin_pluginmanager_repositorydialog_upload_start");
|
||||
|
||||
@@ -75,6 +109,11 @@ $(function() {
|
||||
self.performRepositorySearch();
|
||||
});
|
||||
|
||||
self.listingSearchQuery = ko.observable();
|
||||
self.listingSearchQuery.subscribe(function() {
|
||||
self.performListingSearch();
|
||||
});
|
||||
|
||||
self.installUrl = ko.observable();
|
||||
self.uploadFilename = ko.observable();
|
||||
|
||||
@@ -145,7 +184,7 @@ $(function() {
|
||||
});
|
||||
|
||||
self.enableManagement = ko.pureComputed(function() {
|
||||
return !self.printerState.isPrinting();
|
||||
return !self.printerState.isBusy();
|
||||
});
|
||||
|
||||
self.enableToggle = function(data) {
|
||||
@@ -164,10 +203,20 @@ $(function() {
|
||||
&& !data.pending_uninstall;
|
||||
};
|
||||
|
||||
self.enableRepoInstall = function(data) {
|
||||
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && self.online() && self.isCompatible(data);
|
||||
self.enableCleanup = function(data) {
|
||||
return self.enableManagement()
|
||||
&& data.key !== 'pluginmanager'
|
||||
&& !data.pending_uninstall;
|
||||
};
|
||||
|
||||
self.enableRepoInstall = function(data) {
|
||||
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && !self.throttled() && self.online() && self.isCompatible(data);
|
||||
};
|
||||
|
||||
self.throttled = ko.pureComputed(function() {
|
||||
return self.piSupport && self.piSupport.currentIssue() && !self.settingsViewModel.settings.plugins.pluginmanager.ignore_throttled();
|
||||
});
|
||||
|
||||
self.invalidUrl = ko.pureComputed(function() {
|
||||
// supported pip install URL schemes, according to https://pip.pypa.io/en/stable/reference/pip_install/
|
||||
var allowedUrlSchemes = ["http", "https",
|
||||
@@ -192,6 +241,7 @@ $(function() {
|
||||
return self.enableManagement()
|
||||
&& self.pipAvailable()
|
||||
&& !self.safeMode()
|
||||
&& !self.throttled()
|
||||
&& self.online()
|
||||
&& url !== undefined
|
||||
&& url.trim() !== ""
|
||||
@@ -217,6 +267,7 @@ $(function() {
|
||||
return self.enableManagement()
|
||||
&& self.pipAvailable()
|
||||
&& !self.safeMode()
|
||||
&& !self.throttled()
|
||||
&& name !== undefined
|
||||
&& name.trim() !== ""
|
||||
&& !self.invalidArchive();
|
||||
@@ -267,9 +318,21 @@ $(function() {
|
||||
}
|
||||
});
|
||||
|
||||
self.performListingSearch = function() {
|
||||
var query = self.listingSearchQuery();
|
||||
if (query !== undefined && query.trim() !== "") {
|
||||
query = query.toLocaleLowerCase();
|
||||
self.plugins.changeSearchFunction(function (entry) {
|
||||
return entry && (entry["name"].toLocaleLowerCase().indexOf(query) > -1 || (entry.description && entry.description.toLocaleLowerCase().indexOf(query) > -1));
|
||||
});
|
||||
} else {
|
||||
self.plugins.resetSearch();
|
||||
}
|
||||
};
|
||||
|
||||
self.performRepositorySearch = function() {
|
||||
var query = self.repositorySearchQuery();
|
||||
if (query !== undefined && query.trim() != "") {
|
||||
if (query !== undefined && query.trim() !== "") {
|
||||
query = query.toLocaleLowerCase();
|
||||
self.repositoryplugins.changeSearchFunction(function(entry) {
|
||||
return entry && (entry["title"].toLocaleLowerCase().indexOf(query) > -1 || entry["description"].toLocaleLowerCase().indexOf(query) > -1);
|
||||
@@ -282,6 +345,7 @@ $(function() {
|
||||
|
||||
self.fromResponse = function(data, options) {
|
||||
self._fromPluginsResponse(data.plugins, options);
|
||||
self._fromOrphanResponse(data.orphan_data, options);
|
||||
self._fromRepositoryResponse(data.repository, options);
|
||||
self._fromPipResponse(data.pip, options);
|
||||
|
||||
@@ -315,6 +379,14 @@ $(function() {
|
||||
self.plugins.updateItems(data);
|
||||
};
|
||||
|
||||
self._fromOrphanResponse = function(data) {
|
||||
var orphans = [];
|
||||
_.each(data, function(value, key) {
|
||||
orphans.push({identifier: key, settings: value.settings, data: value.data});
|
||||
});
|
||||
self.orphans.updateItems(orphans);
|
||||
};
|
||||
|
||||
self._fromRepositoryResponse = function(data) {
|
||||
self.repositoryAvailable(data.available);
|
||||
if (data.available) {
|
||||
@@ -350,17 +422,18 @@ $(function() {
|
||||
if (!_.isPlainObject(options)) {
|
||||
options = {
|
||||
refresh_repo: options,
|
||||
refresh_orphans: false,
|
||||
refresh_notices: false,
|
||||
eval_notices: false
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
options.refresh_repo = options.refresh_repo || false;
|
||||
options.refresh_orphans = options.refresh_orphans || false;
|
||||
options.refresh_notices = options.refresh_notices || false;
|
||||
options.eval_notices = options.eval_notices || false;
|
||||
|
||||
OctoPrint.plugins.pluginmanager.get({repo: options.refresh_repo, notices: options.refresh_notices})
|
||||
OctoPrint.plugins.pluginmanager.get({repo: options.refresh_repo, notices: options.refresh_notices, orphans: options.refresh_orphans})
|
||||
.done(function(data) {
|
||||
self.fromResponse(data, options);
|
||||
});
|
||||
@@ -395,14 +468,15 @@ $(function() {
|
||||
.done(onSuccess)
|
||||
.fail(onError);
|
||||
} else {
|
||||
var perform = function() {
|
||||
var performDisabling = function() {
|
||||
OctoPrint.plugins.pluginmanager.disable(data.key)
|
||||
.done(onSuccess)
|
||||
.fail(onError);
|
||||
};
|
||||
|
||||
// always warn if plugin is marked "disabling discouraged"
|
||||
if (data.disabling_discouraged) {
|
||||
var message = _.sprintf(gettext("You are about to disable \"%(name)s\"."), {name: data.name})
|
||||
var message = _.sprintf(gettext("You are about to disable \"%(name)s\"."), {name: _.escape(data.name)})
|
||||
+ "</p><p>" + data.disabling_discouraged;
|
||||
showConfirmationDialog({
|
||||
title: gettext("This is not recommended"),
|
||||
@@ -410,10 +484,21 @@ $(function() {
|
||||
question: gettext("Do you still want to disable it?"),
|
||||
cancel: gettext("Keep enabled"),
|
||||
proceed: gettext("Disable anyway"),
|
||||
onproceed: perform
|
||||
})
|
||||
onproceed: performDisabling
|
||||
});
|
||||
}
|
||||
// warn if global "warn disabling" setting is set"
|
||||
else if (self.settingsViewModel.settings.plugins.pluginmanager.confirm_disable()) {
|
||||
showConfirmationDialog({
|
||||
message: _.sprintf(gettext("You are about to disable \"%(name)s\""), {name: _.escape(data.name)}),
|
||||
cancel: gettext("Keep enabled"),
|
||||
proceed: gettext("Disable plugin"),
|
||||
onproceed: performDisabling,
|
||||
nofade: true
|
||||
});
|
||||
} else {
|
||||
perform();
|
||||
// otherwise just go ahead and disable...
|
||||
performDisabling();
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -447,6 +532,10 @@ $(function() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (self.throttled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (url === undefined) {
|
||||
url = self.installUrl();
|
||||
}
|
||||
@@ -460,13 +549,13 @@ $(function() {
|
||||
if (!reinstall) {
|
||||
workTitle = gettext("Installing plugin...");
|
||||
if (name) {
|
||||
workText = _.sprintf(gettext("Installing plugin \"%(name)s\" from %(url)s..."), {url: url, name: name});
|
||||
workText = _.sprintf(gettext("Installing plugin \"%(name)s\" from %(url)s..."), {url: _.escape(url), name: _.escape(name)});
|
||||
} else {
|
||||
workText = _.sprintf(gettext("Installing plugin from %(url)s..."), {url: url});
|
||||
workText = _.sprintf(gettext("Installing plugin from %(url)s..."), {url: _.escape(url)});
|
||||
}
|
||||
} else {
|
||||
workTitle = gettext("Reinstalling plugin...");
|
||||
workText = _.sprintf(gettext("Reinstalling plugin \"%(name)s\" from %(url)s..."), {url: url, name: name});
|
||||
workText = _.sprintf(gettext("Reinstalling plugin \"%(name)s\" from %(url)s..."), {url: _.escape(url), name: _.escape(name)});
|
||||
}
|
||||
self._markWorking(workTitle, workText);
|
||||
|
||||
@@ -510,25 +599,119 @@ $(function() {
|
||||
}
|
||||
|
||||
if (data.bundled) return;
|
||||
if (data.key == "pluginmanager") return;
|
||||
if (data.key === "pluginmanager") return;
|
||||
|
||||
self._markWorking(gettext("Uninstalling plugin..."), _.sprintf(gettext("Uninstalling plugin \"%(name)s\""), {name: data.name}));
|
||||
// defining actual uninstall logic as functor in order to handle
|
||||
// the confirm/no-confirm logic without duplication of logic
|
||||
var performUninstall = function(cleanup) {
|
||||
self._markWorking(gettext("Uninstalling plugin..."), _.sprintf(gettext("Uninstalling plugin \"%(name)s\""), {name: _.escape(data.name)}));
|
||||
|
||||
OctoPrint.plugins.pluginmanager.uninstall(data.key)
|
||||
.done(function() {
|
||||
self.requestData();
|
||||
})
|
||||
.fail(function() {
|
||||
new PNotify({
|
||||
title: gettext("Something went wrong"),
|
||||
text: gettext("Please consult octoprint.log for details"),
|
||||
type: "error",
|
||||
hide: false
|
||||
OctoPrint.plugins.pluginmanager.uninstall(data.key, cleanup)
|
||||
.done(function() {
|
||||
self.requestData();
|
||||
})
|
||||
.fail(function() {
|
||||
new PNotify({
|
||||
title: gettext("Something went wrong"),
|
||||
text: gettext("Please consult octoprint.log for details"),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
})
|
||||
.always(function() {
|
||||
self._markDone();
|
||||
});
|
||||
})
|
||||
.always(function() {
|
||||
self._markDone();
|
||||
});
|
||||
};
|
||||
|
||||
showConfirmationDialog({
|
||||
message: _.sprintf(gettext("You are about to uninstall the plugin \"%(name)s\""), {name: _.escape(data.name)}),
|
||||
cancel: gettext("Keep installed"),
|
||||
proceed: [
|
||||
gettext("Uninstall"),
|
||||
gettext("Uninstall & clean up data")
|
||||
],
|
||||
onproceed: function(button) {
|
||||
// buttons: 0=uninstall, 1=uninstall&cleanup
|
||||
performUninstall(button === 1)
|
||||
},
|
||||
nofade: true
|
||||
});
|
||||
};
|
||||
|
||||
self.cleanupPlugin = function(data) {
|
||||
var key, name;
|
||||
if (_.isObject(data)) {
|
||||
key = data.key;
|
||||
name = data.name;
|
||||
} else {
|
||||
key = name = data;
|
||||
}
|
||||
|
||||
if (!self.loginState.isAdmin()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (key === "pluginmanager") return;
|
||||
|
||||
var performCleanup = function() {
|
||||
self._markWorking(gettext("Cleaning up plugin data..."), _.sprintf(gettext("Cleaning up data of plugin \"%(name)s\""), {name: _.escape(name)}));
|
||||
|
||||
OctoPrint.plugins.pluginmanager.cleanup(key)
|
||||
.done(function() {
|
||||
self.requestData();
|
||||
})
|
||||
.fail(function() {
|
||||
new PNotify({
|
||||
title: gettext("Something went wrong"),
|
||||
text: gettext("Please consult octoprint.log for details"),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
})
|
||||
.always(function() {
|
||||
self._markDone();
|
||||
})
|
||||
};
|
||||
|
||||
showConfirmationDialog({
|
||||
message: _.sprintf(gettext("You are about to cleanup the plugin data of \"%(name)s\". This operation cannot be reversed."), {name: _.escape(name)}),
|
||||
cancel: gettext("Keep data"),
|
||||
proceed: gettext("Cleanup data"),
|
||||
onproceed: performCleanup,
|
||||
nofade: true
|
||||
});
|
||||
};
|
||||
|
||||
self.cleanupAll = function() {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
return;
|
||||
}
|
||||
|
||||
var performCleanup = function() {
|
||||
var title = gettext("Cleaning up all left over plugin data...");
|
||||
self._markWorking(title, title);
|
||||
|
||||
OctoPrint.plugins.pluginmanager.cleanupAll()
|
||||
.fail(function() {
|
||||
new PNotify({
|
||||
title: gettext("Something went wrong"),
|
||||
text: gettext("Please consult octoprint.log for details"),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
})
|
||||
.always(function() {
|
||||
self._markDone();
|
||||
})
|
||||
};
|
||||
|
||||
showConfirmationDialog({
|
||||
message: gettext("You are about to cleanup left over plugin settings and data of plugins no longer installed. This operation cannot be reversed."),
|
||||
cancel: gettext("Keep data"),
|
||||
proceed: gettext("Cleanup all data"),
|
||||
onproceed: performCleanup,
|
||||
nofade: true
|
||||
});
|
||||
};
|
||||
|
||||
self.refreshRepository = function() {
|
||||
@@ -597,7 +780,8 @@ $(function() {
|
||||
notices: notices,
|
||||
notices_ttl: noticesTtl,
|
||||
pip_args: pipArgs,
|
||||
pip_force_user: self.config_pipForceUser()
|
||||
pip_force_user: self.config_pipForceUser(),
|
||||
confirm_disable: self.config_confirmDisable(),
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -615,6 +799,7 @@ $(function() {
|
||||
self.config_noticesTtl(self.settingsViewModel.settings.plugins.pluginmanager.notices_ttl());
|
||||
self.config_pipAdditionalArgs(self.settingsViewModel.settings.plugins.pluginmanager.pip_args());
|
||||
self.config_pipForceUser(self.settingsViewModel.settings.plugins.pluginmanager.pip_force_user());
|
||||
self.config_confirmDisable(self.settingsViewModel.settings.plugins.pluginmanager.confirm_disable());
|
||||
};
|
||||
|
||||
self.installed = function(data) {
|
||||
@@ -671,13 +856,21 @@ $(function() {
|
||||
line = gettext("Disable <em>%(plugin)s</em>: %(result)s");
|
||||
break;
|
||||
}
|
||||
case "cleanup": {
|
||||
line = gettext("Cleanup <em>%(plugin)s</em>: %(result)s");
|
||||
break;
|
||||
}
|
||||
case "cleanup_all": {
|
||||
line = gettext("Cleanup all: %(result)s");
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
text += "<li>"
|
||||
+ _.sprintf(line, {plugin: step.plugin, result: step.result ? "<i class=\"fa fa-check\"></i>" : "<i class=\"fa fa-remove\"></i>"})
|
||||
+ _.sprintf(line, {plugin: _.escape(step.plugin), result: step.result ? "<i class=\"fa fa-check\"></i>" : "<i class=\"fa fa-remove\"></i>"})
|
||||
+ "</li>";
|
||||
});
|
||||
text += "</ul></p>";
|
||||
@@ -855,16 +1048,16 @@ $(function() {
|
||||
|
||||
var title;
|
||||
if (important) {
|
||||
title = _.sprintf(gettext("Important notice regarding plugin \"%(name)s\""), {name: name});
|
||||
title = _.sprintf(gettext("Important notice regarding plugin \"%(name)s\""), {name: _.escape(name)});
|
||||
} else {
|
||||
title = _.sprintf(gettext("Notice regarding plugin \"%(name)s\""), {name: name});
|
||||
title = _.sprintf(gettext("Notice regarding plugin \"%(name)s\""), {name: _.escape(name)});
|
||||
}
|
||||
|
||||
var text = "";
|
||||
|
||||
if (notification.versions && notification.versions.length > 0) {
|
||||
var versions = _.map(notification.versions, function(v) { return (v == version) ? "<strong>" + v + "</strong>" : v; }).join(", ");
|
||||
text += "<small>" + _.sprintf(gettext("Affected versions: %(versions)s"), {versions: versions}) + "</small>";
|
||||
text += "<small>" + _.sprintf(gettext("Affected versions: %(versions)s"), {versions: _.escape(versions)}) + "</small>";
|
||||
} else {
|
||||
text += "<small>" + gettext("Affected versions: all") + "</small>";
|
||||
}
|
||||
@@ -1060,7 +1253,11 @@ $(function() {
|
||||
var name = "Unknown";
|
||||
if (data.hasOwnProperty("plugin")) {
|
||||
if (data.plugin !== "unknown") {
|
||||
name = data.plugin.name;
|
||||
if (_.isPlainObject(data.plugin)) {
|
||||
name = data.plugin.name;
|
||||
} else {
|
||||
name = data.plugin;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1080,7 +1277,8 @@ $(function() {
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: PluginManagerViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel", "printerStateViewModel", "systemViewModel", "accessViewModel"],
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel", "printerStateViewModel", "systemViewModel", "accessViewModel", "piSupportViewModel"],
|
||||
optional: ["piSupportViewModel"],
|
||||
elements: ["#settings_plugin_pluginmanager"]
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,10 @@
|
||||
#settings_plugin_pluginmanager {
|
||||
}
|
||||
|
||||
#settings_plugin_pluginmanager_pluginlist {
|
||||
display: block;
|
||||
width: auto;
|
||||
height: 500px;
|
||||
max-height: 400px;
|
||||
overflow-x: hidden;
|
||||
overflow-y: scroll;
|
||||
padding-right: 2px;
|
||||
@@ -33,6 +36,41 @@
|
||||
}
|
||||
}
|
||||
|
||||
#settings_plugin_pluginmanager_orphanlist {
|
||||
display: block;
|
||||
width: auto;
|
||||
max-height: 400px;
|
||||
overflow-x: hidden;
|
||||
overflow-y: scroll;
|
||||
padding-right: 2px;
|
||||
margin-bottom: 1em;
|
||||
|
||||
table {
|
||||
|
||||
th, td {
|
||||
&.settings_plugin_plugin_manager_orphans_id {
|
||||
text-overflow: ellipsis;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
&.settings_plugin_plugin_manager_orphans_actions {
|
||||
text-align: center;
|
||||
width: 80px;
|
||||
|
||||
a {
|
||||
text-decoration: none;
|
||||
color: #000;
|
||||
|
||||
&.disabled {
|
||||
color: #ccc;
|
||||
cursor: default;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#settings_plugin_pluginmanager_repositorydialog {
|
||||
h4 {
|
||||
position: relative;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% macro pluginmanager_printing() %}
|
||||
<div class="alert" data-bind="visible: !enableManagement()">
|
||||
{{ _('Take note that all plugin management functionality is disabled while your printer is printing.') }}
|
||||
{{ _('Take note that all plugin management functionality is disabled while your printer is printing or paused.') }}
|
||||
</div>
|
||||
{% endmacro %}
|
||||
|
||||
@@ -20,6 +20,13 @@
|
||||
{% endtrans %}</div>
|
||||
{% endmacro %}
|
||||
|
||||
{% macro pluginmanager_throttled() %}
|
||||
<div class="alert" data-bind="visible: throttled">{% trans %}
|
||||
The system OctoPrint is running on is currently throttled. Due to that it's not possible to install new
|
||||
plugins in order to avoid possible issues caused by system instability.
|
||||
{% endtrans %}</div>
|
||||
{% endmacro %}
|
||||
|
||||
{% macro pluginmanager_offline() %}
|
||||
<div class="alert" data-bind="visible: !online()">{% trans %}
|
||||
It looks like OctoPrint has currently no connection to the internet. Due to that it's not possible
|
||||
@@ -27,77 +34,144 @@
|
||||
{% endtrans %}</div>
|
||||
{% endmacro %}
|
||||
|
||||
{{ pluginmanager_printing() }}
|
||||
{{ pluginmanager_nopip() }}
|
||||
{{ pluginmanager_safemode() }}
|
||||
<ul class="nav nav-pills">
|
||||
<li class="active">
|
||||
<a href="#settings_plugin_pluginmanager_plugins" data-toggle="tab">{{ _('Plugins') }}</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="#settings_plugin_pluginmanager_cleanup" data-toggle="tab">{{ _('Cleanup') }}</a>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div class="pull-right">
|
||||
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="fa fa-wrench"></i></button>
|
||||
</div>
|
||||
<div class="tab-content">
|
||||
<div class="tab-pane active" id="settings_plugin_pluginmanager_plugins">
|
||||
{{ pluginmanager_printing() }}
|
||||
{{ pluginmanager_nopip() }}
|
||||
{{ pluginmanager_safemode() }}
|
||||
{{ pluginmanager_throttled() }}
|
||||
|
||||
<h3>{{ _('Installed Plugins') }}</h3>
|
||||
<div class="pull-right">
|
||||
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration')|edq }}"><i class="fa fa-wrench"></i></button>
|
||||
</div>
|
||||
|
||||
<div id="settings_plugin_pluginmanager_pluginlist">
|
||||
<table class="table table-striped table-hover table-condensed table-hover">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_plugin_plugin_manager_plugins_name">{{ _('Name') }}</th>
|
||||
<th class="settings_plugin_plugin_manager_plugins_actions">{{ _('Actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: plugins.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_plugin_manager_plugins_name">
|
||||
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint') }}" class="fa fa-th-large" data-bind="visible: bundled"></i> <i class="fa fa-lock" title="{{ _('Cannot be uninstalled through OctoPrint') }}" data-bind="visible: !managable"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect') }}" class="fa fa-refresh" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install') }}" class="fa fa-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall') }}" class="fa fa-minus" data-bind="visible: pending_uninstall"></i> <i title="{{ _('Disabled due to safe mode') }}" class="fa fa-medkit" data-bind="visible: safe_mode_victim"></i> <i class="fa fa-exclamation-triangle" title="{{ _('There are notices available regarding this plugin') }}" data-bind="visible: notifications && notifications.length"></i> <i class="fa fa-ban" title="{{ _('This plugin is blacklisted') }}" data-bind="visible: blacklisted"></i></div>
|
||||
<div data-bind="visible: notifications && notifications.length"><a href="javascript:void(0)" class="text-error" style="text-decoration: underline" data-bind="click: function() { $root.showPluginNotifications($data) }, text: $root.showPluginNotificationsLinkText($data)"></a></div>
|
||||
<div><small class="muted" data-bind="text: description"> </small></div>
|
||||
<div data-bind="css: {muted: !enabled}">
|
||||
<small data-bind="visible: url"><i class="fa fa-home"></i> <a data-bind="attr: {href: url}" target="_blank" rel="noreferrer noopener">{{ _('Homepage') }}</a></small>
|
||||
<small data-bind="visible: license"><i class="fa fa-gavel"></i> <span data-bind="text: license"></span></small>
|
||||
<small data-bind="visible: author"><i class="fa fa-user"></i> <span data-bind="text: author"></span></small>
|
||||
<small> </small>
|
||||
<h3>{{ _('Installed Plugins') }}</h3>
|
||||
|
||||
<div style="margin-bottom: 1em" class="clearfix">
|
||||
<input type="text" class="input-block search-query pull-left" data-bind="value: listingSearchQuery, valueUpdate: 'input'" placeholder="{{ _('Search...')|edq }}">
|
||||
|
||||
<div class="pull-right">
|
||||
<div class="btn-group">
|
||||
<button class="btn btn-small" data-bind="click: function() { plugins.removeFilter('bundled'); plugins.removeFilter('3rdparty'); }, css: {active: !_.contains(plugins.currentFilters(), 'bundled') && !_.contains(plugins.currentFilters(), '3rdparty')}" title="{{ _('Show both bundled and third-party plugins')|edq }}">All</button>
|
||||
<button class="btn btn-small" data-bind="click: function() { plugins.addFilter('bundled') }, css: {active: _.contains(plugins.currentFilters(), 'bundled')}" title="{{ _('Show only bundled plugins')|edq }}">{{ _('Bundled') }}</button>
|
||||
<button class="btn btn-small" data-bind="click: function() { plugins.addFilter('3rdparty') }, css: {active: _.contains(plugins.currentFilters(), '3rdparty')}" title="{{ _('Show only third-party plugins')|edq }}">{{ _('3rd party') }}</button>
|
||||
</div>
|
||||
</td>
|
||||
<td class="settings_plugin_plugin_manager_plugins_actions">
|
||||
<a href="#" data-bind="css: $root.toggleButtonCss($data), attr: {title: $root.toggleButtonTitle($data)}, enable: $root.enableToggle($data), click: function() { $root.togglePlugin($data) }"></a> | <a href="#" class="fa fa-trash-o" title="{{ _('Uninstall Plugin') }}" data-bind="css: {disabled: !$root.enableUninstall($data)}, enable: $root.enableUninstall($data), click: function() { $root.uninstallPlugin($data) }"></a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="btn-group">
|
||||
<button class="btn btn-small" data-bind="click: function() { plugins.removeFilter('enabled'); plugins.removeFilter('disabled'); }, css: {active: !_.contains(plugins.currentFilters(), 'enabled') && !_.contains(plugins.currentFilters(), 'disabled')}" title="{{ _('Show both enabled and disabled plugins')|edq }}">All</button>
|
||||
<button class="btn btn-small" data-bind="click: function() { plugins.addFilter('enabled') }, css: {active: _.contains(plugins.currentFilters(), 'enabled')}" title="{{ _('Show only enabled plugins')|edq }}">{{ _('Enabled') }}</button>
|
||||
<button class="btn btn-small" data-bind="click: function() { plugins.addFilter('disabled') }, css: {active: _.contains(plugins.currentFilters(), 'disabled')}" title="{{ _('Show only disabled plugins')|edq }}">{{ _('Disabled') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button class="btn btn-block" data-bind="click: $root.showRepository">{{ _('Get More...') }}</button>
|
||||
<div id="settings_plugin_pluginmanager_pluginlist">
|
||||
<table class="table table-striped table-hover table-condensed table-hover">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_plugin_plugin_manager_plugins_name">{{ _('Name') }}</th>
|
||||
<th class="settings_plugin_plugin_manager_plugins_actions">{{ _('Actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: plugins.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_plugin_manager_plugins_name">
|
||||
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint')|edq }}" class="fa fa-th-large" data-bind="visible: bundled"></i> <i class="fa fa-lock" title="{{ _('Cannot be uninstalled through OctoPrint')|edq }}" data-bind="visible: !managable"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect')|edq }}" class="fa fa-refresh" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install')|edq }}" class="fa fa-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall')|edq }}" class="fa fa-minus" data-bind="visible: pending_uninstall"></i> <i title="{{ _('Disabled due to safe mode')|edq }}" class="fa fa-medkit" data-bind="visible: safe_mode_victim"></i> <i class="fa fa-exclamation-triangle" title="{{ _('There are notices available regarding this plugin')|edq }}" data-bind="visible: notifications && notifications.length"></i> <i class="fa fa-ban" title="{{ _('This plugin is blacklisted')|edq }}" data-bind="visible: blacklisted"></i></div>
|
||||
<div data-bind="visible: notifications && notifications.length"><a href="javascript:void(0)" class="text-error" style="text-decoration: underline" data-bind="click: function() { $root.showPluginNotifications($data) }, text: $root.showPluginNotificationsLinkText($data)"></a></div>
|
||||
<div><small class="muted" data-bind="text: description"> </small></div>
|
||||
<div data-bind="css: {muted: !enabled}">
|
||||
<small data-bind="visible: url"><i class="fa fa-home"></i> <a data-bind="attr: {href: url}" target="_blank" rel="noreferrer noopener">{{ _('Homepage') }}</a></small>
|
||||
<small data-bind="visible: license"><i class="fa fa-gavel"></i> <span data-bind="text: license"></span></small>
|
||||
<small data-bind="visible: author"><i class="fa fa-user"></i> <span data-bind="text: author"></span></small>
|
||||
<small> </small>
|
||||
</div>
|
||||
</td>
|
||||
<td class="settings_plugin_plugin_manager_plugins_actions">
|
||||
<a href="#" data-bind="css: $root.toggleButtonCss($data), attr: {title: $root.toggleButtonTitle($data)}, enable: $root.enableToggle($data), click: function() { $root.togglePlugin($data) }"></a> | <a href="#" class="fa fa-eraser" title="{{ _('Cleanup Plugin Data')|edq }}" data-bind="css: {disabled: !$root.enableCleanup($data)}, enable: $root.enableCleanup($data), click: function() { $root.cleanupPlugin($data) }"></a> | <a href="#" class="fa fa-trash-o" title="{{ _('Uninstall Plugin')|edq }}" data-bind="css: {disabled: !$root.enableUninstall($data)}, enable: $root.enableUninstall($data), click: function() { $root.uninstallPlugin($data) }"></a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="muted" data-bind="visible: pipAvailable()">
|
||||
<div>
|
||||
<small>
|
||||
<a href="javascript:void(0)" class="muted" onclick="$(this).children('i.toggle-arrow').toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')">
|
||||
<i class="fa toggle-arrow fa-caret-right"></i> Using pip of "<span data-bind="text: pipPython"></span>", Version <span data-bind="text: pipVersion"></span>
|
||||
</a>
|
||||
</small>
|
||||
</div>
|
||||
<div class="hide">
|
||||
<small>
|
||||
Installation directory: <span data-bind="text: pipInstallDir"></span> ("--user" flag: <span data-bind="text: pipUseUserString"></span>)<br />
|
||||
Virtual environment: <span data-bind="text: pipVirtualEnvString"></span><br />
|
||||
<span data-bind="visible: pipAdditionalArgs">Additional Arguments: <span data-bind="text: pipAdditionalArgs"></span></span>
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
<button class="btn btn-block" data-bind="click: $root.showRepository">{{ _('Get More...') }}</button>
|
||||
|
||||
<div class="muted">
|
||||
<div>
|
||||
<small>
|
||||
<a href="javascript:void(0)" class="muted" onclick="$(this).children('i.toggle-arrow').toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')">
|
||||
<i class="toggle-arrow fa fa-caret-right"></i> <span data-bind="text: noticeCountText"></span>
|
||||
</a>
|
||||
</small>
|
||||
<div class="muted" data-bind="visible: pipAvailable()">
|
||||
<div>
|
||||
<small>
|
||||
<a href="javascript:void(0)" class="muted" onclick="$(this).children('i.toggle-arrow').toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')">
|
||||
<i class="fa toggle-arrow fa-caret-right"></i> Using pip of "<span data-bind="text: pipPython"></span>", Version <span data-bind="text: pipVersion"></span>
|
||||
</a>
|
||||
</small>
|
||||
</div>
|
||||
<div class="hide">
|
||||
<small>
|
||||
Installation directory: <span data-bind="text: pipInstallDir"></span> ("--user" flag: <span data-bind="text: pipUseUserString"></span>)<br />
|
||||
Virtual environment: <span data-bind="text: pipVirtualEnvString"></span><br />
|
||||
<span data-bind="visible: pipAdditionalArgs">Additional Arguments: <span data-bind="text: pipAdditionalArgs"></span></span>
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="muted">
|
||||
<div>
|
||||
<small>
|
||||
<a href="javascript:void(0)" class="muted" onclick="$(this).children('i.toggle-arrow').toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')">
|
||||
<i class="toggle-arrow fa fa-caret-right"></i> <span data-bind="text: noticeCountText"></span>
|
||||
</a>
|
||||
</small>
|
||||
</div>
|
||||
<div class="hide">
|
||||
<small>
|
||||
<!-- ko if: noticeCount() > 0 --><a href="javascript:void(0)" data-bind="click: function() { reshowNotices(); }">{{ _('Reshow current notices') }}</a> ·<!-- /ko -->
|
||||
<a href="javascript:void(0)" data-bind="click: function() { refreshNotices(); }">{{ _('Refresh notices from repository') }}</a>
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="hide">
|
||||
<small>
|
||||
<!-- ko if: noticeCount() > 0 --><a href="javascript:void(0)" data-bind="click: function() { reshowNotices(); }">{{ _('Reshow current notices') }}</a> ·<!-- /ko -->
|
||||
<a href="javascript:void(0)" data-bind="click: function() { refreshNotices(); }">{{ _('Refresh notices from repository') }}</a>
|
||||
</small>
|
||||
|
||||
<div class="tab-pane" id="settings_plugin_pluginmanager_cleanup">
|
||||
<div class="pull-right">
|
||||
<button class="btn btn-small" data-bind="click: function() { $root.requestData({refresh_orphans: true}) }" title="{{ _('Refresh')|edq }}"><i class="fa fa-refresh"></i></button>
|
||||
</div>
|
||||
|
||||
<h3>{{ _('Cleanup') }}</h3>
|
||||
|
||||
<div data-bind="visible: orphans.paginatedItems().length > 0">
|
||||
<div id="settings_plugin_pluginmanager_orphanlist">
|
||||
<table class="table table-striped table-hover table-condensed table-hover">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_plugin_plugin_manager_orphans_id">{{ _('Identifier') }}</th>
|
||||
<th class="settings_plugin_plugin_manager_orphans_actions">{{ _('Actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: orphans.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_plugin_manager_orphans_id">
|
||||
<span data-bind="text: identifier"></span>
|
||||
</td>
|
||||
<td class="settings_plugin_plugin_manager_orphans_actions">
|
||||
<a href="javascript:void(0)" class="fa fa-eraser" title="{{ _('Cleanup Plugin Data')|edq }}" data-bind="click: function() { $root.cleanupPlugin($data.identifier) }"></a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<button class="btn btn-danger btn-block" data-bind="click: $root.cleanupAll">{{ _('Cleanup all') }}</button>
|
||||
</div>
|
||||
<div data-bind="visible: orphans.paginatedItems().length == 0">
|
||||
{{ _('Nothing to cleanup! There are no settings or data left over from plugins which are no longer installed.') }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -122,6 +196,7 @@
|
||||
{{ pluginmanager_printing() }}
|
||||
{{ pluginmanager_nopip() }}
|
||||
{{ pluginmanager_safemode() }}
|
||||
{{ pluginmanager_throttled() }}
|
||||
{{ pluginmanager_offline() }}
|
||||
<h4 style="position: relative">
|
||||
{{ _('... from the <a href="%(url)s" target="_blank">Plugin Repository</a>', url='https://plugins.octoprint.org') }}
|
||||
@@ -142,7 +217,7 @@
|
||||
</h4>
|
||||
|
||||
<form class="form-search" data-bind="submit: performRepositorySearch">
|
||||
<input type="text" class="input-block search-query" data-bind="value: repositorySearchQuery, valueUpdate: 'input'" placeholder="{{ _('Search...') }}">
|
||||
<input type="text" class="input-block search-query" data-bind="value: repositorySearchQuery, valueUpdate: 'input'" placeholder="{{ _('Search...')|edq }}">
|
||||
</form>
|
||||
|
||||
<div data-bind="visible: repositoryAvailable() && repositoryplugins.paginatedItems().length > 0">
|
||||
@@ -191,7 +266,7 @@
|
||||
<form class="form-inline">
|
||||
<div class="control-group row-fluid" data-bind="css: {error: invalidUrl}">
|
||||
<div class="span9">
|
||||
<input type="text" class="input-block-level" data-bind="value: installUrl, valueUpdate: 'input'" placeholder="{{ _('Enter URL...') }}" >
|
||||
<input type="text" class="input-block-level" data-bind="value: installUrl, valueUpdate: 'input'" placeholder="{{ _('Enter URL...')|edq }}" >
|
||||
</div>
|
||||
<button class="btn btn-primary span3" data-bind="enable: enableUrlInstall, css: {disabled: !enableUrlInstall()}, click: function() { if (enableUrlInstall()) { $root.installPlugin(); } }">{{ _('Install') }}</button>
|
||||
</div>
|
||||
@@ -241,18 +316,30 @@
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form class="form-horizontal">
|
||||
<fieldset>
|
||||
<legend>{{ _('Confirmations') }}</legend>
|
||||
|
||||
<div class="control-group" title="{{ _('Confirm before disabling a plugin')|edq }}">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: config_confirmDisable"> {{ _('Confirm before disabling a plugin') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<p>{% trans %}You should normally <strong>not</strong> have to change <strong>any</strong> of the following settings, they are purely provided for convenience here.{% endtrans %}</p>
|
||||
|
||||
<fieldset>
|
||||
<legend>{{ _('Plugin repository configuration') }}</legend>
|
||||
|
||||
<div class="control-group" title="{{ _('URL of the Plugin Repository to use. You should normally not have to change this.') }}">
|
||||
<div class="control-group" title="{{ _('URL of the Plugin Repository to use. You should normally not have to change this.')|edq }}">
|
||||
<label class="control-label">{{ _('Repository URL') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_repositoryUrl">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('How long to cache repository data, in minutes. You should normally not have to change this.') }}">
|
||||
<div class="control-group" title="{{ _('How long to cache repository data, in minutes. You should normally not have to change this.')|edq }}">
|
||||
<label class="control-label">{{ _('Repository cache TTL') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
@@ -266,13 +353,13 @@
|
||||
<fieldset>
|
||||
<legend>{{ _('Notices configuration') }}</legend>
|
||||
|
||||
<div class="control-group" title="{{ _('URL of the Notices source to use. You should normally not have to change this.') }}">
|
||||
<div class="control-group" title="{{ _('URL of the Notices source to use. You should normally not have to change this.')|edq }}">
|
||||
<label class="control-label">{{ _('Notices URL') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_noticesUrl">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('How long to cache notices, in minutes. You should normally not have to change this.') }}">
|
||||
<div class="control-group" title="{{ _('How long to cache notices, in minutes. You should normally not have to change this.')|edq }}">
|
||||
<label class="control-label">{{ _('Notices cache TTL') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
@@ -286,7 +373,7 @@
|
||||
<fieldset>
|
||||
<legend>{{ _('pip configuration') }}</legend>
|
||||
|
||||
<div class="control-group" title="{{ _('Additional arguments for the pip command. You should normally not have to change this.') }}">
|
||||
<div class="control-group" title="{{ _('Additional arguments for the pip command. You should normally not have to change this.')|edq }}">
|
||||
<label class="control-label">{{ _('Additional arguments') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_pipAdditionalArgs">
|
||||
|
||||
@@ -189,7 +189,7 @@ __plugin_author__ = "Gina Häußge"
|
||||
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/printer_safety_check.html"
|
||||
__plugin_description__ = "Checks for unsafe printers/printer firmwares"
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to "
|
||||
"check if the printer it is connected to has a known safety"
|
||||
"check if the printer it is connected to has a known safety "
|
||||
"issue and inform you about that fact.")
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_implementation__ = PrinterSafetyCheckPlugin()
|
||||
|
||||
@@ -68,7 +68,7 @@ class AnycubicCheck(Check):
|
||||
def _broken_version(self, line):
|
||||
version_str = line[len(self.VERSION):]
|
||||
version = get_comparable_version(version_str, base=True)
|
||||
if version is not None and version <= self.FIXED_VERSION:
|
||||
if version is not None and version < self.FIXED_VERSION:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
@@ -35,9 +35,10 @@ from octoprint.util.pip import LocalPipCaller
|
||||
import octoprint.settings
|
||||
|
||||
|
||||
# OctoPi 0.15+
|
||||
MINIMUM_PYTHON = "2.7.9"
|
||||
MINIMUM_SETUPTOOLS = "5.5.1"
|
||||
MINIMUM_PIP = "9.0.1"
|
||||
MINIMUM_SETUPTOOLS = "39.0.1"
|
||||
MINIMUM_PIP = "9.0.3"
|
||||
|
||||
|
||||
##~~ Plugin
|
||||
@@ -77,6 +78,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
self._console_logger = None
|
||||
|
||||
self._get_throttled = lambda: False
|
||||
|
||||
def initialize(self):
|
||||
self._console_logger = logging.getLogger("octoprint.plugins.softwareupdate.console")
|
||||
|
||||
@@ -119,6 +122,12 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._console_logger.setLevel(logging.DEBUG)
|
||||
self._console_logger.propagate = False
|
||||
|
||||
helpers = self._plugin_manager.get_helpers("pi_support", "get_throttled")
|
||||
if helpers and "get_throttled" in helpers:
|
||||
self._get_throttled = helpers["get_throttled"]
|
||||
if self._settings.get_boolean(["ignore_throttled"]):
|
||||
self._logger.warn("!!! THROTTLE STATE IGNORED !!! You have configured the Software Update plugin to ignore an active throttle state of the underlying system. You might run into stability issues or outright corrupt your install. Consider fixing the throttling issue instead of suppressing it.")
|
||||
|
||||
def on_after_startup(self):
|
||||
self._check_environment()
|
||||
self.get_current_versions()
|
||||
@@ -130,9 +139,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._configured_checks = self._settings.get(["checks"], merged=True)
|
||||
|
||||
update_check_hooks = self._plugin_manager.get_hooks("octoprint.plugin.softwareupdate.check_config")
|
||||
check_providers = self._settings.get(["check_providers"], merged=True)
|
||||
if not isinstance(check_providers, dict):
|
||||
check_providers = dict()
|
||||
check_providers = dict()
|
||||
|
||||
effective_configs = dict()
|
||||
|
||||
@@ -180,9 +187,6 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
for key, config in effective_configs.items():
|
||||
self._configured_checks[key] = config
|
||||
|
||||
self._settings.set(["check_providers"], check_providers)
|
||||
self._settings.save()
|
||||
|
||||
# we only want to process checks that came from plugins for
|
||||
# which the plugins are still installed and enabled
|
||||
config_checks = self._settings.get(["checks"])
|
||||
@@ -291,11 +295,12 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
},
|
||||
},
|
||||
"pip_command": None,
|
||||
"check_providers": {},
|
||||
|
||||
"cache_ttl": 24 * 60,
|
||||
|
||||
"notify_users": True
|
||||
"notify_users": True,
|
||||
|
||||
"ignore_throttled": False
|
||||
}
|
||||
|
||||
def on_settings_load(self):
|
||||
@@ -303,12 +308,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
if "checks" in data:
|
||||
del data["checks"]
|
||||
|
||||
if "check_providers" in data:
|
||||
del data["check_providers"]
|
||||
|
||||
checks = self._get_configured_checks()
|
||||
if "octoprint" in checks:
|
||||
data["octoprint_checkout_folder"] = self._get_octoprint_checkout_folder(checks=checks)
|
||||
data["octoprint_tracked_branch"] = self._get_octoprint_tracked_branch(checks=checks)
|
||||
data["octoprint_pip_target"] = self._get_octoprint_pip_target(checks=checks)
|
||||
data["octoprint_type"] = checks["octoprint"].get("type", None)
|
||||
|
||||
try:
|
||||
@@ -339,6 +343,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
data["octoprint_type"] = None
|
||||
data["octoprint_branch_mappings"] = []
|
||||
|
||||
data["pip_enable_check"] = "pip" in checks
|
||||
|
||||
return data
|
||||
|
||||
def on_settings_save(self, data):
|
||||
@@ -364,6 +370,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
)
|
||||
|
||||
updated_octoprint_check_config = False
|
||||
update_pip_check_config = False
|
||||
|
||||
if "octoprint_checkout_folder" in data:
|
||||
self._settings.set(["checks", "octoprint", "checkout_folder"], data["octoprint_checkout_folder"], defaults=defaults, force=True)
|
||||
@@ -379,11 +386,24 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._settings.set(["checks", "octoprint", "method"], "pip", defaults=defaults)
|
||||
updated_octoprint_check_config = True
|
||||
|
||||
elif octoprint_type == "github_commit":
|
||||
self._settings.set(["checks", "octoprint", "type"], octoprint_type, defaults=defaults)
|
||||
self._settings.set(["checks", "octoprint", "method"], "pip", defaults=defaults)
|
||||
updated_octoprint_check_config = True
|
||||
|
||||
elif octoprint_type == "git_commit":
|
||||
self._settings.set(["checks", "octoprint", "type"], octoprint_type, defaults=defaults)
|
||||
self._settings.set(["checks", "octoprint", "method"], "update_script", defaults=defaults)
|
||||
updated_octoprint_check_config = True
|
||||
|
||||
if "octoprint_tracked_branch" in data:
|
||||
self._settings.set(["checks", "octoprint", "branch"], data["octoprint_tracked_branch"], defaults=defaults, force=True)
|
||||
updated_octoprint_check_config = True
|
||||
|
||||
if "octoprint_pip_target" in data:
|
||||
self._settings.set(["checks", "octoprint", "pip"], data["octoprint_pip_target"], defaults=defaults)
|
||||
updated_octoprint_check_config = True
|
||||
|
||||
if "octoprint_release_channel" in data:
|
||||
prerelease_branches = self._settings.get(["checks", "octoprint", "prerelease_branches"])
|
||||
if prerelease_branches and data["octoprint_release_channel"] in [x["branch"] for x in prerelease_branches]:
|
||||
@@ -395,6 +415,18 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._settings.set(["checks", "octoprint", "prerelease_channel"], None, defaults=defaults, force=True)
|
||||
updated_octoprint_check_config = True
|
||||
|
||||
if "pip_enable_check" in data:
|
||||
checks = self._settings.get(["checks"], merged=True)
|
||||
if data["pip_enable_check"] in octoprint.settings.valid_boolean_trues:
|
||||
checks["pip"] = dict(type="pypi_release",
|
||||
package="pip",
|
||||
pip="pip=={target_version}")
|
||||
elif "pip" in checks:
|
||||
del checks["pip"]
|
||||
self._settings.set(["checks"], checks, force=True)
|
||||
self._settings.save()
|
||||
update_pip_check_config = True
|
||||
|
||||
if updated_octoprint_check_config:
|
||||
self._refresh_configured_checks = True
|
||||
try:
|
||||
@@ -403,8 +435,16 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
pass
|
||||
self._version_cache_dirty = True
|
||||
|
||||
if update_pip_check_config:
|
||||
self._refresh_configured_checks = True
|
||||
try:
|
||||
del self._version_cache["pip"]
|
||||
except KeyError:
|
||||
pass
|
||||
self._version_cache_dirty = True
|
||||
|
||||
def get_settings_version(self):
|
||||
return 6
|
||||
return 7
|
||||
|
||||
def on_settings_migrate(self, target, current=None):
|
||||
|
||||
@@ -489,6 +529,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
dummy_defaults["plugins"][self._identifier]["checks"]["octoprint"] = None
|
||||
self._settings.set(["checks", "octoprint"], None, defaults=dummy_defaults)
|
||||
|
||||
if current is None or current < 7:
|
||||
# remove check_providers again
|
||||
self._settings.set(["check_providers"], None, defaults=dict(check_providers=dict()))
|
||||
|
||||
def _clean_settings_check(self, key, data, defaults, delete=None, save=True):
|
||||
if not data:
|
||||
# nothing to do
|
||||
@@ -591,6 +635,12 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_SOFTWAREUPDATE_UPDATE.require(403)
|
||||
def perform_update(self):
|
||||
throttled = self._get_throttled()
|
||||
if throttled and isinstance(throttled, dict) and throttled.get("current_issue", False) and not self._settings.get_boolean(["ignore_throttled"]):
|
||||
# currently throttled, we refuse to run
|
||||
return flask.make_response("System is currently throttled, refusing to update "
|
||||
"anything due to possible stability issues", 409)
|
||||
|
||||
if self._printer.is_printing() or self._printer.is_paused():
|
||||
# do not update while a print job is running
|
||||
return flask.make_response("Printer is currently printing or paused", 409)
|
||||
@@ -871,6 +921,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
to_be_updated.remove("octoprint")
|
||||
tmp = ["octoprint"] + to_be_updated
|
||||
to_be_updated = tmp
|
||||
if "pip" in to_be_updated:
|
||||
to_be_updated.remove("pip")
|
||||
tmp = ["pip"] + to_be_updated
|
||||
to_be_updated = tmp
|
||||
|
||||
updater_thread = threading.Thread(target=self._update_worker, args=(populated_checks, to_be_updated, force))
|
||||
updater_thread.daemon = False
|
||||
@@ -1063,25 +1117,28 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
raise exceptions.RestartFailed()
|
||||
|
||||
def _populated_check(self, target, check):
|
||||
from flask_babel import gettext
|
||||
|
||||
if not "type" in check:
|
||||
raise exceptions.UnknownCheckType()
|
||||
|
||||
result = dict(check)
|
||||
|
||||
if target == "octoprint":
|
||||
from flask_babel import gettext
|
||||
|
||||
from octoprint.util.version import is_released_octoprint_version, is_stable_octoprint_version
|
||||
|
||||
result["displayName"] = to_unicode(check.get("displayName"), errors="replace")
|
||||
if result["displayName"] is None:
|
||||
displayName = check.get("displayName")
|
||||
if displayName is None:
|
||||
# displayName missing or set to None
|
||||
result["displayName"] = to_unicode(gettext("OctoPrint"), errors="replace")
|
||||
displayName = gettext("OctoPrint")
|
||||
result["displayName"] = to_unicode(displayName, errors="replace")
|
||||
|
||||
result["displayVersion"] = to_unicode(check.get("displayVersion"), errors="replace")
|
||||
if result["displayVersion"] is None:
|
||||
displayVersion = check.get("displayVersion")
|
||||
if displayVersion is None:
|
||||
# displayVersion missing or set to None
|
||||
result["displayVersion"] = "{octoprint_version}"
|
||||
displayVersion = "{octoprint_version}"
|
||||
result["displayVersion"] = to_unicode(displayVersion, errors="replace")
|
||||
|
||||
stable_branch = "master"
|
||||
release_branches = []
|
||||
@@ -1126,6 +1183,23 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
# we force python unequality check for pip installs, to be able to downgrade
|
||||
result["release_compare"] = "python_unequal"
|
||||
|
||||
elif target == "pip":
|
||||
import pkg_resources
|
||||
|
||||
displayName = check.get("displayName")
|
||||
if displayName is None:
|
||||
# displayName missing or set to None
|
||||
displayName = gettext("pip")
|
||||
result["displayName"] = to_unicode(displayName, errors="replace")
|
||||
|
||||
displayVersion = check.get("displayVersion")
|
||||
if displayVersion is None:
|
||||
# displayVersion missing or set to None
|
||||
distribution = pkg_resources.get_distribution("pip")
|
||||
if distribution:
|
||||
displayVersion = distribution.version
|
||||
result["displayVersion"] = to_unicode(displayVersion, errors="replace")
|
||||
|
||||
else:
|
||||
result["displayName"] = to_unicode(check.get("displayName"), errors="replace")
|
||||
if result["displayName"] is None:
|
||||
@@ -1230,6 +1304,24 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
return None
|
||||
|
||||
def _get_octoprint_tracked_branch(self, checks=None):
|
||||
if checks is None:
|
||||
checks = self._get_configured_checks()
|
||||
|
||||
if not "octoprint" in checks:
|
||||
return None
|
||||
|
||||
return checks["octoprint"].get("branch")
|
||||
|
||||
def _get_octoprint_pip_target(self, checks=None):
|
||||
if checks is None:
|
||||
checks = self._get_configured_checks()
|
||||
|
||||
if not "octoprint" in checks:
|
||||
return None
|
||||
|
||||
return checks["octoprint"].get("pip")
|
||||
|
||||
|
||||
def _register_custom_events(*args, **kwargs):
|
||||
return ["update_succeeded", "update_failed"]
|
||||
|
||||
@@ -1 +1 @@
|
||||
#settings_plugin_softwareupdate_updatelist{display:block;width:auto;height:500px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_information .line{display:block}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
|
||||
#settings_plugin_softwareupdate_updatelist{display:block;width:auto;max-height:500px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_information .line{display:block}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
|
||||
@@ -6,6 +6,11 @@ $(function() {
|
||||
self.printerState = parameters[1];
|
||||
self.settings = parameters[2];
|
||||
self.access = parameters[3];
|
||||
|
||||
// optional
|
||||
|
||||
self.piSupport = parameters[4]; // might be null!
|
||||
|
||||
self.popup = undefined;
|
||||
|
||||
self.updateInProgress = false;
|
||||
@@ -25,7 +30,8 @@ $(function() {
|
||||
self.octoprintReleasedVersion = ko.observable();
|
||||
|
||||
self.octoprintUnconfigured = ko.pureComputed(function() {
|
||||
return self.error_checkoutFolder();
|
||||
return self.settings.settings.plugins.softwareupdate.octoprint_type() === "git_commit"
|
||||
&& self.error_checkoutFolder();
|
||||
});
|
||||
self.octoprintUnreleased = ko.pureComputed(function() {
|
||||
return self.settings.settings.plugins.softwareupdate.octoprint_type() === "github_release"
|
||||
@@ -42,9 +48,12 @@ $(function() {
|
||||
|
||||
self.config_cacheTtl = ko.observable();
|
||||
self.config_notifyUsers = ko.observable();
|
||||
self.config_trackedBranch = ko.observable();
|
||||
self.config_checkoutFolder = ko.observable();
|
||||
self.config_pipTarget = ko.observable();
|
||||
self.config_checkType = ko.observable();
|
||||
self.config_releaseChannel = ko.observable();
|
||||
self.config_pipEnableCheck = ko.observable();
|
||||
|
||||
self.error_checkoutFolder = ko.pureComputed(function() {
|
||||
return self.config_checkType() === "git_commit"
|
||||
@@ -52,11 +61,12 @@ $(function() {
|
||||
});
|
||||
|
||||
self.enableUpdate = ko.pureComputed(function() {
|
||||
return !self.updateInProgress && self.environmentSupported();
|
||||
return !self.updateInProgress && self.environmentSupported() && !self.printerState.isPrinting() && !self.throttled();
|
||||
});
|
||||
|
||||
self.enable_configSave = ko.pureComputed(function() {
|
||||
return self.config_checkType() === "github_release"
|
||||
|| self.config_checkType() === "github_commit"
|
||||
|| (self.config_checkType() === "git_commit" && !self.error_checkoutFolder());
|
||||
});
|
||||
|
||||
@@ -92,6 +102,10 @@ $(function() {
|
||||
return _.filter(self.versions.items(), function(info) { return info.updateAvailable && info.updatePossible; });
|
||||
});
|
||||
|
||||
self.throttled = ko.pureComputed(function() {
|
||||
return self.piSupport && self.piSupport.currentIssue() && !self.settings.settings.plugins.pluginmanager.ignore_throttled();
|
||||
});
|
||||
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
|
||||
if (self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_CHECK)) {
|
||||
self.performCheck();
|
||||
@@ -149,7 +163,10 @@ $(function() {
|
||||
notify_users: self.config_notifyUsers(),
|
||||
octoprint_type: self.config_checkType(),
|
||||
octoprint_release_channel: self.config_releaseChannel(),
|
||||
octoprint_checkout_folder: self.config_checkoutFolder()
|
||||
octoprint_checkout_folder: self.config_checkoutFolder(),
|
||||
octoprint_tracked_branch: self.config_trackedBranch(),
|
||||
octoprint_pip_target: self.config_pipTarget(),
|
||||
pip_enable_check: self.config_pipEnableCheck()
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -168,7 +185,8 @@ $(function() {
|
||||
|
||||
self._copyConfig = function() {
|
||||
var availableCheckTypes = [{"key": "github_release", "name": gettext("Release")},
|
||||
{"key": "git_commit", "name": gettext("Commit")}];
|
||||
{"key": "github_commit", "name": gettext("Github Commit")},
|
||||
{"key": "git_commit", "name": gettext("Local checkout")}];
|
||||
self.config_availableCheckTypes(availableCheckTypes);
|
||||
|
||||
var availableReleaseChannels = [];
|
||||
@@ -183,6 +201,10 @@ $(function() {
|
||||
self.config_checkType(self.settings.settings.plugins.softwareupdate.octoprint_type());
|
||||
self.config_releaseChannel(self.settings.settings.plugins.softwareupdate.octoprint_release_channel());
|
||||
self.config_checkoutFolder(self.settings.settings.plugins.softwareupdate.octoprint_checkout_folder());
|
||||
self.config_trackedBranch(self.settings.settings.plugins.softwareupdate.octoprint_tracked_branch());
|
||||
self.config_pipTarget(self.settings.settings.plugins.softwareupdate.octoprint_pip_target());
|
||||
|
||||
self.config_pipEnableCheck(self.settings.settings.plugins.softwareupdate.pip_enable_check());
|
||||
};
|
||||
|
||||
self._copyConfigBack = function() {
|
||||
@@ -208,11 +230,11 @@ $(function() {
|
||||
}
|
||||
|
||||
var fullNameTemplate = gettext("%(name)s: %(version)s");
|
||||
value.fullNameLocal = _.sprintf(fullNameTemplate, {name: value.displayName, version: value.displayVersion});
|
||||
value.fullNameLocal = _.sprintf(fullNameTemplate, {name: _.escape(value.displayName), version: _.escape(value.displayVersion)});
|
||||
|
||||
var fullNameRemoteVars = {name: value.displayName, version: gettext("unknown")};
|
||||
var fullNameRemoteVars = {name: _.escape(value.displayName), version: gettext("unknown")};
|
||||
if (value.hasOwnProperty("information") && value.information.hasOwnProperty("remote") && value.information.remote.hasOwnProperty("name")) {
|
||||
fullNameRemoteVars.version = value.information.remote.name;
|
||||
fullNameRemoteVars.version = _.escape(value.information.remote.name);
|
||||
}
|
||||
value.fullNameRemote = _.sprintf(fullNameTemplate, fullNameRemoteVars);
|
||||
|
||||
@@ -476,36 +498,46 @@ $(function() {
|
||||
type: "error"
|
||||
});
|
||||
self._updateClicked = false;
|
||||
} else {
|
||||
var html = "<p>" + gettext("This will update the following components and restart the server:") + "</p>";
|
||||
html += "<ul>";
|
||||
_.each(items, function(item) {
|
||||
html += "<li>"
|
||||
+ "<span class=\"name\" title=\"" + item.fullNameRemote + "\">" + item.fullNameRemote + "</span>";
|
||||
if (item.releaseNotes) {
|
||||
html += "<br><a href=\"" + item.releaseNotes + "\" target=\"_blank\" rel=\"noreferrer noopener\">" + gettext("Release Notes") + "</a>"
|
||||
}
|
||||
html += "</li>";
|
||||
});
|
||||
html += "</ul>";
|
||||
html += "<p>" + gettext("Be sure to read through any linked release notes, especially those for OctoPrint since they might contain important information you need to know <strong>before</strong> upgrading.") + "</p>"
|
||||
+ "<p><strong>" + gettext("This action may disrupt any ongoing print jobs.") + "</strong></p>"
|
||||
+ "<p>" + gettext("Depending on your printer's controller and general setup, restarting OctoPrint may cause your printer to be reset.") + "</p>"
|
||||
+ "<p>" + gettext("Are you sure you want to proceed?") + "</p>";
|
||||
showConfirmationDialog({
|
||||
title: gettext("Are you sure you want to update now?"),
|
||||
html: html,
|
||||
proceed: gettext("Proceed"),
|
||||
onproceed: function() {
|
||||
self.performUpdate((force === true),
|
||||
_.map(items, function(info) { return info.key }));
|
||||
},
|
||||
onclose: function() {
|
||||
self._updateClicked = false;
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (self.throttled()) {
|
||||
self._showPopup({
|
||||
title: gettext("Can't update while throttled"),
|
||||
text: gettext("Your system is currently throttled. OctoPrint refuses to run updates while in this state due to possible stability issues."),
|
||||
type: "error"
|
||||
});
|
||||
self._updateClicked = false;
|
||||
return;
|
||||
}
|
||||
|
||||
var html = "<p>" + gettext("This will update the following components and restart the server:") + "</p>";
|
||||
html += "<ul>";
|
||||
_.each(items, function(item) {
|
||||
html += "<li>"
|
||||
+ "<span class=\"name\" title=\"" + item.fullNameRemote + "\">" + item.fullNameRemote + "</span>";
|
||||
if (item.releaseNotes) {
|
||||
html += "<br><a href=\"" + item.releaseNotes + "\" target=\"_blank\" rel=\"noreferrer noopener\">" + gettext("Release Notes") + "</a>"
|
||||
}
|
||||
html += "</li>";
|
||||
});
|
||||
html += "</ul>";
|
||||
html += "<p>" + gettext("Be sure to read through any linked release notes, especially those for OctoPrint since they might contain important information you need to know <strong>before</strong> upgrading.") + "</p>"
|
||||
+ "<p><strong>" + gettext("This action may disrupt any ongoing print jobs.") + "</strong></p>"
|
||||
+ "<p>" + gettext("Depending on your printer's controller and general setup, restarting OctoPrint may cause your printer to be reset.") + "</p>"
|
||||
+ "<p>" + gettext("Are you sure you want to proceed?") + "</p>";
|
||||
showConfirmationDialog({
|
||||
title: gettext("Are you sure you want to update now?"),
|
||||
html: html,
|
||||
proceed: gettext("Proceed"),
|
||||
onproceed: function() {
|
||||
self.performUpdate((force === true),
|
||||
_.map(items, function(info) { return info.key }));
|
||||
},
|
||||
onclose: function() {
|
||||
self._updateClicked = false;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self._showWorkingDialog = function(title) {
|
||||
@@ -627,7 +659,7 @@ $(function() {
|
||||
break;
|
||||
}
|
||||
case "updating": {
|
||||
text = _.sprintf(gettext("Now updating %(name)s to %(version)s"), {name: messageData.name, version: messageData.version});
|
||||
text = _.sprintf(gettext("Now updating %(name)s to %(version)s"), {name: _.escape(messageData.name), version: _.escape(messageData.version)});
|
||||
self.loglines.push({line: "", stream: "separator"});
|
||||
self.loglines.push({line: _.repeat("+", text.length), stream: "separator"});
|
||||
self.loglines.push({line: text, stream: "message"});
|
||||
@@ -781,7 +813,8 @@ $(function() {
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: SoftwareUpdateViewModel,
|
||||
dependencies: ["loginStateViewModel", "printerStateViewModel", "settingsViewModel", "accessViewModel"],
|
||||
dependencies: ["loginStateViewModel", "printerStateViewModel", "settingsViewModel", "accessViewModel", "piSupportViewModel"],
|
||||
optional: ["piSupportViewModel"],
|
||||
elements: ["#settings_plugin_softwareupdate", "#softwareupdate_confirmation_dialog", "#wizard_plugin_softwareupdate"]
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
#settings_plugin_softwareupdate_updatelist {
|
||||
display: block;
|
||||
width: auto;
|
||||
height: 500px;
|
||||
max-height: 500px;
|
||||
overflow-x: hidden;
|
||||
overflow-y: scroll;
|
||||
padding-right: 2px;
|
||||
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: config_pipEnableCheck"> {{ _('Enable <code>pip</code> update checks') }}
|
||||
<span class="help-block">{{ _('If you check this, OctoPrint will also notify you of updates of the <code>pip</code> tool used by OctoPrint to install plugins and updates and allow you to update it through OctoPrint. <code>pip</code> is outside of the control of the OctoPrint maintainer, so enable at your own risk.') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
<div class="control-group" data-bind="visible: config_checkType() === 'github_release' || config_checkType() === 'github_commit'">
|
||||
<label class="control-label">{{ _('OctoPrint <code>pip</code> target') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_pipTarget">
|
||||
<span class="help-block">{{ _('You should normally not have to change this.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
Loaded 100 of 237 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user