Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6c622f7c43 | ||
|
|
d34790e74e | ||
|
|
aa5099340e | ||
|
|
693633bd1d | ||
|
|
758062133c | ||
|
|
c55fea666d | ||
|
|
c932e496fa | ||
|
|
bbbdb3dde6 | ||
|
|
b9460b4890 | ||
|
|
947f4c89cc | ||
|
|
5f982ec6c8 | ||
|
|
dcf2e51b21 | ||
|
|
85e6ae8e82 | ||
|
|
859ea0d0e4 | ||
|
|
9cf21aa036 | ||
|
|
637adc3095 | ||
|
|
548f976d35 | ||
|
|
45c92cb1f4 | ||
|
|
f83d5aa89f | ||
|
|
abf073340f | ||
|
|
918ffa2557 | ||
|
|
5cc8ec5cc3 | ||
|
|
fce7b40b51 | ||
|
|
1178fe9e95 | ||
|
|
2f24e73fcb | ||
|
|
9ff5c36370 | ||
|
|
1b4ea75466 | ||
|
|
b4b5689bc4 | ||
|
|
fd4271a962 | ||
|
|
65bc28a03e | ||
|
|
c26515c13d | ||
|
|
25a4d4b79b | ||
|
|
43ca4d8252 | ||
|
|
b56ba6589c | ||
|
|
5c9b507cb7 | ||
|
|
cd7ac032f4 | ||
|
|
a2e5fc0c5c | ||
|
|
536bb31965 | ||
|
|
ef46a49430 | ||
|
|
8e28ddd6a4 | ||
|
|
ab8b0230bd | ||
|
|
754ef428a0 | ||
|
|
455474841e | ||
|
|
ae4e4f22c4 | ||
|
|
96fc70bdb2 | ||
|
|
8ed0befd62 | ||
|
|
766c0c21d4 | ||
|
|
7d50563666 | ||
|
|
4011f60ff9 | ||
|
|
37950cb466 | ||
|
|
2824b967ff | ||
|
|
7b8bf2cf5c | ||
|
|
9299cb54a4 | ||
|
|
b965d4cbde | ||
|
|
7d922f3c77 | ||
|
|
7e894d2ac2 | ||
|
|
948e20b269 | ||
|
|
0e863ad776 | ||
|
|
13d7d5f2f6 | ||
|
|
ac8faf7910 | ||
|
|
bf049ddee4 | ||
|
|
e435d55cb1 | ||
|
|
2c50237699 | ||
|
|
93763a5563 | ||
|
|
7a74f5348d | ||
|
|
b25c2220d1 | ||
|
|
57161dd9c3 | ||
|
|
1343a4a253 | ||
|
|
6de7eabca2 | ||
|
|
2247f30c87 | ||
|
|
ba6a6723a6 | ||
|
|
f9a0cb94f7 | ||
|
|
e689a2c733 | ||
|
|
d07c81f312 | ||
|
|
32f4f8d95b | ||
|
|
7f2e0161a8 | ||
|
|
59993bfca4 | ||
|
|
0782dda20f | ||
|
|
8c1a79558b | ||
|
|
0705a7054c | ||
|
|
54bd7766b9 | ||
|
|
ed215fc5fa | ||
|
|
5f53b704dd | ||
|
|
e8ef0ba8a4 | ||
|
|
49f62bc655 | ||
|
|
0ff43def3a | ||
|
|
cc14b77487 | ||
|
|
7f10c317f1 | ||
|
|
ba1f8c58b4 | ||
|
|
273bb45741 | ||
|
|
e33f69917f | ||
|
|
4b8bdd244e | ||
|
|
202f93426a | ||
|
|
c538604cd5 | ||
|
|
0c44762f6f | ||
|
|
6df57bc1d1 | ||
|
|
e328695100 | ||
|
|
738c699a6e | ||
|
|
8a28220e63 | ||
|
|
5808c1bd8a | ||
|
|
8bbb642a56 | ||
|
|
1f0dbf8f7f | ||
|
|
9a6099ffc2 | ||
|
|
25de95dc93 | ||
|
|
57f6e1e1bc | ||
|
|
edf9c40941 | ||
|
|
4dd4a2cc9c | ||
|
|
81bc8c784a | ||
|
|
294e7fc2db | ||
|
|
6e632d02a0 | ||
|
|
50ff0d810f | ||
|
|
d4be7f18e2 | ||
|
|
6d24a46e88 | ||
|
|
db866d2310 | ||
|
|
bb7e15be84 | ||
|
|
7a007a6417 | ||
|
|
96aad9d34f | ||
|
|
4d3334caf1 | ||
|
|
2745f49d28 | ||
|
|
5470aaaa3a | ||
|
|
f89cbc9133 | ||
|
|
5dfffc36e3 | ||
|
|
3761995aff | ||
|
|
e62cef590b | ||
|
|
677e583345 | ||
|
|
abbf937e7f | ||
|
|
8d14ea6093 | ||
|
|
97826b2f3b | ||
|
|
a1e0078ce5 | ||
|
|
a5bf3c3be1 | ||
|
|
19a5613e59 | ||
|
|
ced286854c | ||
|
|
811ffc760f | ||
|
|
549b60edb1 | ||
|
|
8735b10653 | ||
|
|
29d49179a9 | ||
|
|
19b4a0f403 | ||
|
|
d854b41ffb | ||
|
|
329a575031 | ||
|
|
85ad85bdfa | ||
|
|
95c26a7850 | ||
|
|
885e6f916c | ||
|
|
d7a86a4d28 | ||
|
|
7b3e0563cc | ||
|
|
50a62bf00a | ||
|
|
1c6b0554c7 | ||
|
|
537c205757 | ||
|
|
f07b2477f5 | ||
|
|
5e5531f6d8 | ||
|
|
eadc9ee795 | ||
|
|
0b3f94b6bd | ||
|
|
9f8d30a66c | ||
|
|
2a8eea086c | ||
|
|
bb0bfaee56 | ||
|
|
b8209e8e09 | ||
|
|
a5b87a9067 | ||
|
|
b3e547c60f | ||
|
|
1ead6e2d20 | ||
|
|
016bdd542a | ||
|
|
4dc9d0a536 | ||
|
|
4b11032567 | ||
|
|
0c54eaf176 | ||
|
|
401ebcf685 | ||
|
|
69e5f137a6 | ||
|
|
a0f2079fb5 | ||
|
|
cfa4cb2a7c | ||
|
|
12a1bebe7e | ||
|
|
d461acffc7 | ||
|
|
e60cdc9d0f | ||
|
|
67a0fd11dd | ||
|
|
fca8becb20 | ||
|
|
be423e49fd | ||
|
|
5decb23f23 | ||
|
|
ac151d9019 | ||
|
|
71ccc47717 | ||
|
|
b32f9bddd2 | ||
|
|
1a7193e113 | ||
|
|
a580482c29 | ||
|
|
e230cfb3f3 | ||
|
|
030b6b4478 | ||
|
|
0f818a313d | ||
|
|
326fc943b7 | ||
|
|
7e6ddaf0d6 | ||
|
|
22710ccfb3 | ||
|
|
33ea9c3459 | ||
|
|
e722c2f8ad | ||
|
|
1c99bccef9 | ||
|
|
61bd803942 | ||
|
|
2f5c3570dd | ||
|
|
9e12a8353b | ||
|
|
c6cb430594 | ||
|
|
0e60b26048 | ||
|
|
269f18a22f | ||
|
|
7c74aa4c4d | ||
|
|
a6c1084b14 | ||
|
|
4abd97df09 | ||
|
|
904a3cdaff | ||
|
|
f58d63bb49 | ||
|
|
dedf3f234f | ||
|
|
633d1ae594 | ||
|
|
0846a0fed0 | ||
|
|
f1be116190 | ||
|
|
d5af7b9b48 | ||
|
|
e55677da22 | ||
|
|
9f4a74cca0 | ||
|
|
b40cba659a | ||
|
|
a26b203205 | ||
|
|
6e90c9d730 | ||
|
|
31d7eaad90 | ||
|
|
0d886ab6f1 | ||
|
|
cbd3b1424b | ||
|
|
0ce1575e12 | ||
|
|
268886576f | ||
|
|
cbc6f20fa6 | ||
|
|
608be52b9a | ||
|
|
4badf72e18 | ||
|
|
5da52b6c57 | ||
|
|
c527338cb8 | ||
|
|
46711ce365 | ||
|
|
8353c9bdf5 | ||
|
|
6a7a858065 |
No files matched your search
+10
-6
@@ -7,12 +7,16 @@
|
||||
# The file is processed from top to bottom, the first matching line wins. If <tag> or <reference commit> are left out,
|
||||
# the lookup table does not apply to the matched branches
|
||||
|
||||
# master and staging shall not use the lookup table
|
||||
# master shall not use the lookup table, only tags
|
||||
master
|
||||
staging
|
||||
|
||||
# fix/ branches are fixes for master, so we don't handle those either
|
||||
fix/.*
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.2.7
|
||||
# so are any fix/... branches
|
||||
maintenance 1.2.7-dev 536bb31965db17b969e7c1c53e241ddac4ae1814
|
||||
fix/.* 1.2.7-dev 536bb31965db17b969e7c1c53e241ddac4ae1814
|
||||
|
||||
# every other branch is a development branch and thus gets resolved to 1.2.0-dev for now
|
||||
.* 1.2.0-dev 50cf776e70b9
|
||||
# Special case disconnected checkouts, e.g. 'git checkout <tag>'
|
||||
\(detached.*
|
||||
|
||||
# every other branch is a development branch and thus gets resolved to 1.3.0-dev for now
|
||||
.* 1.3.0-dev 198d3450d94be1a2
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
# Authors
|
||||
|
||||
The following people have contributed to OctoPrint's code base (ordered by
|
||||
date of first contribution):
|
||||
|
||||
* [Gina Häußge](https://github.com/foosel)
|
||||
* [Thomas Sanladerer](https://github.com/imitation)
|
||||
* [Alex Ustyantsev](https://github.com/hudbrog)
|
||||
* [Andrew Dalgleish](https://github.com/ajd4096)
|
||||
* [Dale Price](https://github.com/daprice)
|
||||
* [Václav "ax" Hůla](https://github.com/AxTheB)
|
||||
* [Tom Perry](https://github.com/daftscience)
|
||||
* [Andreas Gohr](https://github.com/splitbrain)
|
||||
* [Lars Norpchen](https://github.com/norpchen)
|
||||
* [Marlon Wünnemann](https://github.com/marwue)
|
||||
* ["algspd"](https://github.com/algspd)
|
||||
* [Peter Uithoven](https://github.com/peteruithoven)
|
||||
* [Bryan Mayland](https://github.com/CapnBry)
|
||||
* [Ross Hendrickson](https://github.com/savorywatt)
|
||||
* [Dan Lipsitt](https://github.com/DanLipsitt)
|
||||
* [James Gao](https://github.com/jamesgao)
|
||||
* [Tonnerre Lombard](https://github.com/tonnerre)
|
||||
* [Marc Hannappel](https://github.com/Salandora)
|
||||
* [Brad Pitcher](https://github.com/brad)
|
||||
* [Gabe Rosenhouse](https://github.com/rosenhouse)
|
||||
* [chriskoz](https://github.com/chriskoz)
|
||||
* [Ilya Novoselov](https://github.com/nullie)
|
||||
* [Corey C](https://github.com/C-o-r-E)
|
||||
* [Jarek Szczepanski](https://github.com/imrahil)
|
||||
* [Jon Nordby](https://github.com/jonnor)
|
||||
* [Aaron Bieber](https://github.com/qbit)
|
||||
* [Guy Sheffer](https://github.com/guysoft)
|
||||
* [Dattas Moonchaser](https://github.com/dattas)
|
||||
* [Pim Rutgers](https://github.com/Booli)
|
||||
* [Koen Kooi](https://github.com/koenkooi)
|
||||
* [Colin Wallace](https://github.com/Wallacoloo)
|
||||
* [Michael Ang](https://github.com/mangtronix)
|
||||
* [Philipp Engel](https://github.com/nosyjoe)
|
||||
* [Giles Hall](https://github.com/vishnubob)
|
||||
* [Bevaz](https://github.com/Bevaz)
|
||||
* [Bortek](https://github.com/bortek)
|
||||
* [Rob Speed](https://github.com/rspeed)
|
||||
* [Renha](https://github.com/Renha)
|
||||
* [Antoine Bertin](https://github.com/Diaoul)
|
||||
* [Teja Philipp](https://github.com/hungerpirat)
|
||||
* ["matobago"](https://github.com/matobago)
|
||||
* ["nophead"](https://github.com/nophead)
|
||||
* [Bob Clough](https://github.com/thinkl33t)
|
||||
* [Mikk Kiilaspää](https://github.com/Mikk36)
|
||||
* [Jack Minardi](https://github.com/jminardi)
|
||||
* [Mark Walker](https://github.com/markwal)
|
||||
* [Lucas Clemente](https://github.com/lucas-clemente)
|
||||
* [Andrew Erickson](https://github.com/aerickson)
|
||||
* [Nicanor Romero Venier](https://github.com/nicanor-romero)
|
||||
* [Thomas Hou](https://github.com/masterhou)
|
||||
|
||||
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
|
||||
the server side GCODE interpreter are still based on Cura's code base from
|
||||
December 2012 and hence on the work of its authors up until then.
|
||||
+326
-36
@@ -1,33 +1,303 @@
|
||||
# OctoPrint Changelog
|
||||
|
||||
## 1.2.0 (Unreleased)
|
||||
## 1.2.7 (2015-10-20)
|
||||
|
||||
### Improvements
|
||||
|
||||
* [#1062](https://github.com/foosel/OctoPrint/issues/1062) - Plugin Manager
|
||||
now has a configuration dialog that among other things allows defining the
|
||||
used `pip` command if auto detection proves to be insufficient here.
|
||||
* Allow defining additional `pip` parameters in Plugin Manager. That might
|
||||
make `sudo`-less installation of plugins possible in situations where it's
|
||||
tricky otherwise.
|
||||
* Improved timelapse processing (backported from `devel` branch):
|
||||
* Individually captured frames cannot "overtake" each other anymore through
|
||||
usage of a capture queue.
|
||||
* Notifications will now be shown when the capturing of the timelapse's
|
||||
post roll happens, including an approximation of how long that will take.
|
||||
* Usage of `requests` instead of `urllib` for fetching the snapshot,
|
||||
appears to also have [positive effects on webcam compatibility](https://github.com/foosel/OctoPrint/issues/1078).
|
||||
* Some more defensive escaping for various settings in the UI (e.g. webcam URL)
|
||||
* Switch to more error resilient saving of configuration files and other files
|
||||
modified during runtime (save to temporary file & move). Should reduce risk
|
||||
of file corruption.
|
||||
* Downloading GCODE and STL files should now set more fitting `Content-Type`
|
||||
headers (`text/plain` and `application/sla`) for better client side support
|
||||
for "Open with" like usage scenarios.
|
||||
* Selecting z-triggered timelapse mode will now inform about that not working
|
||||
when printing from SD card.
|
||||
* Software Update Plugin: Removed "The web interface will now be reloaded"
|
||||
notification after successful update since that became obsolete with
|
||||
introduction of the "Reload Now" overlay.
|
||||
* Updated required version of `psutil` and `netifaces` dependencies.
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* [#1057](https://github.com/foosel/OctoPrint/issues/1057) - Better error
|
||||
resilience of the Software Update plugin against broken/incomplete update
|
||||
configurations.
|
||||
* [#1075](https://github.com/foosel/OctoPrint/issues/1075) - Fixed support
|
||||
of `sudo` for installing plugins, but added big visible warning about it
|
||||
as it's **not** recommended.
|
||||
* [#1077](https://github.com/foosel/OctoPrint/issues/1077) - Do not hiccup
|
||||
on [UTF-8 BOMs](https://en.wikipedia.org/wiki/Byte_order_mark) (or other
|
||||
BOMs for that matter) at the beginning of GCODE files.
|
||||
* Fixed an issue that caused user sessions to not be properly associated,
|
||||
leading to Sessions getting duplicated, wrongly saved etc.
|
||||
* Fixed internal server error (HTTP 500) response on REST API calls with
|
||||
unset `Content-Type` header.
|
||||
* Fixed an issue leading to drag-and-drop file uploads to trigger frontend
|
||||
processing in various other file upload widgets.
|
||||
* Fixed a documentation error.
|
||||
* Fixed caching behaviour on GCODE/STL downloads, was setting the `ETag`
|
||||
header improperly.
|
||||
* Fixed GCODE viewer not properly detecting change of currently visualized
|
||||
file on Windows systems.
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.6...1.2.7))
|
||||
|
||||
## 1.2.6 (2015-09-02)
|
||||
|
||||
### Improvements
|
||||
|
||||
* Added support for version reporting on detached checkouts
|
||||
(see [#1041](https://github.com/foosel/OctoPrint/pull/1041))
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Pinned requirement for [psutil](https://pypi.python.org/pypi/psutil)
|
||||
dependency to version 3.1.1 of that library due to an issue when
|
||||
installing version 3.2.0 of that library released on 2015-09-02 through
|
||||
a `python setup.py install` on OctoPrint. Also pinned all other requirements
|
||||
to definitive versions that definitely work while at it to keep that from
|
||||
happening again.
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.5...1.2.6))
|
||||
|
||||
## 1.2.5 (2015-08-31)
|
||||
|
||||
### Improvements
|
||||
|
||||
* [#986](https://github.com/foosel/OctoPrint/issues/986) - Added tooltip for
|
||||
"additional data" button in file list.
|
||||
* [#1028](https://github.com/foosel/OctoPrint/issues/1028) - Hint about why
|
||||
timelapse configuration is disabled.
|
||||
* New central configuration option for commands to restart OctoPrint and to
|
||||
restart and shut down the system OctoPrint is running on. This allows plugins
|
||||
(like the Software Update Plugin or the Plugin Manager) and core functionality
|
||||
to perform these common administrative tasks without the user needing to define
|
||||
everything redundantly.
|
||||
* Settings dialog now visualizes when settings are saving and when they being
|
||||
retrieved. Also the Send/Cancel buttons are disabled while settings are saving
|
||||
to prevent duplicated requests and concurrent retrieval of the settings by
|
||||
multiple viewmodels is disabled as well.
|
||||
* Better protection against rendering errors from templates provided by third
|
||||
party plugins.
|
||||
* Better protection against corrupting the configuration by using a temporary
|
||||
file as intermediate buffer.
|
||||
* Added warning to UI regarding Z timelapses and spiralized objects.
|
||||
* Better compatibility with Repetier firmware:
|
||||
* Added "Format Error" to whitelisted recoverable communication errors
|
||||
(see also [#1032](https://github.com/foosel/OctoPrint/pull/1032)).
|
||||
* Added option to ignore repeated resend requests for the same line (see
|
||||
also discussion in [#1015](https://github.com/foosel/OctoPrint/pull/1015)).
|
||||
* Software Update Plugin:
|
||||
* Adjusted to utilize new centralized restart commands (see above).
|
||||
* Allow configuration of checkout folder and version tracking type via
|
||||
Plugin Configuration.
|
||||
* Display message to user if OctoPrint's checkout folder is not configured
|
||||
or a non-release version is running and version tracking against releases
|
||||
is enabled.
|
||||
* Clear version cache when a change in the check configuration is detected.
|
||||
* Mark check configurations for which an update is not possible.
|
||||
* Made disk space running low a bit more obvious through visual warning on
|
||||
configurable thresholds.
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* [#985](https://github.com/foosel/OctoPrint/issues/985) - Do not hiccup on
|
||||
unset `Content-Type` part headers for multipart file uploads.
|
||||
* [#1001](https://github.com/foosel/OctoPrint/issues/1001) - Fixed connection
|
||||
tab not unfolding properly (see also [#1002](https://github.com/foosel/OctoPrint/pull/1002)).
|
||||
* [#1012](https://github.com/foosel/OctoPrint/issues/1012) - All API
|
||||
responses now set no-cache headers, making the Edge browser behave a bit better
|
||||
* [#1019](https://github.com/foosel/OctoPrint/issues/1019) - Better error
|
||||
handling of problems when trying to write the webassets cache.
|
||||
* [#1021](https://github.com/foosel/OctoPrint/issues/1021) - Properly handle
|
||||
serial close on Macs.
|
||||
* [#1031](https://github.com/foosel/OctoPrint/issues/1031) - Special
|
||||
handling of `M112` (emergency stop) command:
|
||||
* Jump send queue
|
||||
* In case the printer's firmware doesn't understand it yet, at least
|
||||
shutdown all of the heaters
|
||||
* Disconnect
|
||||
* Properly reset job progress to 0% when restarting a previously completed
|
||||
printjob (see [#998](https://github.com/foosel/OctoPrint/pull/998)).
|
||||
* Report an update as failed if the `pip` command returns a return code that
|
||||
indicates failure.
|
||||
* Fixed sorting of templates: could only be sorted by name, individual
|
||||
configurations were ignored (see [#1022](https://github.com/foosel/OctoPrint/pull/1022)).
|
||||
* Fixed positioning of custom context menus: were offset due to changes in
|
||||
overall positioning settings (see [#1023](https://github.com/foosel/OctoPrint/pull/1023)).
|
||||
* Software Update: Don't use display version for comparison of git commit
|
||||
hashs.
|
||||
* Fixed temperature parsing for multi extruder setups.
|
||||
* Fixed nested vertical and horizontal custom control layouts.
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.4...1.2.5))
|
||||
|
||||
## 1.2.4 (2015-07-23)
|
||||
|
||||
### Improvements
|
||||
|
||||
* `RepeatedTimer` now defaults to `daemon` set to `True`. This makes sure
|
||||
plugins using it don't have to remember to set that flag themselves in
|
||||
order for the server to properly shut down when timers are still active.
|
||||
* Fixed a typo in the docs about `logging.yaml` (top level element is
|
||||
`loggers`, not `logger`).
|
||||
* Support for plugins with external dependencies (`dependency_links` in
|
||||
setuptools), interesting for plugin authors who need to depend on Python
|
||||
libraries that are (not yet) available on PyPI.
|
||||
* Better resilience against errors within plugins.
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Do not cache web page when running for the first time, to avoid caching
|
||||
the first run dialog popup along side with it. This should solve issues
|
||||
people were having when configuring OctoPrint for the first time, then
|
||||
reloading the page without clearing the cache, being again prompted with
|
||||
the dialog with no chance to clear it.
|
||||
* Fix/workaround for occasional white panes in settings dialog on Safari 8,
|
||||
which appears to have an issue with fixed positioning.
|
||||
* Fixed form field truncation in upload requests that could lead to problems
|
||||
when trying to import Cura profiles with names longer than 28 characters.
|
||||
* Fixed webcam rotation for timelapse rendering.
|
||||
* Fixed user settings not reaching the editor in the frontend.
|
||||
* Notifications that are in process of being closed don't open again on
|
||||
mouse over (that was actually more of an unwanted feature).
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.3...1.2.4))
|
||||
|
||||
## 1.2.3 (2015-07-09)
|
||||
|
||||
### Improvements
|
||||
|
||||
* New option to actively poll the watched folder. This should make it work also
|
||||
if it is mounted on a filesystem that doesn't allow getting notifications
|
||||
about added files through notification by the operating system (e.g.
|
||||
network shares).
|
||||
* Better resilience against senseless temperature/SD-status-polling intervals
|
||||
(such as 0).
|
||||
* Log exceptions during writing to the serial port to `octoprint.log`.
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* [#961](https://github.com/foosel/OctoPrint/pull/961) - Fixed a JavaScript error that caused an error to be logged when "enter" was pressed in file or plugin search.
|
||||
* [#962](https://github.com/foosel/OctoPrint/pull/962) - ``url(...)``s in packed CSS and LESS files should now be rewritten properly too to refer to correct paths
|
||||
* Update notifications were not vanishing properly after updating:
|
||||
* Only use version cache for update notifications if the OctoPrint version still is the same to make sure the cache gets invalidated after an external update of OctoPrint.
|
||||
* Do not persist version information when saving settings of the Software Update plugin
|
||||
* Always delete files from the ``watched`` folder after importing then. Using file preprocessor plugins could lead to the files staying there.
|
||||
* Fixed an encoding problem causing OctoPrint's Plugin Manager and Software Update plugins to choke on UTF-8 characters in the update output.
|
||||
* Fixed sorting by file size in file list
|
||||
* More resilience against missing plugin assets:
|
||||
* Asset existence will now be checked before they get included
|
||||
in the assets to bundle by webassets, logging a warning if a
|
||||
file isn't present.
|
||||
* Monkey-patched webassets filter chain to not die when a file
|
||||
doesn't exist, but to log an error instead and just return
|
||||
an empty file instead.
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.2...1.2.3))
|
||||
|
||||
## 1.2.2 (2015-06-30)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Fixed an admin-only security issue introduced in 1.2.0, updating is strongly advised.
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.1...1.2.2))
|
||||
|
||||
## 1.2.1 (2015-06-30)
|
||||
|
||||
### Improvements
|
||||
|
||||
* More flexibility when interpreting compatibility data from plugin repository. If compatibility information is provided
|
||||
only as a version number it's prefixed with `>=` for the check (so stating a compatibility of only
|
||||
`1.2.0` will now make the plugin compatible to OctoPrint 1.2.0+, not only 1.2.0). Alternatively the compatibility
|
||||
information may now contain stuff like `>=1.2,<1.3` in which case the plugin will only be shown as compatible
|
||||
to OctoPrint versions 1.2.0 and up but not 1.3.0 or anything above that. See also
|
||||
[the requirement specification format of the `pkg_resources` package](https://pythonhosted.org/setuptools/pkg_resources.html#requirements-parsing).
|
||||
* Only print the commands of configured event handlers to the log when a new `debug` flag is present in the config
|
||||
(see [the docs](http://docs.octoprint.org/en/master/configuration/config_yaml.html#events)). Reduces risk of disclosing sensitive data when sharing log files.
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* [#956](https://github.com/foosel/OctoPrint/issues/956) - Fixed server crash when trying to configure a default
|
||||
slicing profile for a still unconfigured slicer.
|
||||
* [#957](https://github.com/foosel/OctoPrint/issues/957) - Increased maximum allowed body size for plugin archive uploads.
|
||||
* Bugs without tickets:
|
||||
* Clean exit on `SIGTERM`, calling the shutdown functions provided by plugins.
|
||||
* Don't disconnect on `volume.init` errors from the firmware.
|
||||
* `touch` uploaded files on local file storage to ensure proper "uploaded date" even for files that are just moved
|
||||
from other locations of the file system (e.g. when being added from the `watched` folder).
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.0...1.2.1))
|
||||
|
||||
## 1.2.0 (2015-06-25)
|
||||
|
||||
### Note for Upgraders
|
||||
|
||||
* The [Cura integration](https://github.com/daid/Cura) has changed in such a way that OctoPrint now calls the
|
||||
[CuraEngine](https://github.com/Ultimaker/CuraEngine) directly instead of depending on the full Cura installation. See
|
||||
[the wiki](https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura) for instructions on how to change your setup to
|
||||
accommodate the new integration.
|
||||
|
||||
### New Features
|
||||
|
||||
* OctoPrint now has a [plugin system](http://docs.octoprint.org/en/master/plugins/index.html) which allows extending its
|
||||
core functionality.
|
||||
* Plugins may be installed through the new and bundled [Plugin Manager Plugin](https://github.com/foosel/OctoPrint/wiki/Plugin:-Plugin-Manager)
|
||||
available in OctoPrint's settings. This Plugin Manager also allows browsing and easy installation of plugins
|
||||
registered on the official [OctoPrint Plugin Repository](http://plugins.octoprint.org).
|
||||
* For interested developers there is a [tutorial available in the documentation](http://docs.octoprint.org/en/master/plugins/gettingstarted.html)
|
||||
and also a [cookiecutter template](https://github.com/OctoPrint/cookiecutter-octoprint-plugin) to quickly bootstrap
|
||||
new plugins.
|
||||
* Added internationalization of UI. Translations of OctoPrint are being crowd sourced via [Transifex](https://www.transifex.com/projects/p/octoprint/).
|
||||
Language Packs for both the core application as well as installed plugins can be uploaded through a new management
|
||||
dialog in Settings > Appearance > Language Packs.
|
||||
dialog in Settings > Appearance > Language Packs. A translation into German is included, further language packs
|
||||
will soon be made available.
|
||||
* Printer Profiles: Printer properties like print volume, extruder offsets etc are now managed via Printer Profiles. A
|
||||
connection to a printer will always have a printer profile associated.
|
||||
* File management now supports STL files as first class citizens (including UI adjustments to allow management of
|
||||
uploaded STL files including removal and reslicing) and also allows folders (not yet supported by UI). STL files
|
||||
can be downloaded like GCODE files.
|
||||
* Slicing has been greatly improved:
|
||||
* It now allows for a definition of slicing profiles to use for slicing plus overrides which can be defined per slicing
|
||||
job (defining overrides is not yet part of the UI but it's on the roadmap).
|
||||
* A new slicing dialog has been added which allows (re-)slicing uploaded STL files (which are now displayed in the file list
|
||||
as well). The slicing profile and printer profile to use can be specified here as well as the file name to which to
|
||||
slice to and the action to take after slicing has been completed (none, selecting the sliced GCODE for printing or
|
||||
starting to print it directly)
|
||||
* The slicing API allows positioning the model to slice on the print bed (Note: this is not yet available in the UI).
|
||||
* Slicers themselves are integrated into the system via ``SlicingPlugins``.
|
||||
* Bundled [Cura Plugin](https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura) allows slicing through CuraEngine up
|
||||
to and including 15.04. Existing Cura slicing profiles can be imported through the web interface.
|
||||
* New file list: Pagination is gone, no more (mobile incompatible) pop overs, instead scrollable and with instant
|
||||
search
|
||||
* You can now define a folder (default: `~/.octoprint/watched`) to be watched for newly added GCODE (or -- if slicing
|
||||
support is enabled -- STL) files to automatically add.
|
||||
* OctoPrint now has a [plugin system](http://docs.octoprint.org/en/devel/plugins/index.html) which allows extending its
|
||||
core functionality. Plugins may be installed through the new Plugin Manager available in OctoPrint's settings. This
|
||||
Plugin Manager also allows browsing and easy installation of plugins registered on the official
|
||||
[OctoPrint Plugin Repository](http://plugins.octoprint.org).
|
||||
* New type of API key: [App Session Keys](http://docs.octoprint.org/en/devel/api/apps.html) for trusted applications
|
||||
* Printer Profiles: Printer properties like print volume, extruder offsets etc are now managed via Printer Profiles. A
|
||||
connection to a printer will always have a printer profile associated.
|
||||
* New type of API key: [App Session Keys](http://docs.octoprint.org/en/master/api/apps.html) for trusted applications
|
||||
* OctoPrint now supports `action:...` commands received via debug messages (`// action:...`) from the printer. Currently supported are
|
||||
- `action:pause`: Pauses the current job in OctoPrint
|
||||
- `action:resume`: Resumes the current job in OctoPrint
|
||||
- `action:disconnect`: Disconnects OctoPrint from the printer
|
||||
Plugins can add supported commands by [hooking](http://docs.octoprint.org/en/devel/plugins/hooks.html) into the
|
||||
Plugins can add supported commands by [hooking](http://docs.octoprint.org/en/master/plugins/hooks.html) into the
|
||||
``octoprint.comm.protocol.action`` hook
|
||||
* Mousing over the webcam image in the control tab enables key control mode, allowing you to quickly move the axis of your
|
||||
printer with your computer's keyboard ([#610](https://github.com/foosel/OctoPrint/pull/610)):
|
||||
- arrow keys: X and Y axes
|
||||
- W, S / PageUp, PageDown: Y axes
|
||||
- W, S / PageUp, PageDown: Z axes
|
||||
- Home: Home X and Y axes
|
||||
- End: Home Z axes
|
||||
- 1, 2, 3, 4: change step size used (0.1, 1, 10, 100mm)
|
||||
@@ -36,9 +306,11 @@
|
||||
* Custom controls now support a row layout
|
||||
* Users can now define custom GCODE scripts to run upon starting/pausing/resuming/success/failure of a print or for
|
||||
custom controls ([#457](https://github.com/foosel/OctoPrint/issues/457), [#347](https://github.com/foosel/OctoPrint/issues/347))
|
||||
* Bundled [Software Update Plugin](https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update) takes care of notifying about new OctoPrint releases and also allows
|
||||
updating if configured as such. Plugins may register themselves with the update notification and application process
|
||||
through a new hook ["octoprint.plugin.softwareupdate.check_config"]().
|
||||
* Bundled [Discovery Plugin](https://github.com/foosel/OctoPrint/wiki/Plugin:-Discovery) allows discovery of OctoPrint
|
||||
instances via SSDP/UPNP and optionally also via ZeroConf/Bonjour/Avahi.
|
||||
* Bundled [Software Update Plugin](https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update) takes care of notifying
|
||||
about new OctoPrint releases and also allows updating if configured as such. Plugins may register themselves with the
|
||||
update notification and application process through a new hook ["octoprint.plugin.softwareupdate.check_config"](https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update#octoprintpluginsoftwareupdatecheck_config).
|
||||
|
||||
### Improvements
|
||||
|
||||
@@ -51,23 +323,7 @@
|
||||
* Better error reporting for timelapse rendering and system commands
|
||||
* Custom control can now be defined so that they show a Confirm dialog with configurable text before executing
|
||||
([#532](https://github.com/foosel/OctoPrint/issues/532) and [#590](https://github.com/foosel/OctoPrint/pull/590))
|
||||
* Slicing has been greatly improved:
|
||||
* It now allows for a definition of slicing profiles to use for slicing plus overrides which can be defined per slicing
|
||||
job (defining overrides is not yet part of the UI but it's on the roadmap).
|
||||
* A new slicing dialog has been added which allows (re-)slicing uploaded STL files (which are now displayed in the file list
|
||||
as well). This dialog also allows specifying which action to take after slicing has been completed (none, selecting the
|
||||
sliced GCODE for printing or starting to print it directly)
|
||||
* Slicers themselves are integrated into the system via ``SlicingPlugins``.
|
||||
* The [Cura integration](https://github.com/daid/Cura) has changed in such a way that OctoPrint now calls the
|
||||
[CuraEngine](https://github.com/Ultimaker/CuraEngine) directly instead of depending on the full Cura installation. See
|
||||
[the wiki](https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura) for instructions on how to change your setup to
|
||||
accommodate the new integration.
|
||||
* The "Slicing done" notification is now colored green ([#558](https://github.com/foosel/OctoPrint/issues/558)).
|
||||
* The slicing API allows positioning the model to slice on the print bed (Note: this is not yet available in the UI).
|
||||
* File management now supports STL files as first class citizens (including UI adjustments to allow management of
|
||||
uploaded STL files including removal and reslicing) and also allows folders (not yet supported by UI). STL files
|
||||
can be downloaded like GCODE files.
|
||||
* Also interpret lines starting with "!!" as errors
|
||||
* Serial communication: Also interpret lines starting with "!!" as errors
|
||||
* Added deletion of pyc files to the `python setup.py clean` command
|
||||
* Settings now show a QRCode for the API Key ([#637](https://github.com/foosel/OctoPrint/pull/637))
|
||||
* Username in UI is no longer enclosed in scare quotes ([#595](https://github.com/foosel/OctoPrint/pull/595))
|
||||
@@ -85,13 +341,14 @@
|
||||
* The server now tracks the modification date of the configuration file and reloads it prior to saving the config if
|
||||
it has been changed during runtime by external editing, hence no config settings added manually while the server
|
||||
was running should be overwritten anymore.
|
||||
* Automatically hard-reload the UI if upon reconnecting to the server a new version is detected.
|
||||
* Display a "Please Reload" overlay when a new server version or a change in installed plugins is detected after a
|
||||
reconnect to the server.
|
||||
* Better handling of errors on the websocket - no more logging of the full stack trace to the log, only a warning
|
||||
message for now.
|
||||
* Daemonized OctoPrint now cleans up its pidfile when receiving a TERM signal ([#711](https://github.com/foosel/OctoPrint/issues/711))
|
||||
* Added serial types for OpenBSD ([#551](https://github.com/foosel/OctoPrint/pull/551))
|
||||
* Improved behaviour of terminal:
|
||||
* Disabling autoscrolling now also stops cutting of the log while it's enabled, effectively preventing log lines from
|
||||
* Disabling autoscrolling now also stops cutting off the log while it's enabled, effectively preventing log lines from
|
||||
being modified at all ([#735](https://github.com/foosel/OctoPrint/issues/735))
|
||||
* Applying filters displays ``[...]`` where lines where removed and doesn't cause scrolling on filtered lines
|
||||
anymore ([#286](https://github.com/foosel/OctoPrint/issues/286))
|
||||
@@ -118,7 +375,6 @@
|
||||
from each other (see also [#823](https://github.com/foosel/OctoPrint/pull/823))
|
||||
* Renamed "Temperature Timeout" and "SD Status Timeout" in Settings to "Temperature Interval" and "SD Status Interval"
|
||||
to better reflect what those values are actually used for.
|
||||
* Better behaviour of the settings dialog on mobile devices.
|
||||
* Added support for rectangular printer beds with the origin in the center ([#682](https://github.com/foosel/OctoPrint/issues/682)
|
||||
and [#852](https://github.com/foosel/OctoPrint/pull/852)). Printer profiles now contain a new settings ``volume.origin``
|
||||
which can either be ``lowerleft`` or ``center``. For circular beds only ``center`` is supported.
|
||||
@@ -130,8 +386,26 @@
|
||||
changed under "Temperatures" in the Settings ([#343](https://github.com/foosel/OctoPrint/issues/343)).
|
||||
* High-DPI support for the GCode viewer ([#837](https://github.com/foosel/OctoPrint/issues/837)).
|
||||
* Stop websocket connections from multiplying ([#888](https://github.com/foosel/OctoPrint/pull/888)).
|
||||
* New setting to rotate webcam by 90° counter clockwise ([#895](https://github.com/foosel/OctoPrint/issues/895) and
|
||||
* New setting to rotate webcam by 90° counter clockwise ([#895](https://github.com/foosel/OctoPrint/issues/895) and
|
||||
[#906](https://github.com/foosel/OctoPrint/pull/906))
|
||||
* System commands now be set to a) run asynchronized by setting their `async` property to `true` and b) to ignore their
|
||||
result by setting their `ignore` property to `true`.
|
||||
* Various improvements of newly introduced features over the course of development:
|
||||
* File management: The new implementation will migrate metadata from the old one upon first startup after upgrade from
|
||||
version 1.1.x to 1.2.x. That should speed up initial startup.
|
||||
* File management: GCODE Analysis backlog processing has been throttled to not take up too many resources on system
|
||||
startup. Freshly uploaded files should still be analyzed at full speed.
|
||||
* Plugins: SettingsPlugins may track versions of configuration format stored in `config.yaml`, including a custom
|
||||
migration method getting called when a mismatch between the currently stored configuration format version and the one
|
||||
reported by the plugin as current is detected.
|
||||
* Plugins: Plugins may now have a folder for plugin related data whose path can be retrieved from the plugin itself
|
||||
via its new method [`get_plugin_data_folder`](http://docs.octoprint.org/en/master/modules/plugin.html#octoprint.plugin.types.OctoPrintPlugin.get_plugin_data_folder).
|
||||
* Plugin Manager: Don't allow plugin management actions (like installing/uninstalling or enabling/disabling) while the
|
||||
printer is printing (see also unreproduced issue [#936](https://github.com/foosel/OctoPrint/issues/936)).
|
||||
* Plugin Manager: More options to try to match up installed plugin packages with discovered plugins.
|
||||
* Plugin Manager: Display a more friendly message if after the installation of a plugin it could not be correctly
|
||||
identifier.
|
||||
* Software Update: Enforce refreshing of available updates after any changes in enabled plugins.
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
@@ -194,6 +468,16 @@
|
||||
* Fixed another instance of a missing `branch` field in version dicts generated by versioneer (compare
|
||||
[#634](https://github.com/foosel/OctoPrint/pull/634)). Caused an issue when installing from source archive
|
||||
downloaded from Github.
|
||||
* [#931](https://github.com/foosel/OctoPrint/issues/931) - Adjusted `octoprint_setuptools` to be compatible to older
|
||||
versions of setuptools potentially site-wide installed on hosts.
|
||||
* [#942](https://github.com/foosel/OctoPrint/issues/942) - Settings can now be saved again after installing a new
|
||||
plugin. Plugins must not use `super` anymore to call parent implementation of `SettingsPlugin.on_settings_save` but
|
||||
should instead switch to `SettingsPlugin.on_settings_save(self, ...)`. Settings API will capture related
|
||||
`TypeErrors` and log a big warning to the log file indicating which plugin caused the problem and needs to be
|
||||
updated. Also updated all bundled plugins accordingly.
|
||||
* Software Update: Don't persist more check data than necessary in the configuration. Solves an issue where persisted
|
||||
information overrode updated check configuration reported by plugins, leading to a "an update is available" loop.
|
||||
An auto-migration function was added that should remove the redundant data.
|
||||
* Various fixes without tickets:
|
||||
* GCODE viewer now doesn't stumble over completely extrusionless GCODE files
|
||||
* Do not deliver the API key on settings API unless user has admin rights
|
||||
@@ -211,7 +495,13 @@
|
||||
"Operational" state.
|
||||
* Log cancelled prints only once (thanks to @imrahil for the headsup)
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.1.2...master))
|
||||
### More information
|
||||
|
||||
* [Commits](https://github.com/foosel/OctoPrint/compare/1.1.2...1.2.0)
|
||||
* Release Candidates:
|
||||
* [RC1](https://github.com/foosel/OctoPrint/releases/tag/1.2.0-rc1)
|
||||
* [RC2](https://github.com/foosel/OctoPrint/releases/tag/1.2.0-rc2)
|
||||
* [RC3](https://github.com/foosel/OctoPrint/releases/tag/1.2.0-rc3)
|
||||
|
||||
## 1.1.2 (2015-03-23)
|
||||
|
||||
|
||||
+8
-6
@@ -21,29 +21,31 @@ Pull Requests
|
||||
plugin. If the current plugin system doesn't allow you to implement your feature as a plugin, create a "Brainstorming"
|
||||
ticket to get the discussion going how best to solve *this* in OctoPrint's plugin system - maybe that's the actual PR
|
||||
you have been waiting for to contribute :)
|
||||
2. If you plan to make **any large changes to the code or appearance, please open a "Brainstorming" ticket first** so that
|
||||
2. If you plan to make **any large changes to the code or appearance, please open a "Brainstorming" ticket first** so that
|
||||
we can determine if it's a good time for your specific pull request. It might be that I'm currently in the process of
|
||||
making heavy changes to the code locations you'd target as well, or your approach doesn't fit the general "project
|
||||
making heavy changes to the code locations you'd target as well, or your approach doesn't fit the general "project
|
||||
vision", and that would just cause unnecessary work and frustration for everyone or possibly get the PR rejected.
|
||||
3. When adding code to OctoPrint, make sure you **follow the current coding style**. That means tabs instead of spaces in the
|
||||
python files (yes, I know that this goes against PEP-8, I don't care) and space instead of tabs in the Javascript sources,
|
||||
english language (that means code, variables, comments!), comments where necessary (tell why the code does something like
|
||||
it does it, structure your code), following the general architecture. If your PR needs to make changes to the Stylesheets,
|
||||
change the ``.less`` files from which the CSS is compiled. PRs that contain direct changes to the compiled
|
||||
CSS will be closed.
|
||||
4. **Test your changes thoroughly**. That also means testing with usage scenarios you don't normally use, e.g. if you only
|
||||
change the ``.less`` files from which the CSS is compiled. PRs that contain direct changes to the compiled
|
||||
CSS will be closed.
|
||||
4. **Test your changes thoroughly**. That also means testing with usage scenarios you don't normally use, e.g. if you only
|
||||
use access control, test without and vice versa. If you only test with your printer, test with the virtual printer and
|
||||
vice versa. State in your pull request how your tested your changes.
|
||||
5. Please create all pull requests **against the `devel` branch**.
|
||||
6. Create **one pull request per feature/bug fix**.
|
||||
7. Create a **custom branch** for your feature/bug fix and use that as base for your pull request. Pull requests directly
|
||||
against your version of `devel` will be closed.
|
||||
7. In your pull request's description, **state what your pull request is doing**, as in, what feature does it implement, what
|
||||
8. In your pull request's description, **state what your pull request is doing**, as in, what feature does it implement, what
|
||||
bug does it fix. The more thoroughly you explain your intent behind the PR here, the higher the chances it will get merged
|
||||
fast.
|
||||
9. Don't forget to **add yourself to the [AUTHORS](../AUTHORS.md) file** :)
|
||||
|
||||
History
|
||||
-------
|
||||
|
||||
* 2015-01-23: More guidelines for creating pull requests, support/questions redirected to Mailinglist/G+ community
|
||||
* 2015-01-27: Added another explicit link to the FAQ
|
||||
* 2015-07-07: Added step to add yourself to AUTHORS when creating a PR :)
|
||||
@@ -1,26 +1,68 @@
|
||||
OctoPrint
|
||||
=========
|
||||
|
||||
[](https://flattr.com/submit/auto?user_id=foosel&url=https://github.com/foosel/OctoPrint&title=OctoPrint&language=&tags=github&category=software)
|
||||
|
||||
OctoPrint provides a responsive web interface for controlling a 3D printer (RepRap, Ultimaker, ...). It is Free Software
|
||||
OctoPrint provides a snappy web interface for controlling a 3D printer (RepRap, Ultimaker, ...). It is Free Software
|
||||
and released under the [GNU Affero General Public License V3](http://www.gnu.org/licenses/agpl.html).
|
||||
|
||||
Its website can be found at [octoprint.org](http://octoprint.org).
|
||||
|
||||
The documentation is located at [docs.octoprint.org](http://docs.octoprint.org).
|
||||
|
||||
The official plugin repository can be reached at [plugins.octoprint.org](http://plugins.octoprint.org).
|
||||
|
||||

|
||||
|
||||
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 [the mailing list](https://groups.google.com/group/octoprint)
|
||||
or the [G+ Community](https://plus.google.com/communities/102771308349328485741) where there are other active users who might be
|
||||
able to help you with any questions you might have.
|
||||
|
||||
Contributing
|
||||
------------
|
||||
|
||||
Please see the project's [Contribution Guidelines](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md).
|
||||
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), support
|
||||
of other users in the [bug tracker](https://github.com/foosel/OctoPrint/issues),
|
||||
[the Mailinglist](https://groups.google.com/group/octoprint) or
|
||||
[the G+ Community](https://plus.google.com/communities/102771308349328485741).
|
||||
|
||||
If you think something is bad as it is about OctoPrint or its documentation the way it is, please help
|
||||
in any way to make it better instead of just complaining about it -- this is an Open Source Project
|
||||
after all :)
|
||||
|
||||
For information about how to go about contributions of any kind, please see the project's
|
||||
[Contribution Guidelines](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md).
|
||||
|
||||
Installation
|
||||
------------
|
||||
|
||||
Installation instructions for installing from source for different operating systems can be found [on the wiki](https://github.com/foosel/OctoPrint/wiki#assorted-guides).
|
||||
Installation instructions for installing from source for different operating
|
||||
systems can be found [on the wiki](https://github.com/foosel/OctoPrint/wiki#assorted-guides).
|
||||
|
||||
If you want to run OctoPrint on a Raspberry Pi you might want to take a look at [OctoPi](https://github.com/guysoft/OctoPi)
|
||||
which is a custom SD card image that includes OctoPrint plus dependencies.
|
||||
|
||||
The generic steps that should basically be done regardless of operating system
|
||||
and runtime environment are the following (as *regular
|
||||
user*, please keep your hands *off* of the `sudo` command here!) - this assumes
|
||||
you already have Python 2.7, pip and virtualenv set up:
|
||||
|
||||
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 --system-site-packages venv`
|
||||
4. Install OctoPrint *into that virtual environment*: `./venv/bin/python setup.py 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. If you want to not only be notified about new
|
||||
releases but also be able to automatically upgrade to them from within
|
||||
OctoPrint, take a look [at the documentation of the Software Update Plugin](https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update#making-octoprint-updateable-on-existing-installations)
|
||||
and at its settings.
|
||||
|
||||
Dependencies
|
||||
------------
|
||||
|
||||
@@ -36,7 +78,11 @@ OctoPrint currently only supports Python 2.7.
|
||||
Usage
|
||||
-----
|
||||
|
||||
Running the `setup.py` script installs the `octoprint` script in your Python installation's scripts folder
|
||||
Running the `setup.py` script via
|
||||
|
||||
python setup.py install
|
||||
|
||||
installs the `octoprint` script in your Python installation's scripts folder
|
||||
(which depending on whether you installed OctoPrint globally or into a virtual env will be on your `PATH` or not). The
|
||||
following usage examples assume that said `octoprint` script is on your `PATH`.
|
||||
|
||||
@@ -77,5 +123,13 @@ which is located at `~/.octoprint` on Linux, at `%APPDATA%/OctoPrint` on Windows
|
||||
at `~/Library/Application Support/OctoPrint` on MacOS.
|
||||
|
||||
A comprehensive overview of all available configuration settings can be found
|
||||
[on the wiki](https://github.com/foosel/OctoPrint/wiki/Configuration). Please note that the most commonly used
|
||||
configuration settings can also easily be edited from OctoPrint's settings dialog.
|
||||
[in the docs](http://docs.octoprint.org/en/master/configuration/config_yaml.html).
|
||||
Please note that the most commonly used configuration settings can also easily
|
||||
be edited from OctoPrint's settings dialog.
|
||||
|
||||
Special Thanks
|
||||
--------------
|
||||
|
||||
The development of OctoPrint is sponsored and maintained by [BQ](http://www.bq.com/).
|
||||
Cross-browser testing services are kindly provided by [BrowserStack](http://www.browserstack.com/).
|
||||
Profiling is done with the help of [PyVmMonitor](http://www.pyvmmonitor.com).
|
||||
+46
-39
@@ -216,6 +216,10 @@ Progress information
|
||||
File related
|
||||
============
|
||||
|
||||
.. todo::
|
||||
|
||||
Update to reflect enhanced data now available.
|
||||
|
||||
.. _sec-api-datamodel-files-file:
|
||||
|
||||
File information
|
||||
@@ -233,10 +237,51 @@ File information
|
||||
- 1
|
||||
- String
|
||||
- The name of the file
|
||||
* - ``type``
|
||||
- 1
|
||||
- String
|
||||
- Type of file. ``model`` or ``machinecode``. Or ``folder`` if it's a folder, in which case the ``children``
|
||||
node will be populated
|
||||
|
||||
Additional properties depend on ``type``. For a ``type`` value of ``folder``, see "Folders". For any other value
|
||||
see "Files".
|
||||
|
||||
Folders
|
||||
'''''''
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``children``
|
||||
- 0..*
|
||||
- Array of :ref:`File information items <sec-api-datamodel-files-file>`
|
||||
- Contained children for entries of type ``folder``
|
||||
|
||||
Files
|
||||
'''''
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``hash``
|
||||
- 1
|
||||
- String
|
||||
- MD5 hash of the file
|
||||
* - ``size``
|
||||
- 0..1
|
||||
- Number
|
||||
- The size of the file in bytes. Only available for ``local`` files.
|
||||
- The size of the file in bytes. Only available for ``local`` files or ``sdcard`` files if the printer
|
||||
supports file sizes for sd card files.
|
||||
* - ``date``
|
||||
- 0..1
|
||||
- Unix timestamp
|
||||
@@ -254,10 +299,6 @@ File information
|
||||
- 0..1
|
||||
- :ref:`GCODE analysis information <sec-api-datamodel-files-gcodeanalysis>`
|
||||
- Information from the analysis of the GCODE file, if available. Left out in abridged version.
|
||||
* - ``prints``
|
||||
- 0..1
|
||||
- :ref:`Print history <sec-api-datamodel-files-prints>`
|
||||
- Information regarding prints of this file, if available. Left out in abridged version.
|
||||
|
||||
.. _sec-api-datamodel-files-gcodeanalysis:
|
||||
|
||||
@@ -290,40 +331,6 @@ GCODE analysis information
|
||||
- The volume of filament used, in cm³
|
||||
|
||||
|
||||
.. _sec-api-datamodel-files-prints:
|
||||
|
||||
Print history
|
||||
-------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``failure``
|
||||
- 1
|
||||
- Number
|
||||
- The number of failed prints on record for the file
|
||||
* - ``success``
|
||||
- 1
|
||||
- Number
|
||||
- The number of successful prints on record for the file
|
||||
* - ``last``
|
||||
- 0..1
|
||||
- Object
|
||||
- Information regarding the last print on record for the file
|
||||
* - ``last.date``
|
||||
- 1
|
||||
- Unix timestamp
|
||||
- Timestamp when this file was printed last
|
||||
* - ``last.success``
|
||||
- 1
|
||||
- Boolean
|
||||
- Whether the last print on record was a success (``true``) or not (``false``)
|
||||
|
||||
.. _sec-api-datamodel-files-ref:
|
||||
|
||||
References
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@ Log file management
|
||||
Retrieve a list of available log files
|
||||
======================================
|
||||
|
||||
.. http:post:: /api/logs
|
||||
.. http:get:: /api/logs
|
||||
|
||||
Retrieve information regarding all log files currently available and regarding the disk space still available
|
||||
in the system on the location the log files are being stored.
|
||||
|
||||
@@ -366,6 +366,27 @@ Use the following settings to add shell/gcode commands to be executed on certain
|
||||
type: gcode
|
||||
enabled: False
|
||||
|
||||
.. note::
|
||||
|
||||
For debugging purposes, you can also add an additional property ``debug`` to your event subscription definitions
|
||||
that if set to true will make the event handler print a log line with your subscription's command after performing
|
||||
all placeholder replacements. Example:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
events:
|
||||
subscriptions:
|
||||
- event: Startup
|
||||
command: "logger 'OctoPrint started up'"
|
||||
type: system
|
||||
debug: true
|
||||
|
||||
This will be logged in OctoPrint's logfile as
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
Executing System Command: logger 'OctoPrint started up'
|
||||
|
||||
.. _sec-configuration-config_yaml-feature:
|
||||
|
||||
Feature
|
||||
@@ -600,7 +621,8 @@ Use the following settings to configure the server:
|
||||
.. code-block:: yaml
|
||||
|
||||
server:
|
||||
# Use this option to define the host to which to bind the server, defaults to "0.0.0.0" (= all interfaces)
|
||||
# Use this option to define the host to which to bind the server, defaults to "0.0.0.0" (= all
|
||||
# interfaces)
|
||||
host: 0.0.0.0
|
||||
|
||||
# Use this option to define the port to which to bind the server, defaults to 5000
|
||||
@@ -670,6 +692,18 @@ Use the following settings to configure the server:
|
||||
# Maximum size of requests other than file uploads in bytes, defaults to 100KB.
|
||||
maxSize: 102400
|
||||
|
||||
# Commands to restart/shutdown octoprint or the system it's running on
|
||||
commands:
|
||||
|
||||
# Command to restart OctoPrint, defaults to being unset
|
||||
serverRestartCommand: sudo service octoprint restart
|
||||
|
||||
# Command to restart the system OctoPrint is running on, defaults to being unset
|
||||
systemRestartCommand: sudo shutdown -r now
|
||||
|
||||
# Command to shut down the system OctoPrint is running on, defaults to being unset
|
||||
systemShutdownCommand: sudo shutdown -h now
|
||||
|
||||
|
||||
.. note::
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ Changing log levels
|
||||
If you need to change the default logging level within OctoPrint, create the file with a text editor of your choice
|
||||
(it's usually not there). The general format is this::
|
||||
|
||||
logger:
|
||||
loggers:
|
||||
<component>:
|
||||
level: <loglevel>
|
||||
|
||||
@@ -27,7 +27,7 @@ new log level to set. An example for increasing the log level of the events and
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
logger:
|
||||
loggers:
|
||||
octoprint.events:
|
||||
level: DEBUG
|
||||
octoprint.filemanager:
|
||||
@@ -97,4 +97,4 @@ expressed in YAML as follows:
|
||||
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||
|
||||
The possible keys for the logging format can be found in the
|
||||
`Python documentation on LogRecord attributes <https://docs.python.org/2/library/logging.html#logrecord-attributes>`_.
|
||||
`Python documentation on LogRecord attributes <https://docs.python.org/2/library/logging.html#logrecord-attributes>`_.
|
||||
@@ -0,0 +1,69 @@
|
||||
.. _sec-features-access_control:
|
||||
|
||||
Access Control
|
||||
==============
|
||||
|
||||
When Access Control is enabled, anonymous users (not logged in) will only see
|
||||
the read-only parts of the UI which are the following:
|
||||
|
||||
* printer state
|
||||
* available gcode files and stats (upload is disabled)
|
||||
* temperature
|
||||
* webcam
|
||||
* gcode viewer
|
||||
* terminal output (sending commands is disabled)
|
||||
* available timelapse movies
|
||||
* any components provided through plugins which are enabled for anonymous
|
||||
users
|
||||
|
||||
Logged in users will get access to everything besides the Settings and System
|
||||
Commands, which are admin-only.
|
||||
|
||||
If Access Control is disabled, everything is directly accessible. **That also
|
||||
includes all administrative functionality as well as full control over the
|
||||
printer!**
|
||||
|
||||
Upon first start a configuration wizard is provided which allows configuration
|
||||
of the first administrator account or alternatively disabling Access Control
|
||||
(which is **NOT** recommended for systems that are directly accessible via the
|
||||
Internet!).
|
||||
|
||||
.. hint::
|
||||
|
||||
If you plan to have your OctoPrint instance accessible over the internet,
|
||||
**always enable Access Control**.
|
||||
|
||||
.. _sec-features-access_control-rerunning_wizard:
|
||||
|
||||
Rerunning the wizard
|
||||
--------------------
|
||||
|
||||
In case Access Control was disabled in the configuration wizard, it is
|
||||
possibly to re-run it by editing ``config.yaml`` [#f1]_ and setting ``firstRun``
|
||||
in the ``server`` section and ``enabled`` in the ``accessControl`` section to
|
||||
``true``:
|
||||
|
||||
.. code-block-ext:: yaml
|
||||
|
||||
accessControl:
|
||||
enabled: true
|
||||
# ...
|
||||
server:
|
||||
firstRun: true
|
||||
|
||||
Then restart the server and connect to the web interface - the wizard should
|
||||
be shown again.
|
||||
|
||||
.. note::
|
||||
|
||||
If user accounts were created prior to disabling Access Control and those
|
||||
user accounts are not to be used any more, remove ``.octoprint/users.yaml``.
|
||||
If you don't remove this file, the above changes won't lead to the
|
||||
configuration being shown again, instead Access Control will just be
|
||||
enabled using the already existing login data. This is to prevent you from
|
||||
resetting access control by accident.
|
||||
|
||||
.. rubric:: Footnotes
|
||||
|
||||
.. [#f1] For Linux that will be ``~/.octoprint/config.yaml``, for Windows it will be ``%APPDATA%/OctoPrint/config.yaml`` and for
|
||||
Mac ``~/Library/Application Support/OctoPrint/config.yaml``
|
||||
@@ -10,7 +10,7 @@ buttons which trigger sending of one or more lines of GCODE to the printer over
|
||||
parameterization of these commands with values entered by the user to full blown GCODE script templates backed by
|
||||
`Jinja2 <http://jinja.pocoo.org/>`_.
|
||||
|
||||
Custom controls are configured within :ref:`config.yaml <sec-configuration-config_yaml>` in a ``controls`` section which
|
||||
Custom controls are configured within :ref:`config.yaml <sec-configuration-config_yaml>` [#f1]_ in a ``controls`` section which
|
||||
basically represents a hierarchical structure of all configured custom controls of various types.
|
||||
|
||||
.. note::
|
||||
@@ -94,6 +94,13 @@ button that sends one or more commands to the printer when clicked, displaying o
|
||||
controls that just serve as *container* for other controls, the latter being identified by having a ``children``
|
||||
attribute wrapping more controls.
|
||||
|
||||
.. hint::
|
||||
|
||||
Take a look at the `Custom Control Editor plugin <http://plugins.octoprint.org/plugins/customControl/>`_
|
||||
which allows you configuring your Custom Controls through OctoPrint's
|
||||
settings interface without the need to manually edit the configuration
|
||||
file.
|
||||
|
||||
.. _sec-features-custom_controls-types:
|
||||
|
||||
Types
|
||||
@@ -278,4 +285,9 @@ Parameterized GCODE Script
|
||||
G28 X0 Y0
|
||||
|
||||
Note the usage of the ``parameters.repetitions`` template variable in the GCODE script template, which will contain
|
||||
the value selected by the user for the "Go arounds" slider.
|
||||
the value selected by the user for the "Go arounds" slider.
|
||||
|
||||
.. rubric:: Footnotes
|
||||
|
||||
.. [#f1] For Linux that will be ``~/.octoprint/config.yaml``, for Windows it will be ``%APPDATA%/OctoPrint/config.yaml`` and for
|
||||
Mac ``~/Library/Application Support/OctoPrint/config.yaml``
|
||||
@@ -7,6 +7,7 @@ Features
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
|
||||
accesscontrol.rst
|
||||
custom_controls.rst
|
||||
gcode_scripts.rst
|
||||
action_commands.rst
|
||||
|
||||
@@ -64,7 +64,7 @@ See :ref:`Developing Plugins <sec-plugins>`.
|
||||
.. rubric:: Footnotes
|
||||
|
||||
.. [#f1] For Linux that will be ``~/.octoprint/plugins``, for Windows it will be ``%APPDATA%/OctoPrint/plugins`` and for
|
||||
Mac ``~/Library/Application Support/OctoPrint``
|
||||
Mac ``~/Library/Application Support/OctoPrint/plugins``
|
||||
.. [#f2] Make sure to use the exact same Python installation for installing the plugin that you also used for
|
||||
installing & running OctoPrint. For OctoPi this means using ``~/oprint/bin/pip`` for installing plugins
|
||||
instead of just ``pip``.
|
||||
@@ -6,6 +6,10 @@ Welcome to OctoPrint's documentation!
|
||||
:alt: The OctoPrint Logo
|
||||
:align: right
|
||||
|
||||
This documentation is still in the process of being migrated from
|
||||
`OctoPrint's wiki <https://github.com/foosel/OctoPrint/wiki>`_, so also take
|
||||
a look there!
|
||||
|
||||
Contents
|
||||
========
|
||||
|
||||
|
||||
@@ -257,7 +257,7 @@ them as (hopefully) documented.
|
||||
:emphasize-lines: 6-8,20
|
||||
:caption: Excerpt from the Growl Plugin showing utilization of the helpers published by the Discovery Plugin.
|
||||
:name: sec-plugin-concepts-helpers-example-usage
|
||||
|
||||
|
||||
def on_after_startup(self):
|
||||
host = self._settings.get(["hostname"])
|
||||
port = self._settings.getInt(["port"])
|
||||
@@ -270,7 +270,7 @@ them as (hopefully) documented.
|
||||
self.growl, _ = self._register_growl(host, port, password=password)
|
||||
|
||||
# ...
|
||||
|
||||
|
||||
def on_api_get(self, request):
|
||||
if not self.zeroconf_browse:
|
||||
return flask.jsonify(dict(
|
||||
@@ -302,6 +302,10 @@ An overview of these properties follows.
|
||||
``self._basefolder``
|
||||
The plugin's base folder where it's installed. Can be used to refer to files relative to the plugin's installation
|
||||
location, e.g. included scripts, templates or assets.
|
||||
``self._datafolder``
|
||||
The plugin's additional data folder path. Can be used to store additional files needed for the plugin's operation (cache,
|
||||
data files etc). Plugins should not access this property directly but instead utilize :func:`~octoprint.plugin.types.OctoPrintPlugin.get_plugin_data_folder`
|
||||
which will make sure the path actually does exist and if not create it before returning it.
|
||||
``self._logger``
|
||||
A `python logger instance <https://docs.python.org/2/library/logging.html>`_ logging to the log target
|
||||
``octoprint.plugin.<plugin identifier>``.
|
||||
@@ -340,4 +344,4 @@ Lifecycle
|
||||
|
||||
.. image:: ../images/plugins_lifecycle.png
|
||||
:align: center
|
||||
:alt: The lifecycle of OctoPrint plugins.
|
||||
:alt: The lifecycle of OctoPrint plugins.
|
||||
+110
-28
@@ -19,7 +19,7 @@ We'll start at the most basic form a plugin can take - just a couple of simple l
|
||||
from __future__ import absolute_import
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_version__ = "1.0"
|
||||
__plugin_version__ = "1.0.0"
|
||||
__plugin_description__ = "A quick \"Hello World\" example plugin for OctoPrint"
|
||||
|
||||
Saving this as ``helloworld.py`` in ``~/.octoprint/plugins`` yields you something resembling these log entries upon server startup::
|
||||
@@ -31,7 +31,7 @@ Saving this as ``helloworld.py`` in ``~/.octoprint/plugins`` yields you somethin
|
||||
2015-01-27 11:14:36,135 - octoprint.plugin.core - INFO - 3 plugin(s) registered with the system:
|
||||
| CuraEngine (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/cura
|
||||
| Discovery (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/discovery
|
||||
| Hello World (1.0) = /home/pi/.octoprint/plugins/helloworld.py
|
||||
| Hello World (1.0.0) = /home/pi/.octoprint/plugins/helloworld.py
|
||||
|
||||
OctoPrint found that plugin in the folder and took a look into it. The name and the version it displays in that log
|
||||
entry it got from the ``__plugin_name__`` and ``__plugin_version__`` lines. It also read the description from
|
||||
@@ -59,7 +59,7 @@ Apart from being discovered by OctoPrint, our plugin does nothing yet. We want t
|
||||
self._logger.info("Hello World!")
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_version__ = "1.0"
|
||||
__plugin_version__ = "1.0.0"
|
||||
__plugin_description__ = "A quick \"Hello World\" example plugin for OctoPrint"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
@@ -95,33 +95,101 @@ as a simple python file following the naming convention ``<plugin identifier>.py
|
||||
that can be done in one file. Distributing multiple files and getting your users to install them in the right way
|
||||
so that OctoPrint will be able to actually find and load them is certainly not impossible, but we want to do it in the
|
||||
best way possible, meaning we want to make our plugin a fully installable python module that your users will be able to
|
||||
install directly via Python's standard package manager ``pip`` or alternatively via `OctoPrint's own plugin manager <https://github.com/OctoPrint/OctoPrint-PluginManager>`_.
|
||||
install directly via `OctoPrint's built-in Plugin Manager <https://github.com/foosel/OctoPrint/wiki/Plugin:-Plugin-Manager>`_
|
||||
or alternatively manually utilizing Python's standard package manager ``pip`` directly.
|
||||
|
||||
So let's begin. First checkout the `Plugin Skeleton <https://github.com/OctoPrint/OctoPrint-PluginSkeleton>`_ and rename
|
||||
the ``octoprint_skeleton`` folder to something better suited to our "Hello World" plugin::
|
||||
So let's begin. We'll use the `cookiecutter <https://github.com/audreyr/cookiecutter>`_ template for OctoPrint plugins here,
|
||||
so we'll first need to install that::
|
||||
|
||||
$ git clone https://github.com/OctoPrint/OctoPrint-PluginSkeleton.git OctoPrint-HelloWorld
|
||||
Cloning into 'OctoPrint-HelloWorld'...
|
||||
[...]
|
||||
$ pip install cookiecutter
|
||||
|
||||
Then we can use the ``cookiecutter`` command to generate a new OctoPrint plugin skeleton for us::
|
||||
|
||||
$ cookiecutter gh:OctoPrint/cookiecutter-octoprint-plugin
|
||||
Cloning into 'cookiecutter-octoprint-plugin'...
|
||||
remote: Counting objects: 70, done.
|
||||
remote: Compressing objects: 100% (17/17), done.
|
||||
emote: Total 70 (delta 0), reused 0 (delta 0), pack-reused 51
|
||||
Unpacking objects: 100% (70/70), done.
|
||||
Checking connectivity... done.
|
||||
plugin_identifier (default is "skeleton")? helloworld
|
||||
plugin_package (default is "octoprint_helloworld")?
|
||||
plugin_name (default is "OctoPrint-Helloworld")?
|
||||
repo_name (default is "OctoPrint-Helloworld")?
|
||||
full_name (default is "You")? Your Name
|
||||
email (default is "you@example.com")? you@somewhere.net
|
||||
github_username (default is "you")? yourGithubName
|
||||
plugin_version (default is "0.1.0")? 1.0.0
|
||||
plugin_description (default is "TODO")? A quick "Hello World" example plugin for OctoPrint
|
||||
plugin_license (default is "AGPLv3")?
|
||||
plugin_homepage (default is "https://github.com/yourGithubName/OctoPrint-Helloworld")?
|
||||
plugin_source (default is "https://github.com/yourGithubName/OctoPrint-Helloworld")?
|
||||
plugin_installurl (default is "https://github.com/yourGithubName/OctoPrint-Helloworld/archive/master.zip")?
|
||||
$ cd OctoPrint-HelloWorld
|
||||
$ mv octoprint_skeleton octoprint_helloworld
|
||||
|
||||
Then edit the configuration in the ``setup.py`` file to mirror our own "Hello World" plugin. The configuration should
|
||||
look something like this:
|
||||
This will create a project structure in the ``OctoPrint-HelloWorld`` folder we just changed to that looks like this::
|
||||
|
||||
extras/
|
||||
README.txt
|
||||
helloworld.md
|
||||
octoprint_helloworld/
|
||||
static/
|
||||
css/
|
||||
README.txt
|
||||
js/
|
||||
README.txt
|
||||
less/
|
||||
README.txt
|
||||
templates/
|
||||
README.txt
|
||||
__init__.py
|
||||
translations/
|
||||
README.txt
|
||||
.editorconfig
|
||||
.gitignore
|
||||
babel.cfg
|
||||
MANIFEST.in
|
||||
README.md
|
||||
requirements.txt
|
||||
setup.py
|
||||
|
||||
While we'll need some of those folders later on, we'll now delete everything that we don't need right now first, that
|
||||
will make it easier to understand what folder does what later on. Delete the following folders and anything in them:
|
||||
|
||||
* ``extras``
|
||||
* ``translations``
|
||||
* ``octoprint_helloworld/static``
|
||||
* ``octoprint_helloworld/templates``
|
||||
|
||||
The final project structure should look like this for now::
|
||||
|
||||
octoprint_helloworld/
|
||||
__init__.py
|
||||
.editorconfig
|
||||
.gitignore
|
||||
babel.cfg
|
||||
MANIFEST.in
|
||||
README.md
|
||||
requirements.txt
|
||||
setup.py
|
||||
|
||||
Out of curiosity, take a look into the ``setup.py`` file. The cookiecutter template should have prefilled all the
|
||||
configuration parameters for you:
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
plugin_identifier = "helloworld"
|
||||
plugin_name = "OctoPrint-HelloWorld"
|
||||
plugin_version = "1.0"
|
||||
plugin_description = "A quick \"Hello World\" example plugin for OctoPrint"
|
||||
plugin_author = "You"
|
||||
plugin_package = "octoprint_helloworld"
|
||||
plugin_name = "OctoPrint-Helloworld"
|
||||
plugin_version = "1.0.0"
|
||||
plugin_description = """A quick "Hello World" example plugin for OctoPrint"""
|
||||
plugin_author = "Your Name"
|
||||
plugin_author_email = "you@somewhere.net"
|
||||
plugin_url = "https://github.com/you/OctoPrint-HelloWorld"
|
||||
plugin_url = "https://github.com/yourGithubName/OctoPrint-Helloworld"
|
||||
plugin_license = "AGPLv3"
|
||||
|
||||
Now all that's left to do is to move our ``helloworld.py`` into the ``octoprint_helloworld`` folder and renaming it to
|
||||
``__init__.py``. Make sure to delete the copy under ``~/.octoprint/plugins`` in the process, including the `.pyc` file!
|
||||
``__init__.py``. Make sure to delete the copy under ``~/.octoprint/plugins`` in the process, including the ``.pyc`` file!
|
||||
|
||||
The plugin is now ready to be installed via ``python setup.py install``. However, since we are still
|
||||
working on our plugin, it makes more sense to use ``python setup.py develop`` for now -- this way the plugin becomes
|
||||
@@ -132,7 +200,7 @@ discoverable by OctoPrint, however we don't have to reinstall it after any chang
|
||||
running egg_info
|
||||
creating OctoPrint_HelloWorld.egg-info
|
||||
[...]
|
||||
Finished processing dependencies for OctoPrint-HelloWorld==1.0
|
||||
Finished processing dependencies for OctoPrint-HelloWorld==1.0.0
|
||||
|
||||
Restart OctoPrint. Your plugin should still be properly discovered and the log line should be printed::
|
||||
|
||||
@@ -143,7 +211,7 @@ Restart OctoPrint. Your plugin should still be properly discovered and the log l
|
||||
2015-01-27 13:43:34,818 - octoprint.plugin.core - INFO - 3 plugin(s) registered with the system:
|
||||
| CuraEngine (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/cura
|
||||
| Discovery (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/discovery
|
||||
| Hello World (1.0) = /home/pi/OctoPrint-HelloWorld/octoprint_helloworld
|
||||
| Hello World (1.0.0) = /home/pi/OctoPrint-HelloWorld/octoprint_helloworld
|
||||
[...]
|
||||
2015-01-27 13:43:38,997 - octoprint.plugins.helloworld - INFO - Hello World!
|
||||
|
||||
@@ -157,7 +225,7 @@ of information now defined twice:
|
||||
:caption: __init__.py
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_version__ = "1.0"
|
||||
__plugin_version__ = "1.0.0"
|
||||
__plugin_description__ = "A quick \"Hello World\" example plugin for OctoPrint"
|
||||
|
||||
.. code-block:: python
|
||||
@@ -165,7 +233,7 @@ of information now defined twice:
|
||||
:caption: setup.py
|
||||
|
||||
plugin_name = "OctoPrint-HelloWorld"
|
||||
plugin_version = "1.0"
|
||||
plugin_version = "1.0.0"
|
||||
plugin_description = "A quick \"Hello World\" example plugin for OctoPrint"
|
||||
|
||||
The nice thing about our plugin now being a proper python package is that OctoPrint can and will access the metadata defined
|
||||
@@ -191,7 +259,7 @@ and restart OctoPrint::
|
||||
2015-01-27 13:46:33,786 - octoprint.plugin.core - INFO - 3 plugin(s) registered with the system:
|
||||
| CuraEngine (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/cura
|
||||
| Discovery (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/discovery
|
||||
| OctoPrint-HelloWorld (1.0) = /home/pi/OctoPrint-HelloWorld/octoprint_helloworld
|
||||
| OctoPrint-HelloWorld (1.0.0) = /home/pi/OctoPrint-HelloWorld/octoprint_helloworld
|
||||
|
||||
Our "Hello World" Plugin still gets detected fine, but it's now listed under the same name it's installed under,
|
||||
"OctoPrint-HelloWorld". That's a bit redundant and squashed, so we'll override that bit via ``__plugin_name__`` again:
|
||||
@@ -218,7 +286,7 @@ Restart OctoPrint again::
|
||||
2015-01-27 13:48:54,122 - octoprint.plugin.core - INFO - 3 plugin(s) registered with the system:
|
||||
| CuraEngine (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/cura
|
||||
| Discovery (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/discovery
|
||||
| Hello World (1.0) = /home/pi/OctoPrint-HelloWorld/octoprint_helloworld
|
||||
| Hello World (1.0.0) = /home/pi/OctoPrint-HelloWorld/octoprint_helloworld
|
||||
|
||||
Much better! You can override pretty much all of the metadata defined within ``setup.py`` from within your Plugin itself --
|
||||
take a look at :ref:`the available control properties <sec-plugin-concepts-controlproperties>` for all available
|
||||
@@ -227,7 +295,7 @@ overrides.
|
||||
Following the README of the `Plugin Skeleton <https://github.com/OctoPrint/OctoPrint-PluginSkeleton>`_ you could now
|
||||
already publish your plugin on Github and it would be directly installable by others using pip::
|
||||
|
||||
pip install https://github.com/you/OctoPrint-HelloWorld/archive/master.zip
|
||||
pip install https://github.com/yourGithubName/OctoPrint-HelloWorld/archive/master.zip
|
||||
|
||||
But let's add some more features instead.
|
||||
|
||||
@@ -275,6 +343,10 @@ Our plugin's directory structure should now look like this::
|
||||
templates/
|
||||
helloworld_navbar.jinja2
|
||||
__init__.py
|
||||
.editorconfig
|
||||
.gitignore
|
||||
babel.cfg
|
||||
MANIFEST.in
|
||||
README.md
|
||||
requirements.txt
|
||||
setup.py
|
||||
@@ -532,6 +604,10 @@ look like this::
|
||||
helloworld_settings.jinja2
|
||||
helloworld_tab.jinja2
|
||||
__init__.py
|
||||
.editorconfig
|
||||
.gitignore
|
||||
babel.cfg
|
||||
MANIFEST.in
|
||||
README.md
|
||||
requirements.txt
|
||||
setup.py
|
||||
@@ -685,11 +761,14 @@ First we'll create a new folder within our plugin's ``static`` folder called ``c
|
||||
helloworld_settings.jinja2
|
||||
helloworld_tab.jinja2
|
||||
__init__.py
|
||||
.editorconfig
|
||||
.gitignore
|
||||
babel.cfg
|
||||
MANIFEST.in
|
||||
README.md
|
||||
requirements.txt
|
||||
setup.py
|
||||
|
||||
|
||||
Put something like the following into ``helloworld.css``:
|
||||
|
||||
.. code-block:: css
|
||||
@@ -794,11 +873,14 @@ in the process. The folder structure of our plugin should now look like this::
|
||||
helloworld_settings.jinja2
|
||||
helloworld_tab.jinja2
|
||||
__init__.py
|
||||
.editorconfig
|
||||
.gitignore
|
||||
babel.cfg
|
||||
MANIFEST.in
|
||||
README.md
|
||||
requirements.txt
|
||||
setup.py
|
||||
|
||||
|
||||
Then adjust our returned assets to include our LESS file as well:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@@ -16,22 +16,23 @@ INSTALL_REQUIRES = [
|
||||
"flask>=0.9,<0.11",
|
||||
"werkzeug==0.8.3",
|
||||
"tornado==4.0.1",
|
||||
"sockjs-tornado>=1.0.0",
|
||||
"sockjs-tornado==1.0.1",
|
||||
"PyYAML==3.10",
|
||||
"Flask-Login==0.2.2",
|
||||
"Flask-Principal==0.3.5",
|
||||
"Flask-Babel==0.9",
|
||||
"Flask-Assets==0.10",
|
||||
"pyserial",
|
||||
"netaddr",
|
||||
"watchdog",
|
||||
"sarge>=0.1.4",
|
||||
"netifaces",
|
||||
"pylru",
|
||||
"rsa",
|
||||
"pkginfo",
|
||||
"requests",
|
||||
"semantic_version"
|
||||
"pyserial==2.7",
|
||||
"netaddr==0.7.17",
|
||||
"watchdog==0.8.3",
|
||||
"sarge==0.1.4",
|
||||
"netifaces==0.10",
|
||||
"pylru==1.0.9",
|
||||
"rsa==3.2",
|
||||
"pkginfo==1.2.1",
|
||||
"requests==2.7.0",
|
||||
"semantic_version==2.4.2",
|
||||
"psutil==3.2.1"
|
||||
]
|
||||
|
||||
# Additional requirements for optional install options
|
||||
|
||||
+20
-13
@@ -74,6 +74,9 @@ class Events(object):
|
||||
# Timelapse
|
||||
CAPTURE_START = "CaptureStart"
|
||||
CAPTURE_DONE = "CaptureDone"
|
||||
CAPTURE_FAILED = "CaptureFailed"
|
||||
POSTROLL_START = "PostRollStart"
|
||||
POSTROLL_END = "PostRollEnd"
|
||||
MOVIE_RENDERING = "MovieRendering"
|
||||
MOVIE_DONE = "MovieDone"
|
||||
MOVIE_FAILED = "MovieFailed"
|
||||
@@ -254,10 +257,11 @@ class CommandTrigger(GenericEventListener):
|
||||
event = subscription["event"]
|
||||
command = subscription["command"]
|
||||
commandType = subscription["type"]
|
||||
debug = subscription["debug"] if "debug" in subscription else False
|
||||
|
||||
if not event in self._subscriptions.keys():
|
||||
self._subscriptions[event] = []
|
||||
self._subscriptions[event].append((command, commandType))
|
||||
self._subscriptions[event].append((command, commandType, debug))
|
||||
|
||||
if not event in eventsToSubscribe:
|
||||
eventsToSubscribe.append(event)
|
||||
@@ -275,7 +279,7 @@ class CommandTrigger(GenericEventListener):
|
||||
if not event in self._subscriptions:
|
||||
return
|
||||
|
||||
for command, commandType in self._subscriptions[event]:
|
||||
for command, commandType, debug in self._subscriptions[event]:
|
||||
try:
|
||||
if isinstance(command, (tuple, list, set)):
|
||||
processedCommand = []
|
||||
@@ -283,19 +287,23 @@ class CommandTrigger(GenericEventListener):
|
||||
processedCommand.append(self._processCommand(c, payload))
|
||||
else:
|
||||
processedCommand = self._processCommand(command, payload)
|
||||
self.executeCommand(processedCommand, commandType)
|
||||
self.executeCommand(processedCommand, commandType, debug=debug)
|
||||
except KeyError, e:
|
||||
self._logger.warn("There was an error processing one or more placeholders in the following command: %s" % command)
|
||||
|
||||
def executeCommand(self, command, commandType):
|
||||
def executeCommand(self, command, commandType, debug=False):
|
||||
if commandType == "system":
|
||||
self._executeSystemCommand(command)
|
||||
self._executeSystemCommand(command, debug=debug)
|
||||
elif commandType == "gcode":
|
||||
self._executeGcodeCommand(command)
|
||||
self._executeGcodeCommand(command, debug=debug)
|
||||
|
||||
def _executeSystemCommand(self, command):
|
||||
def _executeSystemCommand(self, command, debug=False):
|
||||
def commandExecutioner(command):
|
||||
self._logger.info("Executing system command: %s" % command)
|
||||
if debug:
|
||||
self._logger.info("Executing system command: %s" % command)
|
||||
# we run this with shell=True since we have to trust whatever
|
||||
# our admin configured as command and since we want to allow
|
||||
# shell-alike handling here...
|
||||
subprocess.Popen(command, shell=True)
|
||||
|
||||
try:
|
||||
@@ -306,16 +314,15 @@ class CommandTrigger(GenericEventListener):
|
||||
commandExecutioner(command)
|
||||
except subprocess.CalledProcessError, e:
|
||||
self._logger.warn("Command failed with return code %i: %s" % (e.returncode, str(e)))
|
||||
except Exception, ex:
|
||||
except:
|
||||
self._logger.exception("Command failed")
|
||||
|
||||
def _executeGcodeCommand(self, command):
|
||||
def _executeGcodeCommand(self, command, debug=False):
|
||||
commands = [command]
|
||||
if isinstance(command, (list, tuple, set)):
|
||||
self._logger.debug("Executing GCode commands: %r" % command)
|
||||
commands = list(command)
|
||||
else:
|
||||
self._logger.debug("Executing GCode command: %s" % command)
|
||||
if debug:
|
||||
self._logger.info("Executing GCode commands: %r" % command)
|
||||
self._printer.commands(commands)
|
||||
|
||||
def _processCommand(self, command, payload):
|
||||
|
||||
@@ -18,6 +18,11 @@ from .analysis import QueueEntry, AnalysisQueue
|
||||
from .storage import LocalFileStorage
|
||||
from .util import AbstractFileWrapper, StreamWrapper, DiskFileWrapper
|
||||
|
||||
from collections import namedtuple
|
||||
|
||||
ContentTypeMapping = namedtuple("ContentTypeMapping", "extensions, content_type")
|
||||
ContentTypeDetector = namedtuple("ContentTypeDetector", "extensions, detector")
|
||||
|
||||
extensions = dict(
|
||||
)
|
||||
|
||||
@@ -25,11 +30,11 @@ def full_extension_tree():
|
||||
result = dict(
|
||||
# extensions for 3d model files
|
||||
model=dict(
|
||||
stl=["stl"]
|
||||
stl=ContentTypeMapping(["stl"], "application/sla")
|
||||
),
|
||||
# extensions for printable machine code
|
||||
machinecode=dict(
|
||||
gcode=["gcode", "gco", "g"]
|
||||
gcode=ContentTypeMapping(["gcode", "gco", "g"], "text/plain")
|
||||
)
|
||||
)
|
||||
|
||||
@@ -68,8 +73,12 @@ def get_all_extensions(subtree=None):
|
||||
for key, value in subtree.items():
|
||||
if isinstance(value, dict):
|
||||
result += get_all_extensions(value)
|
||||
elif isinstance(value, (ContentTypeMapping, ContentTypeDetector)):
|
||||
result += value.extensions
|
||||
elif isinstance(value, (list, tuple)):
|
||||
result += value
|
||||
elif isinstance(subtree, (ContentTypeMapping, ContentTypeDetector)):
|
||||
result = subtree.extensions
|
||||
elif isinstance(subtree, (list, tuple)):
|
||||
result = subtree
|
||||
return result
|
||||
@@ -79,7 +88,9 @@ def get_path_for_extension(extension, subtree=None):
|
||||
subtree = full_extension_tree()
|
||||
|
||||
for key, value in subtree.items():
|
||||
if isinstance(value, (list, tuple)) and extension in value:
|
||||
if isinstance(value, (ContentTypeMapping, ContentTypeDetector)) and extension in value.extensions:
|
||||
return [key]
|
||||
elif isinstance(value, (list, tuple)) and extension in value:
|
||||
return [key]
|
||||
elif isinstance(value, dict):
|
||||
path = get_path_for_extension(extension, subtree=value)
|
||||
@@ -88,6 +99,23 @@ def get_path_for_extension(extension, subtree=None):
|
||||
|
||||
return None
|
||||
|
||||
def get_content_type_mapping_for_extension(extension, subtree=None):
|
||||
if not subtree:
|
||||
subtree = full_extension_tree()
|
||||
|
||||
for key, value in subtree.items():
|
||||
content_extension_matches = isinstance(value, (ContentTypeMapping, ContentTypeDetector)) and extension in value. extensions
|
||||
list_extension_matches = isinstance(value, (list, tuple)) and extension in value
|
||||
|
||||
if content_extension_matches or list_extension_matches:
|
||||
return value
|
||||
elif isinstance(value, dict):
|
||||
result = get_content_type_mapping_for_extension(extension, subtree=value)
|
||||
if result is not None:
|
||||
return result
|
||||
|
||||
return None
|
||||
|
||||
def valid_extension(extension, type=None):
|
||||
if not type:
|
||||
return extension in get_all_extensions()
|
||||
@@ -106,6 +134,19 @@ def get_file_type(filename):
|
||||
extension = extension[1:].lower()
|
||||
return get_path_for_extension(extension)
|
||||
|
||||
def get_mime_type(filename):
|
||||
_, extension = os.path.splitext(filename)
|
||||
extension = extension[1:].lower()
|
||||
mapping = get_content_type_mapping_for_extension(extension)
|
||||
if mapping:
|
||||
if isinstance(mapping, ContentTypeMapping) and mapping.content_type is not None:
|
||||
return mapping.content_type
|
||||
elif isinstance(mapping, ContentTypeDetector) and callable(mapping.detector):
|
||||
result = mapping.detector(filename)
|
||||
if result is not None:
|
||||
return result
|
||||
return "application/octet-stream"
|
||||
|
||||
|
||||
class NoSuchStorage(Exception):
|
||||
pass
|
||||
@@ -136,8 +177,16 @@ class FileManager(object):
|
||||
|
||||
def initialize(self):
|
||||
self.reload_plugins()
|
||||
for storage_type, storage_manager in self._storage_managers.items():
|
||||
self._determine_analysis_backlog(storage_type, storage_manager)
|
||||
|
||||
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():
|
||||
self._determine_analysis_backlog(storage_type, storage_manager)
|
||||
|
||||
import threading
|
||||
thread = threading.Thread(target=worker)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
def reload_plugins(self):
|
||||
self._progress_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.ProgressPlugin)
|
||||
@@ -147,16 +196,22 @@ class FileManager(object):
|
||||
self._slicing_progress_callbacks.append(callback)
|
||||
|
||||
def unregister_slicingprogress_callback(self, callback):
|
||||
self._slicing_progress_callbacks.remove(callback)
|
||||
try:
|
||||
self._slicing_progress_callbacks.remove(callback)
|
||||
except ValueError:
|
||||
# callback was not registered
|
||||
pass
|
||||
|
||||
def _determine_analysis_backlog(self, storage_type, storage_manager):
|
||||
self._logger.info("Adding backlog items from {storage_type} to analysis queue".format(**locals()))
|
||||
counter = 0
|
||||
for entry, path, printer_profile in storage_manager.analysis_backlog:
|
||||
file_type = get_file_type(path)[-1]
|
||||
|
||||
# we'll use the default printer profile for the backlog since we don't know better
|
||||
queue_entry = QueueEntry(entry, file_type, storage_type, path, self._printer_profile_manager.get_default())
|
||||
self._analysis_queue.enqueue(queue_entry, high_priority=False)
|
||||
counter += 1
|
||||
self._logger.info("Added {counter} items from storage type \"{storage_type}\" to analysis queue".format(**locals()))
|
||||
|
||||
def add_storage(self, storage_type, storage_manager):
|
||||
self._storage_managers[storage_type] = storage_manager
|
||||
@@ -304,7 +359,12 @@ class FileManager(object):
|
||||
printer_profile = self._printer_profile_manager.get_current_or_default()
|
||||
|
||||
for hook in self._preprocessor_hooks.values():
|
||||
hook_file_object = hook(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
|
||||
try:
|
||||
hook_file_object = hook(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
|
||||
except:
|
||||
self._logger.exception("Error when calling preprocessor hook {}, ignoring".format(hook))
|
||||
continue
|
||||
|
||||
if hook_file_object is not None:
|
||||
file_object = hook_file_object
|
||||
file_path = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
|
||||
|
||||
@@ -11,6 +11,7 @@ import Queue as queue
|
||||
import os
|
||||
import threading
|
||||
import collections
|
||||
import time
|
||||
|
||||
from octoprint.events import Events, eventManager
|
||||
|
||||
@@ -100,6 +101,9 @@ class AbstractAnalysisQueue(object):
|
||||
.. automethod:: _do_abort
|
||||
"""
|
||||
|
||||
LOW_PRIO = 0
|
||||
HIGH_PRIO = 100
|
||||
|
||||
def __init__(self, finished_callback):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -133,10 +137,10 @@ class AbstractAnalysisQueue(object):
|
||||
|
||||
if high_priority:
|
||||
self._logger.debug("Adding entry {entry} to analysis queue with high priority".format(entry=entry))
|
||||
prio = 0
|
||||
prio = self.__class__.HIGH_PRIO
|
||||
else:
|
||||
self._logger.debug("Adding entry {entry} to analysis queue with low priority".format(entry=entry))
|
||||
prio = 100
|
||||
prio = self.__class__.LOW_PRIO
|
||||
|
||||
self._queue.put((prio, entry))
|
||||
|
||||
@@ -173,13 +177,15 @@ class AbstractAnalysisQueue(object):
|
||||
self._active.wait()
|
||||
|
||||
try:
|
||||
self._analyze(entry)
|
||||
self._analyze(entry, high_priority=(priority == self.__class__.HIGH_PRIO))
|
||||
self._queue.task_done()
|
||||
except gcodeInterpreter.AnalysisAborted:
|
||||
aborted = entry
|
||||
self._logger.debug("Running analysis of entry {entry} aborted".format(**locals()))
|
||||
else:
|
||||
time.sleep(1.0)
|
||||
|
||||
def _analyze(self, entry):
|
||||
def _analyze(self, entry, high_priority=False):
|
||||
path = entry.absolute_path
|
||||
if path is None or not os.path.exists(path):
|
||||
return
|
||||
@@ -188,20 +194,26 @@ class AbstractAnalysisQueue(object):
|
||||
self._current_progress = 0
|
||||
|
||||
try:
|
||||
self._logger.debug("Starting analysis of {entry}".format(**locals()))
|
||||
self._logger.info("Starting analysis of {entry}".format(**locals()))
|
||||
eventManager().fire(Events.METADATA_ANALYSIS_STARTED, {"file": entry.path, "type": entry.type})
|
||||
result = self._do_analysis()
|
||||
try:
|
||||
result = self._do_analysis(high_priority=high_priority)
|
||||
except TypeError:
|
||||
result = self._do_analysis()
|
||||
self._logger.debug("Analysis of entry {entry} finished, notifying callback".format(**locals()))
|
||||
self._finished_callback(self._current, result)
|
||||
finally:
|
||||
self._current = None
|
||||
self._current_progress = None
|
||||
|
||||
def _do_analysis(self):
|
||||
def _do_analysis(self, high_priority=False):
|
||||
"""
|
||||
Performs the actual analysis of the current entry which can be accessed via ``self._current``. Needs to be
|
||||
overridden by sub classes.
|
||||
|
||||
Arguments:
|
||||
high_priority (bool): Whether the current entry has high priority or not.
|
||||
|
||||
Returns:
|
||||
object: The result of the analysis which will be forwarded to the ``finished_callback`` provided during
|
||||
construction.
|
||||
@@ -235,10 +247,17 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
* The extruded volume in cm³
|
||||
"""
|
||||
|
||||
def _do_analysis(self):
|
||||
def _do_analysis(self, high_priority=False):
|
||||
try:
|
||||
def throttle():
|
||||
time.sleep(0.01)
|
||||
|
||||
throttle_callback = throttle
|
||||
if high_priority:
|
||||
throttle_callback = None
|
||||
|
||||
self._gcode = gcodeInterpreter.gcode()
|
||||
self._gcode.load(self._current.absolute_path, self._current.printer_profile)
|
||||
self._gcode.load(self._current.absolute_path, self._current.printer_profile, throttle=throttle_callback)
|
||||
|
||||
result = dict()
|
||||
if self._gcode.totalMoveTimeMinute:
|
||||
@@ -256,4 +275,4 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
|
||||
def _do_abort(self):
|
||||
if self._gcode:
|
||||
self._gcode.abort()
|
||||
self._gcode.abort()
|
||||
@@ -309,6 +309,41 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
self._metadata_cache = pylru.lrucache(10)
|
||||
|
||||
self._old_metadata = None
|
||||
self._initialize_metadata()
|
||||
|
||||
def _initialize_metadata(self):
|
||||
self._logger.info("Initializing the file metadata for {}...".format(self.basefolder))
|
||||
|
||||
old_metadata_path = os.path.join(self.basefolder, "metadata.yaml")
|
||||
backup_path = os.path.join(self.basefolder, "metadata.yaml.backup")
|
||||
|
||||
if os.path.exists(old_metadata_path):
|
||||
# load the old metadata file
|
||||
try:
|
||||
with open(old_metadata_path) as f:
|
||||
import yaml
|
||||
self._old_metadata = yaml.safe_load(f)
|
||||
except:
|
||||
self._logger.exception("Error while loading old metadata file")
|
||||
|
||||
# make sure the metadata is initialized as far as possible
|
||||
self._list_folder(self.basefolder)
|
||||
|
||||
# rename the old metadata file
|
||||
self._old_metadata = None
|
||||
try:
|
||||
import shutil
|
||||
shutil.move(old_metadata_path, backup_path)
|
||||
except:
|
||||
self._logger.exception("Could not rename old metadata.yaml file")
|
||||
|
||||
else:
|
||||
# make sure the metadata is initialized as far as possible
|
||||
self._list_folder(self.basefolder)
|
||||
|
||||
self._logger.info("... file metadata for {} initialized successfully.".format(self.basefolder))
|
||||
|
||||
@property
|
||||
def analysis_backlog(self):
|
||||
for entry in self._analysis_backlog_generator():
|
||||
@@ -420,6 +455,9 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
self._add_links(name, path, links)
|
||||
|
||||
# touch the file to set last access and modification time to now
|
||||
os.utime(file_path, None)
|
||||
|
||||
return self.path_in_storage((path, name))
|
||||
|
||||
def remove_file(self, path):
|
||||
@@ -919,12 +957,7 @@ class LocalFileStorage(StorageInterface):
|
||||
if entry in metadata and isinstance(metadata[entry], dict):
|
||||
entry_data = metadata[entry]
|
||||
else:
|
||||
entry_data = dict(
|
||||
hash=self._create_hash(entry_path),
|
||||
links=[],
|
||||
notes=[]
|
||||
)
|
||||
metadata[entry] = entry_data
|
||||
entry_data = self._add_basic_metadata(path, entry, save=False, metadata=metadata)
|
||||
metadata_dirty = True
|
||||
|
||||
# TODO extract model hash from source if possible to recreate link
|
||||
@@ -959,6 +992,31 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
return result
|
||||
|
||||
def _add_basic_metadata(self, path, entry, additional_metadata=None, save=True, metadata=None):
|
||||
if additional_metadata is None:
|
||||
additional_metadata = dict()
|
||||
|
||||
if metadata is None:
|
||||
metadata = self._get_metadata(path)
|
||||
|
||||
entry_data = dict(
|
||||
hash=self._create_hash(os.path.join(path, entry)),
|
||||
links=[],
|
||||
notes=[]
|
||||
)
|
||||
|
||||
if path == self.basefolder and self._old_metadata is not None and entry in self._old_metadata and "gcodeAnalysis" in self._old_metadata[entry]:
|
||||
# if there is still old metadata available and that contains an analysis for this file, use it!
|
||||
entry_data["analysis"] = self._old_metadata[entry]["gcodeAnalysis"]
|
||||
|
||||
entry_data.update(additional_metadata)
|
||||
metadata[entry] = entry_data
|
||||
|
||||
if save:
|
||||
self._save_metadata(path, metadata)
|
||||
|
||||
return entry_data
|
||||
|
||||
def _create_hash(self, path):
|
||||
import hashlib
|
||||
|
||||
@@ -993,16 +1051,22 @@ class LocalFileStorage(StorageInterface):
|
||||
def _save_metadata(self, path, metadata):
|
||||
metadata_path = os.path.join(path, ".metadata.yaml")
|
||||
|
||||
fh, metadata_temporary_path = tempfile.mkstemp()
|
||||
os.close(fh)
|
||||
|
||||
with self._metadata_lock:
|
||||
try:
|
||||
with open(metadata_temporary_path, "w") as f:
|
||||
import yaml
|
||||
yaml.safe_dump(metadata, stream=f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
import yaml
|
||||
import shutil
|
||||
shutil.move(metadata_temporary_path, metadata_path)
|
||||
|
||||
file_obj = tempfile.NamedTemporaryFile(delete=False)
|
||||
try:
|
||||
yaml.safe_dump(metadata, stream=file_obj, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
file_obj.close()
|
||||
shutil.move(file_obj.name, metadata_path)
|
||||
finally:
|
||||
try:
|
||||
if os.path.exists(file_obj.name):
|
||||
os.remove(file_obj.name)
|
||||
except Exception as e:
|
||||
self._logger.warn("Could not delete file {}: {}".format(file_obj.name, str(e)))
|
||||
except:
|
||||
self._logger.exception("Error while writing .metadata.yaml to {path}".format(**locals()))
|
||||
else:
|
||||
|
||||
@@ -7,6 +7,8 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
|
||||
|
||||
import io
|
||||
|
||||
from octoprint.util import atomic_write
|
||||
|
||||
class AbstractFileWrapper(object):
|
||||
"""
|
||||
Wrapper for file representations to save to storages.
|
||||
@@ -85,7 +87,7 @@ class StreamWrapper(AbstractFileWrapper):
|
||||
"""
|
||||
import shutil
|
||||
|
||||
with open(path, "wb") as dest:
|
||||
with atomic_write(path, "wb") as dest:
|
||||
with self.stream() as source:
|
||||
shutil.copyfileobj(source, dest)
|
||||
|
||||
|
||||
@@ -281,6 +281,7 @@ class PluginSettings(object):
|
||||
defaults = dict()
|
||||
self.defaults = dict(plugins=dict())
|
||||
self.defaults["plugins"][plugin_key] = defaults
|
||||
self.defaults["plugins"][plugin_key]["_config_version"] = None
|
||||
|
||||
if get_preprocessors is None:
|
||||
get_preprocessors = dict()
|
||||
@@ -309,11 +310,17 @@ class PluginSettings(object):
|
||||
return result
|
||||
|
||||
def add_getter_kwargs(kwargs):
|
||||
kwargs.update(defaults=self.defaults, preprocessors=self.get_preprocessors)
|
||||
if not "defaults" in kwargs:
|
||||
kwargs.update(defaults=self.defaults)
|
||||
if not "preprocessors" in kwargs:
|
||||
kwargs.update(preprocessors=self.get_preprocessors)
|
||||
return kwargs
|
||||
|
||||
def add_setter_kwargs(kwargs):
|
||||
kwargs.update(defaults=self.defaults, preprocessors=self.set_preprocessors)
|
||||
if not "defaults" in kwargs:
|
||||
kwargs.update(defaults=self.defaults)
|
||||
if not "preprocessors" in kwargs:
|
||||
kwargs.update(preprocessors=self.set_preprocessors)
|
||||
return kwargs
|
||||
|
||||
self.access_methods = dict(
|
||||
@@ -419,6 +426,15 @@ class PluginSettings(object):
|
||||
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 __getattr__(self, item):
|
||||
all_access_methods = self.access_methods.keys() + self.deprecated_access_methods.keys()
|
||||
if item in all_access_methods:
|
||||
|
||||
@@ -428,7 +428,9 @@ class PluginManager(object):
|
||||
It is able to discover plugins both through possible file system locations as well as customizable entry points.
|
||||
"""
|
||||
|
||||
def __init__(self, plugin_folders, plugin_types, plugin_entry_points, logging_prefix=None, plugin_disabled_list=None, plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None):
|
||||
def __init__(self, plugin_folders, plugin_types, plugin_entry_points, logging_prefix=None,
|
||||
plugin_disabled_list=None, plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None,
|
||||
plugin_validators=None):
|
||||
self.logger = logging.getLogger(__name__)
|
||||
|
||||
if logging_prefix is None:
|
||||
@@ -453,6 +455,8 @@ class PluginManager(object):
|
||||
|
||||
self.implementation_injects = dict()
|
||||
self.implementation_inject_factories = []
|
||||
self.implementation_pre_inits = []
|
||||
self.implementation_post_inits = []
|
||||
|
||||
self.on_plugin_loaded = lambda *args, **kwargs: None
|
||||
self.on_plugin_unloaded = lambda *args, **kwargs: None
|
||||
@@ -849,27 +853,35 @@ class PluginManager(object):
|
||||
return False
|
||||
return hook in self.plugin_obsolete_hooks
|
||||
|
||||
def initialize_implementations(self, additional_injects=None, additional_inject_factories=None):
|
||||
def initialize_implementations(self, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None):
|
||||
for name, plugin in self.enabled_plugins.items():
|
||||
self.initialize_implementation_of_plugin(name, plugin,
|
||||
additional_injects=additional_injects,
|
||||
additional_inject_factories=additional_inject_factories)
|
||||
additional_inject_factories=additional_inject_factories,
|
||||
additional_pre_inits=additional_pre_inits,
|
||||
additional_post_inits=additional_post_inits)
|
||||
|
||||
self.logger.info("Initialized {count} plugin(s)".format(count=len(self.plugin_implementations)))
|
||||
self.logger.info("Initialized {count} plugin implementation(s)".format(count=len(self.plugin_implementations)))
|
||||
|
||||
def initialize_implementation_of_plugin(self, name, plugin, additional_injects=None, additional_inject_factories=None):
|
||||
def initialize_implementation_of_plugin(self, name, plugin, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None):
|
||||
if plugin.implementation is None:
|
||||
return
|
||||
|
||||
return self.initialize_implementation(name, plugin, plugin.implementation,
|
||||
additional_injects=additional_injects,
|
||||
additional_inject_factories=additional_inject_factories)
|
||||
additional_inject_factories=additional_inject_factories,
|
||||
additional_pre_inits=additional_pre_inits,
|
||||
additional_post_inits=additional_post_inits)
|
||||
|
||||
def initialize_implementation(self, name, plugin, implementation, additional_injects=None, additional_inject_factories=None):
|
||||
def initialize_implementation(self, name, plugin, implementation, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None):
|
||||
if additional_injects is None:
|
||||
additional_injects = dict()
|
||||
if additional_inject_factories is None:
|
||||
additional_inject_factories = []
|
||||
if additional_pre_inits is None:
|
||||
additional_pre_inits = []
|
||||
if additional_post_inits is None:
|
||||
additional_post_inits = []
|
||||
|
||||
injects = self.implementation_injects
|
||||
injects.update(additional_injects)
|
||||
@@ -877,6 +889,12 @@ class PluginManager(object):
|
||||
inject_factories = self.implementation_inject_factories
|
||||
inject_factories += additional_inject_factories
|
||||
|
||||
pre_inits = self.implementation_pre_inits
|
||||
pre_inits += additional_pre_inits
|
||||
|
||||
post_inits = self.implementation_post_inits
|
||||
post_inits += additional_post_inits
|
||||
|
||||
try:
|
||||
kwargs = dict(injects)
|
||||
|
||||
@@ -904,8 +922,16 @@ class PluginManager(object):
|
||||
for arg, value in return_value.items():
|
||||
setattr(implementation, "_" + arg, value)
|
||||
|
||||
# execute any additional pre init methods
|
||||
for pre_init in pre_inits:
|
||||
pre_init(name, implementation)
|
||||
|
||||
implementation.initialize()
|
||||
|
||||
# execute any additional post init methods
|
||||
for post_init in post_inits:
|
||||
post_init(name, implementation)
|
||||
|
||||
except Exception as e:
|
||||
self._deactivate_plugin(name, plugin)
|
||||
plugin.enabled = False
|
||||
@@ -929,15 +955,13 @@ class PluginManager(object):
|
||||
self.logger.info("No plugins available")
|
||||
else:
|
||||
self.logger.info("{count} plugin(s) registered with the system:\n{plugins}".format(count=len(all_plugins), plugins="\n".join(
|
||||
sorted(
|
||||
map(lambda x: "| " + x.long_str(show_bundled=show_bundled,
|
||||
bundled_strs=bundled_str,
|
||||
show_location=show_location,
|
||||
location_str=location_str,
|
||||
show_enabled=show_enabled,
|
||||
enabled_strs=enabled_str),
|
||||
self.enabled_plugins.values())
|
||||
)
|
||||
map(lambda x: "| " + x.long_str(show_bundled=show_bundled,
|
||||
bundled_strs=bundled_str,
|
||||
show_location=show_location,
|
||||
location_str=location_str,
|
||||
show_enabled=show_enabled,
|
||||
enabled_strs=enabled_str),
|
||||
sorted(self.plugins.values(), key=lambda x: str(x).lower()))
|
||||
)))
|
||||
|
||||
def get_plugin(self, identifier, require_enabled=True):
|
||||
@@ -1187,15 +1211,15 @@ class Plugin(object):
|
||||
class RestartNeedingPlugin(Plugin):
|
||||
pass
|
||||
|
||||
class PluginNeedsRestart(BaseException):
|
||||
class PluginNeedsRestart(Exception):
|
||||
def __init__(self, name):
|
||||
super(BaseException, self).__init__()
|
||||
Exception.__init__(self)
|
||||
self.name = name
|
||||
self.message = "Plugin {name} cannot be enabled or disabled after system startup".format(**locals())
|
||||
|
||||
class PluginLifecycleException(BaseException):
|
||||
class PluginLifecycleException(Exception):
|
||||
def __init__(self, name, reason, message):
|
||||
super(BaseException, self).__init__()
|
||||
Exception.__init__(self)
|
||||
self.name = name
|
||||
self.reason = reason
|
||||
|
||||
@@ -1206,7 +1230,7 @@ class PluginLifecycleException(BaseException):
|
||||
|
||||
class PluginCantInitialize(PluginLifecycleException):
|
||||
def __init__(self, name, reason):
|
||||
super(PluginLifecycleException, self).__init__(name, reason, "Plugin {name} cannot be initialized: {reason}")
|
||||
PluginLifecycleException.__init__(self, name, reason, "Plugin {name} cannot be initialized: {reason}")
|
||||
|
||||
class PluginCantEnable(PluginLifecycleException):
|
||||
def __init__(self, name, reason):
|
||||
@@ -1214,4 +1238,4 @@ class PluginCantEnable(PluginLifecycleException):
|
||||
|
||||
class PluginCantDisable(PluginLifecycleException):
|
||||
def __init__(self, name, reason):
|
||||
super(PluginLifecycleException, self).__init__(name, reason, "Plugin {name} cannot be disabled: {reason}")
|
||||
PluginLifecycleException.__init__(self, name, reason, "Plugin {name} cannot be disabled: {reason}")
|
||||
@@ -69,9 +69,32 @@ class OctoPrintPlugin(Plugin):
|
||||
|
||||
The :class:`~octoprint.server.LifecycleManager` instance. Injected by the plugin core system upon initialization
|
||||
of the implementation.
|
||||
|
||||
.. attribute:: _data_folder
|
||||
|
||||
Path to the data folder for the plugin to use for any data it might have to persist. Should always be accessed
|
||||
through :meth:`get_plugin_data_folder` since that function will also ensure that the data folder actually exists
|
||||
and if not creating it before returning it. Injected by the plugin core system upon initialization of the
|
||||
implementation.
|
||||
|
||||
.. automethod:: get_plugin_data_folder
|
||||
"""
|
||||
|
||||
pass
|
||||
def get_plugin_data_folder(self):
|
||||
"""
|
||||
Retrieves the path to a data folder specifically for the plugin, ensuring it exists and if not creating it
|
||||
before returning it.
|
||||
|
||||
Plugins may use this folder for storing additional data they need for their operation.
|
||||
"""
|
||||
if self._data_folder is None:
|
||||
raise RuntimeError("self._plugin_data_folder is None, has the plugin been initialized yet?")
|
||||
|
||||
import os
|
||||
if not os.path.isdir(self._data_folder):
|
||||
os.makedirs(self._data_folder)
|
||||
return self._data_folder
|
||||
|
||||
|
||||
class ReloadNeedingPlugin(Plugin):
|
||||
pass
|
||||
@@ -718,7 +741,7 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
def on_settings_save(self, data):
|
||||
old_flag = self._settings.get_boolean(["sub", "some_flag"])
|
||||
|
||||
super(MySettingsPlugin, self).on_settings_save(data)
|
||||
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
|
||||
|
||||
new_flag = self._settings.get_boolean(["sub", "some_flag"])
|
||||
if old_flag != new_flag:
|
||||
@@ -758,7 +781,10 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
|
||||
:return: the current settings of the plugin, as a dictionary
|
||||
"""
|
||||
return self._settings.get([], asdict=True, merged=True)
|
||||
data = self._settings.get([], asdict=True, merged=True)
|
||||
if "_config_version" in data:
|
||||
del data["_config_version"]
|
||||
return data
|
||||
|
||||
def on_settings_save(self, data):
|
||||
"""
|
||||
@@ -780,9 +806,12 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
"""
|
||||
import octoprint.util
|
||||
|
||||
if "_config_version" in data:
|
||||
del data["_config_version"]
|
||||
|
||||
current = self._settings.get([], asdict=True, merged=True)
|
||||
data = octoprint.util.dict_merge(current, data)
|
||||
self._settings.set([], data)
|
||||
merged = octoprint.util.dict_merge(current, data)
|
||||
self._settings.set([], merged)
|
||||
|
||||
def get_settings_defaults(self):
|
||||
"""
|
||||
@@ -830,6 +859,50 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
"""
|
||||
return dict(), dict()
|
||||
|
||||
def get_settings_version(self):
|
||||
"""
|
||||
Retrieves the settings format version of the plugin.
|
||||
|
||||
Use this to have OctoPrint trigger your migration function if it detects an outdated settings version in
|
||||
config.yaml.
|
||||
|
||||
Returns:
|
||||
int or None: an int signifying the current settings format, should be incremented by plugins whenever there
|
||||
are backwards incompatible changes. Returning None here disables the version tracking for the
|
||||
plugin's configuration.
|
||||
"""
|
||||
return None
|
||||
|
||||
def on_settings_migrate(self, target, current):
|
||||
"""
|
||||
Called by OctoPrint if it detects that the installed version of the plugin necessitates a higher settings version
|
||||
than the one currently stored in _config.yaml. Will also be called if the settings data stored in config.yaml
|
||||
doesn't have version information, in which case the ``current`` parameter will be None.
|
||||
|
||||
Your plugin's implementation should take care of migrating any data by utilizing self._settings. OctoPrint
|
||||
will take care of saving any changes to disk by calling `self._settings.save()` after returning from this method.
|
||||
|
||||
This method will be called before your plugin's :func:`on_settings_initialized` method, with all injections already
|
||||
having taken place. You can therefore depend on the configuration having been migrated by the time
|
||||
:func:`on_settings_initialized` is called.
|
||||
|
||||
Arguments:
|
||||
target (int): The settings format version the plugin requires, this should always be the same value as
|
||||
returned by :func:`get_settings_version`.
|
||||
current (int or None): The settings format version as currently stored in config.yaml. May be None if
|
||||
no version information can be found.
|
||||
"""
|
||||
pass
|
||||
|
||||
def on_settings_initialized(self):
|
||||
"""
|
||||
Called after the settings have been initialized and - if necessary - also been migrated through a call to
|
||||
func:`on_settings_migrate`.
|
||||
|
||||
This method will always be called after the `initialize` method.
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class EventHandlerPlugin(OctoPrintPlugin):
|
||||
"""
|
||||
|
||||
@@ -35,6 +35,14 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
self._cancelled_jobs = []
|
||||
self._job_mutex = threading.Lock()
|
||||
|
||||
##~~ TemplatePlugin API
|
||||
|
||||
def get_template_configs(self):
|
||||
from flask.ext.babel import gettext
|
||||
return [
|
||||
dict(type="settings", name=gettext("CuraEngine"))
|
||||
]
|
||||
|
||||
##~~ StartupPlugin API
|
||||
|
||||
def on_startup(self, host, port):
|
||||
@@ -129,7 +137,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
def on_settings_save(self, data):
|
||||
old_debug_logging = self._settings.get_boolean(["debug_logging"])
|
||||
|
||||
super(CuraPlugin, self).on_settings_save(data)
|
||||
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
|
||||
|
||||
new_debug_logging = self._settings.get_boolean(["debug_logging"])
|
||||
if old_debug_logging != new_debug_logging:
|
||||
@@ -218,7 +226,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
if not on_progress_kwargs:
|
||||
on_progress_kwargs = dict()
|
||||
|
||||
self._cura_logger.info("### Slicing %s to %s using profile stored at %s" % (model_path, machinecode_path, profile_path))
|
||||
self._cura_logger.info(u"### Slicing %s to %s using profile stored at %s" % (model_path, machinecode_path, profile_path))
|
||||
|
||||
engine_settings = self._convert_to_engine(profile_path, printer_profile, posX, posY)
|
||||
|
||||
@@ -227,16 +235,15 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
return False, "Path to CuraEngine is not configured "
|
||||
|
||||
working_dir, _ = os.path.split(executable)
|
||||
args = ['"%s"' % executable, '-v', '-p']
|
||||
args = [executable, '-v', '-p']
|
||||
for k, v in engine_settings.items():
|
||||
args += ["-s", '"%s=%s"' % (k, str(v))]
|
||||
args += ['-o', '"%s"' % machinecode_path, '"%s"' % model_path]
|
||||
args += ["-s", "%s=%s" % (k, str(v))]
|
||||
args += ["-o", machinecode_path, model_path]
|
||||
|
||||
self._logger.info(u"Running %r in %s" % (" ".join(args), working_dir))
|
||||
|
||||
import sarge
|
||||
command = " ".join(args)
|
||||
self._logger.info("Running %r in %s" % (command, working_dir))
|
||||
|
||||
p = sarge.run(command, cwd=working_dir, async=True, stdout=sarge.Capture(), stderr=sarge.Capture())
|
||||
p = sarge.run(args, cwd=working_dir, async=True, stdout=sarge.Capture(), stderr=sarge.Capture())
|
||||
p.wait_events()
|
||||
self._slicing_commands[machinecode_path] = p.commands[0]
|
||||
|
||||
@@ -254,6 +261,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
p.commands[0].poll()
|
||||
continue
|
||||
|
||||
line = octoprint.util.to_unicode(line, errors="replace")
|
||||
self._cura_logger.debug(line.strip())
|
||||
|
||||
if on_progress is not None:
|
||||
@@ -282,14 +290,14 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
#
|
||||
# with <step_factor> being 0 for "inset", 1 for "skin" and 2 for "export".
|
||||
|
||||
if line.startswith("Layer count:") and layer_count is None:
|
||||
if line.startswith(u"Layer count:") and layer_count is None:
|
||||
try:
|
||||
layer_count = float(line[len("Layer count:"):].strip())
|
||||
layer_count = float(line[len(u"Layer count:"):].strip())
|
||||
except:
|
||||
pass
|
||||
|
||||
elif line.startswith("Progress:"):
|
||||
split_line = line[len("Progress:"):].strip().split(":")
|
||||
elif line.startswith(u"Progress:"):
|
||||
split_line = line[len(u"Progress:"):].strip().split(":")
|
||||
if len(split_line) == 3:
|
||||
step, current_layer, _ = split_line
|
||||
try:
|
||||
@@ -302,21 +310,21 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
on_progress_kwargs["_progress"] = (step_factor[step] * layer_count + current_layer) / (layer_count * 3)
|
||||
on_progress(*on_progress_args, **on_progress_kwargs)
|
||||
|
||||
elif line.startswith("Print time:"):
|
||||
elif line.startswith(u"Print time:"):
|
||||
try:
|
||||
print_time = int(line[len("Print time:"):].strip())
|
||||
print_time = int(line[len(u"Print time:"):].strip())
|
||||
if analysis is None:
|
||||
analysis = dict()
|
||||
analysis["estimatedPrintTime"] = print_time
|
||||
except:
|
||||
pass
|
||||
|
||||
elif line.startswith("Filament:") or line.startswith("Filament2:"):
|
||||
if line.startswith("Filament:"):
|
||||
filament_str = line[len("Filament:"):].strip()
|
||||
elif line.startswith(u"Filament:") or line.startswith(u"Filament2:"):
|
||||
if line.startswith(u"Filament:"):
|
||||
filament_str = line[len(u"Filament:"):].strip()
|
||||
tool_key = "tool0"
|
||||
else:
|
||||
filament_str = line[len("Filament2:"):].strip()
|
||||
filament_str = line[len(u"Filament2:"):].strip()
|
||||
tool_key = "tool1"
|
||||
|
||||
try:
|
||||
@@ -339,20 +347,20 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
|
||||
with self._job_mutex:
|
||||
if machinecode_path in self._cancelled_jobs:
|
||||
self._cura_logger.info("### Cancelled")
|
||||
self._cura_logger.info(u"### Cancelled")
|
||||
raise octoprint.slicing.SlicingCancelled()
|
||||
|
||||
self._cura_logger.info("### Finished, returncode %d" % p.returncode)
|
||||
self._cura_logger.info(u"### Finished, returncode %d" % p.returncode)
|
||||
if p.returncode == 0:
|
||||
return True, dict(analysis=analysis)
|
||||
else:
|
||||
self._logger.warn("Could not slice via Cura, got return code %r" % p.returncode)
|
||||
self._logger.warn(u"Could not slice via Cura, got return code %r" % p.returncode)
|
||||
return False, "Got returncode %r" % p.returncode
|
||||
|
||||
except octoprint.slicing.SlicingCancelled as e:
|
||||
raise e
|
||||
except:
|
||||
self._logger.exception("Could not slice via Cura, got an unknown error")
|
||||
self._logger.exception(u"Could not slice via Cura, got an unknown error")
|
||||
return False, "Unknown error, please consult the log file"
|
||||
|
||||
finally:
|
||||
@@ -371,7 +379,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
command = self._slicing_commands[machinecode_path]
|
||||
if command is not None:
|
||||
command.terminate()
|
||||
self._logger.info("Cancelled slicing of %s" % machinecode_path)
|
||||
self._logger.info(u"Cancelled slicing of %s" % machinecode_path)
|
||||
|
||||
def _load_profile(self, path):
|
||||
import yaml
|
||||
@@ -385,7 +393,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
|
||||
def _save_profile(self, path, profile, allow_overwrite=True):
|
||||
import yaml
|
||||
with open(path, "wb") as f:
|
||||
with octoprint.util.atomic_write(path, "wb") as f:
|
||||
yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
|
||||
def _convert_to_engine(self, profile_path, printer_profile, posX, posY):
|
||||
@@ -410,4 +418,4 @@ __plugin_author__ = "Gina Häußge"
|
||||
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura"
|
||||
__plugin_description__ = "Adds support for slicing via CuraEngine from within OctoPrint"
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_implementation__ = CuraPlugin()
|
||||
__plugin_implementation__ = CuraPlugin()
|
||||
@@ -12,6 +12,7 @@ import octoprint.plugin.core
|
||||
from octoprint.settings import valid_boolean_trues
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
from octoprint.server import admin_permission
|
||||
from octoprint.util.pip import PipCaller, UnknownPip
|
||||
|
||||
from flask import jsonify, make_response
|
||||
from flask.ext.babel import gettext
|
||||
@@ -21,6 +22,8 @@ import sarge
|
||||
import sys
|
||||
import requests
|
||||
import re
|
||||
import os
|
||||
import pkg_resources
|
||||
|
||||
class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
@@ -35,11 +38,29 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._pending_install = set()
|
||||
self._pending_uninstall = set()
|
||||
|
||||
self._pip_caller = None
|
||||
self._pip_version_dependency_links = pkg_resources.parse_version("1.5")
|
||||
|
||||
self._repository_available = False
|
||||
self._repository_plugins = []
|
||||
self._repository_cache_path = None
|
||||
self._repository_cache_ttl = 0
|
||||
|
||||
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._pip_caller = PipCaller(configured=self._settings.get(["pip"]))
|
||||
self._pip_caller.on_log_call = self._log_call
|
||||
self._pip_caller.on_log_stdout = self._log_stdout
|
||||
self._pip_caller.on_log_stderr = self._log_stderr
|
||||
|
||||
##~~ Body size hook
|
||||
|
||||
def increase_upload_bodysize(self, current_max_body_sizes, *args, **kwargs):
|
||||
# set a maximum body size of 50 MB for plugin archive uploads
|
||||
return [("POST", r"/upload_archive", 50 * 1024 * 1024)]
|
||||
|
||||
##~~ StartupPlugin
|
||||
|
||||
@@ -52,16 +73,33 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._console_logger.setLevel(logging.DEBUG)
|
||||
self._console_logger.propagate = False
|
||||
|
||||
self._repository_available = self._refresh_repository()
|
||||
self._repository_available = self._fetch_repository_from_disk()
|
||||
|
||||
##~~ SettingsPlugin
|
||||
|
||||
def get_settings_defaults(self):
|
||||
return dict(
|
||||
repository="http://plugins.octoprint.org/plugins.json",
|
||||
pip=None
|
||||
repository_ttl=24*60,
|
||||
pip=None,
|
||||
pip_args=None,
|
||||
dependency_links=False,
|
||||
hidden=[]
|
||||
)
|
||||
|
||||
def on_settings_save(self, data):
|
||||
old_pip = self._settings.get(["pip"])
|
||||
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
|
||||
new_pip = self._settings.get(["pip"])
|
||||
|
||||
self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60
|
||||
if old_pip != new_pip:
|
||||
self._pip_caller.configured = new_pip
|
||||
try:
|
||||
self._pip_caller.trigger_refresh()
|
||||
except:
|
||||
self._pip_caller
|
||||
|
||||
##~~ AssetPlugin
|
||||
|
||||
def get_assets(self):
|
||||
@@ -95,11 +133,17 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
upload_path = flask.request.values[input_upload_path]
|
||||
upload_name = flask.request.values[input_upload_name]
|
||||
|
||||
exts = filter(lambda x: upload_name.lower().endswith(x), (".zip", ".tar.gz", ".tgz", ".tar"))
|
||||
if not len(exts):
|
||||
return flask.make_response("File doesn't have a valid extension for a plugin archive", 400)
|
||||
|
||||
ext = exts[0]
|
||||
|
||||
import tempfile
|
||||
import shutil
|
||||
import os
|
||||
|
||||
archive = tempfile.NamedTemporaryFile(delete=False, suffix="-{upload_name}".format(**locals()))
|
||||
archive = tempfile.NamedTemporaryFile(delete=False, suffix="{ext}".format(**locals()))
|
||||
try:
|
||||
archive.close()
|
||||
shutil.copy(upload_path, archive.name)
|
||||
@@ -132,18 +176,38 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
result.append(self._to_external_representation(plugin))
|
||||
|
||||
if "refresh_repository" in request.values and request.values["refresh_repository"] in valid_boolean_trues:
|
||||
self._refresh_repository()
|
||||
self._repository_available = self._refresh_repository()
|
||||
|
||||
return jsonify(plugins=result, repository=dict(available=self._repository_available, plugins=self._repository_plugins), os=self._get_os(), octoprint=self._get_octoprint_version())
|
||||
return jsonify(plugins=result,
|
||||
repository=dict(
|
||||
available=self._repository_available,
|
||||
plugins=self._repository_plugins
|
||||
),
|
||||
os=self._get_os(),
|
||||
octoprint=self._get_octoprint_version(),
|
||||
pip=dict(
|
||||
available=self._pip_caller.available,
|
||||
command=self._pip_caller.command,
|
||||
version=self._pip_caller.version_string,
|
||||
use_sudo=self._pip_caller.use_sudo,
|
||||
additional_args=self._settings.get(["pip_args"])
|
||||
))
|
||||
|
||||
def on_api_command(self, command, data):
|
||||
if not admin_permission.can():
|
||||
return make_response("Insufficient rights", 403)
|
||||
|
||||
if self._printer.is_printing() or self._printer.is_paused():
|
||||
# do not update while a print job is running
|
||||
return make_response("Printer is currently printing or paused", 409)
|
||||
|
||||
if command == "install":
|
||||
url = data["url"]
|
||||
plugin_name = data["plugin"] if "plugin" in data else None
|
||||
return self.command_install(url=url, force="force" in data and data["force"] in valid_boolean_trues, reinstall=plugin_name)
|
||||
return self.command_install(url=url,
|
||||
force="force" in data and data["force"] in valid_boolean_trues,
|
||||
dependency_links="dependency_links" in data and data["dependency_links"] in valid_boolean_trues,
|
||||
reinstall=plugin_name)
|
||||
|
||||
elif command == "uninstall":
|
||||
plugin_name = data["plugin"]
|
||||
@@ -161,18 +225,17 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
plugin = self._plugin_manager.plugins[plugin_name]
|
||||
return self.command_toggle(plugin, command)
|
||||
|
||||
elif command == "refresh_repository":
|
||||
self._repository_available = self._refresh_repository()
|
||||
return jsonify(repository=dict(available=self._repository_available, plugins=self._repository_plugins))
|
||||
|
||||
def command_install(self, url=None, path=None, force=False, reinstall=None):
|
||||
def command_install(self, url=None, path=None, force=False, reinstall=None, dependency_links=False):
|
||||
if url is not None:
|
||||
pip_args = ["install", sarge.shell_quote(url)]
|
||||
elif path is not None:
|
||||
pip_args = ["install", path]
|
||||
pip_args = ["install", sarge.shell_quote(path)]
|
||||
else:
|
||||
raise ValueError("Either url or path must be provided")
|
||||
|
||||
if dependency_links or self._settings.get_boolean(["dependency_links"]):
|
||||
pip_args.append("--process-dependency-links")
|
||||
|
||||
all_plugins_before = self._plugin_manager.find_plugins()
|
||||
|
||||
success_string = "Successfully installed"
|
||||
@@ -234,12 +297,31 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
package_name = plugin.origin.package_name
|
||||
package_version = plugin.origin.package_version
|
||||
versioned_package = "{package_name}-{package_version}".format(**locals())
|
||||
|
||||
if package_name in installed or versioned_package in installed:
|
||||
# exact match, we are done here
|
||||
new_plugin_key = key
|
||||
new_plugin = plugin
|
||||
break
|
||||
|
||||
else:
|
||||
# it might still be a version that got stripped by python's package resources, e.g. 1.4.5a0 => 1.4.5a
|
||||
found = False
|
||||
|
||||
for inst in installed:
|
||||
if inst.startswith(versioned_package):
|
||||
found = True
|
||||
break
|
||||
|
||||
if found:
|
||||
new_plugin_key = key
|
||||
new_plugin = plugin
|
||||
break
|
||||
else:
|
||||
return make_response("Could not find plugin that was installed", 500)
|
||||
self._logger.warn("The plugin was installed successfully, but couldn't be found afterwards to initialize properly during runtime. Please restart OctoPrint.")
|
||||
result = dict(result=True, url=url, needs_restart=True, needs_refresh=True, was_reinstalled=False, plugin="unknown")
|
||||
self._send_result_notification("install", result)
|
||||
return jsonify(result)
|
||||
|
||||
self._plugin_manager.mark_plugin(new_plugin_key, uninstalled=False)
|
||||
self._plugin_manager.reload_plugins()
|
||||
@@ -360,80 +442,31 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._plugin_manager.send_plugin_message(self._identifier, notification)
|
||||
|
||||
def _call_pip(self, args):
|
||||
pip_command = self._settings.get(["pip"])
|
||||
if pip_command is None:
|
||||
import os
|
||||
python_command = sys.executable
|
||||
binary_dir = os.path.dirname(python_command)
|
||||
if self._pip_caller is None or not self._pip_caller.available:
|
||||
raise RuntimeError(u"No pip available, can't operate".format(**locals()))
|
||||
|
||||
pip_command = os.path.join(binary_dir, "pip")
|
||||
if sys.platform == "win32":
|
||||
# Windows is a bit special... first of all the file will be called pip.exe, not just pip, and secondly
|
||||
# for a non-virtualenv install (e.g. global install) the pip binary will not be located in the
|
||||
# same folder as python.exe, but in a subfolder Scripts, e.g.
|
||||
#
|
||||
# C:\Python2.7\
|
||||
# |- python.exe
|
||||
# `- Scripts
|
||||
# `- pip.exe
|
||||
if "--process-dependency-links" in args:
|
||||
self._log_message(u"Installation needs to process external dependencies, that might make it take a bit longer than usual depending on the pip version")
|
||||
if self._pip_caller < self._pip_version_dependency_links:
|
||||
args.remove("--process-dependency-links")
|
||||
|
||||
# virtual env?
|
||||
pip_command = os.path.join(binary_dir, "pip.exe")
|
||||
additional_args = self._settings.get(["pip_args"])
|
||||
if additional_args:
|
||||
args.append(additional_args)
|
||||
|
||||
if not os.path.isfile(pip_command):
|
||||
# nope, let's try the Scripts folder then
|
||||
scripts_dir = os.path.join(binary_dir, "Scripts")
|
||||
if os.path.isdir(scripts_dir):
|
||||
pip_command = os.path.join(scripts_dir, "pip.exe")
|
||||
return self._pip_caller.execute(*args)
|
||||
|
||||
if not os.path.isfile(pip_command) or not os.access(pip_command, os.X_OK):
|
||||
raise RuntimeError(u"No pip path configured and {pip_command} does not exist or is not executable, can't install".format(**locals()))
|
||||
def _log_message(self, *lines):
|
||||
self._log(lines, prefix=u"*", stream="message")
|
||||
|
||||
command = [pip_command] + args
|
||||
|
||||
self._logger.debug(u"Calling: {}".format(" ".join(command)))
|
||||
|
||||
p = sarge.run(" ".join(command), shell=True, async=True, stdout=sarge.Capture(), stderr=sarge.Capture())
|
||||
p.wait_events()
|
||||
|
||||
all_stdout = []
|
||||
all_stderr = []
|
||||
try:
|
||||
while p.returncode is None:
|
||||
line = p.stderr.readline(timeout=0.5)
|
||||
if line:
|
||||
self._log_stderr(line)
|
||||
all_stderr.append(line)
|
||||
|
||||
line = p.stdout.readline(timeout=0.5)
|
||||
if line:
|
||||
self._log_stdout(line)
|
||||
all_stdout.append(line)
|
||||
|
||||
p.commands[0].poll()
|
||||
|
||||
finally:
|
||||
p.close()
|
||||
|
||||
stderr = p.stderr.text
|
||||
if stderr:
|
||||
split_lines = stderr.split("\n")
|
||||
self._log_stderr(*split_lines)
|
||||
all_stderr += split_lines
|
||||
|
||||
stdout = p.stdout.text
|
||||
if stdout:
|
||||
split_lines = stdout.split("\n")
|
||||
self._log_stdout(*split_lines)
|
||||
all_stdout += split_lines
|
||||
|
||||
return p.returncode, all_stdout, all_stderr
|
||||
def _log_call(self, *lines):
|
||||
self._log(lines, prefix=u" ", stream="call")
|
||||
|
||||
def _log_stdout(self, *lines):
|
||||
self._log(lines, prefix=">", stream="stdout")
|
||||
self._log(lines, prefix=u">", stream="stdout")
|
||||
|
||||
def _log_stderr(self, *lines):
|
||||
self._log(lines, prefix="!", stream="stderr")
|
||||
self._log(lines, prefix=u"!", stream="stderr")
|
||||
|
||||
def _log(self, lines, prefix=None, stream=None, strip=True):
|
||||
if strip:
|
||||
@@ -473,14 +506,48 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
elif plugin.enabled and plugin.key not in self._pending_disable:
|
||||
self._pending_disable.add(plugin.key)
|
||||
|
||||
def _refresh_repository(self):
|
||||
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:
|
||||
try:
|
||||
import json
|
||||
with open(self._repository_cache_path) as f:
|
||||
repo_data = json.load(f)
|
||||
self._logger.info("Loaded plugin repository data from disk, was still valid")
|
||||
except:
|
||||
self._logger.exception("Error while loading repository data from {}".format(self._repository_cache_path))
|
||||
|
||||
return self._refresh_repository(repo_data=repo_data)
|
||||
|
||||
def _fetch_repository_from_url(self):
|
||||
import requests
|
||||
repository_url = self._settings.get(["repository"])
|
||||
try:
|
||||
r = requests.get(repository_url)
|
||||
self._logger.info("Loaded plugin repository data from {}".format(repository_url))
|
||||
except Exception as e:
|
||||
self._logger.warn("Could not fetch plugins from repository at {repository_url}: {message}".format(repository_url=repository_url, message=str(e)))
|
||||
return False
|
||||
self._logger.exception("Could not fetch plugins from repository at {repository_url}: {message}".format(repository_url=repository_url, message=str(e)))
|
||||
return None
|
||||
|
||||
repo_data = r.json()
|
||||
|
||||
try:
|
||||
import json
|
||||
with octoprint.util.atomic_write(self._repository_cache_path, "wb") as f:
|
||||
json.dump(repo_data, f)
|
||||
except Exception as e:
|
||||
self._logger.exception("Error while saving repository data to {}: {}".format(self._repository_cache_path, str(e)))
|
||||
|
||||
return repo_data
|
||||
|
||||
def _refresh_repository(self, repo_data=None):
|
||||
if repo_data is None:
|
||||
repo_data = self._fetch_repository_from_url()
|
||||
if repo_data is None:
|
||||
return False
|
||||
|
||||
current_os = self._get_os()
|
||||
octoprint_version = self._get_octoprint_version()
|
||||
@@ -489,29 +556,51 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
def map_repository_entry(entry):
|
||||
result = dict(entry)
|
||||
|
||||
if not "follow_dependency_links" in result:
|
||||
result["follow_dependency_links"] = False
|
||||
|
||||
result["is_compatible"] = dict(
|
||||
octoprint=True,
|
||||
os=True
|
||||
)
|
||||
|
||||
if "compatibility" in entry:
|
||||
if "octoprint" in entry["compatibility"]:
|
||||
import semantic_version
|
||||
for octo_compat in entry["compatibility"]["octoprint"]:
|
||||
s = semantic_version.Spec("=={}".format(octo_compat))
|
||||
if semantic_version.Version(octoprint_version) in s:
|
||||
break
|
||||
else:
|
||||
result["is_compatible"]["octoprint"] = False
|
||||
if "octoprint" in entry["compatibility"] and entry["compatibility"]["octoprint"] is not None and len(entry["compatibility"]["octoprint"]):
|
||||
result["is_compatible"]["octoprint"] = self._is_octoprint_compatible(octoprint_version, entry["compatibility"]["octoprint"])
|
||||
|
||||
if "os" in entry["compatibility"]:
|
||||
result["is_compatible"]["os"] = current_os in entry["compatibility"]["os"]
|
||||
if "os" in entry["compatibility"] and entry["compatibility"]["os"] is not None and len(entry["compatibility"]["os"]):
|
||||
result["is_compatible"]["os"] = self._is_os_compatible(current_os, entry["compatibility"]["os"])
|
||||
|
||||
return result
|
||||
|
||||
self._repository_plugins = map(map_repository_entry, r.json())
|
||||
self._repository_plugins = map(map_repository_entry, repo_data)
|
||||
return True
|
||||
|
||||
def _is_octoprint_compatible(self, octoprint_version_string, compatibility_entries):
|
||||
"""
|
||||
Tests if the current ``octoprint_version`` is compatible to any of the provided ``compatibility_entries``.
|
||||
"""
|
||||
|
||||
octoprint_version = pkg_resources.parse_version(octoprint_version_string)
|
||||
for octo_compat in compatibility_entries:
|
||||
if not any(octo_compat.startswith(c) for c in ("<", "<=", "!=", "==", ">=", ">", "~=", "===")):
|
||||
octo_compat = ">={}".format(octo_compat)
|
||||
|
||||
s = next(pkg_resources.parse_requirements("OctoPrint" + octo_compat))
|
||||
if octoprint_version in s:
|
||||
break
|
||||
else:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def _is_os_compatible(self, current_os, compatibility_entries):
|
||||
"""
|
||||
Tests if the ``current_os`` matches any of the provided ``compatibility_entries``.
|
||||
"""
|
||||
return current_os in compatibility_entries
|
||||
|
||||
def _get_os(self):
|
||||
if sys.platform == "win32":
|
||||
return "windows"
|
||||
@@ -540,7 +629,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
pending_enable=(not plugin.enabled and plugin.key in self._pending_enable),
|
||||
pending_disable=(plugin.enabled and plugin.key in self._pending_disable),
|
||||
pending_install=(plugin.key in self._pending_install),
|
||||
pending_uninstall=(plugin.key in self._pending_uninstall)
|
||||
pending_uninstall=(plugin.key in self._pending_uninstall),
|
||||
origin=plugin.origin.type
|
||||
)
|
||||
|
||||
__plugin_name__ = "Plugin Manager"
|
||||
@@ -548,4 +638,12 @@ __plugin_author__ = "Gina Häußge"
|
||||
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Plugin-Manager"
|
||||
__plugin_description__ = "Allows installing and managing OctoPrint plugins"
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_implementation__ = PluginManagerPlugin()
|
||||
|
||||
def __plugin_load__():
|
||||
global __plugin_implementation__
|
||||
__plugin_implementation__ = PluginManagerPlugin()
|
||||
|
||||
global __plugin_hooks__
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.server.http.bodysize": __plugin_implementation__.increase_upload_bodysize
|
||||
}
|
||||
@@ -1 +1 @@
|
||||
table th.settings_plugin_plugin_manager_plugins_name,table td.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}table th.settings_plugin_plugin_manager_plugins_actions,table td.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}table th.settings_plugin_plugin_manager_plugins_actions a,table td.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}table th.settings_plugin_plugin_manager_plugins_actions a.disabled,table td.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog .slimScrollDiv{margin-bottom:20px}#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;padding-right:10px;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_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_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{overflow:hidden;width:auto;height:300px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px;padding-right:10px}
|
||||
table th.settings_plugin_plugin_manager_plugins_name,table td.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}table th.settings_plugin_plugin_manager_plugins_actions,table td.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}table th.settings_plugin_plugin_manager_plugins_actions a,table td.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}table th.settings_plugin_plugin_manager_plugins_actions a.disabled,table td.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog .slimScrollDiv{margin-bottom:20px}#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;padding-right:10px;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_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_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{overflow:hidden;width:auto;height:300px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px;padding-right:10px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:bold}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
|
||||
@@ -4,6 +4,14 @@ $(function() {
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.settingsViewModel = parameters[1];
|
||||
self.printerState = parameters[2];
|
||||
|
||||
self.config_repositoryUrl = ko.observable();
|
||||
self.config_repositoryTtl = ko.observable();
|
||||
self.config_pipCommand = ko.observable();
|
||||
self.config_pipAdditionalArgs = ko.observable();
|
||||
|
||||
self.configurationDialog = $("#settings_plugin_pluginmanager_configurationdialog");
|
||||
|
||||
self.plugins = new ItemListHelper(
|
||||
"plugin.pluginmanager.installedplugins",
|
||||
@@ -69,11 +77,39 @@ $(function() {
|
||||
self.loglines = ko.observableArray([]);
|
||||
self.installedPlugins = ko.observableArray([]);
|
||||
|
||||
self.followDependencyLinks = ko.observable(false);
|
||||
|
||||
self.pipAvailable = ko.observable(false);
|
||||
self.pipCommand = ko.observable();
|
||||
self.pipVersion = ko.observable();
|
||||
self.pipUseSudo = ko.observable();
|
||||
self.pipAdditionalArgs = ko.observable();
|
||||
|
||||
self.working = ko.observable(false);
|
||||
self.workingTitle = ko.observable();
|
||||
self.workingDialog = undefined;
|
||||
self.workingOutput = undefined;
|
||||
|
||||
self.enableManagement = ko.computed(function() {
|
||||
return !self.printerState.isPrinting();
|
||||
});
|
||||
|
||||
self.enableToggle = function(data) {
|
||||
return self.enableManagement() && data.key != 'pluginmanager';
|
||||
};
|
||||
|
||||
self.enableUninstall = function(data) {
|
||||
return self.enableManagement()
|
||||
&& (data.origin != "entry_point" || self.pipAvailable())
|
||||
&& !data.bundled
|
||||
&& data.key != 'pluginmanager'
|
||||
&& !data.pending_uninstall;
|
||||
};
|
||||
|
||||
self.enableRepoInstall = function(data) {
|
||||
return self.enableManagement() && self.pipAvailable() && self.isCompatible(data);
|
||||
};
|
||||
|
||||
self.invalidUrl = ko.computed(function() {
|
||||
var url = self.installUrl();
|
||||
return url !== undefined && url.trim() != "" && !(_.startsWith(url.toLocaleLowerCase(), "http://") || _.startsWith(url.toLocaleLowerCase(), "https://"));
|
||||
@@ -81,7 +117,7 @@ $(function() {
|
||||
|
||||
self.enableUrlInstall = ko.computed(function() {
|
||||
var url = self.installUrl();
|
||||
return url !== undefined && url.trim() != "" && !self.invalidUrl();
|
||||
return self.enableManagement() && self.pipAvailable() && url !== undefined && url.trim() != "" && !self.invalidUrl();
|
||||
});
|
||||
|
||||
self.invalidArchive = ko.computed(function() {
|
||||
@@ -91,7 +127,7 @@ $(function() {
|
||||
|
||||
self.enableArchiveInstall = ko.computed(function() {
|
||||
var name = self.uploadFilename();
|
||||
return name !== undefined && name.trim() != "" && !self.invalidArchive();
|
||||
return self.enableManagement() && self.pipAvailable() && name !== undefined && name.trim() != "" && !self.invalidArchive();
|
||||
});
|
||||
|
||||
self.uploadElement.fileupload({
|
||||
@@ -108,6 +144,9 @@ $(function() {
|
||||
self.uploadButton.unbind("click");
|
||||
self.uploadButton.bind("click", function() {
|
||||
self._markWorking(gettext("Installing plugin..."), gettext("Installing plugin from uploaded archive..."));
|
||||
data.formData = {
|
||||
dependency_links: self.followDependencyLinks()
|
||||
};
|
||||
data.submit();
|
||||
return false;
|
||||
});
|
||||
@@ -133,17 +172,20 @@ $(function() {
|
||||
self.performRepositorySearch = function() {
|
||||
var query = self.repositorySearchQuery();
|
||||
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);
|
||||
});
|
||||
} else {
|
||||
self.repositoryplugins.resetSearch();
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
self.fromResponse = function(data) {
|
||||
self._fromPluginsResponse(data.plugins);
|
||||
self._fromRepositoryResponse(data.repository)
|
||||
self._fromRepositoryResponse(data.repository);
|
||||
self._fromPipResponse(data.pip);
|
||||
};
|
||||
|
||||
self._fromPluginsResponse = function(data) {
|
||||
@@ -164,6 +206,21 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self._fromPipResponse = function(data) {
|
||||
self.pipAvailable(data.available);
|
||||
if (data.available) {
|
||||
self.pipCommand(data.command);
|
||||
self.pipVersion(data.version);
|
||||
self.pipUseSudo(data.use_sudo);
|
||||
self.pipAdditionalArgs(data.additional_args);
|
||||
} else {
|
||||
self.pipCommand(undefined);
|
||||
self.pipVersion(undefined);
|
||||
self.pipUseSudo(undefined);
|
||||
self.pipAdditionalArgs(undefined);
|
||||
}
|
||||
};
|
||||
|
||||
self.requestData = function(includeRepo) {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
return;
|
||||
@@ -182,6 +239,10 @@ $(function() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!self.enableManagement()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.key == "pluginmanager") return;
|
||||
|
||||
var command = self._getToggleCommand(data);
|
||||
@@ -212,23 +273,35 @@ $(function() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!self.enableManagement()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (self.installed(data)) {
|
||||
self.installPlugin(data.archive, data.title, data.id);
|
||||
self.installPlugin(data.archive, data.title, data.id, data.follow_dependency_links || self.followDependencyLinks());
|
||||
} else {
|
||||
self.installPlugin(data.archive, data.title);
|
||||
self.installPlugin(data.archive, data.title, undefined, data.follow_dependency_links || self.followDependencyLinks());
|
||||
}
|
||||
};
|
||||
|
||||
self.installPlugin = function(url, name, reinstall) {
|
||||
self.installPlugin = function(url, name, reinstall, followDependencyLinks) {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!self.enableManagement()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (url === undefined) {
|
||||
url = self.installUrl();
|
||||
}
|
||||
if (!url) return;
|
||||
|
||||
if (followDependencyLinks === undefined) {
|
||||
followDependencyLinks = self.followDependencyLinks();
|
||||
}
|
||||
|
||||
var workTitle, workText;
|
||||
if (!reinstall) {
|
||||
workTitle = gettext("Installing plugin...");
|
||||
@@ -244,7 +317,7 @@ $(function() {
|
||||
self._markWorking(workTitle, workText);
|
||||
|
||||
var command = "install";
|
||||
var payload = {url: url};
|
||||
var payload = {url: url, dependency_links: followDependencyLinks};
|
||||
if (reinstall) {
|
||||
payload["plugin"] = reinstall;
|
||||
payload["force"] = true;
|
||||
@@ -270,6 +343,10 @@ $(function() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!self.enableManagement()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.bundled) return;
|
||||
if (data.key == "pluginmanager") return;
|
||||
|
||||
@@ -296,9 +373,59 @@ $(function() {
|
||||
return;
|
||||
}
|
||||
|
||||
self._postCommand("refresh_repository", {}, function(data) {
|
||||
self._fromRepositoryResponse(data.repository);
|
||||
})
|
||||
self.requestData(true);
|
||||
};
|
||||
|
||||
self.showPluginSettings = function() {
|
||||
self._copyConfig();
|
||||
self.configurationDialog.modal();
|
||||
};
|
||||
|
||||
self.savePluginSettings = function() {
|
||||
var pipCommand = self.config_pipCommand();
|
||||
if (pipCommand != undefined && pipCommand.trim() == "") {
|
||||
pipCommand = null;
|
||||
}
|
||||
|
||||
var repository = self.config_repositoryUrl();
|
||||
if (repository != undefined && repository.trim() == "") {
|
||||
repository = null;
|
||||
}
|
||||
|
||||
var repositoryTtl;
|
||||
try {
|
||||
repositoryTtl = parseInt(self.config_repositoryTtl());
|
||||
} catch (ex) {
|
||||
repositoryTtl = null;
|
||||
}
|
||||
|
||||
var pipArgs = self.config_pipAdditionalArgs();
|
||||
if (pipArgs != undefined && pipArgs.trim() == "") {
|
||||
pipArgs = null;
|
||||
}
|
||||
|
||||
var data = {
|
||||
plugins: {
|
||||
pluginmanager: {
|
||||
repository: repository,
|
||||
repository_ttl: repositoryTtl,
|
||||
pip: pipCommand,
|
||||
pip_args: pipArgs
|
||||
}
|
||||
}
|
||||
};
|
||||
self.settingsViewModel.saveData(data, function() {
|
||||
self.configurationDialog.modal("hide");
|
||||
self._copyConfig();
|
||||
self.refreshRepository();
|
||||
});
|
||||
};
|
||||
|
||||
self._copyConfig = function() {
|
||||
self.config_repositoryUrl(self.settingsViewModel.settings.plugins.pluginmanager.repository());
|
||||
self.config_repositoryTtl(self.settingsViewModel.settings.plugins.pluginmanager.repository_ttl());
|
||||
self.config_pipCommand(self.settingsViewModel.settings.plugins.pluginmanager.pip());
|
||||
self.config_pipAdditionalArgs(self.settingsViewModel.settings.plugins.pluginmanager.pip_args());
|
||||
};
|
||||
|
||||
self.installed = function(data) {
|
||||
@@ -411,7 +538,7 @@ $(function() {
|
||||
|
||||
self.toggleButtonCss = function(data) {
|
||||
var icon = self._getToggleCommand(data) == "enable" ? "icon-circle-blank" : "icon-circle";
|
||||
var disabled = (data.key == "pluginmanager") ? " disabled" : "";
|
||||
var disabled = (self.enableToggle(data)) ? "" : " disabled";
|
||||
|
||||
return icon + disabled;
|
||||
};
|
||||
@@ -471,11 +598,22 @@ $(function() {
|
||||
|
||||
var name = "Unknown";
|
||||
if (action == "install") {
|
||||
var unknown = false;
|
||||
|
||||
if (data.hasOwnProperty("plugin")) {
|
||||
name = data.plugin.name;
|
||||
if (data.plugin == "unknown") {
|
||||
unknown = true;
|
||||
} else {
|
||||
name = data.plugin.name;
|
||||
}
|
||||
}
|
||||
|
||||
if (data.was_reinstalled) {
|
||||
if (unknown) {
|
||||
titleSuccess = _.sprintf(gettext("Plugin installed"));
|
||||
textSuccess = gettext("A plugin was installed successfully, however it was impossible to detect which one. Please Restart OctoPrint to make sure everything will be registered properly");
|
||||
textRestart = textSuccess;
|
||||
textReload = textSuccess;
|
||||
} else if (data.was_reinstalled) {
|
||||
titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" reinstalled"), {name: name});
|
||||
textSuccess = gettext("The plugin was reinstalled successfully");
|
||||
textRestart = gettext("The plugin was reinstalled successfully, however a restart of OctoPrint is needed for that to take effect.");
|
||||
@@ -569,5 +707,5 @@ $(function() {
|
||||
}
|
||||
|
||||
// view model class, parameters for constructor, container to bind to
|
||||
ADDITIONAL_VIEWMODELS.push([PluginManagerViewModel, ["loginStateViewModel", "settingsViewModel"], "#settings_plugin_pluginmanager"]);
|
||||
ADDITIONAL_VIEWMODELS.push([PluginManagerViewModel, ["loginStateViewModel", "settingsViewModel", "printerStateViewModel"], "#settings_plugin_pluginmanager"]);
|
||||
});
|
||||
@@ -84,3 +84,20 @@ table {
|
||||
}
|
||||
}
|
||||
|
||||
#settings_plugin_pluginmanager_workingdialog_output {
|
||||
.message {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.stdout {
|
||||
color: #333333;
|
||||
}
|
||||
|
||||
.stderr {
|
||||
color: #990000;
|
||||
}
|
||||
|
||||
.call {
|
||||
color: #000099;
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,35 @@
|
||||
{% macro pluginmanager_printing() %}
|
||||
<div class="alert" data-bind="visible: !enableManagement()">
|
||||
{{ _('Take note that all plugin management functionality is disabled while your printer is printing.') }}
|
||||
</div>
|
||||
{% endmacro %}
|
||||
|
||||
{% macro pluginmanager_nopip() %}
|
||||
<div class="alert" data-bind="visible: !pipAvailable()">{% trans %}
|
||||
The <code>pip</code> command could not be found.
|
||||
Please configure it manually. No installation and uninstallation of plugin
|
||||
packages is possible while <code>pip</code> is unavailable.
|
||||
{% endtrans %}</div>
|
||||
{% endmacro %}
|
||||
|
||||
{% macro pluginmanager_sudopip() %}
|
||||
<div class="alert alert-error" data-bind="visible: pipUseSudo()">{% trans %}
|
||||
The <code>pip</code> command is configured to use <code>sudo</code>. This
|
||||
is <strong>not</strong> recommended due to security reasons. It is <strong>strongly</strong>
|
||||
suggested you install OctoPrint under a
|
||||
<a href="https://github.com/foosel/OctoPrint/#installation">user-owned virtual environment</a>
|
||||
so that the use of <code>sudo</code> is not needed for plugin management.
|
||||
{% endtrans %}</div>
|
||||
{% endmacro %}
|
||||
|
||||
{{ pluginmanager_printing() }}
|
||||
{{ pluginmanager_nopip() }}
|
||||
{{ pluginmanager_sudopip() }}
|
||||
|
||||
<div class="pull-right">
|
||||
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="icon-wrench"></i></button>
|
||||
</div>
|
||||
|
||||
<h3>{{ _('Installed Plugins') }}</h3>
|
||||
|
||||
<table class="table table-striped table-hover table-condensed table-hover">
|
||||
@@ -20,7 +52,7 @@
|
||||
</div>
|
||||
</td>
|
||||
<td class="settings_plugin_plugin_manager_plugins_actions">
|
||||
<a href="#" data-bind="css: $root.toggleButtonCss($data), attr: {title: $root.toggleButtonTitle($data)}, enable: key != 'pluginmanager', click: function() { $root.togglePlugin($data) }"></a> | <a href="#" class="icon-trash" title="{{ _('Uninstall Plugin') }}" data-bind="css: {disabled: bundled || key == 'pluginmanager' || pending_uninstall}, enable: !bundled && key != 'pluginmanager' && !pending_uninstall, click: function() { $root.uninstallPlugin($data) }"></a>
|
||||
<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="icon-trash" title="{{ _('Uninstall Plugin') }}" data-bind="css: {disabled: !$root.enableUninstall($data)}, enable: $root.enableUninstall($data), click: function() { $root.uninstallPlugin($data) }"></a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
@@ -39,13 +71,17 @@
|
||||
|
||||
<button class="btn btn-block" data-bind="click: $root.showRepository">{{ _('Get More...') }}</button>
|
||||
|
||||
<p class="muted" data-bind="visible: pipAvailable()">
|
||||
<small>Using pip at "<span data-bind="text: pipCommand"></span>" (Version <span data-bind="text: pipVersion"></span><span data-bind="visible: pipAdditionalArgs">, additional arguments: <span data-bind="text: pipAdditionalArgs"></span></span>)</small>
|
||||
</p>
|
||||
|
||||
<div id="settings_plugin_pluginmanager_workingdialog" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
<h3 data-bind="text: workingTitle"></h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<pre id="settings_plugin_pluginmanager_workingdialog_output" class="terminal pre-scrollable" style="height: 170px" data-bind="foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr'}"></span><br></pre>
|
||||
<pre id="settings_plugin_pluginmanager_workingdialog_output" class="terminal pre-scrollable" style="height: 170px" data-bind="foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message'}"></span><br></pre>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" data-bind="enable: !$root.working()" aria-hidden="true">{{ _('Close') }}</button>
|
||||
@@ -58,6 +94,9 @@
|
||||
<h3>{{ _('Install new Plugins...') }}</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
{{ pluginmanager_printing() }}
|
||||
{{ pluginmanager_nopip() }}
|
||||
{{ pluginmanager_sudopip() }}
|
||||
<h4 style="position: relative">
|
||||
{{ _('... from the <a href="%(url)s" target="_blank">Plugin Repository</a>', url='http://plugins.octoprint.org') }}
|
||||
<a class="dropdown-toggle pull-right" data-toggle="dropdown" href="#">
|
||||
@@ -74,7 +113,7 @@
|
||||
</a>
|
||||
</h4>
|
||||
|
||||
<form class="form-search">
|
||||
<form class="form-search" data-bind="submit: performRepositorySearch">
|
||||
<input type="text" class="input-block search-query" data-bind="value: repositorySearchQuery, valueUpdate: 'input'" placeholder="{{ _('Search...') }}">
|
||||
</form>
|
||||
|
||||
@@ -94,7 +133,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="span3">
|
||||
<button class="btn btn-primary btn-block" data-bind="enable: $root.isCompatible($data), css: {disabled: !$root.isCompatible($data)}, click: function() { if ($root.isCompatible($data)) { $root.installFromRepository($data); } else { return false; } }"><i class="icon-add"></i> <span data-bind="text: $root.installButtonText($data)"></span></button>
|
||||
<button class="btn btn-primary btn-block" data-bind="enable: $root.enableRepoInstall($data), css: {disabled: !$root.enableRepoInstall($data)}, click: function() { if ($root.enableRepoInstall($data)) { $root.installFromRepository($data); } else { return false; } }"><i class="icon-add"></i> <span data-bind="text: $root.installButtonText($data)"></span></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -138,8 +177,67 @@
|
||||
</div>
|
||||
<span class="help-block" data-bind="visible: invalidArchive">{{ _('This does not look like a valid plugin archive. Valid plugin archives should be either zip files or tarballs and have the extension ".zip", ".tar.gz", ".tgz" or ".tar"') }}</span>
|
||||
</form>
|
||||
|
||||
<div>
|
||||
<div><small><a href="#" class="muted" onclick="$(this).children().toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="icon-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
|
||||
<div class="hide">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: followDependencyLinks"> {{ _('Use <code>--process-dependency-links</code> with <code>pip install</code>') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="settings_plugin_pluginmanager_configurationdialog" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
<h3>{{ _('Plugin Configuration') }}</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group" title="{{ _('pip command to use for managing plugins. You might have to configure this if auto detection fails.') }}">
|
||||
<label class="control-label">{{ _('pip command') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_pipCommand" placeholder="{{ _('Autodetect') }}">
|
||||
<span class="help-inline">{{ _('<strong>Only</strong> set this if OctoPrint cannot autodetect the path to <code>pip</code> to use for managing plugins.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('Additional arguments for pip command. You should normally not have to change this.') }}">
|
||||
<label class="control-label">{{ _('Additional pip arguments') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_pipAdditionalArgs">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('URL of the Plugin Repository to use. You should normally not have to change this.') }}">
|
||||
<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.') }}">
|
||||
<label class="control-label">{{ _('Repository cache TTL') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="number" class="input-mini" data-bind="value: config_repositoryTtl">
|
||||
<span class="add-on">min</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</button>
|
||||
<button class="btn btn-primary" data-bind="click: savePluginSettings" aria-hidden="true">{{ _('Save') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -12,6 +12,7 @@ import flask
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
import hashlib
|
||||
|
||||
from . import version_checks, updaters, exceptions, util
|
||||
|
||||
@@ -37,12 +38,18 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
self._version_cache = dict()
|
||||
self._version_cache_ttl = 0
|
||||
self._version_cache_path = None
|
||||
self._version_cache_dirty = False
|
||||
|
||||
def initialize(self):
|
||||
self._version_cache_ttl = self._settings.get_int(["cache_ttl"]) * 60
|
||||
self._version_cache_path = os.path.join(self.get_plugin_data_folder(), "versioncache.yaml")
|
||||
self._load_version_cache()
|
||||
|
||||
def refresh_checks(name, plugin):
|
||||
self._refresh_configured_checks = True
|
||||
self._send_client_message("update_versions")
|
||||
|
||||
self._plugin_lifecycle_manager.add_callback("enabled", refresh_checks)
|
||||
self._plugin_lifecycle_manager.add_callback("disabled", refresh_checks)
|
||||
|
||||
@@ -52,6 +59,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._refresh_configured_checks = False
|
||||
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)
|
||||
for name, hook in update_check_hooks.items():
|
||||
try:
|
||||
hook_checks = hook()
|
||||
@@ -59,12 +67,74 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._logger.exception("Error while retrieving update information from plugin {name}".format(**locals()))
|
||||
else:
|
||||
for key, data in hook_checks.items():
|
||||
check_providers[key] = name
|
||||
if key in self._configured_checks:
|
||||
data = dict_merge(data, self._configured_checks[key])
|
||||
self._configured_checks[key] = data
|
||||
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"])
|
||||
plugin_and_not_enabled = lambda k: k in check_providers and \
|
||||
not check_providers[k] in self._plugin_manager.enabled_plugins
|
||||
obsolete_plugin_checks = filter(plugin_and_not_enabled,
|
||||
config_checks.keys())
|
||||
for key in obsolete_plugin_checks:
|
||||
self._logger.debug("Check for key {} was provided by plugin {} that's no longer available, ignoring it".format(key, check_providers[key]))
|
||||
del self._configured_checks[key]
|
||||
|
||||
return self._configured_checks
|
||||
|
||||
def _load_version_cache(self):
|
||||
if not os.path.isfile(self._version_cache_path):
|
||||
return
|
||||
|
||||
import yaml
|
||||
try:
|
||||
with open(self._version_cache_path) as f:
|
||||
data = yaml.safe_load(f)
|
||||
except:
|
||||
self._logger.exception("Error while loading version cache from disk")
|
||||
else:
|
||||
try:
|
||||
if not isinstance(data, dict):
|
||||
self._logger.info("Version cache was created in a different format, not using it")
|
||||
return
|
||||
|
||||
if "__version" in data:
|
||||
data_version = data["__version"]
|
||||
else:
|
||||
self._logger.info("Can't determine version of OctoPrint version cache was created for, not using it")
|
||||
return
|
||||
|
||||
from octoprint._version import get_versions
|
||||
octoprint_version = get_versions()["version"]
|
||||
if data_version != octoprint_version:
|
||||
self._logger.info("Version cache was created for another version of OctoPrint, not using it")
|
||||
return
|
||||
|
||||
self._version_cache = data
|
||||
self._version_cache_dirty = False
|
||||
self._logger.info("Loaded version cache from disk")
|
||||
except:
|
||||
self._logger.exception("Error parsing in version cache data")
|
||||
|
||||
def _save_version_cache(self):
|
||||
import yaml
|
||||
from octoprint.util import atomic_write
|
||||
from octoprint._version import get_versions
|
||||
|
||||
octoprint_version = get_versions()["version"]
|
||||
self._version_cache["__version"] = octoprint_version
|
||||
|
||||
with atomic_write(self._version_cache_path) as file_obj:
|
||||
yaml.safe_dump(self._version_cache, stream=file_obj, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
|
||||
self._version_cache_dirty = False
|
||||
self._logger.info("Saved version cache to disk")
|
||||
|
||||
#~~ SettingsPlugin API
|
||||
|
||||
def get_settings_defaults(self):
|
||||
@@ -78,20 +148,191 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
"restart": "octoprint"
|
||||
},
|
||||
},
|
||||
"pip_command": None,
|
||||
"check_providers": {},
|
||||
|
||||
"octoprint_restart_command": None,
|
||||
"environment_restart_command": None,
|
||||
|
||||
"cache_ttl": 60,
|
||||
"cache_ttl": 24 * 60,
|
||||
}
|
||||
|
||||
def on_settings_load(self):
|
||||
data = dict(octoprint.plugin.SettingsPlugin.on_settings_load(self))
|
||||
if "checks" in data:
|
||||
del data["checks"]
|
||||
|
||||
checks = self._get_configured_checks()
|
||||
if "octoprint" in checks:
|
||||
if "checkout_folder" in checks["octoprint"]:
|
||||
data["octoprint_checkout_folder"] = checks["octoprint"]["checkout_folder"]
|
||||
elif "update_folder" in checks["octoprint"]:
|
||||
data["octoprint_checkout_folder"] = checks["octoprint"]["update_folder"]
|
||||
else:
|
||||
data["octoprint_checkout_folder"] = None
|
||||
data["octoprint_type"] = checks["octoprint"].get("type", None)
|
||||
else:
|
||||
data["octoprint_checkout_folder"] = None
|
||||
data["octoprint_type"] = None
|
||||
|
||||
return data
|
||||
|
||||
def on_settings_save(self, data):
|
||||
super(SoftwareUpdatePlugin, self).on_settings_save(data)
|
||||
for key in self.get_settings_defaults():
|
||||
if key == "checks" or key == "cache_ttl" or key == "octoprint_checkout_folder" or key == "octoprint_type":
|
||||
continue
|
||||
if key in data:
|
||||
self._settings.set([key], data[key])
|
||||
|
||||
if "cache_ttl" in data:
|
||||
self._settings.set_int(["cache_ttl"], data["cache_ttl"])
|
||||
self._version_cache_ttl = self._settings.get_int(["cache_ttl"]) * 60
|
||||
|
||||
checks = self._get_configured_checks()
|
||||
if "octoprint" in checks:
|
||||
check = checks["octoprint"]
|
||||
update_type = check.get("type", None)
|
||||
checkout_folder = check.get("checkout_folder", None)
|
||||
update_folder = check.get("update_folder", None)
|
||||
|
||||
defaults = dict(
|
||||
plugins=dict(softwareupdate=dict(
|
||||
checks=dict(
|
||||
octoprint=dict(
|
||||
type=update_type,
|
||||
checkout_folder=checkout_folder,
|
||||
update_folder=update_folder
|
||||
)
|
||||
)
|
||||
))
|
||||
)
|
||||
|
||||
if "octoprint_checkout_folder" in data:
|
||||
self._settings.set(["checks", "octoprint", "checkout_folder"], data["octoprint_checkout_folder"], defaults=defaults, force=True)
|
||||
if update_folder and data["octoprint_checkout_folder"]:
|
||||
self._settings.set(["checks", "octoprint", "update_folder"], None, defaults=defaults, force=True)
|
||||
self._refresh_configured_checks = True
|
||||
|
||||
if "octoprint_type" in data and data["octoprint_type"] in ("github_release", "git_commit"):
|
||||
self._settings.set(["checks", "octoprint", "type"], data["octoprint_type"], defaults=defaults, force=True)
|
||||
self._refresh_configured_checks = True
|
||||
|
||||
def get_settings_version(self):
|
||||
return 4
|
||||
|
||||
def on_settings_migrate(self, target, current=None):
|
||||
|
||||
if current is None or current < 4:
|
||||
# config version 4 and higher moves octoprint_restart_command and
|
||||
# environment_restart_command to the core configuration
|
||||
|
||||
# current plugin commands
|
||||
configured_octoprint_restart_command = self._settings.get(["octoprint_restart_command"])
|
||||
configured_environment_restart_command = self._settings.get(["environment_restart_command"])
|
||||
|
||||
# current global commands
|
||||
configured_system_restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"])
|
||||
configured_server_restart_command = self._settings.global_get(["server", "commands", "serverRestartCommand"])
|
||||
|
||||
# only set global commands if they are not yet set
|
||||
if configured_system_restart_command is None and configured_environment_restart_command is not None:
|
||||
self._settings.global_set(["server", "commands", "systemRestartCommand"], configured_environment_restart_command)
|
||||
if configured_server_restart_command is None and configured_octoprint_restart_command is not None:
|
||||
self._settings.global_set(["server", "commands", "serverRestartCommand"], configured_octoprint_restart_command)
|
||||
|
||||
# delete current plugin commands from config
|
||||
self._settings.set(["environment_restart_command"], None)
|
||||
self._settings.set(["octoprint_restart_command"], None)
|
||||
|
||||
if current is None or current == 2:
|
||||
# No config version and config version 2 need the same fix, stripping
|
||||
# accidentally persisted data off the checks
|
||||
|
||||
configured_checks = self._settings.get(["checks"], incl_defaults=False)
|
||||
if configured_checks is None:
|
||||
configured_checks = dict()
|
||||
|
||||
check_keys = configured_checks.keys()
|
||||
|
||||
# take care of the octoprint entry
|
||||
if "octoprint" in configured_checks:
|
||||
octoprint_check = dict(configured_checks["octoprint"])
|
||||
if "type" not in octoprint_check or octoprint_check["type"] != "github_commit":
|
||||
deletables=["current", "displayName", "displayVersion"]
|
||||
else:
|
||||
deletables=[]
|
||||
octoprint_check = self._clean_settings_check("octoprint", octoprint_check, self.get_settings_defaults()["checks"]["octoprint"], delete=deletables, save=False)
|
||||
check_keys.remove("octoprint")
|
||||
|
||||
# and the hooks
|
||||
update_check_hooks = self._plugin_manager.get_hooks("octoprint.plugin.softwareupdate.check_config")
|
||||
for name, hook in update_check_hooks.items():
|
||||
try:
|
||||
hook_checks = hook()
|
||||
except:
|
||||
self._logger.exception("Error while retrieving update information from plugin {name}".format(**locals()))
|
||||
else:
|
||||
for key, data in hook_checks.items():
|
||||
if key in configured_checks:
|
||||
settings_check = dict(configured_checks[key])
|
||||
merged = dict_merge(data, settings_check)
|
||||
if "type" not in merged or merged["type"] != "github_commit":
|
||||
deletables = ["current", "displayVersion"]
|
||||
else:
|
||||
deletables = []
|
||||
|
||||
self._clean_settings_check(key, settings_check, data, delete=deletables, save=False)
|
||||
check_keys.remove(key)
|
||||
|
||||
# and anything that's left over we'll just remove now
|
||||
for key in check_keys:
|
||||
dummy_defaults = dict(plugins=dict())
|
||||
dummy_defaults["plugins"][self._identifier] = dict(checks=dict())
|
||||
dummy_defaults["plugins"][self._identifier]["checks"][key] = None
|
||||
self._settings.set(["checks", key], None, defaults=dummy_defaults)
|
||||
|
||||
elif current == 1:
|
||||
# config version 1 had the error that the octoprint check got accidentally
|
||||
# included in checks["octoprint"], leading to recursion and hence to
|
||||
# yaml parser errors
|
||||
|
||||
configured_checks = self._settings.get(["checks"], incl_defaults=False)
|
||||
if configured_checks is None:
|
||||
return
|
||||
|
||||
if "octoprint" in configured_checks and "octoprint" in configured_checks["octoprint"]:
|
||||
# that's a circular reference, back to defaults
|
||||
dummy_defaults = dict(plugins=dict())
|
||||
dummy_defaults["plugins"][self._identifier] = dict(checks=dict())
|
||||
dummy_defaults["plugins"][self._identifier]["checks"]["octoprint"] = None
|
||||
self._settings.set(["checks", "octoprint"], None, defaults=dummy_defaults)
|
||||
|
||||
def _clean_settings_check(self, key, data, defaults, delete=None, save=True):
|
||||
if delete is None:
|
||||
delete = []
|
||||
|
||||
for k, v in data.items():
|
||||
if k in defaults and defaults[k] == data[k]:
|
||||
del data[k]
|
||||
|
||||
for k in delete:
|
||||
if k in data:
|
||||
del data[k]
|
||||
|
||||
dummy_defaults = dict(plugins=dict())
|
||||
dummy_defaults["plugins"][self._identifier] = dict(checks=dict())
|
||||
dummy_defaults["plugins"][self._identifier]["checks"][key] = defaults
|
||||
if len(data):
|
||||
self._settings.set(["checks", key], data, defaults=dummy_defaults)
|
||||
else:
|
||||
self._settings.set(["checks", key], None, defaults=dummy_defaults)
|
||||
|
||||
if save:
|
||||
self._settings.save()
|
||||
|
||||
return data
|
||||
|
||||
#~~ BluePrint API
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/check", methods=["GET"])
|
||||
@restricted_access
|
||||
def check_for_update(self):
|
||||
if "check" in flask.request.values:
|
||||
check_targets = map(str.strip, flask.request.values["check"].split(","))
|
||||
@@ -101,7 +342,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
if "force" in flask.request.values and flask.request.values["force"] in octoprint.settings.valid_boolean_trues:
|
||||
force = True
|
||||
else:
|
||||
force=False
|
||||
force = False
|
||||
|
||||
try:
|
||||
information, update_available, update_possible = self.get_current_versions(check_targets=check_targets, force=force)
|
||||
@@ -116,10 +357,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
def perform_update(self):
|
||||
if self._printer.is_printing() or self._printer.is_paused():
|
||||
# do not update while a print job is running
|
||||
flask.make_response("Printer is currently printing or paused", 409)
|
||||
return flask.make_response("Printer is currently printing or paused", 409)
|
||||
|
||||
if not "application/json" in flask.request.headers["Content-Type"]:
|
||||
flask.make_response("Expected content-type JSON", 400)
|
||||
return flask.make_response("Expected content-type JSON", 400)
|
||||
|
||||
json_data = flask.request.json
|
||||
|
||||
@@ -128,9 +369,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
else:
|
||||
check_targets = None
|
||||
|
||||
if "force" in json_data:
|
||||
from octoprint.settings import valid_boolean_trues
|
||||
force = (json_data["force"] in valid_boolean_trues)
|
||||
if "force" in json_data and json_data["force"] in octoprint.settings.valid_boolean_trues:
|
||||
force = True
|
||||
else:
|
||||
force = False
|
||||
|
||||
@@ -149,8 +389,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
##~~ TemplatePlugin API
|
||||
|
||||
def get_template_configs(self):
|
||||
from flask.ext.babel import gettext
|
||||
return [
|
||||
dict(type="settings", name="Software Update")
|
||||
dict(type="settings", name=gettext("Software Update"))
|
||||
]
|
||||
|
||||
#~~ Updater
|
||||
@@ -176,40 +417,51 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
continue
|
||||
|
||||
try:
|
||||
target_information, target_update_available, target_update_possible = self._get_current_version(target, check, force=force)
|
||||
populated_check = self._populated_check(target, check)
|
||||
target_information, target_update_available, target_update_possible = self._get_current_version(target, populated_check, force=force)
|
||||
if target_information is None:
|
||||
continue
|
||||
target_information = dict()
|
||||
except exceptions.UnknownCheckType:
|
||||
self._logger.warn("Unknown update check type for %s" % target)
|
||||
self._logger.warn("Unknown update check type for target {}: {}".format(target, check.get("type", "<n/a>")))
|
||||
continue
|
||||
|
||||
target_information = dict_merge(dict(local=dict(name="unknown", value="unknown"), remote=dict(name="unknown", value="unknown")), target_information)
|
||||
|
||||
update_available = update_available or target_update_available
|
||||
update_possible = update_possible or (target_update_possible and target_update_available)
|
||||
information[target] = dict(updateAvailable=target_update_available, updatePossible=target_update_possible, information=target_information)
|
||||
|
||||
if "displayName" in check:
|
||||
information[target]["displayName"] = check["displayName"]
|
||||
from octoprint._version import get_versions
|
||||
octoprint_version = get_versions()["version"]
|
||||
local_name = target_information["local"]["name"]
|
||||
local_value = target_information["local"]["value"]
|
||||
|
||||
if "displayVersion" in check:
|
||||
from octoprint._version import get_versions
|
||||
octoprint_version = get_versions()["version"]
|
||||
local_name = target_information["local"]["name"]
|
||||
local_value = target_information["local"]["value"]
|
||||
information[target]["displayVersion"] = check["displayVersion"].format(octoprint_version=octoprint_version, local_name=local_name, local_value=local_value)
|
||||
information[target] = dict(updateAvailable=target_update_available,
|
||||
updatePossible=target_update_possible,
|
||||
information=target_information,
|
||||
displayName=populated_check["displayName"],
|
||||
displayVersion=populated_check["displayVersion"].format(octoprint_version=octoprint_version, local_name=local_name, local_value=local_value),
|
||||
check=populated_check)
|
||||
|
||||
if self._version_cache_dirty:
|
||||
self._save_version_cache()
|
||||
return information, update_available, update_possible
|
||||
|
||||
def _get_check_hash(self, check):
|
||||
hash = hashlib.md5()
|
||||
hash.update(repr(check))
|
||||
return hash.hexdigest()
|
||||
|
||||
def _get_current_version(self, target, check, force=False):
|
||||
"""
|
||||
Determines the current version information for one target based on its check configuration.
|
||||
"""
|
||||
|
||||
current_hash = self._get_check_hash(check)
|
||||
if target in self._version_cache and not force:
|
||||
timestamp, information, update_available, update_possible = self._version_cache[target]
|
||||
if timestamp + self._version_cache_ttl >= time.time():
|
||||
return information, update_available, update_possible
|
||||
data = self._version_cache[target]
|
||||
if data["hash"] == current_hash and data["timestamp"] + self._version_cache_ttl >= time.time() > data["timestamp"]:
|
||||
# we also check that timestamp < now to not get confused too much by clock changes
|
||||
return data["information"], data["available"], data["possible"]
|
||||
|
||||
information = dict()
|
||||
update_available = False
|
||||
@@ -232,7 +484,12 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
except:
|
||||
update_possible = False
|
||||
|
||||
self._version_cache[target] = (time.time(), information, update_available, update_possible)
|
||||
self._version_cache[target] = dict(timestamp=time.time(),
|
||||
hash=current_hash,
|
||||
information=information,
|
||||
available=update_available,
|
||||
possible=update_possible)
|
||||
self._version_cache_dirty = True
|
||||
return information, update_available, update_possible
|
||||
|
||||
def _send_client_message(self, message_type, data=None):
|
||||
@@ -309,11 +566,17 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._send_client_message("error", dict(results=target_results))
|
||||
|
||||
else:
|
||||
self._save_version_cache()
|
||||
|
||||
# otherwise the update process was a success, but we might still have to restart
|
||||
if restart_type is not None and restart_type in ("octoprint", "environment"):
|
||||
# one of our updates requires a restart of either type "octoprint" or "environment". Let's see if
|
||||
# we can actually perform that
|
||||
restart_command = self._settings.get(["%s_restart_command" % restart_type])
|
||||
|
||||
if restart_type == "octoprint":
|
||||
restart_command = self._settings.global_get(["server", "commands", "serverRestartCommand"])
|
||||
elif restart_type == "environment":
|
||||
restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"])
|
||||
|
||||
if restart_command is not None:
|
||||
self._send_client_message("restarting", dict(restart_type=restart_type, results=target_results))
|
||||
@@ -378,15 +641,17 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
# persist the new version if necessary for check type
|
||||
if check["type"] == "github_commit":
|
||||
checks = self._settings.get(["checks"], merged=True)
|
||||
if target in checks:
|
||||
# TODO make this cleaner, right now it saves too much to disk
|
||||
checks[target]["current"] = target_version
|
||||
self._settings.set(["checks"], checks)
|
||||
dummy_default = dict(plugins=dict())
|
||||
dummy_default["plugins"][self._identifier] = dict(checks=dict())
|
||||
dummy_default["plugins"][self._identifier]["checks"][target] = dict(current=None)
|
||||
self._settings.set(["checks", target, "current"], target_version, defaults=dummy_default)
|
||||
|
||||
# we have to save here (even though that makes us save quite often) since otherwise the next
|
||||
# load will overwrite our changes we just made
|
||||
self._settings.save()
|
||||
# we have to save here (even though that makes us save quite often) since otherwise the next
|
||||
# load will overwrite our changes we just made
|
||||
self._settings.save()
|
||||
|
||||
del self._version_cache[target]
|
||||
self._version_cache_dirty = True
|
||||
|
||||
return target_error, target_result
|
||||
|
||||
@@ -404,6 +669,33 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._logger.warn("Restart stderr:\n%s" % e.stderr)
|
||||
raise exceptions.RestartFailed()
|
||||
|
||||
def _populated_check(self, target, check):
|
||||
if not "type" in check:
|
||||
raise exceptions.UnknownCheckType()
|
||||
|
||||
result = dict(check)
|
||||
|
||||
if target == "octoprint":
|
||||
from flask.ext.babel import gettext
|
||||
result["displayName"] = check.get("displayName", gettext("OctoPrint"))
|
||||
result["displayVersion"] = check.get("displayVersion", "{octoprint_version}")
|
||||
|
||||
from octoprint._version import get_versions
|
||||
versions = get_versions()
|
||||
if check["type"] == "github_commit":
|
||||
result["current"] = versions.get("full-revisionid", versions.get("full", "unknown"))
|
||||
else:
|
||||
result["current"] = versions["version"]
|
||||
else:
|
||||
result["displayName"] = check.get("displayName", target)
|
||||
result["displayVersion"] = check.get("displayVersion", check.get("current", "unknown"))
|
||||
if check["type"] in ("github_commit"):
|
||||
result["current"] = check.get("current", None)
|
||||
else:
|
||||
result["current"] = check.get("current", check.get("displayVersion", None))
|
||||
|
||||
return result
|
||||
|
||||
def _get_version_checker(self, target, check):
|
||||
"""
|
||||
Retrieves the version checker to use for given target and check configuration. Will raise an UnknownCheckType
|
||||
@@ -413,13 +705,6 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
if not "type" in check:
|
||||
raise exceptions.ConfigurationInvalid("no check type defined")
|
||||
|
||||
if target == "octoprint":
|
||||
from octoprint._version import get_versions
|
||||
from flask.ext.babel import gettext
|
||||
check["displayName"] = gettext("OctoPrint")
|
||||
check["displayVersion"] = "{octoprint_version}"
|
||||
check["current"] = get_versions()["version"]
|
||||
|
||||
check_type = check["type"]
|
||||
if check_type == "github_release":
|
||||
return version_checks.github_release
|
||||
@@ -443,6 +728,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
if "update_script" in check:
|
||||
return updaters.update_script
|
||||
elif "pip" in check:
|
||||
if not "pip_command" in check and self._settings.get(["pip_command"]) is not None:
|
||||
check["pip_command"] = self._settings.get(["pip_command"])
|
||||
return updaters.pip
|
||||
elif "python_updater" in check:
|
||||
return updaters.python_updater
|
||||
|
||||
@@ -13,12 +13,22 @@ $(function() {
|
||||
|
||||
self.currentlyBeingUpdated = [];
|
||||
|
||||
self.config_restartCommand = ko.observable();
|
||||
self.config_rebootCommand = ko.observable();
|
||||
self.octoprintUnconfigured = ko.observable();
|
||||
self.octoprintUnreleased = ko.observable();
|
||||
|
||||
self.config_cacheTtl = ko.observable();
|
||||
self.config_checkoutFolder = ko.observable();
|
||||
self.config_checkType = ko.observable();
|
||||
|
||||
self.configurationDialog = $("#settings_plugin_softwareupdate_configurationdialog");
|
||||
|
||||
self.config_availableCheckTypes = [
|
||||
{"key": "github_release", "name": gettext("Release")},
|
||||
{"key": "git_commit", "name": gettext("Commit")}
|
||||
];
|
||||
|
||||
self.reloadOverlay = $("#reloadui_overlay");
|
||||
|
||||
self.versions = new ItemListHelper(
|
||||
"plugin.softwareupdate.versions",
|
||||
{
|
||||
@@ -44,9 +54,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self._showPopup = function(options, eventListeners) {
|
||||
if (self.popup !== undefined) {
|
||||
self.popup.remove();
|
||||
}
|
||||
self._closePopup();
|
||||
self.popup = new PNotify(options);
|
||||
|
||||
if (eventListeners) {
|
||||
@@ -65,6 +73,12 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self._closePopup = function() {
|
||||
if (self.popup !== undefined) {
|
||||
self.popup.remove();
|
||||
}
|
||||
};
|
||||
|
||||
self.showPluginSettings = function() {
|
||||
self._copyConfig();
|
||||
self.configurationDialog.modal();
|
||||
@@ -74,19 +88,122 @@ $(function() {
|
||||
var data = {
|
||||
plugins: {
|
||||
softwareupdate: {
|
||||
octoprint_restart_command: self.config_restartCommand(),
|
||||
environment_restart_command: self.config_rebootCommand(),
|
||||
cache_ttl: parseInt(self.config_cacheTtl())
|
||||
cache_ttl: parseInt(self.config_cacheTtl()),
|
||||
octoprint_checkout_folder: self.config_checkoutFolder(),
|
||||
octoprint_type: self.config_checkType()
|
||||
}
|
||||
}
|
||||
};
|
||||
self.settings.saveData(data, function() { self.configurationDialog.modal("hide"); self._copyConfig(); });
|
||||
self.settings.saveData(data, function() {
|
||||
self.configurationDialog.modal("hide");
|
||||
self._copyConfig();
|
||||
self.performCheck();
|
||||
});
|
||||
};
|
||||
|
||||
self._copyConfig = function() {
|
||||
self.config_restartCommand(self.settings.settings.plugins.softwareupdate.octoprint_restart_command());
|
||||
self.config_rebootCommand(self.settings.settings.plugins.softwareupdate.environment_restart_command());
|
||||
self.config_cacheTtl(self.settings.settings.plugins.softwareupdate.cache_ttl());
|
||||
self.config_checkoutFolder(self.settings.settings.plugins.softwareupdate.octoprint_checkout_folder());
|
||||
self.config_checkType(self.settings.settings.plugins.softwareupdate.octoprint_type());
|
||||
};
|
||||
|
||||
self.fromCheckResponse = function(data, ignoreSeen, showIfNothingNew) {
|
||||
var versions = [];
|
||||
_.each(data.information, function(value, key) {
|
||||
value["key"] = key;
|
||||
|
||||
if (!value.hasOwnProperty("displayName") || value.displayName == "") {
|
||||
value.displayName = value.key;
|
||||
}
|
||||
if (!value.hasOwnProperty("displayVersion") || value.displayVersion == "") {
|
||||
value.displayVersion = value.information.local.name;
|
||||
}
|
||||
|
||||
versions.push(value);
|
||||
});
|
||||
self.versions.updateItems(versions);
|
||||
|
||||
var octoprint = data.information["octoprint"];
|
||||
if (octoprint && octoprint.hasOwnProperty("check")) {
|
||||
var check = octoprint.check;
|
||||
if (BRANCH != "master" && check["type"] == "github_release") {
|
||||
self.octoprintUnreleased(true);
|
||||
} else {
|
||||
self.octoprintUnreleased(false);
|
||||
}
|
||||
|
||||
var checkoutFolder = (check["checkout_folder"] || "").trim();
|
||||
var updateFolder = (check["update_folder"] || "").trim();
|
||||
var checkType = check["type"] || "";
|
||||
if ((checkType == "github_release" || checkType == "git_commit") && checkoutFolder == "" && updateFolder == "") {
|
||||
self.octoprintUnconfigured(true);
|
||||
} else {
|
||||
self.octoprintUnconfigured(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (data.status == "updateAvailable" || data.status == "updatePossible") {
|
||||
var text = gettext("There are updates available for the following components:");
|
||||
|
||||
text += "<ul>";
|
||||
_.each(self.versions.items(), function(update_info) {
|
||||
if (update_info.updateAvailable) {
|
||||
var displayName = update_info.key;
|
||||
if (update_info.hasOwnProperty("displayName")) {
|
||||
displayName = update_info.displayName;
|
||||
}
|
||||
text += "<li>" + displayName + (update_info.updatePossible ? " <i class=\"icon-ok\"></i>" : "") + "</li>";
|
||||
}
|
||||
});
|
||||
text += "</ul>";
|
||||
|
||||
text += "<small>" + gettext("Those components marked with <i class=\"icon-ok\"></i> can be updated directly.") + "</small>";
|
||||
|
||||
var options = {
|
||||
title: gettext("Update Available"),
|
||||
text: text,
|
||||
hide: false
|
||||
};
|
||||
var eventListeners = {};
|
||||
|
||||
if (data.status == "updatePossible" && self.loginState.isAdmin()) {
|
||||
// if user is admin, add action buttons
|
||||
options["confirm"] = {
|
||||
confirm: true,
|
||||
buttons: [{
|
||||
text: gettext("Ignore"),
|
||||
click: function() {
|
||||
self._markNotificationAsSeen(data.information);
|
||||
self._showPopup({
|
||||
text: gettext("You can make this message display again via \"Settings\" > \"Software Update\" > \"Check for update now\"")
|
||||
});
|
||||
}
|
||||
}, {
|
||||
text: gettext("Update now"),
|
||||
addClass: "btn-primary",
|
||||
click: self.update
|
||||
}]
|
||||
};
|
||||
options["buttons"] = {
|
||||
closer: false,
|
||||
sticker: false
|
||||
};
|
||||
}
|
||||
|
||||
if (ignoreSeen || !self._hasNotificationBeenSeen(data.information)) {
|
||||
self._showPopup(options, eventListeners);
|
||||
}
|
||||
} else if (data.status == "current") {
|
||||
if (showIfNothingNew) {
|
||||
self._showPopup({
|
||||
title: gettext("Everything is up-to-date"),
|
||||
hide: false,
|
||||
type: "success"
|
||||
});
|
||||
} else {
|
||||
self._closePopup();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self.performCheck = function(showIfNothingNew, force, ignoreSeen) {
|
||||
@@ -102,79 +219,7 @@ $(function() {
|
||||
type: "GET",
|
||||
dataType: "json",
|
||||
success: function(data) {
|
||||
var versions = [];
|
||||
_.each(data.information, function(value, key) {
|
||||
value["key"] = key;
|
||||
|
||||
if (!value.hasOwnProperty("displayName") || value.displayName == "") {
|
||||
value.displayName = value.key;
|
||||
}
|
||||
if (!value.hasOwnProperty("displayVersion") || value.displayVersion == "") {
|
||||
value.displayVersion = value.information.local.name;
|
||||
}
|
||||
|
||||
versions.push(value);
|
||||
});
|
||||
self.versions.updateItems(versions);
|
||||
|
||||
if (data.status == "updateAvailable" || data.status == "updatePossible") {
|
||||
var text = gettext("There are updates available for the following components:");
|
||||
|
||||
text += "<ul>";
|
||||
_.each(self.versions.items(), function(update_info) {
|
||||
if (update_info.updateAvailable) {
|
||||
var displayName = update_info.key;
|
||||
if (update_info.hasOwnProperty("displayName")) {
|
||||
displayName = update_info.displayName;
|
||||
}
|
||||
text += "<li>" + displayName + (update_info.updatePossible ? " <i class=\"icon-ok\"></i>" : "") + "</li>";
|
||||
}
|
||||
});
|
||||
text += "</ul>";
|
||||
|
||||
text += "<small>" + gettext("Those components marked with <i class=\"icon-ok\"></i> can be updated directly.") + "</small>";
|
||||
|
||||
var options = {
|
||||
title: gettext("Update Available"),
|
||||
text: text,
|
||||
hide: false
|
||||
};
|
||||
var eventListeners = {};
|
||||
|
||||
if (data.status == "updatePossible" && self.loginState.isAdmin()) {
|
||||
// if user is admin, add action buttons
|
||||
options["confirm"] = {
|
||||
confirm: true,
|
||||
buttons: [{
|
||||
text: gettext("Ignore"),
|
||||
click: function() {
|
||||
self._markNotificationAsSeen(data.information);
|
||||
self._showPopup({
|
||||
text: gettext("You can make this message display again via \"Settings\" > \"SoftwareUpdate\" > \"Check for update now\"")
|
||||
});
|
||||
}
|
||||
}, {
|
||||
text: gettext("Update now"),
|
||||
addClass: "btn-primary",
|
||||
click: self.update
|
||||
}]
|
||||
};
|
||||
options["buttons"] = {
|
||||
closer: false,
|
||||
sticker: false
|
||||
};
|
||||
}
|
||||
|
||||
if (ignoreSeen || !self._hasNotificationBeenSeen(data.information)) {
|
||||
self._showPopup(options, eventListeners);
|
||||
}
|
||||
} else if (data.status == "current" && showIfNothingNew) {
|
||||
self._showPopup({
|
||||
title: gettext("Everything is up-to-date"),
|
||||
hide: false,
|
||||
type: "success"
|
||||
});
|
||||
}
|
||||
self.fromCheckResponse(data, ignoreSeen, showIfNothingNew);
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -286,18 +331,10 @@ $(function() {
|
||||
self.onDataUpdaterReconnect = function() {
|
||||
if (self.waitingForRestart) {
|
||||
self.waitingForRestart = false;
|
||||
|
||||
var options = {
|
||||
title: gettext("Restart successful!"),
|
||||
text: gettext("The server was restarted successfully. The page will now reload automatically."),
|
||||
type: "success",
|
||||
hide: false
|
||||
};
|
||||
self._showPopup(options);
|
||||
self.updateInProgress = false;
|
||||
|
||||
var delay = 5 + Math.floor(Math.random() * 5) + 1;
|
||||
setTimeout(function() {location.reload(true);}, delay * 1000);
|
||||
if (!self.reloadOverlay.is(":visible")) {
|
||||
self.reloadOverlay.show();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -421,6 +458,10 @@ $(function() {
|
||||
self.updateInProgress = false;
|
||||
break;
|
||||
}
|
||||
case "update_versions": {
|
||||
self.performCheck();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (options != undefined) {
|
||||
@@ -432,4 +473,4 @@ $(function() {
|
||||
|
||||
// view model class, parameters for constructor, container to bind to
|
||||
ADDITIONAL_VIEWMODELS.push([SoftwareUpdateViewModel, ["loginStateViewModel", "printerStateViewModel", "settingsViewModel"], document.getElementById("settings_plugin_softwareupdate")]);
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,21 @@
|
||||
<div class="alert" data-bind="visible: octoprintUnconfigured()">{% trans %}
|
||||
Please configure the <strong>checkout folder</strong> of OctoPrint, otherwise
|
||||
this plugin won't be able to update it. Click on the <i class="icon-wrench"></i> button
|
||||
to do this. Also refer to the <a href="https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update" target="_blank">Documentation</a>.
|
||||
{% endtrans %}</div>
|
||||
<div class="alert" data-bind="visible: !octoprintUnconfigured() && octoprintUnreleased()">{% trans %}
|
||||
<p>
|
||||
<strong>You are running a non-release version of OctoPrint but are tracking OctoPrint
|
||||
releases.</strong>
|
||||
</p><p>
|
||||
You probably want OctoPrint to track the matching development version instead.
|
||||
If you have a local OctoPrint checkout folder switched to another branch,
|
||||
<strong>simply switching over to "Commit" tracking</strong> will already
|
||||
take care of that. Otherwise please take a look at the
|
||||
<a href="https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update" target="_blank">Documentation</a>.
|
||||
</p>
|
||||
{% endtrans %}</div>
|
||||
|
||||
<div class="pull-right">
|
||||
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="icon-wrench"></i></button>
|
||||
</div>
|
||||
@@ -11,7 +29,7 @@
|
||||
<span data-bind="invisible: !updateAvailable"><i class="icon-bell" title="{{ _('Update available') }}"></i></span>
|
||||
</td>
|
||||
<td class="settings_plugin_softwareupdate_column_information">
|
||||
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span><br>
|
||||
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span> <span data-bind="invisible: updatePossible"><i class="icon-exclamation-sign" title="{{ _('Update not possible, configuration ok?') }}"></i></span><br>
|
||||
<small class="muted">
|
||||
{{ _('Installed:') }} <span data-bind="text: information.local.name"></span><br>
|
||||
{{ _('Available:') }} <span data-bind="text: information.remote.name"></span>
|
||||
@@ -44,7 +62,7 @@
|
||||
<div><small><a href="#" class="muted" onclick="$(this).children().toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="icon-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
|
||||
<div class="hide">
|
||||
<button class="btn btn-block" data-bind="click: function() { $root.performCheck(true, true, true); }">{{ _('Force check for update (overrides cache used for update checks)') }}</button>
|
||||
<button class="btn btn-block btn-danger" data-bind="click: function() { $root.update(true); }">{{ _('Force update now (even if no new versions are available)') }}</button>
|
||||
<button class="btn btn-block btn-danger" data-bind="visible: CONFIG_DEBUG, click: function() { $root.update(true); }">{{ _('Force update now (even if no new versions are available)') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -56,15 +74,15 @@
|
||||
<div class="modal-body">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Restart Command') }}</label>
|
||||
<label class="control-label">{{ _('OctoPrint checkout folder') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_restartCommand">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_checkoutFolder">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Reboot Command') }}</label>
|
||||
<label class="control-label">{{ _('OctoPrint version tracking') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_rebootCommand">
|
||||
<select data-bind="value: config_checkType, options: config_availableCheckTypes, optionsText: 'name', optionsValue: 'key'"></select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
|
||||
@@ -7,31 +7,78 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
|
||||
import logging
|
||||
import pkg_resources
|
||||
|
||||
try:
|
||||
import pip as _pip
|
||||
except:
|
||||
_pip = None
|
||||
from octoprint.util.pip import PipCaller, UnknownPip
|
||||
from .. import exceptions
|
||||
|
||||
logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pip")
|
||||
console_logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pip.console")
|
||||
|
||||
_pip_callers = dict()
|
||||
_pip_version_dependency_links = pkg_resources.parse_version("1.5")
|
||||
|
||||
def can_perform_update(target, check):
|
||||
return "pip" in check and _pip is not None
|
||||
pip_caller = _get_pip_caller(command=check["pip_command"] if "pip_command" in check else None)
|
||||
return "pip" in check and pip_caller is not None and pip_caller.available
|
||||
|
||||
def _get_pip_caller(command=None):
|
||||
key = command
|
||||
if command is None:
|
||||
key = "__default"
|
||||
|
||||
if not key in _pip_callers:
|
||||
try:
|
||||
_pip_callers[key] = PipCaller(configured=command)
|
||||
_pip_callers[key].on_log_call = _log_call
|
||||
_pip_callers[key].on_log_stdout = _log_stdout
|
||||
_pip_callers[key].on_log_stderr = _log_stderr
|
||||
except UnknownPip:
|
||||
_pip_callers[key] = None
|
||||
|
||||
return _pip_callers[key]
|
||||
|
||||
def perform_update(target, check, target_version):
|
||||
logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pip")
|
||||
pip_command = None
|
||||
if "pip_command" in check:
|
||||
pip_command = check["pip_command"]
|
||||
|
||||
pip_caller = _get_pip_caller(command=pip_command)
|
||||
if pip_caller is None:
|
||||
raise exceptions.UpdateError("Can't run pip", None)
|
||||
|
||||
install_arg = check["pip"].format(target_version=target_version)
|
||||
|
||||
logger.debug("Target: %s, executing pip install %s" % (target, install_arg))
|
||||
logger.debug(u"Target: %s, executing pip install %s" % (target, install_arg))
|
||||
pip_args = ["install", check["pip"].format(target_version=target_version, target=target_version)]
|
||||
_pip.main(pip_args)
|
||||
|
||||
if "force_reinstall" in check and check["force_reinstall"]:
|
||||
# if force_reinstall is true, we need to install the package a second time, this time forcing its reinstall
|
||||
# without forcing its dependencies too
|
||||
logger.debug("Target. %s, executing pip install %s --ignore-reinstalled --force-reinstall --no-deps" % (target, install_arg))
|
||||
pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"]
|
||||
_pip.main(pip_args)
|
||||
if "dependency_links" in check and check["dependency_links"] and pip_caller >= _pip_version_dependency_links:
|
||||
pip_args += ["--process-dependency-links"]
|
||||
|
||||
returncode, stdout, stderr = pip_caller.execute(*pip_args)
|
||||
if returncode != 0:
|
||||
raise exceptions.UpdateError("Error while executing pip install", (stdout, stderr))
|
||||
|
||||
logger.debug(u"Target: %s, executing pip install %s --ignore-reinstalled --force-reinstall --no-deps" % (target, install_arg))
|
||||
pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"]
|
||||
|
||||
returncode, stdout, stderr = pip_caller.execute(*pip_args)
|
||||
if returncode != 0:
|
||||
raise exceptions.UpdateError("Error while executing pip install --force-reinstall", (stdout, stderr))
|
||||
|
||||
return "ok"
|
||||
|
||||
def _log_call(*lines):
|
||||
_log(lines, prefix=u" ")
|
||||
|
||||
def _log_stdout(*lines):
|
||||
_log(lines, prefix=u">")
|
||||
|
||||
def _log_stderr(*lines):
|
||||
_log(lines, prefix=u"!")
|
||||
|
||||
def _log(lines, prefix=None):
|
||||
lines = map(lambda x: x.strip(), lines)
|
||||
for line in lines:
|
||||
console_logger.debug(u"{prefix} {line}".format(**locals()))
|
||||
|
||||
@@ -13,7 +13,17 @@ from ..util import execute
|
||||
|
||||
|
||||
def can_perform_update(target, check):
|
||||
return "update_script" in check and ("checkout_folder" in check or "update_folder" in check)
|
||||
import os
|
||||
script_configured = bool("update_script" in check and check["update_script"])
|
||||
|
||||
folder = None
|
||||
if "update_folder" in check:
|
||||
folder = check["update_folder"]
|
||||
elif "checkout_folder" in check:
|
||||
folder = check["checkout_folder"]
|
||||
folder_configured = bool(folder and os.path.isdir(folder))
|
||||
|
||||
return script_configured and folder_configured
|
||||
|
||||
|
||||
def perform_update(target, check, target_version):
|
||||
|
||||
@@ -44,27 +44,71 @@ def _get_latest_release(user, repo, include_prerelease=False):
|
||||
return latest["name"], latest["tag_name"]
|
||||
|
||||
|
||||
def _is_current(release_information, compare_type, custom=None):
|
||||
def _get_sanitized_version(version_string):
|
||||
if "-" in version_string:
|
||||
version_string = version_string[:version_string.find("-")]
|
||||
return version_string
|
||||
|
||||
|
||||
def _get_comparable_version_pkg_resources(version_string, force_base=True):
|
||||
import pkg_resources
|
||||
|
||||
version = pkg_resources.parse_version(version_string)
|
||||
|
||||
if force_base:
|
||||
if isinstance(version, tuple):
|
||||
# old setuptools
|
||||
base_version = []
|
||||
for part in version:
|
||||
if part.startswith("*"):
|
||||
break
|
||||
base_version.append(part)
|
||||
version = tuple(base_version)
|
||||
else:
|
||||
# new setuptools
|
||||
version = pkg_resources.parse_version(version.base_version)
|
||||
|
||||
return version
|
||||
|
||||
|
||||
def _get_comparable_version_semantic(version_string, force_base=True):
|
||||
import semantic_version
|
||||
|
||||
version = semantic_version.Version.coerce(version_string, partial=False)
|
||||
|
||||
if force_base:
|
||||
version_string = "{}.{}.{}".format(version.major, version.minor, version.patch)
|
||||
version = semantic_version.Version.coerce(version_string, partial=False)
|
||||
|
||||
return version
|
||||
|
||||
|
||||
def _is_current(release_information, compare_type, custom=None, force_base=True):
|
||||
if release_information["remote"]["value"] is None:
|
||||
return True
|
||||
|
||||
if not compare_type in ("semantic", "unequal", "custom") or compare_type == "custom" and custom is None:
|
||||
compare_type = "semantic"
|
||||
if not compare_type in ("python", "semantic", "unequal", "custom") or compare_type == "custom" and custom is None:
|
||||
compare_type = "python"
|
||||
|
||||
sanitized_local = _get_sanitized_version(release_information["local"]["value"])
|
||||
sanitized_remote = _get_sanitized_version(release_information["remote"]["value"])
|
||||
|
||||
try:
|
||||
if compare_type == "semantic":
|
||||
import semantic_version
|
||||
|
||||
local_version = semantic_version.Version(release_information["local"]["value"])
|
||||
remote_version = semantic_version.Version(release_information["remote"]["value"])
|
||||
if compare_type == "python":
|
||||
local_version = _get_comparable_version_pkg_resources(sanitized_local, force_base=force_base)
|
||||
remote_version = _get_comparable_version_pkg_resources(sanitized_remote, force_base=force_base)
|
||||
return local_version >= remote_version
|
||||
|
||||
elif compare_type == "semantic":
|
||||
local_version = _get_comparable_version_semantic(sanitized_local, force_base=force_base)
|
||||
remote_version = _get_comparable_version_semantic(sanitized_remote, force_base=force_base)
|
||||
return local_version >= remote_version
|
||||
|
||||
elif compare_type == "custom":
|
||||
return custom(release_information["local"], release_information["remote"])
|
||||
return custom(sanitized_local, sanitized_remote)
|
||||
|
||||
else:
|
||||
return release_information["local"]["value"] == release_information["remote"]["value"]
|
||||
return sanitized_local == sanitized_remote
|
||||
except:
|
||||
logger.exception("Could not check if version is current due to an error, assuming it is")
|
||||
return True
|
||||
@@ -74,12 +118,14 @@ def get_latest(target, check, custom_compare=None):
|
||||
if not "user" in check or not "repo" in check:
|
||||
raise ConfigurationInvalid("github_release update configuration for %s needs user and repo set" % target)
|
||||
|
||||
current = None
|
||||
if "current" in check:
|
||||
current = check["current"]
|
||||
current = check.get("current", None)
|
||||
include_prerelease = check.get("prerelease", False)
|
||||
force_base = check.get("force_base", True)
|
||||
|
||||
remote_name, remote_tag = _get_latest_release(check["user"], check["repo"], include_prerelease=check["prerelease"] == True if "prerelease" in check else False)
|
||||
compare_type = check["release_compare"] if "release_compare" in check else "semantic"
|
||||
remote_name, remote_tag = _get_latest_release(check["user"],
|
||||
check["repo"],
|
||||
include_prerelease=include_prerelease)
|
||||
compare_type = check["release_compare"] if "release_compare" in check else "python"
|
||||
|
||||
information =dict(
|
||||
local=dict(name=current, value=current),
|
||||
@@ -88,4 +134,7 @@ def get_latest(target, check, custom_compare=None):
|
||||
|
||||
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_tag))
|
||||
|
||||
return information, _is_current(information, compare_type, custom=custom_compare)
|
||||
return information, _is_current(information,
|
||||
compare_type,
|
||||
custom=custom_compare,
|
||||
force_base=force_base)
|
||||
@@ -65,6 +65,7 @@ class VirtualPrinter():
|
||||
self._heatupThread = None
|
||||
|
||||
self._okBeforeCommandOutput = settings().getBoolean(["devel", "virtualPrinter", "okBeforeCommandOutput"])
|
||||
self._supportM112 = settings().getBoolean(["devel", "virtualPrinter", "supportM112"])
|
||||
|
||||
self._sendWait = settings().getBoolean(["devel", "virtualPrinter", "sendWait"])
|
||||
self._waitInterval = settings().getFloat(["devel", "virtualPrinter", "waitInterval"])
|
||||
@@ -83,6 +84,7 @@ class VirtualPrinter():
|
||||
|
||||
self._action_hooks = plugin_manager().get_hooks("octoprint.plugin.virtual_printer.custom_action")
|
||||
|
||||
self._killed = False
|
||||
|
||||
waitThread = threading.Thread(target=self._sendWaitAfterTimeout)
|
||||
waitThread.start()
|
||||
@@ -106,7 +108,7 @@ class VirtualPrinter():
|
||||
|
||||
def _processIncoming(self):
|
||||
next_wait_timeout = time.time() + self._waitInterval
|
||||
while self.incoming is not None:
|
||||
while self.incoming is not None and not self._killed:
|
||||
self._simulateTemps()
|
||||
|
||||
try:
|
||||
@@ -266,9 +268,10 @@ class VirtualPrinter():
|
||||
elif "G92" in data:
|
||||
self._setPosition(data)
|
||||
|
||||
elif data.startswith("G0") or data.startswith("G1") or data.startswith("G2") or data.startswith("G3") \
|
||||
or data.startswith("G28") or data.startswith("G29") or data.startswith("G30") \
|
||||
or data.startswith("G31") or data.startswith("G32"):
|
||||
elif data.startswith("G28"):
|
||||
self._performMove(data)
|
||||
|
||||
elif data.startswith("G0") or data.startswith("G1") or data.startswith("G2") or data.startswith("G3"):
|
||||
# simulate reprap buffered commands via a Queue with maxsize which internally simulates the moves
|
||||
self.buffered.put(data)
|
||||
|
||||
@@ -291,6 +294,12 @@ class VirtualPrinter():
|
||||
if len(data.strip()) > 0 and not self._okBeforeCommandOutput:
|
||||
self._sendOk()
|
||||
|
||||
def _kill(self):
|
||||
if not self._supportM112:
|
||||
return
|
||||
self._killed = True
|
||||
self.outgoing.put("echo:EMERGENCY SHUTDOWN DETECTED. KILLED.")
|
||||
|
||||
def _triggerResend(self, expected=None, actual=None):
|
||||
with self._incoming_lock:
|
||||
if expected is None:
|
||||
@@ -303,8 +312,13 @@ class VirtualPrinter():
|
||||
else:
|
||||
self.outgoing.put("Error: expected line %d got %d" % (expected, actual))
|
||||
|
||||
self.outgoing.put("Resend:%d" % expected)
|
||||
self.outgoing.put("ok")
|
||||
def request_resend():
|
||||
self.outgoing.put("Resend:%d" % expected)
|
||||
self.outgoing.put("ok")
|
||||
|
||||
if settings().getBoolean(["devel", "virtualPrinter", "repetierStyleResends"]):
|
||||
request_resend()
|
||||
request_resend()
|
||||
|
||||
def _debugTrigger(self, data):
|
||||
if data == "action_pause":
|
||||
@@ -516,14 +530,10 @@ class VirtualPrinter():
|
||||
pass
|
||||
|
||||
if duration:
|
||||
if settings().getBoolean(["devel", "virtualPrinter", "waitOnLongMoves"]):
|
||||
slept = 0
|
||||
while duration - slept > self._read_timeout:
|
||||
time.sleep(self._read_timeout)
|
||||
self.outgoing.put("wait")
|
||||
slept += self._read_timeout
|
||||
else:
|
||||
time.sleep(duration)
|
||||
slept = 0
|
||||
while duration - slept > self._read_timeout and not self._killed:
|
||||
time.sleep(self._read_timeout)
|
||||
slept += self._read_timeout
|
||||
|
||||
def _setPosition(self, line):
|
||||
matchX = re.search("X([0-9.]+)", line)
|
||||
@@ -577,6 +587,9 @@ class VirtualPrinter():
|
||||
self._selectedSdFilePos = 0
|
||||
with open(self._selectedSdFile, "r") as f:
|
||||
for line in iter(f.readline, ""):
|
||||
if self._killed:
|
||||
break
|
||||
|
||||
# reset position if requested by client
|
||||
if self._newSdFilePos is not None:
|
||||
f.seek(self._newSdFilePos)
|
||||
@@ -606,12 +619,12 @@ class VirtualPrinter():
|
||||
delay = 1
|
||||
if heater.startswith("tool"):
|
||||
toolNum = int(heater[len("tool"):])
|
||||
while self.temp[toolNum] < self.targetTemp[toolNum] - delta or self.temp[toolNum] > self.targetTemp[toolNum] + delta:
|
||||
while not self._killed and (self.temp[toolNum] < self.targetTemp[toolNum] - delta or self.temp[toolNum] > self.targetTemp[toolNum] + delta):
|
||||
self._simulateTemps(delta=delta)
|
||||
self.outgoing.put("T:%0.2f" % self.temp[toolNum])
|
||||
time.sleep(delay)
|
||||
elif heater == "bed":
|
||||
while self.bedTemp < self.bedTargetTemp - delta or self.bedTemp > self.bedTargetTemp + delta:
|
||||
while not self._killed and (self.bedTemp < self.bedTargetTemp - delta or self.bedTemp > self.bedTargetTemp + delta):
|
||||
self._simulateTemps(delta=delta)
|
||||
self.outgoing.put("B:%0.2f" % self.bedTemp)
|
||||
time.sleep(delay)
|
||||
@@ -662,6 +675,11 @@ class VirtualPrinter():
|
||||
with self._incoming_lock:
|
||||
if self.incoming is None or self.outgoing is None:
|
||||
return
|
||||
|
||||
if "M112" in data and self._supportM112:
|
||||
self._kill()
|
||||
return
|
||||
|
||||
try:
|
||||
self.incoming.put(data, timeout=self._write_timeout)
|
||||
except Queue.Full:
|
||||
@@ -685,6 +703,9 @@ class VirtualPrinter():
|
||||
self.buffered = None
|
||||
|
||||
def _sendOk(self):
|
||||
if self.outgoing is None:
|
||||
return
|
||||
|
||||
if settings().getBoolean(["devel", "virtualPrinter", "okWithLinenumber"]):
|
||||
self.outgoing.put("ok %d" % self.lastN)
|
||||
else:
|
||||
|
||||
@@ -467,6 +467,6 @@ class PrinterCallback(object):
|
||||
"""
|
||||
pass
|
||||
|
||||
class UnknownScript(BaseException):
|
||||
class UnknownScript(Exception):
|
||||
def __init__(self, name, *args, **kwargs):
|
||||
self.name = name
|
||||
@@ -329,12 +329,14 @@ class PrinterProfileManager(object):
|
||||
if os.path.exists(path) and not allow_overwrite:
|
||||
raise SaveError("Profile %s already exists and not allowed to overwrite" % profile["id"])
|
||||
|
||||
from octoprint.util import atomic_write
|
||||
import yaml
|
||||
with open(path, "wb") as f:
|
||||
try:
|
||||
try:
|
||||
with atomic_write(path, "wb") as f:
|
||||
yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
except Exception as e:
|
||||
raise SaveError("Cannot save profile %s: %s" % (profile["id"], str(e)))
|
||||
except Exception as e:
|
||||
self._logger.exception("Error while trying to save profile %s" % profile["id"])
|
||||
raise SaveError("Cannot save profile %s: %s" % (profile["id"], str(e)))
|
||||
|
||||
def _remove_from_path(self, path):
|
||||
try:
|
||||
|
||||
@@ -389,6 +389,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._timeEstimationData = TimeEstimationHelper(rolling_window=rolling_window, threshold=threshold, countdown=countdown)
|
||||
|
||||
self._lastProgressReport = None
|
||||
self._setProgressData(0, None, None, None)
|
||||
self._setCurrentZ(None)
|
||||
self._comm.startPrint()
|
||||
|
||||
@@ -679,7 +680,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
# Use a string for mtime because it could be float and the
|
||||
# javascript needs to exact match
|
||||
if not sd:
|
||||
date = int(os.stat(path_on_disk).st_ctime)
|
||||
date = int(os.stat(path_on_disk).st_mtime)
|
||||
|
||||
try:
|
||||
fileData = self._fileManager.get_metadata(FileDestinations.SDCARD if sd else FileDestinations.LOCAL, path_on_disk)
|
||||
|
||||
@@ -14,12 +14,14 @@ from flask.ext.babel import Babel, gettext, ngettext
|
||||
from flask.ext.assets import Environment, Bundle
|
||||
from babel import Locale
|
||||
from watchdog.observers import Observer
|
||||
from watchdog.observers.polling import PollingObserver
|
||||
from collections import defaultdict
|
||||
|
||||
import os
|
||||
import logging
|
||||
import logging.config
|
||||
import atexit
|
||||
import signal
|
||||
|
||||
SUCCESS = {}
|
||||
NO_CONTENT = ("", 204)
|
||||
@@ -79,7 +81,7 @@ def on_identity_loaded(sender, identity):
|
||||
if user is None:
|
||||
return
|
||||
|
||||
identity.provides.add(UserNeed(user.get_name()))
|
||||
identity.provides.add(UserNeed(user.get_id()))
|
||||
if user.is_user():
|
||||
identity.provides.add(RoleNeed("user"))
|
||||
if user.is_admin():
|
||||
@@ -96,9 +98,9 @@ def load_user(id):
|
||||
|
||||
if userManager is not None:
|
||||
if sessionid:
|
||||
return userManager.findUser(username=id, session=sessionid)
|
||||
return userManager.findUser(userid=id, session=sessionid)
|
||||
else:
|
||||
return userManager.findUser(username=id)
|
||||
return userManager.findUser(userid=id)
|
||||
return users.DummyUser()
|
||||
|
||||
|
||||
@@ -196,7 +198,8 @@ class Server():
|
||||
file_manager=fileManager,
|
||||
printer=printer,
|
||||
app_session_manager=appSessionManager,
|
||||
plugin_lifecycle_manager=pluginLifecycleManager
|
||||
plugin_lifecycle_manager=pluginLifecycleManager,
|
||||
data_folder=os.path.join(settings().getBaseFolder("data"), name)
|
||||
)
|
||||
|
||||
def settings_plugin_inject_factory(name, implementation):
|
||||
@@ -210,9 +213,34 @@ class Server():
|
||||
set_preprocessors=set_preprocessors)
|
||||
return dict(settings=plugin_settings)
|
||||
|
||||
def settings_plugin_config_migration(name, implementation):
|
||||
if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
|
||||
return
|
||||
|
||||
settings_version = implementation.get_settings_version()
|
||||
settings_migrator = implementation.on_settings_migrate
|
||||
|
||||
if settings_version is not None and settings_migrator is not None:
|
||||
stored_version = implementation._settings.get_int(["_config_version"])
|
||||
if stored_version is None or stored_version < settings_version:
|
||||
settings_migrator(settings_version, stored_version)
|
||||
implementation._settings.set_int(["_config_version"], settings_version)
|
||||
implementation._settings.save()
|
||||
|
||||
implementation.on_settings_initialized()
|
||||
|
||||
pluginManager.implementation_inject_factories=[octoprint_plugin_inject_factory, settings_plugin_inject_factory]
|
||||
pluginManager.initialize_implementations()
|
||||
|
||||
settingsPlugins = pluginManager.get_implementations(octoprint.plugin.SettingsPlugin)
|
||||
for implementation in settingsPlugins:
|
||||
try:
|
||||
settings_plugin_config_migration(implementation._identifier, implementation)
|
||||
except:
|
||||
self._logger.exception("Error while trying to migrate settings for plugin {}, ignoring it".format(implementation._identifier))
|
||||
|
||||
pluginManager.implementation_post_inits=[settings_plugin_config_migration]
|
||||
|
||||
pluginManager.log_all_plugins()
|
||||
|
||||
# initialize file manager and register it for changes in the registered plugins
|
||||
@@ -302,13 +330,34 @@ class Server():
|
||||
|
||||
upload_suffixes = dict(name=s.get(["server", "uploads", "nameSuffix"]), path=s.get(["server", "uploads", "pathSuffix"]))
|
||||
|
||||
def mime_type_guesser(path):
|
||||
from octoprint.filemanager import get_mime_type
|
||||
return get_mime_type(path)
|
||||
|
||||
download_handler_kwargs = dict(
|
||||
as_attachment=True,
|
||||
allow_client_caching=False
|
||||
)
|
||||
additional_mime_types=dict(mime_type_guesser=mime_type_guesser)
|
||||
admin_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))
|
||||
no_hidden_files_validator = dict(path_validation=util.tornado.path_validation_factory(lambda path: not os.path.basename(path).startswith("."), status_code=404))
|
||||
|
||||
def joined_dict(*dicts):
|
||||
if not len(dicts):
|
||||
return dict()
|
||||
|
||||
joined = dict()
|
||||
for d in dicts:
|
||||
joined.update(d)
|
||||
return joined
|
||||
|
||||
server_routes = self._router.urls + [
|
||||
# various downloads
|
||||
(r"/downloads/timelapse/([^/]*\.mpg)", util.tornado.LargeResponseHandler, dict(path=s.getBaseFolder("timelapse"), as_attachment=True)),
|
||||
(r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, dict(path=s.getBaseFolder("uploads"), as_attachment=True, path_validation=util.tornado.path_validation_factory(lambda path: not os.path.basename(path).startswith("."), status_code=404))),
|
||||
(r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, dict(path=s.getBaseFolder("logs"), as_attachment=True, access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.admin_validator))),
|
||||
(r"/downloads/timelapse/([^/]*\.mpg)", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("timelapse")), download_handler_kwargs, no_hidden_files_validator)),
|
||||
(r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("uploads")), download_handler_kwargs, no_hidden_files_validator, additional_mime_types)),
|
||||
(r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("logs")), download_handler_kwargs, admin_validator)),
|
||||
# camera snapshot
|
||||
(r"/downloads/camera/current", util.tornado.UrlForwardHandler, dict(url=s.get(["webcam", "snapshot"]), as_attachment=True, access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))),
|
||||
(r"/downloads/camera/current", util.tornado.UrlProxyHandler, dict(url=s.get(["webcam", "snapshot"]), as_attachment=True, access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))),
|
||||
# generated webassets
|
||||
(r"/static/webassets/(.*)", util.tornado.LargeResponseHandler, dict(path=os.path.join(s.getBaseFolder("generated"), "webassets")))
|
||||
]
|
||||
@@ -375,7 +424,12 @@ class Server():
|
||||
printer.connect(port=port, baudrate=baudrate, profile=printer_profile["id"] if "id" in printer_profile else "_default")
|
||||
|
||||
# start up watchdogs
|
||||
observer = Observer()
|
||||
if s.getBoolean(["feature", "pollWatched"]):
|
||||
# use less performant polling observer if explicitely configured
|
||||
observer = PollingObserver()
|
||||
else:
|
||||
# use os default
|
||||
observer = Observer()
|
||||
observer.schedule(util.watchdog.GcodeWatchdogHandler(fileManager, printer), s.getBaseFolder("watched"))
|
||||
observer.start()
|
||||
|
||||
@@ -417,16 +471,27 @@ class Server():
|
||||
|
||||
# prepare our shutdown function
|
||||
def on_shutdown():
|
||||
self._logger.info("Goodbye!")
|
||||
# will be called on clean system exit and shutdown the watchdog observer and call the on_shutdown methods
|
||||
# on all registered ShutdownPlugins
|
||||
self._logger.info("Shutting down...")
|
||||
observer.stop()
|
||||
observer.join()
|
||||
octoprint.plugin.call_plugin(octoprint.plugin.ShutdownPlugin,
|
||||
"on_shutdown")
|
||||
self._logger.info("Goodbye!")
|
||||
atexit.register(on_shutdown)
|
||||
|
||||
def sigterm_handler(*args, **kwargs):
|
||||
# will stop tornado on SIGTERM, making the program exit cleanly
|
||||
def shutdown_tornado():
|
||||
ioloop.stop()
|
||||
ioloop.add_callback_from_signal(shutdown_tornado)
|
||||
signal.signal(signal.SIGTERM, sigterm_handler)
|
||||
|
||||
try:
|
||||
# this is the main loop - as long as tornado is running, OctoPrint is running
|
||||
ioloop.start()
|
||||
except KeyboardInterrupt:
|
||||
except (KeyboardInterrupt, SystemExit):
|
||||
pass
|
||||
except:
|
||||
self._logger.fatal("Now that is embarrassing... Something really really went wrong here. Please report this including the stacktrace below in OctoPrint's bugtracker. Thanks!")
|
||||
@@ -503,6 +568,9 @@ class Server():
|
||||
},
|
||||
"tornado.general": {
|
||||
"level": "INFO"
|
||||
},
|
||||
"octoprint.server.util.flask": {
|
||||
"level": "WARN"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
@@ -594,7 +662,10 @@ class Server():
|
||||
def _register_template_plugins(self):
|
||||
template_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin)
|
||||
for plugin in template_plugins:
|
||||
self._register_additional_template_plugin(plugin)
|
||||
try:
|
||||
self._register_additional_template_plugin(plugin)
|
||||
except:
|
||||
self._logger.exception("Error while trying to register templates of plugin {}, ignoring it".format(plugin._identifier))
|
||||
|
||||
def _register_additional_template_plugin(self, plugin):
|
||||
folder = plugin.get_template_folder()
|
||||
@@ -629,14 +700,22 @@ class Server():
|
||||
def _register_blueprint_plugins(self):
|
||||
blueprint_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.BlueprintPlugin)
|
||||
for plugin in blueprint_plugins:
|
||||
self._register_blueprint_plugin(plugin)
|
||||
try:
|
||||
self._register_blueprint_plugin(plugin)
|
||||
except:
|
||||
self._logger.exception("Error while registering blueprint of plugin {}, ignoring it".format(plugin._identifier))
|
||||
continue
|
||||
|
||||
def _register_asset_plugins(self):
|
||||
asset_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.AssetPlugin)
|
||||
for plugin in asset_plugins:
|
||||
if isinstance(plugin, octoprint.plugin.BlueprintPlugin):
|
||||
continue
|
||||
self._register_asset_plugin(plugin)
|
||||
try:
|
||||
self._register_asset_plugin(plugin)
|
||||
except:
|
||||
self._logger.exception("Error while registering assets of plugin {}, ignoring it".format(plugin._identifier))
|
||||
continue
|
||||
|
||||
def _register_blueprint_plugin(self, plugin):
|
||||
name = plugin._identifier
|
||||
@@ -671,9 +750,66 @@ class Server():
|
||||
global pluginManager
|
||||
|
||||
util.flask.fix_webassets_cache()
|
||||
util.flask.fix_webassets_filtertool()
|
||||
|
||||
base_folder = settings().getBaseFolder("generated")
|
||||
|
||||
# clean the folder
|
||||
if settings().getBoolean(["devel", "webassets", "clean_on_startup"]):
|
||||
import shutil
|
||||
import errno
|
||||
import sys
|
||||
|
||||
for entry in ("webassets", ".webassets-cache"):
|
||||
path = os.path.join(base_folder, entry)
|
||||
|
||||
# delete path if it exists
|
||||
if os.path.isdir(path):
|
||||
try:
|
||||
self._logger.debug("Deleting {path}...".format(**locals()))
|
||||
shutil.rmtree(path)
|
||||
except:
|
||||
self._logger.exception("Error while trying to delete {path}, leaving it alone".format(**locals()))
|
||||
continue
|
||||
|
||||
# re-create path
|
||||
self._logger.debug("Creating {path}...".format(**locals()))
|
||||
error_text = "Error while trying to re-create {path}, that might cause errors with the webassets cache".format(**locals())
|
||||
try:
|
||||
os.makedirs(path)
|
||||
except OSError as e:
|
||||
if e.errno == errno.EACCES:
|
||||
# that might be caused by the user still having the folder open somewhere, let's try again after
|
||||
# waiting a bit
|
||||
import time
|
||||
for n in xrange(3):
|
||||
time.sleep(0.5)
|
||||
self._logger.debug("Creating {path}: Retry #{retry} after {time}s".format(path=path, retry=n+1, time=(n + 1)*0.5))
|
||||
try:
|
||||
os.makedirs(path)
|
||||
break
|
||||
except:
|
||||
if self._logger.isEnabledFor(logging.DEBUG):
|
||||
self._logger.exception("Ignored error while creating directory {path}".format(**locals()))
|
||||
pass
|
||||
else:
|
||||
# this will only get executed if we never did
|
||||
# successfully execute makedirs above
|
||||
self._logger.exception(error_text)
|
||||
continue
|
||||
else:
|
||||
# not an access error, so something we don't understand
|
||||
# went wrong -> log an error and stop
|
||||
self._logger.exception(error_text)
|
||||
continue
|
||||
except:
|
||||
# not an OSError, so something we don't understand
|
||||
# went wrong -> log an error and stop
|
||||
self._logger.exception(error_text)
|
||||
continue
|
||||
|
||||
self._logger.info("Reset webasset folder {path}...".format(**locals()))
|
||||
|
||||
AdjustedEnvironment = type(Environment)(Environment.__name__, (Environment,), dict(
|
||||
resolver_class=util.flask.PluginAssetResolver
|
||||
))
|
||||
@@ -691,12 +827,10 @@ class Server():
|
||||
assets.updater = UpdaterType
|
||||
|
||||
enable_gcodeviewer = settings().getBoolean(["gcodeViewer", "enabled"])
|
||||
enable_timelapse = (settings().get(["webcam", "snapshot"]) and settings().get(["webcam", "ffmpeg"]))
|
||||
preferred_stylesheet = settings().get(["devel", "stylesheet"])
|
||||
|
||||
dynamic_assets = util.flask.collect_plugin_assets(
|
||||
enable_gcodeviewer=enable_gcodeviewer,
|
||||
enable_timelapse=enable_timelapse,
|
||||
preferred_stylesheet=preferred_stylesheet
|
||||
)
|
||||
|
||||
@@ -754,17 +888,7 @@ class Server():
|
||||
if len(less_app) == 0:
|
||||
less_app = ["empty"]
|
||||
|
||||
js_libs_bundle = Bundle(*js_libs, output="webassets/packed_libs.js")
|
||||
if settings().getBoolean(["devel", "webassets", "minify"]):
|
||||
js_app_bundle = Bundle(*js_app, output="webassets/package_app.js", filters="rjsmin")
|
||||
else:
|
||||
js_app_bundle = Bundle(*js_app, output="webassets/package_app.js")
|
||||
all_js_bundle = Bundle(js_libs_bundle, js_app_bundle, output="webassets/packed.js")
|
||||
|
||||
css_libs_bundle = Bundle(*css_libs, output="webassets/packed_libs.css")
|
||||
css_app_bundle = Bundle(*css_app, output="webassets/packed_app.css")
|
||||
|
||||
from webassets.filter import register_filter
|
||||
from webassets.filter import register_filter, Filter
|
||||
from webassets.filter.cssrewrite.base import PatternRewriter
|
||||
import re
|
||||
class LessImportRewrite(PatternRewriter):
|
||||
@@ -783,13 +907,31 @@ class Server():
|
||||
|
||||
return "{import_with_options}\"{import_url}\";".format(**locals())
|
||||
|
||||
class JsDelimiterBundle(Filter):
|
||||
name = "js_delimiter_bundler"
|
||||
options = {}
|
||||
def input(self, _in, out, **kwargs):
|
||||
out.write(_in.read())
|
||||
out.write("\n;\n")
|
||||
|
||||
register_filter(LessImportRewrite)
|
||||
register_filter(JsDelimiterBundle)
|
||||
|
||||
all_css_bundle = Bundle(css_libs_bundle, css_app_bundle, output="webassets/packed.css")
|
||||
all_less_bundle = Bundle(*less_app, output="webassets/packed.less", filters="less_importrewrite")
|
||||
js_libs_bundle = Bundle(*js_libs, output="webassets/packed_libs.js", filters="js_delimiter_bundler")
|
||||
if settings().getBoolean(["devel", "webassets", "minify"]):
|
||||
js_app_bundle = Bundle(*js_app, output="webassets/packed_app.js", filters="rjsmin, js_delimiter_bundler")
|
||||
else:
|
||||
js_app_bundle = Bundle(*js_app, output="webassets/packed_app.js", filters="js_delimiter_bundler")
|
||||
|
||||
assets.register("all_js", all_js_bundle)
|
||||
assets.register("all_css", all_css_bundle)
|
||||
css_libs_bundle = Bundle(*css_libs, output="webassets/packed_libs.css")
|
||||
css_app_bundle = Bundle(*css_app, output="webassets/packed_app.css", filters="cssrewrite")
|
||||
|
||||
all_less_bundle = Bundle(*less_app, output="webassets/packed_app.less", filters="cssrewrite, less_importrewrite")
|
||||
|
||||
assets.register("js_libs", js_libs_bundle)
|
||||
assets.register("js_app", js_app_bundle)
|
||||
assets.register("css_libs", css_libs_bundle)
|
||||
assets.register("css_app", css_app_bundle)
|
||||
assets.register("less_app", all_less_bundle)
|
||||
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ import octoprint.server
|
||||
import octoprint.plugin
|
||||
from octoprint.server import admin_permission, NO_CONTENT
|
||||
from octoprint.settings import settings as s, valid_boolean_trues
|
||||
from octoprint.server.util import apiKeyRequestHandler, corsResponseHandler
|
||||
from octoprint.server.util import noCachingResponseHandler, apiKeyRequestHandler, corsResponseHandler
|
||||
from octoprint.server.util.flask import restricted_access, get_json_command_from_request, passive_login
|
||||
|
||||
|
||||
@@ -42,6 +42,8 @@ from . import languages as api_languages
|
||||
|
||||
VERSION = "0.1"
|
||||
|
||||
api.after_request(noCachingResponseHandler)
|
||||
|
||||
api.before_request(apiKeyRequestHandler)
|
||||
api.after_request(corsResponseHandler)
|
||||
|
||||
@@ -152,22 +154,25 @@ def performSystemAction():
|
||||
available_actions = s().get(["system", "actions"])
|
||||
for availableAction in available_actions:
|
||||
if availableAction["action"] == action:
|
||||
async = availableAction["async"] if "async" in availableAction else False
|
||||
ignore = availableAction["ignore"] if "ignore" in availableAction else False
|
||||
logger.info("Performing command: %s" % availableAction["command"])
|
||||
try:
|
||||
# Note: we put the command in brackets since sarge (up to the most recently released version) has
|
||||
# a bug concerning shell=True commands. Once sarge 0.1.4 we can upgrade to that and remove this
|
||||
# workaround again
|
||||
#
|
||||
# See https://bitbucket.org/vinay.sajip/sarge/issue/21/behavior-is-not-like-popen-using-shell
|
||||
p = sarge.run([availableAction["command"]], stderr=sarge.Capture(), shell=True)
|
||||
if p.returncode != 0:
|
||||
returncode = p.returncode
|
||||
stderr_text = p.stderr.text
|
||||
logger.warn("Command failed with return code %i: %s" % (returncode, stderr_text))
|
||||
return make_response(("Command failed with return code %i: %s" % (returncode, stderr_text), 500, []))
|
||||
# we run this with shell=True since we have to trust whatever
|
||||
# our admin configured as command and since we want to allow
|
||||
# shell-alike handling here...
|
||||
p = sarge.run(availableAction["command"], stderr=sarge.Capture(), shell=True, async=async)
|
||||
if not async:
|
||||
if not ignore and p.returncode != 0:
|
||||
returncode = p.returncode
|
||||
stderr_text = p.stderr.text
|
||||
logger.warn("Command failed with return code %i: %s" % (returncode, stderr_text))
|
||||
return make_response(("Command failed with return code %i: %s" % (returncode, stderr_text), 500, []))
|
||||
except Exception, e:
|
||||
logger.warn("Command failed: %s" % e)
|
||||
return make_response(("Command failed: %s" % e, 500, []))
|
||||
if not ignore:
|
||||
logger.warn("Command failed: %s" % e)
|
||||
return make_response(("Command failed: %s" % e, 500, []))
|
||||
break
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
from flask import request, jsonify, make_response, url_for
|
||||
|
||||
import octoprint.util as util
|
||||
from octoprint.filemanager.destinations import FileDestinations
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
from octoprint.server import printer, fileManager, slicingManager, eventManager, NO_CONTENT
|
||||
@@ -18,6 +17,8 @@ import octoprint.filemanager
|
||||
import octoprint.filemanager.util
|
||||
import octoprint.slicing
|
||||
|
||||
import psutil
|
||||
|
||||
|
||||
#~~ GCODE file handling
|
||||
|
||||
@@ -29,7 +30,8 @@ def readGcodeFiles():
|
||||
filter = request.values["filter"]
|
||||
files = _getFileList(FileDestinations.LOCAL, filter=filter)
|
||||
files.extend(_getFileList(FileDestinations.SDCARD))
|
||||
return jsonify(files=files, free=util.get_free_bytes(settings().getBaseFolder("uploads")))
|
||||
usage = psutil.disk_usage(settings().getBaseFolder("uploads"))
|
||||
return jsonify(files=files, free=usage.free, total=usage.total)
|
||||
|
||||
|
||||
@api.route("/files/<string:origin>", methods=["GET"])
|
||||
@@ -40,7 +42,8 @@ def readGcodeFilesForOrigin(origin):
|
||||
files = _getFileList(origin)
|
||||
|
||||
if origin == FileDestinations.LOCAL:
|
||||
return jsonify(files=files, free=util.get_free_bytes(settings().getBaseFolder("uploads")))
|
||||
usage = psutil.disk_usage(settings().getBaseFolder("uploads"))
|
||||
return jsonify(files=files, free=usage.free, total=usage.total)
|
||||
else:
|
||||
return jsonify(files=files)
|
||||
|
||||
|
||||
@@ -90,11 +90,17 @@ def getInstalledLanguagePacks():
|
||||
def uploadLanguagePack():
|
||||
input_name = "file"
|
||||
input_upload_path = input_name + "." + settings().get(["server", "uploads", "pathSuffix"])
|
||||
if not input_upload_path in request.values:
|
||||
input_upload_name = input_name + "." + settings().get(["server", "uploads", "nameSuffix"])
|
||||
if not input_upload_path in request.values or not input_upload_name in request.values:
|
||||
return make_response("No file included", 400)
|
||||
|
||||
upload_name = request.values[input_upload_name]
|
||||
upload_path = request.values[input_upload_path]
|
||||
|
||||
exts = filter(lambda x: upload_name.lower().endswith(x), (".zip", ".tar.gz", ".tgz", ".tar"))
|
||||
if not len(exts):
|
||||
return make_response("File doesn't have a valid extension for a plugin archive", 400)
|
||||
|
||||
target_path = settings().getBaseFolder("translations")
|
||||
|
||||
if tarfile.is_tarfile(upload_path):
|
||||
@@ -143,5 +149,5 @@ def _validate_archive_name(name):
|
||||
raise InvalidLanguagePack("Provided language pack contains invalid name {name}".format(**locals()))
|
||||
|
||||
|
||||
class InvalidLanguagePack(BaseException):
|
||||
class InvalidLanguagePack(Exception):
|
||||
pass
|
||||
@@ -15,15 +15,18 @@ from octoprint.settings import settings
|
||||
from octoprint.server import NO_CONTENT, admin_permission
|
||||
from octoprint.server.util.flask import redirect_to_tornado, restricted_access
|
||||
from octoprint.server.api import api
|
||||
from octoprint.util import get_free_bytes
|
||||
|
||||
|
||||
@api.route("/logs", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def getLogFiles():
|
||||
import psutil
|
||||
usage = psutil.disk_usage(settings().getBaseFolder("logs"))
|
||||
|
||||
files = _getLogFiles()
|
||||
return jsonify(files=files, free=get_free_bytes(settings().getBaseFolder("logs")))
|
||||
|
||||
return jsonify(files=files, free=usage.free, total=usage.total)
|
||||
|
||||
|
||||
@api.route("/logs/<path:filename>", methods=["GET"])
|
||||
|
||||
@@ -26,6 +26,8 @@ import octoprint.util
|
||||
|
||||
@api.route("/settings", methods=["GET"])
|
||||
def getSettings():
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
s = settings()
|
||||
|
||||
connectionOptions = get_connection_options()
|
||||
@@ -66,7 +68,9 @@ def getSettings():
|
||||
"swallowOkAfterResend": s.getBoolean(["feature", "swallowOkAfterResend"]),
|
||||
"repetierTargetTemp": s.getBoolean(["feature", "repetierTargetTemp"]),
|
||||
"externalHeatupDetection": s.getBoolean(["feature", "externalHeatupDetection"]),
|
||||
"keyboardControl": s.getBoolean(["feature", "keyboardControl"])
|
||||
"keyboardControl": s.getBoolean(["feature", "keyboardControl"]),
|
||||
"pollWatched": s.getBoolean(["feature", "pollWatched"]),
|
||||
"ignoreIdenticalResends": s.getBoolean(["feature", "ignoreIdenticalResends"])
|
||||
},
|
||||
"serial": {
|
||||
"port": connectionOptions["portPreference"],
|
||||
@@ -109,6 +113,17 @@ def getSettings():
|
||||
"afterPrintResumed": None,
|
||||
"snippets": dict()
|
||||
}
|
||||
},
|
||||
"server": {
|
||||
"commands": {
|
||||
"systemShutdownCommand": s.get(["server", "commands", "systemShutdownCommand"]),
|
||||
"systemRestartCommand": s.get(["server", "commands", "systemRestartCommand"]),
|
||||
"serverRestartCommand": s.get(["server", "commands", "serverRestartCommand"])
|
||||
},
|
||||
"diskspace": {
|
||||
"warning": s.getInt(["server", "diskspace", "warning"]),
|
||||
"critical": s.getInt(["server", "diskspace", "critical"])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,17 +133,30 @@ def getSettings():
|
||||
for name in gcode_scripts:
|
||||
data["scripts"]["gcode"][name] = s.loadScript("gcode", name, source=True)
|
||||
|
||||
def process_plugin_result(name, plugin, result):
|
||||
def process_plugin_result(name, result):
|
||||
if result:
|
||||
try:
|
||||
jsonify(test=result)
|
||||
except:
|
||||
logger.exception("Error while jsonifying settings from plugin {}, please contact the plugin author about this".format(name))
|
||||
|
||||
if not "plugins" in data:
|
||||
data["plugins"] = dict()
|
||||
if "__enabled" in result:
|
||||
del result["__enabled"]
|
||||
data["plugins"][name] = result
|
||||
|
||||
octoprint.plugin.call_plugin(octoprint.plugin.SettingsPlugin,
|
||||
"on_settings_load",
|
||||
callback=process_plugin_result)
|
||||
for plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin):
|
||||
try:
|
||||
result = plugin.on_settings_load()
|
||||
process_plugin_result(plugin._identifier, result)
|
||||
except TypeError:
|
||||
logger.warn("Could not load settings for plugin {name} ({version}) since it called super(...)".format(name=plugin._plugin_name, version=plugin._plugin_version))
|
||||
logger.warn("in a way which has issues due to OctoPrint's dynamic reloading after plugin operations.")
|
||||
logger.warn("Please contact the plugin's author and ask to update the plugin to use a direct call like")
|
||||
logger.warn("octoprint.plugin.SettingsPlugin.on_settings_load(self) instead.")
|
||||
except:
|
||||
logger.exception("Could not load settings for plugin {name} ({version})".format(version=plugin._plugin_version, name=plugin._plugin_name))
|
||||
|
||||
return jsonify(data)
|
||||
|
||||
@@ -137,6 +165,8 @@ def getSettings():
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def setSettings():
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
@@ -182,6 +212,8 @@ def setSettings():
|
||||
if "repetierTargetTemp" in data["feature"].keys(): s.setBoolean(["feature", "repetierTargetTemp"], data["feature"]["repetierTargetTemp"])
|
||||
if "externalHeatupDetection" in data["feature"].keys(): s.setBoolean(["feature", "externalHeatupDetection"], data["feature"]["externalHeatupDetection"])
|
||||
if "keyboardControl" in data["feature"].keys(): s.setBoolean(["feature", "keyboardControl"], data["feature"]["keyboardControl"])
|
||||
if "pollWatched" in data["feature"]: s.setBoolean(["feature", "pollWatched"], data["feature"]["pollWatched"])
|
||||
if "ignoreIdenticalResends" in data["feature"]: s.setBoolean(["feature", "ignoreIdenticalResends"], data["feature"]["ignoreIdenticalResends"])
|
||||
|
||||
if "serial" in data.keys():
|
||||
if "autoconnect" in data["serial"].keys(): s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
|
||||
@@ -231,12 +263,28 @@ def setSettings():
|
||||
continue
|
||||
s.saveScript("gcode", name, script.replace("\r\n", "\n").replace("\r", "\n"))
|
||||
|
||||
if "server" in data:
|
||||
if "commands" in data["server"]:
|
||||
if "systemShutdownCommand" in data["server"]["commands"].keys(): s.set(["server", "commands", "systemShutdownCommand"], data["server"]["commands"]["systemShutdownCommand"])
|
||||
if "systemRestartCommand" in data["server"]["commands"].keys(): s.set(["server", "commands", "systemRestartCommand"], data["server"]["commands"]["systemRestartCommand"])
|
||||
if "serverRestartCommand" in data["server"]["commands"].keys(): s.set(["server", "commands", "serverRestartCommand"], data["server"]["commands"]["serverRestartCommand"])
|
||||
if "diskspace" in data["server"]:
|
||||
if "warning" in data["server"]["diskspace"]: s.setInt(["server", "diskspace", "warning"], data["server"]["diskspace"]["warning"])
|
||||
if "critical" in data["server"]["diskspace"]: s.setInt(["server", "diskspace", "critical"], data["server"]["diskspace"]["critical"])
|
||||
|
||||
if "plugins" in data:
|
||||
for plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin):
|
||||
plugin_id = plugin._identifier
|
||||
if plugin_id in data["plugins"]:
|
||||
plugin.on_settings_save(data["plugins"][plugin_id])
|
||||
|
||||
try:
|
||||
plugin.on_settings_save(data["plugins"][plugin_id])
|
||||
except TypeError:
|
||||
logger.warn("Could not save settings for plugin {name} ({version}) since it called super(...)".format(name=plugin._plugin_name, version=plugin._plugin_version))
|
||||
logger.warn("in a way which has issues due to OctoPrint's dynamic reloading after plugin operations.")
|
||||
logger.warn("Please contact the plugin's author and ask to update the plugin to use a direct call like")
|
||||
logger.warn("octoprint.plugin.SettingsPlugin.on_settings_save(self, data) instead.")
|
||||
except:
|
||||
logger.exception("Could not save settings for plugin {name} ({version})".format(version=plugin._plugin_version, name=plugin._plugin_name))
|
||||
|
||||
if s.save():
|
||||
eventManager().fire(Events.SETTINGS_UPDATED)
|
||||
|
||||
@@ -57,7 +57,7 @@ def slicingListSlicerProfiles(slicer):
|
||||
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["GET"])
|
||||
def slicingGetSlicerProfile(slicer, name):
|
||||
try:
|
||||
profile = slicingManager.load_profile(slicer, name)
|
||||
profile = slicingManager.load_profile(slicer, name, require_configured=False)
|
||||
except UnknownSlicer:
|
||||
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
|
||||
except UnknownProfile:
|
||||
@@ -106,7 +106,7 @@ def slicingPatchSlicerProfile(slicer, name):
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
profile = slicingManager.load_profile(slicer, name)
|
||||
profile = slicingManager.load_profile(slicer, name, require_configured=False)
|
||||
except UnknownSlicer:
|
||||
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
|
||||
except UnknownProfile:
|
||||
|
||||
@@ -29,14 +29,14 @@ def getTimelapseData():
|
||||
config = {"type": "off"}
|
||||
if timelapse is not None and isinstance(timelapse, octoprint.timelapse.ZTimelapse):
|
||||
config["type"] = "zchange"
|
||||
config["postRoll"] = timelapse.postRoll()
|
||||
config["fps"] = timelapse.fps()
|
||||
config["postRoll"] = timelapse.post_roll
|
||||
config["fps"] = timelapse.fps
|
||||
elif timelapse is not None and isinstance(timelapse, octoprint.timelapse.TimedTimelapse):
|
||||
config["type"] = "timed"
|
||||
config["postRoll"] = timelapse.postRoll()
|
||||
config["fps"] = timelapse.fps()
|
||||
config["postRoll"] = timelapse.post_roll
|
||||
config["fps"] = timelapse.fps
|
||||
config.update({
|
||||
"interval": timelapse.interval()
|
||||
"interval": timelapse.interval
|
||||
})
|
||||
|
||||
files = octoprint.timelapse.getFinishedTimelapses()
|
||||
|
||||
@@ -10,10 +10,15 @@ from flask import Blueprint, request, make_response, jsonify
|
||||
|
||||
import octoprint.server
|
||||
import octoprint.plugin
|
||||
|
||||
from octoprint.server.util import noCachingResponseHandler, corsResponseHandler
|
||||
from octoprint.settings import settings as s
|
||||
|
||||
apps = Blueprint("apps", __name__)
|
||||
|
||||
apps.after_request(noCachingResponseHandler)
|
||||
apps.after_request(corsResponseHandler)
|
||||
|
||||
@apps.route("/auth", methods=["GET"])
|
||||
def getSessionKey():
|
||||
unverified_key, valid_until = octoprint.server.appSessionManager.create()
|
||||
|
||||
@@ -80,6 +80,18 @@ def corsResponseHandler(resp):
|
||||
return resp
|
||||
|
||||
|
||||
def noCachingResponseHandler(resp):
|
||||
"""
|
||||
``after_request`` handler for blueprints which shall set no caching headers
|
||||
on their responses.
|
||||
|
||||
Sets ``Cache-Control``, ``Pragma`` and ``Expires`` headers accordingly
|
||||
to prevent all client side caching from taking place.
|
||||
"""
|
||||
|
||||
return flask.add_non_caching_response_headers(resp)
|
||||
|
||||
|
||||
def optionsAllowOrigin(request):
|
||||
"""
|
||||
Shortcut for request handling for CORS OPTIONS requests to set CORS headers.
|
||||
|
||||
@@ -19,6 +19,7 @@ import uuid
|
||||
import threading
|
||||
import logging
|
||||
import netaddr
|
||||
import os
|
||||
|
||||
from octoprint.settings import settings
|
||||
import octoprint.server
|
||||
@@ -122,12 +123,19 @@ def enable_additional_translations(default_locale="en", additional_folders=None)
|
||||
|
||||
def fix_webassets_cache():
|
||||
from webassets import cache
|
||||
import os
|
||||
import tempfile
|
||||
import pickle
|
||||
import shutil
|
||||
|
||||
error_logger = logging.getLogger(__name__ + ".fix_webassets_cache")
|
||||
|
||||
def fixed_set(self, key, data):
|
||||
import os
|
||||
import tempfile
|
||||
import pickle
|
||||
import shutil
|
||||
|
||||
if not os.path.exists(self.directory):
|
||||
error_logger.warn("Cache directory {} doesn't exist, not going "
|
||||
"to attempt to write cache file".format(self.directory))
|
||||
|
||||
md5 = '%s' % cache.make_md5(self.V, key)
|
||||
filename = os.path.join(self.directory, md5)
|
||||
fd, temp_filename = tempfile.mkstemp(prefix='.' + md5,
|
||||
@@ -147,6 +155,11 @@ def fix_webassets_cache():
|
||||
import warnings
|
||||
from webassets.cache import make_md5
|
||||
|
||||
if not os.path.exists(self.directory):
|
||||
error_logger.warn("Cache directory {} doesn't exist, not going "
|
||||
"to attempt to read cache file".format(self.directory))
|
||||
return None
|
||||
|
||||
try:
|
||||
hash = make_md5(self.V, key)
|
||||
except IOError as e:
|
||||
@@ -174,6 +187,37 @@ def fix_webassets_cache():
|
||||
cache.FilesystemCache.set = fixed_set
|
||||
cache.FilesystemCache.get = fixed_get
|
||||
|
||||
def fix_webassets_filtertool():
|
||||
from webassets.merge import FilterTool, log, MemoryHunk
|
||||
|
||||
error_logger = logging.getLogger(__name__ + ".fix_webassets_filtertool")
|
||||
|
||||
def fixed_wrap_cache(self, key, func):
|
||||
"""Return cache value ``key``, or run ``func``.
|
||||
"""
|
||||
if self.cache:
|
||||
if not self.no_cache_read:
|
||||
log.debug('Checking cache for key %s', key)
|
||||
content = self.cache.get(key)
|
||||
if not content in (False, None):
|
||||
log.debug('Using cached result for %s', key)
|
||||
return MemoryHunk(content)
|
||||
|
||||
try:
|
||||
content = func().getvalue()
|
||||
if self.cache:
|
||||
try:
|
||||
log.debug('Storing result in cache with key %s', key,)
|
||||
self.cache.set(key, content)
|
||||
except:
|
||||
error_logger.exception("Got an exception while trying to save file to cache, not caching")
|
||||
return MemoryHunk(content)
|
||||
except:
|
||||
error_logger.exception("Got an exception while trying to apply filter, ignoring file")
|
||||
return MemoryHunk(u"")
|
||||
|
||||
FilterTool._wrap_cache = fixed_wrap_cache
|
||||
|
||||
#~~ passive login helper
|
||||
|
||||
def passive_login():
|
||||
@@ -183,8 +227,10 @@ def passive_login():
|
||||
user = flask.ext.login.current_user
|
||||
|
||||
if user is not None and not user.is_anonymous():
|
||||
flask.g.user = user
|
||||
flask.ext.principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask.ext.principal.Identity(user.get_id()))
|
||||
if hasattr(user, "get_session"):
|
||||
flask.session["usersession.id"] = user.get_session()
|
||||
flask.g.user = user
|
||||
return flask.jsonify(user.asDict())
|
||||
elif settings().getBoolean(["accessControl", "autologinLocal"]) \
|
||||
and settings().get(["accessControl", "autologinAs"]) is not None \
|
||||
@@ -208,14 +254,14 @@ def passive_login():
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.exception("Could not autologin user %s for networks %r" % (autologinAs, localNetworks))
|
||||
|
||||
return ("", 204)
|
||||
return "", 204
|
||||
|
||||
|
||||
#~~ cache decorator for cacheable views
|
||||
|
||||
_cache = SimpleCache()
|
||||
|
||||
def cached(timeout=5 * 60, key=lambda: "view/%s" % flask.request.path, unless=None, refreshif=None):
|
||||
def cached(timeout=5 * 60, key=lambda: "view/%s" % flask.request.path, unless=None, refreshif=None, unless_response=None):
|
||||
def decorator(f):
|
||||
@functools.wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
@@ -244,6 +290,11 @@ def cached(timeout=5 * 60, key=lambda: "view/%s" % flask.request.path, unless=No
|
||||
logger.debug("No cache entry or refreshing cache for {path}, calling wrapped function".format(path=flask.request.path))
|
||||
rv = f(*args, **kwargs)
|
||||
|
||||
# do not store if the "unless_response" condition is true
|
||||
if callable(unless_response) and unless_response(rv):
|
||||
logger.debug("Not caching result for {path}, bypassed".format(path=flask.request.path))
|
||||
return rv
|
||||
|
||||
# store it in the cache
|
||||
_cache.set(cache_key, rv, timeout=timeout)
|
||||
|
||||
@@ -256,6 +307,31 @@ def cached(timeout=5 * 60, key=lambda: "view/%s" % flask.request.path, unless=No
|
||||
def cache_check_headers():
|
||||
return "no-cache" in flask.request.cache_control or "no-cache" in flask.request.pragma
|
||||
|
||||
def cache_check_response_headers(response):
|
||||
if not isinstance(response, flask.Response):
|
||||
return False
|
||||
|
||||
headers = response.headers
|
||||
|
||||
if "Cache-Control" in headers and "no-cache" in headers["Cache-Control"]:
|
||||
return True
|
||||
|
||||
if "Pragma" in headers and "no-cache" in headers["Pragma"]:
|
||||
return True
|
||||
|
||||
if "Expires" in headers and headers["Expires"] in ("0", "-1"):
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def add_non_caching_response_headers(response):
|
||||
response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0"
|
||||
response.headers["Pragma"] = "no-cache"
|
||||
response.headers["Expires"] = "-1"
|
||||
return response
|
||||
|
||||
|
||||
#~~ access validators for use with tornado
|
||||
|
||||
|
||||
@@ -454,7 +530,8 @@ def get_remote_address(request):
|
||||
|
||||
|
||||
def get_json_command_from_request(request, valid_commands):
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
content_type = request.headers.get("Content-Type", None)
|
||||
if content_type is None or not "application/json" in content_type:
|
||||
return None, None, make_response("Expected content-type JSON", 400)
|
||||
|
||||
data = request.json
|
||||
@@ -534,7 +611,9 @@ class SettingsCheckUpdater(webassets.updater.BaseUpdater):
|
||||
|
||||
##~~ plugin assets collector
|
||||
|
||||
def collect_plugin_assets(enable_gcodeviewer=True, enable_timelapse=True, preferred_stylesheet="css"):
|
||||
def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
|
||||
logger = logging.getLogger(__name__ + ".collect_plugin_assets")
|
||||
|
||||
supported_stylesheets = ("css", "less")
|
||||
assets = dict(
|
||||
js=[],
|
||||
@@ -555,6 +634,7 @@ def collect_plugin_assets(enable_gcodeviewer=True, enable_timelapse=True, prefer
|
||||
'js/app/viewmodels/slicing.js',
|
||||
'js/app/viewmodels/temperature.js',
|
||||
'js/app/viewmodels/terminal.js',
|
||||
'js/app/viewmodels/timelapse.js',
|
||||
'js/app/viewmodels/users.js',
|
||||
'js/app/viewmodels/log.js',
|
||||
'js/app/viewmodels/usersettings.js'
|
||||
@@ -566,8 +646,6 @@ def collect_plugin_assets(enable_gcodeviewer=True, enable_timelapse=True, prefer
|
||||
'gcodeviewer/js/gCodeReader.js',
|
||||
'gcodeviewer/js/renderer.js'
|
||||
]
|
||||
if enable_timelapse:
|
||||
assets["js"].append('js/app/viewmodels/timelapse.js')
|
||||
|
||||
if preferred_stylesheet == "less":
|
||||
assets["less"].append('less/octoprint.less')
|
||||
@@ -577,14 +655,29 @@ def collect_plugin_assets(enable_gcodeviewer=True, enable_timelapse=True, prefer
|
||||
asset_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.AssetPlugin)
|
||||
for implementation in asset_plugins:
|
||||
name = implementation._identifier
|
||||
all_assets = implementation.get_assets()
|
||||
try:
|
||||
all_assets = implementation.get_assets()
|
||||
basefolder = implementation.get_asset_folder()
|
||||
except:
|
||||
logger.exception("Got an error while trying to collect assets from {}, ignoring assets from the plugin".format(name))
|
||||
continue
|
||||
|
||||
def asset_exists(category, asset):
|
||||
exists = os.path.exists(os.path.join(basefolder, asset))
|
||||
if not exists:
|
||||
logger.warn("Plugin {} is referring to non existing {} asset {}".format(name, category, asset))
|
||||
return exists
|
||||
|
||||
if "js" in all_assets:
|
||||
for asset in all_assets["js"]:
|
||||
if not asset_exists("js", asset):
|
||||
continue
|
||||
assets["js"].append('plugin/{name}/{asset}'.format(**locals()))
|
||||
|
||||
if preferred_stylesheet in all_assets:
|
||||
for asset in all_assets[preferred_stylesheet]:
|
||||
if not asset_exists(preferred_stylesheet, asset):
|
||||
continue
|
||||
assets[preferred_stylesheet].append('plugin/{name}/{asset}'.format(**locals()))
|
||||
else:
|
||||
for stylesheet in supported_stylesheets:
|
||||
@@ -592,6 +685,8 @@ def collect_plugin_assets(enable_gcodeviewer=True, enable_timelapse=True, prefer
|
||||
continue
|
||||
|
||||
for asset in all_assets[stylesheet]:
|
||||
if not asset_exists(stylesheet, asset):
|
||||
continue
|
||||
assets[stylesheet].append('plugin/{name}/{asset}'.format(**locals()))
|
||||
break
|
||||
|
||||
|
||||
@@ -49,8 +49,23 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.
|
||||
self._remoteAddress = self._getRemoteAddress(info)
|
||||
self._logger.info("New connection from client: %s" % self._remoteAddress)
|
||||
|
||||
plugin_signature = lambda impl: "{}:{}".format(impl._identifier, impl._plugin_version)
|
||||
template_plugins = map(plugin_signature, self._pluginManager.get_implementations(octoprint.plugin.TemplatePlugin))
|
||||
asset_plugins = map(plugin_signature, self._pluginManager.get_implementations(octoprint.plugin.AssetPlugin))
|
||||
ui_plugins = sorted(set(template_plugins + asset_plugins))
|
||||
|
||||
import hashlib
|
||||
plugin_hash = hashlib.md5()
|
||||
plugin_hash.update(",".join(ui_plugins))
|
||||
|
||||
# connected => update the API key, might be necessary if the client was left open while the server restarted
|
||||
self._emit("connected", {"apikey": octoprint.server.UI_API_KEY, "version": octoprint.server.VERSION, "display_version": octoprint.server.DISPLAY_VERSION})
|
||||
self._emit("connected", {
|
||||
"apikey": octoprint.server.UI_API_KEY,
|
||||
"version": octoprint.server.VERSION,
|
||||
"display_version": octoprint.server.DISPLAY_VERSION,
|
||||
"branch": octoprint.server.BRANCH,
|
||||
"plugin_hash": plugin_hash.hexdigest()
|
||||
})
|
||||
|
||||
self._printer.register_callback(self)
|
||||
self._fileManager.register_slicingprogress_callback(self)
|
||||
|
||||
@@ -245,7 +245,7 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
|
||||
self._on_part_header(self._buffer[delimiter_len+2:end_of_header])
|
||||
self._buffer = self._buffer[end_of_header + 4:]
|
||||
|
||||
if delimiter_loc != -1 and self._buffer[delimiter_len:delimiter_len+2] == "--":
|
||||
if delimiter_loc != -1 and self._buffer.strip() == delimiter + "--":
|
||||
# we saw the last boundary and are at the end of our request
|
||||
if self._current_part:
|
||||
self._on_part_finish(self._current_part)
|
||||
@@ -360,13 +360,24 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
|
||||
for name, part in self._parts.iteritems():
|
||||
if "filename" in part:
|
||||
# add form fields for filename, path, size and content_type for all files contained in the request
|
||||
fields = dict((self._suffixes[key], value) for (key, value) in dict(name=part["filename"], path=part["path"], size=str(os.stat(part["path"]).st_size), content_type=part["content_type"]).iteritems())
|
||||
if not "path" in part:
|
||||
continue
|
||||
|
||||
parameters = dict(
|
||||
name=part["filename"],
|
||||
path=part["path"],
|
||||
size=str(os.stat(part["path"]).st_size)
|
||||
)
|
||||
if "content_type" in part:
|
||||
parameters["content_type"] = part["content_type"]
|
||||
|
||||
fields = dict((self._suffixes[key], value) for (key, value) in parameters.iteritems())
|
||||
for n, p in fields.iteritems():
|
||||
key = name + "." + n
|
||||
self._new_body += b"--%s\r\n" % self._multipart_boundary
|
||||
self._new_body += b"Content-Disposition: form-data; name=\"%s\"\r\n" % key
|
||||
self._new_body += b"\r\n"
|
||||
self._new_body += p + b"\r\n"
|
||||
self._new_body += b"%s\r\n" % p
|
||||
elif "data" in part:
|
||||
self._new_body += b"--%s\r\n" % self._multipart_boundary
|
||||
value = part["data"]
|
||||
@@ -757,6 +768,8 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
|
||||
:class:``~tornado.web.StaticFileHandler`` as the ``default_filename`` keyword parameter). Defaults to ``None``.
|
||||
as_attachment (bool): Whether to serve requested files with ``Content-Disposition: attachment`` header (``True``)
|
||||
or not. Defaults to ``False``.
|
||||
allow_client_caching (bool): Whether to allow the client to cache (by not setting any ``Cache-Control`` or
|
||||
``Expires`` headers on the response) or not.
|
||||
access_validation (function): Callback to call in the ``get`` method to validate access to the resource. Will
|
||||
be called with ``self.request`` as parameter which contains the full tornado request object. Should raise
|
||||
a ``tornado.web.HTTPError`` if access is not allowed in which case the request will not be further processed.
|
||||
@@ -765,13 +778,22 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
|
||||
with the requested path as parameter. Should raise a ``tornado.web.HTTPError`` (e.g. an 404) if the requested
|
||||
path does not pass validation in which case the request will not be further processed.
|
||||
Defaults to ``None`` and hence no path validation being performed.
|
||||
etag_generator (function): Callback to call for generating the value of the ETag response header. Will be
|
||||
called with the response handler as parameter. May return ``None`` to prevent the ETag response header
|
||||
from being set. If not provided the last modified time of the file in question will be used as returned
|
||||
by ``get_content_version``.
|
||||
"""
|
||||
|
||||
def initialize(self, path, default_filename=None, as_attachment=False, access_validation=None, path_validation=None):
|
||||
def initialize(self, path, default_filename=None, as_attachment=False, allow_client_caching=True,
|
||||
access_validation=None, path_validation=None, etag_generator=None,
|
||||
mime_type_guesser=None):
|
||||
tornado.web.StaticFileHandler.initialize(self, os.path.abspath(path), default_filename)
|
||||
self._as_attachment = as_attachment
|
||||
self._allow_client_caching = allow_client_caching
|
||||
self._access_validation = access_validation
|
||||
self._path_validation = path_validation
|
||||
self._etag_generator = etag_generator
|
||||
self._mime_type_guesser = mime_type_guesser
|
||||
|
||||
def get(self, path, include_body=True):
|
||||
if self._access_validation is not None:
|
||||
@@ -785,6 +807,24 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
|
||||
if self._as_attachment:
|
||||
self.set_header("Content-Disposition", "attachment")
|
||||
|
||||
if not self._allow_client_caching:
|
||||
self.set_header("Cache-Control", "max-age=0, must-revalidate, private")
|
||||
self.set_header("Expires", "-1")
|
||||
|
||||
def compute_etag(self):
|
||||
if self._etag_generator is not None:
|
||||
return self._etag_generator(self)
|
||||
else:
|
||||
return self.get_content_version(self.absolute_path)
|
||||
|
||||
def get_content_type(self):
|
||||
if self._mime_type_guesser is not None:
|
||||
type = self._mime_type_guesser(self.absolute_path)
|
||||
if type is not None:
|
||||
return type
|
||||
|
||||
return tornado.web.StaticFileHandler.get_content_type(self)
|
||||
|
||||
@classmethod
|
||||
def get_content_version(cls, abspath):
|
||||
import os
|
||||
@@ -794,7 +834,7 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
|
||||
##~~ URL Forward Handler for forwarding requests to a preconfigured static URL
|
||||
|
||||
|
||||
class UrlForwardHandler(tornado.web.RequestHandler):
|
||||
class UrlProxyHandler(tornado.web.RequestHandler):
|
||||
"""
|
||||
`tornado.web.RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>`_ that proxies
|
||||
requests to a preconfigured url and returns the response. Allows delivery of the requested content as attachment
|
||||
@@ -804,7 +844,7 @@ class UrlForwardHandler(tornado.web.RequestHandler):
|
||||
for making the request to the configured endpoint and return the body of the client response with the status code
|
||||
from the client response and the following headers:
|
||||
|
||||
* ``Date``, ``Cache-Control``, ``Server``, ``Content-Type`` and ``Location`` will be copied over.
|
||||
* ``Date``, ``Cache-Control``, ``Expires``, ``ETag``, ``Server``, ``Content-Type`` and ``Location`` will be copied over.
|
||||
* If ``as_attachment`` is set to True, ``Content-Disposition`` will be set to ``attachment``. If ``basename`` is
|
||||
set including the attachement's ``filename`` attribute will be set to the base name followed by the extension
|
||||
guessed based on the MIME type from the ``Content-Type`` header of the response. If no extension can be guessed
|
||||
@@ -854,7 +894,7 @@ class UrlForwardHandler(tornado.web.RequestHandler):
|
||||
filename = None
|
||||
|
||||
self.set_status(response.code)
|
||||
for name in ("Date", "Cache-Control", "Server", "Content-Type", "Location"):
|
||||
for name in ("Date", "Cache-Control", "Server", "Content-Type", "Location", "Expires", "ETag"):
|
||||
value = response.headers.get(name)
|
||||
if value:
|
||||
self.set_header(name, value)
|
||||
@@ -924,4 +964,4 @@ def path_validation_factory(path_filter, status_code=404):
|
||||
def f(path):
|
||||
if not path_filter(path):
|
||||
raise tornado.web.HTTPError(status_code)
|
||||
return f
|
||||
return f
|
||||
@@ -56,6 +56,11 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
|
||||
file_wrapper.filename,
|
||||
file_wrapper,
|
||||
allow_overwrite=True)
|
||||
if os.path.exists(path):
|
||||
try:
|
||||
os.remove(path)
|
||||
except:
|
||||
self._logger.exception("Error while trying to clear a file from the watched folder")
|
||||
|
||||
def on_created(self, event):
|
||||
self._upload(event.src_path)
|
||||
@@ -12,16 +12,24 @@ from flask import request, g, url_for, make_response, render_template, send_from
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
from octoprint.server import app, userManager, pluginManager, gettext, debug, LOCALES, VERSION, DISPLAY_VERSION, UI_API_KEY
|
||||
from octoprint.server import app, userManager, pluginManager, gettext, \
|
||||
debug, LOCALES, VERSION, DISPLAY_VERSION, UI_API_KEY, BRANCH
|
||||
from octoprint.settings import settings
|
||||
|
||||
import re
|
||||
|
||||
from . import util
|
||||
|
||||
import logging
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
_valid_id_re = re.compile("[a-z_]+")
|
||||
_valid_div_re = re.compile("[a-zA-Z_-]+")
|
||||
|
||||
@app.route("/")
|
||||
@util.flask.cached(refreshif=lambda: util.flask.cache_check_headers() or "_refresh" in request.values, key=lambda: "view/%s/%s" % (request.path, g.locale))
|
||||
@util.flask.cached(refreshif=lambda: util.flask.cache_check_headers() or "_refresh" in request.values,
|
||||
key=lambda: "view/%s/%s" % (request.path, g.locale),
|
||||
unless_response=util.flask.cache_check_response_headers)
|
||||
def index():
|
||||
|
||||
#~~ a bunch of settings
|
||||
@@ -148,6 +156,7 @@ def index():
|
||||
folders=(gettext("Folders"), dict(template="dialogs/settings/folders.jinja2", _div="settings_folders", custom_bindings=False)),
|
||||
appearance=(gettext("Appearance"), dict(template="dialogs/settings/appearance.jinja2", _div="settings_appearance", custom_bindings=False)),
|
||||
logs=(gettext("Logs"), dict(template="dialogs/settings/logs.jinja2", _div="settings_logs")),
|
||||
server=(gettext("Server"), dict(template="dialogs/settings/server.jinja2", _div="settings_server", custom_bindings=False)),
|
||||
)
|
||||
if enable_accesscontrol:
|
||||
templates["settings"]["entries"]["accesscontrol"] = (gettext("Access Control"), dict(template="dialogs/settings/accesscontrol.jinja2", _div="settings_users", custom_bindings=False))
|
||||
@@ -170,17 +179,21 @@ def index():
|
||||
name = implementation._identifier
|
||||
plugin_names.add(name)
|
||||
|
||||
vars = implementation.get_template_vars()
|
||||
try:
|
||||
vars = implementation.get_template_vars()
|
||||
configs = implementation.get_template_configs()
|
||||
except:
|
||||
_logger.exception("Error while retrieving template data for plugin {}, ignoring it".format(name))
|
||||
continue
|
||||
|
||||
if not isinstance(vars, dict):
|
||||
vars = dict()
|
||||
if not isinstance(configs, (list, tuple)):
|
||||
configs = []
|
||||
|
||||
for var_name, var_value in vars.items():
|
||||
plugin_vars["plugin_" + name + "_" + var_name] = var_value
|
||||
|
||||
configs = implementation.get_template_configs()
|
||||
if not isinstance(configs, (list, tuple)):
|
||||
configs = []
|
||||
|
||||
includes = _process_template_configs(name, implementation, configs, template_rules)
|
||||
|
||||
for t in template_types:
|
||||
@@ -223,9 +236,30 @@ def index():
|
||||
# finally add anything that's not included in our order yet
|
||||
sorted_missing = list(missing_in_order)
|
||||
if template_sorting[t]["key"] is not None:
|
||||
# anything but navbar and generic components get sorted by their name
|
||||
if template_sorting[t]["key"] == "name":
|
||||
sorted_missing = sorted(missing_in_order, key=lambda x: templates[t]["entries"][x][0])
|
||||
# default extractor: works with entries that are dicts and entries that are 2-tuples with the
|
||||
# entry data at index 1
|
||||
def extractor(item, key):
|
||||
if isinstance(item, dict) and key in item:
|
||||
return item[key]
|
||||
elif isinstance(item, tuple) and len(item) > 1 and isinstance(item[1], dict) and key in item[1]:
|
||||
return item[1][key]
|
||||
|
||||
return None
|
||||
|
||||
# if template type provides custom extractor, make sure its exceptions are handled
|
||||
if "key_extractor" in template_sorting[t] and callable(template_sorting[t]["key_extractor"]):
|
||||
def create_safe_extractor(extractor):
|
||||
def f(x, k):
|
||||
try:
|
||||
return extractor(x, k)
|
||||
except:
|
||||
_logger.exception("Error while extracting sorting keys for template {}".format(t))
|
||||
return None
|
||||
return f
|
||||
extractor = create_safe_extractor(template_sorting[t]["key_extractor"])
|
||||
|
||||
sort_key = template_sorting[t]["key"]
|
||||
sorted_missing = sorted(missing_in_order, key=lambda x: extractor(templates[t]["entries"][x], sort_key))
|
||||
|
||||
if template_sorting[t]["add"] == "prepend":
|
||||
templates[t]["order"] = sorted_missing + templates[t]["order"]
|
||||
@@ -240,15 +274,17 @@ def index():
|
||||
|
||||
#~~ prepare full set of template vars for rendering
|
||||
|
||||
first_run = settings().getBoolean(["server", "firstRun"]) and (userManager is None or not userManager.hasBeenCustomized())
|
||||
render_kwargs = dict(
|
||||
webcamStream=settings().get(["webcam", "stream"]),
|
||||
enableTemperatureGraph=settings().get(["feature", "temperatureGraph"]),
|
||||
enableAccessControl=userManager is not None,
|
||||
enableSdSupport=settings().get(["feature", "sdSupport"]),
|
||||
firstRun=settings().getBoolean(["server", "firstRun"]) and (userManager is None or not userManager.hasBeenCustomized()),
|
||||
firstRun=first_run,
|
||||
debug=debug,
|
||||
version=VERSION,
|
||||
display_version=DISPLAY_VERSION,
|
||||
branch=BRANCH,
|
||||
gcodeMobileThreshold=settings().get(["gcodeViewer", "mobileSizeThreshold"]),
|
||||
gcodeThreshold=settings().get(["gcodeViewer", "sizeThreshold"]),
|
||||
uiApiKey=UI_API_KEY,
|
||||
@@ -260,10 +296,18 @@ def index():
|
||||
|
||||
#~~ render!
|
||||
|
||||
return render_template(
|
||||
import datetime
|
||||
|
||||
response = make_response(render_template(
|
||||
"index.jinja2",
|
||||
**render_kwargs
|
||||
)
|
||||
))
|
||||
response.headers["Last-Modified"] = datetime.datetime.now()
|
||||
|
||||
if first_run:
|
||||
response = util.flask.add_non_caching_response_headers(response)
|
||||
|
||||
return response
|
||||
|
||||
|
||||
def _process_template_configs(name, implementation, configs, rules):
|
||||
@@ -302,6 +346,8 @@ def _process_template_configs(name, implementation, configs, rules):
|
||||
app.jinja_env.get_or_select_template(data["template"])
|
||||
except TemplateNotFound:
|
||||
pass
|
||||
except:
|
||||
_logger.exception("Error in template {}, not going to include it".format(data["template"]))
|
||||
else:
|
||||
includes[template_type].append(rule["to_entry"](data))
|
||||
|
||||
@@ -326,6 +372,9 @@ def _process_template_config(name, implementation, rule, config=None, counter=1)
|
||||
data["_div"] = rule["div"](name)
|
||||
if "suffix" in data:
|
||||
data["_div"] = data["_div"] + data["suffix"]
|
||||
if not _valid_div_re.match(data["_div"]):
|
||||
_logger.warn("Template config {} contains invalid div identifier {}, skipping it".format(name, data["_div"]))
|
||||
return None
|
||||
|
||||
if not "template" in data:
|
||||
data["template"] = rule["template"](name)
|
||||
@@ -337,6 +386,7 @@ def _process_template_config(name, implementation, rule, config=None, counter=1)
|
||||
data_bind = "allowBindings: true"
|
||||
if "data_bind" in data:
|
||||
data_bind = data_bind + ", " + data["data_bind"]
|
||||
data_bind = data_bind.replace("\"", "\\\"")
|
||||
data["data_bind"] = data_bind
|
||||
|
||||
data["_key"] = "plugin_" + name
|
||||
|
||||
+61
-36
@@ -30,6 +30,8 @@ import logging
|
||||
import re
|
||||
import uuid
|
||||
|
||||
from octoprint.util import atomic_write
|
||||
|
||||
_APPNAME = "OctoPrint"
|
||||
|
||||
_instance = None
|
||||
@@ -104,6 +106,15 @@ default_settings = {
|
||||
"pathSuffix": "path"
|
||||
},
|
||||
"maxSize": 100 * 1024, # 100 KB
|
||||
"commands": {
|
||||
"systemShutdownCommand": None,
|
||||
"systemRestartCommand": None,
|
||||
"serverRestartCommand": None
|
||||
},
|
||||
"diskspace": {
|
||||
"warning": 500 * 1024 * 1024, # 500 MB
|
||||
"critical": 200 * 1024 * 1024, # 200 MB
|
||||
}
|
||||
},
|
||||
"webcam": {
|
||||
"stream": None,
|
||||
@@ -142,7 +153,10 @@ default_settings = {
|
||||
"repetierTargetTemp": False,
|
||||
"externalHeatupDetection": True,
|
||||
"supportWait": True,
|
||||
"keyboardControl": True
|
||||
"keyboardControl": True,
|
||||
"pollWatched": False,
|
||||
"ignoreIdenticalResends": False,
|
||||
"identicalResendsCountdown": 7
|
||||
},
|
||||
"folder": {
|
||||
"uploads": None,
|
||||
@@ -156,7 +170,8 @@ default_settings = {
|
||||
"printerProfiles": None,
|
||||
"scripts": None,
|
||||
"translations": None,
|
||||
"generated": None
|
||||
"generated": None,
|
||||
"data": None
|
||||
},
|
||||
"temperature": {
|
||||
"profiles": [
|
||||
@@ -186,7 +201,7 @@ default_settings = {
|
||||
"settings": [
|
||||
"section_printer", "serial", "printerprofiles", "temperatures", "terminalfilters", "gcodescripts",
|
||||
"section_features", "features", "webcam", "accesscontrol", "api",
|
||||
"section_octoprint", "folders", "appearance", "logs", "plugin_pluginmanager", "plugin_softwareupdate"
|
||||
"section_octoprint", "server", "folders", "appearance", "logs", "plugin_pluginmanager", "plugin_softwareupdate"
|
||||
],
|
||||
"usersettings": ["access", "interface"],
|
||||
"generic": []
|
||||
@@ -251,7 +266,8 @@ default_settings = {
|
||||
},
|
||||
"webassets": {
|
||||
"minify": False,
|
||||
"bundle": True
|
||||
"bundle": True,
|
||||
"clean_on_startup": True
|
||||
},
|
||||
"virtualPrinter": {
|
||||
"enabled": False,
|
||||
@@ -268,6 +284,7 @@ default_settings = {
|
||||
},
|
||||
"hasBed": True,
|
||||
"repetierStyleTargetTemperature": False,
|
||||
"repetierStyleResends": False,
|
||||
"okBeforeCommandOutput": False,
|
||||
"smoothieTemperatureReporting": False,
|
||||
"extendedSdFileList": False,
|
||||
@@ -277,7 +294,8 @@ default_settings = {
|
||||
"txBuffer": 40,
|
||||
"commandBuffer": 4,
|
||||
"sendWait": True,
|
||||
"waitInterval": 1.0
|
||||
"waitInterval": 1.0,
|
||||
"supportM112": True
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -318,14 +336,14 @@ class Settings(object):
|
||||
|
||||
"/dev/ttyACM0"
|
||||
|
||||
``["serial", "timeouts"]`` ::
|
||||
``["serial", "timeout"]`` ::
|
||||
|
||||
communication: 20.0
|
||||
temperature: 5.0
|
||||
sdStatus: 1.0
|
||||
connection: 10.0
|
||||
|
||||
``["serial", "timeouts", "temperature"]`` ::
|
||||
``["serial", "timeout", "temperature"]`` ::
|
||||
|
||||
5.0
|
||||
|
||||
@@ -771,11 +789,17 @@ class Settings(object):
|
||||
if not self._dirty and not force:
|
||||
return False
|
||||
|
||||
with open(self._configfile, "wb") as configFile:
|
||||
yaml.safe_dump(self._config, configFile, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
self._dirty = False
|
||||
self.load()
|
||||
return True
|
||||
from octoprint.util import atomic_write
|
||||
try:
|
||||
with atomic_write(self._configfile, "wb", prefix="octoprint-config-", suffix=".yaml") as configFile:
|
||||
yaml.safe_dump(self._config, configFile, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
self._dirty = False
|
||||
except:
|
||||
self._logger.exception("Error while saving config.yaml!")
|
||||
raise
|
||||
else:
|
||||
self.load()
|
||||
return True
|
||||
|
||||
@property
|
||||
def last_modified(self):
|
||||
@@ -788,7 +812,7 @@ class Settings(object):
|
||||
|
||||
#~~ getter
|
||||
|
||||
def get(self, path, asdict=False, config=None, defaults=None, preprocessors=None, merged=False):
|
||||
def get(self, path, asdict=False, config=None, defaults=None, preprocessors=None, merged=False, incl_defaults=True):
|
||||
import octoprint.util as util
|
||||
|
||||
if len(path) == 0:
|
||||
@@ -806,7 +830,7 @@ class Settings(object):
|
||||
if key in config and key in defaults:
|
||||
config = config[key]
|
||||
defaults = defaults[key]
|
||||
elif key in defaults:
|
||||
elif incl_defaults and key in defaults:
|
||||
config = {}
|
||||
defaults = defaults[key]
|
||||
else:
|
||||
@@ -831,7 +855,7 @@ class Settings(object):
|
||||
value = config[key]
|
||||
if merged and key in defaults:
|
||||
value = util.dict_merge(defaults[key], value)
|
||||
elif key in defaults:
|
||||
elif incl_defaults and key in defaults:
|
||||
value = defaults[key]
|
||||
else:
|
||||
value = None
|
||||
@@ -852,8 +876,8 @@ class Settings(object):
|
||||
else:
|
||||
return results
|
||||
|
||||
def getInt(self, path, config=None, defaults=None, preprocessors=None):
|
||||
value = self.get(path, defaults=defaults, preprocessors=preprocessors)
|
||||
def getInt(self, path, config=None, defaults=None, preprocessors=None, incl_defaults=True):
|
||||
value = self.get(path, config=config, defaults=defaults, preprocessors=preprocessors, incl_defaults=incl_defaults)
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
@@ -863,8 +887,8 @@ class Settings(object):
|
||||
self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path))
|
||||
return None
|
||||
|
||||
def getFloat(self, path, config=None, defaults=None, preprocessors=None):
|
||||
value = self.get(path, config=config, defaults=defaults, preprocessors=preprocessors)
|
||||
def getFloat(self, path, config=None, defaults=None, preprocessors=None, incl_defaults=True):
|
||||
value = self.get(path, config=config, defaults=defaults, preprocessors=preprocessors, incl_defaults=incl_defaults)
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
@@ -874,8 +898,8 @@ class Settings(object):
|
||||
self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path))
|
||||
return None
|
||||
|
||||
def getBoolean(self, path, config=None, defaults=None, preprocessors=None):
|
||||
value = self.get(path, config=config, defaults=defaults, preprocessors=preprocessors)
|
||||
def getBoolean(self, path, config=None, defaults=None, preprocessors=None, incl_defaults=True):
|
||||
value = self.get(path, config=config, defaults=defaults, preprocessors=preprocessors, incl_defaults=incl_defaults)
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, bool):
|
||||
@@ -930,14 +954,15 @@ class Settings(object):
|
||||
|
||||
#~~ setter
|
||||
|
||||
def set(self, path, value, force=False, defaults=None, preprocessors=None):
|
||||
def set(self, path, value, force=False, defaults=None, config=None, preprocessors=None):
|
||||
if len(path) == 0:
|
||||
return
|
||||
|
||||
if self._mtime is not None and self.last_modified != self._mtime:
|
||||
self.load()
|
||||
|
||||
config = self._config
|
||||
if config is None:
|
||||
config = self._config
|
||||
if defaults is None:
|
||||
defaults = default_settings
|
||||
if preprocessors is None:
|
||||
@@ -966,16 +991,16 @@ class Settings(object):
|
||||
if not force and key in defaults and key in config and defaults[key] == value:
|
||||
del config[key]
|
||||
self._dirty = True
|
||||
elif force or (not key in config and defaults[key] != value) or (key in config and config[key] != value):
|
||||
if value is None:
|
||||
elif force or (not key in config and key in defaults and defaults[key] != value) or (key in config and config[key] != value):
|
||||
if value is None and key in config:
|
||||
del config[key]
|
||||
else:
|
||||
config[key] = value
|
||||
self._dirty = True
|
||||
|
||||
def setInt(self, path, value, force=False, defaults=None, preprocessors=None):
|
||||
def setInt(self, path, value, force=False, defaults=None, config=None, preprocessors=None):
|
||||
if value is None:
|
||||
self.set(path, None, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
self.set(path, None, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
return
|
||||
|
||||
try:
|
||||
@@ -984,11 +1009,11 @@ class Settings(object):
|
||||
self._logger.warn("Could not convert %r to a valid integer when setting option %r" % (value, path))
|
||||
return
|
||||
|
||||
self.set(path, intValue, force)
|
||||
self.set(path, intValue, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
|
||||
def setFloat(self, path, value, force=False, defaults=None, preprocessors=None):
|
||||
def setFloat(self, path, value, force=False, defaults=None, config=None, preprocessors=None):
|
||||
if value is None:
|
||||
self.set(path, None, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
self.set(path, None, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
return
|
||||
|
||||
try:
|
||||
@@ -997,15 +1022,15 @@ class Settings(object):
|
||||
self._logger.warn("Could not convert %r to a valid integer when setting option %r" % (value, path))
|
||||
return
|
||||
|
||||
self.set(path, floatValue, force)
|
||||
self.set(path, floatValue, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
|
||||
def setBoolean(self, path, value, force=False, defaults=None, preprocessors=None):
|
||||
def setBoolean(self, path, value, force=False, defaults=None, config=None, preprocessors=None):
|
||||
if value is None or isinstance(value, bool):
|
||||
self.set(path, value, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
self.set(path, value, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
elif value.lower() in valid_boolean_trues:
|
||||
self.set(path, True, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
self.set(path, True, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
else:
|
||||
self.set(path, False, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
self.set(path, False, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
|
||||
def setBaseFolder(self, type, path, force=False):
|
||||
if type not in default_settings["folder"].keys():
|
||||
@@ -1034,7 +1059,7 @@ class Settings(object):
|
||||
path, _ = os.path.split(filename)
|
||||
if not os.path.exists(path):
|
||||
os.makedirs(path)
|
||||
with open(filename, "w+") as f:
|
||||
with atomic_write(filename, "wb") as f:
|
||||
f.write(script)
|
||||
|
||||
def _default_basedir(applicationName):
|
||||
|
||||
@@ -24,6 +24,8 @@ import octoprint.plugin
|
||||
import octoprint.events
|
||||
from octoprint.settings import settings
|
||||
|
||||
import logging
|
||||
|
||||
from .exceptions import *
|
||||
|
||||
|
||||
@@ -102,6 +104,8 @@ class SlicingManager(object):
|
||||
"""
|
||||
|
||||
def __init__(self, profile_path, printer_profile_manager):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._profile_path = profile_path
|
||||
self._printer_profile_manager = printer_profile_manager
|
||||
|
||||
@@ -123,7 +127,11 @@ class SlicingManager(object):
|
||||
plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SlicerPlugin)
|
||||
slicers = dict()
|
||||
for plugin in plugins:
|
||||
slicers[plugin.get_slicer_properties()["type"]] = plugin
|
||||
try:
|
||||
slicers[plugin.get_slicer_properties()["type"]] = plugin
|
||||
except:
|
||||
self._logger.exception("Error while getting properties from slicer {}, ignoring it".format(plugin._identifier))
|
||||
continue
|
||||
self._slicers = slicers
|
||||
|
||||
@property
|
||||
|
||||
@@ -33,7 +33,7 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
class SlicingException(BaseException):
|
||||
class SlicingException(Exception):
|
||||
"""
|
||||
Base exception of all slicing related exceptions.
|
||||
"""
|
||||
@@ -54,7 +54,7 @@ class SlicerException(SlicingException):
|
||||
Identifier of the slicer for which the exception was raised.
|
||||
"""
|
||||
def __init__(self, slicer, *args, **kwargs):
|
||||
super(SlicingException, self).__init__(*args, **kwargs)
|
||||
SlicingException.__init__(self, *args, **kwargs)
|
||||
self.slicer = slicer
|
||||
|
||||
class SlicerNotConfigured(SlicerException):
|
||||
@@ -62,7 +62,7 @@ class SlicerNotConfigured(SlicerException):
|
||||
Raised if a slicer is not yet configured but must be configured to proceed.
|
||||
"""
|
||||
def __init__(self, slicer, *args, **kwargs):
|
||||
super(SlicerException, self).__init__(slicer, *args, **kwargs)
|
||||
SlicerException.__init__(self, slicer, *args, **kwargs)
|
||||
self.message = "Slicer not configured: {slicer}".format(slicer=slicer)
|
||||
|
||||
class UnknownSlicer(SlicerException):
|
||||
@@ -70,10 +70,10 @@ class UnknownSlicer(SlicerException):
|
||||
Raised if a slicer is unknown.
|
||||
"""
|
||||
def __init__(self, slicer, *args, **kwargs):
|
||||
super(SlicerException, self).__init__(slicer, *args, **kwargs)
|
||||
SlicerException.__init__(self, slicer, *args, **kwargs)
|
||||
self.message = "No such slicer: {slicer}".format(slicer=slicer)
|
||||
|
||||
class ProfileException(BaseException):
|
||||
class ProfileException(Exception):
|
||||
"""
|
||||
Base exception of all slicing profile related exceptions.
|
||||
|
||||
@@ -86,7 +86,7 @@ class ProfileException(BaseException):
|
||||
Identifier of the profile for which the exception was raised.
|
||||
"""
|
||||
def __init__(self, slicer, profile, *args, **kwargs):
|
||||
super(BaseException, self).__init__(*args, **kwargs)
|
||||
Exception.__init__(self, *args, **kwargs)
|
||||
self.slicer = slicer
|
||||
self.profile = profile
|
||||
|
||||
@@ -95,7 +95,7 @@ class UnknownProfile(ProfileException):
|
||||
Raised if a slicing profile does not exist but must exist to proceed.
|
||||
"""
|
||||
def __init__(self, slicer, profile, *args, **kwargs):
|
||||
super(ProfileException, self).__init__(slicer, profile, *args, **kwargs)
|
||||
ProfileException.__init__(self, slicer, profile, *args, **kwargs)
|
||||
self.message = "Profile {profile} for slicer {slicer} does not exist".format(profile=profile, slicer=slicer)
|
||||
|
||||
class ProfileAlreadyExists(ProfileException):
|
||||
@@ -103,5 +103,5 @@ class ProfileAlreadyExists(ProfileException):
|
||||
Raised if a slicing profile already exists and must not be overwritten.
|
||||
"""
|
||||
def __init__(self, slicer, profile, *args, **kwargs):
|
||||
super(ProfileException, self).__init__(slicer, profile, *args, **kwargs)
|
||||
self.message = "Profile {profile} for slicer {slicer} already exists".format(profile=profile, slicer=slicer)
|
||||
ProfileException.__init__(self, slicer, profile, *args, **kwargs)
|
||||
self.message = "Profile {profile} for slicer {slicer} already exists".format(profile=profile, slicer=slicer)
|
||||
@@ -1 +1 @@
|
||||
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-warning:hover,.btn-warning:focus,.btn-warning:aLine truncated
|
||||
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-warning:hover,.btn-warning:focus,.btn-warning:aLine truncated
|
||||
@@ -9,6 +9,11 @@ function DataUpdater(allViewModels) {
|
||||
self._autoReconnectTimeouts = [0, 1, 1, 2, 3, 5, 8, 13, 20, 40, 100];
|
||||
self._autoReconnectDialogIndex = 1;
|
||||
|
||||
self._pluginHash = undefined;
|
||||
|
||||
self.reloadOverlay = $("#reloadui_overlay");
|
||||
$("#reloadui_overlay_reload").click(function() { location.reload(true); });
|
||||
|
||||
self.connect = function() {
|
||||
var options = {};
|
||||
if (SOCKJS_DEBUG) {
|
||||
@@ -117,8 +122,12 @@ function DataUpdater(allViewModels) {
|
||||
var oldVersion = VERSION;
|
||||
VERSION = data["version"];
|
||||
DISPLAY_VERSION = data["display_version"];
|
||||
BRANCH = data["branch"];
|
||||
$("span.version").text(DISPLAY_VERSION);
|
||||
|
||||
var oldPluginHash = self._pluginHash;
|
||||
self._pluginHash = data["plugin_hash"];
|
||||
|
||||
if ($("#offline_overlay").is(":visible")) {
|
||||
hideOfflineOverlay();
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
@@ -132,13 +141,8 @@ function DataUpdater(allViewModels) {
|
||||
}
|
||||
}
|
||||
|
||||
if (oldVersion != VERSION) {
|
||||
// version change detected, force reloading UI - use randomized delay to reduce server load in
|
||||
// the case of multiple clients
|
||||
var delay = 5 + Math.floor(Math.random() * 5) + 1;
|
||||
setTimeout(function() {location.reload(true);}, delay * 1000);
|
||||
|
||||
// TODO notify about that, or show confirmation
|
||||
if (oldVersion != VERSION || (oldPluginHash != undefined && oldPluginHash != self._pluginHash)) {
|
||||
self.reloadOverlay.show();
|
||||
}
|
||||
|
||||
break;
|
||||
@@ -173,6 +177,7 @@ function DataUpdater(allViewModels) {
|
||||
var type = data["type"];
|
||||
var payload = data["payload"];
|
||||
var html = "";
|
||||
var format = {};
|
||||
|
||||
log.debug("Got event " + type + " with payload: " + JSON.stringify(payload));
|
||||
|
||||
@@ -183,7 +188,31 @@ function DataUpdater(allViewModels) {
|
||||
} else if (type == "MovieFailed") {
|
||||
html = "<p>" + _.sprintf(gettext("Rendering of timelapse %(movie_basename)s failed with return code %(returncode)s"), payload) + "</p>";
|
||||
html += pnotifyAdditionalInfo('<pre style="overflow: auto">' + payload.error + '</pre>');
|
||||
new PNotify({title: gettext("Rendering failed"), text: html, type: "error", hide: false});
|
||||
new PNotify({
|
||||
title: gettext("Rendering failed"),
|
||||
text: html,
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
} else if (type == "PostRollStart") {
|
||||
var title = gettext("Capturing timelapse postroll");
|
||||
|
||||
var text;
|
||||
if (!payload.postroll_duration) {
|
||||
text = _.sprintf(gettext("Now capturing timelapse post roll, this will take only a moment..."), format);
|
||||
} else {
|
||||
if (payload.postroll_duration > 60) {
|
||||
format = {duration: _.sprintf(gettext("%(minutes)d min"), {minutes: payload.postroll_duration / 60})};
|
||||
} else {
|
||||
format = {duration: _.sprintf(gettext("%(seconds)d sec"), {seconds: payload.postroll_duration})};
|
||||
}
|
||||
text = _.sprintf(gettext("Now capturing timelapse post roll, this will take approximately %(duration)s..."), format);
|
||||
}
|
||||
|
||||
new PNotify({
|
||||
title: title,
|
||||
text: text
|
||||
});
|
||||
} else if (type == "SlicingStarted") {
|
||||
gcodeUploadProgress.addClass("progress-striped").addClass("active");
|
||||
gcodeUploadProgressBar.css("width", "100%");
|
||||
|
||||
@@ -333,6 +333,34 @@ function formatSize(bytes) {
|
||||
return _.sprintf("%.1f%s", bytes, "TB");
|
||||
}
|
||||
|
||||
function bytesFromSize(size) {
|
||||
if (size == undefined || size.trim() == "") return undefined;
|
||||
|
||||
var parsed = size.match(/^([+]?[0-9]*\.?[0-9]+)(?:\s*)?(.*)$/);
|
||||
var number = parsed[1];
|
||||
var unit = parsed[2].trim();
|
||||
|
||||
if (unit == "") return parseFloat(number);
|
||||
|
||||
var units = {
|
||||
b: 1,
|
||||
byte: 1,
|
||||
bytes: 1,
|
||||
kb: 1024,
|
||||
mb: Math.pow(1024, 2),
|
||||
gb: Math.pow(1024, 3),
|
||||
tb: Math.pow(1024, 4)
|
||||
};
|
||||
unit = unit.toLowerCase();
|
||||
|
||||
if (!units.hasOwnProperty(unit)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
var factor = units[unit];
|
||||
return number * factor;
|
||||
}
|
||||
|
||||
function formatDuration(seconds) {
|
||||
if (!seconds) return "-";
|
||||
if (seconds < 0) return "00:00:00";
|
||||
@@ -461,3 +489,17 @@ function splitTextToArray(text, sep, stripEmpty, filter) {
|
||||
function(item) { return (stripEmpty ? item : true) && (filter ? filter(item) : true); }
|
||||
);
|
||||
}
|
||||
|
||||
var sizeObservable = function(observable) {
|
||||
return ko.computed({
|
||||
read: function() {
|
||||
return formatSize(observable());
|
||||
},
|
||||
write: function(value) {
|
||||
var result = bytesFromSize(value);
|
||||
if (result != undefined) {
|
||||
observable(result);
|
||||
}
|
||||
}
|
||||
})
|
||||
};
|
||||
@@ -21,6 +21,15 @@ $(function() {
|
||||
headers: {"X-Api-Key": UI_API_KEY}
|
||||
});
|
||||
|
||||
//~~ Initialize file upload plugin
|
||||
|
||||
$.widget("blueimp.fileupload", $.blueimp.fileupload, {
|
||||
options: {
|
||||
dropZone: null,
|
||||
pasteZone: null
|
||||
}
|
||||
});
|
||||
|
||||
//~~ Initialize i18n
|
||||
|
||||
var catalog = window["BABEL_TO_LOAD_" + LOCALE];
|
||||
@@ -51,6 +60,7 @@ $(function() {
|
||||
//~~ Initialize PNotify
|
||||
|
||||
PNotify.prototype.options.styling = "bootstrap2";
|
||||
PNotify.prototype.options.mouse_reset = false;
|
||||
|
||||
//~~ Initialize view models
|
||||
|
||||
@@ -58,7 +68,7 @@ $(function() {
|
||||
var viewModelMap = {};
|
||||
|
||||
// Fix Function#name on browsers that do not support it (IE):
|
||||
// see: http://stackoverflow.com/questions/6903762/function-name-not-supported-in-ie
|
||||
// see: http://stackoverflow.com/questions/6903762/function-name-not-supported-in-ie
|
||||
if (!(function f() {}).name) {
|
||||
Object.defineProperty(Function.prototype, 'name', {
|
||||
get: function() {
|
||||
@@ -320,7 +330,7 @@ $(function() {
|
||||
.data("contextParent", $(this))
|
||||
.show()
|
||||
.css({
|
||||
position: "absolute",
|
||||
position: "fixed",
|
||||
left: getMenuPosition(e.clientX, 'width', 'scrollLeft'),
|
||||
top: getMenuPosition(e.clientY, 'height', 'scrollTop'),
|
||||
"z-index": 9999
|
||||
|
||||
@@ -86,6 +86,15 @@ $(function() {
|
||||
self._processStateData(data.state);
|
||||
};
|
||||
|
||||
self.openOrCloseOnStateChange = function() {
|
||||
var connectionTab = $("#connection");
|
||||
if (self.isOperational() && connectionTab.hasClass("in")) {
|
||||
connectionTab.collapse("hide");
|
||||
} else if (!self.isOperational() && !connectionTab.hasClass("in")) {
|
||||
connectionTab.collapse("show");
|
||||
}
|
||||
}
|
||||
|
||||
self._processStateData = function(data) {
|
||||
self.previousIsOperational = self.isOperational();
|
||||
|
||||
@@ -97,15 +106,10 @@ $(function() {
|
||||
self.isReady(data.flags.ready);
|
||||
self.isLoading(data.flags.loading);
|
||||
|
||||
var connectionTab = $("#connection");
|
||||
if (self.previousIsOperational != self.isOperational()) {
|
||||
if (self.isOperational() && connectionTab.hasClass("in")) {
|
||||
// connection just got established, close connection tab for now
|
||||
connectionTab.collapse("hide");
|
||||
} else if (!connectionTab.hasClass("in")) {
|
||||
// connection just dropped, make sure connection tab is open
|
||||
connectionTab.collapse("show");
|
||||
}
|
||||
if (self.loginState.isAdmin() && self.previousIsOperational != self.isOperational()) {
|
||||
// only open or close if the panel is visible (for admins) and
|
||||
// the state just changed to avoid thwarting manual open/close
|
||||
self.openOrCloseOnStateChange();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -147,6 +151,16 @@ $(function() {
|
||||
|
||||
self.onStartup = function() {
|
||||
self.requestData();
|
||||
|
||||
// when isAdmin becomes true the first time, set the panel open or
|
||||
// closed based on the connection state
|
||||
var subscription = self.loginState.isAdmin.subscribe(function(newValue) {
|
||||
if (newValue) {
|
||||
// wait until after the isAdmin state has run through all subscriptions
|
||||
setTimeout(self.openOrCloseOnStateChange, 0);
|
||||
subscription.dispose();
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -2,9 +2,10 @@ $(function() {
|
||||
function GcodeFilesViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.printerState = parameters[0];
|
||||
self.settingsViewModel = parameters[0];
|
||||
self.loginState = parameters[1];
|
||||
self.slicing = parameters[2];
|
||||
self.printerState = parameters[2];
|
||||
self.slicing = parameters[3];
|
||||
|
||||
self.isErrorOrClosed = ko.observable(undefined);
|
||||
self.isOperational = ko.observable(undefined);
|
||||
@@ -21,11 +22,35 @@ $(function() {
|
||||
});
|
||||
|
||||
self.freeSpace = ko.observable(undefined);
|
||||
self.totalSpace = ko.observable(undefined);
|
||||
self.freeSpaceString = ko.computed(function() {
|
||||
if (!self.freeSpace())
|
||||
return "-";
|
||||
return formatSize(self.freeSpace());
|
||||
});
|
||||
self.totalSpaceString = ko.computed(function() {
|
||||
if (!self.totalSpace())
|
||||
return "-";
|
||||
return formatSize(self.totalSpace());
|
||||
});
|
||||
|
||||
self.diskusageWarning = ko.computed(function() {
|
||||
return self.freeSpace() != undefined
|
||||
&& self.freeSpace() < self.settingsViewModel.server_diskspace_warning();
|
||||
});
|
||||
self.diskusageCritical = ko.computed(function() {
|
||||
return self.freeSpace() != undefined
|
||||
&& self.freeSpace() < self.settingsViewModel.server_diskspace_critical();
|
||||
});
|
||||
self.diskusageString = ko.computed(function() {
|
||||
if (self.diskusageCritical()) {
|
||||
return gettext("Your available free disk space is critically low.");
|
||||
} else if (self.diskusageWarning()) {
|
||||
return gettext("Your available free disk space is starting to run low.");
|
||||
} else {
|
||||
return gettext("Your current disk usage.");
|
||||
}
|
||||
});
|
||||
|
||||
self.uploadButton = undefined;
|
||||
|
||||
@@ -47,8 +72,8 @@ $(function() {
|
||||
},
|
||||
"size": function(a, b) {
|
||||
// sorts descending
|
||||
if (b["bytes"] === undefined || a["bytes"] > b["bytes"]) return -1;
|
||||
if (a["bytes"] < b["bytes"]) return 1;
|
||||
if (b["size"] === undefined || a["size"] > b["size"]) return -1;
|
||||
if (a["size"] < b["size"]) return 1;
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
@@ -155,10 +180,14 @@ $(function() {
|
||||
}
|
||||
}
|
||||
|
||||
if (response.free) {
|
||||
if (response.free != undefined) {
|
||||
self.freeSpace(response.free);
|
||||
}
|
||||
|
||||
if (response.total != undefined) {
|
||||
self.totalSpace(response.total);
|
||||
}
|
||||
|
||||
self.highlightFilename(self.printerState.filename());
|
||||
};
|
||||
|
||||
@@ -308,15 +337,18 @@ $(function() {
|
||||
return output;
|
||||
};
|
||||
|
||||
self.performSearch = function() {
|
||||
self.performSearch = function(e) {
|
||||
var query = self.searchQuery();
|
||||
if (query !== undefined && query.trim() != "") {
|
||||
query = query.toLocaleLowerCase();
|
||||
self.listHelper.changeSearchFunction(function(entry) {
|
||||
return entry && entry["name"].toLocaleLowerCase().indexOf(query) > -1;
|
||||
});
|
||||
} else {
|
||||
self.listHelper.resetSearch();
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
self.onDataUpdaterReconnect = function() {
|
||||
@@ -572,7 +604,7 @@ $(function() {
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
GcodeFilesViewModel,
|
||||
["printerStateViewModel", "loginStateViewModel", "slicingViewModel"],
|
||||
["settingsViewModel", "loginStateViewModel", "printerStateViewModel", "slicingViewModel"],
|
||||
"#files_wrapper"
|
||||
]);
|
||||
});
|
||||
@@ -28,15 +28,17 @@ $(function() {
|
||||
new PNotify({title: "Success", text: _.sprintf(gettext("The command \"%(command)s\" executed successfully"), {command: action.name}), type: "success"});
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
var error = "<p>" + _.sprintf(gettext("The command \"%(command)s\" could not be executed."), {command: action.name}) + "</p>";
|
||||
error += pnotifyAdditionalInfo("<pre>" + jqXHR.responseText + "</pre>");
|
||||
new PNotify({title: gettext("Error"), text: error, type: "error", hide: false});
|
||||
if (!action.hasOwnProperty("ignore") || !action.ignore) {
|
||||
var error = "<p>" + _.sprintf(gettext("The command \"%(command)s\" could not be executed."), {command: action.name}) + "</p>";
|
||||
error += pnotifyAdditionalInfo("<pre>" + jqXHR.responseText + "</pre>");
|
||||
new PNotify({title: gettext("Error"), text: error, type: "error", hide: false});
|
||||
}
|
||||
}
|
||||
})
|
||||
};
|
||||
if (action.confirm) {
|
||||
showConfirmationDialog(action.confirm, function (e) {
|
||||
callback();
|
||||
callback();
|
||||
});
|
||||
} else {
|
||||
callback();
|
||||
@@ -49,4 +51,4 @@ $(function() {
|
||||
["loginStateViewModel", "appearanceViewModel", "settingsViewModel", "userSettingsViewModel"],
|
||||
"#navbar"
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,10 @@ $(function() {
|
||||
self.users = parameters[1];
|
||||
self.printerProfiles = parameters[2];
|
||||
|
||||
self.receiving = ko.observable(false);
|
||||
self.sending = ko.observable(false);
|
||||
self.callbacks = [];
|
||||
|
||||
self.api_enabled = ko.observable(undefined);
|
||||
self.api_key = ko.observable(undefined);
|
||||
self.api_allowCrossOrigin = ko.observable(undefined);
|
||||
@@ -113,6 +117,8 @@ $(function() {
|
||||
self.feature_repetierTargetTemp = ko.observable(undefined);
|
||||
self.feature_disableExternalHeatupDetection = ko.observable(undefined);
|
||||
self.feature_keyboardControl = ko.observable(undefined);
|
||||
self.feature_pollWatched = ko.observable(undefined);
|
||||
self.feature_ignoreIdenticalResends = ko.observable(undefined);
|
||||
|
||||
self.serial_port = ko.observable();
|
||||
self.serial_baudrate = ko.observable();
|
||||
@@ -148,6 +154,15 @@ $(function() {
|
||||
|
||||
self.terminalFilters = ko.observableArray([]);
|
||||
|
||||
self.server_commands_systemShutdownCommand = ko.observable(undefined);
|
||||
self.server_commands_systemRestartCommand = ko.observable(undefined);
|
||||
self.server_commands_serverRestartCommand = ko.observable(undefined);
|
||||
|
||||
self.server_diskspace_warning = ko.observable();
|
||||
self.server_diskspace_critical = ko.observable();
|
||||
self.server_diskspace_warning_str = sizeObservable(self.server_diskspace_warning);
|
||||
self.server_diskspace_critical_str = sizeObservable(self.server_diskspace_critical);
|
||||
|
||||
self.settings = undefined;
|
||||
|
||||
self.addTemperatureProfile = function() {
|
||||
@@ -256,13 +271,42 @@ $(function() {
|
||||
};
|
||||
|
||||
self.requestData = function(callback) {
|
||||
if (self.receiving()) {
|
||||
if (callback) {
|
||||
self.callbacks.push(callback);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
self.receiving(true);
|
||||
$.ajax({
|
||||
url: API_BASEURL + "settings",
|
||||
type: "GET",
|
||||
dataType: "json",
|
||||
success: function(response) {
|
||||
self.fromResponse(response);
|
||||
if (callback) callback();
|
||||
if (callback) {
|
||||
self.callbacks.push(callback);
|
||||
}
|
||||
|
||||
try {
|
||||
self.fromResponse(response);
|
||||
|
||||
var cb;
|
||||
while (self.callbacks.length) {
|
||||
cb = self.callbacks.shift();
|
||||
try {
|
||||
cb();
|
||||
} catch(exc) {
|
||||
log.error("Error calling settings callback", cb, ":", (exc.stack || exc));
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
self.receiving(false);
|
||||
self.callbacks = [];
|
||||
}
|
||||
},
|
||||
error: function(xhr) {
|
||||
self.receiving(false);
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -377,6 +421,7 @@ $(function() {
|
||||
self.feature_repetierTargetTemp(response.feature.repetierTargetTemp);
|
||||
self.feature_disableExternalHeatupDetection(!response.feature.externalHeatupDetection);
|
||||
self.feature_keyboardControl(response.feature.keyboardControl);
|
||||
self.feature_pollWatched(response.feature.pollWatched);
|
||||
|
||||
self.serial_port(response.serial.port);
|
||||
self.serial_baudrate(response.serial.baudrate);
|
||||
@@ -413,12 +458,18 @@ $(function() {
|
||||
self.system_actions(response.system.actions);
|
||||
|
||||
self.terminalFilters(response.terminalFilters);
|
||||
|
||||
self.server_commands_systemShutdownCommand(response.server.commands.systemShutdownCommand);
|
||||
self.server_commands_systemRestartCommand(response.server.commands.systemRestartCommand);
|
||||
self.server_commands_serverRestartCommand(response.server.commands.serverRestartCommand);
|
||||
};
|
||||
|
||||
self.saveData = function (data, successCallback) {
|
||||
self.settingsDialog.trigger("beforeSave");
|
||||
|
||||
if (data == undefined) {
|
||||
// we only set sending to true when we didn't include data
|
||||
self.sending(true);
|
||||
data = ko.mapping.toJS(self.settings);
|
||||
|
||||
data = _.extend(data, {
|
||||
@@ -457,7 +508,8 @@ $(function() {
|
||||
"swallowOkAfterResend": self.feature_swallowOkAfterResend(),
|
||||
"repetierTargetTemp": self.feature_repetierTargetTemp(),
|
||||
"externalHeatupDetection": !self.feature_disableExternalHeatupDetection(),
|
||||
"keyboardControl": self.feature_keyboardControl()
|
||||
"keyboardControl": self.feature_keyboardControl(),
|
||||
"pollWatched": self.feature_pollWatched()
|
||||
},
|
||||
"serial": {
|
||||
"port": self.serial_port(),
|
||||
@@ -496,6 +548,13 @@ $(function() {
|
||||
"beforePrintResumed": self.scripts_gcode_beforePrintResumed(),
|
||||
"afterPrinterConnected": self.scripts_gcode_afterPrinterConnected()
|
||||
}
|
||||
},
|
||||
"server": {
|
||||
"commands": {
|
||||
"systemShutdownCommand": self.server_commands_systemShutdownCommand(),
|
||||
"systemRestartCommand": self.server_commands_systemRestartCommand(),
|
||||
"serverRestartCommand": self.server_commands_serverRestartCommand()
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -507,11 +566,24 @@ $(function() {
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify(data),
|
||||
success: function(response) {
|
||||
self.fromResponse(response);
|
||||
if (successCallback) successCallback(response);
|
||||
self.receiving(true);
|
||||
self.sending(false);
|
||||
try {
|
||||
self.fromResponse(response);
|
||||
if (successCallback) successCallback(response);
|
||||
} finally {
|
||||
self.receiving(false);
|
||||
}
|
||||
},
|
||||
error: function(xhr) {
|
||||
self.sending(false);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.onEventSettingsUpdated = function() {
|
||||
self.requestData();
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
|
||||
@@ -86,7 +86,7 @@ $(function() {
|
||||
self._processCurrentLogData = function(data) {
|
||||
self.log(self.log().concat(_.map(data, function(line) { return self._toInternalFormat(line) })));
|
||||
if (self.autoscrollEnabled()) {
|
||||
self.log(self.log.slice(-300));
|
||||
self.log(self.log.slice(-self.buffer()));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
+4
-3
@@ -726,8 +726,9 @@
|
||||
selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
|
||||
}
|
||||
|
||||
$parent = $(selector)
|
||||
$parent.length || ($parent = $this.parent())
|
||||
$parent = selector && (selector != "#") && $(selector)
|
||||
|
||||
if (!$parent || !$parent.length) $parent = $this.parent()
|
||||
|
||||
return $parent
|
||||
}
|
||||
@@ -2156,4 +2157,4 @@
|
||||
})
|
||||
|
||||
|
||||
}(window.jQuery);
|
||||
}(window.jQuery);
|
||||
@@ -1,6 +0,0 @@
|
||||
/*!
|
||||
* Bootstrap.js by @fat & @mdo
|
||||
* Copyright 2012 Twitter, Inc.
|
||||
* http://www.apache.org/licenses/LICENSE-2.0.txt
|
||||
*/
|
||||
!function($){"use strict";$(function(){$.support.transition=function(){var transitionEnd=function(){var name,el=document.createElement("bootstrap"),transEndEventNames={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(name in transEndEventNames)if(void 0!==el.style[name])return transEndEventNames[name]}();return transitionEnd&&{end:transitionEnd}}()})}(window.jQuery),!function($){"use strict";var dismiss='[data-dismiss="alert"]',Alert=function(el){$(el).on("click",dismiss,this.close)};Alert.prototype.close=function(e){function removeElement(){$parent.trigger("closed").remove()}var $parent,$this=$(this),selector=$this.attr("data-target");selector||(selector=$this.attr("href"),selector=selector&&selector.replace(/.*(?=#[^\s]*$)/,"")),$parent=$(selector),e&&e.preventDefault(),$parent.length||($parent=$this.hasClass("alert")?$this:$this.parent()),$parent.trigger(e=$.Event("close")),e.isDefaultPrevented()||($parent.removeClass("in"),$.support.transition&&$parent.hasClass("fade")?$parent.on($.support.transition.end,removeElement):removeElement())};var old=$.fn.alert;$.fn.alert=function(option){return this.each(function(){var $this=$(this),data=$this.data("alert");data||$this.data("alert",data=new Alert(this)),"string"==typeof option&&data[option].call($this)})},$.fn.alert.Constructor=Alert,$.fn.alert.noConflict=function(){return $.fn.alert=old,this},$(document).on("click.alert.data-api",dismiss,Alert.prototype.close)}(window.jQuery),!function($){"use strict";var Button=function(element,options){this.$element=$(element),this.options=$.extend({},$.fn.button.defaults,options)};Button.prototype.setState=function(state){var d="disabled",$el=this.$element,data=$el.data(),val=$el.is("input")?"val":"html";state+="Text",data.resetText||$el.data("resetText",$el[val]()),$el[val](data[state]||this.options[state]),setTimeout(function(){"loadingText"==state?$el.addClass(d).attr(d,d):$el.removeClass(d).removeAttr(d)},0)},Button.prototype.toggle=function(){var $parent=this.$element.closest('[data-toggle="buttons-radio"]');$parent&&$parent.find(".active").removeClass("active"),this.$element.toggleClass("active")};var old=$.fn.button;$.fn.button=function(option){return this.each(function(){var $this=$(this),data=$this.data("button"),options="object"==typeof option&&option;data||$this.data("button",data=new Button(this,options)),"toggle"==option?data.toggle():option&&data.setState(option)})},$.fn.button.defaults={loadingText:"loading..."},$.fn.button.Constructor=Button,$.fn.button.noConflict=function(){return $.fn.button=old,this},$(document).on("click.button.data-api","[data-toggle^=button]",function(e){var $btn=$(e.target);$btn.hasClass("btn")||($btn=$btn.closest(".btn")),$btn.button("toggle")})}(window.jQuery),!function($){"use strict";var Carousel=function(element,options){this.$element=$(element),this.options=options,"hover"==this.options.pause&&this.$element.on("mouseenter",$.proxy(this.pause,this)).on("mouseleave",$.proxy(this.cycle,this))};Carousel.prototype={cycle:function(e){return e||(this.paused=!1),this.options.interval&&!this.paused&&(this.interval=setInterval($.proxy(this.next,this),this.options.interval)),this},to:function(pos){var $active=this.$element.find(".item.active"),children=$active.parent().children(),activePos=children.index($active),that=this;if(!(pos>children.length-1||0>pos))return this.sliding?this.$element.one("slid",function(){that.to(pos)}):activePos==pos?this.pause().cycle():this.slide(pos>activePos?"next":"prev",$(children[pos]))},pause:function(e){return e||(this.paused=!0),this.$element.find(".next, .prev").length&&$.support.transition.end&&(this.$element.trigger($.support.transition.end),this.cycle()),clearInterval(this.interval),this.interval=null,this},next:function(){return this.sliding?void 0:this.slide("next")},prev:function(){return this.sliding?void 0:this.slide("prev")},slide:function(type,next){var e,$active=this.$element.find(".item.active"),$next=next||$active[type](),isCycling=this.interval,direction="next"==type?"left":"right",fallback="next"==type?"first":"last",that=this;if(this.sliding=!0,isCycling&&this.pause(),$next=$next.length?$next:this.$element.find(".item")[fallback](),e=$.Event("slide",{relatedTarget:$next[0]}),!$next.hasClass("active")){if($.support.transition&&this.$element.hasClass("slide")){if(this.$element.trigger(e),e.isDefaultPrevented())return;$next.addClass(type),$next[0].offsetWidth,$active.addClass(direction),$next.addClass(direction),this.$element.one($.support.transition.end,function(){$next.removeClass([type,direction].join(" ")).addClass("active"),$active.removeClass(["active",direction].join(" ")),that.sliding=!1,setTimeout(function(){that.$element.trigger("slid")},0)})}else{if(this.$element.trigger(e),e.isDefaultPrevented())return;$active.removeClass("active"),$next.addClass("active"),this.sliding=!1,this.$element.trigger("slid")}return isCycling&&this.cycle()Line truncated
|
||||
@@ -387,19 +387,21 @@ ul.dropdown-menu li a {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/** Offline overlay */
|
||||
/** Offline & Reload overlay */
|
||||
|
||||
#offline_overlay {
|
||||
#offline_overlay,
|
||||
#reloadui_overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
z-index: 10000;
|
||||
z-index: 10001;
|
||||
display: none;
|
||||
}
|
||||
|
||||
#offline_overlay_background {
|
||||
#offline_overlay_background,
|
||||
#reloadui_overlay_background {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
@@ -412,7 +414,8 @@ ul.dropdown-menu li a {
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
#offline_overlay_wrapper {
|
||||
#offline_overlay_wrapper,
|
||||
#reloadui_overlay_wrapper {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
@@ -608,11 +611,11 @@ ul.dropdown-menu li a {
|
||||
}
|
||||
}
|
||||
|
||||
.custom_section_horizontal .custom_control {
|
||||
.custom_section_horizontal > .custom_control {
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.custom_section_vertical .custom_control {
|
||||
.custom_section_vertical > .custom_control {
|
||||
display:block;
|
||||
}
|
||||
|
||||
@@ -972,6 +975,20 @@ textarea.block {
|
||||
}
|
||||
}
|
||||
|
||||
// Special delivery for Safari browsers... because Safari >= 8 sometimes just
|
||||
// shows us white panes on the settings dialog when the full-sized-box has
|
||||
// an absolute position (which it needs for both scrollbars to work), at least
|
||||
// until the page is resized or otherwise a rerender is triggered, we'll have
|
||||
// our styling resolve to static positioning on that browser for now.
|
||||
//
|
||||
// This btw also means that the dialog will change in size. Yay.
|
||||
//
|
||||
// Better use something else if you have the option, that thing is really
|
||||
// weird.
|
||||
_::-webkit-full-page-media, _:future, :root .full-sized-box {
|
||||
position: static;
|
||||
}
|
||||
|
||||
.scrollable {
|
||||
height: 100%;
|
||||
overflow: auto;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<div id="settings_dialog" class="modal hide fade large" tabindex="-1" role="dialog" aria-labelledby="settings_dialog_label" aria-hidden="true">
|
||||
<div class="modal-header">
|
||||
<button type="button" class="close" data-dismiss="modal">×</button>
|
||||
<h3 id="settings_dialog_label">{{ _('OctoPrint Settings') }}</h3>
|
||||
<h3 id="settings_dialog_label">{{ _('OctoPrint Settings') }} <i class="icon-spinner icon-spin" data-bind="visible: receiving"></i></h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="full-sized-box">
|
||||
@@ -20,7 +20,7 @@
|
||||
class="{% if mark_active %}active{% set mark_active = False %}{% endif %} {% if "classes_link" in data %}{{ data.classes_link|join(' ') }}{% elif "classes" in data %}{{ data.classes|join(' ') }}{% endif %}"
|
||||
{% if "styles_link" in data %} style="{{ data.styles_link|join(', ') }}" {% elif "styles" in data %} style="{{ data.styles|join(', ') }}" {% endif %}
|
||||
>
|
||||
<a href="#{{ data._div }}" data-toggle="tab">{{ entry }}</a>
|
||||
<a href="#{{ data._div }}" data-toggle="tab">{{ entry|e }}</a>
|
||||
</li>
|
||||
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
|
||||
{% endif %}
|
||||
@@ -49,6 +49,6 @@
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</button>
|
||||
<button class="btn btn-primary" data-bind="click: function() { saveData(undefined, $root.hide) }">{{ _('Save') }}</button>
|
||||
<button class="btn btn-primary" data-bind="click: function() { saveData(undefined, $root.hide) }, enable: !sending(), css: {disabled: sending()}"><i class="icon-spinner icon-spin" data-bind="visible: sending"></i> {{ _('Save') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -48,6 +48,13 @@
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: feature_ignoreIdenticalResends" id="settings-ignoreIdenticalResends"> {{ _('Ignore consecutive resend requests for the same line') }} <span class="label">{{ _('Repetier') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
@@ -62,11 +69,4 @@
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: feature_swallowOkAfterResend" id="settings-swallowOkAfterResend"> {{ _('Swallow the first "ok" after a resend response') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@@ -1,4 +1,6 @@
|
||||
<form class="form-horizontal">
|
||||
<h3>{{ _('Folders') }}</h3>
|
||||
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-folderUploads">{{ _('Upload Folder') }}</label>
|
||||
<div class="controls">
|
||||
@@ -29,4 +31,28 @@
|
||||
<input type="text" class="input-block-level" data-bind="value: folder_watched" id="settings-folderWatched">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: feature_pollWatched" id="settings-featurePollWatched"> {{ _('Actively poll the watched folder. Check this if files in your watched folder aren\'t automatically added otherwise.') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h3>{{ _('Disk space thresholds') }}</h3>
|
||||
|
||||
<p>{{ _('If the free disk space falls below these thresholds, OctoPrint will warn the user.') }}</p>
|
||||
|
||||
<div class="control-group" title="{{ ('Threshold after which to warn about the remaining free space on disk.') }}">
|
||||
<label class="control-label" for="settings.serverDiskusageWarning">{{ _('Warning') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-mini text-right" data-bind="value: server_diskspace_warning_str">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ ('Threshold after which to consider remaining free space on disk as critical.') }}">
|
||||
<label class="control-label" for="settings.serverDiskusageCritical">{{ _('Critical') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-mini text-right" data-bind="value: server_diskspace_critical_str">
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@@ -22,7 +22,7 @@
|
||||
<label class="control-label" for="settings-serialTimeoutTemperature">{{ _('Temperature interval') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="number" step="any" min="0" class="input-mini text-right" data-bind="value: serial_timeoutTemperature" id="settings-serialTimeoutTemperature">
|
||||
<input type="number" step="any" min="1" class="input-mini text-right" data-bind="value: serial_timeoutTemperature" id="settings-serialTimeoutTemperature">
|
||||
<span class="add-on">s</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
<form class="form-horizontal">
|
||||
<h3>{{ _('Commands') }}</h3>
|
||||
|
||||
<div class="control-group" title="{{ _('Command to restart the OctoPrint server') }}">
|
||||
<label class="control-label" for="settings-serverRestartCommand">{{ _('Restart OctoPrint') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: server_commands_serverRestartCommand" id="settings-serverRestartCommand">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('Command to restart the system OctoPrint is running on') }}">
|
||||
<label class="control-label" for="settings-systemRestartCommand">{{ _('Restart system') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: server_commands_systemRestartCommand" id="settings-systemRestartCommand">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('Command to shut down the system OctoPrint is running on') }}">
|
||||
<label class="control-label" for="settings-systemShutdownCommand">{{ _('Shutdown system') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: server_commands_systemShutdownCommand" id="settings-systemShutdownCommand">
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@@ -17,7 +17,7 @@
|
||||
class="{% if mark_active %}active{% set mark_active = False %}{% endif %} {% if "classes_link" in data %}{{ data.classes_link|join(' ') }}{% elif "classes" in data %}{{ data.classes|join(' ') }}{% endif %}"
|
||||
{% if "styles_link" in data %} style="{{ data.styles_link|join(', ') }}" {% elif "styles" in data %} style="{{ data.styles|join(', ') }}" {% endif %}
|
||||
>
|
||||
<a href="#{{ data._div }}" data-toggle="tab">{{ entry }}</a>
|
||||
<a href="#{{ data._div }}" data-toggle="tab">{{ entry|e }}</a>
|
||||
</li>
|
||||
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
|
||||
{% endif %}
|
||||
|
||||
@@ -55,7 +55,7 @@
|
||||
>
|
||||
<div class="accordion-heading">
|
||||
<a class="accordion-toggle" data-toggle="collapse" data-target="#{{ data._div }}">
|
||||
{% if "icon" in data %}<i class="icon-{{ data.icon }}"></i> {% endif %}{{ entry }}
|
||||
{% if "icon" in data %}<i class="icon-{{ data.icon }}"></i> {% endif %}{{ entry|e }}
|
||||
</a>
|
||||
{% if "template_header" in data %}
|
||||
{% include data.template_header ignore missing %}
|
||||
@@ -87,7 +87,7 @@
|
||||
{% if "data_bind" in data %}data-bind="{{ data.data_bind }}"{% endif %}
|
||||
{% if "styles_link" in data %} style="{{ data.styles_link|join(', ') }}" {% elif "styles" in data %} style="{{ data.styles|join(', ') }}" {% endif %}
|
||||
>
|
||||
<a href="#{{ data._div }}" data-toggle="tab">{{ entry }}</a>
|
||||
<a href="#{{ data._div }}" data-toggle="tab">{{ entry|e }}</a>
|
||||
</li>
|
||||
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
|
||||
{% endfor %}
|
||||
@@ -112,7 +112,7 @@
|
||||
</div>
|
||||
<div class="footer">
|
||||
<ul class="pull-left muted">
|
||||
<li><small>{{ _('Version') }}: <span class="version">{{ display_version }}</span></small></li>
|
||||
<li><small>{{ _('Version') }}: <span class="version">{{ display_version|e }}</span></small></li>
|
||||
</ul>
|
||||
<ul class="pull-right">
|
||||
<li><a href="http://octoprint.org"><i class="icon-home"></i> {{ _('Homepage') }}</a></li>
|
||||
@@ -134,6 +134,7 @@
|
||||
<!-- Overlays -->
|
||||
{% include 'overlays/dragndrop.jinja2' %}
|
||||
{% include 'overlays/offline.jinja2' %}
|
||||
{% include 'overlays/reloadui.jinja2' %}
|
||||
<!-- End of overlays -->
|
||||
|
||||
<!-- Generic plugin template files -->
|
||||
|
||||
@@ -10,23 +10,24 @@
|
||||
var CONFIG_TIMELAPSEFILESPERPAGE = 10;
|
||||
var CONFIG_LOGFILESPERPAGE = 10;
|
||||
var CONFIG_USERSPERPAGE = 10;
|
||||
var CONFIG_WEBCAM_STREAM = "{{ webcamStream }}";
|
||||
var CONFIG_WEBCAM_STREAM = "{{ webcamStream|e }}";
|
||||
var CONFIG_ACCESS_CONTROL = {% if enableAccessControl -%} true; {% else %} false; {%- endif %}
|
||||
var CONFIG_SD_SUPPORT = {% if enableSdSupport -%} true; {% else %} false; {%- endif %}
|
||||
var CONFIG_FIRST_RUN = {% if firstRun -%} true; {% else %} false; {%- endif %}
|
||||
var CONFIG_TEMPERATURE_GRAPH = {% if enableTemperatureGraph -%} true; {% else %} false; {%- endif %}
|
||||
var CONFIG_GCODE_SIZE_THRESHOLD = {{ gcodeThreshold }};
|
||||
var CONFIG_GCODE_MOBILE_SIZE_THRESHOLD = {{ gcodeMobileThreshold }};
|
||||
var CONFIG_GCODE_SIZE_THRESHOLD = {{ gcodeThreshold|e }};
|
||||
var CONFIG_GCODE_MOBILE_SIZE_THRESHOLD = {{ gcodeMobileThreshold|e }};
|
||||
|
||||
var SOCKJS_URI = "{{ url_for('index') }}" + "sockjs";
|
||||
var SOCKJS_DEBUG = CONFIG_DEBUG;
|
||||
// sockjs should define CLOSE_NORMAL for us, but they don't (from ws spec)
|
||||
var SOCKJS_CLOSE_NORMAL = 1000
|
||||
var SOCKJS_CLOSE_NORMAL = 1000;
|
||||
|
||||
var UI_API_KEY = "{{ uiApiKey }}";
|
||||
var VERSION = "{{ version }}";
|
||||
var DISPLAY_VERSION = "{{ display_version }}";
|
||||
var LOCALE = "{{ g.locale }}";
|
||||
var UI_API_KEY = "{{ uiApiKey|e }}";
|
||||
var VERSION = "{{ version|e }}";
|
||||
var DISPLAY_VERSION = "{{ display_version|e }}";
|
||||
var BRANCH = "{{ branch|e }}";
|
||||
var LOCALE = "{{ g.locale|e }}";
|
||||
var AVAILABLE_LOCALES = {{ locales|tojson }};
|
||||
|
||||
var OCTOPRINT_VIEWMODELS = [];
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
{% assets "all_js" %}
|
||||
{% assets "js_libs" %}
|
||||
<script type="text/javascript" src="{{ ASSET_URL }}"></script>
|
||||
{% endassets %}
|
||||
|
||||
{% assets "js_app" %}
|
||||
<script type="text/javascript" src="{{ ASSET_URL }}"></script>
|
||||
{% endassets %}
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" id="login_remember" data-bind="checked: loginState.loginRemember"> {{ _('Remember me') }}
|
||||
</label>
|
||||
<button class="btn btn-block btn-primary" id="login_button" data-bind="click: loginState.login">{{ _('Login') }}</button>
|
||||
<button class="btn btn-block btn-primary" id="login_button" data-bind="click: function() { loginState.login(); }">{{ _('Login') }}</button>
|
||||
</div>
|
||||
<ul id="login_dropdown_loggedin" class="hide" data-bind="css: {hide: !loginState.loggedIn(), 'dropdown-menu': loginState.loggedIn()}">
|
||||
<li><a href="#" id="usersettings_button" data-bind="click: function() { usersettings.show(); }">{{ _('User Settings') }}</a></li>
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
<div id="reloadui_overlay" xmlns="http://www.w3.org/1999/html">
|
||||
<div id="reloadui_overlay_background"></div>
|
||||
<div id="reloadui_overlay_wrapper">
|
||||
<div class="container">
|
||||
<div class="hero-unit">
|
||||
<h1>{{ _('Please reload') }}</h1>
|
||||
<p>{{ _('There is a new version of the server active now, a reload of the user interface is needed. This will not interrupt any print jobs you might have ongoing. Please reload the web interface now by clicking the button below.') }}</p>
|
||||
<p>
|
||||
<a class="btn btn-primary btn-large" id="reloadui_overlay_reload">{{ _('Reload now') }}</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1,4 +1,4 @@
|
||||
<form class="form-search">
|
||||
<form class="form-search" data-bind="submit: performSearch">
|
||||
<input type="text" class="input-block search-query" data-bind="value: searchQuery, valueUpdate: 'input'" placeholder="{{ _('Search...') }}">
|
||||
</form>
|
||||
<div class="gcode_files" data-bind="slimScrolledForeach: listHelper.paginatedItems">
|
||||
@@ -10,11 +10,11 @@
|
||||
<div class="size">{{ _('Size') }}: <span data-bind="text: formatSize(size)"></span></div>
|
||||
<div class="additionalInfo hide" data-bind="html: $root.getAdditionalData($data)"></div>
|
||||
<div class="btn-group action-buttons">
|
||||
<div class="btn btn-mini toggleAdditionalData" data-bind="click: function() { if ($root.enableAdditionalData($data)) { $root.toggleAdditionalData($data); } else { return; } }, css: { disabled: !$root.enableAdditionalData($data) }"><i class="icon-chevron-down"></i></div>
|
||||
<a class="btn btn-mini" data-bind="attr: {href: $root.downloadLink($data), css: {disabled: !$root.downloadLink($data)}}"><i class="icon-download-alt" title="{{ _('Download') }}"></i></a>
|
||||
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableRemove($data)) { $root.removeFile($data); } else { return; } }, css: {disabled: !$root.enableRemove($data)}"><i class="icon-trash" title="{{ _('Remove') }}"></i></div>
|
||||
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, false); } else { return; } }, css: {disabled: !$root.enableSelect($data)}"><i class="icon-folder-open" title="{{ _('Load') }}"></i></div>
|
||||
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, true); } else { return; } }, css: {disabled: !$root.enableSelect($data)}"><i class="icon-print" title="{{ _('Load and Print') }}"></i></div>
|
||||
<div class="btn btn-mini toggleAdditionalData" data-bind="click: function() { if ($root.enableAdditionalData($data)) { $root.toggleAdditionalData($data); } else { return; } }, css: { disabled: !$root.enableAdditionalData($data) }" title="{{ _('Additional data') }}"><i class="icon-chevron-down"></i></div>
|
||||
<a class="btn btn-mini" data-bind="attr: {href: $root.downloadLink($data), css: {disabled: !$root.downloadLink($data)}}" title="{{ _('Download') }}"><i class="icon-download-alt"></i></a>
|
||||
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableRemove($data)) { $root.removeFile($data); } else { return; } }, css: {disabled: !$root.enableRemove($data)}" title="{{ _('Remove') }}"><i class="icon-trash"></i></div>
|
||||
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, false); } else { return; } }, css: {disabled: !$root.enableSelect($data)}" title="{{ _('Load') }}"><i class="icon-folder-open"></i></div>
|
||||
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, true); } else { return; } }, css: {disabled: !$root.enableSelect($data)}" title="{{ _('Load and Print') }}"><i class="icon-print"></i></div>
|
||||
</div>
|
||||
</script>
|
||||
|
||||
@@ -23,9 +23,9 @@
|
||||
<div class="uploaded">{{ _('Uploaded') }}: <span data-bind="text: formatTimeAgo(date)"></span></div>
|
||||
<div class="size">{{ _('Size') }}: <span data-bind="text: formatSize(size)"></span></div>
|
||||
<div class="btn-group action-buttons">
|
||||
<a class="btn btn-mini" data-bind="attr: {href: $root.downloadLink($data), css: {disabled: !$root.downloadLink($data)}}"><i class="icon-download-alt" title="{{ _('Download') }}"></i></a>
|
||||
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableRemove($data)) { $root.removeFile($data); } else { return; } }, css: {disabled: !$root.enableRemove($data)}"><i class="icon-trash" title="{{ _('Remove') }}"></i></div>
|
||||
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSlicing($data)) { $root.sliceFile($data); } else { return; } }, css: {disabled: !$root.enableSlicing($data)}"><i class="icon-magic" title="{{ _('Slice') }}"></i></div>
|
||||
<a class="btn btn-mini" data-bind="attr: {href: $root.downloadLink($data), css: {disabled: !$root.downloadLink($data)}}" title="{{ _('Download') }}"><i class="icon-download-alt"></i></a>
|
||||
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableRemove($data)) { $root.removeFile($data); } else { return; } }, css: {disabled: !$root.enableRemove($data)}" title="{{ _('Remove') }}"><i class="icon-trash"></i></div>
|
||||
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSlicing($data)) { $root.sliceFile($data); } else { return; } }, css: {disabled: !$root.enableSlicing($data)}" title="{{ _('Slice') }}"><i class="icon-magic"></i></div>
|
||||
</div>
|
||||
</script>
|
||||
|
||||
@@ -33,8 +33,8 @@
|
||||
<div class="title" data-bind="text: name"></div>
|
||||
</script>
|
||||
</div>
|
||||
<div class="muted text-right">
|
||||
<small>{{ _('Free') }}: <span data-bind="text: freeSpaceString"></span></small>
|
||||
<div class="text-right muted" data-bind="attr: {title: diskusageString}, css: {'text-error': diskusageCritical}, style: {'font-weight': diskusageCritical() || diskusageWarning() ? 'bold' : 'normal'}">
|
||||
<small>{{ _('Free') }}: <span data-bind="text: freeSpaceString"></span> / {{ _('Total') }}: <span data-bind="text: totalSpaceString"></span> <i class="icon-exclamation-sign" data-bind="visible: diskusageWarning" style="display: none"></i></small>
|
||||
</div>
|
||||
<div style="display: none;" data-bind="visible: loginState.isUser">
|
||||
<div class="row-fluid upload-buttons">
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
{% assets "all_css" %}
|
||||
{% assets "css_libs" %}
|
||||
<link href="{{ ASSET_URL }}" rel="stylesheet" media="screen">
|
||||
{% endassets %}
|
||||
|
||||
{% assets "css_app" %}
|
||||
<link href="{{ ASSET_URL }}" rel="stylesheet" media="screen">
|
||||
{% endassets %}
|
||||
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
<div style="display: none;" data-bind="visible: loginState.isUser">
|
||||
<div class="alert" data-bind="visible: isPrinting()">
|
||||
{{ _('Take note that timelapse configuration is disabled while your printer is printing.') }}
|
||||
</div>
|
||||
<h1>{{ _('Timelapse Configuration') }}</h1>
|
||||
|
||||
<label for="webcam_timelapse_mode">{{ _('Timelapse Mode') }}</label>
|
||||
<select id="webcam_timelapse_mode" data-bind="value: timelapseType, enable: isOperational() && !isPrinting() && loginState.isUser()">
|
||||
<option value="off">{{ _('Off') }}</option>
|
||||
<option value="zchange">{{ _('On Z Change') }}</option>
|
||||
<option value="timed">{{ _('Timed') }}</option>
|
||||
<option value="zchange">{{ _('On Z Change') }}</option>
|
||||
</select>
|
||||
<span class="help-block" data-bind="visible: timelapseType() == 'zchange'"><span class="label label-warning">{{ _('Warning') }}</span> {{ _('Do not use with spiralized ("Joris") vases or similar continuous Z models.') }}</span>
|
||||
<span class="help-block" data-bind="visible: timelapseType() == 'zchange'"><span class="label label-info">{{ _('Note') }}</span> {% trans %}Does not work when printing from the printer's SD Card (no way to detect the change in Z reliably). Use "Timed" mode for those prints instead.{% endtrans %}</span>
|
||||
|
||||
<label for="webcam_timelapse_fps">{{ _('Timelapse frame rate (in frames per second)') }}</label>
|
||||
<div class="input-append">
|
||||
|
||||
+207
-135
@@ -6,13 +6,13 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import urllib
|
||||
import time
|
||||
import subprocess
|
||||
import fnmatch
|
||||
import datetime
|
||||
import sys
|
||||
import shutil
|
||||
import Queue
|
||||
import requests
|
||||
|
||||
import octoprint.util as util
|
||||
|
||||
@@ -58,7 +58,7 @@ def notifyCallbacks(timelapse):
|
||||
if timelapse is None:
|
||||
config = None
|
||||
else:
|
||||
config = timelapse.configData()
|
||||
config = timelapse.config_data()
|
||||
for callback in updateCallbacks:
|
||||
try: callback.sendTimelapseConfig(config)
|
||||
except: logging.getLogger(__name__).exception("Exception while pushing timelapse configuration")
|
||||
@@ -86,12 +86,12 @@ def configureTimelapse(config=None, persist=False):
|
||||
if type is None or "off" == type:
|
||||
current = None
|
||||
elif "zchange" == type:
|
||||
current = ZTimelapse(postRoll=postRoll, fps=fps)
|
||||
current = ZTimelapse(post_roll=postRoll, fps=fps)
|
||||
elif "timed" == type:
|
||||
interval = 10
|
||||
if "options" in config and "interval" in config["options"] and config["options"]["interval"] > 0:
|
||||
interval = config["options"]["interval"]
|
||||
current = TimedTimelapse(postRoll=postRoll, interval=interval, fps=fps)
|
||||
current = TimedTimelapse(post_roll=postRoll, interval=interval, fps=fps)
|
||||
|
||||
notifyCallbacks(current)
|
||||
|
||||
@@ -101,72 +101,83 @@ def configureTimelapse(config=None, persist=False):
|
||||
|
||||
|
||||
class Timelapse(object):
|
||||
def __init__(self, postRoll=0, fps=25):
|
||||
QUEUE_ENTRY_TYPE_CAPTURE = "capture"
|
||||
QUEUE_ENTRY_TYPE_CALLBACK = "callback"
|
||||
|
||||
def __init__(self, post_roll=0, fps=25):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._imageNumber = None
|
||||
self._inTimelapse = False
|
||||
self._gcodeFile = None
|
||||
self._image_number = None
|
||||
self._in_timelapse = False
|
||||
self._gcode_file = None
|
||||
|
||||
self._postRoll = postRoll
|
||||
self._postRollStart = None
|
||||
self._onPostRollDone = None
|
||||
self._post_roll = post_roll
|
||||
self._on_post_roll_done = None
|
||||
|
||||
self._captureDir = settings().getBaseFolder("timelapse_tmp")
|
||||
self._movieDir = settings().getBaseFolder("timelapse")
|
||||
self._snapshotUrl = settings().get(["webcam", "snapshot"])
|
||||
self._ffmpegThreads = settings().get(["webcam", "ffmpegThreads"])
|
||||
self._capture_dir = settings().getBaseFolder("timelapse_tmp")
|
||||
self._movie_dir = settings().getBaseFolder("timelapse")
|
||||
self._snapshot_url = settings().get(["webcam", "snapshot"])
|
||||
self._ffmpeg_threads = settings().get(["webcam", "ffmpegThreads"])
|
||||
|
||||
self._fps = fps
|
||||
|
||||
self._renderThread = None
|
||||
self._captureMutex = threading.Lock()
|
||||
self._render_thread = None
|
||||
|
||||
self._capture_mutex = threading.Lock()
|
||||
self._capture_queue = Queue.Queue()
|
||||
self._capture_queue_active = True
|
||||
|
||||
self._capture_queue_thread = threading.Thread(target=self._capture_queue_worker)
|
||||
self._capture_queue_thread.daemon = True
|
||||
self._capture_queue_thread.start()
|
||||
|
||||
# subscribe events
|
||||
eventManager().subscribe(Events.PRINT_STARTED, self.onPrintStarted)
|
||||
eventManager().subscribe(Events.PRINT_FAILED, self.onPrintDone)
|
||||
eventManager().subscribe(Events.PRINT_DONE, self.onPrintDone)
|
||||
eventManager().subscribe(Events.PRINT_RESUMED, self.onPrintResumed)
|
||||
for (event, callback) in self.eventSubscriptions():
|
||||
eventManager().subscribe(Events.PRINT_STARTED, self.on_print_started)
|
||||
eventManager().subscribe(Events.PRINT_FAILED, self.on_print_done)
|
||||
eventManager().subscribe(Events.PRINT_DONE, self.on_print_done)
|
||||
eventManager().subscribe(Events.PRINT_RESUMED, self.on_print_resumed)
|
||||
for (event, callback) in self.event_subscriptions():
|
||||
eventManager().subscribe(event, callback)
|
||||
|
||||
def postRoll(self):
|
||||
return self._postRoll
|
||||
@property
|
||||
def post_roll(self):
|
||||
return self._post_roll
|
||||
|
||||
@property
|
||||
def fps(self):
|
||||
return self._fps
|
||||
|
||||
def unload(self):
|
||||
if self._inTimelapse:
|
||||
self.stopTimelapse(doCreateMovie=False)
|
||||
if self._in_timelapse:
|
||||
self.stop_timelapse(doCreateMovie=False)
|
||||
|
||||
# unsubscribe events
|
||||
eventManager().unsubscribe(Events.PRINT_STARTED, self.onPrintStarted)
|
||||
eventManager().unsubscribe(Events.PRINT_FAILED, self.onPrintDone)
|
||||
eventManager().unsubscribe(Events.PRINT_DONE, self.onPrintDone)
|
||||
eventManager().unsubscribe(Events.PRINT_RESUMED, self.onPrintResumed)
|
||||
for (event, callback) in self.eventSubscriptions():
|
||||
eventManager().unsubscribe(Events.PRINT_STARTED, self.on_print_started)
|
||||
eventManager().unsubscribe(Events.PRINT_FAILED, self.on_print_done)
|
||||
eventManager().unsubscribe(Events.PRINT_DONE, self.on_print_done)
|
||||
eventManager().unsubscribe(Events.PRINT_RESUMED, self.on_print_resumed)
|
||||
for (event, callback) in self.event_subscriptions():
|
||||
eventManager().unsubscribe(event, callback)
|
||||
|
||||
def onPrintStarted(self, event, payload):
|
||||
def on_print_started(self, event, payload):
|
||||
"""
|
||||
Override this to perform additional actions upon start of a print job.
|
||||
"""
|
||||
self.startTimelapse(payload["file"])
|
||||
self.start_timelapse(payload["file"])
|
||||
|
||||
def onPrintDone(self, event, payload):
|
||||
def on_print_done(self, event, payload):
|
||||
"""
|
||||
Override this to perform additional actions upon the stop of a print job.
|
||||
"""
|
||||
self.stopTimelapse(success=(event==Events.PRINT_DONE))
|
||||
self.stop_timelapse(success=(event==Events.PRINT_DONE))
|
||||
|
||||
def onPrintResumed(self, event, payload):
|
||||
def on_print_resumed(self, event, payload):
|
||||
"""
|
||||
Override this to perform additional actions upon the pausing of a print job.
|
||||
"""
|
||||
if not self._inTimelapse:
|
||||
self.startTimelapse(payload["file"])
|
||||
if not self._in_timelapse:
|
||||
self.start_timelapse(payload["file"])
|
||||
|
||||
def eventSubscriptions(self):
|
||||
def event_subscriptions(self):
|
||||
"""
|
||||
Override this method to subscribe to additional events by returning an array of (event, callback) tuples.
|
||||
|
||||
@@ -178,7 +189,7 @@ class Timelapse(object):
|
||||
"""
|
||||
return []
|
||||
|
||||
def configData(self):
|
||||
def config_data(self):
|
||||
"""
|
||||
Override this method to return the current timelapse configuration data. The data should have the following
|
||||
form:
|
||||
@@ -188,105 +199,153 @@ class Timelapse(object):
|
||||
"""
|
||||
return None
|
||||
|
||||
def startTimelapse(self, gcodeFile):
|
||||
def start_timelapse(self, gcodeFile):
|
||||
self._logger.debug("Starting timelapse for %s" % gcodeFile)
|
||||
self.cleanCaptureDir()
|
||||
self.clean_capture_dir()
|
||||
|
||||
self._imageNumber = 0
|
||||
self._inTimelapse = True
|
||||
self._gcodeFile = os.path.basename(gcodeFile)
|
||||
self._image_number = 0
|
||||
self._in_timelapse = True
|
||||
self._gcode_file = os.path.basename(gcodeFile)
|
||||
|
||||
def stopTimelapse(self, doCreateMovie=True, success=True):
|
||||
def stop_timelapse(self, doCreateMovie=True, success=True):
|
||||
self._logger.debug("Stopping timelapse")
|
||||
|
||||
self._inTimelapse = False
|
||||
self._in_timelapse = False
|
||||
|
||||
def resetImageNumber():
|
||||
self._imageNumber = None
|
||||
self._image_number = None
|
||||
|
||||
def createMovie():
|
||||
self._renderThread = threading.Thread(target=self._createMovie, kwargs={"success": success})
|
||||
self._renderThread.daemon = True
|
||||
self._renderThread.start()
|
||||
self._render_thread = threading.Thread(target=self._create_movie, kwargs={"success": success})
|
||||
self._render_thread.daemon = True
|
||||
self._render_thread.start()
|
||||
|
||||
def resetAndCreate():
|
||||
resetImageNumber()
|
||||
createMovie()
|
||||
|
||||
if self._postRoll > 0:
|
||||
self._postRollStart = time.time()
|
||||
def waitForCaptures(callback):
|
||||
self._capture_queue.put(dict(type=self.__class__.QUEUE_ENTRY_TYPE_CALLBACK, callback=callback))
|
||||
|
||||
def getWaitForCaptures(callback):
|
||||
def f():
|
||||
waitForCaptures(callback)
|
||||
return f
|
||||
|
||||
if self._post_roll > 0:
|
||||
eventManager().fire(Events.POSTROLL_START, dict(postroll_duration=self.calculate_post_roll(), postroll_length=self.post_roll, postroll_fps=self.fps))
|
||||
self._post_roll_start = time.time()
|
||||
if doCreateMovie:
|
||||
self._onPostRollDone = resetAndCreate
|
||||
self._on_post_roll_done = getWaitForCaptures(resetAndCreate)
|
||||
else:
|
||||
self._onPostRollDone = resetImageNumber
|
||||
self.processPostRoll()
|
||||
self._on_post_roll_done = resetImageNumber
|
||||
self.process_post_roll()
|
||||
else:
|
||||
self._postRollStart = None
|
||||
self._post_roll_start = None
|
||||
if doCreateMovie:
|
||||
resetAndCreate()
|
||||
waitForCaptures(resetAndCreate)
|
||||
else:
|
||||
resetImageNumber()
|
||||
|
||||
def processPostRoll(self):
|
||||
pass
|
||||
def calculate_post_roll(self):
|
||||
return None
|
||||
|
||||
def process_post_roll(self):
|
||||
self.post_roll_finished()
|
||||
|
||||
def post_roll_finished(self):
|
||||
if self.post_roll:
|
||||
eventManager().fire(Events.POSTROLL_END)
|
||||
if self._on_post_roll_done is not None:
|
||||
self._on_post_roll_done()
|
||||
|
||||
def captureImage(self):
|
||||
if self._captureDir is None:
|
||||
if self._capture_dir is None:
|
||||
self._logger.warn("Cannot capture image, capture directory is unset")
|
||||
return
|
||||
|
||||
if self._imageNumber is None:
|
||||
self._logger.warn("Cannot capture image, image number is unset")
|
||||
return
|
||||
with self._capture_mutex:
|
||||
if self._image_number is None:
|
||||
self._logger.warn("Cannot capture image, image number is unset")
|
||||
return
|
||||
|
||||
filename = os.path.join(self._capture_dir, "tmp_%05d.jpg" % self._image_number)
|
||||
self._image_number += 1
|
||||
|
||||
with self._captureMutex:
|
||||
filename = os.path.join(self._captureDir, "tmp_%05d.jpg" % self._imageNumber)
|
||||
self._imageNumber += 1
|
||||
self._logger.debug("Capturing image to %s" % filename)
|
||||
captureThread = threading.Thread(target=self._captureWorker, kwargs={"filename": filename})
|
||||
captureThread.daemon = True
|
||||
captureThread.start()
|
||||
entry = dict(type=self.__class__.QUEUE_ENTRY_TYPE_CAPTURE,
|
||||
filename=filename,
|
||||
onerror=self._on_capture_error)
|
||||
self._capture_queue.put(entry)
|
||||
return filename
|
||||
|
||||
def _captureWorker(self, filename):
|
||||
def _on_capture_error(self):
|
||||
with self._capture_mutex:
|
||||
if self._image_number is not None and self._image_number > 0:
|
||||
self._image_number -= 1
|
||||
|
||||
def _capture_queue_worker(self):
|
||||
while self._capture_queue_active:
|
||||
entry = self._capture_queue.get(block=True)
|
||||
|
||||
if entry["type"] == self.__class__.QUEUE_ENTRY_TYPE_CAPTURE and "filename" in entry:
|
||||
filename = entry["filename"]
|
||||
onerror = entry.pop("onerror", None)
|
||||
self._perform_capture(filename, onerror=onerror)
|
||||
|
||||
elif entry["type"] == self.__class__.QUEUE_ENTRY_TYPE_CALLBACK and "callback" in entry:
|
||||
args = entry.pop("args", [])
|
||||
kwargs = entry.pop("kwargs", dict())
|
||||
entry["callback"](*args, **kwargs)
|
||||
|
||||
def _perform_capture(self, filename, onerror=None):
|
||||
eventManager().fire(Events.CAPTURE_START, {"file": filename})
|
||||
try:
|
||||
urllib.urlretrieve(self._snapshotUrl, filename)
|
||||
self._logger.debug("Image %s captured from %s" % (filename, self._snapshotUrl))
|
||||
self._logger.debug("Going to capture %s from %s" % (filename, self._snapshot_url))
|
||||
r = requests.get(self._snapshot_url, stream=True)
|
||||
with open (filename, "wb") as f:
|
||||
for chunk in r.iter_content(chunk_size=1024):
|
||||
if chunk:
|
||||
f.write(chunk)
|
||||
f.flush()
|
||||
self._logger.debug("Image %s captured from %s" % (filename, self._snapshot_url))
|
||||
except:
|
||||
self._logger.exception("Could not capture image %s from %s, decreasing image counter again" % (filename, self._snapshotUrl))
|
||||
with self._captureMutex:
|
||||
if self._imageNumber is not None and self._imageNumber > 0:
|
||||
self._imageNumber -= 1
|
||||
eventManager().fire(Events.CAPTURE_DONE, {"file": filename})
|
||||
self._logger.exception("Could not capture image %s from %s" % (filename, self._snapshot_url))
|
||||
if callable(onerror):
|
||||
onerror()
|
||||
eventManager().fire(Events.CAPTURE_FAILED, {"file": filename})
|
||||
return False
|
||||
else:
|
||||
eventManager().fire(Events.CAPTURE_DONE, {"file": filename})
|
||||
return True
|
||||
|
||||
def _createMovie(self, success=True):
|
||||
def _create_movie(self, success=True):
|
||||
ffmpeg = settings().get(["webcam", "ffmpeg"])
|
||||
bitrate = settings().get(["webcam", "bitrate"])
|
||||
if ffmpeg is None or bitrate is None:
|
||||
self._logger.warn("Cannot create movie, path to ffmpeg or desired bitrate is unset")
|
||||
return
|
||||
|
||||
input = os.path.join(self._captureDir, "tmp_%05d.jpg")
|
||||
input = os.path.join(self._capture_dir, "tmp_%05d.jpg")
|
||||
if success:
|
||||
output = os.path.join(self._movieDir, "%s_%s.mpg" % (os.path.splitext(self._gcodeFile)[0], time.strftime("%Y%m%d%H%M%S")))
|
||||
output = os.path.join(self._movie_dir, "%s_%s.mpg" % (os.path.splitext(self._gcode_file)[0], time.strftime("%Y%m%d%H%M%S")))
|
||||
else:
|
||||
output = os.path.join(self._movieDir, "%s_%s-failed.mpg" % (os.path.splitext(self._gcodeFile)[0], time.strftime("%Y%m%d%H%M%S")))
|
||||
output = os.path.join(self._movie_dir, "%s_%s-failed.mpg" % (os.path.splitext(self._gcode_file)[0], time.strftime("%Y%m%d%H%M%S")))
|
||||
|
||||
# prepare ffmpeg command
|
||||
command = [
|
||||
ffmpeg, '-framerate', str(self._fps), '-loglevel', 'error', '-i', input, '-vcodec', 'mpeg2video', '-threads', str(self._ffmpegThreads), '-pix_fmt', 'yuv420p', '-r', str(self._fps), '-y', '-b', bitrate,
|
||||
ffmpeg, '-framerate', str(self._fps), '-loglevel', 'error', '-i', input, '-vcodec', 'mpeg2video', '-threads', str(self._ffmpeg_threads), '-pix_fmt', 'yuv420p', '-r', str(self._fps), '-y', '-b', bitrate,
|
||||
'-f', 'vob']
|
||||
|
||||
filters = []
|
||||
|
||||
# flip video if configured
|
||||
if settings().getBoolean(["webcam", "rotate90"]):
|
||||
filters.append('transpose=1')
|
||||
if settings().getBoolean(["webcam", "flipH"]):
|
||||
filters.append('hflip')
|
||||
if settings().getBoolean(["webcam", "flipV"]):
|
||||
filters.append('vflip')
|
||||
if settings().getBoolean(["webcam", "rotate90"]):
|
||||
filters.append('transpose=2')
|
||||
|
||||
# add watermark if configured
|
||||
watermarkFilter = None
|
||||
@@ -315,7 +374,7 @@ class Timelapse(object):
|
||||
# finalize command with output file
|
||||
self._logger.debug("Rendering movie to %s" % output)
|
||||
command.append("\"" + output + "\"")
|
||||
eventManager().fire(Events.MOVIE_RENDERING, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output)})
|
||||
eventManager().fire(Events.MOVIE_RENDERING, {"gcode": self._gcode_file, "movie": output, "movie_basename": os.path.basename(output)})
|
||||
|
||||
command_str = " ".join(command)
|
||||
self._logger.debug("Executing command: %s" % command_str)
|
||||
@@ -323,75 +382,74 @@ class Timelapse(object):
|
||||
try:
|
||||
p = sarge.run(command_str, stderr=sarge.Capture())
|
||||
if p.returncode == 0:
|
||||
eventManager().fire(Events.MOVIE_DONE, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output)})
|
||||
eventManager().fire(Events.MOVIE_DONE, {"gcode": self._gcode_file, "movie": output, "movie_basename": os.path.basename(output)})
|
||||
else:
|
||||
returncode = p.returncode
|
||||
stderr_text = p.stderr.text
|
||||
self._logger.warn("Could not render movie, got return code %r: %s" % (returncode, stderr_text))
|
||||
eventManager().fire(Events.MOVIE_FAILED, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output), "returncode": returncode, "error": stderr_text})
|
||||
eventManager().fire(Events.MOVIE_FAILED, {"gcode": self._gcode_file, "movie": output, "movie_basename": os.path.basename(output), "returncode": returncode, "error": stderr_text})
|
||||
except:
|
||||
self._logger.exception("Could not render movie due to unknown error")
|
||||
eventManager().fire(Events.MOVIE_FAILED, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output), "returncode": 255, "error": "Unknown error"})
|
||||
eventManager().fire(Events.MOVIE_FAILED, {"gcode": self._gcode_file, "movie": output, "movie_basename": os.path.basename(output), "returncode": 255, "error": "Unknown error"})
|
||||
|
||||
def cleanCaptureDir(self):
|
||||
if not os.path.isdir(self._captureDir):
|
||||
def clean_capture_dir(self):
|
||||
if not os.path.isdir(self._capture_dir):
|
||||
self._logger.warn("Cannot clean capture directory, it is unset")
|
||||
return
|
||||
|
||||
for filename in os.listdir(self._captureDir):
|
||||
for filename in os.listdir(self._capture_dir):
|
||||
if not fnmatch.fnmatch(filename, "*.jpg"):
|
||||
continue
|
||||
os.remove(os.path.join(self._captureDir, filename))
|
||||
os.remove(os.path.join(self._capture_dir, filename))
|
||||
|
||||
|
||||
class ZTimelapse(Timelapse):
|
||||
def __init__(self, postRoll=0, fps=25):
|
||||
Timelapse.__init__(self, postRoll=postRoll, fps=fps)
|
||||
def __init__(self, post_roll=0, fps=25):
|
||||
Timelapse.__init__(self, post_roll=post_roll, fps=fps)
|
||||
self._logger.debug("ZTimelapse initialized")
|
||||
|
||||
def eventSubscriptions(self):
|
||||
def event_subscriptions(self):
|
||||
return [
|
||||
(Events.Z_CHANGE, self._onZChange)
|
||||
(Events.Z_CHANGE, self._on_z_change)
|
||||
]
|
||||
|
||||
def configData(self):
|
||||
def config_data(self):
|
||||
return {
|
||||
"type": "zchange"
|
||||
}
|
||||
|
||||
def processPostRoll(self):
|
||||
Timelapse.processPostRoll(self)
|
||||
def process_post_roll(self):
|
||||
with self._capture_mutex:
|
||||
filename = os.path.join(self._capture_dir, "tmp_%05d.jpg" % self._image_number)
|
||||
self._image_number += 1
|
||||
|
||||
filename = os.path.join(self._captureDir, "tmp_%05d.jpg" % self._imageNumber)
|
||||
self._imageNumber += 1
|
||||
with self._captureMutex:
|
||||
self._captureWorker(filename)
|
||||
if self._perform_capture(filename):
|
||||
for _ in range(self._post_roll * self._fps):
|
||||
newFile = os.path.join(self._capture_dir, "tmp_%05d.jpg" % self._image_number)
|
||||
self._image_number += 1
|
||||
shutil.copyfile(filename, newFile)
|
||||
|
||||
for i in range(self._postRoll * self._fps):
|
||||
newFile = os.path.join(self._captureDir, "tmp_%05d.jpg" % (self._imageNumber))
|
||||
self._imageNumber += 1
|
||||
shutil.copyfile(filename, newFile)
|
||||
Timelapse.process_post_roll(self)
|
||||
|
||||
if self._onPostRollDone is not None:
|
||||
self._onPostRollDone()
|
||||
|
||||
def _onZChange(self, event, payload):
|
||||
def _on_z_change(self, event, payload):
|
||||
self.captureImage()
|
||||
|
||||
|
||||
class TimedTimelapse(Timelapse):
|
||||
def __init__(self, postRoll=0, interval=1, fps=25):
|
||||
Timelapse.__init__(self, postRoll=postRoll, fps=fps)
|
||||
def __init__(self, post_roll=0, interval=1, fps=25):
|
||||
Timelapse.__init__(self, post_roll=post_roll, fps=fps)
|
||||
self._interval = interval
|
||||
if self._interval < 1:
|
||||
self._interval = 1 # force minimum interval of 1s
|
||||
self._timerThread = None
|
||||
self._postroll_captures = 0
|
||||
self._timer = None
|
||||
self._logger.debug("TimedTimelapse initialized")
|
||||
|
||||
@property
|
||||
def interval(self):
|
||||
return self._interval
|
||||
|
||||
def configData(self):
|
||||
def config_data(self):
|
||||
return {
|
||||
"type": "timed",
|
||||
"options": {
|
||||
@@ -399,25 +457,39 @@ class TimedTimelapse(Timelapse):
|
||||
}
|
||||
}
|
||||
|
||||
def onPrintStarted(self, event, payload):
|
||||
Timelapse.onPrintStarted(self, event, payload)
|
||||
if self._timerThread is not None:
|
||||
def on_print_started(self, event, payload):
|
||||
Timelapse.on_print_started(self, event, payload)
|
||||
if self._timer is not None:
|
||||
return
|
||||
|
||||
self._timerThread = threading.Thread(target=self._timerWorker)
|
||||
self._timerThread.daemon = True
|
||||
self._timerThread.start()
|
||||
|
||||
def onPrintDone(self, event, payload):
|
||||
Timelapse.onPrintDone(self, event, payload)
|
||||
self._timerThread = None
|
||||
|
||||
def _timerWorker(self):
|
||||
self._logger.debug("Starting timer for interval based timelapse")
|
||||
while self._inTimelapse or (self._postRollStart and time.time() - self._postRollStart <= self._postRoll * self._fps):
|
||||
self.captureImage()
|
||||
time.sleep(self._interval)
|
||||
from octoprint.util import RepeatedTimer
|
||||
self._timer = RepeatedTimer(self._interval, self._timer_task,
|
||||
run_first=True, condition=self._timer_active,
|
||||
on_finish=self._on_timer_finished)
|
||||
self._timer.start()
|
||||
|
||||
if self._postRollStart is not None and self._onPostRollDone is not None:
|
||||
self._onPostRollDone()
|
||||
self._postRollStart = None
|
||||
def on_print_done(self, event, payload):
|
||||
self._postroll_captures = self.post_roll * self.fps
|
||||
Timelapse.on_print_done(self, event, payload)
|
||||
|
||||
def calculate_post_roll(self):
|
||||
return self.post_roll * self.fps * self.interval
|
||||
|
||||
def process_post_roll(self):
|
||||
pass
|
||||
|
||||
def post_roll_finished(self):
|
||||
Timelapse.post_roll_finished(self)
|
||||
self._timer = None
|
||||
|
||||
def _timer_active(self):
|
||||
return self._in_timelapse or self._postroll_captures > 0
|
||||
|
||||
def _timer_task(self):
|
||||
self.captureImage()
|
||||
if self._postroll_captures > 0:
|
||||
self._postroll_captures -= 1
|
||||
|
||||
def _on_timer_finished(self):
|
||||
self.post_roll_finished()
|
||||
Binary file not shown.
File diff suppressed because it is too large.
Load diff
+39
-29
@@ -17,29 +17,37 @@ import logging
|
||||
|
||||
from octoprint.settings import settings
|
||||
|
||||
from octoprint.util import atomic_write
|
||||
|
||||
class UserManager(object):
|
||||
valid_roles = ["user", "admin"]
|
||||
|
||||
def __init__(self):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._session_users_by_session = dict()
|
||||
self._session_users_by_username = dict()
|
||||
self._session_users_by_userid = dict()
|
||||
|
||||
def login_user(self, user):
|
||||
self._cleanup_sessions()
|
||||
|
||||
if user is None \
|
||||
or (isinstance(user, LocalProxy) and not isinstance(user._get_current_object(), User)) \
|
||||
or (not isinstance(user, LocalProxy) and not isinstance(user, User)):
|
||||
if user is None:
|
||||
return
|
||||
|
||||
if isinstance(user, LocalProxy):
|
||||
user = user._get_current_object()
|
||||
|
||||
if not isinstance(user, User):
|
||||
return None
|
||||
|
||||
if not isinstance(user, SessionUser):
|
||||
user = SessionUser(user)
|
||||
|
||||
self._session_users_by_session[user.get_session()] = user
|
||||
|
||||
if not user.get_name() in self._session_users_by_username:
|
||||
self._session_users_by_username[user.get_name()] = []
|
||||
self._session_users_by_username[user.get_name()].append(user)
|
||||
userid = user.get_id()
|
||||
if not userid in self._session_users_by_userid:
|
||||
self._session_users_by_userid[userid] = []
|
||||
self._session_users_by_userid[userid].append(user)
|
||||
|
||||
self._logger.debug("Logged in user: %r" % user)
|
||||
|
||||
@@ -49,14 +57,18 @@ class UserManager(object):
|
||||
if user is None:
|
||||
return
|
||||
|
||||
if isinstance(user, LocalProxy):
|
||||
user = user._get_current_object()
|
||||
|
||||
if not isinstance(user, SessionUser):
|
||||
return
|
||||
|
||||
if user.get_name() in self._session_users_by_username:
|
||||
users_by_username = self._session_users_by_username[user.get_name()]
|
||||
for u in users_by_username:
|
||||
userid = user.get_id()
|
||||
if userid in self._session_users_by_userid:
|
||||
users_by_userid = self._session_users_by_userid[userid]
|
||||
for u in users_by_userid:
|
||||
if u.get_session() == user.get_session():
|
||||
users_by_username.remove(u)
|
||||
users_by_userid.remove(u)
|
||||
break
|
||||
|
||||
if user.get_session() in self._session_users_by_session:
|
||||
@@ -137,21 +149,19 @@ class UserManager(object):
|
||||
pass
|
||||
|
||||
def removeUser(self, username):
|
||||
if username in self._session_users_by_username:
|
||||
users = self._session_users_by_username[username]
|
||||
if username in self._session_users_by_userid:
|
||||
users = self._session_users_by_userid[username]
|
||||
sessions = [user.get_session() for user in users if isinstance(user, SessionUser)]
|
||||
for session in sessions:
|
||||
if session in self._session_users_by_session:
|
||||
del self._session_users_by_session[session]
|
||||
del self._session_users_by_username[username]
|
||||
del self._session_users_by_userid[username]
|
||||
|
||||
def findUser(self, username=None, session=None):
|
||||
if session is not None:
|
||||
for session in self._session_users_by_session:
|
||||
user = self._session_users_by_session[session]
|
||||
if username is None or username == user.get_name():
|
||||
return user
|
||||
break
|
||||
def findUser(self, userid=None, session=None):
|
||||
if session is not None and session in self._session_users_by_session:
|
||||
user = self._session_users_by_session[session]
|
||||
if userid is None or userid == user.get_id():
|
||||
return user
|
||||
|
||||
return None
|
||||
|
||||
@@ -209,7 +219,7 @@ class FilebasedUserManager(UserManager):
|
||||
"settings": user._settings
|
||||
}
|
||||
|
||||
with open(self._userfile, "wb") as f:
|
||||
with atomic_write(self._userfile, "wb") as f:
|
||||
yaml.safe_dump(data, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
self._dirty = False
|
||||
self._load()
|
||||
@@ -345,16 +355,16 @@ class FilebasedUserManager(UserManager):
|
||||
self._dirty = True
|
||||
self._save()
|
||||
|
||||
def findUser(self, username=None, apikey=None, session=None):
|
||||
user = UserManager.findUser(self, username=username, session=session)
|
||||
def findUser(self, userid=None, apikey=None, session=None):
|
||||
user = UserManager.findUser(self, userid=userid, session=session)
|
||||
|
||||
if user is not None:
|
||||
return user
|
||||
|
||||
if username is not None:
|
||||
if username not in self._users.keys():
|
||||
if userid is not None:
|
||||
if userid not in self._users.keys():
|
||||
return None
|
||||
return self._users[username]
|
||||
return self._users[userid]
|
||||
|
||||
elif apikey is not None:
|
||||
for user in self._users.values():
|
||||
@@ -413,7 +423,7 @@ class User(UserMixin):
|
||||
return self._passwordHash == passwordHash
|
||||
|
||||
def get_id(self):
|
||||
return self._username
|
||||
return self.get_name()
|
||||
|
||||
def get_name(self):
|
||||
return self._username
|
||||
@@ -474,7 +484,7 @@ class User(UserMixin):
|
||||
|
||||
class SessionUser(User):
|
||||
def __init__(self, user):
|
||||
User.__init__(self, user._username, user._passwordHash, user._active, user._roles, user._apikey)
|
||||
User.__init__(self, user._username, user._passwordHash, user._active, user._roles, user._apikey, user._settings)
|
||||
|
||||
import string
|
||||
import random
|
||||
|
||||
@@ -17,7 +17,7 @@ import shutil
|
||||
import threading
|
||||
from functools import wraps
|
||||
import warnings
|
||||
|
||||
import contextlib
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -197,29 +197,12 @@ def get_exception_string():
|
||||
return "%s: '%s' @ %s:%s:%d" % (str(sys.exc_info()[0].__name__), str(sys.exc_info()[1]), os.path.basename(locationInfo[0]), locationInfo[2], locationInfo[1])
|
||||
|
||||
|
||||
@deprecated("get_free_bytes has been deprecated and will be removed in the future",
|
||||
includedoc="Replaced by `psutil.disk_usage <http://pythonhosted.org/psutil/#psutil.disk_usage>`_.",
|
||||
since="1.2.5")
|
||||
def get_free_bytes(path):
|
||||
"""
|
||||
Retrieves the number of free bytes on the partition ``path`` is located at and returns it. Works on both Windows and
|
||||
Unix/Linux.
|
||||
|
||||
Taken from http://stackoverflow.com/a/2372171/2028598
|
||||
|
||||
Arguments:
|
||||
path (string): The path for which to check the remaining partition space.
|
||||
|
||||
Returns:
|
||||
int: The amount of bytes still left on the partition.
|
||||
"""
|
||||
|
||||
path = os.path.abspath(path)
|
||||
if sys.platform == "win32":
|
||||
import ctypes
|
||||
freeBytes = ctypes.c_ulonglong(0)
|
||||
ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(path), None, None, ctypes.pointer(freeBytes))
|
||||
return freeBytes.value
|
||||
else:
|
||||
st = os.statvfs(path)
|
||||
return st.f_bavail * st.f_frsize
|
||||
import psutil
|
||||
return psutil.disk_usage(path).free
|
||||
|
||||
|
||||
def get_dos_filename(origin, existing_filenames=None, extension=None, **kwargs):
|
||||
@@ -352,9 +335,7 @@ def silent_remove(file):
|
||||
def sanitize_ascii(line):
|
||||
if not isinstance(line, basestring):
|
||||
raise ValueError("Expected either str or unicode but got {} instead".format(line.__class__.__name__ if line is not None else None))
|
||||
if isinstance(line, str):
|
||||
line = unicode(line, 'ascii', 'replace')
|
||||
return line.encode('ascii', 'replace').rstrip()
|
||||
return to_unicode(line, encoding="ascii", errors="replace").rstrip()
|
||||
|
||||
|
||||
def filter_non_ascii(line):
|
||||
@@ -369,12 +350,28 @@ def filter_non_ascii(line):
|
||||
"""
|
||||
|
||||
try:
|
||||
unicode(line, 'ascii').encode('ascii')
|
||||
to_str(to_unicode(line, encoding="ascii"), encoding="ascii")
|
||||
return False
|
||||
except ValueError:
|
||||
return True
|
||||
|
||||
|
||||
def to_str(s_or_u, encoding="utf-8", errors="strict"):
|
||||
"""Make sure ``s_or_u`` is a str."""
|
||||
if isinstance(s_or_u, unicode):
|
||||
return s_or_u.encode(encoding, errors=errors)
|
||||
else:
|
||||
return s_or_u
|
||||
|
||||
|
||||
def to_unicode(s_or_u, encoding="utf-8", errors="strict"):
|
||||
"""Make sure ``s_or_u`` is a unicode string."""
|
||||
if isinstance(s_or_u, str):
|
||||
return s_or_u.decode(encoding, errors=errors)
|
||||
else:
|
||||
return s_or_u
|
||||
|
||||
|
||||
def dict_merge(a, b):
|
||||
"""
|
||||
Recursively deep-merges two dictionaries.
|
||||
@@ -499,6 +496,38 @@ def address_for_client(host, port):
|
||||
except:
|
||||
continue
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def atomic_write(filename, mode="w+b", prefix="tmp", suffix=""):
|
||||
temp_config = tempfile.NamedTemporaryFile(mode=mode, prefix=prefix, suffix=suffix, delete=False)
|
||||
yield temp_config
|
||||
temp_config.close()
|
||||
shutil.move(temp_config.name, filename)
|
||||
|
||||
|
||||
def bom_aware_open(filename, encoding="ascii", mode="r", **kwargs):
|
||||
import codecs
|
||||
|
||||
codec = codecs.lookup(encoding)
|
||||
encoding = codec.name
|
||||
|
||||
if kwargs is None:
|
||||
kwargs = dict()
|
||||
|
||||
potential_bom_attribute = "BOM_" + codec.name.replace("utf-", "utf").upper()
|
||||
if "r" in mode and hasattr(codecs, potential_bom_attribute):
|
||||
# these encodings might have a BOM, so let's see if there is one
|
||||
bom = getattr(codecs, potential_bom_attribute)
|
||||
|
||||
with open(filename, "rb") as f:
|
||||
header = f.read(4)
|
||||
|
||||
if header.startswith(bom):
|
||||
encoding += "-sig"
|
||||
|
||||
return codecs.open(filename, encoding=encoding, **kwargs)
|
||||
|
||||
|
||||
class RepeatedTimer(threading.Thread):
|
||||
"""
|
||||
This class represents an action that should be run repeatedly in an interval. It is similar to python's
|
||||
@@ -556,9 +585,18 @@ class RepeatedTimer(threading.Thread):
|
||||
run_first (boolean): If set to True, the function will be run for the first time *before* the first wait period.
|
||||
If set to False (the default), the function will be run for the first time *after* the first wait period.
|
||||
condition (callable): Condition that needs to be True for loop to continue. Defaults to ``lambda: True``.
|
||||
on_condition_false (callable): Callback to call when the timer finishes due to condition becoming false. Will
|
||||
be called before the ``on_finish`` callback.
|
||||
on_cancelled (callable): Callback to call when the timer finishes due to being cancelled. Will be called
|
||||
before the ``on_finish`` callback.
|
||||
on_finish (callable): Callback to call when the timer finishes, either due to being cancelled or since
|
||||
the condition became false.
|
||||
daemon (bool): daemon flag to set on underlying thread.
|
||||
"""
|
||||
|
||||
def __init__(self, interval, function, args=None, kwargs=None, run_first=False, condition=None):
|
||||
def __init__(self, interval, function, args=None, kwargs=None,
|
||||
run_first=False, condition=None, on_condition_false=None,
|
||||
on_cancelled=None, on_finish=None, daemon=True):
|
||||
threading.Thread.__init__(self)
|
||||
|
||||
if args is None:
|
||||
@@ -580,8 +618,14 @@ class RepeatedTimer(threading.Thread):
|
||||
self.run_first = run_first
|
||||
self.condition = condition
|
||||
|
||||
self.on_condition_false = on_condition_false
|
||||
self.on_cancelled = on_cancelled
|
||||
self.on_finish = on_finish
|
||||
|
||||
self.daemon = daemon
|
||||
|
||||
def cancel(self):
|
||||
self.finished.set()
|
||||
self._finish(self.on_cancelled)
|
||||
|
||||
def run(self):
|
||||
while self.condition():
|
||||
@@ -596,15 +640,26 @@ class RepeatedTimer(threading.Thread):
|
||||
# wait, but break if we are cancelled
|
||||
self.finished.wait(self.interval())
|
||||
if self.finished.is_set():
|
||||
break
|
||||
return
|
||||
|
||||
if not self.run_first:
|
||||
# if we are to run the function AFTER waiting for the first time
|
||||
self.function(*self.args, **self.kwargs)
|
||||
|
||||
# make sure we set our finished event so we can detect that the loop was finished
|
||||
# we'll only get here if the condition was false
|
||||
self._finish(self.on_condition_false)
|
||||
|
||||
def _finish(self, *callbacks):
|
||||
self.finished.set()
|
||||
|
||||
for callback in callbacks:
|
||||
if not callable(callback):
|
||||
continue
|
||||
callback()
|
||||
|
||||
if callable(self.on_finish):
|
||||
self.on_finish()
|
||||
|
||||
|
||||
class CountedEvent(object):
|
||||
|
||||
@@ -681,4 +736,4 @@ class InvariantContainer(object):
|
||||
return len(self._data)
|
||||
|
||||
def __iter__(self):
|
||||
return self._data.__iter__()
|
||||
return self._data.__iter__()
|
||||
+388
-164
@@ -24,13 +24,86 @@ from octoprint.settings import settings, default_settings
|
||||
from octoprint.events import eventManager, Events
|
||||
from octoprint.filemanager import valid_file_type
|
||||
from octoprint.filemanager.destinations import FileDestinations
|
||||
from octoprint.util import get_exception_string, sanitize_ascii, filter_non_ascii, CountedEvent, RepeatedTimer
|
||||
from octoprint.util import get_exception_string, sanitize_ascii, filter_non_ascii, CountedEvent, RepeatedTimer, to_unicode, bom_aware_open
|
||||
|
||||
try:
|
||||
import _winreg
|
||||
except:
|
||||
pass
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
# a bunch of regexes we'll need for the communication parsing...
|
||||
|
||||
regex_float_pattern = "[-+]?[0-9]*\.?[0-9]+"
|
||||
regex_positive_float_pattern = "[+]?[0-9]*\.?[0-9]+"
|
||||
regex_int_pattern = "\d+"
|
||||
|
||||
regex_command = re.compile("^\s*((?P<commandGM>[GM]\d+)|(?P<commandT>T)\d+)")
|
||||
"""Regex for a GCODE command."""
|
||||
|
||||
regex_float = re.compile(regex_float_pattern)
|
||||
"""Regex for a float value."""
|
||||
|
||||
regexes_parameters = dict(
|
||||
floatP=re.compile("(^|[^A-Za-z])[Pp](?P<value>%s)" % regex_float_pattern),
|
||||
floatS=re.compile("(^|[^A-Za-z])[Ss](?P<value>%s)" % regex_float_pattern),
|
||||
floatZ=re.compile("(^|[^A-Za-z])[Zz](?P<value>%s)" % regex_float_pattern),
|
||||
intN=re.compile("(^|[^A-Za-z])[Nn](?P<value>%s)" % regex_int_pattern),
|
||||
intT=re.compile("(^|[^A-Za-z])[Tt](?P<value>%s)" % regex_int_pattern)
|
||||
)
|
||||
"""Regexes for parsing various GCODE command parameters."""
|
||||
|
||||
regex_minMaxError = re.compile("Error:[0-9]\n")
|
||||
"""Regex matching first line of min/max errors from the firmware."""
|
||||
|
||||
regex_sdPrintingByte = re.compile("(?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
|
||||
"""
|
||||
|
||||
regex_sdFileOpened = re.compile("File opened:\s*(?P<name>.*?)\s+Size:\s*(?P<size>%s)" % regex_int_pattern)
|
||||
"""Regex matching "File opened" messages from the firmware.
|
||||
|
||||
Groups will be as follows:
|
||||
|
||||
* ``name``: name of the file reported as having been opened (str)
|
||||
* ``size``: size of the file in bytes (int)
|
||||
"""
|
||||
|
||||
regex_temp = re.compile("(?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_repetierTempExtr = 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_repetierTempBed = 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)
|
||||
"""
|
||||
|
||||
def serialList():
|
||||
baselist=[]
|
||||
if os.name=="nt":
|
||||
@@ -151,6 +224,7 @@ class MachineCom(object):
|
||||
|
||||
self._long_running_command = False
|
||||
self._heating = False
|
||||
self._connection_closing = False
|
||||
|
||||
self._timeout = None
|
||||
|
||||
@@ -158,12 +232,15 @@ class MachineCom(object):
|
||||
self._sendChecksumWithUnknownCommands = settings().getBoolean(["feature", "sendChecksumWithUnknownCommands"])
|
||||
self._unknownCommandsNeedAck = settings().getBoolean(["feature", "unknownCommandsNeedAck"])
|
||||
self._currentLine = 1
|
||||
self._line_mutex = threading.RLock()
|
||||
self._resendDelta = None
|
||||
self._lastLines = deque([], 50)
|
||||
self._lastCommError = None
|
||||
self._lastResendNumber = None
|
||||
self._currentResendCount = 0
|
||||
self._resendSwallowNextOk = False
|
||||
self._resendSwallowRepetitions = settings().getBoolean(["feature", "ignoreIdenticalResends"])
|
||||
self._resendSwallowRepetitionsCounter = 0
|
||||
|
||||
self._clear_to_send = CountedEvent(max=10, name="comm.clear_to_send")
|
||||
self._send_queue = TypedQueue()
|
||||
@@ -195,28 +272,6 @@ class MachineCom(object):
|
||||
self._currentFile = None
|
||||
|
||||
# regexes
|
||||
floatPattern = "[-+]?[0-9]*\.?[0-9]+"
|
||||
positiveFloatPattern = "[+]?[0-9]*\.?[0-9]+"
|
||||
intPattern = "\d+"
|
||||
self._regex_command = re.compile("^\s*([GM]\d+|T)")
|
||||
self._regex_float = re.compile(floatPattern)
|
||||
self._regex_paramZFloat = re.compile("Z(%s)" % floatPattern)
|
||||
self._regex_paramSInt = re.compile("S(%s)" % intPattern)
|
||||
self._regex_paramNInt = re.compile("N(%s)" % intPattern)
|
||||
self._regex_paramTInt = re.compile("T(%s)" % intPattern)
|
||||
self._regex_minMaxError = re.compile("Error:[0-9]\n")
|
||||
self._regex_sdPrintingByte = re.compile("([0-9]*)/([0-9]*)")
|
||||
self._regex_sdFileOpened = re.compile("File opened:\s*(.*?)\s+Size:\s*(%s)" % intPattern)
|
||||
|
||||
# Regex matching temperature entries in line. Groups will be as follows:
|
||||
# - 1: whole tool designator incl. optional toolNumber ("T", "Tn", "B")
|
||||
# - 2: toolNumber, if given ("", "n", "")
|
||||
# - 3: actual temperature
|
||||
# - 4: whole target substring, if given (e.g. " / 22.0")
|
||||
# - 5: target temperature
|
||||
self._regex_temp = re.compile("(B|T(\d*)):\s*(%s)(\s*\/?\s*(%s))?" % (positiveFloatPattern, positiveFloatPattern))
|
||||
self._regex_repetierTempExtr = re.compile("TargetExtr([0-9]+):(%s)" % positiveFloatPattern)
|
||||
self._regex_repetierTempBed = re.compile("TargetBed:(%s)" % positiveFloatPattern)
|
||||
|
||||
self._long_running_commands = settings().get(["serial", "longRunningCommands"])
|
||||
|
||||
@@ -383,6 +438,10 @@ class MachineCom(object):
|
||||
##~~ external interface
|
||||
|
||||
def close(self, isError = False):
|
||||
if self._connection_closing:
|
||||
return
|
||||
self._connection_closing = True
|
||||
|
||||
if self._temperature_timer is not None:
|
||||
try:
|
||||
self._temperature_timer.cancel()
|
||||
@@ -400,11 +459,15 @@ class MachineCom(object):
|
||||
|
||||
printing = self.isPrinting() or self.isPaused()
|
||||
if self._serial is not None:
|
||||
try:
|
||||
self._serial.close()
|
||||
except:
|
||||
self._logger.exception("Error while trying to close serial port")
|
||||
isError = True
|
||||
if isError:
|
||||
self._changeState(self.STATE_CLOSED_WITH_ERROR)
|
||||
else:
|
||||
self._changeState(self.STATE_CLOSED)
|
||||
self._serial.close()
|
||||
self._serial = None
|
||||
|
||||
if settings().get(["feature", "sdSupport"]):
|
||||
@@ -428,7 +491,7 @@ class MachineCom(object):
|
||||
self._clear_to_send.set()
|
||||
|
||||
def sendCommand(self, cmd, cmd_type=None, processed=False):
|
||||
cmd = cmd.encode('ascii', 'replace')
|
||||
cmd = to_unicode(cmd, errors="replace")
|
||||
if not processed:
|
||||
cmd = process_gcode_line(cmd)
|
||||
if not cmd:
|
||||
@@ -529,7 +592,7 @@ class MachineCom(object):
|
||||
|
||||
self.sendCommand("M24")
|
||||
|
||||
self._sd_status_timer = RepeatedTimer(lambda: get_interval("sdStatus"), self._poll_sd_status, run_first=True)
|
||||
self._sd_status_timer = RepeatedTimer(lambda: get_interval("sdStatus", default_value=1.0), self._poll_sd_status, run_first=True)
|
||||
self._sd_status_timer.start()
|
||||
else:
|
||||
line = self._getNext()
|
||||
@@ -708,51 +771,9 @@ class MachineCom(object):
|
||||
|
||||
##~~ communication monitoring and handling
|
||||
|
||||
def _parseTemperatures(self, line):
|
||||
result = {}
|
||||
maxToolNum = 0
|
||||
for match in re.finditer(self._regex_temp, line):
|
||||
tool = match.group(1)
|
||||
toolNumber = int(match.group(2)) if match.group(2) and len(match.group(2)) > 0 else None
|
||||
if toolNumber > maxToolNum:
|
||||
maxToolNum = toolNumber
|
||||
|
||||
try:
|
||||
actual = float(match.group(3))
|
||||
target = None
|
||||
if match.group(4) and match.group(5):
|
||||
target = float(match.group(5))
|
||||
|
||||
result[tool] = (toolNumber, actual, target)
|
||||
except ValueError:
|
||||
# catch conversion issues, we'll rather just not get the temperature update instead of killing the connection
|
||||
pass
|
||||
|
||||
if "T0" in result.keys() and "T" in result.keys():
|
||||
del result["T"]
|
||||
|
||||
return maxToolNum, result
|
||||
|
||||
def _processTemperatures(self, line):
|
||||
maxToolNum, parsedTemps = self._parseTemperatures(line)
|
||||
|
||||
# extruder temperatures
|
||||
if not "T0" in parsedTemps.keys() and not "T1" in parsedTemps.keys() and "T" in parsedTemps.keys():
|
||||
# no T1 so only single reporting, "T" is our one and only extruder temperature
|
||||
toolNum, actual, target = parsedTemps["T"]
|
||||
|
||||
if target is not None:
|
||||
self._temp[0] = (actual, target)
|
||||
elif 0 in self._temp.keys() and self._temp[0] is not None and isinstance(self._temp[0], tuple):
|
||||
(oldActual, oldTarget) = self._temp[0]
|
||||
self._temp[0] = (actual, oldTarget)
|
||||
else:
|
||||
self._temp[0] = (actual, None)
|
||||
elif not "T0" in parsedTemps.keys() and "T" in parsedTemps.keys():
|
||||
# Smoothieware sends multi extruder temperature data this way: "T:<first extruder> T1:<second extruder> ..." and therefore needs some special treatment...
|
||||
_, actual, target = parsedTemps["T"]
|
||||
del parsedTemps["T"]
|
||||
parsedTemps["T0"] = (0, actual, target)
|
||||
current_tool = self._currentTool if self._currentTool is not None else 0
|
||||
maxToolNum, parsedTemps = parse_temperature_line(line, current_tool)
|
||||
|
||||
if "T0" in parsedTemps.keys():
|
||||
for n in range(maxToolNum + 1):
|
||||
@@ -760,18 +781,18 @@ class MachineCom(object):
|
||||
if not tool in parsedTemps.keys():
|
||||
continue
|
||||
|
||||
toolNum, actual, target = parsedTemps[tool]
|
||||
actual, target = parsedTemps[tool]
|
||||
if target is not None:
|
||||
self._temp[toolNum] = (actual, target)
|
||||
elif toolNum in self._temp.keys() and self._temp[toolNum] is not None and isinstance(self._temp[toolNum], tuple):
|
||||
(oldActual, oldTarget) = self._temp[toolNum]
|
||||
self._temp[toolNum] = (actual, oldTarget)
|
||||
self._temp[n] = (actual, target)
|
||||
elif n in self._temp and self._temp[n] is not None and isinstance(self._temp[n], tuple):
|
||||
(oldActual, oldTarget) = self._temp[n]
|
||||
self._temp[n] = (actual, oldTarget)
|
||||
else:
|
||||
self._temp[toolNum] = (actual, None)
|
||||
self._temp[n] = (actual, None)
|
||||
|
||||
# bed temperature
|
||||
if "B" in parsedTemps.keys():
|
||||
toolNum, actual, target = parsedTemps["B"]
|
||||
actual, target = parsedTemps["B"]
|
||||
if target is not None:
|
||||
self._bedTemp = (actual, target)
|
||||
elif self._bedTemp is not None and isinstance(self._bedTemp, tuple):
|
||||
@@ -844,7 +865,11 @@ class MachineCom(object):
|
||||
self._callback.on_comm_force_disconnect()
|
||||
else:
|
||||
for hook in self._printer_action_hooks:
|
||||
self._printer_action_hooks[hook](self, line, action_command)
|
||||
try:
|
||||
self._printer_action_hooks[hook](self, line, action_command)
|
||||
except:
|
||||
self._logger.exception("Error while calling hook {} with action command {}".format(self._printer_action_hooks[hook], action_command))
|
||||
continue
|
||||
else:
|
||||
continue
|
||||
|
||||
@@ -895,8 +920,8 @@ class MachineCom(object):
|
||||
self._callback.on_comm_temperature_update(self._temp, self._bedTemp)
|
||||
|
||||
elif supportRepetierTargetTemp and ('TargetExtr' in line or 'TargetBed' in line):
|
||||
matchExtr = self._regex_repetierTempExtr.match(line)
|
||||
matchBed = self._regex_repetierTempBed.match(line)
|
||||
matchExtr = regex_repetierTempExtr.match(line)
|
||||
matchBed = regex_repetierTempBed.match(line)
|
||||
|
||||
if matchExtr is not None:
|
||||
toolNum = int(matchExtr.group(1))
|
||||
@@ -950,18 +975,18 @@ class MachineCom(object):
|
||||
self._callback.on_comm_sd_files(self._sdFiles)
|
||||
elif 'SD printing byte' in line and self.isSdPrinting():
|
||||
# answer to M27, at least on Marlin, Repetier and Sprinter: "SD printing byte %d/%d"
|
||||
match = self._regex_sdPrintingByte.search(line)
|
||||
self._currentFile.setFilepos(int(match.group(1)))
|
||||
match = regex_sdPrintingByte.search(line)
|
||||
self._currentFile.setFilepos(int(match.group("current")))
|
||||
self._callback.on_comm_progress()
|
||||
elif 'File opened' in line and not self._ignore_select:
|
||||
# answer to M23, at least on Marlin, Repetier and Sprinter: "File opened:%s Size:%d"
|
||||
match = self._regex_sdFileOpened.search(line)
|
||||
match = regex_sdFileOpened.search(line)
|
||||
if self._sdFileToSelect:
|
||||
name = self._sdFileToSelect
|
||||
self._sdFileToSelect = None
|
||||
else:
|
||||
name = match.group(1)
|
||||
self._currentFile = PrintingSdFileInformation(name, int(match.group(2)))
|
||||
name = match.group("name")
|
||||
self._currentFile = PrintingSdFileInformation(name, int(match.group("size")))
|
||||
elif 'File selected' in line:
|
||||
if self._ignore_select:
|
||||
self._ignore_select = False
|
||||
@@ -1181,7 +1206,7 @@ class MachineCom(object):
|
||||
|
||||
def _onConnected(self):
|
||||
self._serial.timeout = settings().getFloat(["serial", "timeout", "communication"])
|
||||
self._temperature_timer = RepeatedTimer(lambda: get_interval("temperature"), self._poll_temperature, run_first=True)
|
||||
self._temperature_timer = RepeatedTimer(lambda: get_interval("temperature", default_value=4.0), self._poll_temperature, run_first=True)
|
||||
self._temperature_timer.start()
|
||||
|
||||
self._changeState(self.STATE_OPERATIONAL)
|
||||
@@ -1241,10 +1266,10 @@ class MachineCom(object):
|
||||
self._changeState(self.STATE_DETECT_SERIAL)
|
||||
serial_obj = self._detectPort(True)
|
||||
if serial_obj is None:
|
||||
self._log("Failed to autodetect serial port")
|
||||
self._errorValue = 'Failed to autodetect serial port.'
|
||||
self._errorValue = 'Failed to autodetect serial port, please set it manually.'
|
||||
self._changeState(self.STATE_ERROR)
|
||||
eventManager().fire(Events.ERROR, {"error": self.getErrorString()})
|
||||
self._log("Failed to autodetect serial port, please set it manually.")
|
||||
return None
|
||||
|
||||
port = serial_obj.port
|
||||
@@ -1266,11 +1291,17 @@ class MachineCom(object):
|
||||
for name, factory in serial_factories:
|
||||
try:
|
||||
serial_obj = factory(self, self._port, self._baudrate, settings().getFloat(["serial", "timeout", "connection"]))
|
||||
except Exception:
|
||||
self._log("Unexpected error while connecting to serial port: %s %s (hook %s)" % (self._port, get_exception_string(), name))
|
||||
self._errorValue = "Failed to open serial port, permissions correct?"
|
||||
except:
|
||||
exception_string = get_exception_string()
|
||||
self._errorValue = "Connection error, see Terminal tab"
|
||||
self._changeState(self.STATE_ERROR)
|
||||
eventManager().fire(Events.ERROR, {"error": self.getErrorString()})
|
||||
|
||||
self._log("Unexpected error while connecting to serial port: %s %s (hook %s)" % (self._port, exception_string, name))
|
||||
|
||||
if "failed to set custom baud rate" in exception_string.lower():
|
||||
self._log("Your installation does not support custom baudrates (e.g. 250000) for connecting to your printer. This is a problem of the pyserial library that OctoPrint depends on. Please update to a pyserial version that supports your baudrate or switch your printer's firmware to a standard baudrate (e.g. 115200). See https://github.com/foosel/OctoPrint/wiki/OctoPrint-support-for-250000-baud-rate-on-Raspbian")
|
||||
|
||||
return False
|
||||
|
||||
if serial_obj is not None:
|
||||
@@ -1289,13 +1320,17 @@ class MachineCom(object):
|
||||
# Marlin reports an MIN/MAX temp error as "Error:x\n: Extruder switched off. MAXTEMP triggered !\n"
|
||||
# But a bed temp error is reported as "Error: Temperature heated bed switched off. MAXTEMP triggered !!"
|
||||
# So we can have an extra newline in the most common case. Awesome work people.
|
||||
if self._regex_minMaxError.match(line):
|
||||
if regex_minMaxError.match(line):
|
||||
line = line.rstrip() + self._readline()
|
||||
|
||||
#Skip the communication errors, as those get corrected.
|
||||
if 'line number' in line.lower() or 'checksum' in line.lower() or 'expected line' in line.lower():
|
||||
if 'line number' in line.lower() or 'checksum' in line.lower() or 'format error' in line.lower() or 'expected line' in line.lower():
|
||||
#Skip the communication errors, as those get corrected.
|
||||
self._lastCommError = line[6:] if line.startswith("Error:") else line[2:]
|
||||
pass
|
||||
elif 'volume.init' in line.lower() or "openroot" in line.lower() or 'workdir' in line.lower()\
|
||||
or "error writing to file" in line.lower():
|
||||
#Also skip errors with the SD card
|
||||
pass
|
||||
elif not self.isError():
|
||||
self._errorValue = line[6:] if line.startswith("Error:") else line[2:]
|
||||
self._changeState(self.STATE_ERROR)
|
||||
@@ -1303,14 +1338,17 @@ class MachineCom(object):
|
||||
return line
|
||||
|
||||
def _readline(self):
|
||||
if self._serial == None:
|
||||
if self._serial is None:
|
||||
return None
|
||||
|
||||
try:
|
||||
ret = self._serial.readline()
|
||||
except:
|
||||
self._log("Unexpected error while reading serial port: %s" % (get_exception_string()))
|
||||
self._errorValue = get_exception_string()
|
||||
self.close(True)
|
||||
if not self._connection_closing:
|
||||
self._logger.exception("Unexpected error while reading from serial port")
|
||||
self._log("Unexpected error while reading serial port, please consult octoprint.log for details: %s" % (get_exception_string()))
|
||||
self._errorValue = get_exception_string()
|
||||
self.close(True)
|
||||
return None
|
||||
if ret == '':
|
||||
#self._log("Recv: TIMEOUT")
|
||||
@@ -1387,9 +1425,18 @@ class MachineCom(object):
|
||||
self._currentResendCount += 1
|
||||
return
|
||||
|
||||
# If we ignore resend repetitions (Repetier firmware...), check if we
|
||||
# need to do this now. If the same line number has been requested we
|
||||
# already saw and resent, we'll ignore it up to <counter> times.
|
||||
if self._resendSwallowRepetitions and lineToResend == self._lastResendNumber and self._resendSwallowRepetitionsCounter > 0:
|
||||
self._logger.debug("Ignoring resend request for line %d, that is probably a repetition sent by the firmware to ensure it arrives, not a real request" % lineToResend)
|
||||
self._resendSwallowRepetitionsCounter -= 1
|
||||
return
|
||||
|
||||
self._resendDelta = resendDelta
|
||||
self._lastResendNumber = lineToResend
|
||||
self._currentResendCount = 0
|
||||
self._resendSwallowRepetitionsCounter = settings().getInt(["feature", "identicalResendsCountdown"])
|
||||
|
||||
if self._resendDelta > len(self._lastLines) or len(self._lastLines) == 0 or self._resendDelta < 0:
|
||||
self._errorValue = "Printer requested line %d but no sufficient history is available, can't resend" % lineToResend
|
||||
@@ -1446,25 +1493,6 @@ class MachineCom(object):
|
||||
# trigger the "queued" phase only if we are not streaming to sd right now
|
||||
self._process_command_phase("queued", cmd, cmd_type, gcode=gcode)
|
||||
|
||||
def gcode_command_for_cmd(self, cmd):
|
||||
"""
|
||||
Tries to parse the provided ``cmd`` and extract the GCODE command identifier from it (e.g. "G0" for "G0 X10.0").
|
||||
|
||||
Arguments:
|
||||
cmd (str): The command to try to parse.
|
||||
|
||||
Returns:
|
||||
str or None: The GCODE command identifier if it could be parsed, or None if not.
|
||||
"""
|
||||
if not cmd:
|
||||
return None
|
||||
|
||||
gcode = self._regex_command.search(cmd)
|
||||
if not gcode:
|
||||
return None
|
||||
|
||||
return gcode.group(1)
|
||||
|
||||
##~~ send loop handling
|
||||
|
||||
def _enqueue_for_sending(self, command, linenumber=None, command_type=None):
|
||||
@@ -1505,7 +1533,7 @@ class MachineCom(object):
|
||||
# some firmwares (e.g. Smoothie) might support additional in-band communication that will not
|
||||
# stick to the acknowledgement behaviour of GCODE, so we check here if we have a GCODE command
|
||||
# at hand here and only clear our clear_to_send flag later if that's the case
|
||||
gcode = self.gcode_command_for_cmd(command)
|
||||
gcode = gcode_command_for_cmd(command)
|
||||
|
||||
if linenumber is not None:
|
||||
# line number predetermined - this only happens for resends, so we'll use the number and
|
||||
@@ -1521,13 +1549,11 @@ class MachineCom(object):
|
||||
continue
|
||||
|
||||
# now comes the part where we increase line numbers and send stuff - no turning back now
|
||||
command_to_send = command.encode("ascii", errors="replace")
|
||||
if (gcode is not None or self._sendChecksumWithUnknownCommands) and (self.isPrinting() or self._alwaysSendChecksum):
|
||||
linenumber = self._currentLine
|
||||
self._addToLastLines(command)
|
||||
self._currentLine += 1
|
||||
self._doSendWithChecksum(command, linenumber)
|
||||
self._doIncrementAndSendWithChecksum(command_to_send)
|
||||
else:
|
||||
self._doSendWithoutChecksum(command)
|
||||
self._doSendWithoutChecksum(command_to_send)
|
||||
|
||||
# trigger "sent" phase and use up one "ok"
|
||||
self._process_command_phase("sent", command, command_type, gcode=gcode)
|
||||
@@ -1553,7 +1579,7 @@ class MachineCom(object):
|
||||
return command, command_type, gcode
|
||||
|
||||
if gcode is None:
|
||||
gcode = self.gcode_command_for_cmd(command)
|
||||
gcode = gcode_command_for_cmd(command)
|
||||
|
||||
# send it through the phase specific handlers provided by plugins
|
||||
for name, hook in self._gcode_hooks[phase].items():
|
||||
@@ -1608,11 +1634,18 @@ class MachineCom(object):
|
||||
# handler returned a tuple of an unexpected length
|
||||
return original_tuple
|
||||
|
||||
gcode = self.gcode_command_for_cmd(command)
|
||||
gcode = gcode_command_for_cmd(command)
|
||||
return command, command_type, gcode
|
||||
|
||||
##~~ actual sending via serial
|
||||
|
||||
def _doIncrementAndSendWithChecksum(self, cmd):
|
||||
with self._line_mutex:
|
||||
linenumber = self._currentLine
|
||||
self._addToLastLines(cmd)
|
||||
self._currentLine += 1
|
||||
self._doSendWithChecksum(cmd, linenumber)
|
||||
|
||||
def _doSendWithChecksum(self, cmd, lineNumber):
|
||||
commandToSend = "N%d %s" % (lineNumber, cmd)
|
||||
checksum = reduce(lambda x,y:x^y, map(ord, commandToSend))
|
||||
@@ -1620,6 +1653,9 @@ class MachineCom(object):
|
||||
self._doSendWithoutChecksum(commandToSend)
|
||||
|
||||
def _doSendWithoutChecksum(self, cmd):
|
||||
if self._serial is None:
|
||||
return
|
||||
|
||||
self._log("Send: %s" % cmd)
|
||||
try:
|
||||
self._serial.write(cmd + '\n')
|
||||
@@ -1628,27 +1664,31 @@ class MachineCom(object):
|
||||
try:
|
||||
self._serial.write(cmd + '\n')
|
||||
except:
|
||||
self._log("Unexpected error while writing serial port: %s" % (get_exception_string()))
|
||||
if not self._connection_closing:
|
||||
self._logger.exception("Unexpected error while writing to serial port")
|
||||
self._log("Unexpected error while writing to serial port: %s" % (get_exception_string()))
|
||||
self._errorValue = get_exception_string()
|
||||
self.close(True)
|
||||
except:
|
||||
if not self._connection_closing:
|
||||
self._logger.exception("Unexpected error while writing to serial port")
|
||||
self._log("Unexpected error while writing to serial port: %s" % (get_exception_string()))
|
||||
self._errorValue = get_exception_string()
|
||||
self.close(True)
|
||||
except:
|
||||
self._log("Unexpected error while writing serial port: %s" % (get_exception_string()))
|
||||
self._errorValue = get_exception_string()
|
||||
self.close(True)
|
||||
|
||||
##~~ command handlers
|
||||
|
||||
def _gcode_T_sent(self, cmd, cmd_type=None):
|
||||
toolMatch = self._regex_paramTInt.search(cmd)
|
||||
toolMatch = regexes_parameters["intT"].search(cmd)
|
||||
if toolMatch:
|
||||
self._currentTool = int(toolMatch.group(1))
|
||||
self._currentTool = int(toolMatch.group("value"))
|
||||
|
||||
def _gcode_G0_sent(self, cmd, cmd_type=None):
|
||||
if 'Z' in cmd:
|
||||
match = self._regex_paramZFloat.search(cmd)
|
||||
match = regexes_parameters["floatZ"].search(cmd)
|
||||
if match:
|
||||
try:
|
||||
z = float(match.group(1))
|
||||
z = float(match.group("value"))
|
||||
if self._currentZ != z:
|
||||
self._currentZ = z
|
||||
self._callback.on_comm_z_change(z)
|
||||
@@ -1663,13 +1703,13 @@ class MachineCom(object):
|
||||
|
||||
def _gcode_M104_sent(self, cmd, cmd_type=None):
|
||||
toolNum = self._currentTool
|
||||
toolMatch = self._regex_paramTInt.search(cmd)
|
||||
toolMatch = regexes_parameters["intT"].search(cmd)
|
||||
if toolMatch:
|
||||
toolNum = int(toolMatch.group(1))
|
||||
match = self._regex_paramSInt.search(cmd)
|
||||
toolNum = int(toolMatch.group("value"))
|
||||
match = regexes_parameters["floatS"].search(cmd)
|
||||
if match:
|
||||
try:
|
||||
target = float(match.group(1))
|
||||
target = float(match.group("value"))
|
||||
if toolNum in self._temp.keys() and self._temp[toolNum] is not None and isinstance(self._temp[toolNum], tuple):
|
||||
(actual, oldTarget) = self._temp[toolNum]
|
||||
self._temp[toolNum] = (actual, target)
|
||||
@@ -1679,10 +1719,10 @@ class MachineCom(object):
|
||||
pass
|
||||
|
||||
def _gcode_M140_sent(self, cmd, cmd_type=None):
|
||||
match = self._regex_paramSInt.search(cmd)
|
||||
match = regexes_parameters["floatS"].search(cmd)
|
||||
if match:
|
||||
try:
|
||||
target = float(match.group(1))
|
||||
target = float(match.group("value"))
|
||||
if self._bedTemp is not None and isinstance(self._bedTemp, tuple):
|
||||
(actual, oldTarget) = self._bedTemp
|
||||
self._bedTemp = (actual, target)
|
||||
@@ -1705,37 +1745,61 @@ class MachineCom(object):
|
||||
|
||||
def _gcode_M110_sending(self, cmd, cmd_type=None):
|
||||
newLineNumber = None
|
||||
match = self._regex_paramNInt.search(cmd)
|
||||
match = regexes_parameters["intN"].search(cmd)
|
||||
if match:
|
||||
try:
|
||||
newLineNumber = int(match.group(1))
|
||||
newLineNumber = int(match.group("value"))
|
||||
except:
|
||||
pass
|
||||
else:
|
||||
newLineNumber = 0
|
||||
|
||||
# send M110 command with new line number
|
||||
self._currentLine = newLineNumber
|
||||
with self._line_mutex:
|
||||
# send M110 command with new line number
|
||||
self._currentLine = newLineNumber
|
||||
|
||||
# after a reset of the line number we have no way to determine what line exactly the printer now wants
|
||||
self._lastLines.clear()
|
||||
# after a reset of the line number we have no way to determine what line exactly the printer now wants
|
||||
self._lastLines.clear()
|
||||
self._resendDelta = None
|
||||
|
||||
def _gcode_M112_queuing(self, cmd, cmd_type=None): # It's an emergency what todo? Canceling the print should be the minimum
|
||||
self.cancelPrint()
|
||||
def _gcode_M112_queuing(self, cmd, cmd_type=None):
|
||||
# emergency stop, jump the queue with the M112
|
||||
self._doSendWithoutChecksum("M112")
|
||||
self._doIncrementAndSendWithChecksum("M112")
|
||||
|
||||
# No idea if the printer is still listening or if M112 won. Just in case
|
||||
# we'll now try to also manually make sure all heaters are shut off - better
|
||||
# safe than sorry. We do this ignoring the queue since at this point it
|
||||
# is irrelevant whether the printer has sent enough ack's or not, we
|
||||
# are going to shutdown the connection in a second anyhow.
|
||||
for tool in range(self._printerProfileManager.get_current_or_default()["extruder"]["count"]):
|
||||
self._doIncrementAndSendWithChecksum("M104 T{tool} S0".format(tool=tool))
|
||||
self._doIncrementAndSendWithChecksum("M140 S0")
|
||||
|
||||
# close to reset host state
|
||||
self._errorValue = "Closing serial port due to emergency stop M112."
|
||||
self._log(self._errorValue)
|
||||
self.close(isError=True)
|
||||
|
||||
# fire the M112 event since we sent it and we're going to prevent the caller from seeing it
|
||||
gcode = "M112"
|
||||
if gcode in gcodeToEvent:
|
||||
eventManager().fire(gcodeToEvent[gcode])
|
||||
|
||||
# return None 1-tuple to eat the one that is queuing because we don't want to send it twice
|
||||
# I hope it got it the first time because as far as I can tell, there is no way to know
|
||||
return None,
|
||||
|
||||
def _gcode_G4_sent(self, cmd, cmd_type=None):
|
||||
# we are intending to dwell for a period of time, increase the timeout to match
|
||||
cmd = cmd.upper()
|
||||
p_idx = cmd.find('P')
|
||||
s_idx = cmd.find('S')
|
||||
p_match = regexes_parameters["floatP"].search(cmd)
|
||||
s_match = regexes_parameters["floatS"].search(cmd)
|
||||
|
||||
_timeout = 0
|
||||
if p_idx != -1:
|
||||
# dwell time is specified in milliseconds
|
||||
_timeout = float(cmd[p_idx+1:]) / 1000.0
|
||||
elif s_idx != -1:
|
||||
# dwell time is specified in seconds
|
||||
_timeout = float(cmd[s_idx+1:])
|
||||
if p_match:
|
||||
_timeout = float(p_match.group("value")) / 1000.0
|
||||
elif s_match:
|
||||
_timeout = float(s_match.group("value"))
|
||||
self._timeout = get_new_timeout("communication") + _timeout
|
||||
|
||||
##~~ command phase handlers
|
||||
@@ -1889,7 +1953,7 @@ class PrintingGcodeFileInformation(PrintingFileInformation):
|
||||
Opens the file for reading and determines the file size.
|
||||
"""
|
||||
PrintingFileInformation.start(self)
|
||||
self._handle = open(self._filename, "r")
|
||||
self._handle = bom_aware_open(self._filename, encoding="utf-8", errors="replace")
|
||||
|
||||
def close(self):
|
||||
"""
|
||||
@@ -1919,7 +1983,7 @@ class PrintingGcodeFileInformation(PrintingFileInformation):
|
||||
if self._handle is None:
|
||||
# file got closed just now
|
||||
return None
|
||||
line = self._handle.readline()
|
||||
line = to_unicode(self._handle.readline())
|
||||
if not line:
|
||||
self.close()
|
||||
processed = process_gcode_line(line, offsets=offsets, current_tool=current_tool)
|
||||
@@ -1976,9 +2040,9 @@ class TypedQueue(queue.Queue):
|
||||
return item
|
||||
|
||||
|
||||
class TypeAlreadyInQueue(BaseException):
|
||||
class TypeAlreadyInQueue(Exception):
|
||||
def __init__(self, t, *args, **kwargs):
|
||||
BaseException.__init__(self, *args, **kwargs)
|
||||
Exception.__init__(self, *args, **kwargs)
|
||||
self.type = t
|
||||
|
||||
|
||||
@@ -1987,11 +2051,15 @@ def get_new_timeout(type):
|
||||
return now + get_interval(type)
|
||||
|
||||
|
||||
def get_interval(type):
|
||||
def get_interval(type, default_value=0.0):
|
||||
if type not in default_settings["serial"]["timeout"]:
|
||||
return 0
|
||||
return default_value
|
||||
else:
|
||||
return settings().getFloat(["serial", "timeout", type])
|
||||
value = settings().getFloat(["serial", "timeout", type])
|
||||
if not value:
|
||||
return default_value
|
||||
else:
|
||||
return value
|
||||
|
||||
_temp_command_regex = re.compile("^M(?P<command>104|109|140|190)(\s+T(?P<tool>\d+)|\s+S(?P<temperature>[-+]?\d*\.?\d*))+")
|
||||
|
||||
@@ -2121,3 +2189,159 @@ def convert_feedback_controls(configured_controls):
|
||||
|
||||
return feedback_controls, feedback_matcher
|
||||
|
||||
def canonicalize_temperatures(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 = 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
|
||||
|
||||
def parse_temperature_line(line, current):
|
||||
"""
|
||||
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.
|
||||
|
||||
Arguments:
|
||||
line (str): the temperature line to parse
|
||||
current (int): the current active extruder
|
||||
|
||||
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``
|
||||
"""
|
||||
|
||||
result = {}
|
||||
maxToolNum = 0
|
||||
for match in re.finditer(regex_temp, line):
|
||||
values = match.groupdict()
|
||||
tool = values["tool"]
|
||||
toolnum = values.get("toolnum", None)
|
||||
toolNumber = int(toolnum) if toolnum is not None and len(toolnum) else None
|
||||
if toolNumber > maxToolNum:
|
||||
maxToolNum = toolNumber
|
||||
|
||||
try:
|
||||
actual = float(match.group(3))
|
||||
target = None
|
||||
if match.group(4) and match.group(5):
|
||||
target = float(match.group(5))
|
||||
|
||||
result[tool] = (actual, target)
|
||||
except ValueError:
|
||||
# catch conversion issues, we'll rather just not get the temperature update instead of killing the connection
|
||||
pass
|
||||
|
||||
return max(maxToolNum, current), canonicalize_temperatures(result, current)
|
||||
|
||||
def gcode_command_for_cmd(cmd):
|
||||
"""
|
||||
Tries to parse the provided ``cmd`` and extract the GCODE command identifier from it (e.g. "G0" for "G0 X10.0").
|
||||
|
||||
Arguments:
|
||||
cmd (str): The command to try to parse.
|
||||
|
||||
Returns:
|
||||
str or None: The GCODE command identifier if it could be parsed, or None if not.
|
||||
"""
|
||||
if not cmd:
|
||||
return None
|
||||
|
||||
gcode = regex_command.search(cmd)
|
||||
if not gcode:
|
||||
return None
|
||||
|
||||
values = gcode.groupdict()
|
||||
if "commandGM" in values and values["commandGM"]:
|
||||
return values["commandGM"]
|
||||
elif "commandT" in values and values["commandT"]:
|
||||
return values["commandT"]
|
||||
else:
|
||||
# this should never happen
|
||||
return None
|
||||
|
||||
@@ -30,18 +30,20 @@ class gcode(object):
|
||||
self.progressCallback = None
|
||||
self._abort = False
|
||||
self._filamentDiameter = 0
|
||||
|
||||
def load(self, filename, printer_profile):
|
||||
|
||||
def load(self, filename, printer_profile, throttle=None):
|
||||
if os.path.isfile(filename):
|
||||
self.filename = filename
|
||||
self._fileSize = os.stat(filename).st_size
|
||||
with open(filename, "r") as f:
|
||||
self._load(f, printer_profile)
|
||||
|
||||
import codecs
|
||||
with codecs.open(filename, encoding="utf-8", errors="replace") as f:
|
||||
self._load(f, printer_profile, throttle=throttle)
|
||||
|
||||
def abort(self):
|
||||
self._abort = True
|
||||
|
||||
def _load(self, gcodeFile, printer_profile):
|
||||
def _load(self, gcodeFile, printer_profile, throttle=None):
|
||||
filePos = 0
|
||||
readBytes = 0
|
||||
pos = [0.0, 0.0, 0.0]
|
||||
@@ -237,6 +239,9 @@ class gcode(object):
|
||||
for i in range(len(totalExtrusion), currentExtruder + 1):
|
||||
totalExtrusion.append(0.0)
|
||||
|
||||
if throttle is not None:
|
||||
throttle()
|
||||
|
||||
if self.progressCallback is not None:
|
||||
self.progressCallback(100.0)
|
||||
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import sarge
|
||||
import sys
|
||||
import logging
|
||||
|
||||
|
||||
from octoprint.util import to_unicode
|
||||
|
||||
|
||||
class UnknownPip(Exception):
|
||||
pass
|
||||
|
||||
class PipCaller(object):
|
||||
def __init__(self, configured=None):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self.configured = configured
|
||||
self.refresh = False
|
||||
|
||||
self._command = None
|
||||
self._version = None
|
||||
self._version_string = None
|
||||
self._use_sudo = False
|
||||
|
||||
self.trigger_refresh()
|
||||
|
||||
self.on_log_call = lambda *args, **kwargs: None
|
||||
self.on_log_stdout = lambda *args, **kwargs: None
|
||||
self.on_log_stderr = lambda *args, **kwargs: None
|
||||
|
||||
def __le__(self, other):
|
||||
return self.version is not None and self.version <= other
|
||||
|
||||
def __lt__(self, other):
|
||||
return self.version is not None and self.version < other
|
||||
|
||||
def __ge__(self, other):
|
||||
return self.version is not None and self.version >= other
|
||||
|
||||
def __gt__(self, other):
|
||||
return self.version is not None and self.version > other
|
||||
|
||||
@property
|
||||
def command(self):
|
||||
return self._command
|
||||
|
||||
@property
|
||||
def version(self):
|
||||
return self._version
|
||||
|
||||
@property
|
||||
def version_string(self):
|
||||
return self._version_string
|
||||
|
||||
@property
|
||||
def use_sudo(self):
|
||||
return self._use_sudo
|
||||
|
||||
@property
|
||||
def available(self):
|
||||
return self._command is not None
|
||||
|
||||
def trigger_refresh(self):
|
||||
try:
|
||||
self._command, self._version, self._version_string, self._use_sudo = self._find_pip()
|
||||
except:
|
||||
self._logger.exception("Error while discovering pip command")
|
||||
self._command = None
|
||||
self._version = None
|
||||
self.refresh = False
|
||||
|
||||
def execute(self, *args):
|
||||
if self.refresh:
|
||||
self.trigger_refresh()
|
||||
|
||||
if self._command is None:
|
||||
raise UnknownPip()
|
||||
|
||||
command = [self._command] + list(args)
|
||||
if self._use_sudo:
|
||||
command = ["sudo"] + command
|
||||
|
||||
joined_command = " ".join(command)
|
||||
self._logger.debug(u"Calling: {}".format(joined_command))
|
||||
self.on_log_call(joined_command)
|
||||
|
||||
p = sarge.run(command, async=True, stdout=sarge.Capture(), stderr=sarge.Capture())
|
||||
p.wait_events()
|
||||
|
||||
all_stdout = []
|
||||
all_stderr = []
|
||||
try:
|
||||
while p.returncode is None:
|
||||
line = p.stderr.readline(timeout=0.5)
|
||||
if line:
|
||||
line = to_unicode(line, errors="replace")
|
||||
self._log_stderr(line)
|
||||
all_stderr.append(line)
|
||||
|
||||
line = p.stdout.readline(timeout=0.5)
|
||||
if line:
|
||||
line = to_unicode(line, errors="replace")
|
||||
self._log_stdout(line)
|
||||
all_stdout.append(line)
|
||||
|
||||
p.commands[0].poll()
|
||||
|
||||
finally:
|
||||
p.close()
|
||||
|
||||
stderr = p.stderr.text
|
||||
if stderr:
|
||||
split_lines = stderr.split("\n")
|
||||
self._log_stderr(*split_lines)
|
||||
all_stderr += split_lines
|
||||
|
||||
stdout = p.stdout.text
|
||||
if stdout:
|
||||
split_lines = stdout.split("\n")
|
||||
self._log_stdout(*split_lines)
|
||||
all_stdout += split_lines
|
||||
|
||||
return p.returncode, all_stdout, all_stderr
|
||||
|
||||
|
||||
def _find_pip(self):
|
||||
pip_command = self.configured
|
||||
|
||||
if pip_command is not None and pip_command.startswith("sudo "):
|
||||
pip_command = pip_command[len("sudo "):]
|
||||
pip_sudo = True
|
||||
else:
|
||||
pip_sudo = False
|
||||
|
||||
pip_version = None
|
||||
version_segment = None
|
||||
|
||||
if pip_command is None:
|
||||
import os
|
||||
python_command = sys.executable
|
||||
binary_dir = os.path.dirname(python_command)
|
||||
|
||||
pip_command = os.path.join(binary_dir, "pip")
|
||||
if sys.platform == "win32":
|
||||
# Windows is a bit special... first of all the file will be called pip.exe, not just pip, and secondly
|
||||
# for a non-virtualenv install (e.g. global install) the pip binary will not be located in the
|
||||
# same folder as python.exe, but in a subfolder Scripts, e.g.
|
||||
#
|
||||
# C:\Python2.7\
|
||||
# |- python.exe
|
||||
# `- Scripts
|
||||
# `- pip.exe
|
||||
|
||||
# virtual env?
|
||||
pip_command = os.path.join(binary_dir, "pip.exe")
|
||||
|
||||
if not os.path.isfile(pip_command):
|
||||
# nope, let's try the Scripts folder then
|
||||
scripts_dir = os.path.join(binary_dir, "Scripts")
|
||||
if os.path.isdir(scripts_dir):
|
||||
pip_command = os.path.join(scripts_dir, "pip.exe")
|
||||
|
||||
if not os.path.isfile(pip_command) or not os.access(pip_command, os.X_OK):
|
||||
pip_command = None
|
||||
|
||||
if pip_command is not None:
|
||||
self._logger.debug("Found pip at {}, going to figure out its version".format(pip_command))
|
||||
|
||||
sarge_command = [pip_command, "--version"]
|
||||
if pip_sudo:
|
||||
sarge_command = ["sudo"] + sarge_command
|
||||
p = sarge.run(sarge_command, stdout=sarge.Capture(), stderr=sarge.Capture())
|
||||
|
||||
if p.returncode != 0:
|
||||
self._logger.warn("Error while trying to run pip --version: {}".format(p.stderr.text))
|
||||
pip_command = None
|
||||
|
||||
output = p.stdout.text
|
||||
# output should look something like this:
|
||||
#
|
||||
# pip <version> from <path> (<python version>)
|
||||
#
|
||||
# we'll just split on whitespace and then try to use the second entry
|
||||
|
||||
if not output.startswith("pip"):
|
||||
self._logger.warn("pip command returned unparseable output, can't determine version: {}".format(output))
|
||||
|
||||
split_output = map(lambda x: x.strip(), output.split())
|
||||
if len(split_output) < 2:
|
||||
self._logger.warn("pip command returned unparseable output, can't determine version: {}".format(output))
|
||||
|
||||
version_segment = split_output[1]
|
||||
|
||||
from pkg_resources import parse_version
|
||||
try:
|
||||
pip_version = parse_version(version_segment)
|
||||
except:
|
||||
self._logger.exception("Error while trying to parse version string from pip command")
|
||||
else:
|
||||
self._logger.info("Found pip at {}, version is {}".format(pip_command, version_segment))
|
||||
|
||||
return pip_command, pip_version, version_segment, pip_sudo
|
||||
|
||||
def _log_stdout(self, *lines):
|
||||
self.on_log_stdout(*lines)
|
||||
|
||||
def _log_stderr(self, *lines):
|
||||
self.on_log_stderr(*lines)
|
||||
@@ -439,7 +439,7 @@ def get_babel_commandclasses(pot_file=None,
|
||||
def create_plugin_setup_parameters(identifier="todo", name="TODO", version="0.1", description="TODO", author="TODO",
|
||||
mail="todo@example.com", url="TODO", license="AGPLv3", source_folder=".", additional_data=None,
|
||||
additional_packages=None, ignored_packages=None, requires=None, extra_requires=None,
|
||||
cmdclass=None, eggs=None, package=None):
|
||||
cmdclass=None, eggs=None, package=None, dependency_links=None):
|
||||
import pkg_resources
|
||||
|
||||
if package is None:
|
||||
@@ -454,6 +454,9 @@ def create_plugin_setup_parameters(identifier="todo", name="TODO", version="0.1"
|
||||
if ignored_packages is None:
|
||||
ignored_packages = list()
|
||||
|
||||
if dependency_links is None:
|
||||
dependency_links = list()
|
||||
|
||||
if requires is None:
|
||||
requires = ["OctoPrint"]
|
||||
if not isinstance(requires, list):
|
||||
@@ -491,7 +494,8 @@ def create_plugin_setup_parameters(identifier="todo", name="TODO", version="0.1"
|
||||
cmdclass.update(get_babel_commandclasses(pot_file=pot_file, output_dir=translation_dir, bundled_dir=bundled_dir, pack_name_prefix="{name}-i18n-".format(**locals()), pack_path_prefix="_plugins/{identifier}/".format(**locals())))
|
||||
|
||||
from setuptools import find_packages
|
||||
packages = find_packages(where=source_folder, exclude=ignored_packages, include=[package, "{package}.*".format(**locals())] + additional_packages)
|
||||
packages = list(set([package] + filter(lambda x: x.startswith("{package}.".format(package=package)), find_packages(where=source_folder, exclude=ignored_packages)) + additional_packages))
|
||||
print("Found packages: {packages!r}".format(**locals()))
|
||||
|
||||
return dict(
|
||||
name=name,
|
||||
@@ -518,6 +522,7 @@ def create_plugin_setup_parameters(identifier="todo", name="TODO", version="0.1"
|
||||
|
||||
install_requires=requires,
|
||||
extras_require=extra_requires,
|
||||
dependency_links=dependency_links,
|
||||
|
||||
# Hook the plugin into the "octoprint.plugin" entry point, mapping the plugin_identifier to the plugin_package.
|
||||
# That way OctoPrint will be able to find the plugin and load it.
|
||||
|
||||
@@ -8,4 +8,3 @@ from __future__ import absolute_import
|
||||
__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"
|
||||
|
||||
@@ -13,6 +13,98 @@ import mock
|
||||
import octoprint.filemanager
|
||||
import octoprint.filemanager.util
|
||||
|
||||
class FilemanagerMethodTest(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
# mock plugin manager
|
||||
self.plugin_manager_patcher = mock.patch("octoprint.plugin.plugin_manager")
|
||||
self.plugin_manager_getter = self.plugin_manager_patcher.start()
|
||||
|
||||
self.plugin_manager = mock.MagicMock()
|
||||
|
||||
hook_extensions = dict(
|
||||
some_plugin=lambda: dict(dict(machinecode=dict(foo=["foo", "f"]))),
|
||||
other_plugin=lambda: dict(dict(model=dict(amf=["amf"]))),
|
||||
mime_map=lambda: dict(
|
||||
mime_map=dict(
|
||||
mime_map_yes=octoprint.filemanager.ContentTypeMapping(["mime_map_yes"], "application/mime_map_yes")
|
||||
)
|
||||
),
|
||||
mime_detect=lambda: dict(
|
||||
dict(
|
||||
machinecode=dict(
|
||||
mime_detect_yes=octoprint.filemanager.ContentTypeDetector(["mime_detect_yes"], lambda x: "application/mime_detect_yes"),
|
||||
mime_detect_no=octoprint.filemanager.ContentTypeDetector(["mime_detect_no"], lambda x: None)
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
self.plugin_manager.get_hooks.return_value = hook_extensions
|
||||
|
||||
self.plugin_manager_getter.return_value = self.plugin_manager
|
||||
|
||||
def tearDown(self):
|
||||
self.plugin_manager_patcher.stop()
|
||||
|
||||
def test_full_extension_tree(self):
|
||||
full = octoprint.filemanager.full_extension_tree()
|
||||
self.assertTrue("machinecode" in full)
|
||||
self.assertTrue("gcode" in full["machinecode"])
|
||||
self.assertTrue(isinstance(full["machinecode"]["gcode"], octoprint.filemanager.ContentTypeMapping))
|
||||
self.assertItemsEqual(["gcode", "gco", "g"], full["machinecode"]["gcode"].extensions)
|
||||
self.assertTrue("foo" in full["machinecode"])
|
||||
self.assertTrue(isinstance(full["machinecode"]["foo"], list))
|
||||
self.assertItemsEqual(["f", "foo"], full["machinecode"]["foo"])
|
||||
|
||||
self.assertTrue("model" in full)
|
||||
self.assertTrue("stl" in full["model"])
|
||||
self.assertTrue(isinstance(full["model"]["stl"], octoprint.filemanager.ContentTypeMapping))
|
||||
self.assertItemsEqual(["stl"], full["model"]["stl"].extensions)
|
||||
self.assertTrue("amf" in full["model"])
|
||||
self.assertTrue(isinstance(full["model"]["amf"], list))
|
||||
self.assertItemsEqual(["amf"], full["model"]["amf"])
|
||||
|
||||
def test_get_mimetype(self):
|
||||
self.assertEquals(octoprint.filemanager.get_mime_type("foo.stl"), "application/sla")
|
||||
self.assertEquals(octoprint.filemanager.get_mime_type("foo.gcode"), "text/plain")
|
||||
self.assertEquals(octoprint.filemanager.get_mime_type("foo.unknown"), "application/octet-stream")
|
||||
self.assertEquals(octoprint.filemanager.get_mime_type("foo.mime_map_yes"), "application/mime_map_yes")
|
||||
self.assertEquals(octoprint.filemanager.get_mime_type("foo.mime_map_no"), "application/octet-stream")
|
||||
self.assertEquals(octoprint.filemanager.get_mime_type("foo.mime_detect_yes"), "application/mime_detect_yes")
|
||||
self.assertEquals(octoprint.filemanager.get_mime_type("foo.mime_detect_no"), "application/octet-stream")
|
||||
|
||||
def test_valid_file_type(self):
|
||||
self.assertTrue(octoprint.filemanager.valid_file_type("foo.stl", type="model"))
|
||||
self.assertTrue(octoprint.filemanager.valid_file_type("foo.stl", type="stl"))
|
||||
self.assertFalse(octoprint.filemanager.valid_file_type("foo.stl", type="machinecode"))
|
||||
self.assertTrue(octoprint.filemanager.valid_file_type("foo.foo", type="machinecode"))
|
||||
self.assertTrue(octoprint.filemanager.valid_file_type("foo.foo", type="foo"))
|
||||
self.assertTrue(octoprint.filemanager.valid_file_type("foo.foo"))
|
||||
self.assertTrue(octoprint.filemanager.valid_file_type("foo.mime_map_yes"))
|
||||
self.assertTrue(octoprint.filemanager.valid_file_type("foo.mime_detect_yes"))
|
||||
self.assertFalse(octoprint.filemanager.valid_file_type("foo.unknown"))
|
||||
|
||||
def test_get_file_type(self):
|
||||
self.assertEquals(["machinecode", "gcode"], octoprint.filemanager.get_file_type("foo.gcode"))
|
||||
self.assertEquals(["machinecode", "gcode"], octoprint.filemanager.get_file_type("foo.gco"))
|
||||
self.assertEquals(["machinecode", "foo"], octoprint.filemanager.get_file_type("foo.f"))
|
||||
self.assertEquals(["model", "stl"], octoprint.filemanager.get_file_type("foo.stl"))
|
||||
self.assertEquals(["model", "amf"], octoprint.filemanager.get_file_type("foo.amf"))
|
||||
self.assertIsNone(octoprint.filemanager.get_file_type("foo.unknown"))
|
||||
|
||||
def test_hook_failure(self):
|
||||
def hook():
|
||||
raise RuntimeError("Boo!")
|
||||
self.plugin_manager.get_hooks.return_value = dict(hook=hook)
|
||||
|
||||
with mock.patch("octoprint.filemanager.logging") as patched_logging:
|
||||
logger = mock.MagicMock()
|
||||
patched_logging.getLogger.return_value = logger
|
||||
|
||||
octoprint.filemanager.get_all_extensions()
|
||||
|
||||
self.assertEquals(1, len(logger.mock_calls))
|
||||
|
||||
class FileManagerTest(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
@@ -109,13 +201,13 @@ class FileManagerTest(unittest.TestCase):
|
||||
self.assertEquals(metadata, expected)
|
||||
self.local_storage.get_metadata.assert_called_once_with("test.file")
|
||||
|
||||
@mock.patch("__builtin__.open", new_callable=mock.mock_open)
|
||||
@mock.patch("octoprint.filemanager.util.atomic_write")
|
||||
@mock.patch("io.FileIO")
|
||||
@mock.patch("shutil.copyfileobj")
|
||||
@mock.patch("os.remove")
|
||||
@mock.patch("tempfile.NamedTemporaryFile")
|
||||
@mock.patch("time.time", side_effect=[1411979916.422, 1411979932.116])
|
||||
def test_slice(self, mocked_time, mocked_tempfile, mocked_os, mocked_shutil, mocked_fileio, mocked_open):
|
||||
def test_slice(self, mocked_time, mocked_tempfile, mocked_os, mocked_shutil, mocked_fileio, mocked_atomic_write):
|
||||
callback = mock.MagicMock()
|
||||
callback_args = ("one", "two", "three")
|
||||
|
||||
@@ -187,8 +279,8 @@ class FileManagerTest(unittest.TestCase):
|
||||
self.local_storage.add_file.assert_called_once_with("dest.file", mock.ANY, printer_profile=expected_printer_profile, allow_overwrite=True, links=expected_links)
|
||||
|
||||
# assert that the generated gcode was manipulated as required
|
||||
expected_open_calls = [mock.call("prefix/dest.file", "wb")]
|
||||
self.assertEquals(mocked_open.call_args_list, expected_open_calls)
|
||||
expected_atomic_write_calls = [mock.call("prefix/dest.file", "wb")]
|
||||
self.assertEquals(mocked_atomic_write.call_args_list, expected_atomic_write_calls)
|
||||
#mocked_open.return_value.write.assert_called_once_with(";Generated from source.file aabbccddeeff\r")
|
||||
|
||||
# assert that shutil was asked to copy the concatenated multistream
|
||||
|
||||
@@ -156,3 +156,76 @@ class TestCommHelpers(unittest.TestCase):
|
||||
self.assertEquals(x_template, x["templates"][x_template_key])
|
||||
|
||||
self.assertEquals("(?P<group{temp_key}>{temp_regex})|(?P<group{x_key}>{x_regex})".format(**locals()), matcher.pattern)
|
||||
|
||||
@data(
|
||||
("G4 P2.0", "floatP", True, "2.0"),
|
||||
("M109 S220.0", "floatS", True, "220.0"),
|
||||
("G1 X10.0 Y10.0 Z0.2", "floatZ", True, "0.2"),
|
||||
("G1X10.0Y10.0Z0.2", "floatZ", True, "0.2"),
|
||||
("g1x10.0y10.0z0.2", "floatZ", True, "0.2"),
|
||||
("M110 N0", "intN", True, "0"),
|
||||
("M104 S220.0 T1", "intT", True, "1"),
|
||||
("M104 T1 S220.0", "intT", True, "1"),
|
||||
("N100 M110", "intN", True, "100"),
|
||||
("NP100", "floatP", False, None),
|
||||
)
|
||||
@unpack
|
||||
def test_parameter_regexes(self, line, parameter, should_match, expected_value):
|
||||
from octoprint.util.comm import regexes_parameters
|
||||
|
||||
regex = regexes_parameters[parameter]
|
||||
match = regex.search(line)
|
||||
|
||||
if should_match:
|
||||
self.assertIsNotNone(match)
|
||||
self.assertEquals(expected_value, match.group("value"))
|
||||
else:
|
||||
self.assertIsNone(match)
|
||||
|
||||
@data(
|
||||
("G0 X0", "G0"),
|
||||
("G28 X0 Y0", "G28"),
|
||||
("M109 S220.0 T1", "M109"),
|
||||
("M117 Hello World", "M117"),
|
||||
("T0", "T"),
|
||||
("T3", "T"),
|
||||
(None, None),
|
||||
("No match", None)
|
||||
)
|
||||
@unpack
|
||||
def test_gcode_command_for_cmd(self, cmd, expected):
|
||||
from octoprint.util.comm import gcode_command_for_cmd
|
||||
result = gcode_command_for_cmd(cmd)
|
||||
self.assertEquals(expected, result)
|
||||
|
||||
@data(
|
||||
("T:23.0 B:60.0", 0, dict(T0=(23.0, None), B=(60.0, None)), 0),
|
||||
("T:23.0 B:60.0", 1, dict(T1=(23.0, None), B=(60.0, None)), 1),
|
||||
("T:23.0/220.0 B:60.0/70.0", 0, dict(T0=(23.0, 220.0), B=(60.0, 70.0)), 0),
|
||||
("ok T:23.0/220.0 T0:23.0/220.0 T1:50.2/210.0 T2:39.4/220.0 B:60.0", 0, dict(T0=(23.0, 220.0), T1=(50.2, 210.0), T2=(39.4, 220.0), B=(60.0, None)), 2),
|
||||
("ok T:50.2/210.0 T0:23.0/220.0 T1:50.2/210.0 T2:39.4/220.0 B:60.0", 1, dict(T0=(23.0, 220.0), T1=(50.2, 210.0), T2=(39.4, 220.0), B=(60.0, None)), 2)
|
||||
)
|
||||
@unpack
|
||||
def test_process_temperature_line(self, line, current, expected_result, expected_max):
|
||||
from octoprint.util.comm import parse_temperature_line
|
||||
maxtool, result = parse_temperature_line(line, current)
|
||||
self.assertDictEqual(expected_result, result)
|
||||
self.assertEquals(expected_max, maxtool)
|
||||
|
||||
@data(
|
||||
(dict(T=(23.0,None)), 0, dict(T0=(23.0, None))),
|
||||
(dict(T=(23.0,None)), 1, dict(T1=(23.0, None))),
|
||||
(dict(T=(23.0, None), T0=(23.0, None), T1=(42.0, None)), 0, dict(T0=(23.0, None), T1=(42.0, None))),
|
||||
(dict(T=(42.0, None), T0=(23.0, None), T1=(42.0, None)), 1, dict(T0=(23.0, None), T1=(42.0, None))),
|
||||
(dict(T=(21.0, None), T0=(23.0, None), T1=(42.0, None)), 0, dict(T0=(21.0, None), T1=(42.0, None))),
|
||||
(dict(T=(41.0, None), T0=(23.0, None), T1=(42.0, None)), 1, dict(T0=(23.0, None), T1=(41.0, None))),
|
||||
(dict(T=(23.0, None), T1=(42.0, None)), 1, dict(T0=(23.0, None), T1=(42.0, None))),
|
||||
(dict(T0=(23.0, None), T1=(42.0, None)), 1, dict(T0=(23.0, None), T1=(42.0, None)))
|
||||
|
||||
)
|
||||
@unpack
|
||||
def test_canonicalize_temperatures(self, parsed, current, expected):
|
||||
from octoprint.util.comm import canonicalize_temperatures
|
||||
result = canonicalize_temperatures(parsed, current)
|
||||
self.assertDictEqual(expected, result)
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import unittest
|
||||
import mock
|
||||
import time
|
||||
|
||||
from octoprint.util import RepeatedTimer
|
||||
|
||||
|
||||
class Countdown(object):
|
||||
def __init__(self, start):
|
||||
self._counter = start
|
||||
|
||||
def step(self):
|
||||
self._counter -= 1
|
||||
|
||||
@property
|
||||
def counter(self):
|
||||
return self._counter
|
||||
|
||||
|
||||
class IncreasingInterval(Countdown):
|
||||
def __init__(self, start, factor):
|
||||
Countdown.__init__(self, start)
|
||||
self._start = start
|
||||
self._factor = factor
|
||||
|
||||
def interval(self):
|
||||
result = (self._start - self._counter + 1) * self._factor
|
||||
return result
|
||||
|
||||
|
||||
class RepeatedTimerTest(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
def test_condition(self):
|
||||
countdown = Countdown(5)
|
||||
timer_task = mock.MagicMock()
|
||||
timer_task.side_effect = countdown.step
|
||||
|
||||
timer = RepeatedTimer(0.1, timer_task, condition=lambda: countdown.counter > 0)
|
||||
timer.start()
|
||||
|
||||
# wait for it
|
||||
timer.join()
|
||||
|
||||
self.assertEquals(5, timer_task.call_count)
|
||||
|
||||
def test_finished_callback(self):
|
||||
countdown = Countdown(5)
|
||||
timer_task = mock.MagicMock()
|
||||
timer_task.side_effect = countdown.step
|
||||
|
||||
on_finished = mock.MagicMock()
|
||||
|
||||
timer = RepeatedTimer(0.1, timer_task, condition=lambda: countdown.counter > 0, on_finish=on_finished)
|
||||
timer.start()
|
||||
|
||||
# wait for it
|
||||
timer.join()
|
||||
|
||||
self.assertEquals(1, on_finished.call_count)
|
||||
|
||||
def test_condition_callback(self):
|
||||
countdown = Countdown(5)
|
||||
timer_task = mock.MagicMock()
|
||||
timer_task.side_effect = countdown.step
|
||||
|
||||
on_cancelled = mock.MagicMock()
|
||||
on_condition_false = mock.MagicMock()
|
||||
|
||||
timer = RepeatedTimer(0.1, timer_task,
|
||||
condition=lambda: countdown.counter > 0,
|
||||
on_condition_false=on_condition_false,
|
||||
on_cancelled=on_cancelled)
|
||||
timer.start()
|
||||
|
||||
# wait for it
|
||||
timer.join()
|
||||
|
||||
self.assertEquals(1, on_condition_false.call_count)
|
||||
self.assertEquals(0, on_cancelled.call_count)
|
||||
|
||||
def test_cancelled_callback(self):
|
||||
countdown = Countdown(5)
|
||||
timer_task = mock.MagicMock()
|
||||
timer_task.side_effect = countdown.step
|
||||
|
||||
on_cancelled = mock.MagicMock()
|
||||
on_condition_false = mock.MagicMock()
|
||||
|
||||
timer = RepeatedTimer(10, timer_task,
|
||||
condition=lambda: countdown.counter > 0,
|
||||
on_condition_false=on_condition_false,
|
||||
on_cancelled=on_cancelled)
|
||||
timer.start()
|
||||
|
||||
# give it some time to run
|
||||
time.sleep(1)
|
||||
|
||||
# then cancel it and wait for the thread to really finish
|
||||
timer.cancel()
|
||||
timer.join()
|
||||
|
||||
self.assertEquals(0, on_condition_false.call_count)
|
||||
self.assertEquals(1, on_cancelled.call_count)
|
||||
|
||||
def test_run_first(self):
|
||||
timer_task = mock.MagicMock()
|
||||
|
||||
timer = RepeatedTimer(60, timer_task, run_first=True)
|
||||
timer.start()
|
||||
|
||||
# give it some time to run
|
||||
time.sleep(1)
|
||||
|
||||
# then cancel it and wait for the thread to really finish
|
||||
timer.cancel()
|
||||
timer.join()
|
||||
|
||||
# should have run once
|
||||
self.assertEquals(1, timer_task.call_count)
|
||||
|
||||
def test_not_run_first(self):
|
||||
timer_task = mock.MagicMock()
|
||||
|
||||
timer = RepeatedTimer(60, timer_task)
|
||||
timer.start()
|
||||
|
||||
# give it some time to run - should hang in the sleep phase though
|
||||
time.sleep(1)
|
||||
|
||||
# then cancel it and wait for the thread to really finish
|
||||
timer.cancel()
|
||||
timer.join()
|
||||
|
||||
self.assertEquals(0, timer_task.call_count)
|
||||
|
||||
def test_adjusted_interval(self):
|
||||
increasing_interval = IncreasingInterval(3, 1)
|
||||
|
||||
timer_task = mock.MagicMock()
|
||||
timer_task.side_effect = increasing_interval.step
|
||||
|
||||
timer = RepeatedTimer(increasing_interval.interval,
|
||||
timer_task,
|
||||
condition=lambda: increasing_interval.counter > 0)
|
||||
|
||||
# this should take 1 + 2 + 3 = 6s
|
||||
start_time = time.time()
|
||||
timer.start()
|
||||
timer.join()
|
||||
duration = time.time() - start_time
|
||||
|
||||
self.assertEquals(3, timer_task.call_count)
|
||||
self.assertGreaterEqual(duration, 6)
|
||||
self.assertLess(duration, 7)
|
||||
|
||||
def test_condition_change_during_task(self):
|
||||
def sleep():
|
||||
time.sleep(2)
|
||||
|
||||
timer_task = mock.MagicMock()
|
||||
timer_task.side_effect = sleep
|
||||
|
||||
timer = RepeatedTimer(0.1, timer_task, run_first=True)
|
||||
timer.start()
|
||||
|
||||
time.sleep(1)
|
||||
timer.condition = lambda: False
|
||||
timer.join()
|
||||
|
||||
self.assertEquals(1, timer_task.call_count)
|
||||
Binary file not shown.
File diff suppressed because it is too large.
Load diff
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user