Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
77753ca026 | ||
|
|
e88e6ba292 | ||
|
|
25c56a5402 | ||
|
|
7fc0f48659 | ||
|
|
dfe345007e | ||
|
|
4fe6e0545a | ||
|
|
c84e199e87 | ||
|
|
79f7a5a1e7 | ||
|
|
679674df22 | ||
|
|
5989d243d3 | ||
|
|
97cb0088f6 | ||
|
|
2ed36ed383 | ||
|
|
12b8a54081 | ||
|
|
a35e145649 | ||
|
|
f77be701a2 | ||
|
|
c33e9e4c85 | ||
|
|
1f9fe8c868 | ||
|
|
8f2e4ad978 | ||
|
|
b82d955ec7 | ||
|
|
832d2f4155 | ||
|
|
c336452f6c | ||
|
|
a9b6edde2b | ||
|
|
d59ef5c711 | ||
|
|
375480c707 | ||
|
|
60cacb9447 | ||
|
|
c159ab7fe2 | ||
|
|
e949e0198f | ||
|
|
1a6dbb3f4a | ||
|
|
10e834f623 | ||
|
|
5ce34f774e | ||
|
|
0456896d71 | ||
|
|
e06c09e206 | ||
|
|
a6d3299b91 | ||
|
|
0a7f2a209b | ||
|
|
67f7580506 | ||
|
|
aab3a7bd63 | ||
|
|
d0f5592421 | ||
|
|
bb6ea4d81b | ||
|
|
7e32e5be8f | ||
|
|
266cae3509 | ||
|
|
0dcbffb9d2 | ||
|
|
fb8c56be57 | ||
|
|
2bc0c4a77f | ||
|
|
187c09e7da | ||
|
|
5c62b33967 | ||
|
|
5db9acb359 | ||
|
|
962d6ab27f | ||
|
|
21699699b6 | ||
|
|
8fec0859d9 | ||
|
|
1b9ff1b0e2 | ||
|
|
ee2d644239 | ||
|
|
a50db4b08e | ||
|
|
6f5707a0fc | ||
|
|
cf053ddbed | ||
|
|
b1101f5150 | ||
|
|
3a9d581423 | ||
|
|
142a1b0dcb | ||
|
|
a33f44ea25 | ||
|
|
23e58d2fc1 | ||
|
|
2e897f19ac | ||
|
|
16e96743c5 | ||
|
|
4c6c764c5c | ||
|
|
e86ba9a395 | ||
|
|
c1c09d417d | ||
|
|
f8d225a768 | ||
|
|
4c3f4c2a8b | ||
|
|
cc3d34635e | ||
|
|
c81c93896b | ||
|
|
3cdc59d7f1 | ||
|
|
5156cdbe68 | ||
|
|
0915c45f72 | ||
|
|
b2c1bb4b53 | ||
|
|
3bb06a1a33 | ||
|
|
8ad165c625 | ||
|
|
841b86a017 | ||
|
|
c0c249ece9 | ||
|
|
5fc194accd | ||
|
|
ed6c01c12a | ||
|
|
e309646504 | ||
|
|
96ee80afd2 | ||
|
|
8aec836d22 | ||
|
|
697df4f3ce | ||
|
|
ac3f4d598c | ||
|
|
836fbef6d8 | ||
|
|
ce4cf38547 | ||
|
|
38a5da1c35 | ||
|
|
b205e84d4b | ||
|
|
7ab4d12548 | ||
|
|
f6c3e5991d | ||
|
|
188b59a319 | ||
|
|
b3594e367e | ||
|
|
12d40122d1 | ||
|
|
2e11a7b860 | ||
|
|
f20185db3a | ||
|
|
0db323d0c5 | ||
|
|
639d8d4c5f | ||
|
|
5e0b53b651 | ||
|
|
1ebfa4b1dd | ||
|
|
35c45df86c | ||
|
|
a50e8bbbb5 | ||
|
|
4665070601 | ||
|
|
b34fc8e05e | ||
|
|
a3ece229f2 | ||
|
|
fc53febb87 | ||
|
|
dad956b5c9 | ||
|
|
981110d4b2 | ||
|
|
cbd94a9020 | ||
|
|
77db00a2ea | ||
|
|
665078e1a4 | ||
|
|
cfae406a4c | ||
|
|
00c14e6936 | ||
|
|
6a1b162e7b | ||
|
|
a2fd39b3c4 | ||
|
|
bda2fd94e3 | ||
|
|
9e207ca8a1 | ||
|
|
5d321926bb | ||
|
|
3d3e0212c6 | ||
|
|
e3d44d7d06 | ||
|
|
d39c124f35 | ||
|
|
8603ea4b6f | ||
|
|
a681048df6 | ||
|
|
d689496802 | ||
|
|
5a23b46c11 | ||
|
|
2b96e57923 | ||
|
|
885e88a5e0 | ||
|
|
674637f6b2 | ||
|
|
9056f5d610 | ||
|
|
0feae3ba18 | ||
|
|
1cc3ddb03c | ||
|
|
33cafbbd8a | ||
|
|
d274a9c73d | ||
|
|
c3619a3795 | ||
|
|
dffb33727d | ||
|
|
78724163b1 | ||
|
|
b6a09abb83 | ||
|
|
77b6d83e0b | ||
|
|
7c6b85a0ad | ||
|
|
5e55d637af | ||
|
|
8942d7d50d | ||
|
|
0ad09e422d | ||
|
|
0657160389 | ||
|
|
cfde6342a8 | ||
|
|
832c27ed18 | ||
|
|
59d78ba893 | ||
|
|
7770ee3d08 | ||
|
|
2d9ad41e49 | ||
|
|
821156c9d6 | ||
|
|
9e5982be29 | ||
|
|
39c87d19b7 | ||
|
|
d029abc8f3 | ||
|
|
7b5848b9c3 | ||
|
|
53bfbf5acf | ||
|
|
917c9e54ba | ||
|
|
d8d9c7fe64 | ||
|
|
6c0f2de780 | ||
|
|
700975d670 | ||
|
|
9fac314d71 | ||
|
|
9dfee34f01 | ||
|
|
dc8473bc4d | ||
|
|
c1c75f032d | ||
|
|
9ad180c02a | ||
|
|
7795320fc8 | ||
|
|
a54c8fbeb7 | ||
|
|
263c297bed |
No files matched your search
+8
-6
@@ -16,14 +16,16 @@ prerelease
|
||||
HEAD
|
||||
\(detached.*
|
||||
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.3.3
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.3.5
|
||||
# so are any fix/... and improve/... branches
|
||||
maintenance 1.3.3 0a69dbeddb301d5a32827a3f0d561f875df24234 pep440-dev
|
||||
fix/.* 1.3.3 0a69dbeddb301d5a32827a3f0d561f875df24234 pep440-dev
|
||||
improve/.* 1.3.3 0a69dbeddb301d5a32827a3f0d561f875df24234 pep440-dev
|
||||
maintenance 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev
|
||||
fix/.* 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev
|
||||
improve/.* 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev
|
||||
|
||||
# staging/maintenance is currently the branch for preparation of 1.3.3rc4 (if we'll need that)
|
||||
staging/maintenance 1.3.3rc4 ce1541e956778b732458599a21f38b6783a0c2ec pep440-dev
|
||||
# staging/maintenance is currently the branch for preparation of 1.3.5rc4
|
||||
# so is regressionfix/...
|
||||
staging/maintenance 1.3.5rc4 679674df2282af0c4500367fa93864c6defa3802 pep440-dev
|
||||
regressionfix/.* 1.3.5rc4 679674df2282af0c4500367fa93864c6defa3802 pep440-dev
|
||||
|
||||
# every other branch is a development branch and thus gets resolved to 1.4.0-dev for now
|
||||
.* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
|
||||
@@ -80,6 +80,7 @@ date of first contribution):
|
||||
* [Andreas Werner](https://github.com/gallore)
|
||||
* [Shawn Bruce](https://github.com/kantlivelong)
|
||||
* [Claudiu Ceia] (https://github.com/ClaudiuCeia)
|
||||
* [Goswin von Brederlow](https://github.com/mrvn)
|
||||
|
||||
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
|
||||
|
||||
@@ -1,5 +1,98 @@
|
||||
# OctoPrint Changelog
|
||||
|
||||
## 1.3.5 (2017-10-16)
|
||||
|
||||
### Improvements
|
||||
|
||||
* [#1162](https://github.com/foosel/OctoPrint/pull/1162) - Allow `octoprint.comm.protocol.gcode.queuing` hook to return a list of commands.
|
||||
* [#1572](https://github.com/foosel/OctoPrint/issues/1572) & [#1881](https://github.com/foosel/OctoPrint/issues/1881) - Refactored web interface startup process to minimise risk of race conditions and speed improvements. Also added sequence diagram to the documentation showing the new processing order.
|
||||
* [#1640](https://github.com/foosel/OctoPrint/issues/1640) - Mouse over temperature graph to get exact data for that time.
|
||||
* [#1679](https://github.com/foosel/OctoPrint/issues/1679) - Support temperature autoreporting by the firmware instead of polling if the firmware reports to support it. For this to work with Marlin 1.1.0 to 1.1.3 you'll need to explicitly enable `EXTENDED_CAPABILITIES_REPORT` *and* `AUTO_REPORT_TEMPERATURES` in your firmware configuration, otherwise your firmware won't report that it actually supports this feature.
|
||||
* [#1737](https://github.com/foosel/OctoPrint/issues/1737) - Auto-detect Anet A8 firmware and treat as Repetier Firmware (which it actually appears to be, just renamed - thanks Anet for making this even harder).
|
||||
* [#1842](https://github.com/foosel/OctoPrint/issues/1842) - Update bundled FontAwesome to 4.7 (see also [#1915](https://github.com/foosel/OctoPrint/pull/1915)).
|
||||
* [#1910](https://github.com/foosel/OctoPrint/issues/1910) - Make last/pause/cancel temperature available for GCODE scripts.
|
||||
* [#1925](https://github.com/foosel/OctoPrint/issues/1925) - Include configured webcam stream URL in "Webcam stream not loaded" message for logged in users/admins. Slightly different wording for guests vs users vs admins.
|
||||
* [#1941](https://github.com/foosel/OctoPrint/issues/1941) - Enable "block while dwelling" flag when Malyan firmware is detected since that firmware seems to handle `G4` identically to Repetier Firmware instead of Marlin (like it claims to). See also [#1762](https://github.com/foosel/OctoPrint/issues/1762).
|
||||
* [#1946](https://github.com/foosel/OctoPrint/issues/1946) - Add option to disable position logging on cancel/pause. See "Log position on cancel" and "Log position on pause" under Settings > Serial > Advanced options.
|
||||
* [#1971](https://github.com/foosel/OctoPrint/issues/1971) - Refactored temperature inputs. They now sport some fancy +/- buttons to increment/decrement the current temperature (which also auto submit after a couple of seconds) and easier editing by keyboard. The temperature offset was also slightly redesigned to make room for that.
|
||||
* [#1975](https://github.com/foosel/OctoPrint/issues/1975) - Better error reporting when deleting timelapses.
|
||||
* [#2010](https://github.com/foosel/OctoPrint/pull/2010) - Slight refactoring in the terminal tab: Full width input field, auto focus of input field when just clicking on terminal output.
|
||||
* [#2011](https://github.com/foosel/OctoPrint/issues/2011) - Centralized online connectivity check (with opt-in of course). None of the bundled plugins will attempt to fetch data from the net when the connectivity check indicates that would fail anyhow. This should improve server startup times and various requests when running isolated.
|
||||
* [#2025](https://github.com/foosel/OctoPrint/issues/2025) - More verbose logging of asynchronous system commands (e.g. restart/shutdown).
|
||||
* Allow timelapse configuration through UI even when not connected to the printer (suggested in [#1918](https://github.com/foosel/OctoPrint/issues/1918))
|
||||
* Disable "Upload to SD" UI elements while printing (suggested in [#1914](https://github.com/foosel/OctoPrint/issues/1914))
|
||||
* Update bundled SockJS to 1.1.2 incl. source maps
|
||||
* Set `X-Robots` HTTP header and remove `Server` header from all responses, also set `robots` meta tag in page.
|
||||
* Don't require to enter programmer mode for printer port autodetection when there's only one possible port candidate anyhow.
|
||||
* More sensible sorting of baudrates (additionally configured, then 115200, then 250000, then everything else).
|
||||
* Don't show "Unhandled communication error" on autodetection failure.
|
||||
* Make timeout after which to unload the webcam stream after navigating away from it configurable (as suggested in [#1937](https://github.com/foosel/OctoPrint/issues/1937))
|
||||
* Add `ToolChange` event and tool change GCODE scripts
|
||||
* Support parsing GCODE subcodes.
|
||||
* Add `octoprint.users.factory` hook, allowing plugins to extend/swap out the user manager OctoPrint uses.
|
||||
* Corewizard: Disable view model and client code if it's not actually required.
|
||||
* Corewizard: Disable injection of JS files into UI when it's not actually required.
|
||||
* GCODE analysis: Moved into its own subprocess. That should improve performance on multi core systems.
|
||||
* GCODE viewer: Ignore coordinates outside bed when zooming/centering on model. Those usually are nozzle priming routines.
|
||||
* JS Client Lib: Add centralized browser detection as `OctoPrint.coreui.browser`. Available properties: `chrome`, `firefox`, `safari`, `ie`, `edge`, `opera` as well as `mobile` and `desktop`, all of which are boolean values.
|
||||
* Plugin Manager plugin: Detect if a plugin requires a reconnect to the printer to become fully active/inactive.
|
||||
* Software Update plugin: Force exact version when updating OctoPrint and tracking releases.
|
||||
* Software Update plugin: "Devel RCs" release channel now also tracks maintenance RCs. That way people don't have to toggle between the two any more to get *all* RCs.
|
||||
* Software Update plugin: `bitbucket_commit` check type now supports API credentials (see also [#1993](https://github.com/foosel/OctoPrint/pull/1993)).
|
||||
* Wizard: Allow suppressing the "the settings got updated" dialog through subwizards, in case they need to update settings asynchronously as part of their workflow.
|
||||
* More resilience against expected folders being files.
|
||||
* More resilience against a wrong user manager class being configured.
|
||||
* Some code refactoring & cleanup.
|
||||
* Some HTML & CSS improvements.
|
||||
|
||||
### Bug fixes
|
||||
|
||||
* [#1916](https://github.com/foosel/OctoPrint/issues/1916) - Fix webcam not loading if first/initial tab is "Control"
|
||||
* [#1924](https://github.com/foosel/OctoPrint/issues/1924) - Filter out source map links from bundled JS webassets.
|
||||
* [#1943](https://github.com/foosel/OctoPrint/issues/1943) - Fix issue causing unnecessary creation of default printer profile on startup
|
||||
* [#1946](https://github.com/foosel/OctoPrint/issues/1946) - Decouple writing of print log from everything else. Fixes delay in cancel processing.
|
||||
* [#1963](https://github.com/foosel/OctoPrint/issues/1963) & [#1974](https://github.com/foosel/OctoPrint/issues/1974) - Allow empty & custom size in print job events. Also fixes an issue with timelapses when printing from SD on printers that require the GPX plugin to work.
|
||||
* [#1996](https://github.com/foosel/OctoPrint/issues/1996) - Support all line ending variantes in the GCODE viewer. Solves an issue with GCODE generated for Prusa's multi material extruder since that uses only `\r` for some reason.
|
||||
* [#2007](https://github.com/foosel/OctoPrint/issues/2007) - Fix issue parsing temperature lines from the printer that contain negative values.
|
||||
* [#2012](https://github.com/foosel/OctoPrint/issues/2012) - Fix command line interface of Software Update plugin.
|
||||
* [#2017](https://github.com/foosel/OctoPrint/issues/2017) - Fix issue in GCODE viewer with files that contain a visit to the first layer twice (e.g. brim, then nose dive from higher z for actual model), causing all but the last layer segment to not be rendered.
|
||||
* [#2033](https://github.com/foosel/OctoPrint/issues/2033) (regression) - Temperature tab: Fix for legend in graph not updating with current values on mouse over.
|
||||
* [#2033](https://github.com/foosel/OctoPrint/issues/2033) (regression) - Temperature tab: Fix for new temperature inputs not fitting on one line in Firefox.
|
||||
* [#2033](https://github.com/foosel/OctoPrint/issues/2033) (regression) - Temperature tab & GCODE viewer: Fix for available tools (and offsets) not properly updating on change of printer profile.
|
||||
* [#2033](https://github.com/foosel/OctoPrint/issues/2033) (regression) - Wizard: Fix sorting of required wizards not properly handling non-ASCII unicode.
|
||||
* [#2035](https://github.com/foosel/OctoPrint/issues/2035) (regression) - Fix an issue of the server not starting up if there's a file in the analysis backlog. The reason for this is that spawning a new process while the intermediary server is active causes the server port to be blocked (this is due to how subprocessing works by default), in turn leading to an error on startup since the port cannot be bound by the actual server. Since the GCODE analysis takes now place in its own subprocess and hence triggers this problem, it had to be moved until after the actual server has already started up to avoid this problem.
|
||||
* [#2059](https://github.com/foosel/OctoPrint/issues/2059) (regression) - Fix an issue causing the new temperature controls to wrap on touch enabled devices when the temperature dropdown is opened.
|
||||
* [#2090](https://github.com/foosel/OctoPrint/issues/2090) (regression) - Fix an issue causing an aborted server startup under Windows if the timing is just right.
|
||||
* [#2135](https://github.com/foosel/OctoPrint/issues/2135) (regression) - Fix an issue causing import errors inside the GCODE analysis tool in certain environments due to `sys.path` entries causing relative imports.
|
||||
* [#2136](https://github.com/foosel/OctoPrint/issues/2136) (regression) - Fix wrong minimum version for `sockjs-tornado` dependency.
|
||||
* [#2137](https://github.com/foosel/OctoPrint/issues/2137) (regression) - Fix issue with session cookies getting lost when running an OctoPrint instance on a subpath of another (e.g. `octopi.local/` and `octopi.local/octoprint2`).
|
||||
* [#2140](https://github.com/foosel/OctoPrint/issues/2140) (regression) - Fix issue with locale dependent sorting of sub wizards during first time setup causing issues leading to the wizard not being able to complete.
|
||||
* Fix various popup buttons allowing multiple clicks (suggested in [#1914](https://github.com/foosel/OctoPrint/issues/1914))
|
||||
* Software Update Plugin: Perform server restart asynchronously. Should reduce restart times on updates significantly.
|
||||
* Don't hex-escape `\t`, `\r` or `\n` in terminal output
|
||||
* Use client side default printer profile if the default profile could not be found on the server
|
||||
* Use both "to" and "from" coordinates of a given move for min/max model coordinate calculation in GCODE analysis. Otherwise wrong values could be calculated under certain circumstances.
|
||||
* Fix potential race condition in resend request handling.
|
||||
* Fix potential race condition in web socket handling.
|
||||
* Fix handling of tool offsets in GCODE analysis - diverted too far from firmware implementations, causing wrong calculations.
|
||||
* Fix `FileAdded`, `FileRemoved`, `FolderAdded`, `FolderRemoved` events not being fired with the correct event name.
|
||||
* Fix potential division by zero in progress reporting if the timing was just right.
|
||||
* Fix sorting order for multiple tools in the "State" panel.
|
||||
* Fix file position vs. line ending handling in GCODE viewer. Could lead to slightly off file position calculation and hence possibly to the wrong move being plotted when synchronizing with print progress.
|
||||
* Wizard: Fix `onWizardPreventSettingsRefreshDialog` callback invocation. (regression)
|
||||
* Corewizard plugin: Fix `firstrunonly` wizards (e.g. for printer profile configuration) being displayed again if _any_ of the sub wizards (e.g. for the online check opt-in and configuration) is active. (regression)
|
||||
* Fix an issue causing rollover of `serial.log` to fail under Windows. (regression)
|
||||
|
||||
### More Information
|
||||
|
||||
* [Commits](https://github.com/foosel/OctoPrint/compare/1.3.4...1.3.5)
|
||||
* Release Candidates:
|
||||
* [1.3.5rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.5rc1)
|
||||
* [1.3.5rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.5rc2)
|
||||
* [1.3.5rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.5rc3)
|
||||
* [1.3.5rc4](https://github.com/foosel/OctoPrint/releases/tag/1.3.5rc4)
|
||||
* A special **Thank you!** to everyone who reported back on these release candidates this time: [alexxy](https://github.com/alexxy), [andrivet](https://github.com/andrivet), [b-morgan](https://github.com/b-morgan), [BillyBlaze](https://github.com/BillyBlaze), [CapnBry](https://github.com/CapnBry), [chippypilot](https://github.com/chippypilot), [ctgreybeard](https://github.com/ctgreybeard), [cxt666](https://github.com/cxt666), [DaSTIG](https://github.com/DaSTIG), [fhbmax](https://github.com/fhbmax), [fiveangle](https://github.com/fiveangle), [goeland86](https://github.com/goeland86), [JohnOCFII](https://github.com/JohnOCFII), [Kunsi](https://github.com/Kunsi), [mgrl](https://github.com/mgrl), [MoonshineSG](https://github.com/MoonshineSG), [nate-ubiquisoft](https://github.com/nate-ubiquisoft), [Neoolog](https://github.com/Neoolog), [ntoff](https://github.com/ntoff), [oferfrid](https://github.com/oferfrid), [roygilby](https://github.com/roygilby), [SAinc](https://github.com/SAinc), [sbts](https://github.com/sbts), [thess](https://github.com/thess), [tkurbad](https://github.com/tkurbad), [tsillini](https://github.com/tsillini) and [TylonHH](https://github.com/TylonHH).
|
||||
|
||||
## 1.3.4 (2017-06-01)
|
||||
|
||||
### Note for owners of Malyan M200/Monoprice Select Mini
|
||||
|
||||
+6
-7
@@ -14,30 +14,29 @@ thanks to everyone who contributed!
|
||||
* Boris Hussein
|
||||
* Brad Jackson
|
||||
* Brian E. Tyler
|
||||
* Chris Day
|
||||
* Christian Petropolis
|
||||
* COLLE+McVOY
|
||||
* CreativeTools
|
||||
* D Brian Kimmel
|
||||
* DeltaMaker 3D Printers
|
||||
* Doug Johnson
|
||||
* E3D BigBox
|
||||
* Ernesto Martinez
|
||||
* Exovite
|
||||
* F. Kunsmann
|
||||
* Farren Young II
|
||||
* Frank Sander
|
||||
* Gary Deen
|
||||
* Gary N McKinney
|
||||
* George Robles
|
||||
* günter weber
|
||||
* Ivan Krasin
|
||||
* James Seigel
|
||||
* Jamie R McGuigan
|
||||
* Jason Lawrence
|
||||
* Jeff Moe
|
||||
* Josh Daniels
|
||||
* Kaile Riser
|
||||
* Kale Stedman
|
||||
* Kazuhiro Ogura
|
||||
* Lamin Kivelä
|
||||
* Makespace Madrid
|
||||
* Marcus Ackermann
|
||||
* Mark Qvist
|
||||
@@ -45,6 +44,7 @@ thanks to everyone who contributed!
|
||||
* Masayoshi Mitsui
|
||||
* Michael Aumock
|
||||
* Miles Flavel
|
||||
* mitchell hirsch
|
||||
* Mohammed khorakiwala
|
||||
* Noe Ruiz
|
||||
* Patrick McGinnis
|
||||
@@ -55,14 +55,13 @@ thanks to everyone who contributed!
|
||||
* Roger Strolz
|
||||
* Roy Cortes
|
||||
* Samer Najia
|
||||
* SD3D
|
||||
* SeeMeCNC
|
||||
* Simon Hallam
|
||||
* Stefan Krister
|
||||
* Stephane Schittly
|
||||
* Sven Mueller
|
||||
* Symbiotic Devices
|
||||
* Thomas Hatley
|
||||
* Timeshell.ca
|
||||
* Trent Shumay
|
||||
|
||||
and 1098 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
||||
and 1133 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
||||
@@ -54,6 +54,12 @@ under Settings > Plugin Manager, or by directly editing ``config.yaml``:
|
||||
# Time to live for the repository cache
|
||||
repository_ttl: 1440
|
||||
|
||||
# The URL of the plugin notices feed to use
|
||||
notices: http://plugins.octoprint.org/notices.json
|
||||
|
||||
# Time to live for the notices feed cache
|
||||
notices_ttl: 360
|
||||
|
||||
# Additional arguments to use with pip. Defaults to unset,
|
||||
# you normally shouldn't need to modify this
|
||||
pip_args: --some --additional --pip --arguments
|
||||
@@ -76,6 +82,36 @@ under Settings > Plugin Manager, or by directly editing ``config.yaml``:
|
||||
- hidden
|
||||
- plugins
|
||||
|
||||
.. _sec-bundledplugins-pluginmanager-hooks:
|
||||
|
||||
Hooks
|
||||
-----
|
||||
|
||||
.. _sec-bundledplugins-pluginmanager-hooks-reconnect_hooks:
|
||||
|
||||
octoprint.plugin.pluginmanager.reconnect_hooks
|
||||
++++++++++++++++++++++++++++++++++++++++++++++
|
||||
|
||||
.. py:function:: reconnect_hooks_hook(*args, **kwargs)
|
||||
|
||||
Returns additional hooks defined by the plugin for which the plugin manager
|
||||
should display the "You should reconnect to your printer" message on plugin
|
||||
install/uninstall/enabling/disabling.
|
||||
|
||||
Handlers should return a Python list containing the affected hook names.
|
||||
|
||||
**Example**
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def reconnect_hooks_hook(*args, **kwargs):
|
||||
return ["octoprint.plugin.exampleplugin.some_custom_hook",
|
||||
"octoprint.plugin.exampleplugin.some_other_custom_hook"]
|
||||
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.plugin.pluginmanager.reconnect_hooks": reconnect_hooks_hook
|
||||
}
|
||||
|
||||
.. _sec-bundledplugins-pluginmanager-sourcecode:
|
||||
|
||||
Source Code
|
||||
|
||||
@@ -198,6 +198,13 @@ Version checks
|
||||
* ``branch``: Branch of the Bitbucket repository to check, defaults to
|
||||
``master`` if not set.
|
||||
* ``current``: Current commit hash. Will be updated automatically.
|
||||
* ``api_user``: (mandatory only for private repositories) Bitbucket user name (not email address).
|
||||
Requires ``api_password`` to be set. Hint: This is used for the check only. For the actual
|
||||
download you might register your public SSH key as access key for the according repo and
|
||||
configure this as pip URL in ``config.yaml``: ``git+ssh://git@bitbucket.org/my_user/my_repo.git@{target_version}``
|
||||
* ``api_password``: (mandatory only for private repositories) App password. Requires
|
||||
``api_user`` to be set. **Important**: Never use your actual Bitbucket login password. Generate
|
||||
a new app password. App passwords are user specific on Bitbucket.
|
||||
|
||||
* ``git_commit``: Checks a local git repository for new commits on its
|
||||
configured remote. Additional config parameters:
|
||||
|
||||
+1
-1
@@ -33,7 +33,7 @@ needs_sphinx = '1.3'
|
||||
# Add any Sphinx extension module names here, as strings. They can be extensions
|
||||
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
|
||||
extensions = ['codeblockext', 'onlineinclude', 'sphinx.ext.todo', 'sphinx.ext.autodoc', 'sphinxcontrib.httpdomain',
|
||||
'sphinx.ext.napoleon']
|
||||
'sphinx.ext.napoleon', 'sphinxcontrib.mermaid']
|
||||
todo_include_todos = True
|
||||
|
||||
# Add any paths that contain templates here, relative to this directory.
|
||||
|
||||
@@ -909,6 +909,20 @@ Use the following settings to configure the server:
|
||||
# Command to shut down the system OctoPrint is running on, defaults to being unset
|
||||
systemShutdownCommand: sudo shutdown -h now
|
||||
|
||||
# Configuration of the regular online connectivity check
|
||||
onlineCheck:
|
||||
# whether the online check is enabled, defaults to false due to valid privacy concerns
|
||||
enabled: false
|
||||
|
||||
# interval in which to check for online connectivity (in seconds)
|
||||
interval: 300
|
||||
|
||||
# DNS host against which to check (default: 8.8.8.8 aka Google's DNS)
|
||||
host: 8.8.8.8
|
||||
|
||||
# DNS port against which to check (default: 53 - the default DNS port)
|
||||
port: 53
|
||||
|
||||
# Settings of when to display what disk space warning
|
||||
diskspace:
|
||||
|
||||
|
||||
@@ -110,6 +110,14 @@ ClientClosed
|
||||
|
||||
* ``remoteAddress``: the remote address (IP) of the client that disconnected
|
||||
|
||||
ConnectivityChanged
|
||||
The server's internet connectivity changed
|
||||
|
||||
Payload:
|
||||
|
||||
* ``old``: Old connectivity value (true for online, false for offline)
|
||||
* ``new``: New connectivity value (true for online, false for offline)
|
||||
|
||||
Printer communication
|
||||
---------------------
|
||||
|
||||
@@ -477,6 +485,15 @@ PositionUpdate
|
||||
* ``t``: last tool selected *through OctoPrint*
|
||||
* ``f``: last feedrate for move commands ``G0``, ``G1`` or ``G28`` sent *through OctoPrint*
|
||||
|
||||
ToolChange
|
||||
A tool change command was sent to the printer. The payload contains the former current tool index and the
|
||||
new current tool index.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``old``: old tool index
|
||||
* ``new``: new tool index
|
||||
|
||||
Timelapses
|
||||
----------
|
||||
|
||||
|
||||
@@ -68,7 +68,16 @@ All GCODE scripts have access to the following template variables through the te
|
||||
|
||||
* ``printer_profile``: The currently selected Printer Profile, including
|
||||
information such as the extruder count, the build volume size, the filament diameter etc.
|
||||
* ``last_position``: Last position reported by the printer via `M114` (might be unset if no `M114` was sent so far!)
|
||||
* ``last_position``: Last position reported by the printer via `M114` (might be unset if no `M114` was sent so far!).
|
||||
Consists of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and
|
||||
current tool ``t`` taken from commands sent through OctoPrint. All of these coordinates might be ``None`` if no
|
||||
position could be retrieved from the printer or the values could not be tracked (in case of ``f`` and ``t``)!
|
||||
* ``last_temperature``: Last actual and target temperature reported for all available tools and if available the
|
||||
heated bed. This is a dictionary of key-value pairs. The keys are the indices of the available tools (``0``, ``1``,
|
||||
...) and ``b`` for the heated bed. The values are a dictionary consisting of ``actual`` and ``target`` keys mapped
|
||||
to the corresponding temperature in degrees celsius. Note that not all tools your printer has must necessarily be
|
||||
present here, neither must the heated bed - it depends on whether OctoPrint has values for a tool or the bed. Also
|
||||
note that ``actual`` and ``target`` might be ``None``.
|
||||
* ``script``: An object wrapping the script's type (``gcode``) and name (e.g. ``afterPrintCancelled``) as ``script.type``
|
||||
and ``script.name`` respectively.
|
||||
|
||||
@@ -76,17 +85,24 @@ There are a few additional template variables available for the following specif
|
||||
|
||||
* ``afterPrintPaused`` and ``beforePrintResumed``
|
||||
|
||||
* ``pause_position``: Position reported by the printer via ``M114`` immediately before the print was paused. Consists
|
||||
of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and current tool
|
||||
``t`` taken from commands sent through OctoPrint. All of these coordinates might be ``None`` if no position could be
|
||||
retrieved from the printer or the values could not be tracked (in case of ``f`` and ``t``)!
|
||||
* ``pause_position``: Position reported by the printer via ``M114`` immediately before the print was paused. See
|
||||
``last_position`` above for the structure to expect here.
|
||||
|
||||
**Please note:** This will not be available if you disable
|
||||
"Log position on pause" under Settings > Serial > Advanced options!
|
||||
* ``pause_temperature``: Last known temperature values when the print was paused. See ``last_temperature`` above
|
||||
for the structure to expect here.
|
||||
|
||||
* ``afterPrintCancelled``
|
||||
|
||||
* ``cancel_position``: Position reported by the printer via ``M114`` immediately before the print was cancelled.
|
||||
Consists of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and
|
||||
current tool ``t`` taken from commands sent through OctoPrint. All of these coordinates might be ``None`` if no
|
||||
position could be retrieved from the printer or the values could not be tracked (in case of ``f`` and ``t``)!
|
||||
See ``last_position`` above for the structure to expect here.
|
||||
|
||||
**Please note:** This will not be available if you disable
|
||||
"Log position on cancel" under Settings > Serial > Advanced options!
|
||||
* ``cancel_temperature``: Last known temperature values when the print was cancelled. See ``last_temperature`` above
|
||||
for the structure to expect here.
|
||||
|
||||
|
||||
.. warning::
|
||||
|
||||
|
||||
@@ -14,4 +14,5 @@ Internal Modules
|
||||
server.rst
|
||||
settings.rst
|
||||
slicing.rst
|
||||
users.rst
|
||||
util.rst
|
||||
@@ -0,0 +1,9 @@
|
||||
.. _sec-modules-users:
|
||||
|
||||
octoprint.users
|
||||
---------------
|
||||
|
||||
.. automodule:: octoprint.users
|
||||
:members:
|
||||
|
||||
|
||||
+62
-3
@@ -389,14 +389,15 @@ This describes actually four hooks:
|
||||
* ``octoprint.comm.protocol.gcode.sending``
|
||||
* ``octoprint.comm.protocol.gcode.sent``
|
||||
|
||||
.. py:function:: protocol_gcodephase_hook(comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs)
|
||||
.. py:function:: protocol_gcodephase_hook(comm_instance, phase, cmd, cmd_type, gcode, subcode=None, *args, **kwargs)
|
||||
|
||||
Pre- and postprocess commands as they progress through the various phases of being sent to the printer. The phases
|
||||
are the following:
|
||||
|
||||
* ``queuing``: This phase is triggered just before the command is added to the send queue of the communication layer. This
|
||||
corresponds to the moment a command is being read from a file that is currently being printed. Handlers
|
||||
may suppress or change commands or their command type here.
|
||||
may suppress or change commands or their command type here. This is the only phase that supports multi command
|
||||
expansion by having the handler return a list, see below for details.
|
||||
* ``queued``: This phase is triggered just after the command was added to the send queue of the communication layer.
|
||||
No manipulation is possible here anymore (returned values will be ignored).
|
||||
* ``sending``: This phase is triggered just before the command is actually being sent to the printer. Right afterwards
|
||||
@@ -425,7 +426,7 @@ This describes actually four hooks:
|
||||
|
||||
* ``None``: Don't change anything. Note that Python functions will also automatically return ``None`` if
|
||||
an empty ``return`` statement is used or just nothing is returned explicitly from the handler. Hence, the following
|
||||
examples are all falling into this category:
|
||||
examples are all falling into this category and equivalent:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@@ -450,6 +451,27 @@ This describes actually four hooks:
|
||||
should use this option.
|
||||
* A 2-tuple consisting of a rewritten version of the ``cmd`` and the ``cmd_type``, e.g. ``return "M105", "temperature_poll"``.
|
||||
Handlers which wish to rewrite both the command and the command type should use this option.
|
||||
* **"queuing" phase only**: A list of any of the above to allow for expanding one command into
|
||||
many. The following example shows how any queued command could be turned into a sequence of a temperature query,
|
||||
line number reset, display of the ``gcode`` on the printer's display and finally the actual command (this example
|
||||
does not make a lot of sense to be quite honest):
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def rewrite_foo(self, comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs):
|
||||
if gcode or not cmd.startswith("@foo"):
|
||||
return
|
||||
|
||||
return [("M105", "temperature_poll"), # 2-tuple, command & command type
|
||||
("M110",), # 1-tuple, just the command
|
||||
"M117 echo foo: {}".format(cmd)] # string, just the command
|
||||
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.comm.protocol.gcode.queuing": rewrite_foo
|
||||
}
|
||||
|
||||
Note: Only one command of a given ``cmd_type`` (other than None) may be queued at a time. Trying to rewrite the ``cmd_type``
|
||||
to one already in the queue will give an error.
|
||||
|
||||
**Example**
|
||||
|
||||
@@ -469,6 +491,8 @@ This describes actually four hooks:
|
||||
:param str cmd_type: Type of command, e.g. ``temperature_poll`` for temperature polling or ``sd_status_poll`` for SD
|
||||
printing status polling.
|
||||
:param str gcode: Parsed GCODE command, e.g. ``G0`` or ``M110``, may also be None if no known command could be parsed
|
||||
:param str subcode: Parsed subcode of the GCODE command, e.g. ``1`` for ``M80.1``. Will be None if no subcode was provided
|
||||
or no command could be parsed.
|
||||
:return: None, 1-tuple, 2-tuple or string, see the description above for details.
|
||||
|
||||
.. _sec-plugins-hook-comm-protocol-gcode-received:
|
||||
@@ -922,3 +946,38 @@ octoprint.ui.web.templatetypes
|
||||
:param dict template_sorting: read-only dictionary of currently configured template sorting specifications
|
||||
:return: a list of 3-tuples (template type, rule, sorting spec)
|
||||
:rtype: list
|
||||
|
||||
.. _sec-plugins-hook-users-factory:
|
||||
|
||||
octoprint.users.factory
|
||||
~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: user_manager_factory_hook(components, settings, *args, **kwargs)
|
||||
|
||||
Return a :class:`~octoprint.users.UserManager` instance to use as global user manager object. This will
|
||||
be called only once during initial server startup.
|
||||
|
||||
The provided ``components`` is a dictionary containing the already initialized system components:
|
||||
|
||||
* ``plugin_manager``: The :class:`~octoprint.plugin.core.PluginManager`
|
||||
* ``printer_profile_manager``: The :class:`~octoprint.printer.profile.PrinterProfileManager`
|
||||
* ``event_bus``: The :class:`~octoprint.events.EventManager`
|
||||
* ``analysis_queue``: The :class:`~octoprint.filemanager.analysis.AnalysisQueue`
|
||||
* ``slicing_manager``: The :class:`~octoprint.slicing.SlicingManager`
|
||||
* ``file_manager``: The :class:`~octoprint.filemanager.FileManager`
|
||||
* ``app_session_manager``: The :class:`~octoprint.server.util.flask.AppSessionManager`
|
||||
* ``plugin_lifecycle_manager``: The :class:`~octoprint.server.LifecycleManager`
|
||||
* ``preemptive_cache``: The :class:`~octoprint.server.util.flask.PreemptiveCache`
|
||||
|
||||
If the factory returns anything but ``None``, it will be assigned to the global ``userManager`` instance.
|
||||
|
||||
If no of the registered factories return a user manager instance, the class referenced by the ``config.yaml``
|
||||
entry ``accessControl.userManager`` will be initialized if possible, otherwise a stock
|
||||
:class:`~octoprint.users.FilebasedUserManager` will be instantiated, linked to the default user storage
|
||||
file ``~/.octoprint/users.yaml``.
|
||||
|
||||
:param dict components: System components to use for user manager instance initialization
|
||||
:param SettingsManager settings: The global settings manager instance to fetch configuration values from if necessary
|
||||
:return: The ``userManager`` instance to use globally.
|
||||
:rtype: UserManager subclass or None
|
||||
|
||||
@@ -45,6 +45,8 @@ An overview of these properties follows.
|
||||
OctoPrint's application session manager, an instance of :class:`octoprint.server.util.flask.AppSessionManager`.
|
||||
``self._user_manager``
|
||||
OctoPrint's user manager, an instance of :class:`octoprint.users.UserManager`.
|
||||
``self._connectivity_checker``
|
||||
OctoPrint's connectivity checker, an instance of :class:`octoprint.util.ConnectivityChecker`.
|
||||
|
||||
.. seealso::
|
||||
|
||||
|
||||
@@ -299,6 +299,130 @@ on your view model, taking a list of all bound view models:
|
||||
});
|
||||
})
|
||||
|
||||
.. _sec-plugins-viewmodels-livecycle:
|
||||
|
||||
Lifecycle diagrams
|
||||
------------------
|
||||
|
||||
.. _sec-plugins-viewmodels-startup:
|
||||
|
||||
Web interface startup
|
||||
~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. mermaid::
|
||||
|
||||
sequenceDiagram
|
||||
participant Main
|
||||
participant onServerConnect
|
||||
participant fetchSettings
|
||||
participant bindViewModels
|
||||
participant DataUpdater
|
||||
participant LoginStateViewModel
|
||||
|
||||
Note right of DataUpdater: connectCallback = undefined
|
||||
|
||||
activate Main
|
||||
|
||||
Main->>+DataUpdater: connect
|
||||
Note right of DataUpdater: initialized = false
|
||||
DataUpdater-->>Main: ok
|
||||
deactivate Main
|
||||
DataUpdater->>DataUpdater: asynchronous connect to server...
|
||||
activate DataUpdater
|
||||
Note right of DataUpdater: store any callbacks instead of triggering (e.g. onServerConnect, fromHistoryData, fromCurrentData, ...)
|
||||
DataUpdater-X+Main: done
|
||||
deactivate DataUpdater
|
||||
deactivate DataUpdater
|
||||
|
||||
Main->>+DataUpdater: connectCallback = onServerConnect
|
||||
Note right of DataUpdater: connectCallback = onServerConnect
|
||||
DataUpdater-->>-Main: ok
|
||||
Main->>+onServerConnect: call
|
||||
onServerConnect->>+LoginStateViewModel: passiveLogin
|
||||
LoginStateViewModel-->>onServerConnect: ok
|
||||
onServerConnect-->>Main: ok
|
||||
deactivate onServerConnect
|
||||
deactivate Main
|
||||
|
||||
LoginStateViewModel->>+LoginStateViewModel: asynchronous passive login
|
||||
Note over Main,LoginStateViewModel: Session available!
|
||||
LoginStateViewModel-X+onServerConnect: done
|
||||
deactivate LoginStateViewModel
|
||||
deactivate LoginStateViewModel
|
||||
|
||||
onServerConnect->>+DataUpdater: initialized
|
||||
Note right of DataUpdater: initialized = true
|
||||
DataUpdater->DataUpdater: trigger stored callbacks
|
||||
DataUpdater-->>-onServerConnect: ok
|
||||
onServerConnect-X+Main: done
|
||||
deactivate onServerConnect
|
||||
|
||||
Main->>+fetchSettings: call
|
||||
Note right of fetchSettings: trigger onStartup
|
||||
|
||||
fetchSettings-->>Main: ok
|
||||
deactivate Main
|
||||
|
||||
fetchSettings->>+fetchSettings: asynchronous settings fetch
|
||||
fetchSettings->>+bindViewModels: call
|
||||
|
||||
loop for each view model
|
||||
bindViewModels->bindViewModels: trigger onBeforeBinding
|
||||
bindViewModels->bindViewModels: trigger onBoundTo
|
||||
bindViewModels->bindViewModels: trigger onAfterBinding
|
||||
end
|
||||
|
||||
bindViewModels->bindViewModels: trigger onAllBound
|
||||
opt User is logged in
|
||||
bindViewModels->>+LoginStateViewModel: onAllBound
|
||||
LoginStateViewModel->LoginStateViewModel: trigger onUserLoggedIn
|
||||
LoginStateViewModel-->>-bindViewModels: ok
|
||||
end
|
||||
bindViewModels->bindViewModels: trigger onStartupComplete
|
||||
bindViewModels-->>-fetchSettings: ok
|
||||
|
||||
deactivate fetchSettings
|
||||
deactivate fetchSettings
|
||||
|
||||
|
||||
.. _sec-plugins-viewmodels-reconnect:
|
||||
|
||||
Web interface reconnect
|
||||
~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. mermaid::
|
||||
|
||||
sequenceDiagram
|
||||
participant onServerConnect
|
||||
participant DataUpdater
|
||||
participant LoginStateViewModel
|
||||
|
||||
activate DataUpdater
|
||||
DataUpdater->>DataUpdater: call connectCallback
|
||||
DataUpdater->>+onServerConnect: call
|
||||
onServerConnect-->>DataUpdater: ok
|
||||
deactivate DataUpdater
|
||||
|
||||
onServerConnect->>+LoginStateViewModel: passiveLogin
|
||||
LoginStateViewModel-->>onServerConnect: ok
|
||||
deactivate onServerConnect
|
||||
LoginStateViewModel->>+LoginStateViewModel: asynchronous passive login
|
||||
Note over onServerConnect,LoginStateViewModel: Session available!
|
||||
opt User is logged in
|
||||
LoginStateViewModel->LoginStateViewModel: trigger onUserLoggedIn
|
||||
end
|
||||
|
||||
activate onServerConnect
|
||||
LoginStateViewModel-XonServerConnect: done
|
||||
deactivate LoginStateViewModel
|
||||
deactivate LoginStateViewModel
|
||||
|
||||
onServerConnect->>+DataUpdater: initialized
|
||||
DataUpdater->DataUpdater: trigger stored callbacks
|
||||
DataUpdater-->>onServerConnect: ok
|
||||
deactivate DataUpdater
|
||||
deactivate onServerConnect
|
||||
|
||||
.. seealso::
|
||||
|
||||
`OctoPrint's core viewmodels <https://github.com/foosel/OctoPrint/tree/devel/src/octoprint/static/js/app/viewmodels>`_
|
||||
|
||||
@@ -7,41 +7,99 @@ __copyright__ = "Copyright (C) 2015 Gina Häußge - Released under terms of the
|
||||
|
||||
|
||||
import codecs
|
||||
import urllib2
|
||||
import requests
|
||||
from contextlib import closing
|
||||
|
||||
from sphinx.directives import LiteralInclude, dedent_lines
|
||||
from sphinx.directives.code import LiteralIncludeReader, LiteralInclude, dedent_lines, \
|
||||
nodes, set_source_info, parselinenos, logger, container_wrapper
|
||||
|
||||
if False:
|
||||
# For type annotation
|
||||
from typing import Any, List # NOQA
|
||||
|
||||
cache = dict()
|
||||
|
||||
class OnlineIncludeReader(LiteralIncludeReader):
|
||||
|
||||
def read_file(self, filename, location=None):
|
||||
# type: (unicode, Any) -> List[unicode]
|
||||
|
||||
global cache
|
||||
try:
|
||||
if filename in cache:
|
||||
lines = cache[filename]
|
||||
else:
|
||||
with closing(requests.get(filename, stream=True)) as r:
|
||||
r.encoding = self.encoding
|
||||
lines = r.text.splitlines(True)
|
||||
cache[filename] = lines
|
||||
|
||||
if 'tab-width' in self.options:
|
||||
lines = [line.expandtabs(self.options['tab-width']) for line in lines]
|
||||
|
||||
return lines
|
||||
except (IOError, OSError):
|
||||
raise IOError(_('Include file %r not found or reading it failed') % filename)
|
||||
except UnicodeError:
|
||||
raise UnicodeError(_('Encoding %r used for reading included file %r seems to '
|
||||
'be wrong, try giving an :encoding: option') %
|
||||
(self.encoding, filename))
|
||||
|
||||
|
||||
class OnlineIncludeDirective(LiteralInclude):
|
||||
|
||||
def read_with_encoding(self, filename, document, codec_info, encoding):
|
||||
global cache
|
||||
def run(self):
|
||||
# type: () -> List[nodes.Node]
|
||||
document = self.state.document
|
||||
if not document.settings.file_insertion_enabled:
|
||||
return [document.reporter.warning('File insertion disabled',
|
||||
line=self.lineno)]
|
||||
env = document.settings.env
|
||||
|
||||
# convert options['diff'] to absolute path
|
||||
if 'diff' in self.options:
|
||||
_, path = env.relfn2path(self.options['diff'])
|
||||
self.options['diff'] = path
|
||||
|
||||
f = None
|
||||
try:
|
||||
if not self.arguments[0] in cache:
|
||||
f = codecs.StreamReaderWriter(urllib2.urlopen(self.arguments[0]), codec_info[2],
|
||||
codec_info[3], 'strict')
|
||||
lines = f.readlines()
|
||||
cache[self.arguments[0]] = lines
|
||||
else:
|
||||
lines = cache[self.arguments[0]]
|
||||
location = self.state_machine.get_source_and_line(self.lineno)
|
||||
url = self.arguments[0]
|
||||
|
||||
reader = OnlineIncludeReader(url, self.options, env.config)
|
||||
text, lines = reader.read(location=location)
|
||||
|
||||
retnode = nodes.literal_block(text, text, source=url)
|
||||
set_source_info(self, retnode)
|
||||
if self.options.get('diff'): # if diff is set, set udiff
|
||||
retnode['language'] = 'udiff'
|
||||
elif 'language' in self.options:
|
||||
retnode['language'] = self.options['language']
|
||||
retnode['linenos'] = ('linenos' in self.options or
|
||||
'lineno-start' in self.options or
|
||||
'lineno-match' in self.options)
|
||||
retnode['classes'] += self.options.get('class', [])
|
||||
extra_args = retnode['highlight_args'] = {}
|
||||
if 'emphasize-lines' in self.options:
|
||||
hl_lines = parselinenos(self.options['emphasize-lines'], lines)
|
||||
if any(i >= lines for i in hl_lines):
|
||||
logger.warning('line number spec is out of range(1-%d): %r' %
|
||||
(lines, self.options['emphasize-lines']),
|
||||
location=location)
|
||||
extra_args['hl_lines'] = [x + 1 for x in hl_lines if x < lines]
|
||||
extra_args['linenostart'] = reader.lineno_start
|
||||
|
||||
if 'caption' in self.options:
|
||||
caption = self.options['caption'] or self.arguments[0]
|
||||
retnode = container_wrapper(self, retnode, caption)
|
||||
|
||||
# retnode will be note_implicit_target that is linked from caption and numref.
|
||||
# when options['name'] is provided, it should be primary ID.
|
||||
self.add_name(retnode)
|
||||
|
||||
return [retnode]
|
||||
except Exception as exc:
|
||||
return [document.reporter.warning(str(exc), line=self.lineno)]
|
||||
|
||||
lines = dedent_lines(lines, self.options.get('dedent'))
|
||||
return lines
|
||||
except (IOError, OSError, urllib2.URLError):
|
||||
return [document.reporter.warning(
|
||||
'Include file %r not found or reading it failed' % self.arguments[0],
|
||||
line=self.lineno)]
|
||||
except UnicodeError:
|
||||
return [document.reporter.warning(
|
||||
'Encoding %r used for reading included file %r seems to '
|
||||
'be wrong, try giving an :encoding: option' %
|
||||
(encoding, self.arguments[0]))]
|
||||
finally:
|
||||
if f is not None:
|
||||
f.close()
|
||||
|
||||
def visit_onlineinclude(translator, node):
|
||||
translator.visit_literal_block(node)
|
||||
@@ -53,4 +111,4 @@ def setup(app):
|
||||
app.add_directive("onlineinclude", OnlineIncludeDirective)
|
||||
|
||||
handler = (visit_onlineinclude, depart_onlineinclude)
|
||||
app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler)
|
||||
app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler)
|
||||
@@ -23,7 +23,7 @@ INSTALL_REQUIRES = [
|
||||
# to some voodoo needed to get large streamed uploads and downloads
|
||||
# to work that is probably not completely straightforward and therefore
|
||||
# something for post-1.3.0-stable release
|
||||
"sockjs-tornado>=1.0.2,<1.1",
|
||||
"sockjs-tornado>=1.0.3,<1.1",
|
||||
"PyYAML>=3.10,<3.11",
|
||||
"Flask-Login>=0.2.2,<0.3",
|
||||
"Flask-Principal>=0.3.5,<0.4",
|
||||
@@ -48,7 +48,9 @@ INSTALL_REQUIRES = [
|
||||
"future>=0.15,<0.16",
|
||||
"scandir>=1.3,<1.4",
|
||||
"websocket-client>=0.40,<0.41",
|
||||
"python-dateutil>=2.6,<2.7"
|
||||
"python-dateutil>=2.6,<2.7",
|
||||
"wrapt>=1.10.10,<1.11",
|
||||
"futures>=3.1.1,<3.2"
|
||||
]
|
||||
|
||||
if sys.platform == "darwin":
|
||||
@@ -64,9 +66,10 @@ EXTRA_REQUIRES = dict(
|
||||
"ddt",
|
||||
|
||||
# Documentation dependencies
|
||||
"sphinx>=1.3,<1.4",
|
||||
"sphinx>=1.6,<1.7",
|
||||
"sphinxcontrib-httpdomain",
|
||||
"sphinx_rtd_theme",
|
||||
"sphinxcontrib-mermaid",
|
||||
"sphinx_bootstrap_theme",
|
||||
|
||||
# PyPi upload related
|
||||
"pypandoc"
|
||||
|
||||
@@ -194,7 +194,8 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
|
||||
"level": "DEBUG",
|
||||
"formatter": "serial",
|
||||
"backupCount": 3,
|
||||
"filename": os.path.join(settings.getBaseFolder("logs"), "serial.log")
|
||||
"filename": os.path.join(settings.getBaseFolder("logs"), "serial.log"),
|
||||
"delay": True
|
||||
}
|
||||
},
|
||||
"loggers": {
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/usr/bin/env python2
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
if __name__ == "__main__":
|
||||
import octoprint
|
||||
octoprint.main()
|
||||
@@ -135,9 +135,10 @@ from .plugins import plugin_commands
|
||||
from .dev import dev_commands
|
||||
from .client import client_commands
|
||||
from .config import config_commands
|
||||
from .analysis import analysis_commands
|
||||
|
||||
@click.group(name="octoprint", invoke_without_command=True, cls=click.CommandCollection,
|
||||
sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands])
|
||||
sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands, analysis_commands])
|
||||
@standard_options()
|
||||
@legacy_options
|
||||
@click.version_option(version=octoprint.__version__, allow_from_autoenv=False)
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import click
|
||||
|
||||
#~~ "octoprint util" commands
|
||||
|
||||
@click.group()
|
||||
def analysis_commands():
|
||||
pass
|
||||
|
||||
@analysis_commands.group(name="analysis")
|
||||
def util():
|
||||
"""Analysis tools."""
|
||||
pass
|
||||
|
||||
|
||||
@util.command(name="gcode")
|
||||
@click.option("--throttle", "throttle", type=float, default=None)
|
||||
@click.option("--throttle-lines", "throttle_lines", type=int, default=None)
|
||||
@click.option("--speed-x", "speedx", type=float, default=6000)
|
||||
@click.option("--speed-y", "speedy", type=float, default=6000)
|
||||
@click.option("--speed-z", "speedz", type=float, default=300)
|
||||
@click.option("--offset", "offset", type=(float, float), multiple=True)
|
||||
@click.option("--max-t", "maxt", type=int, default=10)
|
||||
@click.option("--g90-extruder", "g90_extruder", is_flag=True)
|
||||
@click.option("--progress", "progress", is_flag=True)
|
||||
@click.argument("path", type=click.Path())
|
||||
def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle_lines, g90_extruder, progress):
|
||||
"""Runs a GCODE file analysis."""
|
||||
|
||||
import time
|
||||
import yaml
|
||||
from octoprint.util.gcodeInterpreter import gcode
|
||||
|
||||
throttle_callback = None
|
||||
if throttle:
|
||||
def throttle_callback(filePos, readBytes):
|
||||
if filePos % throttle_lines == 0:
|
||||
# only apply throttle every $throttle_lines lines
|
||||
time.sleep(throttle)
|
||||
|
||||
offsets = offset
|
||||
if offsets is None:
|
||||
offsets = []
|
||||
elif isinstance(offset, tuple):
|
||||
offsets = list(offsets)
|
||||
offsets = [(0, 0)] + offsets
|
||||
if len(offsets) < maxt:
|
||||
offsets += [(0, 0)] * (maxt - len(offsets))
|
||||
|
||||
start_time = time.time()
|
||||
|
||||
progress_callback = None
|
||||
if progress:
|
||||
def progress_callback(percentage):
|
||||
click.echo("PROGRESS:{}".format(percentage))
|
||||
interpreter = gcode(progress_callback=progress_callback)
|
||||
|
||||
interpreter.load(path,
|
||||
speedx=speedx,
|
||||
speedy=speedy,
|
||||
offsets=offsets,
|
||||
throttle=throttle_callback,
|
||||
max_extruders=maxt,
|
||||
g90_extruder=g90_extruder)
|
||||
|
||||
click.echo("DONE:{}s".format(time.time() - start_time))
|
||||
click.echo("RESULTS:")
|
||||
click.echo(yaml.safe_dump(interpreter.get_result(), default_flow_style=False, indent=" ", allow_unicode=True))
|
||||
+47
-24
@@ -9,7 +9,7 @@ import json
|
||||
|
||||
import octoprint_client
|
||||
|
||||
from octoprint.cli import get_ctx_obj_option
|
||||
from octoprint.cli import get_ctx_obj_option, bulk_options
|
||||
from octoprint import init_settings, FatalStartupError
|
||||
|
||||
|
||||
@@ -23,43 +23,66 @@ class JsonStringParamType(click.ParamType):
|
||||
self.fail("%s is not a valid json string" % value, param, ctx)
|
||||
|
||||
|
||||
def create_client(settings=None, apikey=None, host=None, port=None, httpuser=None, httppass=None, https=False, prefix=None):
|
||||
assert(host is not None or settings is not None)
|
||||
assert(port is not None or settings is not None)
|
||||
assert(apikey is not None or settings is not None)
|
||||
|
||||
if not host:
|
||||
host = settings.get(["server", "host"])
|
||||
host = host if host != "0.0.0.0" else "127.0.0.1"
|
||||
if not port:
|
||||
port = settings.getInt(["server", "port"])
|
||||
|
||||
if not apikey:
|
||||
apikey = settings.get(["api", "key"])
|
||||
|
||||
baseurl = octoprint_client.build_base_url(https=https,
|
||||
httpuser=httpuser,
|
||||
httppass=httppass,
|
||||
host=host,
|
||||
port=port,
|
||||
prefix=prefix)
|
||||
|
||||
return octoprint_client.Client(baseurl, apikey)
|
||||
|
||||
|
||||
client_options = bulk_options([
|
||||
click.option("--apikey", "-a", type=click.STRING),
|
||||
click.option("--host", "-h", type=click.STRING),
|
||||
click.option("--port", "-p", type=click.INT),
|
||||
click.option("--httpuser", type=click.STRING),
|
||||
click.option("--httppass", type=click.STRING),
|
||||
click.option("--https", is_flag=True),
|
||||
click.option("--prefix", type=click.STRING)
|
||||
])
|
||||
"""Common options to configure an API client."""
|
||||
|
||||
|
||||
@click.group()
|
||||
def client_commands():
|
||||
pass
|
||||
|
||||
|
||||
@client_commands.group("client", context_settings=dict(ignore_unknown_options=True))
|
||||
@click.option("--apikey", "-a", type=click.STRING)
|
||||
@click.option("--host", "-h", type=click.STRING)
|
||||
@click.option("--port", "-p", type=click.INT)
|
||||
@click.option("--httpuser", type=click.STRING)
|
||||
@click.option("--httppass", type=click.STRING)
|
||||
@click.option("--https", is_flag=True)
|
||||
@click.option("--prefix", type=click.STRING)
|
||||
@client_options
|
||||
@click.pass_context
|
||||
def client(ctx, apikey, host, port, httpuser, httppass, https, prefix):
|
||||
"""Basic API client."""
|
||||
try:
|
||||
settings = None
|
||||
if not host or not port or not apikey:
|
||||
settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
|
||||
|
||||
if not host:
|
||||
host = settings.get(["server", "host"])
|
||||
host = host if host != "0.0.0.0" else "127.0.0.1"
|
||||
if not port:
|
||||
port = settings.getInt(["server", "port"])
|
||||
ctx.obj.client = create_client(settings=settings,
|
||||
apikey=apikey,
|
||||
host=host,
|
||||
port=port,
|
||||
httpuser=httpuser,
|
||||
httppass=httppass,
|
||||
https=https,
|
||||
prefix=prefix)
|
||||
|
||||
if not apikey:
|
||||
apikey = settings.get(["api", "key"])
|
||||
|
||||
baseurl = octoprint_client.build_base_url(https=https,
|
||||
httpuser=httpuser,
|
||||
httppass=httppass,
|
||||
host=host,
|
||||
port=port,
|
||||
prefix=prefix)
|
||||
|
||||
ctx.obj.client = octoprint_client.Client(baseurl, apikey)
|
||||
except FatalStartupError as e:
|
||||
click.echo(e.message, err=True)
|
||||
click.echo("There was a fatal error initializing the client.", err=True)
|
||||
|
||||
@@ -8,6 +8,8 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
|
||||
|
||||
import click
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
class OctoPrintDevelCommands(click.MultiCommand):
|
||||
"""
|
||||
Custom `click.MultiCommand <http://click.pocoo.org/5/api/#click.MultiCommand>`_
|
||||
|
||||
@@ -60,6 +60,8 @@ class OctoPrintPluginCommands(click.MultiCommand):
|
||||
# fetch registered hooks
|
||||
self.hooks = self.plugin_manager.get_hooks("octoprint.cli.commands")
|
||||
|
||||
logging.basicConfig(level=logging.DEBUG if ctx.obj.verbosity > 0 else logging.WARN)
|
||||
|
||||
self._initialized = True
|
||||
|
||||
def list_commands(self, ctx):
|
||||
@@ -88,14 +90,14 @@ class OctoPrintPluginCommands(click.MultiCommand):
|
||||
continue
|
||||
result[name + self.sep + command.name] = command
|
||||
except:
|
||||
self._logger.exception("Error while retrieving cli commants for plugin {}".format(name))
|
||||
self._logger.exception("Error while retrieving cli commands for plugin {}".format(name))
|
||||
|
||||
return result
|
||||
|
||||
@click.group()
|
||||
@pass_octoprint_ctx
|
||||
def plugin_commands(obj):
|
||||
logging.basicConfig(level=logging.DEBUG if obj.verbosity > 0 else logging.WARN)
|
||||
pass
|
||||
|
||||
@plugin_commands.group(name="plugins", cls=OctoPrintPluginCommands)
|
||||
def plugins():
|
||||
|
||||
+36
-8
@@ -27,9 +27,10 @@ def all_events():
|
||||
|
||||
|
||||
class Events(object):
|
||||
# application startup
|
||||
# server
|
||||
STARTUP = "Startup"
|
||||
SHUTDOWN = "Shutdown"
|
||||
CONNECTIVITY_CHANGED = "ConnectivityChanged"
|
||||
|
||||
# connect/disconnect to printer
|
||||
CONNECTING = "Connecting"
|
||||
@@ -53,10 +54,10 @@ class Events(object):
|
||||
METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished"
|
||||
METADATA_STATISTICS_UPDATED = "MetadataStatisticsUpdated"
|
||||
|
||||
FILE_ADDED = "FileAdded",
|
||||
FILE_REMOVED = "FileRemoved",
|
||||
FOLDER_ADDED = "FolderAdded",
|
||||
FOLDER_REMOVED = "FolderRemoved",
|
||||
FILE_ADDED = "FileAdded"
|
||||
FILE_REMOVED = "FileRemoved"
|
||||
FOLDER_ADDED = "FolderAdded"
|
||||
FOLDER_REMOVED = "FolderRemoved"
|
||||
|
||||
# SD Upload
|
||||
TRANSFER_STARTED = "TransferStarted"
|
||||
@@ -84,6 +85,7 @@ class Events(object):
|
||||
EJECT = "Eject"
|
||||
E_STOP = "EStop"
|
||||
POSITION_UPDATE = "PositionUpdate"
|
||||
TOOL_CHANGE = "ToolChange"
|
||||
REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived"
|
||||
|
||||
# Timelapse
|
||||
@@ -130,9 +132,11 @@ class EventManager(object):
|
||||
self._registeredListeners = collections.defaultdict(list)
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._startup_signaled = False
|
||||
self._shutdown_signaled = False
|
||||
|
||||
self._queue = queue.Queue()
|
||||
self._held_back = queue.Queue()
|
||||
|
||||
self._worker = threading.Thread(target=self._work)
|
||||
self._worker.daemon = True
|
||||
@@ -159,7 +163,8 @@ class EventManager(object):
|
||||
|
||||
octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin,
|
||||
"on_event",
|
||||
args=(event, payload))
|
||||
args=(event, payload),
|
||||
initialized=True)
|
||||
self._logger.info("Event loop shut down")
|
||||
except:
|
||||
self._logger.exception("Ooops, the event bus worker loop crashed")
|
||||
@@ -175,7 +180,30 @@ class EventManager(object):
|
||||
payload being a payload object specific to the event.
|
||||
"""
|
||||
|
||||
self._queue.put((event, payload))
|
||||
send_held_back = False
|
||||
if event == Events.STARTUP:
|
||||
self._logger.info("Processing startup event, this is our first event")
|
||||
self._startup_signaled = True
|
||||
send_held_back = True
|
||||
|
||||
self._enqueue(event, payload)
|
||||
|
||||
if send_held_back:
|
||||
self._logger.info("Adding {} events to queue that "
|
||||
"were held back before startup event".format(self._held_back.qsize()))
|
||||
while True:
|
||||
try:
|
||||
self._queue.put(self._held_back.get(block=False))
|
||||
except queue.Empty:
|
||||
break
|
||||
|
||||
def _enqueue(self, event, payload):
|
||||
if self._startup_signaled:
|
||||
q = self._queue
|
||||
else:
|
||||
q = self._held_back
|
||||
|
||||
q.put((event, payload))
|
||||
|
||||
if event == Events.UPDATED_FILES and "type" in payload and payload["type"] == "printables":
|
||||
# when sending UpdatedFiles with type "printables", also send another event with deprecated type "gcode"
|
||||
@@ -183,7 +211,7 @@ class EventManager(object):
|
||||
import copy
|
||||
legacy_payload = copy.deepcopy(payload)
|
||||
legacy_payload["type"] = "gcode"
|
||||
self._queue.put((event, legacy_payload))
|
||||
q.put((event, legacy_payload))
|
||||
|
||||
def subscribe(self, event, callback):
|
||||
"""
|
||||
|
||||
@@ -20,6 +20,8 @@ from .util import AbstractFileWrapper, StreamWrapper, DiskFileWrapper
|
||||
|
||||
from collections import namedtuple
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
ContentTypeMapping = namedtuple("ContentTypeMapping", "extensions, content_type")
|
||||
ContentTypeDetector = namedtuple("ContentTypeDetector", "extensions, detector")
|
||||
|
||||
@@ -178,9 +180,12 @@ class FileManager(object):
|
||||
import octoprint.settings
|
||||
self._recovery_file = os.path.join(octoprint.settings.settings().getBaseFolder("data"), "print_recovery_data.yaml")
|
||||
|
||||
def initialize(self):
|
||||
def initialize(self, process_backlog=False):
|
||||
self.reload_plugins()
|
||||
if process_backlog:
|
||||
self.process_backlog()
|
||||
|
||||
def process_backlog(self):
|
||||
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():
|
||||
@@ -251,6 +256,26 @@ class FileManager(object):
|
||||
def default_slicer(self):
|
||||
return self._slicing_manager.default_slicer
|
||||
|
||||
def analyse(self, destination, path, printer_profile_id=None):
|
||||
if not self.file_exists(destination, path):
|
||||
return
|
||||
|
||||
if printer_profile_id is None:
|
||||
printer_profile = self._printer_profile_manager.get_current_or_default()
|
||||
else:
|
||||
printer_profile = self._printer_profile_manager.get(printer_profile_id)
|
||||
if printer_profile is None:
|
||||
printer_profile = self._printer_profile_manager.get_current_or_default()
|
||||
|
||||
queue_entry = self._analysis_queue_entry(destination, path)
|
||||
self._analysis_queue.dequeue(queue_entry)
|
||||
|
||||
queue_entry = self._analysis_queue_entry(destination, path, printer_profile=printer_profile)
|
||||
if queue_entry:
|
||||
return self._analysis_queue.enqueue(queue_entry, high_priority=True)
|
||||
|
||||
return False
|
||||
|
||||
def slice(self, slicer_name, source_location, source_path, dest_location, dest_path,
|
||||
position=None, profile=None, printer_profile_id=None, overrides=None, callback=None, callback_args=None):
|
||||
absolute_source_path = self.path_on_disk(source_location, source_path)
|
||||
|
||||
@@ -19,8 +19,6 @@ import time
|
||||
from octoprint.events import Events, eventManager
|
||||
from octoprint.settings import settings
|
||||
|
||||
import octoprint.util.gcodeInterpreter as gcodeInterpreter
|
||||
|
||||
|
||||
class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile")):
|
||||
"""
|
||||
@@ -305,39 +303,95 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
* The extruded volume in cm³
|
||||
"""
|
||||
|
||||
def _do_analysis(self, high_priority=False):
|
||||
try:
|
||||
throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
|
||||
throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"])
|
||||
if throttle > 0:
|
||||
def throttle_callback(filePos, readBytes):
|
||||
if filePos % throttle_lines == 0:
|
||||
# only apply throttle every 100 lines
|
||||
time.sleep(throttle)
|
||||
else:
|
||||
throttle_callback = None
|
||||
def __init__(self, finished_callback):
|
||||
AbstractAnalysisQueue.__init__(self, finished_callback)
|
||||
|
||||
self._gcode = gcodeInterpreter.gcode()
|
||||
self._gcode.load(self._current.absolute_path, self._current.printer_profile, throttle=throttle_callback)
|
||||
self._aborted = False
|
||||
self._reenqueue = False
|
||||
|
||||
def _do_analysis(self, high_priority=False):
|
||||
import sarge
|
||||
import sys
|
||||
import yaml
|
||||
|
||||
try:
|
||||
throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority \
|
||||
else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
|
||||
throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"])
|
||||
max_extruders = settings().getInt(["gcodeAnalysis", "maxExtruders"])
|
||||
g90_extruder = settings().getBoolean(["feature", "g90InfluencesExtruder"])
|
||||
speedx = self._current.printer_profile["axes"]["x"]["speed"]
|
||||
speedy = self._current.printer_profile["axes"]["y"]["speed"]
|
||||
offsets = self._current.printer_profile["extruder"]["offsets"]
|
||||
|
||||
command = [sys.executable, "-m", "octoprint", "analysis", "gcode",
|
||||
"--speed-x={}".format(speedx), "--speed-y={}".format(speedy),
|
||||
"--max-t={}".format(max_extruders), "--throttle={}".format(throttle),
|
||||
"--throttle-lines={}".format(throttle_lines)]
|
||||
for offset in offsets[1:]:
|
||||
command += ["--offset", str(offset[0]), str(offset[1])]
|
||||
if g90_extruder:
|
||||
command += ["--g90-extruder"]
|
||||
command.append(self._current.absolute_path)
|
||||
|
||||
self._logger.info("Invoking analysis command: {}".format(" ".join(command)))
|
||||
|
||||
self._aborted = False
|
||||
p = sarge.run(command, async=True, stdout=sarge.Capture())
|
||||
|
||||
while len(p.commands) == 0:
|
||||
# somewhat ugly... we can't use wait_events because
|
||||
# the events might not be all set if an exception
|
||||
# by sarge is triggered within the async process
|
||||
# thread
|
||||
time.sleep(0.01)
|
||||
|
||||
# by now we should have a command, let's wait for its
|
||||
# process to have been prepared
|
||||
p.commands[0].process_ready.wait()
|
||||
|
||||
if not p.commands[0].process:
|
||||
# the process might have been set to None in case of any exception
|
||||
raise RuntimeError(u"Error while trying to run command {}".format(" ".join(command)))
|
||||
|
||||
try:
|
||||
# let's wait for stuff to finish
|
||||
while p.returncode is None:
|
||||
if self._aborted:
|
||||
# oh, we shall abort, let's do so!
|
||||
p.commands[0].terminate()
|
||||
raise AnalysisAborted(reenqueue=self._reenqueue)
|
||||
|
||||
# else continue
|
||||
p.commands[0].poll()
|
||||
finally:
|
||||
p.close()
|
||||
|
||||
output = p.stdout.text
|
||||
self._logger.debug("Got output: {!r}".format(output))
|
||||
|
||||
if not "RESULTS:" in output:
|
||||
raise RuntimeError("No analysis result found")
|
||||
|
||||
_, output = output.split("RESULTS:")
|
||||
analysis = yaml.safe_load(output)
|
||||
|
||||
result = dict()
|
||||
result["printingArea"] = self._gcode.printing_area
|
||||
result["dimensions"] = self._gcode.dimensions
|
||||
if self._gcode.totalMoveTimeMinute:
|
||||
result["estimatedPrintTime"] = self._gcode.totalMoveTimeMinute * 60
|
||||
if self._gcode.extrusionAmount:
|
||||
result["printingArea"] = analysis["printing_area"]
|
||||
result["dimensions"] = analysis["dimensions"]
|
||||
if analysis["total_time"]:
|
||||
result["estimatedPrintTime"] = analysis["total_time"] * 60
|
||||
if analysis["extrusion_length"]:
|
||||
result["filament"] = dict()
|
||||
for i in range(len(self._gcode.extrusionAmount)):
|
||||
for i in range(len(analysis["extrusion_length"])):
|
||||
result["filament"]["tool%d" % i] = {
|
||||
"length": self._gcode.extrusionAmount[i],
|
||||
"volume": self._gcode.extrusionVolume[i]
|
||||
"length": analysis["extrusion_length"][i],
|
||||
"volume": analysis["extrusion_volume"][i]
|
||||
}
|
||||
return result
|
||||
except gcodeInterpreter.AnalysisAborted as ex:
|
||||
raise AnalysisAborted(reenqueue=ex.reenqueue)
|
||||
finally:
|
||||
self._gcode = None
|
||||
|
||||
def _do_abort(self, reenqueue=True):
|
||||
if self._gcode:
|
||||
self._gcode.abort(reenqueue=reenqueue)
|
||||
self._aborted = True
|
||||
self._reenqueue = reenqueue
|
||||
@@ -20,6 +20,8 @@ from octoprint.util import atomic_write
|
||||
from contextlib import contextmanager
|
||||
from copy import deepcopy
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
import octoprint.filemanager
|
||||
|
||||
from octoprint.util import is_hidden_path
|
||||
|
||||
@@ -135,3 +135,16 @@ def get_divider_line(c, message=None, length=78, indent=3):
|
||||
return c * indent + " " + message + " " + c * (length - indent - 2 - len(message))
|
||||
else:
|
||||
return c * indent + " " + message
|
||||
|
||||
|
||||
def prefix_multilines(text, prefix=": "):
|
||||
lines = text.splitlines()
|
||||
if not lines:
|
||||
return ""
|
||||
|
||||
if len(lines) == 1:
|
||||
return lines[0]
|
||||
|
||||
return lines[0] + "\n" + "\n".join(map(lambda line: prefix + line,
|
||||
lines[1:]))
|
||||
|
||||
@@ -104,7 +104,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
|
||||
UiPlugin]
|
||||
|
||||
if plugin_restart_needing_hooks is None:
|
||||
plugin_restart_needing_hooks = ["octoprint.server.http"]
|
||||
plugin_restart_needing_hooks = ["octoprint.server.http.*",
|
||||
"octoprint.printer.factory"]
|
||||
|
||||
if plugin_obsolete_hooks is None:
|
||||
plugin_obsolete_hooks = ["octoprint.comm.protocol.gcode"]
|
||||
@@ -176,7 +177,7 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None):
|
||||
return plugin_settings(plugin_key, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings)
|
||||
|
||||
|
||||
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None):
|
||||
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None, initialized=True):
|
||||
"""
|
||||
Helper method to invoke the indicated ``method`` on all registered plugin implementations implementing the
|
||||
indicated ``types``. Allows providing method arguments and registering callbacks to call in case of success
|
||||
@@ -212,6 +213,8 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
|
||||
error_callback (function): A callback to invoke after the call of an implementation resulted in an exception.
|
||||
Will be called with the three arguments ``name``, ``plugin`` and ``exc``. ``name`` will be the plugin
|
||||
identifier, ``plugin`` the plugin implementation instance itself and ``exc`` the caught exception.
|
||||
initialized (boolean): Whether the plugin needs to be initialized (True) or not (False). Initialization status
|
||||
is determined be presence of injected ``_identifier`` property.
|
||||
|
||||
"""
|
||||
|
||||
@@ -224,6 +227,9 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
|
||||
|
||||
plugins = plugin_manager().get_implementations(*types, sorting_context=sorting_context)
|
||||
for plugin in plugins:
|
||||
if initialized and not hasattr(plugin, "_identifier"):
|
||||
continue
|
||||
|
||||
if hasattr(plugin, method):
|
||||
try:
|
||||
result = getattr(plugin, method)(*args, **kwargs)
|
||||
@@ -263,13 +269,17 @@ class PluginSettings(object):
|
||||
:returns: The retrieved settings value.
|
||||
:rtype: object
|
||||
|
||||
.. method:: get_int(path)
|
||||
.. method:: get_int(path, min=None, max=None)
|
||||
|
||||
Like :func:`get` but tries to convert the retrieved value to ``int``.
|
||||
Like :func:`get` but tries to convert the retrieved value to ``int``. If ``min`` is provided and the retrieved
|
||||
value is less than it, it will be returned instead of the value. Likewise for ``max`` - it will be returned if
|
||||
the value is greater than it.
|
||||
|
||||
.. method:: get_float(path)
|
||||
.. method:: get_float(path, min=None, max=None)
|
||||
|
||||
Like :func:`get` but tries to convert the retrieved value to ``float``.
|
||||
Like :func:`get` but tries to convert the retrieved value to ``float``. If ``min`` is provided and the retrieved
|
||||
value is less than it, it will be returned instead of the value. Likewise for ``max`` - it will be returned if
|
||||
the value is greater than it.
|
||||
|
||||
.. method:: get_boolean(path)
|
||||
|
||||
@@ -285,13 +295,19 @@ class PluginSettings(object):
|
||||
:param boolean force: If set to True, the modified configuration will even be written back to disk if
|
||||
the value didn't change.
|
||||
|
||||
.. method:: set_int(path, value, force=False)
|
||||
.. method:: set_int(path, value, force=False, min=None, max=None)
|
||||
|
||||
Like :func:`set` but ensures the value is an ``int`` through attempted conversion before setting it.
|
||||
If ``min`` and/or ``max`` are provided, it will also be ensured that the value is greater than or equal
|
||||
to ``min`` and less than or equal to ``max``. If that is not the case, the limit value (``min`` if less than
|
||||
that, ``max`` if greater than that) will be set instead.
|
||||
|
||||
.. method:: set_float(path, value, force=False)
|
||||
.. method:: set_float(path, value, force=False, min=None, max=None)
|
||||
|
||||
Like :func:`set` but ensures the value is an ``float`` through attempted conversion before setting it.
|
||||
If ``min`` and/or ``max`` are provided, it will also be ensured that the value is greater than or equal
|
||||
to ``min`` and less than or equal to ``max``. If that is not the case, the limit value (``min`` if less than
|
||||
that, ``max`` if greater than that) will be set instead.
|
||||
|
||||
.. method:: set_boolean(path, value, force=False)
|
||||
|
||||
|
||||
@@ -31,6 +31,7 @@ import os
|
||||
import imp
|
||||
from collections import defaultdict, namedtuple, OrderedDict
|
||||
import logging
|
||||
import fnmatch
|
||||
|
||||
import pkg_resources
|
||||
import pkginfo
|
||||
@@ -946,45 +947,107 @@ class PluginManager(object):
|
||||
return plugin.needs_restart or self.has_restart_needing_implementation(plugin) or self.has_restart_needing_hooks(plugin)
|
||||
|
||||
def has_restart_needing_implementation(self, plugin):
|
||||
if not plugin.implementation:
|
||||
return False
|
||||
|
||||
return isinstance(plugin.implementation, RestartNeedingPlugin)
|
||||
return self.has_any_of_mixins(plugin, RestartNeedingPlugin)
|
||||
|
||||
def has_restart_needing_hooks(self, plugin):
|
||||
if not plugin.hooks:
|
||||
return False
|
||||
|
||||
hooks = plugin.hooks.keys()
|
||||
for hook in hooks:
|
||||
if self.is_restart_needing_hook(hook):
|
||||
return True
|
||||
return False
|
||||
return self.has_any_of_hooks(plugin, self.plugin_restart_needing_hooks)
|
||||
|
||||
def has_obsolete_hooks(self, plugin):
|
||||
if not plugin.hooks:
|
||||
return False
|
||||
|
||||
hooks = plugin.hooks.keys()
|
||||
for hook in hooks:
|
||||
if self.is_obsolete_hook(hook):
|
||||
return True
|
||||
return False
|
||||
return self.has_any_of_hooks(plugin, self.plugin_obsolete_hooks)
|
||||
|
||||
def is_restart_needing_hook(self, hook):
|
||||
if self.plugin_restart_needing_hooks is None:
|
||||
return False
|
||||
|
||||
for h in self.plugin_restart_needing_hooks:
|
||||
if hook.startswith(h):
|
||||
return True
|
||||
|
||||
return False
|
||||
return self.hook_matches_hooks(hook, self.plugin_restart_needing_hooks)
|
||||
|
||||
def is_obsolete_hook(self, hook):
|
||||
if self.plugin_obsolete_hooks is None:
|
||||
return self.hook_matches_hooks(hook, self.plugin_obsolete_hooks)
|
||||
|
||||
@staticmethod
|
||||
def has_any_of_hooks(plugin, *hooks):
|
||||
"""
|
||||
Tests if the ``plugin`` contains any of the provided ``hooks``.
|
||||
|
||||
Uses :func:`octoprint.plugin.core.PluginManager.hook_matches_hooks`.
|
||||
|
||||
Args:
|
||||
plugin: plugin to test hooks for
|
||||
*hooks: hooks to test against
|
||||
|
||||
Returns:
|
||||
(bool): True if any of the plugin's hooks match the provided hooks,
|
||||
False otherwise.
|
||||
"""
|
||||
|
||||
if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)):
|
||||
hooks = hooks[0]
|
||||
|
||||
hooks = filter(lambda hook: hook is not None, hooks)
|
||||
if not hooks:
|
||||
return False
|
||||
return hook in self.plugin_obsolete_hooks
|
||||
if not plugin or not plugin.hooks:
|
||||
return False
|
||||
|
||||
plugin_hooks = plugin.hooks.keys()
|
||||
|
||||
return any(map(lambda hook: PluginManager.hook_matches_hooks(hook, *hooks),
|
||||
plugin_hooks))
|
||||
|
||||
@staticmethod
|
||||
def hook_matches_hooks(hook, *hooks):
|
||||
"""
|
||||
Tests if ``hook`` matches any of the provided ``hooks`` to test for.
|
||||
|
||||
``hook`` is expected to be an exact hook name.
|
||||
|
||||
``hooks`` is expected to be a list containing one or more hook names or
|
||||
patterns. That can be either an exact hook name or an
|
||||
:func:`fnmatch.fnmatch` pattern.
|
||||
|
||||
Args:
|
||||
hook: the hook to test
|
||||
hooks: the hook name patterns to test against
|
||||
|
||||
Returns:
|
||||
(bool): True if the ``hook`` matches any of the ``hooks``, False otherwise.
|
||||
|
||||
"""
|
||||
|
||||
if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)):
|
||||
hooks = hooks[0]
|
||||
|
||||
hooks = filter(lambda hook: hook is not None, hooks)
|
||||
if not hooks:
|
||||
return False
|
||||
if not hook:
|
||||
return False
|
||||
|
||||
return any(map(lambda h: fnmatch.fnmatch(hook, h),
|
||||
hooks))
|
||||
|
||||
@staticmethod
|
||||
def has_any_of_mixins(plugin, *mixins):
|
||||
"""
|
||||
Tests if the ``plugin`` has an implementation implementing any
|
||||
of the provided ``mixins``.
|
||||
|
||||
Args:
|
||||
plugin: plugin for which to check the implementation
|
||||
*mixins: mixins to test against
|
||||
|
||||
Returns:
|
||||
(bool): True if the plugin's implementation implements any of the
|
||||
provided mixins, False otherwise.
|
||||
"""
|
||||
|
||||
if mixins and len(mixins) == 1 and isinstance(mixins[0], (list, tuple)):
|
||||
mixins = mixins[0]
|
||||
|
||||
mixins = filter(lambda mixin: mixin is not None, mixins)
|
||||
if not mixins:
|
||||
return False
|
||||
if not plugin or not plugin.implementation:
|
||||
return False
|
||||
|
||||
return isinstance(plugin.implementation, tuple(mixins))
|
||||
|
||||
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():
|
||||
|
||||
@@ -23,6 +23,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
from .core import (Plugin, RestartNeedingPlugin, SortablePlugin)
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
class OctoPrintPlugin(Plugin):
|
||||
"""
|
||||
@@ -742,7 +743,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
OctoPrint's version, current ``UI_API_KEY``, tracked file paths and ``LastModified`` value).
|
||||
|
||||
Returns:
|
||||
basestring: An alternatively calculated ETag value. Ignored if ``None`` is returned (default).
|
||||
str: An alternatively calculated ETag value. Ignored if ``None`` is returned (default).
|
||||
"""
|
||||
return None
|
||||
|
||||
|
||||
@@ -28,7 +28,8 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.BlueprintPlugin,
|
||||
octoprint.plugin.StartupPlugin,
|
||||
octoprint.plugin.TemplatePlugin):
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.EventHandlerPlugin):
|
||||
|
||||
def __init__(self):
|
||||
self._cached_channel_configs = None
|
||||
@@ -210,6 +211,14 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
##~~ EventHandlerPlugin
|
||||
|
||||
def on_event(self, event, payload):
|
||||
from octoprint.events import Events
|
||||
if event != Events.CONNECTIVITY_CHANGED or not payload or not payload.get("new", False):
|
||||
return
|
||||
self._fetch_all_channels_async()
|
||||
|
||||
# Internal Tools
|
||||
|
||||
def _mark_read_until(self, channel, until):
|
||||
@@ -266,6 +275,11 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
safe_key = self._slugify(key)
|
||||
return self._get_channel_configs(force=force).get(safe_key)
|
||||
|
||||
def _fetch_all_channels_async(self, force=False):
|
||||
thread = threading.Thread(target=self._fetch_all_channels, kwargs=dict(force=force))
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
def _fetch_all_channels(self, force=False):
|
||||
"""Fetch all channel feeds from cache or network."""
|
||||
|
||||
@@ -298,7 +312,10 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
if data is None:
|
||||
# cache not allowed or empty, fetch from network
|
||||
data = self._get_channel_data_from_network(key, config)
|
||||
if self._connectivity_checker.online:
|
||||
data = self._get_channel_data_from_network(key, config)
|
||||
else:
|
||||
self._logger.info("Looks like we are offline, can't fetch announcements for channel {} from network".format(key))
|
||||
|
||||
return data
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.toggleButtonCss = function(data) {
|
||||
var icon = data.enabled ? "icon-circle" : "icon-circle-blank";
|
||||
var icon = data.enabled ? "fa fa-toggle-on" : "fa fa-toggle-off";
|
||||
var disabled = (self.enableToggle(data)) ? "" : " disabled";
|
||||
|
||||
return icon + disabled;
|
||||
@@ -258,22 +258,22 @@ $(function() {
|
||||
buttons: [{
|
||||
text: gettext("Later"),
|
||||
click: function(notice) {
|
||||
self.hiddenChannels.push(key);
|
||||
notice.remove();
|
||||
self.hiddenChannels.push(key);
|
||||
}
|
||||
}, {
|
||||
text: gettext("Mark read"),
|
||||
click: function(notice) {
|
||||
self.markRead(key, value.last);
|
||||
notice.remove();
|
||||
self.markRead(key, value.last);
|
||||
}
|
||||
}, {
|
||||
text: gettext("Read..."),
|
||||
addClass: "btn-primary",
|
||||
click: function(notice) {
|
||||
notice.remove();
|
||||
self.showAnnouncementDialog(key);
|
||||
self.markRead(key, value.last);
|
||||
notice.remove();
|
||||
}
|
||||
}]
|
||||
},
|
||||
@@ -317,7 +317,13 @@ $(function() {
|
||||
self.announcementDialog = $("#plugin_announcements_dialog");
|
||||
self.announcementDialogContent = $("#plugin_announcements_dialog_content");
|
||||
self.announcementDialogTabs = $("#plugin_announcements_dialog_tabs");
|
||||
};
|
||||
|
||||
self.onEventConnectivityChanged = function(payload) {
|
||||
if (!payload || !payload.new) return;
|
||||
self.retrieveData();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// view model class, parameters for constructor, container to bind to
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
<div class="content" data-bind="html: $data.summary"></div>
|
||||
<div class="actions">
|
||||
<span class="articlelink"><small><a data-bind="text: $data.link, attr: {href: $data.link}" target="_blank" rel="noreferrer noopener"></a></small></span>
|
||||
<span class="markread"><small><a href="javascript:void(0)" data-bind="click: function() { $root.markRead($parent.key, $data.published) }"><i class="icon-eye-open"></i> {{ _('Mark as last read') }}</a></small></span>
|
||||
<span class="markread"><small><a href="javascript:void(0)" data-bind="click: function() { $root.markRead($parent.key, $data.published) }"><i class="fa fa-eye"></i> {{ _('Mark as last read') }}</a></small></span>
|
||||
</div>
|
||||
</article>
|
||||
<!-- /ko -->
|
||||
@@ -40,7 +40,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn configurelink" data-bind="click: configureAnnouncements"><i class="icon-wrench"></i></button>
|
||||
<button class="btn configurelink" data-bind="click: configureAnnouncements"><i class="fa fa-wrench"></i></button>
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1,3 +1,3 @@
|
||||
<a id="navbar_show_announcements" class="pull-right" href="javascript:void(0)" data-bind="click: function() { showAnnouncementDialog(); }" title="{{ _('Announcements') }}">
|
||||
<i data-bind="css: {'icon-bell': !unread(), 'icon-bell-alt': unread()}"></i>
|
||||
<i class="fa" data-bind="css: {'fa-bell-o': !unread(), 'fa-bell': unread()}"></i>
|
||||
</a>
|
||||
@@ -32,4 +32,4 @@
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<button class="btn btn-block" data-bind="click: $root.refreshAnnouncements"><i class="icon-refresh"></i> {{ _('Refresh Announcements') }}</button>
|
||||
<button class="btn btn-block" data-bind="click: $root.refreshAnnouncements"><i class="fa fa-refresh"></i> {{ _('Refresh Announcements') }}</button>
|
||||
@@ -25,6 +25,13 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
names = self._get_subwizard_attrs("_get_", "_wizard_name")
|
||||
additional = self._get_subwizard_attrs("_get_", "_additional_wizard_template_data")
|
||||
|
||||
firstrunonly = self._get_subwizard_attrs("_is_", "_wizard_firstrunonly")
|
||||
firstrun = self._settings.global_get(["server", "firstRun"])
|
||||
|
||||
if not firstrun:
|
||||
required = dict((key, value) for key, value in required.items()
|
||||
if not firstrunonly.get(key, lambda: False)())
|
||||
|
||||
result = list()
|
||||
for key, method in required.items():
|
||||
if not method():
|
||||
@@ -37,7 +44,11 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
if not name:
|
||||
continue
|
||||
|
||||
config = dict(type="wizard", name=name, template="corewizard_{}_wizard.jinja2".format(key), div="wizard_plugin_corewizard_{}".format(key))
|
||||
config = dict(type="wizard",
|
||||
name=name,
|
||||
template="corewizard_{}_wizard.jinja2".format(key),
|
||||
div="wizard_plugin_corewizard_{}".format(key),
|
||||
suffix="_{}".format(key))
|
||||
if key in additional:
|
||||
additional_result = additional[key]()
|
||||
if additional_result:
|
||||
@@ -49,15 +60,26 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
#~~ AssetPlugin API
|
||||
|
||||
def get_assets(self):
|
||||
return dict(
|
||||
js=["js/corewizard.js"]
|
||||
)
|
||||
if self.is_wizard_required():
|
||||
return dict(
|
||||
js=["js/corewizard.js"]
|
||||
)
|
||||
else:
|
||||
return dict()
|
||||
|
||||
#~~ WizardPlugin API
|
||||
|
||||
def is_wizard_required(self):
|
||||
methods = self._get_subwizard_attrs("_is_", "_wizard_required")
|
||||
return self._settings.global_get(["server", "firstRun"]) and any(map(lambda m: m(), methods.values()))
|
||||
required = self._get_subwizard_attrs("_is_", "_wizard_required")
|
||||
firstrunonly = self._get_subwizard_attrs("_is_", "_wizard_firstrunonly")
|
||||
firstrun = self._settings.global_get(["server", "firstRun"])
|
||||
|
||||
if not firstrun:
|
||||
required = dict((key, value) for key, value in required.items()
|
||||
if not firstrunonly.get(key, lambda: False)())
|
||||
any_required = any(map(lambda m: m(), required.values()))
|
||||
|
||||
return any_required
|
||||
|
||||
def get_wizard_details(self):
|
||||
result = dict()
|
||||
@@ -68,13 +90,19 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
return result
|
||||
|
||||
def get_wizard_version(self):
|
||||
return 1
|
||||
|
||||
#~~ ACL subwizard
|
||||
|
||||
def _is_acl_wizard_firstrunonly(self):
|
||||
return True
|
||||
|
||||
def _is_acl_wizard_required(self):
|
||||
return self._user_manager.enabled and not self._user_manager.hasBeenCustomized()
|
||||
|
||||
def _get_acl_wizard_details(self):
|
||||
return dict()
|
||||
return dict(required=self._is_acl_wizard_required())
|
||||
|
||||
def _get_acl_wizard_name(self):
|
||||
return gettext("Access Control")
|
||||
@@ -111,6 +139,9 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
#~~ Webcam subwizard
|
||||
|
||||
def _is_webcam_wizard_firstrunonly(self):
|
||||
return True
|
||||
|
||||
def _is_webcam_wizard_required(self):
|
||||
webcam_snapshot_url = self._settings.global_get(["webcam", "snapshot"])
|
||||
webcam_stream_url = self._settings.global_get(["webcam", "stream"])
|
||||
@@ -119,13 +150,16 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
return not (webcam_snapshot_url and webcam_stream_url and ffmpeg_path)
|
||||
|
||||
def _get_webcam_wizard_details(self):
|
||||
return dict()
|
||||
return dict(required=self._is_webcam_wizard_required())
|
||||
|
||||
def _get_webcam_wizard_name(self):
|
||||
return gettext("Webcam & Timelapse")
|
||||
|
||||
#~~ Server commands subwizard
|
||||
|
||||
def _is_servercommands_wizard_firstrunonly(self):
|
||||
return True
|
||||
|
||||
def _is_servercommands_wizard_required(self):
|
||||
system_shutdown_command = self._settings.global_get(["server", "commands", "systemShutdownCommand"])
|
||||
system_restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"])
|
||||
@@ -134,18 +168,38 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
return not (system_shutdown_command and system_restart_command and server_restart_command)
|
||||
|
||||
def _get_servercommands_wizard_details(self):
|
||||
return dict()
|
||||
return dict(required=self._is_servercommands_wizard_required())
|
||||
|
||||
def _get_servercommands_wizard_name(self):
|
||||
return gettext("Server Commands")
|
||||
|
||||
#~~ Online check subwizard
|
||||
|
||||
def _is_onlinecheck_wizard_firstrunonly(self):
|
||||
return False
|
||||
|
||||
def _is_onlinecheck_wizard_required(self):
|
||||
return self._settings.global_get(["server", "onlineCheck", "enabled"]) is None
|
||||
|
||||
def _get_onlinecheck_wizard_details(self):
|
||||
return dict(required=self._is_onlinecheck_wizard_required())
|
||||
|
||||
def _get_onlinecheck_wizard_name(self):
|
||||
return gettext("Online connectivity check")
|
||||
|
||||
def _get_onlinecheck_additional_wizard_template_data(self):
|
||||
return dict(mandatory=self._is_onlinecheck_wizard_required())
|
||||
|
||||
#~~ Printer profile subwizard
|
||||
|
||||
def _is_printerprofile_wizard_firstrunonly(self):
|
||||
return True
|
||||
|
||||
def _is_printerprofile_wizard_required(self):
|
||||
return self._printer_profile_manager.is_default_unmodified() and self._printer_profile_manager.profile_count == 1
|
||||
|
||||
def _get_printerprofile_wizard_details(self):
|
||||
return dict()
|
||||
return dict(required=self._is_printerprofile_wizard_required())
|
||||
|
||||
def _get_printerprofile_wizard_name(self):
|
||||
return gettext("Default Printer Profile")
|
||||
|
||||
@@ -11,6 +11,8 @@ $(function() {
|
||||
self.setup = ko.observable(false);
|
||||
self.decision = ko.observable();
|
||||
|
||||
self.required = false;
|
||||
|
||||
self.passwordMismatch = ko.pureComputed(function() {
|
||||
return self.password() != self.confirmedPassword();
|
||||
});
|
||||
@@ -72,6 +74,8 @@ $(function() {
|
||||
};
|
||||
|
||||
self.onBeforeWizardTabChange = function(next, current) {
|
||||
if (!self.required) return true;
|
||||
|
||||
if (!current || !_.startsWith(current, "wizard_plugin_corewizard_acl_") || self.setup()) {
|
||||
return true;
|
||||
}
|
||||
@@ -82,7 +86,13 @@ $(function() {
|
||||
return false;
|
||||
};
|
||||
|
||||
self.onWizardDetails = function(response) {
|
||||
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.acl && response.corewizard.details.acl.required;
|
||||
};
|
||||
|
||||
self.onWizardFinish = function() {
|
||||
if (!self.required) return;
|
||||
|
||||
if (!self.decision()) {
|
||||
return "reload";
|
||||
}
|
||||
@@ -94,7 +104,14 @@ $(function() {
|
||||
|
||||
self.settingsViewModel = parameters[0];
|
||||
|
||||
self.required = false;
|
||||
|
||||
self.onWizardDetails = function(response) {
|
||||
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.webcam && response.corewizard.details.webcam.required;
|
||||
};
|
||||
|
||||
self.onWizardFinish = function() {
|
||||
if (!self.required) return;
|
||||
if (self.settingsViewModel.webcam_streamUrl()
|
||||
|| (self.settingsViewModel.webcam_snapshotUrl() && self.settingsViewModel.webcam_ffmpegPath())) {
|
||||
return "reload";
|
||||
@@ -108,23 +125,116 @@ $(function() {
|
||||
self.settingsViewModel = parameters[0];
|
||||
}
|
||||
|
||||
function CoreWizardOnlineCheckViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.settingsViewModel = parameters[0];
|
||||
|
||||
self.setup = ko.observable(false);
|
||||
|
||||
self.decision = ko.observable();
|
||||
self.required = false;
|
||||
self.active = false;
|
||||
|
||||
self.enableOnlineCheck = function() {
|
||||
self.settingsViewModel.server_onlineCheck_enabled(true);
|
||||
self.decision(true);
|
||||
self._sendData();
|
||||
};
|
||||
|
||||
self.disableOnlineCheck = function() {
|
||||
self.settingsViewModel.server_onlineCheck_enabled(false);
|
||||
self.decision(false);
|
||||
self._sendData();
|
||||
};
|
||||
|
||||
self.onBeforeWizardTabChange = function(next, current) {
|
||||
if (!self.required) return true;
|
||||
|
||||
if (!current || !_.startsWith(current, "wizard_plugin_corewizard_onlinecheck_") || self.setup()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
self._showDecisionNeededDialog();
|
||||
return false;
|
||||
};
|
||||
|
||||
self.onBeforeWizardFinish = function() {
|
||||
if (!self.required) return true;
|
||||
|
||||
if (self.setup()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
self._showDecisionNeededDialog();
|
||||
return false;
|
||||
};
|
||||
|
||||
self.onWizardPreventSettingsRefreshDialog = function() {
|
||||
return self.active;
|
||||
};
|
||||
|
||||
self.onWizardDetails = function(response) {
|
||||
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.onlinecheck && response.corewizard.details.onlinecheck.required;
|
||||
};
|
||||
|
||||
self._showDecisionNeededDialog = function() {
|
||||
showMessageDialog({
|
||||
title: gettext("Please set up the online connectivity check"),
|
||||
message: gettext("You haven't yet decided on whether to enable or disable the online connectivity check. You need to either enable or disable it before continuing.")
|
||||
});
|
||||
};
|
||||
|
||||
self._sendData = function() {
|
||||
var data = {
|
||||
server: {
|
||||
onlineCheck: {
|
||||
enabled: self.settingsViewModel.server_onlineCheck_enabled(),
|
||||
interval: self.settingsViewModel.server_onlineCheck_interval(),
|
||||
host: self.settingsViewModel.server_onlineCheck_host(),
|
||||
port: self.settingsViewModel.server_onlineCheck_port()
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self.active = true;
|
||||
self.settingsViewModel.saveData(data)
|
||||
.done(function() {
|
||||
self.setup(true);
|
||||
self.active = false;
|
||||
});
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
function CoreWizardPrinterProfileViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.printerProfiles = parameters[0];
|
||||
|
||||
self.required = false;
|
||||
|
||||
self.editor = self.printerProfiles.createProfileEditor();
|
||||
self.editorLoaded = ko.observable(false);
|
||||
|
||||
self.onStartup = function() {
|
||||
self.onWizardDetails = function(response) {
|
||||
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.printerprofile && response.corewizard.details.printerprofile.required;
|
||||
if (!self.required) return;
|
||||
|
||||
OctoPrint.printerprofiles.get("_default")
|
||||
.done(function(data) {
|
||||
self.editor.fromProfileData(data);
|
||||
self.editorLoaded(true);
|
||||
})
|
||||
.fail(function() {
|
||||
self.editor.fromProfileData();
|
||||
self.editorLoaded(true);
|
||||
});
|
||||
};
|
||||
|
||||
self.onWizardFinish = function() {
|
||||
if (!self.required) return;
|
||||
|
||||
OctoPrint.printerprofiles.update("_default", self.editor.toProfileData())
|
||||
.done(function() {
|
||||
self.printerProfiles.requestData();
|
||||
@@ -144,6 +254,10 @@ $(function() {
|
||||
CoreWizardServerCommandsViewModel,
|
||||
["settingsViewModel"],
|
||||
"#wizard_plugin_corewizard_servercommands"
|
||||
], [
|
||||
CoreWizardOnlineCheckViewModel,
|
||||
["settingsViewModel"],
|
||||
"#wizard_plugin_corewizard_onlinecheck"
|
||||
], [
|
||||
CoreWizardPrinterProfileViewModel,
|
||||
["printerProfilesViewModel"],
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
<h3>{{ _('Configure the connectivity check') }}</h3>
|
||||
|
||||
{% include "snippets/settings/server/serverOnlineCheckDescription.jinja2" %}
|
||||
|
||||
<p>{% trans %}
|
||||
If it is disabled OctoPrint will always assume to have a working connection to the internet.
|
||||
If that should not actually be the case, server startups, update checks and the like might take longer.
|
||||
{% endtrans %}</p>
|
||||
|
||||
<p>{% trans %}
|
||||
OctoPrint comes preconfigured to perform the connectivity check every 15 minutes. You may change the value here.
|
||||
{% endtrans %}</p>
|
||||
|
||||
<form class="form-horizontal" data-bind="with: settingsViewModel, enable: !setup(), css {disabled: setup()}">
|
||||
{% include "snippets/settings/server/serverOnlineCheckInterval.jinja2" %}
|
||||
</form>
|
||||
|
||||
<p>{% trans %}
|
||||
OctoPrint comes preconfigured to utilize Google's DNS server <code>8.8.8.8</code>, port 53 for the connectivity check (if
|
||||
it's enabled). If you have concerns about using that, define the IP and port of a different online server that you
|
||||
trust and that has a high availability.
|
||||
{% endtrans %}</p>
|
||||
|
||||
<form class="form-horizontal" data-bind="with: settingsViewModel, enable: !setup(), css {disabled: setup()}">
|
||||
{% include "snippets/settings/server/serverOnlineCheckHost.jinja2" %}
|
||||
{% include "snippets/settings/server/serverOnlineCheckPort.jinja2" %}
|
||||
</form>
|
||||
|
||||
<p>{% trans %}
|
||||
Finally, please decide on whether to enable or disable the connectivity check. You may change the configuration at
|
||||
any time to a later date through Settings > Server right from within OctoPrint.
|
||||
{% endtrans %}</p>
|
||||
|
||||
<div class="row-fluid">
|
||||
<a href="#" class="btn span6" data-bind="click: function() { if(!setup()){disableOnlineCheck()}}, enable: !setup(), css: {disabled: setup()}">{{ _('Disable Connectivity Check') }}</a>
|
||||
<a href="#" class="btn btn-primary span6" data-bind="click: function() { if(!setup()){enableOnlineCheck()}}, enable: !setup(), css: {disabled: setup()}">{{ _('Enable Connectivity Check') }}</a>
|
||||
</div>
|
||||
|
||||
<div class="onlinecheck_decision" style="display: none" data-bind="visible: setup()">
|
||||
<div class="text-center" style="display: none" data-bind="visible: decision()">{% trans %}
|
||||
Connectivity check is <strong class="text-success">enabled</strong>.
|
||||
{% endtrans %}</div>
|
||||
<div class="text-center" style="display: none" data-bind="visible: !decision()">{% trans %}
|
||||
Connectivity check is <strong class="text-danger">disabled</strong>.
|
||||
{% endtrans %}</div>
|
||||
</div>
|
||||
@@ -7,7 +7,9 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
|
||||
import re
|
||||
|
||||
from builtins import range
|
||||
from past.builtins import basestring
|
||||
|
||||
class SupportLocationTypes(object):
|
||||
NONE = "none"
|
||||
|
||||
@@ -59,6 +59,6 @@
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
|
||||
<button class="btn btn-primary" data-bind="click: performUpload, enable: uploadEnabled, css: {disabled: !uploadEnabled()}" id="settings-cura-import-start"><i class="icon-spinner icon-spin" data-bind="visible: uploadBusy"></i> {{ _('Confirm') }}</button>
|
||||
<button class="btn btn-primary" data-bind="click: performUpload, enable: uploadEnabled, css: {disabled: !uploadEnabled()}" id="settings-cura-import-start"><i class="fa fa-spinner fa-spin" data-bind="visible: uploadBusy"></i> {{ _('Confirm') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -12,10 +12,10 @@
|
||||
</thead>
|
||||
<tbody data-bind="foreach: profiles.paginatedItems">
|
||||
<tr data-bind="attr: {title: description}">
|
||||
<td class="settings_plugin_cura_profiles_key"><span class="icon-star" data-bind="invisible: !isdefault()"></span> <span data-bind="text: key"></span></td>
|
||||
<td class="settings_plugin_cura_profiles_key"><span class="fa fa-star" data-bind="invisible: !isdefault()"></span> <span data-bind="text: key"></span></td>
|
||||
<td class="settings_plugin_cura_profiles_name" data-bind="text: name"></td>
|
||||
<td class="settings_plugin_cura_profiles_actions">
|
||||
<a href="#" class="icon-star" title="{{ _('Make default') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.makeProfileDefault($data); } }"></a> | <a href="#" class="icon-trash" title="{{ _('Delete Profile') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.removeProfile($data); } }"></a>
|
||||
<a href="#" class="fa fa-star" title="{{ _('Make default') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.makeProfileDefault($data); } }"></a> | <a href="#" class="fa fa-trash-o" title="{{ _('Delete Profile') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.removeProfile($data); } }"></a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
|
||||
@@ -5,6 +5,7 @@ __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"
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
import octoprint.plugin
|
||||
import octoprint.plugin.core
|
||||
@@ -35,7 +36,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.StartupPlugin,
|
||||
octoprint.plugin.BlueprintPlugin):
|
||||
octoprint.plugin.BlueprintPlugin,
|
||||
octoprint.plugin.EventHandlerPlugin):
|
||||
|
||||
ARCHIVE_EXTENSIONS = (".zip", ".tar.gz", ".tgz", ".tar")
|
||||
|
||||
@@ -44,7 +46,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
macos=["darwin"],
|
||||
freebsd=lambda x: x.startswith("freebsd"))
|
||||
|
||||
pip_inapplicable_arguments = dict(uninstall=["--user"])
|
||||
PIP_INAPPLICABLE_ARGUMENTS = dict(uninstall=["--user"])
|
||||
|
||||
RECONNECT_HOOKS = ["octoprint.comm.protocol.*",]
|
||||
|
||||
def __init__(self):
|
||||
self._pending_enable = set()
|
||||
@@ -97,13 +101,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._console_logger.propagate = False
|
||||
|
||||
# decouple repository fetching from server startup
|
||||
def fetch_data():
|
||||
self._repository_available = self._fetch_repository_from_disk()
|
||||
self._notices_available = self._fetch_notices_from_disk()
|
||||
|
||||
thread = threading.Thread(target=fetch_data)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
self._fetch_all_data(async=True)
|
||||
|
||||
##~~ SettingsPlugin
|
||||
|
||||
@@ -194,6 +192,14 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
except Exception as e:
|
||||
self._logger.warn("Could not remove temporary file {path} again: {message}".format(path=archive.name, message=str(e)))
|
||||
|
||||
##~~ EventHandlerPlugin
|
||||
|
||||
def on_event(self, event, payload):
|
||||
from octoprint.events import Events
|
||||
if event != Events.CONNECTIVITY_CHANGED or not payload or not payload.get("new", False):
|
||||
return
|
||||
self._fetch_all_data(async=True)
|
||||
|
||||
##~~ SimpleApiPlugin
|
||||
|
||||
def get_api_commands(self):
|
||||
@@ -236,7 +242,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
additional_args=self._settings.get(["pip_args"]),
|
||||
python=sys.executable
|
||||
),
|
||||
safe_mode=safe_mode)
|
||||
safe_mode=safe_mode,
|
||||
online=self._connectivity_checker.online)
|
||||
|
||||
def etag():
|
||||
import hashlib
|
||||
@@ -247,6 +254,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
hash.update(str(self._notices_available))
|
||||
hash.update(repr(self._notices))
|
||||
hash.update(repr(safe_mode))
|
||||
hash.update(repr(self._connectivity_checker.online))
|
||||
return hash.hexdigest()
|
||||
|
||||
def condition():
|
||||
@@ -415,6 +423,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
source_type=source_type,
|
||||
needs_restart=True,
|
||||
needs_refresh=True,
|
||||
needs_reconnect=True,
|
||||
was_reinstalled=False,
|
||||
plugin="unknown")
|
||||
self._send_result_notification("install", result)
|
||||
@@ -426,6 +435,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
or reinstall is not None
|
||||
needs_refresh = new_plugin.implementation \
|
||||
and isinstance(new_plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
|
||||
needs_reconnect = self._plugin_manager.has_any_of_hooks(new_plugin, self._reconnect_hooks) and self._printer.is_operational()
|
||||
|
||||
is_reinstall = self._plugin_manager.is_plugin_marked(new_plugin.key, "uninstalled")
|
||||
self._plugin_manager.mark_plugin(new_plugin.key,
|
||||
@@ -440,6 +450,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
source_type=source_type,
|
||||
needs_restart=needs_restart,
|
||||
needs_refresh=needs_refresh,
|
||||
needs_reconnect=needs_reconnect,
|
||||
was_reinstalled=new_plugin.key in all_plugins_before or reinstall is not None,
|
||||
plugin=self._to_external_plugin(new_plugin))
|
||||
self._send_result_notification("install", result)
|
||||
@@ -496,6 +507,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin)
|
||||
needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
|
||||
needs_reconnect = self._plugin_manager.has_any_of_hooks(plugin, self._reconnect_hooks) and self._printer.is_operational()
|
||||
|
||||
was_pending_install = self._plugin_manager.is_plugin_marked(plugin.key, "installed")
|
||||
self._plugin_manager.mark_plugin(plugin.key,
|
||||
@@ -521,7 +533,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
self._plugin_manager.reload_plugins()
|
||||
|
||||
result = dict(result=True, needs_restart=needs_restart, needs_refresh=needs_refresh, plugin=self._to_external_plugin(plugin))
|
||||
result = dict(result=True,
|
||||
needs_restart=needs_restart,
|
||||
needs_refresh=needs_refresh,
|
||||
needs_reconnect=needs_reconnect,
|
||||
plugin=self._to_external_plugin(plugin))
|
||||
self._send_result_notification("uninstall", result)
|
||||
return jsonify(result)
|
||||
|
||||
@@ -531,11 +547,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin)
|
||||
needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
|
||||
needs_reconnect = self._plugin_manager.has_any_of_hooks(plugin, self._reconnect_hooks) and self._printer.is_operational()
|
||||
|
||||
pending = ((command == "disable" and plugin.key in self._pending_enable) or (command == "enable" and plugin.key in self._pending_disable))
|
||||
safe_mode_victim = getattr(plugin, "safe_mode_victim", False)
|
||||
needs_restart_api = (needs_restart or safe_mode_victim) and not pending
|
||||
needs_refresh_api = needs_refresh and not pending
|
||||
needs_reconnect_api = needs_reconnect and not pending
|
||||
|
||||
try:
|
||||
if command == "disable":
|
||||
@@ -549,11 +567,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
result = dict(result=True,
|
||||
needs_restart=True,
|
||||
needs_refresh=True,
|
||||
needs_reconnect=True,
|
||||
plugin=self._to_external_plugin(plugin))
|
||||
else:
|
||||
result = dict(result=True,
|
||||
needs_restart=needs_restart_api,
|
||||
needs_refresh=needs_refresh_api,
|
||||
needs_reconnect=needs_reconnect_api,
|
||||
plugin=self._to_external_plugin(plugin))
|
||||
|
||||
self._send_result_notification(command, result)
|
||||
@@ -605,7 +625,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
if additional_args is not None:
|
||||
|
||||
inapplicable_arguments = self.__class__.pip_inapplicable_arguments.get(args[0], list())
|
||||
inapplicable_arguments = self.__class__.PIP_INAPPLICABLE_ARGUMENTS.get(args[0], list())
|
||||
for inapplicable_argument in inapplicable_arguments:
|
||||
additional_args = re.sub("(^|\s)" + re.escape(inapplicable_argument) + "\\b", "", additional_args)
|
||||
|
||||
@@ -664,6 +684,18 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
elif (plugin.enabled or getattr(plugin, "safe_mode_enabled", False)) and plugin.key not in self._pending_disable:
|
||||
self._pending_disable.add(plugin.key)
|
||||
|
||||
def _fetch_all_data(self, async=False):
|
||||
def run():
|
||||
self._repository_available = self._fetch_repository_from_disk()
|
||||
self._notices_available = self._fetch_notices_from_disk()
|
||||
|
||||
if async:
|
||||
thread = threading.Thread(target=run)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
else:
|
||||
run()
|
||||
|
||||
def _fetch_repository_from_disk(self):
|
||||
repo_data = None
|
||||
if os.path.isfile(self._repository_cache_path):
|
||||
@@ -681,6 +713,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
return self._refresh_repository(repo_data=repo_data)
|
||||
|
||||
def _fetch_repository_from_url(self):
|
||||
if not self._connectivity_checker.online:
|
||||
self._logger.info("Looks like we are offline, can't fetch repository from network")
|
||||
return None
|
||||
|
||||
repository_url = self._settings.get(["repository"])
|
||||
try:
|
||||
r = requests.get(repository_url, timeout=30)
|
||||
@@ -743,13 +779,17 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
import json
|
||||
with open(self._notices_cache_path) as f:
|
||||
notice_data = json.load(f)
|
||||
self._logger.info("Loaded notices from disk, was still valid")
|
||||
self._logger.info("Loaded notice data from disk, was still valid")
|
||||
except:
|
||||
self._logger.exception("Error while loading notices from {}".format(self._notices_cache_path))
|
||||
|
||||
return self._refresh_notices(notice_data=notice_data)
|
||||
|
||||
def _fetch_notices_from_url(self):
|
||||
if not self._connectivity_checker.online:
|
||||
self._logger.info("Looks like we are offline, can't fetch notices from network")
|
||||
return None
|
||||
|
||||
notices_url = self._settings.get(["notices"])
|
||||
try:
|
||||
r = requests.get(notices_url, timeout=30)
|
||||
@@ -881,6 +921,22 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
octoprint_version = pkg_resources.parse_version(octoprint_version.base_version)
|
||||
return octoprint_version
|
||||
|
||||
@property
|
||||
def _reconnect_hooks(self):
|
||||
reconnect_hooks = self.__class__.RECONNECT_HOOKS
|
||||
|
||||
reconnect_hook_provider_hooks = self._plugin_manager.get_hooks("octoprint.plugin.pluginmanager.reconnect_hooks")
|
||||
for name, hook in reconnect_hook_provider_hooks.items():
|
||||
try:
|
||||
result = hook()
|
||||
if isinstance(result, (list, tuple)):
|
||||
reconnect_hooks.extend(filter(lambda x: isinstance(x, basestring), result))
|
||||
except:
|
||||
self._logger.exception("Error while retrieving additional hooks for which a "
|
||||
"reconnect is required from plugin {name}".format(**locals()))
|
||||
|
||||
return reconnect_hooks
|
||||
|
||||
def _get_plugins(self):
|
||||
plugins = self._plugin_manager.plugins
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
table td.settings_plugin_plugin_manager_plugins_name,table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_plugin_manager_plugins_actions,table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}table td.settings_plugin_plugin_manager_plugins_actions a,table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}table td.settings_plugin_plugin_manager_plugins_actions a.disabled,table th.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 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_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 10px 5px 5px}#settings_plugin_pluginmanager_workingdialog_output span{display:block}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
|
||||
table td.settings_plugin_plugin_manager_plugins_name,table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_plugin_manager_plugins_actions,table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}table td.settings_plugin_plugin_manager_plugins_actions a,table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}table td.settings_plugin_plugin_manager_plugins_actions a.disabled,table th.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 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_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 10px 5px 5px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
|
||||
@@ -174,6 +174,7 @@ $(function() {
|
||||
self.pipPython = ko.observable();
|
||||
|
||||
self.safeMode = ko.observable();
|
||||
self.online = ko.observable();
|
||||
|
||||
self.pipUseUserString = ko.pureComputed(function() {
|
||||
return self.pipUseUser() ? "yes" : "no";
|
||||
@@ -234,7 +235,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.enableRepoInstall = function(data) {
|
||||
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && self.isCompatible(data);
|
||||
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && self.online() && self.isCompatible(data);
|
||||
};
|
||||
|
||||
self.invalidUrl = ko.pureComputed(function() {
|
||||
@@ -244,7 +245,7 @@ $(function() {
|
||||
|
||||
self.enableUrlInstall = ko.pureComputed(function() {
|
||||
var url = self.installUrl();
|
||||
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && url !== undefined && url.trim() != "" && !self.invalidUrl();
|
||||
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && self.online() && url !== undefined && url.trim() != "" && !self.invalidUrl();
|
||||
});
|
||||
|
||||
self.invalidArchive = ko.pureComputed(function() {
|
||||
@@ -321,6 +322,7 @@ $(function() {
|
||||
self._fromPipResponse(data.pip, options);
|
||||
|
||||
self.safeMode(data.safe_mode || false);
|
||||
self.online(data.online !== undefined ? data.online : true);
|
||||
};
|
||||
|
||||
self._fromPluginsResponse = function(data, options) {
|
||||
@@ -663,7 +665,7 @@ $(function() {
|
||||
return self.isCompatible(data) ? (self.installed(data) ? gettext("Reinstall") : gettext("Install")) : (data.disabled ? gettext("Disabled") : gettext("Incompatible"));
|
||||
};
|
||||
|
||||
self._displayNotification = function(response, titleSuccess, textSuccess, textRestart, textReload, titleError, textError) {
|
||||
self._displayNotification = function(response, titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError) {
|
||||
var notification;
|
||||
|
||||
var beforeClose = function(notification) {
|
||||
@@ -685,17 +687,21 @@ $(function() {
|
||||
hide: false
|
||||
};
|
||||
|
||||
var restartClicked = false;
|
||||
if (self.restartCommandSpec) {
|
||||
options.confirm = {
|
||||
confirm: true,
|
||||
buttons: [{
|
||||
text: gettext("Restart now"),
|
||||
click: function () {
|
||||
click: function (notice) {
|
||||
if (restartClicked) return;
|
||||
restartClicked = true;
|
||||
showConfirmationDialog({
|
||||
message: gettext("This will restart your OctoPrint server."),
|
||||
onproceed: function() {
|
||||
OctoPrint.system.executeCommand("core", "restart")
|
||||
.done(function() {
|
||||
notice.remove();
|
||||
new PNotify({
|
||||
title: gettext("Restart in progress"),
|
||||
text: gettext("The server is now being restarted in the background")
|
||||
@@ -707,6 +713,9 @@ $(function() {
|
||||
text: gettext("Trying to restart the server produced an error, please check octoprint.log for details. You'll have to restart manually.")
|
||||
})
|
||||
});
|
||||
},
|
||||
onclose: function() {
|
||||
restartClicked = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -716,6 +725,7 @@ $(function() {
|
||||
|
||||
notification = PNotify.singleButtonNotify(options);
|
||||
} else if (response.needs_refresh) {
|
||||
var refreshClicked = false;
|
||||
notification = PNotify.singleButtonNotify({
|
||||
title: titleSuccess,
|
||||
text: textReload,
|
||||
@@ -724,6 +734,8 @@ $(function() {
|
||||
buttons: [{
|
||||
text: gettext("Reload now"),
|
||||
click: function () {
|
||||
if (refreshClicked) return;
|
||||
refreshClicked = true;
|
||||
location.reload(true);
|
||||
}
|
||||
}]
|
||||
@@ -737,6 +749,15 @@ $(function() {
|
||||
},
|
||||
hide: false
|
||||
})
|
||||
} else if (response.needs_reconnect) {
|
||||
notification = new PNotify({
|
||||
title: titleSuccess,
|
||||
text: textReconnect,
|
||||
callbacks: {
|
||||
before_close: beforeClose
|
||||
},
|
||||
hide: false
|
||||
})
|
||||
} else {
|
||||
notification = new PNotify({
|
||||
title: titleSuccess,
|
||||
@@ -795,7 +816,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.toggleButtonCss = function(data) {
|
||||
var icon = self._getToggleCommand(data) == "enable" ? "icon-circle-blank" : "icon-circle";
|
||||
var icon = self._getToggleCommand(data) == "enable" ? "fa fa-toggle-off" : "fa fa-toggle-on";
|
||||
var disabled = (self.enableToggle(data)) ? "" : " disabled";
|
||||
|
||||
return icon + disabled;
|
||||
@@ -1001,6 +1022,10 @@ $(function() {
|
||||
self._closeAllNotifications();
|
||||
};
|
||||
|
||||
self.onEventConnectivityChanged = function(payload) {
|
||||
self.requestData({eval_notices: true});
|
||||
};
|
||||
|
||||
self._closeAllNotifications = function() {
|
||||
if (self.notifications) {
|
||||
_.each(self.notifications, function(notification) {
|
||||
@@ -1050,7 +1075,7 @@ $(function() {
|
||||
});
|
||||
self._scrollWorkingOutputToEnd();
|
||||
} else if (messageType == "result") {
|
||||
var titleSuccess, textSuccess, textRestart, textReload, titleError, textError;
|
||||
var titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError;
|
||||
var action = data.action;
|
||||
|
||||
var name = "Unknown";
|
||||
@@ -1070,16 +1095,19 @@ $(function() {
|
||||
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;
|
||||
textReconnect = 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.");
|
||||
textReload = gettext("The plugin was reinstalled successfully, however a reload of the page is needed for that to take effect.");
|
||||
textReconnect = gettext("The plugin was reinstalled successfully, however a reconnect to the printer is needed for that to take effect.");
|
||||
} else {
|
||||
titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" installed"), {name: name});
|
||||
textSuccess = gettext("The plugin was installed successfully");
|
||||
textRestart = gettext("The plugin was installed successfully, however a restart of OctoPrint is needed for that to take effect.");
|
||||
textReload = gettext("The plugin was installed successfully, however a reload of the page is needed for that to take effect.");
|
||||
textReconnect = gettext("The plugin was installed successfully, however a reconnect to the printer is needed for that to take effect.");
|
||||
}
|
||||
|
||||
titleError = gettext("Something went wrong");
|
||||
@@ -1131,6 +1159,7 @@ $(function() {
|
||||
textSuccess = gettext("The plugin was uninstalled successfully");
|
||||
textRestart = gettext("The plugin was uninstalled successfully, however a restart of OctoPrint is needed for that to take effect.");
|
||||
textReload = gettext("The plugin was uninstalled successfully, however a reload of the page is needed for that to take effect.");
|
||||
textReconnect = gettext("The plugin was uninstalled successfully, however a reconnect to the printer is needed for that to take effect.");
|
||||
|
||||
titleError = gettext("Something went wrong");
|
||||
if (data.hasOwnProperty("reason")) {
|
||||
@@ -1148,6 +1177,7 @@ $(function() {
|
||||
textSuccess = gettext("The plugin was enabled successfully.");
|
||||
textRestart = gettext("The plugin was enabled successfully, however a restart of OctoPrint is needed for that to take effect.");
|
||||
textReload = gettext("The plugin was enabled successfully, however a reload of the page is needed for that to take effect.");
|
||||
textReconnect = gettext("The plugin was enabled successfully, however a reconnect to the printer is needed for that to take effect.");
|
||||
|
||||
titleError = gettext("Something went wrong");
|
||||
if (data.hasOwnProperty("reason")) {
|
||||
@@ -1165,6 +1195,7 @@ $(function() {
|
||||
textSuccess = gettext("The plugin was disabled successfully.");
|
||||
textRestart = gettext("The plugin was disabled successfully, however a restart of OctoPrint is needed for that to take effect.");
|
||||
textReload = gettext("The plugin was disabled successfully, however a reload of the page is needed for that to take effect.");
|
||||
textReconnect = gettext("The plugin was disabled successfully, however a reconnect to the printer is needed for that to take effect.");
|
||||
|
||||
titleError = gettext("Something went wrong");
|
||||
if (data.hasOwnProperty("reason")) {
|
||||
@@ -1177,7 +1208,7 @@ $(function() {
|
||||
return;
|
||||
}
|
||||
|
||||
self._displayNotification(data, titleSuccess, textSuccess, textRestart, textReload, titleError, textError);
|
||||
self._displayNotification(data, titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError);
|
||||
self.requestData();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -85,10 +85,6 @@ table {
|
||||
}
|
||||
|
||||
#settings_plugin_pluginmanager_workingdialog_output {
|
||||
span {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.message {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@@ -20,12 +20,19 @@
|
||||
{% endtrans %}</div>
|
||||
{% endmacro %}
|
||||
|
||||
{% macro pluginmanager_offline() %}
|
||||
<div class="alert" data-bind="visible: !online()">{% trans %}
|
||||
It looks like OctoPrint has currently no connection to the internet. Due to that it's not possible
|
||||
to install new plugins from the plugin repository or archive URLs.
|
||||
{% endtrans %}</div>
|
||||
{% endmacro %}
|
||||
|
||||
{{ pluginmanager_printing() }}
|
||||
{{ pluginmanager_nopip() }}
|
||||
{{ pluginmanager_safemode() }}
|
||||
|
||||
<div class="pull-right">
|
||||
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="icon-wrench"></i></button>
|
||||
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="fa fa-wrench"></i></button>
|
||||
</div>
|
||||
|
||||
<h3>{{ _('Installed Plugins') }}</h3>
|
||||
@@ -40,18 +47,18 @@
|
||||
<tbody data-bind="foreach: plugins.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_plugin_manager_plugins_name">
|
||||
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint') }}" class="icon-th-large" data-bind="visible: bundled"></i> <i class="icon-lock" title="{{ _('Cannot be uninstalled through OctoPrint') }}" data-bind="visible: !managable"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect') }}" class="icon-refresh" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install') }}" class="icon-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall') }}" class="icon-minus" data-bind="visible: pending_uninstall"></i> <i title="{{ _('Disabled due to safe mode') }}" class="icon-medkit" data-bind="visible: safe_mode_victim"></i> <i class="icon-exclamation-sign" title="{{ _('There are notices available regarding this plugin') }}" data-bind="visible: notifications && notifications.length"></i></div>
|
||||
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint') }}" class="fa fa-th-large" data-bind="visible: bundled"></i> <i class="fa fa-lock" title="{{ _('Cannot be uninstalled through OctoPrint') }}" data-bind="visible: !managable"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect') }}" class="fa fa-refresh" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install') }}" class="fa fa-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall') }}" class="fa fa-minus" data-bind="visible: pending_uninstall"></i> <i title="{{ _('Disabled due to safe mode') }}" class="fa fa-medkit" data-bind="visible: safe_mode_victim"></i> <i class="fa fa-exclamation-triangle" title="{{ _('There are notices available regarding this plugin') }}" data-bind="visible: notifications && notifications.length"></i></div>
|
||||
<div data-bind="visible: notifications && notifications.length"><a href="javascript:void(0)" class="text-error" style="text-decoration: underline" data-bind="click: function() { $root.showPluginNotifications($data) }, text: $root.showPluginNotificationsLinkText($data)"></a></div>
|
||||
<div><small class="muted" data-bind="text: description"> </small></div>
|
||||
<div data-bind="css: {muted: !enabled}">
|
||||
<small data-bind="visible: url"><i class="icon-home"></i> <a data-bind="attr: {href: url}" target="_blank" rel="noreferrer noopener">{{ _('Homepage') }}</a></small>
|
||||
<small data-bind="visible: license"><i class="icon-legal"></i> <span data-bind="text: license"></span></small>
|
||||
<small data-bind="visible: author"><i class="icon-user"></i> <span data-bind="text: author"></span></small>
|
||||
<small data-bind="visible: url"><i class="fa fa-home"></i> <a data-bind="attr: {href: url}" target="_blank" rel="noreferrer noopener">{{ _('Homepage') }}</a></small>
|
||||
<small data-bind="visible: license"><i class="fa fa-gavel"></i> <span data-bind="text: license"></span></small>
|
||||
<small data-bind="visible: author"><i class="fa fa-user"></i> <span data-bind="text: author"></span></small>
|
||||
<small> </small>
|
||||
</div>
|
||||
</td>
|
||||
<td class="settings_plugin_plugin_manager_plugins_actions">
|
||||
<a href="#" data-bind="css: $root.toggleButtonCss($data), attr: {title: $root.toggleButtonTitle($data)}, enable: $root.enableToggle($data), click: function() { $root.togglePlugin($data) }"></a> | <a href="#" class="icon-trash" title="{{ _('Uninstall Plugin') }}" data-bind="css: {disabled: !$root.enableUninstall($data)}, enable: $root.enableUninstall($data), 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="fa fa-trash-o" title="{{ _('Uninstall Plugin') }}" data-bind="css: {disabled: !$root.enableUninstall($data)}, enable: $root.enableUninstall($data), click: function() { $root.uninstallPlugin($data) }"></a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
@@ -73,8 +80,8 @@
|
||||
<div class="muted" data-bind="visible: pipAvailable()">
|
||||
<div>
|
||||
<small>
|
||||
<a href="javascript:void(0)" class="muted" onclick="$(this).children('i.toggle-arrow').toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')">
|
||||
<i class="toggle-arrow icon-caret-right"></i> Using pip of "<span data-bind="text: pipPython"></span>", Version <span data-bind="text: pipVersion"></span>
|
||||
<a href="javascript:void(0)" class="muted" onclick="$(this).children('i.toggle-arrow').toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')">
|
||||
<i class="fa toggle-arrow fa-caret-right"></i> Using pip of "<span data-bind="text: pipPython"></span>", Version <span data-bind="text: pipVersion"></span>
|
||||
</a>
|
||||
</small>
|
||||
</div>
|
||||
@@ -90,8 +97,8 @@
|
||||
<div class="muted">
|
||||
<div>
|
||||
<small>
|
||||
<a href="javascript:void(0)" class="muted" onclick="$(this).children('i.toggle-arrow').toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')">
|
||||
<i class="toggle-arrow icon-caret-right"></i> <span data-bind="text: noticeCountText"></span>
|
||||
<a href="javascript:void(0)" class="muted" onclick="$(this).children('i.toggle-arrow').toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')">
|
||||
<i class="toggle-arrow fa fa-caret-right"></i> <span data-bind="text: noticeCountText"></span>
|
||||
</a>
|
||||
</small>
|
||||
</div>
|
||||
@@ -108,7 +115,7 @@
|
||||
<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', call: stream == 'call', message: stream == 'message', error: stream == 'error'}"></span></pre>
|
||||
<pre id="settings_plugin_pluginmanager_workingdialog_output" class="pre-scrollable pre-output" 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', error: stream == 'error'}"></span></pre>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" data-bind="enable: !$root.working()" aria-hidden="true">{{ _('Close') }}</button>
|
||||
@@ -124,20 +131,21 @@
|
||||
{{ pluginmanager_printing() }}
|
||||
{{ pluginmanager_nopip() }}
|
||||
{{ pluginmanager_safemode() }}
|
||||
{{ pluginmanager_offline() }}
|
||||
<h4 style="position: relative">
|
||||
{{ _('... from the <a href="%(url)s" target="_blank">Plugin Repository</a>', url='http://plugins.octoprint.org') }}
|
||||
<div class="dropdown pull-right">
|
||||
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
|
||||
<span class="icon-wrench"></span>
|
||||
<span class="fa fa-wrench"></span>
|
||||
</a>
|
||||
<ul class="dropdown-menu pull-right">
|
||||
<li><a href="#" data-bind="click: function() { repositoryplugins.changeSorting('title'); }"><i class="icon-ok" data-bind="style: {visibility: repositoryplugins.currentSorting() == 'title' ? 'visible' : 'hidden'}"></i> {{ _('Sort by title') }} ({{ _('ascending') }})</a></li>
|
||||
<li><a href="#" data-bind="click: function() { repositoryplugins.changeSorting('published'); }"><i class="icon-ok" data-bind="style: {visibility: repositoryplugins.currentSorting() == 'published' ? 'visible' : 'hidden'}"></i> {{ _('Sort by publication date') }} ({{ _('descending') }})</a></li>
|
||||
<li><a href="#" data-bind="click: function() { repositoryplugins.changeSorting('title'); }"><i class="fa fa-check" data-bind="style: {visibility: repositoryplugins.currentSorting() == 'title' ? 'visible' : 'hidden'}"></i> {{ _('Sort by title') }} ({{ _('ascending') }})</a></li>
|
||||
<li><a href="#" data-bind="click: function() { repositoryplugins.changeSorting('published'); }"><i class="fa fa-check" data-bind="style: {visibility: repositoryplugins.currentSorting() == 'published' ? 'visible' : 'hidden'}"></i> {{ _('Sort by publication date') }} ({{ _('descending') }})</a></li>
|
||||
<li class="divider"></li>
|
||||
<li><a href="#" data-bind="click: function() { repositoryplugins.toggleFilter('filter_installed'); }"><i class="icon-ok" data-bind="style: {visibility: _.contains(repositoryplugins.currentFilters(), 'filter_installed') ? 'visible' : 'hidden'}"></i> {{ _('Only show uninstalled plugins') }}</a></li>
|
||||
<li><a href="#" data-bind="click: function() { repositoryplugins.toggleFilter('filter_incompatible'); }"><i class="icon-ok" data-bind="style: {visibility: _.contains(repositoryplugins.currentFilters(), 'filter_incompatible') ? 'visible' : 'hidden'}"></i> {{ _('Only show compatible plugins') }}</a></li>
|
||||
<li><a href="#" data-bind="click: function() { repositoryplugins.toggleFilter('filter_installed'); }"><i class="fa fa-check" data-bind="style: {visibility: _.contains(repositoryplugins.currentFilters(), 'filter_installed') ? 'visible' : 'hidden'}"></i> {{ _('Only show uninstalled plugins') }}</a></li>
|
||||
<li><a href="#" data-bind="click: function() { repositoryplugins.toggleFilter('filter_incompatible'); }"><i class="fa fa-check" data-bind="style: {visibility: _.contains(repositoryplugins.currentFilters(), 'filter_incompatible') ? 'visible' : 'hidden'}"></i> {{ _('Only show compatible plugins') }}</a></li>
|
||||
<li class="divider"></li>
|
||||
<li><a href="#" data-bind="click: function() { refreshRepository(); }"><i class="icon-refresh"></i> {{ _('Refresh list from repository') }}</a></li>
|
||||
<li><a href="#" data-bind="click: function() { refreshRepository(); }"><i class="fa fa-refresh"></i> {{ _('Refresh list from repository') }}</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</h4>
|
||||
@@ -154,15 +162,15 @@
|
||||
<div><span data-bind="text: title"></span></div>
|
||||
<div><small class="muted" data-bind="text: description"> </small></div>
|
||||
<div>
|
||||
<small data-bind="visible: page"><i class="icon-info"></i> <a data-bind="attr: {href: page}" target="_blank">{{ _('Details') }}</a></small>
|
||||
<small data-bind="visible: homepage"><i class="icon-home"></i> <a data-bind="attr: {href: homepage}" target="_blank">{{ _('Homepage') }}</a></small>
|
||||
<small data-bind="visible: license"><i class="icon-legal"></i> <span data-bind="text: license"></span></small>
|
||||
<small data-bind="visible: author"><i class="icon-user"></i> <span data-bind="text: author"></span></small>
|
||||
<small data-bind="visible: page"><i class="fa fa-info"></i> <a data-bind="attr: {href: page}" target="_blank">{{ _('Details') }}</a></small>
|
||||
<small data-bind="visible: homepage"><i class="fa fa-home"></i> <a data-bind="attr: {href: homepage}" target="_blank">{{ _('Homepage') }}</a></small>
|
||||
<small data-bind="visible: license"><i class="fa fa-gavel"></i> <span data-bind="text: license"></span></small>
|
||||
<small data-bind="visible: author"><i class="fa fa-user"></i> <span data-bind="text: author"></span></small>
|
||||
<small> </small>
|
||||
</div>
|
||||
</div>
|
||||
<div class="span3">
|
||||
<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>
|
||||
<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="fa fa-add"></i> <span data-bind="text: $root.installButtonText($data)"></span></button>
|
||||
<div data-bind="visible: $data.disabled !== undefined" style="text-align: center"><small><a data-bind="attr: {href: page}" target="_blank">{{ _('"Why?"') }}</a></small></div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -209,7 +217,7 @@
|
||||
</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><small><a href="#" class="muted" onclick="$(this).children().toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="fa fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
|
||||
<div class="hide">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
|
||||
@@ -15,6 +15,9 @@ import time
|
||||
import logging
|
||||
import logging.handlers
|
||||
import hashlib
|
||||
import traceback
|
||||
|
||||
from concurrent import futures
|
||||
|
||||
from . import version_checks, updaters, exceptions, util, cli
|
||||
|
||||
@@ -34,7 +37,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.StartupPlugin,
|
||||
octoprint.plugin.WizardPlugin):
|
||||
octoprint.plugin.WizardPlugin,
|
||||
octoprint.plugin.EventHandlerPlugin):
|
||||
|
||||
COMMIT_TRACKING_TYPES = ("github_commit", "bitbucket_commit")
|
||||
|
||||
@@ -44,7 +48,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._configured_checks = None
|
||||
self._refresh_configured_checks = False
|
||||
|
||||
self._get_versions_mutex = threading.Lock()
|
||||
self._get_versions_mutex = threading.RLock()
|
||||
self._get_versions_data = None
|
||||
self._get_versions_data_ready = threading.Event()
|
||||
|
||||
self._version_cache = dict()
|
||||
self._version_cache_ttl = 0
|
||||
@@ -218,9 +224,13 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
"repo": "OctoPrint",
|
||||
"update_script": "{{python}} \"{update_script}\" --branch={{branch}} --force={{force}} \"{{folder}}\" {{target}}".format(update_script=update_script),
|
||||
"restart": "octoprint",
|
||||
"stable_branch": dict(branch="master", name="Stable"),
|
||||
"prerelease_branches": [dict(branch="rc/maintenance", name="Maintenance RCs"),
|
||||
dict(branch="rc/devel", name="Devel RCs")]
|
||||
"stable_branch": dict(branch="master", commitish=["master"], name="Stable"),
|
||||
"prerelease_branches": [dict(branch="rc/maintenance",
|
||||
commitish=["rc/maintenance"], # maintenance RCs
|
||||
name="Maintenance RCs"),
|
||||
dict(branch="rc/devel",
|
||||
commitish=["rc/maintenance", "rc/devel"], # devel & maintenance RCs
|
||||
name="Devel RCs")]
|
||||
},
|
||||
},
|
||||
"pip_command": None,
|
||||
@@ -463,15 +473,6 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
def view():
|
||||
try:
|
||||
information, update_available, update_possible = self.get_current_versions(check_targets=check_targets, force=force)
|
||||
|
||||
# we don't want to transfer python_checker or python_updater values through json - replace with True
|
||||
for key, data in information.items():
|
||||
if "check" in data:
|
||||
if "python_checker" in data["check"]:
|
||||
data["check"]["python_checker"] = True
|
||||
if "python_updater" in data["check"]:
|
||||
data["check"]["python_updater"] = True
|
||||
|
||||
return flask.jsonify(dict(status="updatePossible" if update_available and update_possible else "updateAvailable" if update_available else "current",
|
||||
information=information,
|
||||
timestamp=self._version_cache_timestamp))
|
||||
@@ -498,9 +499,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
hash.update(repr(data["information"]))
|
||||
hash.update(str(data["available"]))
|
||||
hash.update(str(data["possible"]))
|
||||
hash.update(str(data.get("online", None)))
|
||||
|
||||
hash.update(",".join(targets))
|
||||
hash.update(str(self._version_cache_timestamp))
|
||||
hash.update(str(self._connectivity_checker.online))
|
||||
return hash.hexdigest()
|
||||
|
||||
def condition():
|
||||
@@ -562,6 +565,17 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
checkout_folder = self._get_octoprint_checkout_folder(checks=checks)
|
||||
return check and "update_script" in check and not checkout_folder
|
||||
|
||||
##~~ EventHandlerPlugin API
|
||||
|
||||
def on_event(self, event, payload):
|
||||
from octoprint.events import Events
|
||||
if event != Events.CONNECTIVITY_CHANGED or not payload or not payload.get("new", False):
|
||||
return
|
||||
|
||||
thread = threading.Thread(target=self.get_current_versions)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
#~~ Updater
|
||||
|
||||
def get_current_versions(self, check_targets=None, force=False):
|
||||
@@ -581,53 +595,91 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
information = dict()
|
||||
|
||||
# we don't want to do the same work twice, so let's use a lock
|
||||
with self._get_versions_mutex:
|
||||
for target, check in checks.items():
|
||||
if not target in check_targets:
|
||||
continue
|
||||
if self._get_versions_mutex.acquire(False):
|
||||
self._get_versions_data_ready.clear()
|
||||
try:
|
||||
futures_to_result = dict()
|
||||
online = self._connectivity_checker.check_immediately()
|
||||
self._logger.debug("Looks like we are {}".format("online" if online else "offline"))
|
||||
|
||||
if not check:
|
||||
continue
|
||||
with futures.ThreadPoolExecutor(max_workers=5) as executor:
|
||||
for target, check in checks.items():
|
||||
if not target in check_targets:
|
||||
continue
|
||||
|
||||
try:
|
||||
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:
|
||||
target_information = dict()
|
||||
except exceptions.UnknownCheckType:
|
||||
self._logger.warn("Unknown update check type for target {}: {}".format(target, check.get("type", "<n/a>")))
|
||||
continue
|
||||
if not check:
|
||||
continue
|
||||
|
||||
target_information = dict_merge(dict(local=dict(name="unknown", value="unknown"), remote=dict(name="unknown", value="unknown", release_notes=None)), target_information)
|
||||
try:
|
||||
populated_check = self._populated_check(target, check)
|
||||
future = executor.submit(self._get_current_version, target, populated_check, force=force)
|
||||
futures_to_result[future] = (target, populated_check)
|
||||
except exceptions.UnknownCheckType:
|
||||
self._logger.warn("Unknown update check type for target {}: {}".format(target,
|
||||
check.get("type",
|
||||
"<n/a>")))
|
||||
continue
|
||||
except:
|
||||
self._logger.exception("Could not check {} for updates".format(target))
|
||||
continue
|
||||
|
||||
update_available = update_available or target_update_available
|
||||
update_possible = update_possible or (target_update_possible and target_update_available)
|
||||
for future in futures.as_completed(futures_to_result):
|
||||
|
||||
local_name = target_information["local"]["name"]
|
||||
local_value = target_information["local"]["value"]
|
||||
target, populated_check = futures_to_result[future]
|
||||
if future.exception() is not None:
|
||||
self._logger.error("Could not check {} for updates, error: {!r}".format(target,
|
||||
future.exception()))
|
||||
continue
|
||||
|
||||
release_notes = None
|
||||
if target_information and target_information["remote"] and target_information["remote"]["value"]:
|
||||
if "release_notes" in populated_check and populated_check["release_notes"]:
|
||||
release_notes = populated_check["release_notes"]
|
||||
elif "release_notes" in target_information["remote"]:
|
||||
release_notes = target_information["remote"]["release_notes"]
|
||||
target_information, target_update_available, target_update_possible, target_online, target_error = future.result()
|
||||
|
||||
if release_notes:
|
||||
release_notes = release_notes.format(octoprint_version=VERSION,
|
||||
target_name=target_information["remote"]["name"],
|
||||
target_version=target_information["remote"]["value"])
|
||||
target_information = dict_merge(dict(local=dict(name="?", value="?"),
|
||||
remote=dict(name="?", value="?",
|
||||
release_notes=None),
|
||||
needs_online=True), target_information)
|
||||
|
||||
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=VERSION, local_name=local_name, local_value=local_value),
|
||||
check=populated_check,
|
||||
releaseNotes=release_notes)
|
||||
update_available = update_available or target_update_available
|
||||
update_possible = update_possible or (target_update_possible and target_update_available)
|
||||
|
||||
local_name = target_information["local"]["name"]
|
||||
local_value = target_information["local"]["value"]
|
||||
|
||||
release_notes = None
|
||||
if target_information and target_information["remote"] and target_information["remote"][
|
||||
"value"]:
|
||||
if "release_notes" in populated_check and populated_check["release_notes"]:
|
||||
release_notes = populated_check["release_notes"]
|
||||
elif "release_notes" in target_information["remote"]:
|
||||
release_notes = target_information["remote"]["release_notes"]
|
||||
|
||||
if release_notes:
|
||||
release_notes = release_notes.format(octoprint_version=VERSION,
|
||||
target_name=target_information["remote"]["name"],
|
||||
target_version=target_information["remote"]["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=VERSION,
|
||||
local_name=local_name,
|
||||
local_value=local_value),
|
||||
releaseNotes=release_notes,
|
||||
online=target_online,
|
||||
error=target_error)
|
||||
|
||||
if self._version_cache_dirty:
|
||||
self._save_version_cache()
|
||||
|
||||
self._get_versions_data = information, update_available, update_possible
|
||||
self._get_versions_data_ready.set()
|
||||
finally:
|
||||
self._get_versions_mutex.release()
|
||||
|
||||
else: # something's already in progress, let's wait for it to complete and use its result
|
||||
self._get_versions_data_ready.wait()
|
||||
information, update_available, update_possible = self._get_versions_data
|
||||
|
||||
if self._version_cache_dirty:
|
||||
self._save_version_cache()
|
||||
return information, update_available, update_possible
|
||||
|
||||
def _get_check_hash(self, check):
|
||||
@@ -646,36 +698,50 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
hash.update(dict_to_sorted_repr(check))
|
||||
return hash.hexdigest()
|
||||
|
||||
def _get_current_version(self, target, check, force=False):
|
||||
def _get_current_version(self, target, check, force=False, online=None):
|
||||
"""
|
||||
Determines the current version information for one target based on its check configuration.
|
||||
"""
|
||||
|
||||
current_hash = self._get_check_hash(check)
|
||||
if online is None:
|
||||
online = self._connectivity_checker.online
|
||||
if target in self._version_cache and not force:
|
||||
data = self._version_cache[target]
|
||||
if data["hash"] == current_hash and data["timestamp"] + self._version_cache_ttl >= time.time() > data["timestamp"]:
|
||||
if data["hash"] == current_hash \
|
||||
and data["timestamp"] + self._version_cache_ttl >= time.time() > data["timestamp"] \
|
||||
and data.get("online", None) == online:
|
||||
# we also check that timestamp < now to not get confused too much by clock changes
|
||||
return data["information"], data["available"], data["possible"]
|
||||
return data["information"], data["available"], data["possible"], data["online"], data.get("error", None)
|
||||
|
||||
information = dict()
|
||||
update_available = False
|
||||
error = None
|
||||
|
||||
try:
|
||||
version_checker = self._get_version_checker(target, check)
|
||||
information, is_current = version_checker.get_latest(target, check)
|
||||
information, is_current = version_checker.get_latest(target, check, online=online)
|
||||
if information is not None and not is_current:
|
||||
update_available = True
|
||||
except exceptions.CannotCheckOffline:
|
||||
update_possible = False
|
||||
information["needs_online"] = True
|
||||
except exceptions.UnknownCheckType:
|
||||
self._logger.warn("Unknown check type %s for %s" % (check["type"], target))
|
||||
update_possible = False
|
||||
error = "unknown_check"
|
||||
except exceptions.NetworkError:
|
||||
self._logger.warn("Could not check %s for updates due to a network error" % target)
|
||||
update_possible = False
|
||||
error = "network"
|
||||
except:
|
||||
self._logger.exception("Could not check %s for updates" % target)
|
||||
update_possible = False
|
||||
error = "unknown"
|
||||
else:
|
||||
try:
|
||||
updater = self._get_updater(target, check)
|
||||
update_possible = updater.can_perform_update(target, check)
|
||||
update_possible = updater.can_perform_update(target, check, online=online)
|
||||
except:
|
||||
update_possible = False
|
||||
|
||||
@@ -683,9 +749,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
hash=current_hash,
|
||||
information=information,
|
||||
available=update_available,
|
||||
possible=update_possible)
|
||||
possible=update_possible,
|
||||
online=online,
|
||||
error=error)
|
||||
self._version_cache_dirty = True
|
||||
return information, update_available, update_possible
|
||||
return information, update_available, update_possible, online, error
|
||||
|
||||
def perform_updates(self, check_targets=None, force=False):
|
||||
"""
|
||||
@@ -797,7 +865,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._send_client_message("success", dict(results=target_results))
|
||||
|
||||
def _perform_update(self, target, check, force):
|
||||
information, update_available, update_possible = self._get_current_version(target, check)
|
||||
online = self._connectivity_checker.online
|
||||
|
||||
information, update_available, update_possible, _, _ = self._get_current_version(target, check, online=online)
|
||||
|
||||
if not update_available and not force:
|
||||
return False, None
|
||||
@@ -820,7 +890,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
if updater is None:
|
||||
raise exceptions.UnknownUpdateType()
|
||||
|
||||
update_result = updater.perform_update(target, populated_check, target_version, log_cb=self._log)
|
||||
update_result = updater.perform_update(target, populated_check, target_version, log_cb=self._log, online=online)
|
||||
target_result = ("success", update_result)
|
||||
self._logger.info("Update of %s to %s successful!" % (target, target_version))
|
||||
|
||||
@@ -829,6 +899,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._send_client_message("update_failed", dict(target=target, version=target_version, name=populated_check["displayName"], reason="Unknown update type"))
|
||||
return False, None
|
||||
|
||||
except exceptions.CannotUpdateOffline:
|
||||
self._logger.warn("Update of %s can not be performed, it's not marked as 'offline' capable but we are apparently offline right now" % target)
|
||||
self._send_client_message("update_failed", dict(target=target, version=target_version, name=populated_check["displayName"], reason="No internet connection"))
|
||||
|
||||
except Exception as e:
|
||||
self._logger.exception("Update of %s can not be performed" % target)
|
||||
if not "ignorable" in populated_check or not populated_check["ignorable"]:
|
||||
@@ -868,7 +942,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
self._logger.info("Restarting...")
|
||||
try:
|
||||
util.execute(restart_command)
|
||||
util.execute(restart_command, evaluate_returncode=False, async=True)
|
||||
except exceptions.ScriptError as e:
|
||||
self._logger.exception("Error while restarting via command {}".format(restart_command))
|
||||
self._logger.warn("Restart stdout:\n{}".format(e.stdout))
|
||||
@@ -917,8 +991,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
result["force_base"] = False
|
||||
|
||||
if check.get("update_script", None):
|
||||
# if we are using the update_script, we need to set our update_branch and force
|
||||
# to install the exact version we requested
|
||||
# if we are using the update_script, we need to set our update_branch
|
||||
|
||||
if check.get("prerelease", None):
|
||||
# we are tracking prereleases => we want to be on the correct prerelease channel/branch
|
||||
@@ -928,14 +1001,13 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
# in case it's not already set
|
||||
result["update_branch"] = check.get("update_branch", channel)
|
||||
|
||||
# we also force our target version in the update
|
||||
result["force_exact_version"] = True
|
||||
|
||||
else:
|
||||
# we are not tracking prereleases, but aren't on the stable branch either => switch back
|
||||
# to stable branch on update
|
||||
result["update_branch"] = check.get("update_branch", stable_branch)
|
||||
|
||||
# we also force an exact version
|
||||
result["force_exact_version"] = True
|
||||
|
||||
if BRANCH != result.get("prerelease_channel"):
|
||||
# we force python unequality check here because that will also allow us to
|
||||
|
||||
@@ -9,12 +9,14 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
import click
|
||||
import sys
|
||||
import requests.exceptions
|
||||
import octoprint_client as client
|
||||
from octoprint.cli.client import create_client, client_options
|
||||
|
||||
@click.command("check")
|
||||
@click.option("--force", is_flag=True, help="Ignore the cache for the update check")
|
||||
@click.option("--only-new", is_flag=True, help="Only show entries with updates available")
|
||||
@client_options
|
||||
@click.argument("targets", nargs=-1)
|
||||
def check_command(force, targets):
|
||||
def check_command(force, only_new, apikey, host, port, httpuser, httppass, https, prefix, targets):
|
||||
"""
|
||||
Check for updates.
|
||||
|
||||
@@ -37,7 +39,15 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
if targets:
|
||||
params["check"] = ",".join(targets)
|
||||
|
||||
client.init_client(cli_group.settings)
|
||||
client = create_client(settings=cli_group.settings,
|
||||
apikey=apikey,
|
||||
host=host,
|
||||
port=port,
|
||||
httpuser=httpuser,
|
||||
httppass=httppass,
|
||||
https=https,
|
||||
prefix=prefix)
|
||||
|
||||
r = client.get("plugin/softwareupdate/check", params=params)
|
||||
try:
|
||||
r.raise_for_status()
|
||||
@@ -58,10 +68,15 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
status_text = "Update available"
|
||||
else:
|
||||
status_text = "Update available (manual)"
|
||||
line = "{}\n\tInstalled: {}\n\tAvailable: {}\n\t=> {}".format(info["displayName"],
|
||||
info["information"]["local"]["name"],
|
||||
info["information"]["remote"]["name"],
|
||||
status_text)
|
||||
|
||||
elif only_new:
|
||||
continue
|
||||
|
||||
line = "{} (target: {})\n\tInstalled: {}\n\tAvailable: {}\n\t=> {}".format(info["displayName"],
|
||||
key,
|
||||
info["information"]["local"]["name"],
|
||||
info["information"]["remote"]["name"],
|
||||
status_text)
|
||||
if key == "octoprint":
|
||||
octoprint_line = line
|
||||
else:
|
||||
@@ -83,8 +98,9 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
|
||||
@click.command("update")
|
||||
@click.option("--force", is_flag=True, help="Update even if already up to date")
|
||||
@client_options
|
||||
@click.argument("targets", nargs=-1)
|
||||
def update_command(force, targets):
|
||||
def update_command(force, apikey, host, port, httpuser, httppass, https, prefix, targets):
|
||||
"""
|
||||
Apply updates.
|
||||
|
||||
@@ -108,7 +124,13 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
if targets:
|
||||
data["check"] = targets
|
||||
|
||||
client.init_client(cli_group.settings)
|
||||
client = create_client(apikey=apikey,
|
||||
host=host,
|
||||
port=port,
|
||||
httpuser=httpuser,
|
||||
httppass=httppass,
|
||||
https=https,
|
||||
prefix=prefix)
|
||||
|
||||
flags = dict(
|
||||
waiting_for_restart=False,
|
||||
|
||||
@@ -18,6 +18,20 @@ class UnknownUpdateType(Exception):
|
||||
class UnknownCheckType(Exception):
|
||||
pass
|
||||
|
||||
class NetworkError(Exception):
|
||||
def __init__(self, message=None, cause=None):
|
||||
Exception.__init__(self)
|
||||
self.message = message
|
||||
self.cause = cause
|
||||
|
||||
def __str__(self):
|
||||
if self.message is not None:
|
||||
return self.message
|
||||
elif self.cause is not None:
|
||||
return "NetworkError caused by {}".format(self.cause)
|
||||
else:
|
||||
return "NetworkError"
|
||||
|
||||
class UpdateError(Exception):
|
||||
def __init__(self, message, data):
|
||||
self.message = message
|
||||
@@ -35,3 +49,8 @@ class RestartFailed(Exception):
|
||||
class ConfigurationInvalid(Exception):
|
||||
pass
|
||||
|
||||
class CannotCheckOffline(Exception):
|
||||
pass
|
||||
|
||||
class CannotUpdateOffline(Exception):
|
||||
pass
|
||||
@@ -1 +1 @@
|
||||
td.settings_plugin_softwareupdate_column_update{width:16px}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output span{display:block}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
|
||||
td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_information .line{display:block}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
|
||||
@@ -123,8 +123,9 @@ $(function() {
|
||||
self.config_updateMethod = ko.observable();
|
||||
self.config_releaseChannel = ko.observable();
|
||||
|
||||
self.configurationDialog = $("#settings_plugin_softwareupdate_configurationdialog");
|
||||
self.confirmationDialog = $("#softwareupdate_confirmation_dialog");
|
||||
self.configurationDialog = undefined;
|
||||
self.confirmationDialog = undefined;
|
||||
self._updateClicked = false;
|
||||
|
||||
self.config_availableCheckTypes = ko.observableArray([]);
|
||||
self.config_availableReleaseChannels = ko.observableArray([]);
|
||||
@@ -203,7 +204,7 @@ $(function() {
|
||||
|
||||
self.savePluginSettings = function(viewModel, event) {
|
||||
var target = $(event.target);
|
||||
target.prepend('<i class="icon-spinner icon-spin"></i> ');
|
||||
target.prepend('<i class="fa fa-spinner fa-spin"></i> ');
|
||||
|
||||
var data = {
|
||||
plugins: {
|
||||
@@ -223,7 +224,7 @@ $(function() {
|
||||
self.performCheck();
|
||||
},
|
||||
complete: function() {
|
||||
$("i.icon-spinner", target).remove();
|
||||
$("i.fa-spinner", target).remove();
|
||||
},
|
||||
sending: true
|
||||
});
|
||||
@@ -314,11 +315,11 @@ $(function() {
|
||||
if (data.status == "updateAvailable" || data.status == "updatePossible") {
|
||||
var text = "<div class='softwareupdate_notification'>" + gettext("There are updates available for the following components:");
|
||||
|
||||
text += "<ul class='icons-ul'>";
|
||||
text += "<ul class='fa-ul'>";
|
||||
_.each(self.versions.items(), function(update_info) {
|
||||
if (update_info.updateAvailable) {
|
||||
text += "<li>"
|
||||
+ "<i class='icon-li " + (update_info.updatePossible ? "icon-ok" : "icon-remove")+ "'></i>"
|
||||
+ "<i class='fa fa-li " + (update_info.updatePossible ? "fa-check" : "fa-remove")+ "'></i>"
|
||||
+ "<span class='name' title='" + update_info.fullNameRemote + "'>" + update_info.fullNameRemote + "</span>"
|
||||
+ (update_info.releaseNotes ? "<a href=\"" + update_info.releaseNotes + "\" target=\"_blank\">" + gettext("Release Notes") + "</a>" : "")
|
||||
+ "</li>";
|
||||
@@ -326,7 +327,7 @@ $(function() {
|
||||
});
|
||||
text += "</ul>";
|
||||
|
||||
text += "<p><small>" + gettext("Those components marked with <i class=\"icon-ok\"></i> can be updated directly.") + "</small></p>";
|
||||
text += "<p><small>" + gettext("Those components marked with <i class=\"fa fa-check\"></i> can be updated directly.") + "</small></p>";
|
||||
|
||||
if (!self.loginState.isAdmin()) {
|
||||
text += "<p><small>" + gettext("To have updates applied, get in touch with an administrator of this OctoPrint instance.") + "</small></p>";
|
||||
@@ -357,7 +358,11 @@ $(function() {
|
||||
}, {
|
||||
text: gettext("Update now"),
|
||||
addClass: "btn-primary",
|
||||
click: self.update
|
||||
click: function() {
|
||||
if (self._updateClicked) return;
|
||||
self._updateClicked = true;
|
||||
self.update();
|
||||
}
|
||||
}]
|
||||
};
|
||||
options["buttons"] = {
|
||||
@@ -412,6 +417,42 @@ $(function() {
|
||||
});
|
||||
};
|
||||
|
||||
self.iconTitleForEntry = function(data) {
|
||||
if (data.updatePossible) {
|
||||
return "";
|
||||
} else if (!data.online && data.information && data.information.needs_online) {
|
||||
return gettext("No internet connection");
|
||||
} else if (data.error) {
|
||||
return self.errorTextForEntry(data);
|
||||
} else {
|
||||
return gettext("Update not possible");
|
||||
}
|
||||
};
|
||||
|
||||
self.errorTextForEntry = function(data) {
|
||||
if (!data.error) {
|
||||
return "";
|
||||
}
|
||||
|
||||
switch (data.error) {
|
||||
case "unknown_check": {
|
||||
return gettext("Unknown update check, configuration ok?");
|
||||
}
|
||||
case "needs_online": {
|
||||
return gettext("Cannot check for update, need online connection");
|
||||
}
|
||||
case "network": {
|
||||
return gettext("Network error while checking for update");
|
||||
}
|
||||
case "unknown": {
|
||||
return gettext("Unknown error while checking for update, please check the logs");
|
||||
}
|
||||
default: {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self._markNotificationAsSeen = function(data) {
|
||||
if (!Modernizr.localstorage)
|
||||
return false;
|
||||
@@ -472,7 +513,7 @@ $(function() {
|
||||
var options = {
|
||||
title: gettext("Updating..."),
|
||||
text: gettext("Now updating, please wait."),
|
||||
icon: "icon-cog icon-spin",
|
||||
icon: "fa fa-cog fa-spin",
|
||||
hide: false,
|
||||
buttons: {
|
||||
closer: false,
|
||||
@@ -501,8 +542,14 @@ $(function() {
|
||||
};
|
||||
|
||||
self.update = function(force) {
|
||||
if (self.updateInProgress) return;
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
if (self.updateInProgress) {
|
||||
self._updateClicked = false;
|
||||
return;
|
||||
}
|
||||
if (!self.loginState.isAdmin()) {
|
||||
self._updateClicked = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (self.printerState.isPrinting()) {
|
||||
self._showPopup({
|
||||
@@ -510,6 +557,7 @@ $(function() {
|
||||
text: gettext("A print job is currently in progress. Updating will be prevented until it is done."),
|
||||
type: "error"
|
||||
});
|
||||
self._updateClicked = false;
|
||||
} else {
|
||||
self.forceUpdate = (force == true);
|
||||
self.confirmationDialog.modal("show");
|
||||
@@ -518,9 +566,13 @@ $(function() {
|
||||
};
|
||||
|
||||
self.confirmUpdate = function() {
|
||||
self.confirmationDialog.modal("hide");
|
||||
self.performUpdate(self.forceUpdate,
|
||||
_.map(self.availableAndPossible(), function(info) { return info.key }));
|
||||
self.confirmationDialog.modal("hide");
|
||||
};
|
||||
|
||||
self.confirmationHidden = function() {
|
||||
self._updateClicked = false;
|
||||
};
|
||||
|
||||
self._showWorkingDialog = function(title) {
|
||||
@@ -578,6 +630,10 @@ $(function() {
|
||||
self.onStartup = function() {
|
||||
self.workingDialog = $("#settings_plugin_softwareupdate_workingdialog");
|
||||
self.workingOutput = $("#settings_plugin_softwareupdate_workingdialog_output");
|
||||
self.configurationDialog = $("#settings_plugin_softwareupdate_configurationdialog");
|
||||
self.confirmationDialog = $("#softwareupdate_confirmation_dialog");
|
||||
|
||||
self.confirmationDialog.on("hidden", self.confirmationHidden);
|
||||
};
|
||||
|
||||
self.onServerDisconnect = function() {
|
||||
@@ -587,6 +643,11 @@ $(function() {
|
||||
return true;
|
||||
};
|
||||
|
||||
self.onEventConnectivityChanged = function(payload) {
|
||||
if (!payload || !payload.new) return;
|
||||
self.performCheck();
|
||||
};
|
||||
|
||||
self.onDataUpdaterReconnect = function() {
|
||||
if (self.waitingForRestart) {
|
||||
self.waitingForRestart = false;
|
||||
|
||||
@@ -2,12 +2,14 @@ td.settings_plugin_softwareupdate_column_update {
|
||||
width: 16px;
|
||||
}
|
||||
|
||||
#settings_plugin_softwareupdate_workingdialog_output {
|
||||
font-size: 0.8em;
|
||||
|
||||
span {
|
||||
td.settings_plugin_softwareupdate_column_information {
|
||||
.line {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
#settings_plugin_softwareupdate_workingdialog_output {
|
||||
font-size: 0.8em;
|
||||
|
||||
.message {
|
||||
font-weight: bold;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<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
|
||||
this plugin won't be able to update it. Click on the <i class="fa fa-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 %}
|
||||
@@ -17,7 +17,7 @@
|
||||
{% 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>
|
||||
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="fa fa-wrench"></i></button>
|
||||
</div>
|
||||
|
||||
<h3>{{ _('Current versions') }}</h3>
|
||||
@@ -26,14 +26,15 @@
|
||||
<tbody data-bind="foreach: versions.paginatedItems">
|
||||
<tr data-bind="attr: {title: displayName}">
|
||||
<td class="settings_plugin_softwareupdate_column_update">
|
||||
<span data-bind="invisible: !updateAvailable"><i class="icon-bell" title="{{ _('Update available') }}"></i></span>
|
||||
<span data-bind="invisible: !updateAvailable"><i class="fa fa-bell-o" 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> <span data-bind="invisible: updatePossible"><i class="icon-exclamation-sign" title="{{ _('Update not possible, configuration ok?') }}"></i></span><br>
|
||||
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span> <span data-bind="invisible: updatePossible"><i class="fa fa-exclamation-triangle" data-bind="css: {'fa-unlink': !online && information && information.needs_online, 'fa-exclamation-triangle': !(!online && information && information.needs_online)}, attr: {title: $root.iconTitleForEntry($data)}"></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><br>
|
||||
<span data-bind="visible: releaseNotes">{{ _('Release Notes:') }} <a data-bind="attr: {href: releaseNotes}, text: releaseNotes" target="_blank" rel="noreferrer noopener"></a></span>
|
||||
<span class="line">{{ _('Installed:') }} <span data-bind="text: information.local.name"></span></span>
|
||||
<span class="line">{{ _('Available:') }} <span data-bind="text: information.remote.name"></span></span>
|
||||
<span class="line" data-bind="visible: releaseNotes">{{ _('Release Notes:') }} <a data-bind="attr: {href: releaseNotes}, text: releaseNotes" target="_blank" rel="noreferrer noopener"></a></span>
|
||||
<span class="line text-error" data-bind="visible: error, text: $root.errorTextForEntry($data)"></span>
|
||||
</small>
|
||||
</td>
|
||||
</tr>
|
||||
@@ -57,14 +58,14 @@
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<button class="btn btn-primary btn-block" data-bind="click: function() { $root.performCheck(true, false, true); }, enable: !checking(), css: {disabled: checking()}"><i class="icon-spinner icon-spin" data-bind="visible: checking"></i> {{ _('Check for update now') }}</button>
|
||||
<button class="btn btn-primary btn-block" data-bind="click: function() { $root.performCheck(true, false, true); }, enable: !checking(), css: {disabled: checking()}"><i class="fa fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Check for update now') }}</button>
|
||||
|
||||
<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><small><a href="#" class="muted" onclick="$(this).children().toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="fa fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
|
||||
<div class="hide">
|
||||
<small class="muted" style="display: block">{{ _('Last cache refresh:') }} <span data-bind="text: cacheTimestampText"></span></small>
|
||||
<button class="btn btn-block" data-bind="click: function() { $root.performCheck(true, true, true); }, enable: !checking(), css: {disabled: checking()}"><i class="icon-spinner icon-spin" data-bind="visible: checking"></i> {{ _('Force check for update (overrides cache used for update checks)') }}</button>
|
||||
<button class="btn btn-block btn-danger" data-bind="visible: CONFIG_DEBUG, click: function() { $root.update(true); }, enable: !checking(), css: {disabled: checking()}"><i class="icon-spinner icon-spin" data-bind="visible: checking"></i> {{ _('Force update now (even if no new versions are available)') }}</button>
|
||||
<button class="btn btn-block" data-bind="click: function() { $root.performCheck(true, true, true); }, enable: !checking(), css: {disabled: checking()}"><i class="fa fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Force check for update (overrides cache used for update checks)') }}</button>
|
||||
<button class="btn btn-block btn-danger" data-bind="visible: CONFIG_DEBUG, click: function() { $root.update(true); }, enable: !checking(), css: {disabled: checking()}"><i class="fa fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Force update now (even if no new versions are available)') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -108,7 +109,7 @@
|
||||
<h3 data-bind="text: workingTitle"></h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<pre id="settings_plugin_softwareupdate_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></pre>
|
||||
<pre id="settings_plugin_softwareupdate_workingdialog_output" class="pre-scrollable pre-output" 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></pre>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" data-bind="enable: !$root.working()" aria-hidden="true">{{ _('Close') }}</button>
|
||||
|
||||
@@ -18,9 +18,9 @@ console_logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pi
|
||||
_pip_callers = dict()
|
||||
_pip_version_dependency_links = pkg_resources.parse_version("1.5")
|
||||
|
||||
def can_perform_update(target, check):
|
||||
def can_perform_update(target, check, online=True):
|
||||
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
|
||||
return "pip" in check and pip_caller is not None and pip_caller.available and (online or check.get("offline", False))
|
||||
|
||||
def _get_pip_caller(command=None):
|
||||
key = command
|
||||
@@ -35,11 +35,14 @@ def _get_pip_caller(command=None):
|
||||
|
||||
return _pip_callers[key]
|
||||
|
||||
def perform_update(target, check, target_version, log_cb=None):
|
||||
def perform_update(target, check, target_version, log_cb=None, online=True):
|
||||
pip_command = None
|
||||
if "pip_command" in check:
|
||||
pip_command = check["pip_command"]
|
||||
|
||||
if not online and not check.get("offline", False):
|
||||
raise exceptions.CannotUpdateOffline()
|
||||
|
||||
pip_caller = _get_pip_caller(command=pip_command)
|
||||
if pip_caller is None:
|
||||
raise exceptions.UpdateError("Can't run pip", None)
|
||||
|
||||
@@ -6,9 +6,24 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
def can_perform_update(target, check):
|
||||
return "python_updater" in check and check["python_updater"] is not None and hasattr(check["python_updater"], "perform_update")
|
||||
def can_perform_update(target, check, online=True):
|
||||
return "python_updater" in check and check["python_updater"] is not None and hasattr(check["python_updater"], "perform_update") and (online or check.get("offline", False))
|
||||
|
||||
|
||||
def perform_update(target, check, target_version, log_cb=None):
|
||||
return check["python_updater"].perform_update(target, check, target_version, log_cb=log_cb)
|
||||
def perform_update(target, check, target_version, log_cb=None, online=True):
|
||||
from ..exceptions import CannotUpdateOffline
|
||||
|
||||
if not online and not check("offline", False):
|
||||
raise CannotUpdateOffline()
|
||||
|
||||
try:
|
||||
return check["python_updater"].perform_update(target, check, target_version, log_cb=log_cb, online=online)
|
||||
except:
|
||||
import inspect
|
||||
args, _, _, _ = inspect.getargspec(check["python_updater"].perform_update)
|
||||
if "online" not in args:
|
||||
# old python_updater footprint, simply leave out the online parameter
|
||||
return check["python_updater"].perform_update(target, check, target_version, log_cb=log_cb)
|
||||
|
||||
# some other error, raise again
|
||||
raise
|
||||
@@ -8,7 +8,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
import sys
|
||||
import logging
|
||||
|
||||
from ..exceptions import ConfigurationInvalid, UpdateError
|
||||
from ..exceptions import ConfigurationInvalid, UpdateError, CannotUpdateOffline
|
||||
|
||||
from octoprint.util.commandline import CommandlineCaller, CommandlineError
|
||||
|
||||
@@ -36,7 +36,7 @@ def _get_caller(log_cb=None):
|
||||
return caller
|
||||
|
||||
|
||||
def can_perform_update(target, check):
|
||||
def can_perform_update(target, check, online=True):
|
||||
import os
|
||||
script_configured = bool("update_script" in check and check["update_script"])
|
||||
|
||||
@@ -47,12 +47,15 @@ def can_perform_update(target, check):
|
||||
folder = check["checkout_folder"]
|
||||
folder_configured = bool(folder and os.path.isdir(folder))
|
||||
|
||||
return script_configured and folder_configured
|
||||
return script_configured and folder_configured and (online or check.get("offline", False))
|
||||
|
||||
|
||||
def perform_update(target, check, target_version, log_cb=None):
|
||||
def perform_update(target, check, target_version, log_cb=None, online=True):
|
||||
logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.update_script")
|
||||
|
||||
if not online and not check("offline", False):
|
||||
raise CannotUpdateOffline()
|
||||
|
||||
if not can_perform_update(target, check):
|
||||
raise ConfigurationInvalid("checkout_folder and update_folder are missing for update target %s, one is needed" % target)
|
||||
|
||||
|
||||
@@ -9,12 +9,12 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
from .exceptions import ScriptError
|
||||
|
||||
|
||||
def execute(command, cwd=None, evaluate_returncode=True):
|
||||
def execute(command, cwd=None, evaluate_returncode=True, async=False):
|
||||
import sarge
|
||||
p = None
|
||||
|
||||
try:
|
||||
p = sarge.run(command, cwd=cwd, stdout=sarge.Capture(), stderr=sarge.Capture())
|
||||
p = sarge.run(command, cwd=cwd, stdout=sarge.Capture(), stderr=sarge.Capture(), async=async)
|
||||
except:
|
||||
returncode = p.returncode if p is not None else None
|
||||
stdout = p.stdout.text if p is not None and p.stdout is not None else ""
|
||||
|
||||
@@ -6,15 +6,26 @@ __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms
|
||||
|
||||
import requests
|
||||
import logging
|
||||
|
||||
from ..exceptions import ConfigurationInvalid
|
||||
import base64
|
||||
|
||||
BRANCH_HEAD_URL = "https://api.bitbucket.org/2.0/repositories/{user}/{repo}/commit/{branch}"
|
||||
|
||||
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.bitbucket_commit")
|
||||
|
||||
def _get_latest_commit(user, repo, branch):
|
||||
r = requests.get(BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch))
|
||||
|
||||
def _get_latest_commit(user, repo, branch, api_user=None, api_password=None):
|
||||
from ..exceptions import NetworkError
|
||||
|
||||
url = BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch)
|
||||
headers = {}
|
||||
if api_user is not None and api_password is not None:
|
||||
auth_value = base64.b64encode(b"{user}:{pw}".format(user=api_user, pw=api_password))
|
||||
headers["authorization"] = "Basic {}".format(auth_value)
|
||||
|
||||
try:
|
||||
r = requests.get(url, headers=headers, timeout=(3.05, 30))
|
||||
except requests.ConnectionError as exc:
|
||||
raise NetworkError(cause=exc)
|
||||
|
||||
if not r.status_code == requests.codes.ok:
|
||||
return None
|
||||
@@ -26,24 +37,33 @@ def _get_latest_commit(user, repo, branch):
|
||||
return reference["hash"]
|
||||
|
||||
|
||||
def get_latest(target, check):
|
||||
def get_latest(target, check, online=True):
|
||||
from ..exceptions import ConfigurationInvalid
|
||||
|
||||
if "user" not in check or "repo" not in check:
|
||||
raise ConfigurationInvalid("Update configuration for %s of type bitbucket_commit needs all of user and repo" % target)
|
||||
|
||||
branch = "master"
|
||||
if "branch" in check:
|
||||
if "branch" in check and check["branch"] is not None:
|
||||
branch = check["branch"]
|
||||
|
||||
current = None
|
||||
if "current" in check:
|
||||
current = check["current"]
|
||||
api_user = check.get("api_user")
|
||||
api_password = check.get("api_password")
|
||||
|
||||
remote_commit = _get_latest_commit(check["user"], check["repo"], branch)
|
||||
current = check.get("current")
|
||||
|
||||
information = dict(
|
||||
local=dict(name="Commit {commit}".format(commit=current if current is not None else "unknown"), value=current),
|
||||
remote=dict(name="Commit {commit}".format(commit=remote_commit if remote_commit is not None else "unknown"), value=remote_commit)
|
||||
remote=dict(name="?", value="?"),
|
||||
needs_online=not check.get("offline", False)
|
||||
)
|
||||
if not online and information["needs_online"]:
|
||||
return information, True
|
||||
|
||||
remote_commit = _get_latest_commit(check["user"], check["repo"], branch, api_user, api_password)
|
||||
remote_name = "Commit {commit}".format(commit=remote_commit) if remote_commit is not None else "-"
|
||||
|
||||
information["remote"] = dict(name=remote_name, value=remote_commit)
|
||||
is_current = (current is not None and current == remote_commit) or remote_commit is None
|
||||
|
||||
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_commit))
|
||||
|
||||
@@ -8,14 +8,17 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import logging
|
||||
|
||||
from ..exceptions import ConfigurationInvalid
|
||||
from ..exceptions import ConfigurationInvalid, CannotCheckOffline
|
||||
from ..util import execute
|
||||
|
||||
def get_latest(target, check):
|
||||
def get_latest(target, check, online=True):
|
||||
command = check.get("command")
|
||||
if command is None:
|
||||
raise ConfigurationInvalid("Update configuration for {} of type commandline needs command set and not None".format(target))
|
||||
|
||||
if not online and not check.get("offline", False):
|
||||
raise CannotCheckOffline("{} isn't marked as 'offline' capable, but we are apparently offline right now".format(target))
|
||||
|
||||
returncode, stdout, stderr = execute(command, evaluate_returncode=False)
|
||||
|
||||
# We expect command line check commands to
|
||||
|
||||
@@ -47,38 +47,40 @@ def _git(args, cwd, hide_stderr=False):
|
||||
return p.returncode, stdout
|
||||
|
||||
|
||||
def get_latest(target, check):
|
||||
def get_latest(target, check, online=True):
|
||||
checkout_folder = check.get("checkout_folder")
|
||||
if checkout_folder is None:
|
||||
raise ConfigurationInvalid("Update configuration for {} of type git_commit needs checkout_folder set and not None".format(target))
|
||||
|
||||
returncode, _ = _git(["fetch"], checkout_folder)
|
||||
if returncode != 0:
|
||||
return None, True
|
||||
|
||||
returncode, local_commit = _git(["rev-parse", "@{0}"], checkout_folder)
|
||||
if returncode != 0:
|
||||
return None, True
|
||||
|
||||
information = dict(
|
||||
local=dict(name="Commit %s" % local_commit, value=local_commit),
|
||||
remote=dict(name="?", value="?"),
|
||||
needs_online=not check.get("offline", False)
|
||||
)
|
||||
if not online and information["needs_online"]:
|
||||
return information, True
|
||||
|
||||
returncode, _ = _git(["fetch"], checkout_folder)
|
||||
if returncode != 0:
|
||||
return information, True
|
||||
|
||||
returncode, remote_commit = _git(["rev-parse", "@{u}"], checkout_folder)
|
||||
if returncode != 0:
|
||||
return None, True
|
||||
return information, True
|
||||
|
||||
returncode, base = _git(["merge-base", "@{0}", "@{u}"], checkout_folder)
|
||||
if returncode != 0:
|
||||
return None, True
|
||||
return information, True
|
||||
|
||||
if local_commit == remote_commit or remote_commit == base:
|
||||
information = dict(
|
||||
local=dict(name="Commit %s" % local_commit, value=local_commit),
|
||||
remote=dict(name="Commit %s" % local_commit, value=local_commit)
|
||||
)
|
||||
information["remote"] = dict(name="Commit %s" % local_commit, value=local_commit)
|
||||
is_current = True
|
||||
else:
|
||||
information = dict(
|
||||
local=dict(name="Commit %s" % local_commit, value=local_commit),
|
||||
remote=dict(name="Commit %s" % remote_commit, value=remote_commit)
|
||||
)
|
||||
information["remote"] = dict(name="Commit %s" % remote_commit, value=remote_commit)
|
||||
is_current = local_commit == remote_commit
|
||||
|
||||
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.git_commit")
|
||||
|
||||
@@ -8,14 +8,17 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
import requests
|
||||
import logging
|
||||
|
||||
from ..exceptions import ConfigurationInvalid
|
||||
|
||||
BRANCH_HEAD_URL = "https://api.github.com/repos/{user}/{repo}/git/refs/heads/{branch}"
|
||||
|
||||
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.github_commit")
|
||||
|
||||
def _get_latest_commit(user, repo, branch):
|
||||
r = requests.get(BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch), timeout=30)
|
||||
from ..exceptions import NetworkError
|
||||
|
||||
try:
|
||||
r = requests.get(BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch), timeout=(3.05, 30))
|
||||
except requests.ConnectionError as exc:
|
||||
raise NetworkError(cause=exc)
|
||||
|
||||
from . import log_github_ratelimit
|
||||
log_github_ratelimit(logger, r)
|
||||
@@ -30,7 +33,9 @@ def _get_latest_commit(user, repo, branch):
|
||||
return reference["object"]["sha"]
|
||||
|
||||
|
||||
def get_latest(target, check):
|
||||
def get_latest(target, check, online=True):
|
||||
from ..exceptions import ConfigurationInvalid
|
||||
|
||||
user = check.get("user")
|
||||
repo = check.get("repo")
|
||||
|
||||
@@ -41,16 +46,18 @@ def get_latest(target, check):
|
||||
if "branch" in check and check["branch"] is not None:
|
||||
branch = check["branch"]
|
||||
|
||||
current = None
|
||||
if "current" in check:
|
||||
current = check["current"]
|
||||
current = check.get("current")
|
||||
|
||||
information = dict(local=dict(name="Commit {commit}".format(commit=current if current is not None else "?"), value=current),
|
||||
remote=dict(name="?", value="?"),
|
||||
needs_online=not check.get("offline", False))
|
||||
if not online and information["needs_online"]:
|
||||
return information, True
|
||||
|
||||
remote_commit = _get_latest_commit(check["user"], check["repo"], branch)
|
||||
remote_name = "Commit {commit}".format(commit=remote_commit) if remote_commit is not None else "-"
|
||||
|
||||
information = dict(
|
||||
local=dict(name="Commit {commit}".format(commit=current if current is not None else "unknown"), value=current),
|
||||
remote=dict(name="Commit {commit}".format(commit=remote_commit if remote_commit is not None else "unknown"), value=remote_commit)
|
||||
)
|
||||
information["remote"] = dict(name=remote_name, value=remote_commit)
|
||||
is_current = (current is not None and current == remote_commit) or remote_commit is None
|
||||
|
||||
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_commit))
|
||||
|
||||
@@ -15,7 +15,7 @@ logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.gith
|
||||
def _filter_out_latest(releases,
|
||||
sort_key=None,
|
||||
include_prerelease=False,
|
||||
prerelease_channel=None):
|
||||
commitish=None):
|
||||
"""
|
||||
Filters out the newest of all matching releases.
|
||||
|
||||
@@ -26,31 +26,43 @@ def _filter_out_latest(releases,
|
||||
>>> release_1_2_16rc2 = dict(name="1.2.16rc2", tag_name="1.2.16rc2", html_url="some_url", published_at="2016-08-30T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance")
|
||||
>>> release_1_2_17rc1 = dict(name="1.2.17rc1", tag_name="1.2.17rc1", html_url="some_url", published_at="2016-08-31T12:00:00Z", prerelease=True, draft=True, target_commitish="rc/maintenance")
|
||||
>>> release_1_3_0rc1 = dict(name="1.3.0rc1", tag_name="1.3.0rc1", html_url="some_url", published_at="2016-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/devel")
|
||||
>>> release_1_3_5rc1 = dict(name="1.3.5rc1", tag_name="1.3.5rc1", html_url="some_url", published_at="2017-06-14T10:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance")
|
||||
>>> release_1_2_18 = dict(name="1.2.18", tag_name="1.2.18", html_url="some_url", published_at="2016-12-13T12:00:00Z", prerelease=False, draft=False, target_commitish="master")
|
||||
>>> release_1_4_0rc1 = dict(name="1.4.0rc1", tag_name="1.4.0rc1", html_url="some_url", published_at="2017-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/future")
|
||||
>>> release_1_4_0rc1_devel = dict(name="1.4.0rc1", tag_name="1.4.0rc1", html_url="some_url", published_at="2017-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/devel")
|
||||
>>> releases = [release_1_2_15, release_1_2_16rc1, release_1_2_16rc2, release_1_2_17rc1, release_1_3_0rc1, release_1_4_0rc1]
|
||||
>>> _filter_out_latest(releases, include_prerelease=False, prerelease_channel=None)
|
||||
>>> _filter_out_latest(releases, include_prerelease=False, commitish=None)
|
||||
('1.2.15', '1.2.15', 'some_url')
|
||||
>>> _filter_out_latest(releases, include_prerelease=True, prerelease_channel="rc/maintenance")
|
||||
>>> _filter_out_latest(releases, include_prerelease=True, commitish=["rc/maintenance"])
|
||||
('1.2.16rc2', '1.2.16rc2', 'some_url')
|
||||
>>> _filter_out_latest(releases, include_prerelease=True, prerelease_channel="rc/devel")
|
||||
>>> _filter_out_latest(releases, include_prerelease=True, commitish=["rc/devel"])
|
||||
('1.3.0rc1', '1.3.0rc1', 'some_url')
|
||||
>>> _filter_out_latest(releases, include_prerelease=True, prerelease_channel=None)
|
||||
>>> _filter_out_latest(releases, include_prerelease=True, commitish=None)
|
||||
('1.4.0rc1', '1.4.0rc1', 'some_url')
|
||||
>>> _filter_out_latest(releases, include_prerelease=True, prerelease_channel="rc/doesntexist")
|
||||
>>> _filter_out_latest(releases, include_prerelease=True, commitish=["rc/doesntexist"])
|
||||
('1.2.15', '1.2.15', 'some_url')
|
||||
>>> _filter_out_latest([release_1_2_17rc1])
|
||||
(None, None, None)
|
||||
>>> _filter_out_latest([release_1_2_16rc1, release_1_2_16rc2])
|
||||
(None, None, None)
|
||||
|
||||
>>> comparable_factory = _get_comparable_factory("python", force_base=True)
|
||||
>>> sort_key = lambda release: comparable_factory(_get_sanitized_version(release["tag_name"]))
|
||||
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=False, prerelease_channel=None, sort_key=sort_key)
|
||||
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=False, commitish=None, sort_key=sort_key)
|
||||
('1.2.18', '1.2.18', 'some_url')
|
||||
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, prerelease_channel="rc/maintenance", sort_key=sort_key)
|
||||
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, commitish=["rc/maintenance"], sort_key=sort_key)
|
||||
('1.2.18', '1.2.18', 'some_url')
|
||||
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, prerelease_channel="rc/devel", sort_key=sort_key)
|
||||
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, commitish=["rc/devel"], sort_key=sort_key)
|
||||
('1.3.0rc1', '1.3.0rc1', 'some_url')
|
||||
|
||||
>>> _filter_out_latest([release_1_2_18, release_1_3_5rc1], include_prerelease=True, commitish=["rc/maintenance"])
|
||||
('1.3.5rc1', '1.3.5rc1', 'some_url')
|
||||
>>> _filter_out_latest([release_1_2_18, release_1_3_5rc1], include_prerelease=True, commitish=["rc/maintenance", "rc/devel"])
|
||||
('1.3.5rc1', '1.3.5rc1', 'some_url')
|
||||
>>> _filter_out_latest([release_1_2_18, release_1_3_5rc1, release_1_4_0rc1_devel], include_prerelease=True, commitish=["rc/maintenance"])
|
||||
('1.3.5rc1', '1.3.5rc1', 'some_url')
|
||||
>>> _filter_out_latest([release_1_2_18, release_1_3_5rc1, release_1_4_0rc1_devel], include_prerelease=True, commitish=["rc/maintenance", "rc/devel"])
|
||||
('1.4.0rc1', '1.4.0rc1', 'some_url')
|
||||
"""
|
||||
|
||||
nothing = None, None, None
|
||||
@@ -61,9 +73,9 @@ def _filter_out_latest(releases,
|
||||
# filter out prereleases and drafts
|
||||
filter_function = lambda rel: not rel["prerelease"] and not rel["draft"]
|
||||
if include_prerelease:
|
||||
if prerelease_channel:
|
||||
filter_function = lambda rel: not rel["draft"] and (
|
||||
not rel["prerelease"] or rel["target_commitish"] == prerelease_channel)
|
||||
if commitish:
|
||||
filter_function = lambda rel: not rel["draft"] and \
|
||||
(not rel["prerelease"] or rel["target_commitish"] in commitish)
|
||||
else:
|
||||
filter_function = lambda rel: not rel["draft"]
|
||||
|
||||
@@ -82,10 +94,16 @@ def _filter_out_latest(releases,
|
||||
|
||||
def _get_latest_release(user, repo, compare_type,
|
||||
include_prerelease=False,
|
||||
prerelease_channel=None,
|
||||
commitish=None,
|
||||
force_base=True):
|
||||
from ..exceptions import NetworkError
|
||||
|
||||
nothing = None, None, None
|
||||
r = requests.get(RELEASE_URL.format(user=user, repo=repo), timeout=30)
|
||||
|
||||
try:
|
||||
r = requests.get(RELEASE_URL.format(user=user, repo=repo), timeout=(3.05, 30))
|
||||
except requests.ConnectionError as exc:
|
||||
raise NetworkError(cause=exc)
|
||||
|
||||
from . import log_github_ratelimit
|
||||
log_github_ratelimit(logger, r)
|
||||
@@ -107,7 +125,7 @@ def _get_latest_release(user, repo, compare_type,
|
||||
return _filter_out_latest(releases,
|
||||
sort_key=sort_key,
|
||||
include_prerelease=include_prerelease,
|
||||
prerelease_channel=prerelease_channel)
|
||||
commitish=commitish)
|
||||
|
||||
|
||||
def _get_sanitized_version(version_string):
|
||||
@@ -246,7 +264,7 @@ def _is_current(release_information, compare_type, custom=None, force_base=True)
|
||||
return True
|
||||
|
||||
|
||||
def get_latest(target, check, custom_compare=None):
|
||||
def get_latest(target, check, custom_compare=None, online=True):
|
||||
from ..exceptions import ConfigurationInvalid
|
||||
|
||||
user = check.get("user", None)
|
||||
@@ -255,8 +273,26 @@ def get_latest(target, check, custom_compare=None):
|
||||
if user is None or repo is None or current is None:
|
||||
raise ConfigurationInvalid("Update configuration for {} of type github_release needs all of user, repo and current set and not None".format(target))
|
||||
|
||||
information =dict(
|
||||
local=dict(name=current, value=current),
|
||||
remote=dict(name="?", value="?", release_notes=None),
|
||||
needs_online=not check.get("offline", False)
|
||||
)
|
||||
if not online and information["needs_online"]:
|
||||
return information, True
|
||||
|
||||
include_prerelease = check.get("prerelease", False)
|
||||
prerelease_channel = check.get("prerelease_channel", None)
|
||||
|
||||
# determine valid "commitish" values in case we track prereleases
|
||||
commitish = None
|
||||
if prerelease_channel:
|
||||
prerelease_branches = check.get("prerelease_branches", None)
|
||||
if prerelease_branches:
|
||||
# fetch valid commitish list from configured prerelease_branches for selected channel
|
||||
commitishes = dict((x["branch"], x.get("commitish", [x["branch"]])) for x in prerelease_branches)
|
||||
commitish = commitishes.get(prerelease_channel, [prerelease_channel])
|
||||
|
||||
force_base = check.get("force_base", True)
|
||||
compare_type = _get_sanitized_compare_type(check.get("release_compare", "python"),
|
||||
custom=custom_compare)
|
||||
@@ -265,13 +301,16 @@ def get_latest(target, check, custom_compare=None):
|
||||
check["repo"],
|
||||
compare_type,
|
||||
include_prerelease=include_prerelease,
|
||||
prerelease_channel=prerelease_channel,
|
||||
commitish=commitish,
|
||||
force_base=force_base)
|
||||
|
||||
information =dict(
|
||||
local=dict(name=current, value=current),
|
||||
remote=dict(name=remote_name, value=remote_tag, release_notes=release_notes)
|
||||
)
|
||||
if remote_name is None:
|
||||
if remote_tag is not None:
|
||||
remote_name = remote_tag
|
||||
else:
|
||||
remote_name = "-"
|
||||
|
||||
information["remote"] = dict(name=remote_name, value=remote_tag, release_notes=release_notes)
|
||||
|
||||
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_tag))
|
||||
|
||||
|
||||
@@ -5,11 +5,24 @@ __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"
|
||||
|
||||
from ..exceptions import ConfigurationInvalid
|
||||
from ..exceptions import ConfigurationInvalid, CannotCheckOffline
|
||||
|
||||
def get_latest(target, check, full_data=False):
|
||||
def get_latest(target, check, full_data=False, online=True):
|
||||
python_checker = check.get("python_checker")
|
||||
if python_checker is None or not hasattr(python_checker, "get_latest"):
|
||||
raise ConfigurationInvalid("Update configuration for {} of type python_checker needs python_checker defined and have an attribute \"get_latest\"".format(target))
|
||||
|
||||
return check["python_checker"].get_latest(target, check, full_data=full_data)
|
||||
if not online and not check.get("offline", False):
|
||||
raise CannotCheckOffline("{} isn't marked as 'offline' capable, but we are apparently offline right now".format(target))
|
||||
|
||||
try:
|
||||
return check["python_checker"].get_latest(target, check, full_data=full_data, online=online)
|
||||
except:
|
||||
import inspect
|
||||
args, _, _, _ = inspect.getargspec(check["python_checker"].get_latest)
|
||||
if "online" not in args:
|
||||
# old python_checker footprint, simply leave out the online parameter
|
||||
return check["python_checker"].get_latest(target, check, full_data=full_data)
|
||||
|
||||
# some other error, raise again
|
||||
raise
|
||||
@@ -18,6 +18,7 @@ from serial import SerialTimeoutException
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.plugin import plugin_manager
|
||||
from octoprint.util import RepeatedTimer
|
||||
|
||||
class VirtualPrinter(object):
|
||||
command_regex = re.compile("^([GMTF])(\d+)")
|
||||
@@ -64,6 +65,9 @@ class VirtualPrinter(object):
|
||||
|
||||
self.currentExtruder = 0
|
||||
self.extruderCount = settings().getInt(["devel", "virtualPrinter", "numExtruders"])
|
||||
self.pinnedExtruders = settings().get(["devel", "virtualPrinter", "pinnedExtruders"])
|
||||
if self.pinnedExtruders is None:
|
||||
self.pinnedExtruders = dict()
|
||||
self.sharedNozzle = settings().getBoolean(["devel", "virtualPrinter", "sharedNozzle"])
|
||||
self.temperatureCount = (1 if self.sharedNozzle else self.extruderCount)
|
||||
|
||||
@@ -113,6 +117,10 @@ class VirtualPrinter(object):
|
||||
|
||||
self._okFormatString = settings().get(["devel", "virtualPrinter", "okFormatString"])
|
||||
|
||||
self._capabilities = settings().get(["devel", "virtualPrinter", "capabilities"])
|
||||
|
||||
self._temperature_reporter = None
|
||||
|
||||
self.currentLine = 0
|
||||
self.lastN = 0
|
||||
|
||||
@@ -405,11 +413,26 @@ class VirtualPrinter(object):
|
||||
output = self._m115FormatString.format(firmware_name=self._firmwareName)
|
||||
self._send(output)
|
||||
|
||||
if settings().getBoolean(["devel", "virtualPrinter", "m115ReportCapabilities"]):
|
||||
for cap, enabled in self._capabilities.items():
|
||||
self._send("Cap:{}:{}".format(cap.upper(), "1" if enabled else "0"))
|
||||
|
||||
def _gcode_M117(self, data):
|
||||
# we'll just use this to echo a message, to allow playing around with pause triggers
|
||||
if self._echoOnM117:
|
||||
self._send("echo:%s" % re.search("M117\s+(.*)", data).group(1))
|
||||
|
||||
def _gcode_M155(self, data):
|
||||
interval = int(re.search("S([0-9]+)", data).group(1))
|
||||
if self._temperature_reporter is not None:
|
||||
self._temperature_reporter.cancel()
|
||||
|
||||
if interval > 0:
|
||||
self._temperature_reporter = RepeatedTimer(interval, lambda: self._send(self._generateTemperatureOutput()))
|
||||
self._temperature_reporter.start()
|
||||
else:
|
||||
self._temperature_reporter = None
|
||||
|
||||
def _gcode_M220(self, data):
|
||||
self._feedrate_multiplier = float(re.search('S([0-9]+)', data).group(1))
|
||||
|
||||
@@ -675,9 +698,8 @@ class VirtualPrinter(object):
|
||||
else:
|
||||
self._send("Not SD printing")
|
||||
|
||||
def _processTemperatureQuery(self):
|
||||
def _generateTemperatureOutput(self):
|
||||
includeTarget = not settings().getBoolean(["devel", "virtualPrinter", "repetierStyleTargetTemperature"])
|
||||
includeOk = not self._okBeforeCommandOutput
|
||||
|
||||
# send simulated temperature data
|
||||
if self.temperatureCount > 1:
|
||||
@@ -709,6 +731,11 @@ class VirtualPrinter(object):
|
||||
output = "T:%.2f B:%.2f" % (self.temp[0], self.bedTemp)
|
||||
|
||||
output += " @:64\n"
|
||||
return output
|
||||
|
||||
def _processTemperatureQuery(self):
|
||||
includeOk = not self._okBeforeCommandOutput
|
||||
output = self._generateTemperatureOutput()
|
||||
|
||||
if includeOk:
|
||||
output = "{} {}".format(self._ok(), output)
|
||||
@@ -977,6 +1004,10 @@ class VirtualPrinter(object):
|
||||
timeDiff = self.lastTempAt - time.time()
|
||||
self.lastTempAt = time.time()
|
||||
for i in range(len(self.temp)):
|
||||
if i in self.pinnedExtruders:
|
||||
self.temp[i] = self.pinnedExtruders[i]
|
||||
continue
|
||||
|
||||
if abs(self.temp[i] - self.targetTemp[i]) > delta:
|
||||
oldVal = self.temp[i]
|
||||
self.temp[i] += math.copysign(timeDiff * 10, self.targetTemp[i] - self.temp[i])
|
||||
|
||||
@@ -199,7 +199,7 @@ class PrinterInterface(object):
|
||||
|
||||
def set_temperature_offset(self, offsets=None):
|
||||
"""
|
||||
Sets the temperature ``offsets`` to apply to target temperatures red from a GCODE file while printing.
|
||||
Sets the temperature ``offsets`` to apply to target temperatures read from a GCODE file while printing.
|
||||
|
||||
Arguments:
|
||||
offsets (dict): A dictionary specifying the offsets to apply. Keys must match the format for the ``heater``
|
||||
@@ -299,6 +299,7 @@ class PrinterInterface(object):
|
||||
after the file is selected.
|
||||
|
||||
Raises:
|
||||
InvalidFileType: if the file is not a machinecode file and hence cannot be printed
|
||||
InvalidFileLocation: if an absolute path was provided and not contained within local storage or
|
||||
doesn't exist
|
||||
"""
|
||||
@@ -593,3 +594,6 @@ class UnknownScript(Exception):
|
||||
|
||||
class InvalidFileLocation(Exception):
|
||||
pass
|
||||
|
||||
class InvalidFileType(Exception):
|
||||
pass
|
||||
@@ -228,7 +228,7 @@ class PrinterProfileManager(object):
|
||||
self._logger.info("Migrated default printer profile from settings to _default.profile: {!r}".format(default_overrides))
|
||||
|
||||
def _verify_default_available(self):
|
||||
default_id = settings().get(["printerProfile", "default"])
|
||||
default_id = settings().get(["printerProfiles", "default"])
|
||||
if default_id is None:
|
||||
default_id = "_default"
|
||||
|
||||
@@ -342,7 +342,7 @@ class PrinterProfileManager(object):
|
||||
if identifier is not None and not identifier in all_identifiers:
|
||||
return
|
||||
|
||||
settings().set(["printerProfile", "default"], identifier)
|
||||
settings().set(["printerProfiles", "default"], identifier)
|
||||
settings().save()
|
||||
|
||||
def get_current_or_default(self):
|
||||
|
||||
@@ -15,11 +15,13 @@ import os
|
||||
import threading
|
||||
import time
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
from octoprint import util as util
|
||||
from octoprint.events import eventManager, Events
|
||||
from octoprint.filemanager import FileDestinations, NoSuchStorage
|
||||
from octoprint.filemanager import FileDestinations, NoSuchStorage, valid_file_type
|
||||
from octoprint.plugin import plugin_manager, ProgressPlugin
|
||||
from octoprint.printer import PrinterInterface, PrinterCallback, UnknownScript, InvalidFileLocation
|
||||
from octoprint.printer import PrinterInterface, PrinterCallback, UnknownScript, InvalidFileLocation, InvalidFileType
|
||||
from octoprint.printer.estimation import TimeEstimationHelper
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import comm as comm
|
||||
@@ -761,7 +763,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
(2-tuple) estimated print time left or None if not proper estimate could be made at all, origin of estimation
|
||||
"""
|
||||
|
||||
if progress is None or printTime is None or cleanedPrintTime is None:
|
||||
if progress is None or progress == 0 or printTime is None or cleanedPrintTime is None:
|
||||
return None, None
|
||||
|
||||
dumbTotalPrintTime = printTime / progress
|
||||
@@ -846,6 +848,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._stateMonitor.add_temperature(data)
|
||||
|
||||
def _validateJob(self, filename, sd):
|
||||
if not valid_file_type(filename, type="machinecode"):
|
||||
raise InvalidFileType("{} is not a machinecode file, cannot print".format(filename))
|
||||
|
||||
if sd:
|
||||
return
|
||||
|
||||
@@ -995,7 +1000,17 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
with self._selectedFileMutex:
|
||||
if self._selectedFile is not None:
|
||||
if state == comm.MachineCom.STATE_CLOSED or state == comm.MachineCom.STATE_ERROR or state == comm.MachineCom.STATE_CLOSED_WITH_ERROR:
|
||||
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), False, self._printerProfileManager.get_current_or_default()["id"])
|
||||
def log_print():
|
||||
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL,
|
||||
self._selectedFile["filename"],
|
||||
time.time(),
|
||||
self._comm.getPrintTime(),
|
||||
False,
|
||||
self._printerProfileManager.get_current_or_default()["id"])
|
||||
|
||||
thread = threading.Thread(target=log_print)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
self._analysisQueue.resume() # printing done, put those cpu cycles to good use
|
||||
elif state == comm.MachineCom.STATE_PRINTING:
|
||||
self._analysisQueue.pause() # do not analyse files while printing
|
||||
@@ -1086,12 +1101,18 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
context=dict(event=payload),
|
||||
must_be_set=False)
|
||||
|
||||
self._fileManager.log_print(payload["origin"],
|
||||
payload["path"],
|
||||
time.time(),
|
||||
payload["time"],
|
||||
True,
|
||||
self._printerProfileManager.get_current_or_default()["id"])
|
||||
def log_print():
|
||||
self._fileManager.log_print(payload["origin"],
|
||||
payload["path"],
|
||||
time.time(),
|
||||
payload["time"],
|
||||
True,
|
||||
self._printerProfileManager.get_current_or_default()["id"])
|
||||
|
||||
thread = threading.Thread(target=log_print)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
else:
|
||||
self._updateProgressData()
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
@@ -1114,13 +1135,18 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
context=dict(event=payload),
|
||||
must_be_set=False)
|
||||
|
||||
self._fileManager.log_print(payload["origin"],
|
||||
payload["path"],
|
||||
time.time(),
|
||||
payload["time"],
|
||||
False,
|
||||
self._printerProfileManager.get_current_or_default()["id"])
|
||||
eventManager().fire(Events.PRINT_FAILED, payload)
|
||||
def finalize():
|
||||
self._fileManager.log_print(payload["origin"],
|
||||
payload["path"],
|
||||
time.time(),
|
||||
payload["time"],
|
||||
False,
|
||||
self._printerProfileManager.get_current_or_default()["id"])
|
||||
eventManager().fire(Events.PRINT_FAILED, payload)
|
||||
|
||||
thread = threading.Thread(target=finalize)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
def on_comm_print_job_paused(self):
|
||||
payload = self._payload_for_print_job_event(position=self._comm.pause_position.as_dict() if self._comm and self._comm.pause_position else None)
|
||||
@@ -1169,8 +1195,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
except:
|
||||
self._logger.exception("Error while trying to persist print recovery data")
|
||||
|
||||
def _payload_for_print_job_event(self, location=None, print_job_file=None, position=None):
|
||||
print_job_size = None
|
||||
def _payload_for_print_job_event(self, location=None, print_job_file=None, print_job_size=None, position=None):
|
||||
if print_job_file is None:
|
||||
with self._selectedFileMutex:
|
||||
selected_file = self._selectedFile
|
||||
@@ -1181,7 +1206,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
print_job_size = selected_file.get("filesize", None)
|
||||
location = FileDestinations.SDCARD if selected_file.get("sd", False) else FileDestinations.LOCAL
|
||||
|
||||
if not print_job_file or not print_job_size or not location:
|
||||
if not print_job_file or not location:
|
||||
return dict()
|
||||
|
||||
if location == FileDestinations.SDCARD:
|
||||
@@ -1223,15 +1248,12 @@ class StateMonitor(object):
|
||||
|
||||
self._state = None
|
||||
self._job_data = None
|
||||
self._gcode_data = None
|
||||
self._sd_upload_data = None
|
||||
self._current_z = None
|
||||
self._offsets = {}
|
||||
self._progress = None
|
||||
|
||||
self._progress_dirty = False
|
||||
|
||||
self._offsets = {}
|
||||
|
||||
self._change_event = threading.Event()
|
||||
self._state_lock = threading.Lock()
|
||||
self._progress_lock = threading.Lock()
|
||||
|
||||
@@ -7,16 +7,18 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import uuid
|
||||
from sockjs.tornado import SockJSRouter
|
||||
from flask import Flask, g, request, session, Blueprint, Request, Response
|
||||
from flask.ext.login import LoginManager, current_user
|
||||
from flask.ext.principal import Principal, Permission, RoleNeed, identity_loaded, UserNeed
|
||||
from flask import Flask, g, request, session, Blueprint, Request, Response, current_app
|
||||
from flask.ext.login import LoginManager, current_user, session_protected, user_logged_out
|
||||
from flask.ext.principal import Principal, Permission, RoleNeed, identity_loaded, identity_changed, UserNeed, AnonymousIdentity
|
||||
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
|
||||
|
||||
from builtins import bytes, range
|
||||
from past.builtins import basestring
|
||||
|
||||
import os
|
||||
import logging
|
||||
@@ -25,6 +27,11 @@ import atexit
|
||||
import signal
|
||||
import base64
|
||||
|
||||
try:
|
||||
import fcntl
|
||||
except ImportError:
|
||||
fcntl = None
|
||||
|
||||
SUCCESS = {}
|
||||
NO_CONTENT = ("", 204)
|
||||
NOT_MODIFIED = ("Not Modified", 304)
|
||||
@@ -47,6 +54,7 @@ pluginManager = None
|
||||
appSessionManager = None
|
||||
pluginLifecycleManager = None
|
||||
preemptiveCache = None
|
||||
connectivityChecker = None
|
||||
|
||||
principals = Principal(app)
|
||||
admin_permission = Permission(RoleNeed("admin"))
|
||||
@@ -94,6 +102,29 @@ def on_identity_loaded(sender, identity):
|
||||
if user.is_admin():
|
||||
identity.provides.add(RoleNeed("admin"))
|
||||
|
||||
|
||||
def _clear_identity(sender):
|
||||
# Remove session keys set by Flask-Principal
|
||||
for key in ('identity.id', 'identity.name', 'identity.auth_type'):
|
||||
if key in session:
|
||||
del session[key]
|
||||
|
||||
# switch to anonymous identity
|
||||
identity_changed.send(sender, identity=AnonymousIdentity())
|
||||
|
||||
|
||||
@session_protected.connect_via(app)
|
||||
def on_session_protected(sender):
|
||||
# session was protected, that means the user is no more and we need to clear our identity
|
||||
_clear_identity(sender)
|
||||
|
||||
|
||||
@user_logged_out.connect_via(app)
|
||||
def on_user_logged_out(sender, user=None):
|
||||
# user was logged out, clear identity
|
||||
_clear_identity(sender)
|
||||
|
||||
|
||||
def load_user(id):
|
||||
if id == "_api":
|
||||
return users.ApiUser()
|
||||
@@ -158,11 +189,12 @@ class Server(object):
|
||||
global appSessionManager
|
||||
global pluginLifecycleManager
|
||||
global preemptiveCache
|
||||
global connectivityChecker
|
||||
global debug
|
||||
global safe_mode
|
||||
|
||||
from tornado.ioloop import IOLoop
|
||||
from tornado.web import Application, RequestHandler
|
||||
from tornado.web import Application
|
||||
|
||||
debug = self._debug
|
||||
safe_mode = self._safe_mode
|
||||
@@ -187,6 +219,16 @@ class Server(object):
|
||||
# start the intermediary server
|
||||
self._start_intermediary_server()
|
||||
|
||||
### IMPORTANT!
|
||||
###
|
||||
### Best do not start any subprocesses until the intermediary server shuts down again or they MIGHT inherit the
|
||||
### open port and prevent us from firing up Tornado later.
|
||||
###
|
||||
### The intermediary server's socket should have the CLOSE_EXEC flag (or its equivalent) set where possible, but
|
||||
### we can only do that if fcntl is availabel or we are on Windows, so better safe than sorry.
|
||||
###
|
||||
### See also issues #2035 and #2090
|
||||
|
||||
# then initialize the plugin manager
|
||||
pluginManager.reload_plugins(startup=True, initialize_implementations=False)
|
||||
|
||||
@@ -203,12 +245,46 @@ class Server(object):
|
||||
pluginLifecycleManager = LifecycleManager(pluginManager)
|
||||
preemptiveCache = PreemptiveCache(os.path.join(self._settings.getBaseFolder("data"), "preemptive_cache_config.yaml"))
|
||||
|
||||
# start regular check if we are connected to the internet
|
||||
connectivityEnabled = self._settings.getBoolean(["server", "onlineCheck", "enabled"])
|
||||
connectivityInterval = self._settings.getInt(["server", "onlineCheck", "interval"])
|
||||
connectivityHost = self._settings.get(["server", "onlineCheck", "host"])
|
||||
connectivityPort = self._settings.getInt(["server", "onlineCheck", "port"])
|
||||
|
||||
def on_connectivity_change(old_value, new_value):
|
||||
eventManager.fire(events.Events.CONNECTIVITY_CHANGED, payload=dict(old=old_value, new=new_value))
|
||||
|
||||
connectivityChecker = octoprint.util.ConnectivityChecker(connectivityInterval,
|
||||
connectivityHost,
|
||||
port=connectivityPort,
|
||||
enabled=connectivityEnabled,
|
||||
on_change=on_connectivity_change)
|
||||
|
||||
def on_settings_update(*args, **kwargs):
|
||||
# make sure our connectivity checker runs with the latest settings
|
||||
connectivityEnabled = self._settings.getBoolean(["server", "onlineCheck", "enabled"])
|
||||
connectivityInterval = self._settings.getInt(["server", "onlineCheck", "interval"])
|
||||
connectivityHost = self._settings.get(["server", "onlineCheck", "host"])
|
||||
connectivityPort = self._settings.getInt(["server", "onlineCheck", "port"])
|
||||
|
||||
if connectivityChecker.enabled != connectivityEnabled \
|
||||
or connectivityChecker.interval != connectivityInterval \
|
||||
or connectivityChecker.host != connectivityHost \
|
||||
or connectivityChecker.port != connectivityPort:
|
||||
connectivityChecker.enabled = connectivityEnabled
|
||||
connectivityChecker.interval = connectivityInterval
|
||||
connectivityChecker.host = connectivityHost
|
||||
connectivityChecker.port = connectivityPort
|
||||
connectivityChecker.check_immediately()
|
||||
|
||||
eventManager.subscribe(events.Events.SETTINGS_UPDATED, on_settings_update)
|
||||
|
||||
# setup access control
|
||||
userManagerName = self._settings.get(["accessControl", "userManager"])
|
||||
try:
|
||||
clazz = octoprint.util.get_class(userManagerName)
|
||||
userManager = clazz()
|
||||
except AttributeError as e:
|
||||
except:
|
||||
self._logger.exception("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(userManagerName))
|
||||
userManager = octoprint.users.FilebasedUserManager()
|
||||
finally:
|
||||
@@ -223,10 +299,33 @@ class Server(object):
|
||||
file_manager=fileManager,
|
||||
app_session_manager=appSessionManager,
|
||||
plugin_lifecycle_manager=pluginLifecycleManager,
|
||||
user_manager=userManager,
|
||||
preemptive_cache=preemptiveCache
|
||||
preemptive_cache=preemptiveCache,
|
||||
connectivity_checker=connectivityChecker
|
||||
)
|
||||
|
||||
# create user manager instance
|
||||
user_manager_factories = pluginManager.get_hooks("octoprint.users.factory")
|
||||
for name, factory in user_manager_factories.items():
|
||||
try:
|
||||
userManager = factory(components, self._settings)
|
||||
if userManager is not None:
|
||||
self._logger.debug("Created user manager instance from factory {}".format(name))
|
||||
break
|
||||
except:
|
||||
self._logger.exception("Error while creating user manager instance from factory {}".format(name))
|
||||
else:
|
||||
name = self._settings.get(["accessControl", "userManager"])
|
||||
try:
|
||||
clazz = octoprint.util.get_class(name)
|
||||
userManager = clazz()
|
||||
except:
|
||||
self._logger.exception(
|
||||
"Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(name))
|
||||
userManager = octoprint.users.FilebasedUserManager()
|
||||
finally:
|
||||
userManager.enabled = self._settings.getBoolean(["accessControl", "enabled"])
|
||||
components.update(dict(user_manager=userManager))
|
||||
|
||||
# create printer instance
|
||||
printer_factories = pluginManager.get_hooks("octoprint.printer.factory")
|
||||
for name, factory in printer_factories.items():
|
||||
@@ -342,7 +441,7 @@ class Server(object):
|
||||
if not userManager.enabled:
|
||||
loginManager.anonymous_user = users.DummyUser
|
||||
principals.identity_loaders.appendleft(users.dummy_identity_loader)
|
||||
loginManager.init_app(app)
|
||||
loginManager.init_app(app, add_context_processor=False)
|
||||
|
||||
# register API blueprint
|
||||
self._setup_blueprints()
|
||||
@@ -357,7 +456,8 @@ class Server(object):
|
||||
ioloop = IOLoop()
|
||||
ioloop.install()
|
||||
|
||||
self._router = SockJSRouter(self._create_socket_connection, "/sockjs")
|
||||
self._router = SockJSRouter(self._create_socket_connection, "/sockjs",
|
||||
session_kls=util.sockjs.ThreadSafeSession)
|
||||
|
||||
upload_suffixes = dict(name=self._settings.get(["server", "uploads", "nameSuffix"]), path=self._settings.get(["server", "uploads", "pathSuffix"]))
|
||||
|
||||
@@ -435,9 +535,22 @@ class Server(object):
|
||||
self._logger.debug("Adding additional route {route} handled by handler {handler} and with additional arguments {kwargs!r}".format(**locals()))
|
||||
server_routes.append((route, handler, kwargs))
|
||||
|
||||
server_routes.append((r".*", util.tornado.UploadStorageFallbackHandler, dict(fallback=util.tornado.WsgiInputContainer(app.wsgi_app), file_prefix="octoprint-file-upload-", file_suffix=".tmp", suffixes=upload_suffixes)))
|
||||
headers = {"X-Robots-Tag": "noindex, nofollow, noimageindex"}
|
||||
removed_headers = ["Server"]
|
||||
|
||||
self._tornado_app = Application(server_routes)
|
||||
server_routes.append((r".*", util.tornado.UploadStorageFallbackHandler, dict(fallback=util.tornado.WsgiInputContainer(app.wsgi_app,
|
||||
headers=headers,
|
||||
removed_headers=removed_headers),
|
||||
file_prefix="octoprint-file-upload-",
|
||||
file_suffix=".tmp",
|
||||
suffixes=upload_suffixes)))
|
||||
|
||||
transforms = [util.tornado.GlobalHeaderTransform.for_headers("OctoPrintGlobalHeaderTransform",
|
||||
headers=headers,
|
||||
removed_headers=removed_headers)]
|
||||
|
||||
self._tornado_app = Application(handlers=server_routes,
|
||||
transforms=transforms)
|
||||
max_body_sizes = [
|
||||
("POST", r"/api/files/([^/]*)", self._settings.getInt(["server", "uploads", "maxSize"])),
|
||||
("POST", r"/api/languages", 5 * 1024 * 1024)
|
||||
@@ -471,8 +584,13 @@ class Server(object):
|
||||
self._server = util.tornado.CustomHTTPServer(self._tornado_app, max_body_sizes=max_body_sizes, default_max_body_size=self._settings.getInt(["server", "maxSize"]))
|
||||
self._server.listen(self._port, address=self._host)
|
||||
|
||||
### From now on it's ok to launch subprocesses again
|
||||
|
||||
eventManager.fire(events.Events.STARTUP)
|
||||
|
||||
# analysis backlog
|
||||
fileManager.process_backlog()
|
||||
|
||||
# auto connect
|
||||
if self._settings.getBoolean(["serial", "autoconnect"]):
|
||||
try:
|
||||
@@ -553,7 +671,7 @@ class Server(object):
|
||||
"on_shutdown",
|
||||
sorting_context="ShutdownPlugin.on_shutdown")
|
||||
|
||||
# wait for shutdown even to be processed, but maximally for 15s
|
||||
# wait for shutdown event to be processed, but maximally for 15s
|
||||
event_timeout = 15.0
|
||||
if eventManager.join(timeout=event_timeout):
|
||||
self._logger.warn("Event loop was still busy processing after {}s, shutting down anyhow".format(event_timeout))
|
||||
@@ -568,13 +686,16 @@ class Server(object):
|
||||
def sigterm_handler(*args, **kwargs):
|
||||
# will stop tornado on SIGTERM, making the program exit cleanly
|
||||
def shutdown_tornado():
|
||||
self._logger.debug("Shutting down tornado's IOLoop...")
|
||||
ioloop.stop()
|
||||
self._logger.debug("SIGTERM received...")
|
||||
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()
|
||||
self._logger.debug("Tornado's IOLoop stopped")
|
||||
except (KeyboardInterrupt, SystemExit):
|
||||
pass
|
||||
except:
|
||||
@@ -1045,6 +1166,9 @@ class Server(object):
|
||||
"js/lib/jquery/jquery.ui.widget.js",
|
||||
"js/lib/jquery/jquery.ui.mouse.js",
|
||||
"js/lib/jquery/jquery.flot.js",
|
||||
"js/lib/jquery/jquery.flot.time.js",
|
||||
"js/lib/jquery/jquery.flot.crosshair.js",
|
||||
"js/lib/jquery/jquery.flot.resize.js",
|
||||
"js/lib/jquery/jquery.iframe-transport.js",
|
||||
"js/lib/jquery/jquery.fileupload.js",
|
||||
"js/lib/jquery/jquery.slimscroll.min.js",
|
||||
@@ -1100,7 +1224,8 @@ class Server(object):
|
||||
"css/bootstrap-modal.css",
|
||||
"css/bootstrap-slider.css",
|
||||
"css/bootstrap-tabdrop.css",
|
||||
"css/font-awesome.min.css",
|
||||
"vendor/font-awesome-3.2.1/css/font-awesome.min.css",
|
||||
"vendor/font-awesome-4.7.0/css/font-awesome.min.css",
|
||||
"css/jquery.fileupload-ui.css",
|
||||
"css/pnotify.core.min.css",
|
||||
"css/pnotify.buttons.min.css",
|
||||
@@ -1112,75 +1237,61 @@ class Server(object):
|
||||
less_core = list(dynamic_core_assets["less"]) + list(dynamic_plugin_assets["bundled"]["less"])
|
||||
less_plugins = list(dynamic_plugin_assets["external"]["less"])
|
||||
|
||||
from webassets.filter import register_filter, Filter
|
||||
from webassets.filter.cssrewrite.base import PatternRewriter
|
||||
import re
|
||||
class LessImportRewrite(PatternRewriter):
|
||||
name = "less_importrewrite"
|
||||
|
||||
patterns = {
|
||||
"import_rewrite": re.compile("(@import(\s+\(.*\))?\s+)\"(.*)\";")
|
||||
}
|
||||
|
||||
def import_rewrite(self, m):
|
||||
import_with_options = m.group(1)
|
||||
import_url = m.group(3)
|
||||
|
||||
if not import_url.startswith("http:") and not import_url.startswith("https:") and not import_url.startswith("/"):
|
||||
import_url = "../less/" + import_url
|
||||
|
||||
return "{import_with_options}\"{import_url}\";".format(**locals())
|
||||
|
||||
class JsDelimiterBundler(Filter):
|
||||
name = "js_delimiter_bundler"
|
||||
options = {}
|
||||
def input(self, _in, out, **kwargs):
|
||||
out.write(_in.read())
|
||||
out.write("\n;\n")
|
||||
# a couple of custom filters
|
||||
from octoprint.server.util.webassets import LessImportRewrite, JsDelimiterBundler, SourceMapRewrite, SourceMapRemove
|
||||
from webassets.filter import register_filter
|
||||
|
||||
register_filter(LessImportRewrite)
|
||||
register_filter(SourceMapRewrite)
|
||||
register_filter(SourceMapRemove)
|
||||
register_filter(JsDelimiterBundler)
|
||||
|
||||
# JS
|
||||
js_libs_bundle = Bundle(*js_libs, output="webassets/packed_libs.js", filters="js_delimiter_bundler")
|
||||
js_filters = ["sourcemap_remove", "js_delimiter_bundler"]
|
||||
|
||||
js_client_bundle = Bundle(*js_client, output="webassets/packed_client.js", filters="js_delimiter_bundler")
|
||||
js_core_bundle = Bundle(*js_core, output="webassets/packed_core.js", filters="js_delimiter_bundler")
|
||||
js_libs_bundle = Bundle(*js_libs, output="webassets/packed_libs.js", filters=",".join(js_filters))
|
||||
|
||||
js_client_bundle = Bundle(*js_client, output="webassets/packed_client.js", filters=",".join(js_filters))
|
||||
js_core_bundle = Bundle(*js_core, output="webassets/packed_core.js", filters=",".join(js_filters))
|
||||
|
||||
if len(js_plugins) == 0:
|
||||
js_plugins_bundle = Bundle(*[])
|
||||
else:
|
||||
js_plugins_bundle = Bundle(*js_plugins, output="webassets/packed_plugins.js", filters="js_delimiter_bundler")
|
||||
js_plugins_bundle = Bundle(*js_plugins, output="webassets/packed_plugins.js", filters=",".join(js_filters))
|
||||
|
||||
js_app_bundle = Bundle(js_plugins_bundle, js_core_bundle, output="webassets/packed_app.js", filters="js_delimiter_bundler")
|
||||
js_app_bundle = Bundle(js_plugins_bundle, js_core_bundle, output="webassets/packed_app.js", filters=",".join(js_filters))
|
||||
|
||||
# CSS
|
||||
css_libs_bundle = Bundle(*css_libs, output="webassets/packed_libs.css")
|
||||
css_filters = ["cssrewrite"]
|
||||
|
||||
css_libs_bundle = Bundle(*css_libs, output="webassets/packed_libs.css", filters=",".join(css_filters))
|
||||
|
||||
if len(css_core) == 0:
|
||||
css_core_bundle = Bundle(*[])
|
||||
else:
|
||||
css_core_bundle = Bundle(*css_core, output="webassets/packed_core.css", filters="cssrewrite")
|
||||
css_core_bundle = Bundle(*css_core, output="webassets/packed_core.css", filters=",".join(css_filters))
|
||||
|
||||
if len(css_plugins) == 0:
|
||||
css_plugins_bundle = Bundle(*[])
|
||||
else:
|
||||
css_plugins_bundle = Bundle(*css_plugins, output="webassets/packed_plugins.css", filters="cssrewrite")
|
||||
css_plugins_bundle = Bundle(*css_plugins, output="webassets/packed_plugins.css", filters=",".join(css_filters))
|
||||
|
||||
css_app_bundle = Bundle(css_core, css_plugins, output="webassets/packed_app.css", filters="cssrewrite")
|
||||
css_app_bundle = Bundle(css_core, css_plugins, output="webassets/packed_app.css", filters=",".join(css_filters))
|
||||
|
||||
# LESS
|
||||
less_filters = ["cssrewrite", "less_importrewrite"]
|
||||
|
||||
if len(less_core) == 0:
|
||||
less_core_bundle = Bundle(*[])
|
||||
else:
|
||||
less_core_bundle = Bundle(*less_core, output="webassets/packed_core.less", filters="cssrewrite, less_importrewrite")
|
||||
less_core_bundle = Bundle(*less_core, output="webassets/packed_core.less", filters=",".join(less_filters))
|
||||
|
||||
if len(less_plugins) == 0:
|
||||
less_plugins_bundle = Bundle(*[])
|
||||
else:
|
||||
less_plugins_bundle = Bundle(*less_plugins, output="webassets/packed_plugins.less", filters="cssrewrite, less_importrewrite")
|
||||
less_plugins_bundle = Bundle(*less_plugins, output="webassets/packed_plugins.less", filters=",".join(less_filters))
|
||||
|
||||
less_app_bundle = Bundle(less_core, less_plugins, output="webassets/packed_app.less", filters="cssrewrite, less_importrewrite")
|
||||
less_app_bundle = Bundle(less_core, less_plugins, output="webassets/packed_app.less", filters=",".join(less_filters))
|
||||
|
||||
# asset registration
|
||||
assets.register("js_libs", js_libs_bundle)
|
||||
@@ -1265,21 +1376,44 @@ class Server(object):
|
||||
|
||||
rules = map(process, filter(lambda rule: len(rule) == 2 or len(rule) == 3, rules))
|
||||
|
||||
self._intermediary_server = BaseHTTPServer.HTTPServer((host, port), lambda *args, **kwargs: IntermediaryServerHandler(rules, *args, **kwargs))
|
||||
self._intermediary_server = BaseHTTPServer.HTTPServer((host, port),
|
||||
lambda *args, **kwargs: IntermediaryServerHandler(rules, *args, **kwargs),
|
||||
bind_and_activate=False)
|
||||
|
||||
thread = threading.Thread(target=self._intermediary_server.serve_forever)
|
||||
# if possible, make sure our socket's port descriptor isn't handed over to subprocesses
|
||||
from octoprint.util.platform import set_close_exec
|
||||
try:
|
||||
set_close_exec(self._intermediary_server.fileno())
|
||||
except:
|
||||
self._logger.exception("Error while attempting to set_close_exec on intermediary server socket")
|
||||
|
||||
# then bind the server and have it serve our handler until stopped
|
||||
try:
|
||||
self._intermediary_server.server_bind()
|
||||
self._intermediary_server.server_activate()
|
||||
except:
|
||||
self._intermediary_server.server_close()
|
||||
raise
|
||||
|
||||
def serve():
|
||||
try:
|
||||
self._intermediary_server.serve_forever()
|
||||
except:
|
||||
self._logger.exception("Error in intermediary server")
|
||||
|
||||
thread = threading.Thread(target=serve)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
self._logger.debug("Intermediary server started")
|
||||
self._logger.info("Intermediary server started")
|
||||
|
||||
def _stop_intermediary_server(self):
|
||||
if self._intermediary_server is None:
|
||||
return
|
||||
self._logger.debug("Shutting down intermediary server...")
|
||||
self._logger.info("Shutting down intermediary server...")
|
||||
self._intermediary_server.shutdown()
|
||||
self._intermediary_server.server_close()
|
||||
self._logger.debug("Intermediary server shut down")
|
||||
self._logger.info("Intermediary server shut down")
|
||||
|
||||
class LifecycleManager(object):
|
||||
def __init__(self, plugin_manager):
|
||||
|
||||
@@ -207,7 +207,7 @@ def login():
|
||||
if octoprint.server.userManager.checkPassword(username, password):
|
||||
if octoprint.server.userManager.enabled:
|
||||
user = octoprint.server.userManager.login_user(user)
|
||||
session["usersession.id"] = user.get_session()
|
||||
session["usersession.id"] = user.session
|
||||
g.user = user
|
||||
login_user(user, remember=remember)
|
||||
identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
|
||||
@@ -222,22 +222,21 @@ def login():
|
||||
@api.route("/logout", methods=["POST"])
|
||||
@restricted_access
|
||||
def logout():
|
||||
# Remove session keys set by Flask-Principal
|
||||
for key in ('identity.id', 'identity.name', 'identity.auth_type'):
|
||||
if key in session:
|
||||
del session[key]
|
||||
identity_changed.send(current_app._get_current_object(), identity=AnonymousIdentity())
|
||||
|
||||
# logout from user manager...
|
||||
_logout(current_user)
|
||||
|
||||
# ... and from flask login (and principal)
|
||||
logout_user()
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
def _logout(user):
|
||||
if "usersession.id" in session:
|
||||
del session["usersession.id"]
|
||||
octoprint.server.userManager.logout_user(user)
|
||||
|
||||
|
||||
@api.route("/util/test", methods=["POST"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
|
||||
@@ -78,8 +78,8 @@ def _get_options():
|
||||
default_profile = printerProfileManager.get_default()
|
||||
|
||||
options = dict(
|
||||
ports=connection_options["ports"],
|
||||
baudrates=connection_options["baudrates"],
|
||||
ports=sorted(connection_options["ports"]),
|
||||
baudrates=sorted(connection_options["baudrates"], reverse=True),
|
||||
printerProfiles=[dict(id=printer_profile["id"], name=printer_profile["name"] if "name" in printer_profile else printer_profile["id"]) for printer_profile in profile_options.values() if "id" in printer_profile],
|
||||
portPreference=connection_options["portPreference"],
|
||||
baudratePreference=connection_options["baudratePreference"],
|
||||
|
||||
@@ -464,6 +464,7 @@ def gcodeFileCommand(filename, target):
|
||||
valid_commands = {
|
||||
"select": [],
|
||||
"slice": [],
|
||||
"analyse": [],
|
||||
"copy": ["destination"],
|
||||
"move": ["destination"]
|
||||
}
|
||||
@@ -616,6 +617,17 @@ def gcodeFileCommand(filename, target):
|
||||
r.headers["Location"] = location
|
||||
return r
|
||||
|
||||
elif command == "analyse":
|
||||
if not _verifyFileExists(target, filename):
|
||||
return make_response("File not found on '%s': %s" % (target, filename), 404)
|
||||
|
||||
printer_profile = None
|
||||
if "printerProfile" in data and data["printerProfile"]:
|
||||
printer_profile = data["printerProfile"]
|
||||
|
||||
if not fileManager.analyse(target, filename, printer_profile_id=printer_profile):
|
||||
return make_response("No analysis possible for {} on {}".format(filename, target), 400)
|
||||
|
||||
elif command == "copy" or command == "move":
|
||||
# Copy and move are only possible on local storage
|
||||
if not target in [FileDestinations.LOCAL]:
|
||||
|
||||
@@ -11,6 +11,8 @@ import copy
|
||||
from flask import jsonify, make_response, request, url_for
|
||||
from werkzeug.exceptions import BadRequest
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
from octoprint.server.api import api, NO_CONTENT, valid_boolean_trues
|
||||
from octoprint.server.util.flask import restricted_access, with_revalidation_checking
|
||||
from octoprint.util import dict_merge
|
||||
@@ -18,7 +20,6 @@ from octoprint.util import dict_merge
|
||||
from octoprint.server import printerProfileManager
|
||||
from octoprint.printer.profile import InvalidProfileError, CouldNotOverwriteError, SaveError
|
||||
|
||||
|
||||
def _lastmodified():
|
||||
return printerProfileManager.last_modified
|
||||
|
||||
|
||||
@@ -99,6 +99,7 @@ def getSettings():
|
||||
"webcam": {
|
||||
"streamUrl": s.get(["webcam", "stream"]),
|
||||
"streamRatio": s.get(["webcam", "streamRatio"]),
|
||||
"streamTimeout": s.getInt(["webcam", "streamTimeout"]),
|
||||
"snapshotUrl": s.get(["webcam", "snapshot"]),
|
||||
"ffmpegPath": s.get(["webcam", "ffmpeg"]),
|
||||
"bitrate": s.get(["webcam", "bitrate"]),
|
||||
@@ -142,6 +143,7 @@ def getSettings():
|
||||
"timeoutCommunication": s.getFloat(["serial", "timeout", "communication"]),
|
||||
"timeoutTemperature": s.getFloat(["serial", "timeout", "temperature"]),
|
||||
"timeoutTemperatureTargetSet": s.getFloat(["serial", "timeout", "temperatureTargetSet"]),
|
||||
"timeoutTemperatureAutoreport": s.getFloat(["serial", "timeout", "temperatureAutoreport"]),
|
||||
"timeoutSdStatus": s.getFloat(["serial", "timeout", "sdStatus"]),
|
||||
"log": s.getBoolean(["serial", "log"]),
|
||||
"additionalPorts": s.get(["serial", "additionalPorts"]),
|
||||
@@ -152,6 +154,8 @@ def getSettings():
|
||||
"ignoreErrorsFromFirmware": s.getBoolean(["serial", "ignoreErrorsFromFirmware"]),
|
||||
"disconnectOnErrors": s.getBoolean(["serial", "disconnectOnErrors"]),
|
||||
"triggerOkForM29": s.getBoolean(["serial", "triggerOkForM29"]),
|
||||
"logPositionOnPause": s.getBoolean(["serial", "logPositionOnPause"]),
|
||||
"logPositionOnCancel": s.getBoolean(["serial", "logPositionOnCancel"]),
|
||||
"supportResendsWithoutOk": s.getBoolean(["serial", "supportResendsWithoutOk"]),
|
||||
"maxTimeoutsIdle": s.getInt(["serial", "maxCommunicationTimeouts", "idle"]),
|
||||
"maxTimeoutsPrinting": s.getInt(["serial", "maxCommunicationTimeouts", "printing"]),
|
||||
@@ -166,7 +170,9 @@ def getSettings():
|
||||
},
|
||||
"temperature": {
|
||||
"profiles": s.get(["temperature", "profiles"]),
|
||||
"cutoff": s.getInt(["temperature", "cutoff"])
|
||||
"cutoff": s.getInt(["temperature", "cutoff"]),
|
||||
"sendAutomatically": s.getBoolean(["temperature", "sendAutomatically"]),
|
||||
"sendAutomaticallyAfter": s.getInt(["temperature", "sendAutomaticallyAfter"], min=0, max=30),
|
||||
},
|
||||
"system": {
|
||||
"actions": s.get(["system", "actions"]),
|
||||
@@ -182,6 +188,8 @@ def getSettings():
|
||||
"afterPrintDone": None,
|
||||
"beforePrintPaused": None,
|
||||
"afterPrintResumed": None,
|
||||
"beforeToolChange": None,
|
||||
"afterToolChange": None,
|
||||
"snippets": dict()
|
||||
}
|
||||
},
|
||||
@@ -194,6 +202,12 @@ def getSettings():
|
||||
"diskspace": {
|
||||
"warning": s.getInt(["server", "diskspace", "warning"]),
|
||||
"critical": s.getInt(["server", "diskspace", "critical"])
|
||||
},
|
||||
"onlineCheck": {
|
||||
"enabled": s.getBoolean(["server", "onlineCheck", "enabled"]),
|
||||
"interval": int(s.getInt(["server", "onlineCheck", "interval"]) / 60),
|
||||
"host": s.get(["server", "onlineCheck", "host"]),
|
||||
"port": s.getInt(["server", "onlineCheck", "port"])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -306,6 +320,7 @@ def _saveSettings(data):
|
||||
if "webcam" in data.keys():
|
||||
if "streamUrl" in data["webcam"]: s.set(["webcam", "stream"], data["webcam"]["streamUrl"])
|
||||
if "streamRatio" in data["webcam"] and data["webcam"]["streamRatio"] in ("16:9", "4:3"): s.set(["webcam", "streamRatio"], data["webcam"]["streamRatio"])
|
||||
if "streamTimeout" in data["webcam"]: s.setInt(["webcam", "streamTimeout"], data["webcam"]["streamTimeout"])
|
||||
if "snapshotUrl" in data["webcam"]: s.set(["webcam", "snapshot"], data["webcam"]["snapshotUrl"])
|
||||
if "ffmpegPath" in data["webcam"]: s.set(["webcam", "ffmpeg"], data["webcam"]["ffmpegPath"])
|
||||
if "bitrate" in data["webcam"]: s.set(["webcam", "bitrate"], data["webcam"]["bitrate"])
|
||||
@@ -347,6 +362,7 @@ def _saveSettings(data):
|
||||
if "timeoutCommunication" in data["serial"]: s.setFloat(["serial", "timeout", "communication"], data["serial"]["timeoutCommunication"])
|
||||
if "timeoutTemperature" in data["serial"]: s.setFloat(["serial", "timeout", "temperature"], data["serial"]["timeoutTemperature"])
|
||||
if "timeoutTemperatureTargetSet" in data["serial"]: s.setFloat(["serial", "timeout", "temperatureTargetSet"], data["serial"]["timeoutTemperatureTargetSet"])
|
||||
if "timeoutTemperatureAutoreport" in data["serial"]: s.setFloat(["serial", "timeout", "temperatureAutoreport"], data["serial"]["timeoutTemperatureAutoreport"])
|
||||
if "timeoutSdStatus" in data["serial"]: s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"])
|
||||
if "additionalPorts" in data["serial"] and isinstance(data["serial"]["additionalPorts"], (list, tuple)): s.set(["serial", "additionalPorts"], data["serial"]["additionalPorts"])
|
||||
if "additionalBaudrates" in data["serial"] and isinstance(data["serial"]["additionalBaudrates"], (list, tuple)): s.set(["serial", "additionalBaudrates"], data["serial"]["additionalBaudrates"])
|
||||
@@ -357,6 +373,8 @@ def _saveSettings(data):
|
||||
if "disconnectOnErrors" in data["serial"]: s.setBoolean(["serial", "disconnectOnErrors"], data["serial"]["disconnectOnErrors"])
|
||||
if "triggerOkForM29" in data["serial"]: s.setBoolean(["serial", "triggerOkForM29"], data["serial"]["triggerOkForM29"])
|
||||
if "supportResendsWithoutOk" in data["serial"]: s.setBoolean(["serial", "supportResendsWithoutOk"], data["serial"]["supportResendsWithoutOk"])
|
||||
if "logPositionOnPause" in data["serial"]: s.setBoolean(["serial", "logPositionOnPause"], data["serial"]["logPositionOnPause"])
|
||||
if "logPositionOnCancel" in data["serial"]: s.setBoolean(["serial", "logPositionOnCancel"], data["serial"]["logPositionOnCancel"])
|
||||
if "maxTimeoutsIdle" in data["serial"]: s.setInt(["serial", "maxCommunicationTimeouts", "idle"], data["serial"]["maxTimeoutsIdle"])
|
||||
if "maxTimeoutsPrinting" in data["serial"]: s.setInt(["serial", "maxCommunicationTimeouts", "printing"], data["serial"]["maxTimeoutsPrinting"])
|
||||
if "maxTimeoutsLong" in data["serial"]: s.setInt(["serial", "maxCommunicationTimeouts", "long"], data["serial"]["maxTimeoutsLong"])
|
||||
@@ -382,6 +400,8 @@ def _saveSettings(data):
|
||||
if "temperature" in data.keys():
|
||||
if "profiles" in data["temperature"]: s.set(["temperature", "profiles"], data["temperature"]["profiles"])
|
||||
if "cutoff" in data["temperature"]: s.setInt(["temperature", "cutoff"], data["temperature"]["cutoff"])
|
||||
if "sendAutomatically" in data["temperature"]: s.setBoolean(["temperature", "sendAutomatically"], data["temperature"]["sendAutomatically"])
|
||||
if "sendAutomaticallyAfter" in data["temperature"]: s.setInt(["temperature", "sendAutomaticallyAfter"], data["temperature"]["sendAutomaticallyAfter"], min=0, max=30)
|
||||
|
||||
if "terminalFilters" in data.keys():
|
||||
s.set(["terminalFilters"], data["terminalFilters"])
|
||||
@@ -405,6 +425,16 @@ def _saveSettings(data):
|
||||
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 "onlineCheck" in data["server"]:
|
||||
if "enabled" in data["server"]["onlineCheck"]: s.setBoolean(["server", "onlineCheck", "enabled"], data["server"]["onlineCheck"]["enabled"])
|
||||
if "interval" in data["server"]["onlineCheck"]:
|
||||
try:
|
||||
interval = int(data["server"]["onlineCheck"]["interval"])
|
||||
s.setInt(["server", "onlineCheck", "interval"], interval*60)
|
||||
except ValueError:
|
||||
pass
|
||||
if "host" in data["server"]["onlineCheck"]: s.set(["server", "onlineCheck", "host"], data["server"]["onlineCheck"]["host"])
|
||||
if "port" in data["server"]["onlineCheck"]: s.setInt(["server", "onlineCheck", "port"], data["server"]["onlineCheck"]["port"])
|
||||
|
||||
if "plugins" in data:
|
||||
for plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin):
|
||||
|
||||
@@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
|
||||
import collections
|
||||
import logging
|
||||
import sarge
|
||||
import threading
|
||||
|
||||
from flask import request, make_response, jsonify, url_for
|
||||
from flask.ext.babel import gettext
|
||||
@@ -16,6 +17,7 @@ from octoprint.settings import settings as s
|
||||
from octoprint.server import admin_permission, NO_CONTENT
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.util.flask import restricted_access, get_remote_address
|
||||
from octoprint.logging import prefix_multilines
|
||||
|
||||
|
||||
@api.route("/system", methods=["POST"])
|
||||
@@ -74,38 +76,59 @@ def executeSystemCommand(source, command):
|
||||
|
||||
do_async = command_spec.get("async", False)
|
||||
do_ignore = command_spec.get("ignore", False)
|
||||
logger.info("Performing command for {}:{}: {}".format(source, command, command_spec["command"]))
|
||||
debug = command_spec.get("debug", False)
|
||||
|
||||
if logger.isEnabledFor(logging.DEBUG) or debug:
|
||||
logger.info("Performing command for {}:{}: {}".format(source, command, command_spec["command"]))
|
||||
else:
|
||||
logger.info("Performing command for {}:{}".format(source, command))
|
||||
|
||||
try:
|
||||
if "before" in command_spec and callable(command_spec["before"]):
|
||||
command_spec["before"]()
|
||||
except Exception as e:
|
||||
if not do_ignore:
|
||||
error = "Command \"before\" failed: {}".format(str(e))
|
||||
error = "Command \"before\" for {}:{} failed: {}".format(source, command, str(e))
|
||||
logger.warn(error)
|
||||
return make_response(error, 500)
|
||||
|
||||
try:
|
||||
# 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(command_spec["command"],
|
||||
stdout=sarge.Capture(),
|
||||
stderr=sarge.Capture(),
|
||||
shell=True,
|
||||
async=do_async)
|
||||
if not do_async:
|
||||
def execute():
|
||||
# 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(command_spec["command"],
|
||||
stdout=sarge.Capture(),
|
||||
stderr=sarge.Capture(),
|
||||
shell=True)
|
||||
|
||||
if not do_ignore and p.returncode != 0:
|
||||
returncode = p.returncode
|
||||
stdout_text = p.stdout.text
|
||||
stderr_text = p.stderr.text
|
||||
|
||||
error = "Command failed with return code {}:\nSTDOUT: {}\nSTDERR: {}".format(returncode, stdout_text, stderr_text)
|
||||
logger.warn(error)
|
||||
return make_response(error, 500)
|
||||
error = "Command for {}:{} failed with return code {}:\nSTDOUT: {}\nSTDERR: {}".format(source, command,
|
||||
returncode,
|
||||
stdout_text,
|
||||
stderr_text)
|
||||
logger.warn(prefix_multilines(error, prefix="! "))
|
||||
if not do_async:
|
||||
raise CommandFailed(error)
|
||||
|
||||
if do_async:
|
||||
thread = threading.Thread(target=execute)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
else:
|
||||
try:
|
||||
execute()
|
||||
except CommandFailed as exc:
|
||||
return make_response(exc.error, 500)
|
||||
|
||||
except Exception as e:
|
||||
if not do_ignore:
|
||||
error = "Command failed: {}".format(str(e))
|
||||
error = "Command for {}:{} failed: {}".format(source, command, str(e))
|
||||
logger.warn(error)
|
||||
return make_response(error, 500)
|
||||
|
||||
@@ -164,7 +187,10 @@ def _get_core_command_specs():
|
||||
for action, spec in commands.items():
|
||||
if not spec["command"]:
|
||||
continue
|
||||
spec.update(dict(action=action, source="core", async=True, ignore=True))
|
||||
spec.update(dict(action=action,
|
||||
source="core",
|
||||
async=True,
|
||||
debug=True))
|
||||
available_commands[action] = spec
|
||||
return available_commands
|
||||
|
||||
@@ -202,3 +228,7 @@ def _get_custom_command_spec(action):
|
||||
|
||||
return available_actions[action]
|
||||
|
||||
|
||||
class CommandFailed(Exception):
|
||||
def __init__(self, error):
|
||||
self.error = error
|
||||
@@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import os
|
||||
import threading
|
||||
import logging
|
||||
|
||||
from flask import request, jsonify, url_for, make_response
|
||||
from werkzeug.utils import secure_filename
|
||||
@@ -128,7 +129,12 @@ def deleteTimelapse(filename):
|
||||
timelapse_folder = settings().getBaseFolder("timelapse")
|
||||
full_path = os.path.realpath(os.path.join(timelapse_folder, filename))
|
||||
if full_path.startswith(timelapse_folder) and os.path.exists(full_path):
|
||||
os.remove(full_path)
|
||||
try:
|
||||
os.remove(full_path)
|
||||
except Exception as ex:
|
||||
logging.getLogger(__file__).exception("Error deleting timelapse file {}".format(full_path))
|
||||
return make_response("Unexpected error: {}".format(ex), 500)
|
||||
|
||||
return getTimelapseData()
|
||||
|
||||
|
||||
|
||||
@@ -29,6 +29,8 @@ import octoprint.plugin
|
||||
|
||||
from werkzeug.contrib.cache import BaseCache
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
try:
|
||||
from os import scandir, walk
|
||||
except ImportError:
|
||||
@@ -453,9 +455,12 @@ class OctoPrintFlaskRequest(flask.Request):
|
||||
|
||||
We need this because cookies are not port-specific and we don't want to overwrite our
|
||||
session and other cookies from one OctoPrint instance on our machine with those of another
|
||||
one who happens to listen on the same address albeit a different port.
|
||||
one who happens to listen on the same address albeit a different port or script root.
|
||||
"""
|
||||
return "_P" + self.server_port
|
||||
result = "_P" + self.server_port
|
||||
if self.script_root:
|
||||
return result + "_R" + self.script_root.replace("/", "|")
|
||||
return result
|
||||
|
||||
|
||||
class OctoPrintFlaskResponse(flask.Response):
|
||||
@@ -484,8 +489,8 @@ def passive_login():
|
||||
|
||||
if user is not None and not user.is_anonymous():
|
||||
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()
|
||||
if hasattr(user, "session"):
|
||||
flask.session["usersession.id"] = user.session
|
||||
flask.g.user = user
|
||||
return flask.jsonify(user.asDict())
|
||||
elif settings().getBoolean(["accessControl", "autologinLocal"]) \
|
||||
@@ -503,7 +508,7 @@ def passive_login():
|
||||
user = octoprint.server.userManager.findUser(autologinAs)
|
||||
if user is not None:
|
||||
user = octoprint.server.userManager.login_user(user)
|
||||
flask.session["usersession.id"] = user.get_session()
|
||||
flask.session["usersession.id"] = user.session
|
||||
flask.g.user = user
|
||||
flask.ext.login.login_user(user)
|
||||
flask.ext.principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask.ext.principal.Identity(user.get_id()))
|
||||
|
||||
@@ -8,6 +8,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
import logging
|
||||
import threading
|
||||
import sockjs.tornado
|
||||
import sockjs.tornado.session
|
||||
import time
|
||||
|
||||
import octoprint.timelapse
|
||||
@@ -21,6 +22,34 @@ from octoprint.settings import settings
|
||||
import octoprint.printer
|
||||
|
||||
|
||||
class ThreadSafeSession(sockjs.tornado.session.Session):
|
||||
def __init__(self, conn, server, session_id, expiry=None):
|
||||
sockjs.tornado.session.Session.__init__(self, conn, server, session_id, expiry=expiry)
|
||||
|
||||
def set_handler(self, handler, start_heartbeat=True):
|
||||
if getattr(handler, "__orig_send_pack", None) is None:
|
||||
orig_send_pack = handler.send_pack
|
||||
mutex = threading.RLock()
|
||||
|
||||
def send_pack(*args, **kwargs):
|
||||
with mutex:
|
||||
return orig_send_pack(*args, **kwargs)
|
||||
|
||||
handler.send_pack = send_pack
|
||||
setattr(handler, "__orig_send_pack", orig_send_pack)
|
||||
|
||||
return sockjs.tornado.session.Session.set_handler(self, handler, start_heartbeat=start_heartbeat)
|
||||
|
||||
def remove_handler(self, handler):
|
||||
result = sockjs.tornado.session.Session.remove_handler(self, handler)
|
||||
|
||||
if getattr(handler, "__orig_send_pack", None) is not None:
|
||||
handler.send_pack = getattr(handler, "__orig_send_pack")
|
||||
delattr(handler, "__orig_send_pack")
|
||||
|
||||
return result
|
||||
|
||||
|
||||
class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.PrinterCallback):
|
||||
def __init__(self, printer, fileManager, analysisQueue, userManager, eventManager, pluginManager, session):
|
||||
sockjs.tornado.SockJSConnection.__init__(self, session)
|
||||
@@ -47,8 +76,6 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.
|
||||
self._lastCurrent = 0
|
||||
self._baseRateLimit = 0.5
|
||||
|
||||
self._emit_mutex = threading.RLock()
|
||||
|
||||
def _getRemoteAddress(self, info):
|
||||
forwardedFor = info.headers.get("X-Forwarded-For")
|
||||
if forwardedFor is not None:
|
||||
@@ -205,11 +232,10 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.
|
||||
self.sendEvent(event, payload)
|
||||
|
||||
def _emit(self, type, payload):
|
||||
with self._emit_mutex:
|
||||
try:
|
||||
self.send({type: payload})
|
||||
except Exception as e:
|
||||
if self._logger.isEnabledFor(logging.DEBUG):
|
||||
self._logger.exception("Could not send message to client {}".format(self._remoteAddress))
|
||||
else:
|
||||
self._logger.warn("Could not send message to client {}: {}".format(self._remoteAddress, e))
|
||||
try:
|
||||
self.send({type: payload})
|
||||
except Exception as e:
|
||||
if self._logger.isEnabledFor(logging.DEBUG):
|
||||
self._logger.exception("Could not send message to client {}".format(self._remoteAddress))
|
||||
else:
|
||||
self._logger.warn("Could not send message to client {}: {}".format(self._remoteAddress, e))
|
||||
@@ -531,9 +531,20 @@ class WsgiInputContainer(object):
|
||||
methods have been adjusted to allow for an optionally supplied ``body`` argument which is then used for ``wsgi.input``.
|
||||
"""
|
||||
|
||||
def __init__(self, wsgi_application):
|
||||
def __init__(self, wsgi_application, headers=None, forced_headers=None, removed_headers=None):
|
||||
self.wsgi_application = wsgi_application
|
||||
|
||||
if headers is None:
|
||||
headers = dict()
|
||||
if forced_headers is None:
|
||||
forced_headers = dict()
|
||||
if removed_headers is None:
|
||||
removed_headers = []
|
||||
|
||||
self.headers = headers
|
||||
self.forced_headers = forced_headers
|
||||
self.removed_headers = removed_headers
|
||||
|
||||
def __call__(self, request, body=None):
|
||||
"""
|
||||
Wraps the call against the WSGI app, deriving the WSGI environment from the supplied Tornado ``HTTPServerRequest``.
|
||||
@@ -569,8 +580,14 @@ class WsgiInputContainer(object):
|
||||
headers.append(("Content-Length", str(len(body))))
|
||||
if "content-type" not in header_set:
|
||||
headers.append(("Content-Type", "text/html; charset=UTF-8"))
|
||||
if "server" not in header_set:
|
||||
headers.append(("Server", "TornadoServer/%s" % tornado.version))
|
||||
|
||||
header_set = set(k.lower() for (k, v) in headers)
|
||||
for header, value in self.headers.items():
|
||||
if header.lower() not in header_set:
|
||||
headers.append((header, value))
|
||||
for header, value in self.forced_headers.items():
|
||||
headers.append((header, value))
|
||||
headers = [(header, value) for header, value in headers if not header.lower() in self.removed_headers]
|
||||
|
||||
parts = [tornado.escape.utf8("HTTP/1.1 " + data["status"] + "\r\n")]
|
||||
for key, value in headers:
|
||||
@@ -1025,6 +1042,39 @@ class StaticDataHandler(tornado.web.RequestHandler):
|
||||
self.finish()
|
||||
|
||||
|
||||
class GlobalHeaderTransform(tornado.web.OutputTransform):
|
||||
|
||||
HEADERS = dict()
|
||||
FORCED_HEADERS = dict()
|
||||
REMOVED_HEADERS = []
|
||||
|
||||
@classmethod
|
||||
def for_headers(cls, name, headers=None, forced_headers=None, removed_headers=None):
|
||||
if headers is None:
|
||||
headers = dict()
|
||||
if forced_headers is None:
|
||||
forced_headers = dict()
|
||||
if removed_headers is None:
|
||||
removed_headers = []
|
||||
|
||||
return type(name, (GlobalHeaderTransform,), dict(HEADERS=headers,
|
||||
FORCED_HEADERS=forced_headers,
|
||||
REMOVED_HEADERS=removed_headers))
|
||||
|
||||
def __init__(self, request):
|
||||
tornado.web.OutputTransform.__init__(self, request)
|
||||
|
||||
def transform_first_chunk(self, status_code, headers, chunk, finishing):
|
||||
for header, value in self.HEADERS.items():
|
||||
if not header in headers:
|
||||
headers[header] = value
|
||||
for header, value in self.FORCED_HEADERS.items():
|
||||
headers[header] = value
|
||||
for header in self.REMOVED_HEADERS:
|
||||
del headers[header]
|
||||
return status_code, headers, chunk
|
||||
|
||||
|
||||
#~~ Factory method for creating Flask access validation wrappers from the Tornado request context
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__author__ = "Gina Häußge <gina@octoprint.org>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import re
|
||||
|
||||
try:
|
||||
from urllib import parse as urlparse
|
||||
except:
|
||||
import urlparse
|
||||
|
||||
from webassets.filter import Filter
|
||||
from webassets.filter.cssrewrite.base import PatternRewriter
|
||||
import webassets.filter.cssrewrite.urlpath as urlpath
|
||||
|
||||
|
||||
def replace_url(source_url, output_url, url):
|
||||
# If path is an absolute one, keep it
|
||||
parsed = urlparse.urlparse(url)
|
||||
|
||||
if not parsed.scheme and not parsed.path.startswith('/'):
|
||||
abs_source_url = urlparse.urljoin(source_url, url)
|
||||
|
||||
# relpath() will not detect this case
|
||||
if urlparse.urlparse(abs_source_url).scheme:
|
||||
return abs_source_url
|
||||
|
||||
# rewritten url: relative path from new location (output)
|
||||
# to location of referenced file (source + current url)
|
||||
url = urlpath.relpath(output_url, abs_source_url)
|
||||
|
||||
return url
|
||||
|
||||
|
||||
class UrlRewriter(PatternRewriter):
|
||||
|
||||
def input(self, _in, out, **kw):
|
||||
source, source_path, output, output_path = \
|
||||
kw['source'], kw['source_path'], kw['output'], kw['output_path']
|
||||
|
||||
self.source_path = source_path
|
||||
self.output_path = output_path
|
||||
self.source_url = self.ctx.resolver.resolve_source_to_url(
|
||||
self.ctx, source_path, source)
|
||||
self.output_url = self.ctx.resolver.resolve_output_to_url(
|
||||
self.ctx, output)
|
||||
|
||||
return super(UrlRewriter, self).input(_in, out, **kw)
|
||||
|
||||
def replace_url(self, url):
|
||||
return replace_url(self.source_url, self.output_url, url)
|
||||
|
||||
|
||||
class LessImportRewrite(UrlRewriter):
|
||||
name = "less_importrewrite"
|
||||
|
||||
patterns = {
|
||||
"import_rewrite": re.compile("(@import(\s+\(.*\))?\s+)\"(.*)\";")
|
||||
}
|
||||
|
||||
def import_rewrite(self, m):
|
||||
import_with_options = m.group(1)
|
||||
import_url = self.replace_url(m.group(3))
|
||||
return "{import_with_options}\"{import_url}\";".format(**locals())
|
||||
|
||||
|
||||
class SourceMapRewrite(UrlRewriter):
|
||||
name = "sourcemap_urlrewrite"
|
||||
|
||||
patterns = {
|
||||
"url_rewrite": re.compile("(//#\s+sourceMappingURL=)(.*)")
|
||||
}
|
||||
|
||||
def url_rewrite(self, m):
|
||||
mapping = m.group(1)
|
||||
source_url = self.replace_url(m.group(2))
|
||||
return "{mapping}{source_url}".format(**locals())
|
||||
|
||||
|
||||
class SourceMapRemove(PatternRewriter):
|
||||
name = "sourcemap_remove"
|
||||
|
||||
patterns = {
|
||||
"sourcemap_remove": re.compile("(//#\s+sourceMappingURL=)(.*)")
|
||||
}
|
||||
|
||||
def sourcemap_remove(self, m):
|
||||
return ""
|
||||
|
||||
|
||||
class JsDelimiterBundler(Filter):
|
||||
name = "js_delimiter_bundler"
|
||||
options = {}
|
||||
|
||||
def input(self, _in, out, **kwargs):
|
||||
out.write(_in.read())
|
||||
out.write("\n;\n")
|
||||
@@ -9,6 +9,8 @@ import os
|
||||
import datetime
|
||||
import codecs
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
from collections import defaultdict
|
||||
from flask import request, g, url_for, make_response, render_template, send_from_directory, redirect, abort
|
||||
|
||||
@@ -19,6 +21,7 @@ from octoprint.server import app, userManager, pluginManager, gettext, \
|
||||
NOT_MODIFIED
|
||||
from octoprint.settings import settings
|
||||
from octoprint.filemanager import get_all_extensions
|
||||
from octoprint.util import to_unicode
|
||||
|
||||
import re
|
||||
import base64
|
||||
@@ -458,13 +461,26 @@ def _process_templates():
|
||||
)
|
||||
|
||||
# sorting orders
|
||||
def wizard_key_extractor(d, k):
|
||||
if d[1].get("_key", None) == "plugin_corewizard_acl":
|
||||
# Ultra special case - we MUST always have the ACL wizard first since otherwise any steps that follow and
|
||||
# that require to access APIs to function will run into errors since those APIs won't work before ACL
|
||||
# has been configured. See also #2140
|
||||
return u"0:{}".format(to_unicode(d[0]))
|
||||
elif d[1].get("mandatory", False):
|
||||
# Other mandatory steps come before the optional ones
|
||||
return u"1:{}".format(to_unicode(d[0]))
|
||||
else:
|
||||
# Finally everything else
|
||||
return u"2:{}".format(to_unicode(d[0]))
|
||||
|
||||
template_sorting = dict(
|
||||
navbar=dict(add="prepend", key=None),
|
||||
sidebar=dict(add="append", key="name"),
|
||||
tab=dict(add="append", key="name"),
|
||||
settings=dict(add="custom_append", key="name", custom_add_entries=lambda missing: dict(section_plugins=(gettext("Plugins"), None)), custom_add_order=lambda missing: ["section_plugins"] + missing),
|
||||
usersettings=dict(add="append", key="name"),
|
||||
wizard=dict(add="append", key="name", key_extractor=lambda d, k: "0:{}".format(d[0]) if "mandatory" in d[1] and d[1]["mandatory"] else "1:{}".format(d[0])),
|
||||
wizard=dict(add="append", key="name", key_extractor=wizard_key_extractor),
|
||||
about=dict(add="append", key="name"),
|
||||
generic=dict(add="append", key=None)
|
||||
)
|
||||
@@ -520,7 +536,7 @@ def _process_templates():
|
||||
|
||||
templates["sidebar"]["entries"]= dict(
|
||||
connection=(gettext("Connection"), dict(template="sidebar/connection.jinja2", _div="connection", icon="signal", styles_wrapper=["display: none"], data_bind="visible: loginState.isUser")),
|
||||
state=(gettext("State"), dict(template="sidebar/state.jinja2", _div="state", icon="info-sign")),
|
||||
state=(gettext("State"), dict(template="sidebar/state.jinja2", _div="state", icon="info-circle")),
|
||||
files=(gettext("Files"), dict(template="sidebar/files.jinja2", _div="files", icon="list", classes_content=["overflow_visible"], template_header="sidebar/files_header.jinja2"))
|
||||
)
|
||||
|
||||
|
||||
@@ -34,6 +34,7 @@ import copy
|
||||
import time
|
||||
|
||||
from builtins import bytes
|
||||
from past.builtins import basestring
|
||||
|
||||
try:
|
||||
from collections import ChainMap
|
||||
@@ -93,6 +94,7 @@ default_settings = {
|
||||
"communication": 30,
|
||||
"temperature": 5,
|
||||
"temperatureTargetSet": 2,
|
||||
"temperatureAutoreport": 2,
|
||||
"sdStatus": 1
|
||||
},
|
||||
"maxCommunicationTimeouts": {
|
||||
@@ -110,6 +112,8 @@ default_settings = {
|
||||
"ignoreErrorsFromFirmware": False,
|
||||
"logResends": True,
|
||||
"supportResendsWithoutOk": False,
|
||||
"logPositionOnPause": True,
|
||||
"logPositionOnCancel": True,
|
||||
|
||||
# command specific flags
|
||||
"triggerOkForM29": True
|
||||
@@ -144,6 +148,12 @@ default_settings = {
|
||||
"systemRestartCommand": None,
|
||||
"serverRestartCommand": None
|
||||
},
|
||||
"onlineCheck": {
|
||||
"enabled": None,
|
||||
"interval": 15 * 60, # 15 min
|
||||
"host": "8.8.8.8",
|
||||
"port": 53
|
||||
},
|
||||
"diskspace": {
|
||||
"warning": 500 * 1024 * 1024, # 500 MB
|
||||
"critical": 200 * 1024 * 1024, # 200 MB
|
||||
@@ -156,6 +166,7 @@ default_settings = {
|
||||
"webcam": {
|
||||
"stream": None,
|
||||
"streamRatio": "16:9",
|
||||
"streamTimeout": 5,
|
||||
"snapshot": None,
|
||||
"ffmpeg": None,
|
||||
"ffmpegThreads": 1,
|
||||
@@ -228,7 +239,9 @@ default_settings = {
|
||||
{"name": "ABS", "extruder" : 210, "bed" : 100 },
|
||||
{"name": "PLA", "extruder" : 180, "bed" : 60 }
|
||||
],
|
||||
"cutoff": 30
|
||||
"cutoff": 30,
|
||||
"sendAutomatically": False,
|
||||
"sendAutomaticallyAfter": 1,
|
||||
},
|
||||
"printerProfiles": {
|
||||
"default": None
|
||||
@@ -297,7 +310,7 @@ default_settings = {
|
||||
"apps": {}
|
||||
},
|
||||
"terminalFilters": [
|
||||
{ "name": "Suppress temperature messages", "regex": "(Send: (N\d+\s+)?M105)|(Recv: ok (B|T\d*):)" },
|
||||
{ "name": "Suppress temperature messages", "regex": "(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+)?(B|T\d*):)" },
|
||||
{ "name": "Suppress SD status messages", "regex": "(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)" },
|
||||
{ "name": "Suppress wait responses", "regex": "Recv: wait"}
|
||||
],
|
||||
@@ -337,6 +350,7 @@ default_settings = {
|
||||
"okAfterResend": False,
|
||||
"forceChecksum": False,
|
||||
"numExtruders": 1,
|
||||
"pinnedExtruders": None,
|
||||
"includeCurrentToolInTemps": True,
|
||||
"includeFilenameInOpened": True,
|
||||
"hasBed": True,
|
||||
@@ -362,7 +376,11 @@ default_settings = {
|
||||
"simulateReset": True,
|
||||
"preparedOks": [],
|
||||
"okFormatString": "ok",
|
||||
"m115FormatString": "FIRMWARE_NAME: {firmware_name} PROTOCOL_VERSION:1.0"
|
||||
"m115FormatString": "FIRMWARE_NAME: {firmware_name} PROTOCOL_VERSION:1.0",
|
||||
"m115ReportCapabilities": False,
|
||||
"capabilities": {
|
||||
"AUTOREPORT_TEMP": True
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1268,23 +1286,43 @@ class Settings(object):
|
||||
return None
|
||||
|
||||
def getInt(self, path, **kwargs):
|
||||
minimum = kwargs.pop("min", None)
|
||||
maximum = kwargs.pop("max", None)
|
||||
|
||||
value = self.get(path, **kwargs)
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
try:
|
||||
return int(value)
|
||||
intValue = int(value)
|
||||
|
||||
if minimum is not None and intValue < minimum:
|
||||
return minimum
|
||||
elif maximum is not None and intValue > maximum:
|
||||
return maximum
|
||||
else:
|
||||
return intValue
|
||||
except ValueError:
|
||||
self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path))
|
||||
return None
|
||||
|
||||
def getFloat(self, path, **kwargs):
|
||||
minimum = kwargs.pop("min", None)
|
||||
maximum = kwargs.pop("max", None)
|
||||
|
||||
value = self.get(path, **kwargs)
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
try:
|
||||
return float(value)
|
||||
floatValue = float(value)
|
||||
|
||||
if minimum is not None and floatValue < minimum:
|
||||
return minimum
|
||||
elif maximum is not None and floatValue > maximum:
|
||||
return maximum
|
||||
else:
|
||||
return floatValue
|
||||
except ValueError:
|
||||
self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path))
|
||||
return None
|
||||
@@ -1312,11 +1350,14 @@ class Settings(object):
|
||||
if folder is None:
|
||||
folder = self._get_default_folder(type)
|
||||
|
||||
if not os.path.isdir(folder):
|
||||
if not os.path.exists(folder):
|
||||
if create:
|
||||
os.makedirs(folder)
|
||||
else:
|
||||
raise IOError("No such folder: {folder}".format(folder=folder))
|
||||
raise IOError("No such folder: {}".format(folder))
|
||||
elif os.path.isfile(folder):
|
||||
# hardening against misconfiguration, see #1953
|
||||
raise IOError("Expected a folder at {} but found a file instead".format(folder))
|
||||
|
||||
return folder
|
||||
|
||||
@@ -1437,8 +1478,16 @@ class Settings(object):
|
||||
self.set(path, None, **kwargs)
|
||||
return
|
||||
|
||||
minimum = kwargs.pop("min", None)
|
||||
maximum = kwargs.pop("max", None)
|
||||
|
||||
try:
|
||||
intValue = int(value)
|
||||
|
||||
if minimum is not None and intValue < minimum:
|
||||
intValue = minimum
|
||||
if maximum is not None and intValue > maximum:
|
||||
intValue = maximum
|
||||
except ValueError:
|
||||
self._logger.warn("Could not convert %r to a valid integer when setting option %r" % (value, path))
|
||||
return
|
||||
@@ -1450,8 +1499,16 @@ class Settings(object):
|
||||
self.set(path, None, **kwargs)
|
||||
return
|
||||
|
||||
minimum = kwargs.pop("min", None)
|
||||
maximum = kwargs.pop("max", None)
|
||||
|
||||
try:
|
||||
floatValue = float(value)
|
||||
|
||||
if minimum is not None and floatValue < minimum:
|
||||
floatValue = minimum
|
||||
if maximum is not None and floatValue > maximum:
|
||||
floatValue = maximum
|
||||
except ValueError:
|
||||
self._logger.warn("Could not convert %r to a valid integer when setting option %r" % (value, path))
|
||||
return
|
||||
|
||||
-403
@@ -1,403 +0,0 @@
|
||||
@font-face{font-family:'FontAwesome';src:url('../font/fontawesome-webfont.eot?v=3.2.1');src:url('../font/fontawesome-webfont.eot?#iefix&v=3.2.1') format('embedded-opentype'),url('../font/fontawesome-webfont.woff?v=3.2.1') format('woff'),url('../font/fontawesome-webfont.ttf?v=3.2.1') format('truetype'),url('../font/fontawesome-webfont.svg#fontawesomeregular?v=3.2.1') format('svg');font-weight:normal;font-style:normal;}[class^="icon-"],[class*=" icon-"]{font-family:FontAwesome;font-weight:normal;font-style:normal;text-decoration:inherit;-webkit-font-smoothing:antialiased;*margin-right:.3em;}
|
||||
[class^="icon-"]:before,[class*=" icon-"]:before{text-decoration:inherit;display:inline-block;speak:none;}
|
||||
.icon-large:before{vertical-align:-10%;font-size:1.3333333333333333em;}
|
||||
a [class^="icon-"],a [class*=" icon-"]{display:inline;}
|
||||
[class^="icon-"].icon-fixed-width,[class*=" icon-"].icon-fixed-width{display:inline-block;width:1.1428571428571428em;text-align:right;padding-right:0.2857142857142857em;}[class^="icon-"].icon-fixed-width.icon-large,[class*=" icon-"].icon-fixed-width.icon-large{width:1.4285714285714286em;}
|
||||
.icons-ul{margin-left:2.142857142857143em;list-style-type:none;}.icons-ul>li{position:relative;}
|
||||
.icons-ul .icon-li{position:absolute;left:-2.142857142857143em;width:2.142857142857143em;text-align:center;line-height:inherit;}
|
||||
[class^="icon-"].hide,[class*=" icon-"].hide{display:none;}
|
||||
.icon-muted{color:#eeeeee;}
|
||||
.icon-light{color:#ffffff;}
|
||||
.icon-dark{color:#333333;}
|
||||
.icon-border{border:solid 1px #eeeeee;padding:.2em .25em .15em;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;}
|
||||
.icon-2x{font-size:2em;}.icon-2x.icon-border{border-width:2px;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;}
|
||||
.icon-3x{font-size:3em;}.icon-3x.icon-border{border-width:3px;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;}
|
||||
.icon-4x{font-size:4em;}.icon-4x.icon-border{border-width:4px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;}
|
||||
.icon-5x{font-size:5em;}.icon-5x.icon-border{border-width:5px;-webkit-border-radius:7px;-moz-border-radius:7px;border-radius:7px;}
|
||||
.pull-right{float:right;}
|
||||
.pull-left{float:left;}
|
||||
[class^="icon-"].pull-left,[class*=" icon-"].pull-left{margin-right:.3em;}
|
||||
[class^="icon-"].pull-right,[class*=" icon-"].pull-right{margin-left:.3em;}
|
||||
[class^="icon-"],[class*=" icon-"]{display:inline;width:auto;height:auto;line-height:normal;vertical-align:baseline;background-image:none;background-position:0% 0%;background-repeat:repeat;margin-top:0;}
|
||||
.icon-white,.nav-pills>.active>a>[class^="icon-"],.nav-pills>.active>a>[class*=" icon-"],.nav-list>.active>a>[class^="icon-"],.nav-list>.active>a>[class*=" icon-"],.navbar-inverse .nav>.active>a>[class^="icon-"],.navbar-inverse .nav>.active>a>[class*=" icon-"],.dropdown-menu>li>a:hover>[class^="icon-"],.dropdown-menu>li>a:hover>[class*=" icon-"],.dropdown-menu>.active>a>[class^="icon-"],.dropdown-menu>.active>a>[class*=" icon-"],.dropdown-submenu:hover>a>[class^="icon-"],.dropdown-submenu:hover>a>[class*=" icon-"]{background-image:none;}
|
||||
.btn [class^="icon-"].icon-large,.nav [class^="icon-"].icon-large,.btn [class*=" icon-"].icon-large,.nav [class*=" icon-"].icon-large{line-height:.9em;}
|
||||
.btn [class^="icon-"].icon-spin,.nav [class^="icon-"].icon-spin,.btn [class*=" icon-"].icon-spin,.nav [class*=" icon-"].icon-spin{display:inline-block;}
|
||||
.nav-tabs [class^="icon-"],.nav-pills [class^="icon-"],.nav-tabs [class*=" icon-"],.nav-pills [class*=" icon-"],.nav-tabs [class^="icon-"].icon-large,.nav-pills [class^="icon-"].icon-large,.nav-tabs [class*=" icon-"].icon-large,.nav-pills [class*=" icon-"].icon-large{line-height:.9em;}
|
||||
.btn [class^="icon-"].pull-left.icon-2x,.btn [class*=" icon-"].pull-left.icon-2x,.btn [class^="icon-"].pull-right.icon-2x,.btn [class*=" icon-"].pull-right.icon-2x{margin-top:.18em;}
|
||||
.btn [class^="icon-"].icon-spin.icon-large,.btn [class*=" icon-"].icon-spin.icon-large{line-height:.8em;}
|
||||
.btn.btn-small [class^="icon-"].pull-left.icon-2x,.btn.btn-small [class*=" icon-"].pull-left.icon-2x,.btn.btn-small [class^="icon-"].pull-right.icon-2x,.btn.btn-small [class*=" icon-"].pull-right.icon-2x{margin-top:.25em;}
|
||||
.btn.btn-large [class^="icon-"],.btn.btn-large [class*=" icon-"]{margin-top:0;}.btn.btn-large [class^="icon-"].pull-left.icon-2x,.btn.btn-large [class*=" icon-"].pull-left.icon-2x,.btn.btn-large [class^="icon-"].pull-right.icon-2x,.btn.btn-large [class*=" icon-"].pull-right.icon-2x{margin-top:.05em;}
|
||||
.btn.btn-large [class^="icon-"].pull-left.icon-2x,.btn.btn-large [class*=" icon-"].pull-left.icon-2x{margin-right:.2em;}
|
||||
.btn.btn-large [class^="icon-"].pull-right.icon-2x,.btn.btn-large [class*=" icon-"].pull-right.icon-2x{margin-left:.2em;}
|
||||
.nav-list [class^="icon-"],.nav-list [class*=" icon-"]{line-height:inherit;}
|
||||
.icon-stack{position:relative;display:inline-block;width:2em;height:2em;line-height:2em;vertical-align:-35%;}.icon-stack [class^="icon-"],.icon-stack [class*=" icon-"]{display:block;text-align:center;position:absolute;width:100%;height:100%;font-size:1em;line-height:inherit;*line-height:2em;}
|
||||
.icon-stack .icon-stack-base{font-size:2em;*line-height:1em;}
|
||||
.icon-spin{display:inline-block;-moz-animation:spin 2s infinite linear;-o-animation:spin 2s infinite linear;-webkit-animation:spin 2s infinite linear;animation:spin 2s infinite linear;}
|
||||
a .icon-stack,a .icon-spin{display:inline-block;text-decoration:none;}
|
||||
@-moz-keyframes spin{0%{-moz-transform:rotate(0deg);} 100%{-moz-transform:rotate(359deg);}}@-webkit-keyframes spin{0%{-webkit-transform:rotate(0deg);} 100%{-webkit-transform:rotate(359deg);}}@-o-keyframes spin{0%{-o-transform:rotate(0deg);} 100%{-o-transform:rotate(359deg);}}@-ms-keyframes spin{0%{-ms-transform:rotate(0deg);} 100%{-ms-transform:rotate(359deg);}}@keyframes spin{0%{transform:rotate(0deg);} 100%{transform:rotate(359deg);}}.icon-rotate-90:before{-webkit-transform:rotate(90deg);-moz-transform:rotate(90deg);-ms-transform:rotate(90deg);-o-transform:rotate(90deg);transform:rotate(90deg);filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=1);}
|
||||
.icon-rotate-180:before{-webkit-transform:rotate(180deg);-moz-transform:rotate(180deg);-ms-transform:rotate(180deg);-o-transform:rotate(180deg);transform:rotate(180deg);filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=2);}
|
||||
.icon-rotate-270:before{-webkit-transform:rotate(270deg);-moz-transform:rotate(270deg);-ms-transform:rotate(270deg);-o-transform:rotate(270deg);transform:rotate(270deg);filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=3);}
|
||||
.icon-flip-horizontal:before{-webkit-transform:scale(-1, 1);-moz-transform:scale(-1, 1);-ms-transform:scale(-1, 1);-o-transform:scale(-1, 1);transform:scale(-1, 1);}
|
||||
.icon-flip-vertical:before{-webkit-transform:scale(1, -1);-moz-transform:scale(1, -1);-ms-transform:scale(1, -1);-o-transform:scale(1, -1);transform:scale(1, -1);}
|
||||
a .icon-rotate-90:before,a .icon-rotate-180:before,a .icon-rotate-270:before,a .icon-flip-horizontal:before,a .icon-flip-vertical:before{display:inline-block;}
|
||||
.icon-glass:before{content:"\f000";}
|
||||
.icon-music:before{content:"\f001";}
|
||||
.icon-search:before{content:"\f002";}
|
||||
.icon-envelope-alt:before{content:"\f003";}
|
||||
.icon-heart:before{content:"\f004";}
|
||||
.icon-star:before{content:"\f005";}
|
||||
.icon-star-empty:before{content:"\f006";}
|
||||
.icon-user:before{content:"\f007";}
|
||||
.icon-film:before{content:"\f008";}
|
||||
.icon-th-large:before{content:"\f009";}
|
||||
.icon-th:before{content:"\f00a";}
|
||||
.icon-th-list:before{content:"\f00b";}
|
||||
.icon-ok:before{content:"\f00c";}
|
||||
.icon-remove:before{content:"\f00d";}
|
||||
.icon-zoom-in:before{content:"\f00e";}
|
||||
.icon-zoom-out:before{content:"\f010";}
|
||||
.icon-power-off:before,.icon-off:before{content:"\f011";}
|
||||
.icon-signal:before{content:"\f012";}
|
||||
.icon-gear:before,.icon-cog:before{content:"\f013";}
|
||||
.icon-trash:before{content:"\f014";}
|
||||
.icon-home:before{content:"\f015";}
|
||||
.icon-file-alt:before{content:"\f016";}
|
||||
.icon-time:before{content:"\f017";}
|
||||
.icon-road:before{content:"\f018";}
|
||||
.icon-download-alt:before{content:"\f019";}
|
||||
.icon-download:before{content:"\f01a";}
|
||||
.icon-upload:before{content:"\f01b";}
|
||||
.icon-inbox:before{content:"\f01c";}
|
||||
.icon-play-circle:before{content:"\f01d";}
|
||||
.icon-rotate-right:before,.icon-repeat:before{content:"\f01e";}
|
||||
.icon-refresh:before{content:"\f021";}
|
||||
.icon-list-alt:before{content:"\f022";}
|
||||
.icon-lock:before{content:"\f023";}
|
||||
.icon-flag:before{content:"\f024";}
|
||||
.icon-headphones:before{content:"\f025";}
|
||||
.icon-volume-off:before{content:"\f026";}
|
||||
.icon-volume-down:before{content:"\f027";}
|
||||
.icon-volume-up:before{content:"\f028";}
|
||||
.icon-qrcode:before{content:"\f029";}
|
||||
.icon-barcode:before{content:"\f02a";}
|
||||
.icon-tag:before{content:"\f02b";}
|
||||
.icon-tags:before{content:"\f02c";}
|
||||
.icon-book:before{content:"\f02d";}
|
||||
.icon-bookmark:before{content:"\f02e";}
|
||||
.icon-print:before{content:"\f02f";}
|
||||
.icon-camera:before{content:"\f030";}
|
||||
.icon-font:before{content:"\f031";}
|
||||
.icon-bold:before{content:"\f032";}
|
||||
.icon-italic:before{content:"\f033";}
|
||||
.icon-text-height:before{content:"\f034";}
|
||||
.icon-text-width:before{content:"\f035";}
|
||||
.icon-align-left:before{content:"\f036";}
|
||||
.icon-align-center:before{content:"\f037";}
|
||||
.icon-align-right:before{content:"\f038";}
|
||||
.icon-align-justify:before{content:"\f039";}
|
||||
.icon-list:before{content:"\f03a";}
|
||||
.icon-indent-left:before{content:"\f03b";}
|
||||
.icon-indent-right:before{content:"\f03c";}
|
||||
.icon-facetime-video:before{content:"\f03d";}
|
||||
.icon-picture:before{content:"\f03e";}
|
||||
.icon-pencil:before{content:"\f040";}
|
||||
.icon-map-marker:before{content:"\f041";}
|
||||
.icon-adjust:before{content:"\f042";}
|
||||
.icon-tint:before{content:"\f043";}
|
||||
.icon-edit:before{content:"\f044";}
|
||||
.icon-share:before{content:"\f045";}
|
||||
.icon-check:before{content:"\f046";}
|
||||
.icon-move:before{content:"\f047";}
|
||||
.icon-step-backward:before{content:"\f048";}
|
||||
.icon-fast-backward:before{content:"\f049";}
|
||||
.icon-backward:before{content:"\f04a";}
|
||||
.icon-play:before{content:"\f04b";}
|
||||
.icon-pause:before{content:"\f04c";}
|
||||
.icon-stop:before{content:"\f04d";}
|
||||
.icon-forward:before{content:"\f04e";}
|
||||
.icon-fast-forward:before{content:"\f050";}
|
||||
.icon-step-forward:before{content:"\f051";}
|
||||
.icon-eject:before{content:"\f052";}
|
||||
.icon-chevron-left:before{content:"\f053";}
|
||||
.icon-chevron-right:before{content:"\f054";}
|
||||
.icon-plus-sign:before{content:"\f055";}
|
||||
.icon-minus-sign:before{content:"\f056";}
|
||||
.icon-remove-sign:before{content:"\f057";}
|
||||
.icon-ok-sign:before{content:"\f058";}
|
||||
.icon-question-sign:before{content:"\f059";}
|
||||
.icon-info-sign:before{content:"\f05a";}
|
||||
.icon-screenshot:before{content:"\f05b";}
|
||||
.icon-remove-circle:before{content:"\f05c";}
|
||||
.icon-ok-circle:before{content:"\f05d";}
|
||||
.icon-ban-circle:before{content:"\f05e";}
|
||||
.icon-arrow-left:before{content:"\f060";}
|
||||
.icon-arrow-right:before{content:"\f061";}
|
||||
.icon-arrow-up:before{content:"\f062";}
|
||||
.icon-arrow-down:before{content:"\f063";}
|
||||
.icon-mail-forward:before,.icon-share-alt:before{content:"\f064";}
|
||||
.icon-resize-full:before{content:"\f065";}
|
||||
.icon-resize-small:before{content:"\f066";}
|
||||
.icon-plus:before{content:"\f067";}
|
||||
.icon-minus:before{content:"\f068";}
|
||||
.icon-asterisk:before{content:"\f069";}
|
||||
.icon-exclamation-sign:before{content:"\f06a";}
|
||||
.icon-gift:before{content:"\f06b";}
|
||||
.icon-leaf:before{content:"\f06c";}
|
||||
.icon-fire:before{content:"\f06d";}
|
||||
.icon-eye-open:before{content:"\f06e";}
|
||||
.icon-eye-close:before{content:"\f070";}
|
||||
.icon-warning-sign:before{content:"\f071";}
|
||||
.icon-plane:before{content:"\f072";}
|
||||
.icon-calendar:before{content:"\f073";}
|
||||
.icon-random:before{content:"\f074";}
|
||||
.icon-comment:before{content:"\f075";}
|
||||
.icon-magnet:before{content:"\f076";}
|
||||
.icon-chevron-up:before{content:"\f077";}
|
||||
.icon-chevron-down:before{content:"\f078";}
|
||||
.icon-retweet:before{content:"\f079";}
|
||||
.icon-shopping-cart:before{content:"\f07a";}
|
||||
.icon-folder-close:before{content:"\f07b";}
|
||||
.icon-folder-open:before{content:"\f07c";}
|
||||
.icon-resize-vertical:before{content:"\f07d";}
|
||||
.icon-resize-horizontal:before{content:"\f07e";}
|
||||
.icon-bar-chart:before{content:"\f080";}
|
||||
.icon-twitter-sign:before{content:"\f081";}
|
||||
.icon-facebook-sign:before{content:"\f082";}
|
||||
.icon-camera-retro:before{content:"\f083";}
|
||||
.icon-key:before{content:"\f084";}
|
||||
.icon-gears:before,.icon-cogs:before{content:"\f085";}
|
||||
.icon-comments:before{content:"\f086";}
|
||||
.icon-thumbs-up-alt:before{content:"\f087";}
|
||||
.icon-thumbs-down-alt:before{content:"\f088";}
|
||||
.icon-star-half:before{content:"\f089";}
|
||||
.icon-heart-empty:before{content:"\f08a";}
|
||||
.icon-signout:before{content:"\f08b";}
|
||||
.icon-linkedin-sign:before{content:"\f08c";}
|
||||
.icon-pushpin:before{content:"\f08d";}
|
||||
.icon-external-link:before{content:"\f08e";}
|
||||
.icon-signin:before{content:"\f090";}
|
||||
.icon-trophy:before{content:"\f091";}
|
||||
.icon-github-sign:before{content:"\f092";}
|
||||
.icon-upload-alt:before{content:"\f093";}
|
||||
.icon-lemon:before{content:"\f094";}
|
||||
.icon-phone:before{content:"\f095";}
|
||||
.icon-unchecked:before,.icon-check-empty:before{content:"\f096";}
|
||||
.icon-bookmark-empty:before{content:"\f097";}
|
||||
.icon-phone-sign:before{content:"\f098";}
|
||||
.icon-twitter:before{content:"\f099";}
|
||||
.icon-facebook:before{content:"\f09a";}
|
||||
.icon-github:before{content:"\f09b";}
|
||||
.icon-unlock:before{content:"\f09c";}
|
||||
.icon-credit-card:before{content:"\f09d";}
|
||||
.icon-rss:before{content:"\f09e";}
|
||||
.icon-hdd:before{content:"\f0a0";}
|
||||
.icon-bullhorn:before{content:"\f0a1";}
|
||||
.icon-bell:before{content:"\f0a2";}
|
||||
.icon-certificate:before{content:"\f0a3";}
|
||||
.icon-hand-right:before{content:"\f0a4";}
|
||||
.icon-hand-left:before{content:"\f0a5";}
|
||||
.icon-hand-up:before{content:"\f0a6";}
|
||||
.icon-hand-down:before{content:"\f0a7";}
|
||||
.icon-circle-arrow-left:before{content:"\f0a8";}
|
||||
.icon-circle-arrow-right:before{content:"\f0a9";}
|
||||
.icon-circle-arrow-up:before{content:"\f0aa";}
|
||||
.icon-circle-arrow-down:before{content:"\f0ab";}
|
||||
.icon-globe:before{content:"\f0ac";}
|
||||
.icon-wrench:before{content:"\f0ad";}
|
||||
.icon-tasks:before{content:"\f0ae";}
|
||||
.icon-filter:before{content:"\f0b0";}
|
||||
.icon-briefcase:before{content:"\f0b1";}
|
||||
.icon-fullscreen:before{content:"\f0b2";}
|
||||
.icon-group:before{content:"\f0c0";}
|
||||
.icon-link:before{content:"\f0c1";}
|
||||
.icon-cloud:before{content:"\f0c2";}
|
||||
.icon-beaker:before{content:"\f0c3";}
|
||||
.icon-cut:before{content:"\f0c4";}
|
||||
.icon-copy:before{content:"\f0c5";}
|
||||
.icon-paperclip:before,.icon-paper-clip:before{content:"\f0c6";}
|
||||
.icon-save:before{content:"\f0c7";}
|
||||
.icon-sign-blank:before{content:"\f0c8";}
|
||||
.icon-reorder:before{content:"\f0c9";}
|
||||
.icon-list-ul:before{content:"\f0ca";}
|
||||
.icon-list-ol:before{content:"\f0cb";}
|
||||
.icon-strikethrough:before{content:"\f0cc";}
|
||||
.icon-underline:before{content:"\f0cd";}
|
||||
.icon-table:before{content:"\f0ce";}
|
||||
.icon-magic:before{content:"\f0d0";}
|
||||
.icon-truck:before{content:"\f0d1";}
|
||||
.icon-pinterest:before{content:"\f0d2";}
|
||||
.icon-pinterest-sign:before{content:"\f0d3";}
|
||||
.icon-google-plus-sign:before{content:"\f0d4";}
|
||||
.icon-google-plus:before{content:"\f0d5";}
|
||||
.icon-money:before{content:"\f0d6";}
|
||||
.icon-caret-down:before{content:"\f0d7";}
|
||||
.icon-caret-up:before{content:"\f0d8";}
|
||||
.icon-caret-left:before{content:"\f0d9";}
|
||||
.icon-caret-right:before{content:"\f0da";}
|
||||
.icon-columns:before{content:"\f0db";}
|
||||
.icon-sort:before{content:"\f0dc";}
|
||||
.icon-sort-down:before{content:"\f0dd";}
|
||||
.icon-sort-up:before{content:"\f0de";}
|
||||
.icon-envelope:before{content:"\f0e0";}
|
||||
.icon-linkedin:before{content:"\f0e1";}
|
||||
.icon-rotate-left:before,.icon-undo:before{content:"\f0e2";}
|
||||
.icon-legal:before{content:"\f0e3";}
|
||||
.icon-dashboard:before{content:"\f0e4";}
|
||||
.icon-comment-alt:before{content:"\f0e5";}
|
||||
.icon-comments-alt:before{content:"\f0e6";}
|
||||
.icon-bolt:before{content:"\f0e7";}
|
||||
.icon-sitemap:before{content:"\f0e8";}
|
||||
.icon-umbrella:before{content:"\f0e9";}
|
||||
.icon-paste:before{content:"\f0ea";}
|
||||
.icon-lightbulb:before{content:"\f0eb";}
|
||||
.icon-exchange:before{content:"\f0ec";}
|
||||
.icon-cloud-download:before{content:"\f0ed";}
|
||||
.icon-cloud-upload:before{content:"\f0ee";}
|
||||
.icon-user-md:before{content:"\f0f0";}
|
||||
.icon-stethoscope:before{content:"\f0f1";}
|
||||
.icon-suitcase:before{content:"\f0f2";}
|
||||
.icon-bell-alt:before{content:"\f0f3";}
|
||||
.icon-coffee:before{content:"\f0f4";}
|
||||
.icon-food:before{content:"\f0f5";}
|
||||
.icon-file-text-alt:before{content:"\f0f6";}
|
||||
.icon-building:before{content:"\f0f7";}
|
||||
.icon-hospital:before{content:"\f0f8";}
|
||||
.icon-ambulance:before{content:"\f0f9";}
|
||||
.icon-medkit:before{content:"\f0fa";}
|
||||
.icon-fighter-jet:before{content:"\f0fb";}
|
||||
.icon-beer:before{content:"\f0fc";}
|
||||
.icon-h-sign:before{content:"\f0fd";}
|
||||
.icon-plus-sign-alt:before{content:"\f0fe";}
|
||||
.icon-double-angle-left:before{content:"\f100";}
|
||||
.icon-double-angle-right:before{content:"\f101";}
|
||||
.icon-double-angle-up:before{content:"\f102";}
|
||||
.icon-double-angle-down:before{content:"\f103";}
|
||||
.icon-angle-left:before{content:"\f104";}
|
||||
.icon-angle-right:before{content:"\f105";}
|
||||
.icon-angle-up:before{content:"\f106";}
|
||||
.icon-angle-down:before{content:"\f107";}
|
||||
.icon-desktop:before{content:"\f108";}
|
||||
.icon-laptop:before{content:"\f109";}
|
||||
.icon-tablet:before{content:"\f10a";}
|
||||
.icon-mobile-phone:before{content:"\f10b";}
|
||||
.icon-circle-blank:before{content:"\f10c";}
|
||||
.icon-quote-left:before{content:"\f10d";}
|
||||
.icon-quote-right:before{content:"\f10e";}
|
||||
.icon-spinner:before{content:"\f110";}
|
||||
.icon-circle:before{content:"\f111";}
|
||||
.icon-mail-reply:before,.icon-reply:before{content:"\f112";}
|
||||
.icon-github-alt:before{content:"\f113";}
|
||||
.icon-folder-close-alt:before{content:"\f114";}
|
||||
.icon-folder-open-alt:before{content:"\f115";}
|
||||
.icon-expand-alt:before{content:"\f116";}
|
||||
.icon-collapse-alt:before{content:"\f117";}
|
||||
.icon-smile:before{content:"\f118";}
|
||||
.icon-frown:before{content:"\f119";}
|
||||
.icon-meh:before{content:"\f11a";}
|
||||
.icon-gamepad:before{content:"\f11b";}
|
||||
.icon-keyboard:before{content:"\f11c";}
|
||||
.icon-flag-alt:before{content:"\f11d";}
|
||||
.icon-flag-checkered:before{content:"\f11e";}
|
||||
.icon-terminal:before{content:"\f120";}
|
||||
.icon-code:before{content:"\f121";}
|
||||
.icon-reply-all:before{content:"\f122";}
|
||||
.icon-mail-reply-all:before{content:"\f122";}
|
||||
.icon-star-half-full:before,.icon-star-half-empty:before{content:"\f123";}
|
||||
.icon-location-arrow:before{content:"\f124";}
|
||||
.icon-crop:before{content:"\f125";}
|
||||
.icon-code-fork:before{content:"\f126";}
|
||||
.icon-unlink:before{content:"\f127";}
|
||||
.icon-question:before{content:"\f128";}
|
||||
.icon-info:before{content:"\f129";}
|
||||
.icon-exclamation:before{content:"\f12a";}
|
||||
.icon-superscript:before{content:"\f12b";}
|
||||
.icon-subscript:before{content:"\f12c";}
|
||||
.icon-eraser:before{content:"\f12d";}
|
||||
.icon-puzzle-piece:before{content:"\f12e";}
|
||||
.icon-microphone:before{content:"\f130";}
|
||||
.icon-microphone-off:before{content:"\f131";}
|
||||
.icon-shield:before{content:"\f132";}
|
||||
.icon-calendar-empty:before{content:"\f133";}
|
||||
.icon-fire-extinguisher:before{content:"\f134";}
|
||||
.icon-rocket:before{content:"\f135";}
|
||||
.icon-maxcdn:before{content:"\f136";}
|
||||
.icon-chevron-sign-left:before{content:"\f137";}
|
||||
.icon-chevron-sign-right:before{content:"\f138";}
|
||||
.icon-chevron-sign-up:before{content:"\f139";}
|
||||
.icon-chevron-sign-down:before{content:"\f13a";}
|
||||
.icon-html5:before{content:"\f13b";}
|
||||
.icon-css3:before{content:"\f13c";}
|
||||
.icon-anchor:before{content:"\f13d";}
|
||||
.icon-unlock-alt:before{content:"\f13e";}
|
||||
.icon-bullseye:before{content:"\f140";}
|
||||
.icon-ellipsis-horizontal:before{content:"\f141";}
|
||||
.icon-ellipsis-vertical:before{content:"\f142";}
|
||||
.icon-rss-sign:before{content:"\f143";}
|
||||
.icon-play-sign:before{content:"\f144";}
|
||||
.icon-ticket:before{content:"\f145";}
|
||||
.icon-minus-sign-alt:before{content:"\f146";}
|
||||
.icon-check-minus:before{content:"\f147";}
|
||||
.icon-level-up:before{content:"\f148";}
|
||||
.icon-level-down:before{content:"\f149";}
|
||||
.icon-check-sign:before{content:"\f14a";}
|
||||
.icon-edit-sign:before{content:"\f14b";}
|
||||
.icon-external-link-sign:before{content:"\f14c";}
|
||||
.icon-share-sign:before{content:"\f14d";}
|
||||
.icon-compass:before{content:"\f14e";}
|
||||
.icon-collapse:before{content:"\f150";}
|
||||
.icon-collapse-top:before{content:"\f151";}
|
||||
.icon-expand:before{content:"\f152";}
|
||||
.icon-euro:before,.icon-eur:before{content:"\f153";}
|
||||
.icon-gbp:before{content:"\f154";}
|
||||
.icon-dollar:before,.icon-usd:before{content:"\f155";}
|
||||
.icon-rupee:before,.icon-inr:before{content:"\f156";}
|
||||
.icon-yen:before,.icon-jpy:before{content:"\f157";}
|
||||
.icon-renminbi:before,.icon-cny:before{content:"\f158";}
|
||||
.icon-won:before,.icon-krw:before{content:"\f159";}
|
||||
.icon-bitcoin:before,.icon-btc:before{content:"\f15a";}
|
||||
.icon-file:before{content:"\f15b";}
|
||||
.icon-file-text:before{content:"\f15c";}
|
||||
.icon-sort-by-alphabet:before{content:"\f15d";}
|
||||
.icon-sort-by-alphabet-alt:before{content:"\f15e";}
|
||||
.icon-sort-by-attributes:before{content:"\f160";}
|
||||
.icon-sort-by-attributes-alt:before{content:"\f161";}
|
||||
.icon-sort-by-order:before{content:"\f162";}
|
||||
.icon-sort-by-order-alt:before{content:"\f163";}
|
||||
.icon-thumbs-up:before{content:"\f164";}
|
||||
.icon-thumbs-down:before{content:"\f165";}
|
||||
.icon-youtube-sign:before{content:"\f166";}
|
||||
.icon-youtube:before{content:"\f167";}
|
||||
.icon-xing:before{content:"\f168";}
|
||||
.icon-xing-sign:before{content:"\f169";}
|
||||
.icon-youtube-play:before{content:"\f16a";}
|
||||
.icon-dropbox:before{content:"\f16b";}
|
||||
.icon-stackexchange:before{content:"\f16c";}
|
||||
.icon-instagram:before{content:"\f16d";}
|
||||
.icon-flickr:before{content:"\f16e";}
|
||||
.icon-adn:before{content:"\f170";}
|
||||
.icon-bitbucket:before{content:"\f171";}
|
||||
.icon-bitbucket-sign:before{content:"\f172";}
|
||||
.icon-tumblr:before{content:"\f173";}
|
||||
.icon-tumblr-sign:before{content:"\f174";}
|
||||
.icon-long-arrow-down:before{content:"\f175";}
|
||||
.icon-long-arrow-up:before{content:"\f176";}
|
||||
.icon-long-arrow-left:before{content:"\f177";}
|
||||
.icon-long-arrow-right:before{content:"\f178";}
|
||||
.icon-apple:before{content:"\f179";}
|
||||
.icon-windows:before{content:"\f17a";}
|
||||
.icon-android:before{content:"\f17b";}
|
||||
.icon-linux:before{content:"\f17c";}
|
||||
.icon-dribbble:before{content:"\f17d";}
|
||||
.icon-skype:before{content:"\f17e";}
|
||||
.icon-foursquare:before{content:"\f180";}
|
||||
.icon-trello:before{content:"\f181";}
|
||||
.icon-female:before{content:"\f182";}
|
||||
.icon-male:before{content:"\f183";}
|
||||
.icon-gittip:before{content:"\f184";}
|
||||
.icon-sun:before{content:"\f185";}
|
||||
.icon-moon:before{content:"\f186";}
|
||||
.icon-archive:before{content:"\f187";}
|
||||
.icon-bug:before{content:"\f188";}
|
||||
.icon-vk:before{content:"\f189";}
|
||||
.icon-weibo:before{content:"\f18a";}
|
||||
.icon-renren:before{content:"\f18b";}
|
||||
@@ -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,.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;*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.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.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:focus,.btn:hover{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:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;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{color:#fff;text-shadow:0 -1px 0 rgba(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;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.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,.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;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine 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,.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;*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.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.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:focus,.btn:hover{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:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;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{color:#fff;text-shadow:0 -1px 0 rgba(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;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.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,.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;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
|
||||
@@ -14,7 +14,10 @@ var z_heights = {};
|
||||
var model = [];
|
||||
var max = {x: undefined, y: undefined, z: undefined};
|
||||
var min = {x: undefined, y: undefined, z: undefined};
|
||||
var boundingBox = {minX: undefined, maxX: undefined, minY: undefined, maxY: undefined, minZ: undefined, maxZ: undefined};
|
||||
var modelSize = {x: undefined, y: undefined, z: undefined};
|
||||
var bed = {x: undefined, y: undefined, r: undefined, circular: false, centeredOrigin: false};
|
||||
var ignoreOutsideBed = false;
|
||||
var filamentByLayer = {};
|
||||
var totalFilament = [0];
|
||||
var printTime = 0;
|
||||
@@ -76,6 +79,7 @@ var sendAnalyzeDone = function () {
|
||||
max: max,
|
||||
min: min,
|
||||
modelSize: modelSize,
|
||||
boundingBox: boundingBox,
|
||||
totalFilament: totalFilament,
|
||||
filamentByLayer: filamentByLayer,
|
||||
printTime: printTime,
|
||||
@@ -106,6 +110,36 @@ var purgeLayers = function () {
|
||||
}
|
||||
};
|
||||
|
||||
var bedBounds = function() {
|
||||
if (!bed) {
|
||||
return {xMin: 0, xMax: 0, yMin: 0, yMax: 0};
|
||||
}
|
||||
|
||||
var result;
|
||||
if (bed.circular) {
|
||||
result = {xMin: -bed.r, xMax: bed.r, yMin: -bed.r, yMax: bed.r};
|
||||
} else if (bed.centeredOrigin) {
|
||||
result = {xMin: -bed.x/2.0, xMax: bed.x/2.0, yMin: -bed.y/2.0, yMax: bed.y/2.0};
|
||||
} else {
|
||||
result = {xMin: 0, xMax: bed.x, yMin: 0, yMax: bed.y};
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
var withinBedBounds = function(x, y, bedBounds) {
|
||||
if (!ignoreOutsideBed) return true;
|
||||
|
||||
var result = true;
|
||||
|
||||
if (x !== undefined && !isNaN(x)) {
|
||||
result = result && (x >= bedBounds.xMin && x <= bedBounds.xMax);
|
||||
}
|
||||
if (y !== undefined && !isNaN(y)) {
|
||||
result = result && (y >= bedBounds.yMin && y <= bedBounds.yMax);
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
var analyzeModel = function () {
|
||||
var tmp1 = 0, tmp2 = 0;
|
||||
@@ -113,6 +147,8 @@ var analyzeModel = function () {
|
||||
var type;
|
||||
var printTimeAdd = 0;
|
||||
|
||||
var bounds = bedBounds();
|
||||
|
||||
for (var i = 0; i < model.length; i++) {
|
||||
var cmds = model[i];
|
||||
if (!cmds) continue;
|
||||
@@ -120,41 +156,56 @@ var analyzeModel = function () {
|
||||
for (var j = 0; j < cmds.length; j++) {
|
||||
var tool = cmds[j].tool;
|
||||
|
||||
var x_ok = false;
|
||||
var y_ok = false;
|
||||
var retract = cmds[j].retract && cmds[j].retract > 0;
|
||||
var extrude = cmds[j].extrude && cmds[j].extrude > 0 && !retract;
|
||||
var move = cmds[j].x !== undefined || cmds[j].y !== undefined || cmds[j].z !== undefined;
|
||||
|
||||
var prevInBounds = withinBedBounds(cmds[j].prevX, cmds[j].prevY, bounds);
|
||||
var inBounds = withinBedBounds(cmds[j].x === undefined ? cmds[j].prevX : cmds[j].x,
|
||||
cmds[j].y === undefined ? cmds[j].prevY : cmds[j].y,
|
||||
bounds);
|
||||
|
||||
var recordX = function(x, inBounds) {
|
||||
if (x === undefined || isNaN(x)) return;
|
||||
|
||||
if (typeof(cmds[j].x) !== 'undefined'
|
||||
&& typeof(cmds[j].prevX) !== 'undefined'
|
||||
&& typeof(cmds[j].extrude) !== 'undefined'
|
||||
&& cmds[j].extrude
|
||||
&& !isNaN(cmds[j].x)) {
|
||||
var x = cmds[j].x;
|
||||
max.x = max.x !== undefined ? Math.max(max.x, x) : x;
|
||||
min.x = min.x !== undefined ? Math.min(min.x, x) : x;
|
||||
|
||||
x_ok = true;
|
||||
}
|
||||
if (inBounds) {
|
||||
boundingBox.minX = boundingBox.minX !== undefined ? Math.min(boundingBox.minX, x): x;
|
||||
boundingBox.maxX = boundingBox.maxX !== undefined ? Math.max(boundingBox.maxX, x): x;
|
||||
}
|
||||
};
|
||||
|
||||
if (typeof(cmds[j].y) !== 'undefined'
|
||||
&& typeof(cmds[j].prevY) !== 'undefined'
|
||||
&& typeof(cmds[j].extrude) !== 'undefined'
|
||||
&& cmds[j].extrude
|
||||
&& !isNaN(cmds[j].y)) {
|
||||
var y = cmds[j].y;
|
||||
var recordY = function(y, inBounds) {
|
||||
if (y === undefined || isNaN(y)) return;
|
||||
|
||||
max.y = max.y !== undefined ? Math.max(max.y, y) : y;
|
||||
min.y = min.y !== undefined ? Math.min(min.y, y) : y;
|
||||
|
||||
y_ok = true;
|
||||
}
|
||||
if (inBounds) {
|
||||
boundingBox.minY = boundingBox.minY !== undefined ? Math.min(boundingBox.minY, y): y;
|
||||
boundingBox.maxY = boundingBox.maxY !== undefined ? Math.max(boundingBox.maxY, y): y;
|
||||
}
|
||||
};
|
||||
|
||||
var recordZ = function(z) {
|
||||
if (z === undefined || isNaN(z)) return;
|
||||
|
||||
if (typeof(cmds[j].prevZ) !== 'undefined'
|
||||
&& typeof(cmds[j].extrude) !== 'undefined'
|
||||
&& cmds[j].extrude
|
||||
&& !isNaN(cmds[j].prevZ)) {
|
||||
var z = cmds[j].prevZ;
|
||||
max.z = max.z !== undefined ? Math.max(max.z, z) : z;
|
||||
min.z = min.z !== undefined ? Math.min(min.z, z) : z;
|
||||
|
||||
boundingBox.minZ = min.z;
|
||||
boundingBox.maxZ = max.z;
|
||||
};
|
||||
|
||||
if (move && extrude) {
|
||||
recordX(cmds[j].prevX, prevInBounds);
|
||||
recordX(cmds[j].x, inBounds);
|
||||
recordY(cmds[j].prevY, prevInBounds);
|
||||
recordY(cmds[j].y, inBounds);
|
||||
recordZ(cmds[j].prevZ);
|
||||
recordZ(cmds[j].z);
|
||||
}
|
||||
|
||||
if (!totalFilament[tool]) totalFilament[tool] = 0;
|
||||
@@ -165,20 +216,25 @@ var analyzeModel = function () {
|
||||
filamentByLayer[cmds[j].prevZ][tool] += cmds[j].extrusion;
|
||||
}
|
||||
|
||||
var diffX = cmds[j].x - cmds[j].prevX;
|
||||
var diffY = cmds[j].y - cmds[j].prevY;
|
||||
if (x_ok && y_ok) {
|
||||
printTimeAdd = Math.sqrt(diffX * diffX + diffY * diffY) / (cmds[j].speed / 60);
|
||||
} else if (cmds[j].retract === 0 && cmds[j].extrusion !== 0) {
|
||||
tmp1 = Math.sqrt(diffX * diffX + diffY * diffY) / (cmds[j].speed / 60);
|
||||
tmp2 = Math.abs(cmds[j].extrusion / (cmds[j].speed / 60));
|
||||
printTimeAdd = Math.max(tmp1, tmp2);
|
||||
} else if (cmds[j].retract !== 0) {
|
||||
printTimeAdd = Math.abs(cmds[j].extrusion / (cmds[j].speed / 60));
|
||||
if (cmds[j].x !== undefined && !isNaN(cmds[j].x)
|
||||
&& cmds[j].y !== undefined && !isNaN(cmds[j].y)) {
|
||||
var diffX = cmds[j].x - cmds[j].prevX;
|
||||
var diffY = cmds[j].y - cmds[j].prevY;
|
||||
if (move) {
|
||||
printTimeAdd = Math.sqrt(diffX * diffX + diffY * diffY) / (cmds[j].speed / 60);
|
||||
} else if (extrude) {
|
||||
tmp1 = Math.sqrt(diffX * diffX + diffY * diffY) / (cmds[j].speed / 60);
|
||||
tmp2 = Math.abs(cmds[j].extrusion / (cmds[j].speed / 60));
|
||||
printTimeAdd = Math.max(tmp1, tmp2);
|
||||
} else if (retract) {
|
||||
printTimeAdd = Math.abs(cmds[j].extrusion / (cmds[j].speed / 60));
|
||||
}
|
||||
} else {
|
||||
printTimeAdd = 0;
|
||||
}
|
||||
|
||||
printTime += printTimeAdd;
|
||||
if (typeof(printTimeByLayer[cmds[j].prevZ]) === 'undefined') {
|
||||
if (printTimeByLayer[cmds[j].prevZ] === undefined) {
|
||||
printTimeByLayer[cmds[j].prevZ] = 0;
|
||||
}
|
||||
printTimeByLayer[cmds[j].prevZ] += printTimeAdd;
|
||||
@@ -245,10 +301,16 @@ var doParse = function () {
|
||||
var tool = 0;
|
||||
var prev_extrude = [{a: 0, b: 0, c: 0, e: 0, abs: 0}];
|
||||
var prev_retract = [0];
|
||||
var offset = toolOffsets[0];
|
||||
|
||||
// we keep track of our active toolOffset here so that our visualization lines up - if we didn't
|
||||
// offset the coordinates from the GCODE file with the tool offset, stuff would look wonky since our
|
||||
// visualizer doesn't actually have a physical offset ;)
|
||||
var activeToolOffset = toolOffsets[0];
|
||||
|
||||
var i, j, args;
|
||||
|
||||
model = [];
|
||||
for (var i = 0; i < gcode.length; i++) {
|
||||
for (i = 0; i < gcode.length; i++) {
|
||||
x = undefined;
|
||||
y = undefined;
|
||||
z = undefined;
|
||||
@@ -263,30 +325,35 @@ var doParse = function () {
|
||||
extrude = false;
|
||||
line = line.split(/[\(;]/)[0];
|
||||
|
||||
if (!line || line.trim() === "") {
|
||||
// empty line, skip entirely
|
||||
continue;
|
||||
}
|
||||
|
||||
var addToModel = false;
|
||||
var move = false;
|
||||
|
||||
var log = false;
|
||||
|
||||
if (/^(?:G0|G1|G2|G3)\s/i.test(line)) {
|
||||
var args = line.split(/\s/);
|
||||
args = line.split(/\s/);
|
||||
|
||||
for (var j = 0; j < args.length; j++) {
|
||||
for (j = 0; j < args.length; j++) {
|
||||
switch (argChar = args[j].charAt(0).toLowerCase()) {
|
||||
case 'x':
|
||||
if (relativeMode) {
|
||||
x = prevX + Number(args[j].slice(1)) + offset.x;
|
||||
x = prevX + Number(args[j].slice(1)) + activeToolOffset.x;
|
||||
} else {
|
||||
x = Number(args[j].slice(1)) + offset.x;
|
||||
x = Number(args[j].slice(1)) + activeToolOffset.x;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 'y':
|
||||
if (relativeMode) {
|
||||
y = prevY + Number(args[j].slice(1)) + offset.y;
|
||||
y = prevY + Number(args[j].slice(1)) + activeToolOffset.y;
|
||||
} else {
|
||||
y = Number(args[j].slice(1)) + offset.y;
|
||||
y = Number(args[j].slice(1)) + activeToolOffset.y;
|
||||
}
|
||||
|
||||
break;
|
||||
@@ -320,7 +387,7 @@ var doParse = function () {
|
||||
if (prev_extrude[tool]["abs"] < 0) {
|
||||
prev_retract[tool] = -1;
|
||||
retract = -1;
|
||||
} else if (prev_extrude[tool]["abs"] == 0) {
|
||||
} else if (prev_extrude[tool]["abs"] === 0) {
|
||||
retract = 0;
|
||||
} else if (prev_extrude[tool]["abs"] > 0 && prev_retract[tool] < 0) {
|
||||
prev_retract[tool] = 0;
|
||||
@@ -342,9 +409,9 @@ var doParse = function () {
|
||||
center_j = Number(args[j].slice(1));
|
||||
break;
|
||||
case 'g':
|
||||
if(args[j].charAt(1).toLowerCase()=='2')
|
||||
if(args[j].charAt(1).toLowerCase() === '2')
|
||||
direction=1;
|
||||
if(args[j].charAt(1).toLowerCase()=='3')
|
||||
if(args[j].charAt(1).toLowerCase() === '3')
|
||||
direction=-1;
|
||||
break;
|
||||
}
|
||||
@@ -355,7 +422,7 @@ var doParse = function () {
|
||||
prev_extrude[tool]["abs"] = Math.sqrt((prevX - x) * (prevX - x) + (prevY - y) * (prevY - y));
|
||||
}
|
||||
|
||||
if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined' || retract != 0) {
|
||||
if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined' || retract !== 0) {
|
||||
addToModel = true;
|
||||
move = true;
|
||||
}
|
||||
@@ -378,12 +445,12 @@ var doParse = function () {
|
||||
} else if (/^(?:M103)/i.test(line)) {
|
||||
dcExtrude = false;
|
||||
} else if (/^(?:G92)/i.test(line)) {
|
||||
var args = line.split(/\s/);
|
||||
args = line.split(/\s/);
|
||||
|
||||
for (var j = 0; j < args.length; j++) {
|
||||
for (j = 0; j < args.length; j++) {
|
||||
if (!args[j]) continue;
|
||||
|
||||
if (args.length == 1) {
|
||||
if (args.length === 1) {
|
||||
// G92 without coordinates => reset all axes to 0
|
||||
x = 0;
|
||||
y = 0;
|
||||
@@ -395,11 +462,11 @@ var doParse = function () {
|
||||
} else {
|
||||
switch (argChar = args[j].charAt(0).toLowerCase()) {
|
||||
case 'x':
|
||||
x = Number(args[j].slice(1)) + offset.x;
|
||||
x = Number(args[j].slice(1)) + activeToolOffset.x;
|
||||
break;
|
||||
|
||||
case 'y':
|
||||
y = Number(args[j].slice(1)) + offset.y;
|
||||
y = Number(args[j].slice(1)) + activeToolOffset.y;
|
||||
break;
|
||||
|
||||
case 'z':
|
||||
@@ -428,9 +495,9 @@ var doParse = function () {
|
||||
}
|
||||
|
||||
} else if (/^(?:G28)/i.test(line)) {
|
||||
var args = line.split(/\s/);
|
||||
args = line.split(/\s/);
|
||||
|
||||
if (args.length == 1) {
|
||||
if (args.length === 1) {
|
||||
// G28 with no arguments => home all axis
|
||||
x = 0;
|
||||
y = 0;
|
||||
@@ -454,11 +521,11 @@ var doParse = function () {
|
||||
}
|
||||
|
||||
// if it's the first layer and G28 was without z
|
||||
if (layer == 0 && typeof(z) === 'undefined') {
|
||||
if (layer === 0 && typeof(z) === 'undefined') {
|
||||
z = 0;
|
||||
}
|
||||
|
||||
if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined' || retract != 0) {
|
||||
if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined' || retract !== 0) {
|
||||
addToModel = true;
|
||||
move = true;
|
||||
}
|
||||
@@ -467,13 +534,13 @@ var doParse = function () {
|
||||
if (!prev_extrude[tool]) prev_extrude[tool] = {a: 0, b: 0, c: 0, e: 0, abs: 0};
|
||||
if (!prev_retract[tool]) prev_retract[tool] = 0;
|
||||
|
||||
offset = toolOffsets[tool];
|
||||
if (!offset) offset = {x: 0, y: 0};
|
||||
activeToolOffset = toolOffsets[tool];
|
||||
if (!activeToolOffset) activeToolOffset = {x: 0, y: 0};
|
||||
}
|
||||
|
||||
// If move is on a new height and it's not extruding and
|
||||
// it's not currently already in a Z-lift, assume it's possibly a Z-lift
|
||||
if (typeof(z) !== 'undefined' && z != prevZ && !extrude && !zLift) {
|
||||
if (typeof(z) !== 'undefined' && z !== prevZ && !extrude && !zLift) {
|
||||
zLift = true;
|
||||
zLiftZ = prevZ;
|
||||
}
|
||||
@@ -482,8 +549,8 @@ var doParse = function () {
|
||||
zLift = false;
|
||||
}
|
||||
|
||||
if (typeof(z) !== 'undefined' && z != prevZ) {
|
||||
if (z_heights[z]) {
|
||||
if (typeof(z) !== 'undefined' && z !== prevZ) {
|
||||
if (z_heights[z] !== undefined) {
|
||||
layer = z_heights[z];
|
||||
} else {
|
||||
layer = model.length;
|
||||
@@ -493,7 +560,7 @@ var doParse = function () {
|
||||
sendLayer = layer;
|
||||
sendLayerZ = z;
|
||||
prevZ = z;
|
||||
} else if (typeof(z) == 'undefined' && typeof(prevZ) != 'undefined') {
|
||||
} else if (typeof(z) === 'undefined' && typeof(prevZ) !== 'undefined') {
|
||||
if (z_heights.hasOwnProperty(prevZ)) {
|
||||
layer = z_heights[prevZ];
|
||||
} else {
|
||||
@@ -553,7 +620,7 @@ var doParse = function () {
|
||||
}
|
||||
|
||||
if (typeof(sendLayer) !== "undefined") {
|
||||
if (i - lastSend > gcode.length * 0.02 && sendMultiLayer.length != 0) {
|
||||
if (i - lastSend > gcode.length * 0.02 && sendMultiLayer.length !== 0) {
|
||||
lastSend = i;
|
||||
sendMultiLayerToParent(sendMultiLayer, sendMultiLayerZ, i / gcode.length * 100);
|
||||
sendMultiLayer = [];
|
||||
@@ -573,7 +640,9 @@ var parseGCode = function (message) {
|
||||
gcode = message.gcode;
|
||||
firstReport = message.options.firstReport;
|
||||
toolOffsets = message.options.toolOffsets;
|
||||
if (!toolOffsets || toolOffsets.length == 0) toolOffsets = [{x: 0, y: 0}];
|
||||
if (!toolOffsets || toolOffsets.length === 0) toolOffsets = [{x: 0, y: 0}];
|
||||
bed = message.options.bed;
|
||||
ignoreOutsideBed = message.options.ignoreOutsideBed;
|
||||
g90InfluencesExtruder = message.options.g90InfluencesExtruder;
|
||||
|
||||
doParse();
|
||||
@@ -595,6 +664,7 @@ var runAnalyze = function (message) {
|
||||
max = {x: undefined, y: undefined, z: undefined};
|
||||
min = {x: undefined, y: undefined, z: undefined};
|
||||
modelSize = {x: undefined, y: undefined, z: undefined};
|
||||
boundingBox = {minX: undefined, maxX: undefined, minY: undefined, maxY: undefined, minZ: undefined, maxZ: undefined};
|
||||
filamentByLayer = {};
|
||||
totalFilament = 0;
|
||||
printTime = 0;
|
||||
@@ -607,6 +677,7 @@ var runAnalyze = function (message) {
|
||||
|
||||
var setOption = function (options) {
|
||||
for (var opt in options) {
|
||||
if (!options.hasOwnProperty(opt)) continue;
|
||||
gCodeOptions[opt] = options[opt];
|
||||
}
|
||||
};
|
||||
|
||||
@@ -12,6 +12,9 @@ GCODE.gCodeReader = (function(){
|
||||
var max = {x: undefined, y: undefined, z: undefined};
|
||||
var min = {x: undefined, y: undefined, z: undefined};
|
||||
var modelSize = {x: undefined, y: undefined, z: undefined};
|
||||
var boundingBox = {minX: undefined, maxX: undefined,
|
||||
minY: undefined, maxY: undefined,
|
||||
minZ: undefined, maxZ: undefined};
|
||||
var filamentByLayer = {};
|
||||
var printTimeByLayer;
|
||||
var totalFilament=0;
|
||||
@@ -25,6 +28,14 @@ GCODE.gCodeReader = (function(){
|
||||
toolOffsets: [
|
||||
{x: 0, y: 0}
|
||||
],
|
||||
bed: {
|
||||
x: undefined,
|
||||
y: undefined,
|
||||
r: undefined,
|
||||
circular: undefined,
|
||||
centeredOrigin: undefined
|
||||
},
|
||||
ignoreOutsideBed: false,
|
||||
g90InfluencesExtruder: false
|
||||
};
|
||||
|
||||
@@ -33,15 +44,12 @@ GCODE.gCodeReader = (function(){
|
||||
var prepareGCode = function(totalSize){
|
||||
if(!lines)return;
|
||||
gcode = [];
|
||||
var i, tmp, byteCount;
|
||||
var i, byteCount;
|
||||
|
||||
byteCount = 0;
|
||||
for(i=0;i<lines.length;i++){
|
||||
byteCount += lines[i].length + 1; // line length + \n
|
||||
tmp = lines[i].indexOf(";");
|
||||
if(tmp > 1 || tmp === -1) {
|
||||
gcode.push({line: lines[i], percentage: byteCount * 100 / totalSize});
|
||||
}
|
||||
byteCount += lines[i].length + 1; // line length + line ending
|
||||
gcode.push({line: lines[i], percentage: byteCount * 100 / totalSize});
|
||||
}
|
||||
lines = [];
|
||||
};
|
||||
@@ -123,13 +131,19 @@ GCODE.gCodeReader = (function(){
|
||||
clear: function() {
|
||||
model = [];
|
||||
z_heights = [];
|
||||
max = {x: undefined, y: undefined, z: undefined};
|
||||
min = {x: undefined, y: undefined, z: undefined};
|
||||
modelSize = {x: undefined, y: undefined, z: undefined};
|
||||
boundingBox = {minX: undefined, maxX: undefined,
|
||||
minY: undefined, maxY: undefined,
|
||||
minZ: undefined, maxZ: undefined};
|
||||
},
|
||||
|
||||
loadFile: function(reader){
|
||||
this.clear();
|
||||
|
||||
var totalSize = reader.target.result.length;
|
||||
lines = reader.target.result.split(/\n/);
|
||||
lines = reader.target.result.split(/[\r\n]/g);
|
||||
reader.target.result = null;
|
||||
prepareGCode(totalSize);
|
||||
|
||||
@@ -140,6 +154,8 @@ GCODE.gCodeReader = (function(){
|
||||
options: {
|
||||
firstReport: 5,
|
||||
toolOffsets: gCodeOptions["toolOffsets"],
|
||||
bed: gCodeOptions["bed"],
|
||||
ignoreOutsideBed: gCodeOptions["ignoreOutsideBed"],
|
||||
g90InfluencesExtruder: gCodeOptions["g90InfluencesExtruder"]
|
||||
}
|
||||
}
|
||||
@@ -182,6 +198,7 @@ GCODE.gCodeReader = (function(){
|
||||
min = msg.min;
|
||||
max = msg.max;
|
||||
modelSize = msg.modelSize;
|
||||
boundingBox = msg.boundingBox;
|
||||
totalFilament = msg.totalFilament;
|
||||
filamentByLayer = msg.filamentByLayer;
|
||||
speeds = msg.speeds;
|
||||
@@ -203,6 +220,7 @@ GCODE.gCodeReader = (function(){
|
||||
min: min,
|
||||
max: max,
|
||||
modelSize: modelSize,
|
||||
boundingBox: boundingBox,
|
||||
totalFilament: totalFilament,
|
||||
speeds: speeds,
|
||||
speedsByLayer: speedsByLayer,
|
||||
|
||||
@@ -20,7 +20,8 @@ GCODE.renderer = (function(){
|
||||
var lastX, lastY;
|
||||
var dragStart, dragged;
|
||||
var scaleFactor = 1.1;
|
||||
var model;
|
||||
var model = undefined;
|
||||
var modelInfo = undefined;
|
||||
var initialized = false;
|
||||
var renderOptions = {
|
||||
colorGrid: "#bbbbbb",
|
||||
@@ -40,6 +41,8 @@ GCODE.renderer = (function(){
|
||||
differentiateColors: true,
|
||||
showNextLayer: false,
|
||||
showPreviousLayer: false,
|
||||
showBoundingBox: false,
|
||||
showFullSize: false,
|
||||
|
||||
moveModel: true,
|
||||
zoomInOnModel: false,
|
||||
@@ -65,6 +68,7 @@ GCODE.renderer = (function(){
|
||||
var p2 = ctx.transformedPoint(canvas.width,canvas.height);
|
||||
ctx.clearRect(p1.x,p1.y,p2.x-p1.x,p2.y-p1.y);
|
||||
drawGrid();
|
||||
drawBoundingBox();
|
||||
if(renderOptions['showNextLayer'] && layerNumStore < model.length - 1) {
|
||||
drawLayer(layerNumStore + 1, 0, GCODE.renderer.getLayerNumSegments(layerNumStore + 1), true);
|
||||
}
|
||||
@@ -378,6 +382,44 @@ GCODE.renderer = (function(){
|
||||
ctx.stroke();
|
||||
};
|
||||
|
||||
var drawBoundingBox = function() {
|
||||
if (!modelInfo) return;
|
||||
|
||||
var minX, minY, width, height;
|
||||
|
||||
if (renderOptions["showFullSize"]) {
|
||||
minX = modelInfo.min.x * zoomFactor;
|
||||
minY = modelInfo.min.y * zoomFactor;
|
||||
width = modelInfo.modelSize.x * zoomFactor;
|
||||
height = modelInfo.modelSize.y * zoomFactor;
|
||||
|
||||
ctx.beginPath();
|
||||
ctx.strokeStyle = "#0000ff";
|
||||
ctx.setLineDash([2, 5]);
|
||||
|
||||
ctx.rect(minX, minY * -1, width, height * -1);
|
||||
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
if (renderOptions["showBoundingBox"]) {
|
||||
minX = modelInfo.boundingBox.minX * zoomFactor;
|
||||
minY = modelInfo.boundingBox.minY * zoomFactor;
|
||||
width = modelInfo.boundingBox.maxX * zoomFactor - minX;
|
||||
height = modelInfo.boundingBox.maxY * zoomFactor - minY;
|
||||
|
||||
ctx.beginPath();
|
||||
ctx.strokeStyle = "#ff0000";
|
||||
ctx.setLineDash([2, 5]);
|
||||
|
||||
ctx.rect(minX, minY * -1, width, height * -1);
|
||||
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
ctx.setLineDash([1, 0]);
|
||||
};
|
||||
|
||||
var drawLayer = function(layerNum, fromProgress, toProgress, isNotCurrentLayer){
|
||||
log.trace("Drawing layer " + layerNum + " from " + fromProgress + " to " + toProgress + " (current: " + !isNotCurrentLayer + ")");
|
||||
|
||||
@@ -524,27 +566,27 @@ GCODE.renderer = (function(){
|
||||
ctx.stroke();
|
||||
};
|
||||
|
||||
var applyOffsets = function(mdlInfo) {
|
||||
var applyOffsets = function() {
|
||||
var canvasCenter;
|
||||
|
||||
// determine bed and model offsets
|
||||
if (ctx) ctx.translate(-offsetModelX, -offsetModelY);
|
||||
if (renderOptions["centerViewport"] || renderOptions["zoomInOnModel"]) {
|
||||
canvasCenter = ctx.transformedPoint(canvas.width / 2, canvas.height / 2);
|
||||
if (mdlInfo) {
|
||||
offsetModelX = canvasCenter.x - (mdlInfo.min.x + mdlInfo.modelSize.x / 2) * zoomFactor;
|
||||
offsetModelY = canvasCenter.y + (mdlInfo.min.y + mdlInfo.modelSize.y / 2) * zoomFactor;
|
||||
if (modelInfo) {
|
||||
offsetModelX = canvasCenter.x - (modelInfo.boundingBox.minX + modelInfo.boundingBox.maxX) * zoomFactor / 2;
|
||||
offsetModelY = canvasCenter.y + (modelInfo.boundingBox.minY + modelInfo.boundingBox.maxY) * zoomFactor / 2;
|
||||
} else {
|
||||
offsetModelX = 0;
|
||||
offsetModelY = 0;
|
||||
}
|
||||
offsetBedX = 0;
|
||||
offsetBedY = 0;
|
||||
} else if (mdlInfo && renderOptions["moveModel"]) {
|
||||
offsetModelX = (renderOptions["bed"]["x"] / 2 - (mdlInfo.min.x + mdlInfo.modelSize.x / 2)) * zoomFactor;
|
||||
offsetModelY = -1 * (renderOptions["bed"]["y"] / 2 - (mdlInfo.min.y + mdlInfo.modelSize.y / 2)) * zoomFactor;
|
||||
offsetBedX = -1 * (renderOptions["bed"]["x"] / 2 - (mdlInfo.min.x + mdlInfo.modelSize.x / 2)) * zoomFactor;
|
||||
offsetBedY = (renderOptions["bed"]["y"] / 2 - (mdlInfo.min.y + mdlInfo.modelSize.y / 2)) * zoomFactor;
|
||||
} else if (modelInfo && renderOptions["moveModel"]) {
|
||||
offsetModelX = (renderOptions["bed"]["x"] / 2 - (modelInfo.boundingBox.minX + modelInfo.boundingBox.maxX) / 2) * zoomFactor;
|
||||
offsetModelY = -1 * (renderOptions["bed"]["y"] / 2 - (modelInfo.boundingBox.minY + modelInfo.boundingBox.maxY) / 2) * zoomFactor;
|
||||
offsetBedX = -1 * (renderOptions["bed"]["x"] / 2 - (modelInfo.boundingBox.minX + modelInfo.boundingBox.maxX) / 2) * zoomFactor;
|
||||
offsetBedY = (renderOptions["bed"]["y"] / 2 - (modelInfo.boundingBox.minY + modelInfo.boundingBox.maxY) / 2) * zoomFactor;
|
||||
} else if (renderOptions["bed"]["circular"] || renderOptions["bed"]["centeredOrigin"]) {
|
||||
canvasCenter = ctx.transformedPoint(canvas.width / 2, canvas.height / 2);
|
||||
offsetModelX = canvasCenter.x;
|
||||
@@ -560,7 +602,7 @@ GCODE.renderer = (function(){
|
||||
if (ctx) ctx.translate(offsetModelX, offsetModelY);
|
||||
};
|
||||
|
||||
var applyZoom = function(mdlInfo) {
|
||||
var applyZoom = function() {
|
||||
// get middle of canvas
|
||||
var pt = ctx.transformedPoint(canvas.width/2,canvas.height/2);
|
||||
|
||||
@@ -575,9 +617,12 @@ GCODE.renderer = (function(){
|
||||
transform = ctx.getTransform();
|
||||
}
|
||||
|
||||
if (mdlInfo && renderOptions["zoomInOnModel"]) {
|
||||
if (modelInfo && renderOptions["zoomInOnModel"]) {
|
||||
// if we need to zoom in on model, scale factor is calculated by longer side of object in relation to that axis of canvas
|
||||
var scaleF = mdlInfo.modelSize.x > mdlInfo.modelSize.y ? (canvas.width - 10) / mdlInfo.modelSize.x : (canvas.height - 10) / mdlInfo.modelSize.y;
|
||||
var width = modelInfo.boundingBox.maxX - modelInfo.boundingBox.minX;
|
||||
var length = modelInfo.boundingBox.maxY - modelInfo.boundingBox.minY;
|
||||
|
||||
var scaleF = width > length ? (canvas.width - 10) / width : (canvas.height - 10) / length;
|
||||
scaleF /= zoomFactor;
|
||||
if (transform.a && transform.d) {
|
||||
scaleX = scaleF / transform.a * (renderOptions["invertAxes"]["x"] ? -1 : 1);
|
||||
@@ -682,6 +727,7 @@ GCODE.renderer = (function(){
|
||||
var p2 = ctx.transformedPoint(canvas.width, canvas.height);
|
||||
ctx.clearRect(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y);
|
||||
drawGrid();
|
||||
drawBoundingBox();
|
||||
if (model && model.length) {
|
||||
if (layerNum < model.length) {
|
||||
if (renderOptions['showNextLayer'] && layerNum < model.length - 1) {
|
||||
@@ -715,30 +761,31 @@ GCODE.renderer = (function(){
|
||||
scaleY = 1;
|
||||
speeds = [];
|
||||
speedsByLayer = {};
|
||||
modelInfo = undefined;
|
||||
|
||||
this.doRender([], 0);
|
||||
},
|
||||
doRender: function(mdl, layerNum){
|
||||
model = mdl;
|
||||
modelInfo = undefined;
|
||||
|
||||
var mdlInfo = undefined;
|
||||
prevX = 0;
|
||||
prevY = 0;
|
||||
if (!initialized) this.init();
|
||||
|
||||
var toProgress = 1;
|
||||
if (model) {
|
||||
mdlInfo = GCODE.gCodeReader.getModelInfo();
|
||||
speeds = mdlInfo.speeds;
|
||||
speedsByLayer = mdlInfo.speedsByLayer;
|
||||
if (model && model.length) {
|
||||
modelInfo = GCODE.gCodeReader.getModelInfo();
|
||||
speeds = modelInfo.speeds;
|
||||
speedsByLayer = modelInfo.speedsByLayer;
|
||||
if (model[layerNum]) {
|
||||
toProgress = model[layerNum].length;
|
||||
}
|
||||
}
|
||||
|
||||
applyInversion();
|
||||
applyOffsets(mdlInfo);
|
||||
applyZoom(mdlInfo);
|
||||
applyOffsets();
|
||||
applyZoom();
|
||||
|
||||
this.render(layerNum, 0, toProgress);
|
||||
},
|
||||
|
||||
@@ -161,7 +161,8 @@ GCODE.ui = (function(){
|
||||
bed: options.bed
|
||||
});
|
||||
GCODE.gCodeReader.setOption({
|
||||
toolOffsets: options.toolOffsets
|
||||
toolOffsets: options.toolOffsets,
|
||||
bed: options.bed
|
||||
});
|
||||
GCODE.renderer.render(0, 0);
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ ko.bindingHandlers.toggleContent = {
|
||||
e.preventDefault();
|
||||
if(options.class) {
|
||||
$elm.children('[class^="icon-"]').toggleClass(options.class);
|
||||
$elm.children('[class^="fa"]').toggleClass(options.class);
|
||||
}
|
||||
if(options.container) {
|
||||
if(options.parent) {
|
||||
|
||||
@@ -89,6 +89,10 @@
|
||||
return this.issueEntryCommand(location, path, "select", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintFilesClient.prototype.analyse = function (location, path, parameters, opts) {
|
||||
return this.issueEntryCommand(location, path, "analyse", parameters || {}, opts);
|
||||
};
|
||||
|
||||
OctoPrintFilesClient.prototype.slice = function (location, path, parameters, opts) {
|
||||
return this.issueEntryCommand(location, path, "slice",
|
||||
parameters || {}, opts);
|
||||
|
||||
@@ -106,6 +106,7 @@
|
||||
var onOpen = function() {
|
||||
self.reconnecting = false;
|
||||
self.reconnectTrial = 0;
|
||||
self.onConnected();
|
||||
};
|
||||
|
||||
var onClose = function(e) {
|
||||
@@ -117,6 +118,8 @@
|
||||
return;
|
||||
}
|
||||
|
||||
self.onDisconnected(e.code);
|
||||
|
||||
if (self.reconnectTrial < self.options.timeouts.length) {
|
||||
var timeout = self.options.timeouts[self.reconnectTrial];
|
||||
setTimeout(function() { self.reconnect() }, timeout * 1000);
|
||||
@@ -160,6 +163,8 @@
|
||||
|
||||
OctoPrintSocketClient.prototype.onReconnectAttempt = function(trial) {};
|
||||
OctoPrintSocketClient.prototype.onReconnectFailed = function() {};
|
||||
OctoPrintSocketClient.prototype.onConnected = function() {};
|
||||
OctoPrintSocketClient.prototype.onDisconnected = function(code) {};
|
||||
|
||||
OctoPrintSocketClient.prototype.onRateTooLow = function(measured, minimum) {
|
||||
this.increaseRate();
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
function DataUpdater(allViewModels) {
|
||||
function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
var self = this;
|
||||
|
||||
self.allViewModels = allViewModels;
|
||||
self.connectCallback = connectCallback;
|
||||
self.disconnectCallback = disconnectCallback;
|
||||
|
||||
self._pluginHash = undefined;
|
||||
self._configHash = undefined;
|
||||
|
||||
self._connectedDeferred = undefined;
|
||||
|
||||
self._initializedDeferred = undefined;
|
||||
|
||||
self._throttleFactor = 1;
|
||||
self._baseProcessingLimit = 500.0;
|
||||
self._lastProcessingTimes = [];
|
||||
@@ -57,6 +61,13 @@ function DataUpdater(allViewModels) {
|
||||
return self._connectedDeferred.promise();
|
||||
};
|
||||
|
||||
self.initialized = function() {
|
||||
if (self._initializedDeferred) {
|
||||
self._initializedDeferred.resolve();
|
||||
self._initializedDeferred = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
self._onReconnectAttempt = function(trial) {
|
||||
if (trial <= 0) {
|
||||
// Only consider it a real disconnect if the trial number has exceeded our threshold.
|
||||
@@ -99,7 +110,27 @@ function DataUpdater(allViewModels) {
|
||||
$("#offline_overlay_message").html(gettext("The server appears to be offline, at least I'm not getting any response from it. I <strong>could not reconnect automatically</strong>, but you may try a manual reconnect using the button below."));
|
||||
};
|
||||
|
||||
self._onConnected = function(event) {
|
||||
self._onDisconnected = function(code) {
|
||||
if (self._initializedDeferred) {
|
||||
self._initializedDeferred.reject();
|
||||
}
|
||||
self._initializedDeferred = undefined;
|
||||
|
||||
if (self.disconnectCallback) {
|
||||
self.disconnectCallback();
|
||||
}
|
||||
};
|
||||
|
||||
self._onConnectMessage = function(event) {
|
||||
if (self._initializedDeferred) {
|
||||
self._initializedDeferred.reject();
|
||||
}
|
||||
self._initializedDeferred = $.Deferred();
|
||||
|
||||
if (self.connectCallback) {
|
||||
self.connectCallback();
|
||||
}
|
||||
|
||||
var data = event.data;
|
||||
|
||||
// update version information
|
||||
@@ -117,37 +148,40 @@ function DataUpdater(allViewModels) {
|
||||
var oldConfigHash = self._configHash;
|
||||
self._configHash = data["config_hash"];
|
||||
|
||||
// process safe mode
|
||||
if (self._safeModePopup) self._safeModePopup.remove();
|
||||
if (data["safe_mode"]) {
|
||||
// safe mode is active, let's inform the user
|
||||
log.info("Safe mode is active. Third party plugins are disabled and cannot be enabled.");
|
||||
self._ifInitialized(function() {
|
||||
// process safe mode
|
||||
if (self._safeModePopup) self._safeModePopup.remove();
|
||||
if (data["safe_mode"]) {
|
||||
// safe mode is active, let's inform the user
|
||||
log.info("Safe mode is active. Third party plugins are disabled and cannot be enabled.");
|
||||
|
||||
self._safeModePopup = new PNotify({
|
||||
title: gettext("Safe mode is active"),
|
||||
text: gettext("The server is currently running in safe mode. Third party plugins are disabled and cannot be enabled."),
|
||||
hide: false
|
||||
});
|
||||
}
|
||||
self._safeModePopup = new PNotify({
|
||||
title: gettext("Safe mode is active"),
|
||||
text: gettext("The server is currently running in safe mode. Third party plugins are disabled and cannot be enabled."),
|
||||
hide: false
|
||||
});
|
||||
}
|
||||
|
||||
// if the offline overlay is still showing, now's a good time to
|
||||
// hide it, plus reload the camera feed if it's currently displayed
|
||||
if ($("#offline_overlay").is(":visible")) {
|
||||
hideOfflineOverlay();
|
||||
callViewModels(self.allViewModels, "onServerReconnect");
|
||||
callViewModels(self.allViewModels, "onDataUpdaterReconnect");
|
||||
} else {
|
||||
callViewModels(self.allViewModels, "onServerConnect");
|
||||
}
|
||||
// if the offline overlay is still showing, now's a good time to
|
||||
// hide it, plus reload the camera feed if it's currently displayed
|
||||
if ($("#offline_overlay").is(":visible")) {
|
||||
hideOfflineOverlay();
|
||||
callViewModels(self.allViewModels, "onServerReconnect");
|
||||
callViewModels(self.allViewModels, "onDataUpdaterReconnect");
|
||||
} else {
|
||||
callViewModels(self.allViewModels, "onServerConnect");
|
||||
}
|
||||
|
||||
// if the version, the plugin hash or the config hash changed, we
|
||||
// want the user to reload the UI since it might be stale now
|
||||
var versionChanged = oldVersion != VERSION;
|
||||
var pluginsChanged = oldPluginHash != undefined && oldPluginHash != self._pluginHash;
|
||||
var configChanged = oldConfigHash != undefined && oldConfigHash != self._configHash;
|
||||
if (versionChanged || pluginsChanged || configChanged) {
|
||||
showReloadOverlay();
|
||||
}
|
||||
// if the version, the plugin hash or the config hash changed, we
|
||||
// want the user to reload the UI since it might be stale now
|
||||
var versionChanged = oldVersion !== VERSION;
|
||||
var pluginsChanged = oldPluginHash !== undefined && oldPluginHash !== self._pluginHash;
|
||||
var configChanged = oldConfigHash !== undefined && oldConfigHash !== self._configHash;
|
||||
if (versionChanged || pluginsChanged || configChanged) {
|
||||
showReloadOverlay();
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
log.info("Connected to the server");
|
||||
|
||||
@@ -159,79 +193,89 @@ function DataUpdater(allViewModels) {
|
||||
};
|
||||
|
||||
self._onHistoryData = function(event) {
|
||||
callViewModels(self.allViewModels, "fromHistoryData", [event.data]);
|
||||
};
|
||||
|
||||
self._onCurrentData = function(event) {
|
||||
callViewModels(self.allViewModels, "fromCurrentData", [event.data]);
|
||||
};
|
||||
|
||||
self._onSlicingProgress = function(event) {
|
||||
$("#gcode_upload_progress").find(".bar").text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: Math.round(event.data["progress"])}));
|
||||
|
||||
var data = event.data;
|
||||
callViewModels(self.allViewModels, "onSlicingProgress", [
|
||||
data["slicer"],
|
||||
data["model_path"],
|
||||
data["machinecode_path"],
|
||||
data["progress"]
|
||||
]);
|
||||
};
|
||||
|
||||
self._onEvent = function(event) {
|
||||
var gcodeUploadProgress = $("#gcode_upload_progress");
|
||||
var gcodeUploadProgressBar = $(".bar", gcodeUploadProgress);
|
||||
|
||||
var type = event.data["type"];
|
||||
var payload = event.data["payload"];
|
||||
var html = "";
|
||||
|
||||
log.debug("Got event " + type + " with payload: " + JSON.stringify(payload));
|
||||
|
||||
if (type == "PrintCancelled") {
|
||||
if (payload.firmwareError) {
|
||||
new PNotify({
|
||||
title: gettext("Unhandled communication error"),
|
||||
text: _.sprintf(gettext("There was an unhandled error while talking to the printer. Due to that the ongoing print job was cancelled. Error: %(firmwareError)s"), payload),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
}
|
||||
} else if (type == "Error") {
|
||||
new PNotify({
|
||||
title: gettext("Unhandled communication error"),
|
||||
text: _.sprintf(gettext("The was an unhandled error while talking to the printer. Due to that OctoPrint disconnected. Error: %(error)s"), payload),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
}
|
||||
|
||||
var legacyEventHandlers = {
|
||||
"UpdatedFiles": "onUpdatedFiles",
|
||||
"MetadataStatisticsUpdated": "onMetadataStatisticsUpdated",
|
||||
"MetadataAnalysisFinished": "onMetadataAnalysisFinished",
|
||||
"SlicingDone": "onSlicingDone",
|
||||
"SlicingCancelled": "onSlicingCancelled",
|
||||
"SlicingFailed": "onSlicingFailed"
|
||||
};
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onEvent" + type)) {
|
||||
viewModel["onEvent" + type](payload);
|
||||
} else if (legacyEventHandlers.hasOwnProperty(type) && viewModel.hasOwnProperty(legacyEventHandlers[type])) {
|
||||
// there might still be code that uses the old callbacks, make sure those still get called
|
||||
// but log a warning
|
||||
log.warn("View model " + viewModel.name + " is using legacy event handler " + legacyEventHandlers[type] + ", new handler is called " + legacyEventHandlers[type]);
|
||||
viewModel[legacyEventHandlers[type]](payload);
|
||||
}
|
||||
self._ifInitialized(function() {
|
||||
callViewModels(self.allViewModels, "fromHistoryData", [event.data]);
|
||||
});
|
||||
};
|
||||
|
||||
self._onCurrentData = function(event) {
|
||||
self._ifInitialized(function() {
|
||||
callViewModels(self.allViewModels, "fromCurrentData", [event.data]);
|
||||
});
|
||||
};
|
||||
|
||||
self._onSlicingProgress = function(event) {
|
||||
self._ifInitialized(function() {
|
||||
$("#gcode_upload_progress").find(".bar").text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: Math.round(event.data["progress"])}));
|
||||
|
||||
var data = event.data;
|
||||
callViewModels(self.allViewModels, "onSlicingProgress", [
|
||||
data["slicer"],
|
||||
data["model_path"],
|
||||
data["machinecode_path"],
|
||||
data["progress"]
|
||||
]);
|
||||
});
|
||||
};
|
||||
|
||||
self._onEvent = function(event) {
|
||||
self._ifInitialized(function() {
|
||||
var type = event.data["type"];
|
||||
var payload = event.data["payload"];
|
||||
|
||||
log.debug("Got event " + type + " with payload: " + JSON.stringify(payload));
|
||||
|
||||
if (type == "PrintCancelled") {
|
||||
if (payload.firmwareError) {
|
||||
new PNotify({
|
||||
title: gettext("Unhandled communication error"),
|
||||
text: _.sprintf(gettext("There was an unhandled error while talking to the printer. Due to that the ongoing print job was cancelled. Error: %(firmwareError)s"), payload),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
}
|
||||
} else if (type == "Error") {
|
||||
if (payload.error && payload.error.indexOf("autodetect") == -1) { // ignore "failed to autodetect"
|
||||
new PNotify({
|
||||
title: gettext("Unhandled communication error"),
|
||||
text: _.sprintf(gettext("The was an unhandled error while talking to the printer. Due to that OctoPrint disconnected. Error: %(error)s"), payload),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
var legacyEventHandlers = {
|
||||
"UpdatedFiles": "onUpdatedFiles",
|
||||
"MetadataStatisticsUpdated": "onMetadataStatisticsUpdated",
|
||||
"MetadataAnalysisFinished": "onMetadataAnalysisFinished",
|
||||
"SlicingDone": "onSlicingDone",
|
||||
"SlicingCancelled": "onSlicingCancelled",
|
||||
"SlicingFailed": "onSlicingFailed"
|
||||
};
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onEvent" + type)) {
|
||||
viewModel["onEvent" + type](payload);
|
||||
} else if (legacyEventHandlers.hasOwnProperty(type) && viewModel.hasOwnProperty(legacyEventHandlers[type])) {
|
||||
// there might still be code that uses the old callbacks, make sure those still get called
|
||||
// but log a warning
|
||||
log.warn("View model " + viewModel.name + " is using legacy event handler " + legacyEventHandlers[type] + ", new handler is called " + legacyEventHandlers[type]);
|
||||
viewModel[legacyEventHandlers[type]](payload);
|
||||
}
|
||||
});
|
||||
})
|
||||
};
|
||||
|
||||
self._onTimelapse = function(event) {
|
||||
callViewModels(self.allViewModels, "fromTimelapseData", [event.data]);
|
||||
self._ifInitialized(function() {
|
||||
callViewModels(self.allViewModels, "fromTimelapseData", [event.data]);
|
||||
})
|
||||
};
|
||||
|
||||
self._onPluginMessage = function(event) {
|
||||
callViewModels(self.allViewModels, "onDataUpdaterPluginMessage", [event.data.plugin, event.data.data]);
|
||||
self._ifInitialized(function() {
|
||||
callViewModels(self.allViewModels, "onDataUpdaterPluginMessage", [event.data.plugin, event.data.data]);
|
||||
})
|
||||
};
|
||||
|
||||
self._onIncreaseRate = function(measurement, minimum) {
|
||||
@@ -244,12 +288,21 @@ function DataUpdater(allViewModels) {
|
||||
OctoPrint.socket.decreaseRate();
|
||||
};
|
||||
|
||||
self._ifInitialized = function(callback) {
|
||||
if (self._initializedDeferred) {
|
||||
self._initializedDeferred.done(callback);
|
||||
} else {
|
||||
callback();
|
||||
}
|
||||
};
|
||||
|
||||
OctoPrint.socket.onDisconnected = self._onDisconnected;
|
||||
OctoPrint.socket.onReconnectAttempt = self._onReconnectAttempt;
|
||||
OctoPrint.socket.onReconnectFailed = self._onReconnectFailed;
|
||||
OctoPrint.socket.onRateTooHigh = self._onDecreaseRate;
|
||||
OctoPrint.socket.onRateTooLow = self._onIncreaseRate;
|
||||
OctoPrint.socket
|
||||
.onMessage("connected", self._onConnected)
|
||||
.onMessage("connected", self._onConnectMessage)
|
||||
.onMessage("history", self._onHistoryData)
|
||||
.onMessage("current", self._onCurrentData)
|
||||
.onMessage("slicingProgress", self._onSlicingProgress)
|
||||
|
||||
@@ -524,12 +524,14 @@ function formatFilament(filament) {
|
||||
}
|
||||
|
||||
function cleanTemperature(temp) {
|
||||
if (!temp || temp < 10) return gettext("off");
|
||||
if (temp === undefined || !_.isNumber(temp)) return "-";
|
||||
if (temp < 10) return gettext("off");
|
||||
return temp;
|
||||
}
|
||||
|
||||
function formatTemperature(temp, showF) {
|
||||
if (!temp || temp < 10) return gettext("off");
|
||||
if (temp === undefined || !_.isNumber(temp)) return "-";
|
||||
if (temp < 10) return gettext("off");
|
||||
if (showF) {
|
||||
return _.sprintf("%.1f°C (%.1f°F)", temp, temp * 9 / 5 + 32);
|
||||
} else {
|
||||
@@ -646,6 +648,7 @@ function showConfirmationDialog(msg, onacknowledge, options) {
|
||||
var proceed = options.proceed || gettext("Proceed");
|
||||
var proceedClass = options.proceedClass || "danger";
|
||||
var onproceed = options.onproceed || undefined;
|
||||
var onclose = options.onclose || undefined;
|
||||
var dialogClass = options.dialogClass || "";
|
||||
|
||||
var modalHeader = $('<a href="javascript:void(0)" class="close" data-dismiss="modal" aria-hidden="true">×</a><h3>' + title + '</h3>');
|
||||
@@ -663,14 +666,19 @@ function showConfirmationDialog(msg, onacknowledge, options) {
|
||||
.append($('<div></div>').addClass('modal-header').append(modalHeader))
|
||||
.append($('<div></div>').addClass('modal-body').append(modalBody))
|
||||
.append($('<div></div>').addClass('modal-footer').append(cancelButton).append(proceedButton));
|
||||
modal.on('hidden', function(event) {
|
||||
if (onclose && _.isFunction(onclose)) {
|
||||
onclose(event);
|
||||
}
|
||||
});
|
||||
modal.modal("show");
|
||||
|
||||
proceedButton.click(function(e) {
|
||||
e.preventDefault();
|
||||
modal.modal("hide");
|
||||
if (onproceed && _.isFunction(onproceed)) {
|
||||
onproceed(e);
|
||||
}
|
||||
modal.modal("hide");
|
||||
});
|
||||
|
||||
return modal;
|
||||
@@ -682,9 +690,14 @@ function showConfirmationDialog(msg, onacknowledge, options) {
|
||||
* Will listen to the supplied promise, update the progress on .progress events and
|
||||
* enabling the close button and (optionally) closing the dialog on promise resolve.
|
||||
*
|
||||
* The calling code should call "notify" on the deferred backing the promise and supply
|
||||
* two parameters: the text to display on the progress bar and the optional output field and
|
||||
* a boolean value indicating whether the operation behind that update was successful or not.
|
||||
* The calling code should call "notify" on the deferred backing the promise and supply:
|
||||
*
|
||||
* * the text to display on the progress bar and the optional output field and
|
||||
* a boolean value indicating whether the operation behind that update was successful or not
|
||||
* * a short text to display on the progress bar, a long text to display on the optional output
|
||||
* field and a boolean value indicating whether the operation behind that update was
|
||||
* successful or not
|
||||
*
|
||||
* Non-successful progress updates will remove the barClassSuccess class from the progress bar and
|
||||
* apply the barClassFailure class and also apply the outputClassFailure to the produced line
|
||||
* in the output.
|
||||
@@ -764,7 +777,7 @@ function showProgressModal(options, promise) {
|
||||
|
||||
var pre;
|
||||
if (output) {
|
||||
pre = $("<pre class='terminal pre-scrollable' style='height: 70px; font-size: 0.8em'></pre>");
|
||||
pre = $("<pre class='pre-scrollable pre-output' style='height: 70px; font-size: 0.8em'></pre>");
|
||||
modalBody.append(pre);
|
||||
}
|
||||
|
||||
@@ -778,7 +791,19 @@ function showProgressModal(options, promise) {
|
||||
|
||||
var counter = 0;
|
||||
promise
|
||||
.progress(function(text, success) {
|
||||
.progress(function() {
|
||||
var short, long, success;
|
||||
if (arguments.length === 2) {
|
||||
short = long = arguments[0];
|
||||
success = arguments[1];
|
||||
} else if (arguments.length === 3) {
|
||||
short = arguments[0];
|
||||
long = arguments[1];
|
||||
success = arguments[2];
|
||||
} else {
|
||||
throw Error("Invalid parameters for showProgressModal, expected either (text, success) or (short, long, success)");
|
||||
}
|
||||
|
||||
var value;
|
||||
|
||||
if (max === undefined || max <= 0) {
|
||||
@@ -790,8 +815,8 @@ function showProgressModal(options, promise) {
|
||||
|
||||
// update progress bar
|
||||
progressBar.width(String(value) + "%");
|
||||
progressTextFront.text(text);
|
||||
progressTextBack.text(text);
|
||||
progressTextFront.text(short);
|
||||
progressTextBack.text(short);
|
||||
progressTextFront.width(progress.width());
|
||||
|
||||
// if not successful, apply failure class
|
||||
@@ -803,9 +828,9 @@ function showProgressModal(options, promise) {
|
||||
|
||||
if (output && pre) {
|
||||
if (success) {
|
||||
pre.append($("<span class='" + outputClassSuccess + "'>" + text + "</span><br>"));
|
||||
pre.append($("<span class='" + outputClassSuccess + "'>" + long + "</span>"));
|
||||
} else {
|
||||
pre.append($("<span class='" + outputClassFailure + "'>" + text + "</span><br>"));
|
||||
pre.append($("<span class='" + outputClassFailure + "'>" + long + "</span>"));
|
||||
}
|
||||
pre.scrollTop(pre[0].scrollHeight - pre.height());
|
||||
}
|
||||
@@ -958,11 +983,30 @@ function getOnlyChangedData(data, oldData) {
|
||||
return f(data, oldData);
|
||||
}
|
||||
|
||||
function setOnViewModels(allViewModels, key, value) {
|
||||
setOnViewModelsIf(allViewModels, key, value, undefined);
|
||||
}
|
||||
|
||||
function setOnViewModelsIf(allViewModels, key, value, condition) {
|
||||
if (condition === undefined || !_.isFunction(condition)) {
|
||||
condition = function() { return true; };
|
||||
}
|
||||
|
||||
_.each(allViewModels, function(viewModel) {
|
||||
if (condition(viewModel)) {
|
||||
viewModel[key] = value;
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function callViewModels(allViewModels, method, callback) {
|
||||
if (!allViewModels) return;
|
||||
callViewModelsIf(allViewModels, method, undefined, callback);
|
||||
}
|
||||
|
||||
function callViewModelsIf(allViewModels, method, condition, callback) {
|
||||
if (!allViewModels) return;
|
||||
|
||||
if (condition == undefined || !_.isFunction(condition)) {
|
||||
condition = function() { return true; };
|
||||
}
|
||||
@@ -1048,8 +1092,9 @@ var getQueryParameterByName = function(name, url) {
|
||||
*
|
||||
* E.g. turns a null byte in the string into "\x00".
|
||||
*
|
||||
* Only characters 0 to 31, 127 and 255 will be escaped, that
|
||||
* should leave printable characters and unicode alone.
|
||||
* Characters 0 to 31 excluding 9, 10 and 13 will be escaped, as will
|
||||
* 127 and 255. That should leave printable characters and unicode
|
||||
* alone.
|
||||
*
|
||||
* Originally based on
|
||||
* https://gist.github.com/mathiasbynens/1243213#gistcomment-53590
|
||||
@@ -1063,7 +1108,7 @@ var escapeUnprintableCharacters = function(str) {
|
||||
var charCode;
|
||||
|
||||
while (!isNaN(charCode = str.charCodeAt(index))) {
|
||||
if (charCode < 32 || charCode == 127 || charCode == 255) {
|
||||
if ((charCode < 32 && charCode != 9 && charCode != 10 && charCode != 13) || charCode == 127 || charCode == 255) {
|
||||
// special hex chars
|
||||
result += "\\x" + (charCode > 15 ? "" : "0") + charCode.toString(16)
|
||||
} else {
|
||||
|
||||
@@ -7,7 +7,7 @@ $(function() {
|
||||
|
||||
//~~ Logging setup
|
||||
|
||||
log.setLevel(CONFIG_DEBUG ? "debug" : "info");
|
||||
log.setLevel(CONFIG_DEBUG ? log.levels.DEBUG : log.levels.INFO);
|
||||
|
||||
//~~ OctoPrint client setup
|
||||
OctoPrint.options.baseurl = BASEURL;
|
||||
@@ -38,7 +38,18 @@ $(function() {
|
||||
browserTabVisibility: undefined,
|
||||
selectedTab: undefined,
|
||||
settingsOpen: false,
|
||||
wizardOpen: false
|
||||
wizardOpen: false,
|
||||
browser: {
|
||||
chrome: false,
|
||||
firefox: false,
|
||||
safari: false,
|
||||
ie: false,
|
||||
edge: false,
|
||||
opera: false,
|
||||
|
||||
mobile: false,
|
||||
desktop: false
|
||||
}
|
||||
};
|
||||
|
||||
var browserVisibilityCallbacks = [];
|
||||
@@ -88,6 +99,22 @@ $(function() {
|
||||
updateBrowserVisibility();
|
||||
}
|
||||
|
||||
// determine browser - loosely based on is.js
|
||||
|
||||
var navigator = window.navigator;
|
||||
var userAgent = (navigator && navigator.userAgent || "").toLowerCase();
|
||||
var vendor = (navigator && navigator.vendor || "").toLowerCase();
|
||||
|
||||
exports.browser.opera = userAgent.match(/opera|opr/) != null;
|
||||
exports.browser.chrome = !exports.browser.opera && /google inc/.test(vendor) && userAgent.match(/chrome|crios/) != null;
|
||||
exports.browser.firefox = userAgent.match(/firefox|fxios/) != null;
|
||||
exports.browser.ie = userAgent.match(/msie|trident/) != null;
|
||||
exports.browser.edge = userAgent.match(/edge/) != null;
|
||||
exports.browser.safari = !exports.browser.chrome && !exports.browser.edge && !exports.browser.opera && userAgent.match(/safari/) != null;
|
||||
|
||||
exports.browser.mobile = $.browser.mobile;
|
||||
exports.browser.desktop = !exports.browser.mobile;
|
||||
|
||||
// exports
|
||||
|
||||
exports.isVisible = function() { return !isHidden() };
|
||||
@@ -98,6 +125,8 @@ $(function() {
|
||||
return exports;
|
||||
})();
|
||||
|
||||
log.debug("Browser enviroment:", OctoPrint.coreui.browser);
|
||||
|
||||
//~~ AJAX setup
|
||||
|
||||
// work around a stupid iOS6 bug where ajax requests get cached and only work once, as described at
|
||||
@@ -494,7 +523,15 @@ $(function() {
|
||||
// reload overlay
|
||||
$("#reloadui_overlay_reload").click(function() { location.reload(); });
|
||||
|
||||
//~~ view model binding
|
||||
//~~ final initialization - passive login, settings fetch, view model binding
|
||||
|
||||
if (!_.has(viewModelMap, "settingsViewModel")) {
|
||||
throw new Error("settingsViewModel is missing, can't run UI");
|
||||
}
|
||||
|
||||
if (!_.has(viewModelMap, "loginStateViewModel")) {
|
||||
throw new Error("loginStateViewModel is missing, can't run UI");
|
||||
}
|
||||
|
||||
var bindViewModels = function() {
|
||||
log.info("Going to bind " + allViewModelData.length + " view models...");
|
||||
@@ -563,7 +600,8 @@ $(function() {
|
||||
});
|
||||
}
|
||||
|
||||
viewModel._unbound = viewModel._bindings != undefined && viewModel._bindings.length == 0;
|
||||
viewModel._unbound = viewModel._bindings !== undefined && viewModel._bindings.length === 0;
|
||||
viewModel._bound = viewModel._bindings.length > 0;
|
||||
|
||||
if (viewModel.hasOwnProperty("onAfterBinding")) {
|
||||
viewModel.onAfterBinding();
|
||||
@@ -575,6 +613,7 @@ $(function() {
|
||||
|
||||
// startup complete
|
||||
callViewModels(allViewModels, "onStartupComplete");
|
||||
setOnViewModels(allViewModels, "_startupComplete", true);
|
||||
|
||||
// make sure we can track the browser tab visibility
|
||||
OctoPrint.coreui.onBrowserVisibilityChange(function(status) {
|
||||
@@ -585,34 +624,84 @@ $(function() {
|
||||
log.info("Application startup complete");
|
||||
};
|
||||
|
||||
if (!_.has(viewModelMap, "settingsViewModel")) {
|
||||
throw new Error("settingsViewModel is missing, can't run UI")
|
||||
}
|
||||
var fetchSettings = function() {
|
||||
log.info("Finalizing application startup");
|
||||
|
||||
//~~ Starting up the app
|
||||
callViewModels(allViewModels, "onStartup");
|
||||
|
||||
viewModelMap["settingsViewModel"].requestData()
|
||||
.done(function() {
|
||||
// There appears to be an odd race condition either in JQuery's AJAX implementation or
|
||||
// the browser's implementation of XHR, causing a second GET request from inside the
|
||||
// completion handler of the very same request to never get its completion handler called
|
||||
// if ETag headers are present on the response (the status code of the request does NOT
|
||||
// seem to matter here, only that the ETag header is present).
|
||||
//
|
||||
// Minimal example with which I was able to reproduce this behaviour can be found
|
||||
// at https://gist.github.com/foosel/b2ddb9ebd71b0b63a749444651bfce3f
|
||||
//
|
||||
// Decoupling all consecutive calls from this done event handler hence is an easy way
|
||||
// to avoid this problem. A zero timeout should do the trick nicely.
|
||||
window.setTimeout(bindViewModels, 0);
|
||||
});
|
||||
};
|
||||
|
||||
log.info("Initial application setup done, connecting to server...");
|
||||
|
||||
/**
|
||||
* The following looks a bit complicated, so let me explain...
|
||||
*
|
||||
* Once we connect to the server (and that also includes consecutive reconnects), the
|
||||
* first thing we need to do is perform a passive login to a) establish a proper request
|
||||
* session with the server and b) figure out the login status of our client. That passive
|
||||
* login will be responded to with our session cookie and we must make absolutely sure that
|
||||
* this cannot be overridden by any concurrent requests. E.g. if we would send the passive
|
||||
* login request and also something like a settings fetch, the settings would not have the
|
||||
* cookie yet, hence the server would generate a new session for that request, and if the
|
||||
* response for the settings now arrives later than the passive login we'll get our
|
||||
* session cookie from that login directly overwritten again. That will not only lead to
|
||||
* us losing our login session with the server but also the client _thinking_ it is logged
|
||||
* in when in fact it isn't. See also #1881.
|
||||
*
|
||||
* So what we do here is ensure that we send the passive login request _and nothing else_
|
||||
* until that has been responded to and hence our session been properly established. Only
|
||||
* then we may trigger stuff like the various view model callbacks that might cause
|
||||
* additional requests.
|
||||
*
|
||||
* onServerConnect below takes care of the passive login. Only once that's completed it tells
|
||||
* our DataUpdater that it's ok to trigger any callbacks in view models. On the initial
|
||||
* server connect (during first initialization) we also trigger the settings fetch and
|
||||
* binding proceedure once that's done, but only then.
|
||||
*
|
||||
* Or, as a fancy diagram: https://gist.githubusercontent.com/foosel/0cdc3a03cf5311804271f12e87293c0c/raw/abc84fdc3b13030d70961539d9c132ae39c32085/octoprint_web_startup.txt
|
||||
*/
|
||||
|
||||
var onServerConnect = function() {
|
||||
// Always perform a passive login on server (re)connect. No need for
|
||||
// onServerConnect/onServerReconnect on the LoginStateViewModel with this in place.
|
||||
return viewModelMap["loginStateViewModel"].requestData()
|
||||
.done(function() {
|
||||
// Only mark our data updater as initialized once we've done our initial
|
||||
// passive login request.
|
||||
//
|
||||
// This is to ensure that we have no concurrent requests triggered by socket events
|
||||
// overriding each other's session during app intialization
|
||||
dataUpdater.initialized();
|
||||
});
|
||||
};
|
||||
|
||||
var dataUpdater = new DataUpdater(allViewModels);
|
||||
dataUpdater.connect()
|
||||
.done(function() {
|
||||
log.info("Finalizing application startup");
|
||||
// make sure we trigger onServerConnect should we dis- and reconnect to the server
|
||||
dataUpdater.connectCallback = onServerConnect;
|
||||
|
||||
//~~ Starting up the app
|
||||
callViewModels(allViewModels, "onStartup");
|
||||
|
||||
viewModelMap["settingsViewModel"].requestData()
|
||||
.done(function() {
|
||||
// There appears to be an odd race condition either in JQuery's AJAX implementation or
|
||||
// the browser's implementation of XHR, causing a second GET request from inside the
|
||||
// completion handler of the very same request to never get its completion handler called
|
||||
// if ETag headers are present on the response (the status code of the request does NOT
|
||||
// seem to matter here, only that the ETag header is present).
|
||||
//
|
||||
// Minimal example with which I was able to reproduce this behaviour can be found
|
||||
// at https://gist.github.com/foosel/b2ddb9ebd71b0b63a749444651bfce3f
|
||||
//
|
||||
// Decoupling all consecutive calls from this done event handler hence is an easy way
|
||||
// to avoid this problem. A zero timeout should do the trick nicely.
|
||||
window.setTimeout(bindViewModels, 0);
|
||||
});
|
||||
// perform passive login first
|
||||
onServerConnect().done(function() {
|
||||
// then trigger a settings fetch
|
||||
window.setTimeout(fetchSettings, 0);
|
||||
});
|
||||
});
|
||||
}
|
||||
);
|
||||
@@ -100,7 +100,7 @@ $(function() {
|
||||
self.isReady(data.flags.ready);
|
||||
self.isLoading(data.flags.loading);
|
||||
|
||||
if (self.loginState.isUser() && self.previousIsOperational != self.isOperational()) {
|
||||
if (self.loginState.isUser() && 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();
|
||||
@@ -132,16 +132,14 @@ $(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();
|
||||
}
|
||||
});
|
||||
self.onUserLoggedIn = function() {
|
||||
self.openOrCloseOnStateChange();
|
||||
};
|
||||
|
||||
self.onUserLoggedOut = function() {
|
||||
self.openOrCloseOnStateChange();
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -353,25 +353,21 @@ $(function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self._isSafari = function() {
|
||||
var is_chrome = navigator.userAgent.indexOf('Chrome') > -1;
|
||||
var is_safari = navigator.userAgent.indexOf("Safari") > -1;
|
||||
return is_safari && !is_chrome;
|
||||
};
|
||||
|
||||
self._disableWebcam = function() {
|
||||
// only disable webcam stream if tab is out of focus for more than 5s, otherwise we might cause
|
||||
// more load by the constant connection creation than by the actual webcam stream
|
||||
|
||||
// safari bug doesn't release the mjpeg stream, so we just disable this for safari.
|
||||
if (self._isSafari()) {
|
||||
if (OctoPrint.coreui.browser.safari) {
|
||||
return;
|
||||
}
|
||||
|
||||
var timeout = self.settings.webcam_streamTimeout() || 5;
|
||||
self.webcamDisableTimeout = setTimeout(function () {
|
||||
log.debug("Unloading webcam stream");
|
||||
$("#webcam_image").attr("src", "");
|
||||
self.webcamLoaded(false);
|
||||
}, 5000);
|
||||
}, timeout * 1000);
|
||||
};
|
||||
|
||||
self._enableWebcam = function() {
|
||||
@@ -386,7 +382,7 @@ $(function() {
|
||||
var currentSrc = webcamImage.attr("src");
|
||||
|
||||
// safari bug doesn't release the mjpeg stream, so we just set it up the once
|
||||
if (self._isSafari() && currentSrc != undefined) {
|
||||
if (OctoPrint.coreui.browser.safari && currentSrc != undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -442,6 +438,7 @@ $(function() {
|
||||
self.additionalControls = additionalControls;
|
||||
self.rerenderControls();
|
||||
}
|
||||
self._enableWebcam();
|
||||
};
|
||||
|
||||
self.onFocus = function (data, event) {
|
||||
|
||||
@@ -466,13 +466,13 @@ $(function() {
|
||||
if (event) {
|
||||
var element = $(event.currentTarget);
|
||||
if (element.length) {
|
||||
var icon = $("i.icon-trash", element);
|
||||
var icon = $("i.fa-trash-o", element);
|
||||
if (icon.length) {
|
||||
activateSpinner = function() {
|
||||
icon.removeClass("icon-trash").addClass("icon-spinner icon-spin");
|
||||
icon.removeClass("fa-trash-o").addClass("fa-spinner fa-spin");
|
||||
};
|
||||
finishSpinner = function() {
|
||||
icon.removeClass("icon-spinner icon-spin").addClass("icon-trash");
|
||||
icon.removeClass("fa-spinner fa-spin").addClass("fa-trash-o");
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -581,7 +581,7 @@ $(function() {
|
||||
|
||||
var additionalInfo = $(".additionalInfo", entryElement);
|
||||
additionalInfo.slideToggle("fast", function() {
|
||||
$(".toggleAdditionalData i", entryElement).toggleClass("icon-chevron-down icon-chevron-up");
|
||||
$(".toggleAdditionalData i", entryElement).toggleClass("fa-chevron-down fa-chevron-up");
|
||||
});
|
||||
};
|
||||
|
||||
@@ -841,13 +841,14 @@ $(function() {
|
||||
|
||||
function evaluateDropzones() {
|
||||
var enableLocal = self.loginState.isUser();
|
||||
var enableSd = enableLocal && CONFIG_SD_SUPPORT && self.printerState.isSdReady();
|
||||
var enableSd = enableLocal && CONFIG_SD_SUPPORT && self.printerState.isSdReady() && !self.isPrinting();
|
||||
|
||||
self._setDropzone("local", enableLocal);
|
||||
self._setDropzone("sdcard", enableSd);
|
||||
}
|
||||
self.loginState.isUser.subscribe(evaluateDropzones);
|
||||
self.printerState.isSdReady.subscribe(evaluateDropzones);
|
||||
self.isPrinting.subscribe(evaluateDropzones);
|
||||
evaluateDropzones();
|
||||
|
||||
self.requestData();
|
||||
@@ -1106,7 +1107,7 @@ $(function() {
|
||||
if (foundLocal) {
|
||||
self.dropZoneLocalBackground.addClass("hover");
|
||||
self.dropZoneSdBackground.removeClass("hover");
|
||||
} else if (foundSd && self.printerState.isSdReady()) {
|
||||
} else if (foundSd && self.printerState.isSdReady() && !self.isPrinting()) {
|
||||
self.dropZoneSdBackground.addClass("hover");
|
||||
self.dropZoneLocalBackground.removeClass("hover");
|
||||
} else if (found) {
|
||||
|
||||
@@ -46,6 +46,8 @@ $(function() {
|
||||
self.renderer_zoomOnModel = ko.observable(false);
|
||||
self.renderer_showMoves = ko.observable(true);
|
||||
self.renderer_showRetracts = ko.observable(true);
|
||||
self.renderer_showBoundingBox = ko.observable(false);
|
||||
self.renderer_showFullSize = ko.observable(false);
|
||||
self.renderer_extrusionWidthEnabled = ko.observable(false);
|
||||
self.renderer_extrusionWidth = ko.observable(2);
|
||||
self.renderer_showNext = ko.observable(false);
|
||||
@@ -65,6 +67,8 @@ $(function() {
|
||||
centerViewport: self.renderer_centerViewport(),
|
||||
showMoves: self.renderer_showMoves(),
|
||||
showRetracts: self.renderer_showRetracts(),
|
||||
showBoundingBox: self.renderer_showBoundingBox(),
|
||||
showFullSize: self.renderer_showFullSize(),
|
||||
extrusionWidth: self.renderer_extrusionWidthEnabled() ? self.renderer_extrusionWidth() : 1,
|
||||
showNextLayer: self.renderer_showNext(),
|
||||
showPreviousLayer: self.renderer_showPrevious(),
|
||||
@@ -77,7 +81,8 @@ $(function() {
|
||||
|
||||
var reader = {
|
||||
sortLayers: self.reader_sortLayers(),
|
||||
purgeEmptyLayers: self.reader_hideEmptyLayers()
|
||||
purgeEmptyLayers: self.reader_hideEmptyLayers(),
|
||||
ignoreOutsideBed: true
|
||||
};
|
||||
if (additionalReaderOptions) {
|
||||
_.extend(reader, additionalReaderOptions);
|
||||
@@ -95,6 +100,8 @@ $(function() {
|
||||
self.renderer_zoomOnModel.subscribe(self.synchronizeOptions);
|
||||
self.renderer_showMoves.subscribe(self.synchronizeOptions);
|
||||
self.renderer_showRetracts.subscribe(self.synchronizeOptions);
|
||||
self.renderer_showBoundingBox.subscribe(self.synchronizeOptions);
|
||||
self.renderer_showFullSize.subscribe(self.synchronizeOptions);
|
||||
self.renderer_extrusionWidthEnabled.subscribe(self.synchronizeOptions);
|
||||
self.renderer_extrusionWidth.subscribe(self.synchronizeOptions);
|
||||
self.renderer_showNext.subscribe(self.synchronizeOptions);
|
||||
@@ -102,8 +109,7 @@ $(function() {
|
||||
self.reader_sortLayers.subscribe(self.synchronizeOptions);
|
||||
self.reader_hideEmptyLayers.subscribe(self.synchronizeOptions);
|
||||
|
||||
// subscribe to relevant printer settings...
|
||||
self.settings.printerProfiles.currentProfileData.subscribe(function() {
|
||||
self._printerProfileUpdated = function() {
|
||||
if (!self.enabled) return;
|
||||
|
||||
var currentProfileData = self.settings.printerProfiles.currentProfileData();
|
||||
@@ -120,10 +126,13 @@ $(function() {
|
||||
}
|
||||
|
||||
var bedDimensions = self._retrieveBedDimensions(currentProfileData);
|
||||
if (toolOffsets) {
|
||||
if (bedDimensions) {
|
||||
GCODE.ui.updateOptions({
|
||||
renderer: {
|
||||
bed: bedDimensions
|
||||
},
|
||||
reader: {
|
||||
bed: bedDimensions
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -136,6 +145,27 @@ $(function() {
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// subscribe to relevant printer settings...
|
||||
self.settings.printerProfiles.currentProfileData.subscribe(function() {
|
||||
self._printerProfileUpdated();
|
||||
if (self.settings.printerProfiles.currentProfileData()) {
|
||||
if (self.settings.printerProfiles.currentProfileData().extruder) {
|
||||
self.settings.printerProfiles.currentProfileData().extruder.count.subscribe(self._printerProfileUpdated);
|
||||
self.settings.printerProfiles.currentProfileData().extruder.sharedNozzle.subscribe(self._printerProfileUpdated);
|
||||
self.settings.printerProfiles.currentProfileData().extruder.offsets.subscribe(self._printerProfileUpdated);
|
||||
}
|
||||
if (self.settings.printerProfiles.currentProfileData().volume) {
|
||||
self.settings.printerProfiles.currentProfileData().volume.width.subscribe(self._printerProfileUpdated);
|
||||
self.settings.printerProfiles.currentProfileData().volume.depth.subscribe(self._printerProfileUpdated);
|
||||
self.settings.printerProfiles.currentProfileData().volume.formFactor.subscribe(self._printerProfileUpdated);
|
||||
}
|
||||
if (self.settings.printerProfiles.currentProfileData().axes) {
|
||||
self.settings.printerProfiles.currentProfileData().axes.x.inverted.subscribe(self._printerProfileUpdated);
|
||||
self.settings.printerProfiles.currentProfileData().axes.y.inverted.subscribe(self._printerProfileUpdated);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
self.settings.feature_g90InfluencesExtruder.subscribe(function() {
|
||||
@@ -184,11 +214,13 @@ $(function() {
|
||||
currentProfileData = self.settings.printerProfiles.currentProfileData();
|
||||
}
|
||||
|
||||
if (currentProfileData && currentProfileData.extruder && currentProfileData.extruder.offsets() && !currentProfileData.extruder.sharedNozzle()) {
|
||||
if (currentProfileData && currentProfileData.extruder) {
|
||||
var offsets = [];
|
||||
_.each(currentProfileData.extruder.offsets(), function(offset) {
|
||||
offsets.push({x: offset[0], y: offset[1]})
|
||||
});
|
||||
if (currentProfileData.extruder.offsets() && !currentProfileData.extruder.sharedNozzle()) {
|
||||
_.each(currentProfileData.extruder.offsets(), function(offset) {
|
||||
offsets.push({x: offset[0], y: offset[1]})
|
||||
});
|
||||
}
|
||||
return offsets;
|
||||
} else {
|
||||
return undefined;
|
||||
@@ -247,7 +279,7 @@ $(function() {
|
||||
self._configureLayerSlider(layerSliderElement);
|
||||
self._configureLayerCommandSlider(commandSliderElement);
|
||||
|
||||
self.settings.requestData()
|
||||
self.settings.firstRequest
|
||||
.done(function() {
|
||||
var initResult = GCODE.ui.init({
|
||||
container: "#gcode_canvas",
|
||||
@@ -336,6 +368,7 @@ $(function() {
|
||||
result: response
|
||||
}
|
||||
};
|
||||
GCODE.renderer.clear();
|
||||
GCODE.gCodeReader.loadFile(par);
|
||||
|
||||
if (self.layerSlider != undefined) {
|
||||
@@ -406,7 +439,7 @@ $(function() {
|
||||
self.selectedFile.date(data.job.file.date);
|
||||
self.selectedFile.size(data.job.file.size);
|
||||
|
||||
if (data.job.file.size > CONFIG_GCODE_SIZE_THRESHOLD || ($.browser.mobile && data.job.file.size > CONFIG_GCODE_MOBILE_SIZE_THRESHOLD)) {
|
||||
if (data.job.file.size > CONFIG_GCODE_SIZE_THRESHOLD || (OctoPrint.coreui.browser.mobile && data.job.file.size > CONFIG_GCODE_MOBILE_SIZE_THRESHOLD)) {
|
||||
self.waitForApproval(true);
|
||||
self.loadedFilepath = undefined;
|
||||
self.loadedFileDate = undefined;
|
||||
|
||||
@@ -12,6 +12,7 @@ $(function() {
|
||||
self.isUser = ko.observable(false);
|
||||
|
||||
self.allViewModels = undefined;
|
||||
self.startupDeferred = $.Deferred();
|
||||
|
||||
self.currentUser = ko.observable(undefined);
|
||||
|
||||
@@ -36,28 +37,45 @@ $(function() {
|
||||
});
|
||||
|
||||
self.reloadUser = function() {
|
||||
if (self.currentUser() == undefined) {
|
||||
if (self.currentUser() === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
OctoPrint.users.get(self.currentUser().name)
|
||||
return OctoPrint.users.get(self.currentUser().name)
|
||||
.done(self.updateCurrentUserData);
|
||||
};
|
||||
|
||||
self.requestData = function() {
|
||||
OctoPrint.browser.passiveLogin()
|
||||
return OctoPrint.browser.passiveLogin()
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
if (response && response.name) {
|
||||
self.loggedIn(true);
|
||||
self.updateCurrentUserData(response);
|
||||
callViewModels(self.allViewModels, "onUserLoggedIn", [response]);
|
||||
var process = function() {
|
||||
var currentLoggedIn = self.loggedIn();
|
||||
if (response && response.name) {
|
||||
self.loggedIn(true);
|
||||
self.updateCurrentUserData(response);
|
||||
if (!currentLoggedIn) {
|
||||
callViewModels(self.allViewModels, "onUserLoggedIn", [response]);
|
||||
log.info("User " + response.name + " logged in")
|
||||
}
|
||||
} else {
|
||||
self.loggedIn(false);
|
||||
self.resetCurrentUserData();
|
||||
if (currentLoggedIn) {
|
||||
callViewModels(self.allViewModels, "onUserLoggedOut");
|
||||
log.info("User logged out");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (self.startupDeferred !== undefined) {
|
||||
// Make sure we only fire our "onUserLogged(In|Out)" message after the application
|
||||
// has started up.
|
||||
self.startupDeferred.done(process);
|
||||
} else {
|
||||
self.loggedIn(false);
|
||||
self.resetCurrentUserData();
|
||||
callViewModels(self.allViewModels, "onUserLoggedOut");
|
||||
process();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -101,7 +119,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.logout = function() {
|
||||
OctoPrint.browser.logout()
|
||||
return OctoPrint.browser.logout()
|
||||
.done(function(response) {
|
||||
new PNotify({title: gettext("Logout successful"), text: gettext("You are now logged out"), type: "success"});
|
||||
self.fromResponse(response);
|
||||
@@ -122,11 +140,8 @@ $(function() {
|
||||
|
||||
self.onAllBound = function(allViewModels) {
|
||||
self.allViewModels = allViewModels;
|
||||
};
|
||||
|
||||
self.onStartupComplete = self.onServerConnect = self.onServerReconnect = function() {
|
||||
if (self.allViewModels == undefined) return;
|
||||
self.requestData();
|
||||
self.startupDeferred.resolve();
|
||||
self.startupDeferred = undefined;
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
|
||||
Loaded 100 of 191 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user