Compare commits

...
Author SHA1 Message Date
Gina Häußge b94e513960 Merge remote-tracking branch 'origin/fix/betterPluginDependencyTracking' into fix/betterPluginDependencyTracking 2017-07-05 12:42:27 +02:00
Gina Häußge 875f69ea50 Fixed a unit test 2017-07-05 12:41:17 +02:00
Gina Häußge 5b7639590c Minor refactoring 2017-07-05 12:30:15 +02:00
Gina Häußge 2cd627ec6a Merge branch 'maintenance' into fix/betterPluginDependencyTracking
# Conflicts:
#	src/octoprint/plugin/__init__.py
#	src/octoprint/plugin/core.py
#	src/octoprint/plugins/pluginmanager/__init__.py
#	src/octoprint/plugins/softwareupdate/version_checks/github_release.py
2017-07-05 11:35:54 +02:00
Gina Häußge 3cdc59d7f1 Fix offset passing to analysis subprocess 2017-07-05 08:58:42 +02:00
Gina Häußge 5156cdbe68 Very minor refactoring & cleanup 2017-07-05 08:58:08 +02:00
Gina Häußge 0915c45f72 Merge branch 'maintenance' of github.com:foosel/OctoPrint into maintenance 2017-07-04 16:48:42 +02:00
Gina Häußge b2c1bb4b53 Option to automatically send temperature fine adjustments
As suggested by a loyal Patron ;)
2017-07-04 16:44:23 +02:00
Gina Häußge 8ad165c625 Fix blur of temp input focus on submit
Also separated "clear offset" button in offset editor from input
field, looks better this way.
2017-07-03 16:08:41 +02:00
Gina Häußge 841b86a017 Merge branch 'maintenance' into improve/temperatureInput 2017-07-03 16:07:19 +02:00
Mark Walker c0c249ece9 Typo: red->read 2017-07-01 10:37:51 -07:00
Gina Häußge 5fc194accd Docs: Added sequence diagrams for web interface lifecycle
For now only startup and reconnect to server.
2017-06-30 18:28:49 +02:00
Gina Häußge ed6c01c12a Remove current_user from template contexts
That should never have been enabled for our usage scenario in the
first place.
2017-06-30 14:37:37 +02:00
Gina Häußge e309646504 Prevent unnecessary settings fetch during startup
We fetch settings once explicitly after passive login but before
completed startup. Without this patch we fetched them again after
onUserLoggedIn got fired (if it got fired by the passive login)
during startup. That's not necessary because we did the passive login
before our initial settings fetch, so IF that already logged us in,
our settings fetch already was done with us logged in as well and
the onUserLoggedIn later only tells us what we already knew.
2017-06-30 14:36:18 +02:00
Gina Häußge 96ee80afd2 Only trigger onUserLogged(In|Out) if login state actually changed
This also includes triggering an initial onUserLoggedIn after
initialization if the user turned out to be logged in by passive login.
2017-06-30 14:34:05 +02:00
Gina Häußge 8aec836d22 Minor refactoring of the web interface startup (again)
We still had some concurrent requests triggered through onStartup that
managed to overtake the passive login (and hence nuke the session
data on the client). This should now really not be possible any longer.

Also created a sequence diagram of the new process and linked it from
a lengthy comment.
2017-06-30 11:59:52 +02:00
Gina Häußge 697df4f3ce And fixed connection accordion toggling again
#1001 said hi once more after fixing the onUserLogged(In|Out) events
not firing...
2017-06-30 09:48:57 +02:00
Gina Häußge ac3f4d598c Fixed onUserLoggedIn/Out not firing correctly on startup anymore
Introduced by b205e84d4b
2017-06-30 09:39:14 +02:00
Gina Häußge 836fbef6d8 Fixed an error in the temp graph when not connected 2017-06-30 09:24:07 +02:00
Gina Häußge ce4cf38547 Removed log prefixing again
It caused issues with our line number tracking in the browser
developer tools and I don't see any way to avoid this considering
that we can't adjust the arguments supplied to console.log without in
fact wrapping it :/
2017-06-29 17:37:01 +02:00
Gina Häußge 38a5da1c35 Fix connection accordion again
Slightly different order of things caused #1001 to resurface.
2017-06-29 16:51:04 +02:00
Gina Häußge b205e84d4b Refactored web startup to minimise risks of race conditions
Under specific circumstances it could happen that the passive login
response was overtaken by a response from an earlier still
unauthenticated request which would then effectively overwrite the
session cookie immediately and hence cause the browser to use its
login session against the server, but without displaying that to the
user. See #1881 for what is probably an issue caused by exactly this
kind of scenario.

Additionally a couple of requests needed to be done a second time
after login, just moments after having done them for an anonymous
user. See #1572 for a request to change this behaviour.

This patch changes the startup order of the web interface like this:

  1. connect to the websocket, postpone any events triggered by
     this (e.g. "fromHistoryData") until 3
  2. perform a passive login, postpone any events triggered by this
     (e.g. "onUserLoggedIn", "onUserLoggedOut") until 4
  3. trigger postponed events from 1
  4. trigger "onStartup" (triggers postponed events from 2)
  5. fetch settings
  6. bind view models etc

A connection close of the websocket will disable event processing on the
socket until it is marked as initialized again by the passive login
processing, which will also be triggered immediately on server connect.

That way under normal circumstances nothing should ever get triggered
in the registered view models that might generated requests to the
server API until a passive login has been done, a server session
initialized and if necessary a user properly authenticated.
2017-06-29 15:42:19 +02:00
Gina Häußge 7ab4d12548 Better error resilience against wrong user manager
Also improved get_class by using importlib instead of complicated
climbing through the whole module tree.
2017-06-29 15:07:17 +02:00
Gina Häußge f6c3e5991d PMGR: Detect if plugin needs printer reconnect 2017-06-28 10:30:35 +02:00
Gina Häußge 188b59a319 Added id to tabs content div
cc @Salandora
2017-06-27 15:47:39 +02:00
Gina Häußge b3594e367e Remove superfluous <br> tag from progress dialog output lines 2017-06-27 15:07:00 +02:00
Gina Häußge 12d40122d1 Use wrapt.ObjectProxy for SessionUser wrapper class
Our old manual wrapped didn't properly work in some aspects, this
version now should hopefully take care of most common proxy object
pitfalls.
2017-06-27 15:03:37 +02:00
Gina Häußge 2e11a7b860 Introduced pre-output css class for line based output pres
Easier to just put this on all output pre tags than defining
display:block on the contained spans for all individually.
2017-06-27 11:54:15 +02:00
Gina Häußge f20185db3a Better handling of timelapse deletion errors
Closes #1975
2017-06-27 11:32:42 +02:00
Gina Häußge 0db323d0c5 Removed unused import 2017-06-26 17:14:03 +02:00
Gina Häußge 639d8d4c5f Perform gcode analysis in subprocess 2017-06-26 16:19:18 +02:00
Gina Häußge 5e0b53b651 Better thread safety for SockJS
Heartbeat messages could still be sent out of turn, causing message
corruption or other weird things. This should hopefully fix this.
2017-06-23 17:56:17 +02:00
Gina Häußge 1ebfa4b1dd New event ToolChange and tool change GCODE scripts
(cherry picked from commit 5f79aa6)
2017-06-23 16:06:44 +02:00
Gina Häußge 35c45df86c Allow multi line commands in sending phase
(cherry picked from commit 1018946)
2017-06-23 14:55:34 +02:00
Gina Häußge a50e8bbbb5 Merge branch 'improve/temperatureGraphCrosshair' into maintenance 2017-06-22 17:33:09 +02:00
Gina Häußge 4665070601 last_temperatures -> last_temperature (for consistency) 2017-06-22 12:47:55 +02:00
Gina Häußge b34fc8e05e Merge branch 'improve/temperatureInScripts' into maintenance
# Conflicts:
#	src/octoprint/util/comm.py
2017-06-22 12:45:50 +02:00
Gina Häußge a3ece229f2 Fixed button types & update displayed current offset in dialog 2017-06-21 12:40:59 +02:00
Gina Häußge fc53febb87 WIP: Improved temperature controls 2017-06-20 16:53:41 +02:00
Gina Häußge dad956b5c9 Treat Anet A8 firmware as Repetier firmware
It appears to behave identically and probably is a renamed variant.
That would also explain #1737 and some observations reported in
#1946.
2017-06-19 16:33:33 +02:00
Gina Häußge 981110d4b2 Devel RC release channel should also track Maintenance RCs
That way people don't have to toggle between Maintenance and Devel RCs
just to get _all_ RCs.
2017-06-14 13:52:47 +02:00
Gina Häußge cbd94a9020 Ignore coordinates outside bed for zoom/centering in gcode viewer
They might be nozzle priming routines which are not actually part of
the model proper and hence it doesn't make sense trying to keep them
visible when zooming in on the model, or allowing them to offset the
model center.
2017-06-13 15:59:30 +02:00
Gina Häußge 77db00a2ea Extend coordinates used for min/max calculation
Both old and new position are relevant, we are extruding from one to
the other.
2017-06-13 15:58:12 +02:00
Gina Häußge 665078e1a4 Better backwards compatibility & disable crosshair on mobile 2017-06-07 14:24:24 +02:00
Gina Häußge cfae406a4c Fix issue with hover pos being undefined & resizing of plot 2017-06-07 10:59:22 +02:00
Gina Häußge 00c14e6936 First throw at tracking individual data points in the temp graph
See #1640
2017-06-07 10:10:31 +02:00
Gina Häußge 6a1b162e7b Support for temperature autoreporting instead of polling
Now also detects capabilities reported by (extended) M115 output and
if AUTOREPORT_TEMP is available enables it with the configured
autoreport interval and disables active polling.

Implements #1679
2017-06-06 18:46:23 +02:00
Gina Häußge a2fd39b3c4 Removed some unused variables from StateMonitor 2017-06-06 12:47:38 +02:00
Gina Häußge bda2fd94e3 More hardening against expected folders being files
See #1953
2017-06-06 10:01:21 +02:00
Gina Häußge 9e207ca8a1 SWU: Force exact version update for OctoPrint when tracking releases 2017-06-02 16:27:25 +02:00
Gina Häußge 5d321926bb Corewizard: Don't load js if not required 2017-06-02 16:06:11 +02:00
Gina Häußge 3d3e0212c6 Corewizard: Disable client if not required 2017-06-02 16:06:00 +02:00
Gina Häußge e3d44d7d06 Use client default if server default printer profile in unavailable 2017-06-02 16:05:12 +02:00
Gina Häußge d39c124f35 Allow empty & custom size in print job events
Thanks to @erikheidstra for the heads-up
2017-06-02 14:25:02 +02:00
Gina Häußge 8603ea4b6f Fix stupid typo causing printerProfileManager.set_default
Thanks for the heads-up @erikheidstra!
2017-06-02 14:20:06 +02:00
Gina Häußge a681048df6 Enable blockWhileDwelling for Malyan printers
See #1941 and #1762
2017-06-01 17:08:28 +02:00
Gina Häußge d689496802 Fix stupid typo causing unnecessary creation of default profile 2017-06-01 16:29:49 +02:00
Gina Häußge 5a23b46c11 Merge branch 'staging/maintenance' into maintenance 2017-06-01 16:11:50 +02:00
Gina Häußge 2b96e57923 maintenance & staging/maintenance are now 1.3.5(rc1) 2017-06-01 16:09:34 +02:00
Gina Häußge 885e88a5e0 Merge branch 'rc/maintenance' into staging/maintenance 2017-06-01 16:08:30 +02:00
Gina Häußge fe481e12b3 Prepare release of 1.3.4 (hotfix) 2017-06-01 12:22:23 +02:00
Gina Häußge cbdf85c27a Fix crash on startup thanks to invalid default profile & auto connect
See #1942

This does NOT fix the root cause of `_default.profile` becoming an
empty file (apparently during migration from config.yaml?), however
since this particular situation was impossible to reproduce so far this
workaround for the consequences will have to suffice for now since we
want a hotfix as fast as possible for 1.3.3.
2017-06-01 12:10:12 +02:00
Gina Häußge 674637f6b2 Merge branch 'staging/maintenance' into maintenance 2017-05-31 16:58:32 +02:00
Gina Häußge 9056f5d610 maintenance & staging/maintenance are now 1.3.4(rc1) 2017-05-31 16:57:10 +02:00
Gina Häußge b55c4ef5ca Preparing release of 1.3.3 2017-05-31 15:49:01 +02:00
Gina Häußge b9747d0f0e Fix typo: TRANFERING_FILE
(cherry picked from commit c4fcc59efd)
2017-05-31 11:24:44 +02:00
Gina Häußge 0feae3ba18 Centralized browser detection 2017-05-31 10:45:19 +02:00
Gina Häußge 1cc3ddb03c Add levels & color to browser console log 2017-05-30 17:46:03 +02:00
Gina Häußge 33cafbbd8a Make stream timeout adjustable
As suggested by @ntoff in #1937
2017-05-30 17:26:30 +02:00
Gina Häußge d274a9c73d Fixed a couple of FontAwesome issues
* fa-circle-blank does not exist, replaced with fa-circle-o (see also
    report in #1928)
  * fa-trash-o instead of fa-trash (same look and feel)
  * fa-check instead of fa-check-circle (same look and feel)
  * fixed toggleContent binding to also be able to toggle fa icons
  * fix deletion spinner in file list (was still using old icon-
    classes which of course weren't there anymore and hence not
    toggleable)
  * icons-ul => fa-ul
  * remove superfluous fa class from some places

Follow-up to #1915.
2017-05-29 13:42:11 +02:00
Gina Häußge c3619a3795 No scary message on autodetect fail 2017-05-24 18:04:11 +02:00
Gina Häußge dffb33727d More sensible sorting of baudrates for auto detect
115200 is the most likely baudrate candidate for printers, followed
by 250000. Any additional baudrates that were configured are even more
likely.
2017-05-24 17:56:01 +02:00
Gina Häußge 78724163b1 No need for programmer mode for detecting one port 2017-05-24 17:54:30 +02:00
Gina Häußge b6a09abb83 Fix an issue causing non-gcode commands not to be sent
Introduced by multi-command returns from comm handlers
2017-05-24 17:51:01 +02:00
Gina Häußge 77b6d83e0b Set X-Robots-Tag and remove Server header in responses
Also set robots meta tag in index.jinja2
2017-05-24 16:53:54 +02:00
Gina Häußge 7c6b85a0ad Merge branch 'staging/maintenance' into maintenance 2017-05-24 14:51:24 +02:00
Gina Häußge df038e6a4d staging/maintenance is now 1.3.3rc4.dev 2017-05-24 14:50:18 +02:00
Gina Häußge ce1541e956 Preparing release of 1.3.3rc3 2017-05-24 13:26:06 +02:00
Gina Häußge bd1d0e6073 Merge branch 'rc/maintenance' into staging/maintenance 2017-05-24 12:33:40 +02:00
Gina Häußge ff89cdf6d0 Fix versioneer lookup entry for 1.3.3rc3 staging branch 2017-05-24 12:28:09 +02:00
Gina Häußge 76f58e05ec Better fix for #1821
Instead of disabling capturing of postroll by default (which we actually
don't want and doing so was a mistake thanks to misremembering the
meaning of the variable in question), we now properly reset the
default value for that check box (which wasn't properly set only due to
a very stupid typo).
2017-05-24 12:26:14 +02:00
Gina Häußge 2a600d7d00 Fix consecutive timed timelapses without postroll capture
Due to the timer never properly resetting to None only one timelapse
was ever done.

Introduced in 7e2382fed4, covered until
315a80a7a7.

Closes #1934
2017-05-24 11:57:02 +02:00
Gina Häußge 4a84fa95e4 [docs] Fix another typo in the SettingsPlugin docs 2017-05-23 10:15:04 +02:00
Gina Häußge 557c761e80 [docs] Fix a typo in the SettingsPlugin docs 2017-05-23 10:13:04 +02:00
Gina Häußge 10cb60acca [docs] Warn about the need to protect sensitive settings in plugins 2017-05-22 19:24:20 +02:00
Gina Häußge 5e55d637af Don't escape \t, \r or \n in terminal output 2017-05-22 14:06:12 +02:00
Gina Häußge 8942d7d50d Slight rewording for the webcam error message
See #1925
2017-05-19 18:25:40 +02:00
Gina Häußge 0ad09e422d Add stream URL to webcam error message for logged in users 2017-05-19 17:59:54 +02:00
Gina Häußge 0657160389 Different "webcam error" text for non-admins 2017-05-19 17:59:12 +02:00
Gina Häußge cfde6342a8 Update SockJS to 1.1.2
Also include source maps. While those are stripped when bundling, for
alternative UIs including sockjs they still might make sense.
2017-05-19 12:29:40 +02:00
Gina Häußge 832c27ed18 Filter source maps from bundled assets
At least for now. Might be re-evaluated in the future. URL rewrite
filter for such a case already in place.
2017-05-19 12:28:20 +02:00
Gina Häußge 59d78ba893 Merge branch 'maintenance' of github.com:foosel/OctoPrint into maintenance 2017-05-18 11:20:54 +02:00
Gina Häußge 7770ee3d08 static/assets/vendor => static/vendor
Our static folder is basically an assets folder (it just is named differently).
So let's get rid of the redundant directory level.
2017-05-18 11:12:33 +02:00
Gina Häußge 2d9ad41e49 Moved FontAwesome css into vendor folder & use cssrewrite filter for webassets
That fixes up the relative URLs to the font files and should make updates down the line
a thing of a quick copy and paste (plus allow some more sophisticated dependency
management down the road as well).

Also renamed fonts folder for FontAwesome 3.2.1 from font to fonts, for more
consistency.
2017-05-18 11:10:37 +02:00
Gina Häußge 821156c9d6 Py3: basestring => past.builtins.basestring 2017-05-17 19:01:42 +02:00
Gina Häußge 9e5982be29 Attach on_sent callback to last command only 2017-05-17 18:51:34 +02:00
Gina Häußge 39c87d19b7 Fixed a left-over typo. 2017-05-17 17:47:58 +02:00
Gina Häußge d029abc8f3 Updated docs with an example of multi command expansion 2017-05-17 17:47:58 +02:00
Gina Häußge 7b5848b9c3 Extracted handler result normalization and added tests for it
Caught some more bugs while doing that.
2017-05-17 17:47:57 +02:00
Gina Häußge 53bfbf5acf Refactored things a bit to remove a bit of repetition 2017-05-17 17:47:21 +02:00
Goswin von Brederlow 917c9e54ba Allow octoprint.comm.protocol.gcode.queuing hook to return a list of commands 2017-05-17 17:46:58 +02:00
Davide Depau d8d9c7fe64 Merge branch 'maintenance' into fa-update 2017-05-17 17:46:01 +02:00
Davide Depau 6c0f2de780 upgrade FontAwesome CSS+fonts to 4.7.0, keeping 3.2.1 as fallback [2/2] 2017-05-17 17:35:49 +02:00
Davide Depau 700975d670 upgrade templates to use FontAwesome 4.7.0 classes [1/2] 2017-05-17 17:35:27 +02:00
Gina Häußge 9fac314d71 SWU: restart asynchronously instead of synchronously
Otherwise we will block ourselves, waiting for the restart command to
complete which it only can when we are no longer there.

Should reduce restart times on update significantly.

Downside is that we no longer can wait for the return code of the
call. However, that should be caught by our UI handler timing out for
the restart and showing an error prompting the user to restart
manually.
2017-05-17 13:44:11 +02:00
Gina Häußge 9dfee34f01 Fix various popup buttons allowing multiple clicks
As suggested by @ntoff in #1914
2017-05-17 13:44:08 +02:00
Gina Häußge dc8473bc4d Add check for valid job file type to job validation 2017-05-17 13:44:04 +02:00
Ken c1c75f032d Fixed webcam not loading bug if first/initial tab is "Control"
(cherry picked from commit d66a4f3)
2017-05-17 13:44:01 +02:00
Gina Häußge 9ad180c02a Disable "Upload to SD" ui elements while printing
As suggested by @ntoff in #1914
2017-05-17 13:43:57 +02:00
Gina Häußge 7795320fc8 Allow timelapse config through UI when not connected to printer
That restriction didn't really make sense.

As mentioned in #1918
2017-05-17 13:43:53 +02:00
Gina Häußge a54c8fbeb7 maintenance branch is now 1.3.4.dev 2017-05-17 13:43:49 +02:00
Gina Häußge 337957198b Introducing staging/* branches for rc preparation
That way we can switch maintenance over to follow-up stable release
preparation earlier and don't have to hold back commits.
2017-05-17 13:33:28 +02:00
Gina Häußge 2bae87b85a Preparing release of 1.3.3rc2 2017-05-17 10:59:48 +02:00
Gina Häußge 51959319eb PGMR: Fix call to non existing onAlways
Closes #1919
2017-05-16 16:00:40 +02:00
Gina Häußge 6d73e6557b Timelapse: Disable "save as default" along other controls
Fixes #1918
2017-05-15 13:03:40 +02:00
Gina Häußge 4c65313c7f Fix a regression causing job data to be reset on completion of a print
Fixes #1917
2017-05-15 12:40:05 +02:00
Gina Häußge 41cf85d9db Some rephrasing 2017-05-12 14:58:30 +02:00
Gina Häußge 3fbd477d15 Preparing release of 1.3.3rc1 2017-05-11 15:25:43 +02:00
Gina Häußge 2c73dd36c5 Final fixes before 1.3.3rc1 2017-05-11 15:23:45 +02:00
Gina Häußge c91fe0c4fc Further decouple some plugin fetch tasks from initial startup thread 2017-05-11 15:23:41 +02:00
Gina Häußge 3bfc4725d2 SWU: Added cache timestamp to UI
Implements #1521
2017-05-11 12:45:02 +02:00
Gina Häußge b6fbe6fafd Added docs for bitbucket_commit check type
Update to #1898
2017-05-11 12:12:22 +02:00
Gina Häußge 263c297bed Made last/pause/cancel temperature available in GCODE scripts
Implements #1910
2017-05-11 10:00:54 +02:00
Gina Häußge dba95ee94f Handle G90/G91 and M82/M83 distinct by default
By default G90/G91 define relativeMode, M82/M83 define relativeE. The
extruder coordinate will be viewed as relative when either
relativeMode or relativeE are set. This mirrors the implementation in
Marlin (current and legacy forks) as well as Repetier.

SmoothieWare's implementation resets the relative mode of the
extruder on a G90/G91. To still accomodate this different
implementation a new settings has been added under Settings >
Feature: "G90/G91 overrides relative extruder mode". Checking this
switches to the alternative interpretation for future gcode analysis
and visualization.

The only difference between the two of them is that the following
segment of GCODE:

    M83
    G90

will have the extruder still set to relative on Marlin and
Repetier but set to absolute on Smoothieware.

Please note that the setting in all likelihood will be moved to
the printer profile in the future, since it makes more sense to have
it on a per printer basis. It's not part of the set of features
available for auto detection since it's required for GCODE analysis
and hence needs to be known even outside of a connection to the
printer.

Implements #1818
2017-05-10 16:43:20 +02:00
Gina Häußge f0b63a8e7f Set lines in log outputs to "display: block"
Taken from reverted commits 6465175e09
and 0f6edabea3.
2017-05-10 09:58:02 +02:00
Gina Häußge e166765f7f Revert "Also use fastForEach in working dialogs of PMGR & software update"
This reverts commit 0f6edabea3.
2017-05-10 09:25:53 +02:00
Gina Häußge 15e8bbe147 Revert "Improve terminal performance by adding FastForEach"
This reverts commit 6465175e09.

# Conflicts:
#	src/octoprint/static/css/octoprint.css
#	src/octoprint/static/less/octoprint.less
2017-05-10 09:25:18 +02:00
Gina Häußge 853bb2fc16 Have G92 set pos directly, use offset only for tool offsets
See #1906 for related discussion
2017-05-09 17:17:08 +02:00
Gina Häußge ccc3c4ef32 Detect invalid settings data to persist (not a dict), send 400 2017-05-09 14:36:45 +02:00
Gina Häußge 72898360f3 Get rid of ridiculous float precision in temperature commands
"M104 S200.00000000" is completely unnecessary when "M104 S200" works
just fine.
2017-05-09 09:38:10 +02:00
Gina Häußge 2caa10f15e Don't send T with temperature set commands for shared nozzles
Fixes #1907
2017-05-09 09:29:52 +02:00
Gina Häußge 399ec5a909 Allow configuring the webcam stream's aspect ratio
Options are 16:9 and 4:3, 16:9 is the default.
2017-05-08 17:35:51 +02:00
Gina Häußge c844217f82 Placeholder for webcam image to avoid moving controls on load
An aspect ratio of 16:9 is assumed, with other ratios showing black
letterbox borders as required.

During loading a text "Webcam loading..." is displayed in the webcam
space. On loading error, the (broken) image is hidden and an error
text is displayed instead.

Solves #478
2017-05-08 17:04:03 +02:00
Gina Häußge f32d7c434d Docs: Added note that coordinates in script context might be None
Wasn't made clear before.
2017-05-03 20:18:11 +02:00
Gina Häußge 844494a9d5 Only prevent command processing if streaming AND printing
Otherwise we might run into a rare race condition where the M110 sent
on start of a SD card upload gets prepared for sending after the
source file is already opened. That would then lead to the M110 not
getting processed anymore by OctoPrint and hence the line number
counter not resetting accordingly, leading to one line number
mismatch after the next from the firmware.

Testing if our "isPrinting" flag is ALSO set to true here ensures
that we'll only stop processing commands internally once the state
has actually switched to printing, which only happens after the
firmware responds to the M28 sent after the M110.

Fixes #1882 and probably also the issue encountered by @amd989 in
#1762 (which looks like exactly the same problem)
2017-05-03 18:55:00 +02:00
Gina Häußge f1254622c5 Docs: Link to Jinja 2.8.1 documentation mirror at jinja.octoprint.org
The official docs are only 2.9+, that doesn't help us as long as we are
stuck with 2.8.

Fixes #1900
2017-05-03 11:56:25 +02:00
Gina Häußge 060aa1274a Some minor refactoring of #1898 for better maintainability 2017-05-02 17:45:28 +02:00
Andy Werner fe0aa0301f Software update plugin: added check_type bitbucket_commit
(cherry picked from commit ee75ddc)
2017-05-02 17:25:01 +02:00
Gina Häußge cda48f3b71 Fix some potential encoding issues
Might be a fix for #1884, can't be confirmed though, ticket is
incomplete.
2017-05-02 14:59:05 +02:00
Gina Häußge c69ef1598a Don't allow multiple parallel webcam tests
Disable button when a test is already active. Also have spinner
defined centrally and only made visible on active test.

Should hopefully give better feedback to impatient users ;)

Solves #1897
2017-05-02 13:39:38 +02:00
Gina Häußge 0161d915d6 Some refactoring in CuraViewModel
* Use click data-bind for submit button instead of manual click
    binding
  * Keep metadata synchronized (otherwise changing identifier, name,
    description, overwrite or default flag after adding a file does
    absolutely nothing)
  * Disable submit button and fields when no file is selected.
  * Disable submit button (and show spinned) when request is in
    progress.

Related to #1893
2017-05-02 12:57:32 +02:00
Eyal Soha f5fad5186e Clear upload data when Aborting cura profile upload modal.
This fixes #1893.

Also, only bind click to the "Confirm" button once instead of binding
and unbinding it for each file.  Binding it just once seems cleaner.

(cherry picked from commit 83d1921)
2017-05-02 10:04:54 +02:00
Gina Häußge 2817979c3d CSS updated 2017-05-02 09:57:26 +02:00
Gina Häußge cc44c1a981 Make sure to properly handle unicode passwords
Fix & test for #1891
2017-05-02 09:35:02 +02:00
Gina Häußge dda3a303d2 Recover terminal functionality on processing speed increase
If double the speed needed for output during print/fancy terminal
functionality is detected, re-enable that after a timeout of 5s.
Decrease of speed cancels the timeout again. That should prevent wild
toggling.

Should solve #1862
2017-04-20 12:15:40 +02:00
Gina Häußge b79606da70 Never auto-complete GCODE to send
Solves #1875
2017-04-19 18:03:44 +02:00
Gina Häußge fb9131f67a Some de-duplication 2017-04-19 11:34:34 +02:00
Eyal Soha 358a252736 Fix dragndrop upload
See #1867. Fixes #202.

(cherry picked from commit d658c64)
2017-04-19 11:34:11 +02:00
Gina Häußge fd7c81c7fb Link to FAQ entry about SerialExceptions to log output
As suggested in #1876
2017-04-18 13:03:17 +02:00
Gina Häußge a09b54d374 Have tag based branches not report post versions unless dirty
That will allow us to make changes to e.g. github related metadata files
stored in the repository without OctoPrint reporting a non tag version.
2017-04-13 11:49:58 +02:00
Gina Häußge 2a7cebfe55 Keep "Load and print" button enabled when file is selected
Some users get confused by having to use the blue "Print" button in
the state panel for consecutive prints of the same model, let's solve
this once and for all.
2017-04-12 19:04:45 +02:00
Gina Häußge 0f6edabea3 Also use fastForEach in working dialogs of PMGR & software update 2017-04-12 18:54:08 +02:00
Gina Häußge 45231ea7f8 Merge branch 'improve/terminalFastForEach' into maintenance 2017-04-12 18:21:52 +02:00
Gina Häußge c00b46ef5c Support timeout parameter in client and CLI 2017-04-12 15:40:54 +02:00
Gina Häußge 251a1ea4b5 "a couple" => "a few"/"some"
Because apparently I was using it wrong, at least for some parts of the
world :)
2017-04-12 14:54:32 +02:00
Gina Häußge bba9d6cc18 Use proper timeouts for requests + better error handling
Default behaviour apparently is blocking, we never want that!

Also make error responses actually raise an exception.
2017-04-12 13:50:52 +02:00
Gina Häußge 9bcce4e56a docs: plugin tutorial requires 2017-04-12 13:00:56 +02:00
BillyBlaze 6465175e09 Improve terminal performance by adding FastForEach
Move the AutoScroll function to an animation frame to prevent layout thrashing and to keep it in sync with fastForEach
Remove the <br> tag from the terminal and use display: block; on span tags to prevent increasing DOM nodes and faster processing of the terminal
2017-04-12 08:17:34 +00:00
Gina Häußge fe585e7115 Do not repeatedly apply any set offsets in the gcode interpreter
They would accumulate and cause wrong calculations

Solves #1863
2017-04-12 09:38:53 +02:00
Gina Häußge b84432c8a5 Merge branch 'patch-1' of http://github.com/ParkerK/OctoPrint into maintenance 2017-04-11 09:36:13 +02:00
Parker K c6623c8883 added missing period and space so works 2017-04-10 21:35:46 -04:00
Gina Häußge ef01560199 If file hash doesn't match on adding a file, kill all metadata 2017-04-10 17:31:00 +02:00
Gina Häußge 1666a1f607 Removed "minify" option for assets and some redundancy 2017-04-10 16:28:04 +02:00
Gina Häußge 4109b2f6c2 Announcements: Unit tests for the converters 2017-04-10 13:57:21 +02:00
Gina Häußge 9f32e91e05 Turned lazyload into jquery plugin, used for announcements
On call of the lazyload plugin, all matched img elements will be
checked if they have a data-src attribute. If so, their src attribute
will be replaced with the contents of the data-src attribute
(effectively loading the image) and the data-src attribute will be
removed (so that multiple calls don't call multiple processing).
2017-04-10 11:54:03 +02:00
Gina Häußge 7c8f148fa8 Announcements: Don't load imgs until reader is opened
Closes #1858
2017-04-10 11:21:18 +02:00
Gina Häußge d1c6381792 Intermediary page: Offer "reload now" once server is up but not cached 2017-04-10 10:45:16 +02:00
Gina Häußge a477268beb More logging for preemptive cache 2017-04-10 10:43:46 +02:00
Gina Häußge 346f818707 PGMR: More general flexibility for os compat check
* Don't restrict the list of compatibility values to check against
    to only those we have mapped, also support unmapped more exotic
    ones.

  * Allow 1:1 check against sys.platform values (with startswith).
    Combined with the above that allows very granular compatibility
    modelling ("freebsd11", "freebsd12") if required.

  * Instead of only whitelisting ("linux", "freebsd") now also black
    listing is possible ("!windows").

    A detected os must match all provided whitelist elements (if the
    whitelist is empty that is considered always the case) and none of
    the backlist elements (if the blacklist is empty that is also
    considered always the case).

See the included unit tests for examples of how this works.
2017-04-07 09:18:37 +02:00
Gina Häußge 956d9581c5 PMGR: Add freebsd os compatibility flag 2017-04-07 09:16:26 +02:00
Gina Häußge 7828ab0bf9 Fix tests for server.util.*
Weren't properly included in test suite, and those for the flask
utility also had some errors due to buggy test implementation.
2017-04-07 09:15:08 +02:00
Gina Häußge 41e9d96815 Use pip instead of python setup.py develop in CLI for plugin install
Apparently python setup.py develop tries to re-install all scripts
provided by plugins (maybe only under Windows?). Since that includes
OctoPrint's own executable, things will explode with an access denied
error there. Switching over to pip install -e . fixes that, and also
is more conform with the install approach the plugin will take in
production anyhow.
2017-04-07 09:15:05 +02:00
Gina Häußge 09d1025dfc Use blacklisting instead of whitelisting for checking daemon support
Just to be on the safe side... This is _exactly_ the same behaviour
as it was under 1.2.x again.
2017-04-06 10:02:48 +02:00
Gina Häußge 163fd83bf5 PGMR: Detect necessity to reinstall
So far using the "... from URL" or "... from an uploaded archive"
mechanism for installing a plugin would fail without further
information if the plugin to be installed was already installed.

The plugin manager will now detect this situation by parsing the
corresponding message from the pip output and trigger a reinstall
instantly.

A message about this will be logged to octoprint.log and the install
output.

Additionally the error handling for installation errors has been
slightly improved (install output no longer says "Done!" but "Error!"
with the reason as provided by the server) and the "could not install
plugin from URL unknown" issue should also be solved.
2017-04-04 15:18:37 +02:00
Gina Häußge e109bf0ca6 Fix: Make Printer.is_ready behave as advertised 2017-04-03 18:48:45 +02:00
Gina Häußge 4d324c5239 Fix unit tests 2017-04-03 18:47:27 +02:00
Gina Häußge 8cbf5a74b3 Fix analysis backlog calculation for specific path on storage
We need to convert the provided path into a local storage one first,
otherwise the following scandir calls will fall on their faces.
2017-04-03 17:18:26 +02:00
Gina Häußge b24851ca05 New events: FileAdded, FileRemoved, FolderAdded, FolderRemoved
Closes #1092
2017-04-03 15:50:23 +02:00
Gina Häußge 1219939189 Add missing dependency
Closes #1850
2017-04-03 09:43:07 +02:00
Gina Häußge d72c7c144e Make octoprint_client support multiple instances
Adjusted cli implementation accordingly
2017-03-31 18:48:13 +02:00
Gina Häußge 5c0a564592 PMGR: Better handling of plugins disabled on the repo
Switched button from "Incompatible" to "Disabled", added link to
plugin page on repo with the prominent alert box explaining the
reason for disabling.
2017-03-31 17:55:18 +02:00
Gina Häußge d27dd26a61 PMGR: Also allow filtering notices against affected OctoPrint versions 2017-03-31 17:32:41 +02:00
Gina Häußge 52633d0433 PMGR: Support for plugin notices
Evaluates json data file as e.g. published on
plugins.octoprint.org/notices.json and displays notices for plugins
installed and matching (optional) version lists.
2017-03-31 16:52:48 +02:00
Gina Häußge ea3b7ab1da Update pnotify to version 2.1.0, incl. all modules 2017-03-31 15:22:59 +02:00
Gina Häußge a01b9fe8d4 Disable reload button and show spinner on click 2017-03-30 15:50:32 +02:00
Gina Häußge f1cf482919 Adjusted metadata of bundled plugins 2017-03-30 14:09:12 +02:00
Gina Häußge 18e14aa412 Support "disabling unrecommended" for bundled plugins
* Extended plugin metadata by new property, only evaluated for bundled
    plugins.
  * Adjusted plugin manager to evaluate new metadata and add
    confirmation dialog with details when attempting to disable such
    a plugin.
2017-03-30 14:08:47 +02:00
Gina Häußge c3ad1d3691 Announcements: Various improvements
* Added combined OctoBlog feed, replacing news + spotlight (+
    octoprintonair), added corresponding config migration
  * Subscribe to all registered feeds by default
  * Added config button to announcement reader
  * Added note how to edit announcement subscriptions to notifications
  * Auto-hide announcements on logout
  * Order channels server-side based on new order config setting
2017-03-30 12:40:57 +02:00
Gina Häußge 35d9775e51 Limit verbosity of failed system event handlers 2017-03-30 11:37:46 +02:00
Gina Häußge fda67f48ff Allow users to ignore update notification & setting to disable outright
Old default behaviour of showing logged in users the update
notification stays default, but can now be disabled via the software
update plugin settings.

Additionally added the ignore button to the notification for users as
well (and made ignore entry in local storage user specific to still
show notification to other logged in users), plus a small hint that
in order to apply updates an admin is needed. Additionally now hiding
the notification on log out.

Closes #1739
2017-03-29 14:47:49 +02:00
Gina Häußge e97c9f954d Early validation of file to select for printing & better documentation
See #1843
2017-03-29 11:53:16 +02:00
Gina Häußge 01ad9b8b14 Fix order of PrintCancelled and PrintFailed event
Closes #1836
2017-03-27 17:42:07 +02:00
Gina Häußge 2d105517c9 Synchronized access to selected file in printer implementation
Should solve #1837
2017-03-27 16:48:43 +02:00
Gina Häußge 41d8b3476c Added safe mode section to ticket template 2017-03-27 15:25:45 +02:00
Gina Häußge 97b2a02926 Fix message catchall * not working in socket clientlib 2017-03-24 16:56:11 +01:00
Gina Häußge 517fd6f3ab Auto detect Malyan firmware and configure comm layer
Should close #1762
2017-03-24 16:55:54 +01:00
Gina Häußge fb2f9ba593 Added note on lack of language pack repo & to use the wiki 2017-03-22 16:50:33 +01:00
Gina Häußge 3ec2d7bd14 Delete confirmation & bulk delete for timelapses
Also introduced a new helper, a progress modal that can be used for
providing feedback about things such as bulk delete operations in the
background.

See #748 and discussion in #1807
2017-03-22 16:28:33 +01:00
Gina Häußge 675a54aa05 Fix filter parameter and force parameter on /api/files/<origin> 2017-03-21 13:15:43 +01:00
Gina Häußge 880b99faaf Better feedback of current vs selected profile & available actions
Also part of fixing core reason of #1734
2017-03-21 10:43:45 +01:00
Gina Häußge 5535a9aeb0 Handle default printer profile like all other profiles
It now resides in a file on disk and can be deleted. If the profile
configured as default is not available (e.g. due to having been
manually deleted, or on first start), the default profile as defined
in the profile manager will be written as _default and that will be
used/set as default.

On first start after this change gets applied, OctoPrint will migrate
the old "default overlay" residing in config.yaml to a file on disk
and delete the old entries in config.yaml.

Solves core reason of #1734
2017-03-20 18:33:13 +01:00
Gina Häußge 3bc77ffe3d Always merge with basic default profile 2017-03-20 13:18:39 +01:00
Gina Häußge 896aad3ab0 Migrate printer profile before saving as well
We want to make sure that externally added profiles are up to current
format.
2017-03-20 13:18:39 +01:00
Claudiu Ceia 01e970553f Fix typo: Celcius to Celsius (#1826) 2017-03-20 10:26:53 +01:00
Gina Häußge 6613d580f2 Support daemon mode on linux AND freebsd 2017-03-19 10:53:44 +01:00
Gina Häußge ac6900ffb6 REALLY remove "Hide empty folders" m)
See #1671
2017-03-16 16:33:58 +01:00
Gina Häußge 6465b58384 maintenance branch is now 1.3.3.dev 2017-03-16 15:18:46 +01:00
Gina Häußge fa73fd3c14 Merge branch 'master' into maintenance
# Conflicts:
#	src/octoprint/server/api/settings.py
#	src/octoprint/settings.py
2017-03-16 15:16:52 +01:00
Gina Häußge 0a69dbeddb Preparing release of 1.3.2 2017-03-16 13:08:31 +01:00
Gina Häußge 13714dc8d9 Enable save button when marking "save as default" 2017-03-16 11:25:53 +01:00
Gina Häußge 5a6edefec1 Slight rewording 2017-03-16 11:25:48 +01:00
ntoff 87be930a68 timelapse tab unsaved warning and rearrange interval input box
Addition of a notification under the save button when there are unsaved
changes, and a notice under the save as default checkbox when unticked,
that changes are only temporary.

Also move the "interval" box up the top to position it underneath the
timelapse type dropdown list, and change the text to be a bit more
descriptive.

(cherry picked from commit 381a016)
2017-03-15 12:47:47 +01:00
Gina Häußge 627d11fa51 Remove some redundance & return 400 on all wrong option values 2017-03-14 17:25:39 +01:00
Gina Häußge 315a80a7a7 Fix wrong default value for postroll
Closes #1821
2017-03-14 17:25:13 +01:00
Gina Häußge 1b91790f5f Merge branch 'fix/fileAccessRaceCondition' into maintenance 2017-03-13 17:14:14 +01:00
Gina Häußge 3e5923b21e Consolidate API Key handling
System wide API key now offers a generate button like the user
API keys. Setting the API key directly to a value via the settings API
endpoint is now no longer possible, which should prevent setting it
accidentally thanks to the browser prefilling things where it shouldn't.

No delete button is offered for the system wide API key since it will
get automatically regenerated on server start if not set, so
regeneration is the only functionality here that makes sense.

If no API key is set in the user settings, the "delete" button is now
disabled. If a key is already set and a new one is to be generated, a
confirmation dialog makes sure this is really what the user wants. Same
for deleting an existing API key.

Both the system wide API key and the user specific API keys will now
only display a QRCode if there's actually a value for the key.
2017-03-13 17:09:56 +01:00
Gina Häußge c1fdbaa1e7 Force refresh of settings on login/logout
Our access rights might have changed, so let's make sure our
view of the settings is up to date.
2017-03-13 17:07:27 +01:00
Gina Häußge 6d1e28ae9c We still need _read_lines after all in the streamed file info 2017-01-18 13:04:01 +01:00
Gina Häußge 1e482369b8 Further synchronization in comm layer
Prevent concurrent sending of commands from the monitor thread for
incoming ok's while processing the start, pause, resume or cancel
of a print job.
2017-01-18 12:58:38 +01:00
Gina Häußge a6c4f8ba3b Fix potential race condition on print start
When the sending of the first line of a file to print is still taking
place while an "ok" from the firmware comes in, it's possible
that two threads will try to access the file handle in parallel. That
can lead to trouble within Python's codecs module.

Synchronizing all access to the handle should do the trick.
2017-01-17 17:46:20 +01:00
Gina Häußge 2aa74866ac Match OctoPrint version against required one from plugin setup.py requires 2016-01-20 17:42:20 +01:00
Gina Häußge 3764eec9eb Allow defining required OctoPrint versions in setup_requires 2016-01-20 17:18:45 +01:00
Gina Häußge 083601c978 Extracted version matching against specs into utility methods
Adjusted plugin manager and software update plugin to utilize new methods in
octoprint.util.version
2016-01-20 16:59:46 +01:00
209 changed files with 21225 additions and 5929 deletions

No files matched your search

+44 -26
View File
@@ -1,31 +1,34 @@
READ THE FOLLOWING FIRST:
If not already done, please read the "guidelines for contributing"
that are linked ^-- just up there in the big yellow box. Also read
the FAQ: https://github.com/foosel/OctoPrint/wiki/FAQ.
aka the Contribution Guidelines that are linked ^-- just up there
in the big yellow box.
Also read the FAQ: https://github.com/foosel/OctoPrint/wiki/FAQ.
This is a bug and feature tracker, please only use it to report bugs
or request features within OctoPrint (not OctoPi, not any OctoPrint
plugins and not unofficial OctoPrint versions).
Do not seek support here ("I need help with ..."), that belongs on
the mailing list or the G+ community (both linked in the "guidelines
for contributing" linked above, read it!), NOT here.
Do not seek support here ("I need help with ...", "I have a
question ..."), that belongs on the mailing list or the G+ community
(both linked in the "guidelines for contributing" linked above, read
them!), NOT here.
Mark requests with a "[Request]" prefix in the title please. Fully fill
out the bug reporting template for bug reports (if you don't know where
to find some information - it's all described in the contribution
guidelines linked up there in the big yellow box).
Mark requests with a "[Request]" prefix in the title please. For bug
reports fully fill out the bug reporting template (if you don't know
where to find some information - it's all described in the Contribution
Guidelines linked up there in the big yellow box).
When reporting a bug do NOT delete any lines from the template but
When reporting a bug do NOT delete ANY lines from the template but
those enclosed in [ and ] - and those please DO delete, they are
only provided for your information and removing them makes your
ticket more readable :)
Make sure any bug you want to repor tis still present with the CURRENT
Make sure any bug you want to report is still present with the CURRENT
OctoPrint version and that it does not vanish when you start OctoPrint
in safe mode - how to do that is also explained in the contribution
guidelines linked up there in the big yellow box.
in safe mode - how to do that is also explained in the Contribution
Guidelines linked up there in the big yellow box.
Thank you!
@@ -37,15 +40,27 @@ by heart ;))
#### What were you doing?
[Please describe the steps to reproduce your issue. Be as specific as
possible here. The maintainers will need to reproduce your issue in
order to fix it and that is not possible if they don't know what you
did to get it to happen in the first place.
[Please be as specific as possible here. The maintainers will need to
reproduce your issue in order to fix it and that is not possible if they
don't know what you did to get it to happen in the first place.
Ideally provide exact steps to follow in order to reproduce your problem:
1. ...
2. ...
3. ...
If you encountered a problem with specific files of any sorts, make sure
to also include a link to a file with which to reproduce the problem.]
#### What did you expect to happen and what happened instead?
#### What did you expect to happen?
#### What happened instead?
#### Did the same happen when running OctoPrint in safe mode?
[Try to reproduce your problem in safe mode. You can find information
on how to enable safe mode in the Contribution Guidelines.]
#### Branch & Commit or Version of OctoPrint
@@ -53,7 +68,8 @@ to also include a link to a file with which to reproduce the problem.]
#### Operating System running OctoPrint
[OctoPi, Linux, Windows, MacOS, something else? With version please.]
[OctoPi, Linux, Windows, MacOS, something else? With version please.
OctoPi's version can be found in /etc/octopi_version]
#### Printer model & used firmware incl. version
@@ -61,29 +77,31 @@ to also include a link to a file with which to reproduce the problem.]
#### Browser and Version of Browser, Operating System running Browser
[If applicable, always include if unsure or reporting UI issues.]
[If applicable, always include if unsure.]
#### Link to octoprint.log
[On gist.github.com or pastebin.com. ALWAYS INCLUDE and never truncate.]
[On gist.github.com or pastebin.com. ALWAYS INCLUDE and never truncate.
The Contribution Guidelines tell you where to find that.]
#### Link to contents of terminal tab or serial.log
[On gist.github.com or pastebin.com. If applicable, always include if unsure or
reporting any kind of communication issues between OctoPrint and your printer.
Never truncate.
reporting communication issues. Never truncate.
serial.log is usually not written due to performance reasons and must be
enabled explicitly. Provide at the very least the FULL contents of your
terminal tab at the time of the bug occurrence, even if you do not have
a serial.log.]
a serial.log (which the Contribution Guidelines tell you where to find).]
#### Link to contents of Javascript console in the browser
[On gist.github.com or pastebin.com or alternatively a screenshot. If applicable -
always include if unsure or reporting UI issues.]
always include if unsure or reporting UI issues.
#### Screenshot(s) or video(s) showing the problem:
The Contribution Guidelines tell you where to find that.]
#### Screenshot(s)/video(s) showing the problem:
[If applicable. Always include if unsure or reporting UI issues.]
+7 -4
View File
@@ -16,11 +16,14 @@ prerelease
HEAD
\(detached.*
# maintenance is currently the branch for preparation of maintenance release 1.3.2
# maintenance is currently the branch for preparation of maintenance release 1.3.5
# so are any fix/... and improve/... branches
maintenance 1.3.2 6393de8c7d42a8bbddcab7cdbb6530ea88a8c82d pep440-dev
fix/.* 1.3.2 6393de8c7d42a8bbddcab7cdbb6530ea88a8c82d pep440-dev
improve/.* 1.3.2 6393de8c7d42a8bbddcab7cdbb6530ea88a8c82d pep440-dev
maintenance 1.3.5 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev
fix/.* 1.3.5 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev
improve/.* 1.3.5 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev
# staging/maintenance is currently the branch for preparation of 1.3.5rc1
staging/maintenance 1.3.5rc1 fe481e12b3c50a2def3b41515200e13a8c6a5c72 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
+2
View File
@@ -79,6 +79,8 @@ date of first contribution):
* [Greg Hulands](https://github.com/ghulands)
* [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
+161 -2
View File
@@ -1,6 +1,131 @@
# OctoPrint Changelog
## 1.3.2rc1 (2017-03-10)
## 1.3.4 (2017-06-01)
### Note for owners of Malyan M200/Monoprice Select Mini
OctoPrint's firmware autodetection is now able to detect this printer. Currently when this printer is detected, the following firmware specific features will be enabled automatically:
* Always assume SD card is present (`feature.sdAlwaysAvailable`)
* Send a checksum with the command: Always (`feature.alwaysSendChecksum`)
Since the firmware is a very special kind of beast and its sources are so far unavailable, only tests with a real printer will show if those are sufficient settings for communication with this printer to fully function correctly. Thus, if you run into any issues with enabled firmware autodetection on this printer model, please add a comment in [#1762](https://github.com/foosel/OctoPrint/issues/1762) and explain what kind of communication problem you are seeing. Also make sure to include a [`serial.log`](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md#where-can-i-find-those-log-files-you-keep-talking-about)!
### Bug fixes
* [#1942](https://github.com/foosel/OctoPrint/issues/1942) - Fixed crash on startup in case of an invalid default printer profile combined with "auto-connect on startup" being selected and the printer available to connect to.
### More information
* [Commits](https://github.com/foosel/OctoPrint/compare/1.3.1...1.3.2)
* Release Candidates:
* None since this constitutes a hotfix release to fix an apparently very rare bug introduced with 1.3.3 that seems to be affecting a small number of users.
## 1.3.3 (2017-05-31)
### Note for owners of Malyan M200/Monoprice Select Mini
OctoPrint's firmware autodetection is now able to detect this printer. Currently when this printer is detected, the following firmware specific features will be enabled automatically:
* Always assume SD card is present (`feature.sdAlwaysAvailable`)
* Send a checksum with the command: Always (`feature.alwaysSendChecksum`)
Since the firmware is a very special kind of beast and its sources are so far unavailable, only tests with a real printer will show if those are sufficient settings for communication with this printer to fully function correctly. Thus, if you run into any issues with enabled firmware autodetection on this printer model, please add a comment in [#1762](https://github.com/foosel/OctoPrint/issues/1762) and explain what kind of communication problem you are seeing. Also make sure to include a [`serial.log`](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md#where-can-i-find-those-log-files-you-keep-talking-about)!
### Improvements
* [#478](https://github.com/foosel/OctoPrint/issues/478) - Made webcam stream container fixed height (with selectable aspect ratio) to prevent jumps of the controls beneath it on load.
* [#748](https://github.com/foosel/OctoPrint/issues/748) - Added delete confirmation and bulk delete for timelapses. See also the discussion in brainstorming ticket [#1807](https://github.com/foosel/OctoPrint/issues/1807).
* [#1092](https://github.com/foosel/OctoPrint/issues/1092) - Added new events to the file manager: `FileAdded`, `FileRemoved`, `FolderAdded`, `FolderRemoved`. Contrary to the `Upload` event, `FileAdded` will always fire when a file was added to storage through the file manager, not only when added through the web interface. Extended documentation accordingly.
* [#1521](https://github.com/foosel/OctoPrint/issues/1521) - Software update plugin: Display timestamp of last version cache refresh in "Advanced options" area.
* [#1734](https://github.com/foosel/OctoPrint/issues/1734) - Treat default/initial printer profile like all other printer profiles, persisting it to disk instead of `config.yaml` and allowing deletion. OctoPrint will migrate the existing default profile to the new location on first start.
* [#1734](https://github.com/foosel/OctoPrint/issues/1734) - Better communication of what actions are available for printer profiles.
* [#1739](https://github.com/foosel/OctoPrint/issues/1739) - Software update plugin: Added option to hide update notification from users without admin rights, added "ignore" button and note to get in touch with an admit to update notifications for non admin users.
* [#1762](https://github.com/foosel/OctoPrint/issues/1762) - Added Malyan M200/Monoprice Select Mini to firmware autodetection.
* [#1811](https://github.com/foosel/OctoPrint/issues/1811) - Slight rewording and rearrangement in timelapse configuration, better feedback if settings have been saved.
* [#1818](https://github.com/foosel/OctoPrint/issues/1818) - Support both Marlin/Repetier and Smoothieware interpretations of `G90` after an `M83` in GCODE viewer and analysis. Select "G90/G91 overrides relative extruder mode" in Settings > Features for the Smoothieware interpretation.
* [#1858](https://github.com/foosel/OctoPrint/issues/1858) - Announcement plugin: Images from registered feeds now are lazy loading.
* [#1862](https://github.com/foosel/OctoPrint/issues/1862) - Automatically re-enable fancy terminal functionality when performance recovers.
* [#1875](https://github.com/foosel/OctoPrint/issues/1875) - Marked the command input field in the Terminal tab as not supporting autocomplete to work around an issue in Safari. Note that this is probably only a temporary workaround due to browser vendors [working on deprecating `autocomplete="off"` support](https://bugs.chromium.org/p/chromium/issues/detail?id=468153#c164) and a different solution will need to be found in the future.
* Added link to [`SerialException` FAQ entry](https://github.com/foosel/OctoPrint/wiki/FAQ#octoprint-randomly-loses-connection-to-the-printer-with-a-serialexception) to terminal output when such an error is encountered, as suggested in [#1876](https://github.com/foosel/OctoPrint/issues/1876).
* Force refresh of settings on login/logout.
* Made system wide API key management mirror user API key management.
* Make sure to always migrate and merge saved printer profiles with default profile to ensure all parameters are set. Should avoid issues with plugins trying to save outdated/incomplete profiles.
* Added note on lack of language pack repository & to use the wiki for now.
* Earlier validation of file to select for printing.
* Limit verbosity of failed system event handlers.
* Made bundled python client `octoprint_client` support multiple client instances.
* Disable "Reload" button in the "Please reload" overlay once clicked, added spinner.
* Updated pnotify to 2.1.0.
* Get rid of ridiculous float precision in temperature commands.
* Detect invalid settings data to persist (not a dict), send 400 status in such a case.
* More logging for preemptive caching, to help narrow down any performance issues that might be related to this.
* Further decoupling of some startup tasks from initial server startup thread for better parallelization and improved startup times.
* Announcement plugin: Added combined OctoBlog feed, replacing news and spotlight feed, added corresponding config migration.
* Announcement plugin: Subscribe to all registered feeds by default to ensure better communication flow (all subscriptions but the "Important" channel can however be unsubscribed easily, added corresponding note to the notifications and also a configuration button to the announcement reader).
* Announcement plugin: Auto-hide announcements on logout.
* Announcement plugin: Order channels server-side based on new order config setting.
* Plugin manager: Show warning when disabling a bundled plugin that is not recommended to be disabled, including a reason why disabling it is not recommended. Applies to the bundled announcement, core wizard, discovery and software update plugins.
* Plugin manager: Support for plugin notices for specific plugins from the plugin repository, e.g. to inform users of specific plugins about known issues with the plugin or instruct to update when the software update mechanism of the current plugin version turns out to be misconfigured. Supports matching installed plugin versions and OctoPrint versions to target only affected users.
* Plugin manager: Better visualization of plugins disabled on the repository, no longer shown as "incompatible" but "disabled", with link to the plugin repository page that contains more information.
* Plugin manager: Detect necessity to reinstall a plugin provided through archive URL or upload and immediately do that instead of reporting an "unknown error" without further information.
* Plugin manager: Added `freebsd` for compatibility check.
* Plugin manager: More general flexibility for OS compatibility check:
* Support for arbitrary values to match against
* Allow 1:1 check again `sys.platform` values (with `startswith`).
* Support black listing (`!windows`) additionally to white listing. A detected OS must match all provided white list elements (if the white list is empty that is considered to be always the case) and none of the black list elements (if the black list is empty that is also considered to be always the case).
* Software update plugin: New check type `bitbucket_commit` (see also [#1898](https://github.com/foosel/OctoPrint/pull/1898))
* Docs: Now referring to dedicated Jinja 2.8 documentation as hosted at [jinja.octoprint.org](http://jinja.octoprint.org) for all template needs, to avoid confusion when consulting current Jinja documentation as available on its project page (2.9+, which OctoPrint can't upgrade to due to backwards incompatible changes).
* Docs: Better documentation of what kind of input the `FileManager` accepts for `select_file`.
* Docs: Specified OctoPrint version required for plugin tutorial.
### Bug fixes
* [#202](https://github.com/foosel/OctoPrint/issues/202) - Fixed an issue with the drag-n-drop area flickering if the mouse was moved too slow while dragging (see also [#1867](https://github.com/foosel/OctoPrint/pull/1867)).
* [#1671](https://github.com/foosel/OctoPrint/issues/1671) - Removed obsolete entry of no longer available filter for empty folders from file list options.
* [#1821](https://github.com/foosel/OctoPrint/issues/1821) - Properly reset "Capture post roll images" setting in timelapse configuration when switching from "off" to "timed" timelapse mode.
* [#1822](https://github.com/foosel/OctoPrint/issues/1822) - Properly reset file metadata when a file is overwritten with a new version.
* [#1836](https://github.com/foosel/OctoPrint/issues/1836) - Fixed order of `PrintCancelled` and `PrintFailed` events on print cancel.
* [#1837](https://github.com/foosel/OctoPrint/issues/1837) - Fixed a race condition causing OctoPrint trying to read data from the current job on job cancel that was no longer there.
* [#1838](https://github.com/foosel/OctoPrint/issues/1838) - Fixed a rare race condition causing an error right at the very start of a print.
* [#1863](https://github.com/foosel/OctoPrint/issues/1863) - Fixed an issue in the analysis of GCODE files containing coordinate offsets for X, Y or Z via `G92`, leading to a wrong calculation of the model size thanks to accumulating offsets.
* [#1882](https://github.com/foosel/OctoPrint/issues/1882) - Fixed a rare race condition occurring at the start of streaming a file to the printer's SD card, leading to endless line number mismatches.
* [#1884](https://github.com/foosel/OctoPrint/issues/1884) - CuraEngine plugin: Fixed a potential encoding issue when logging non-ASCII parameters supplied to CuraEngine
* [#1891](https://github.com/foosel/OctoPrint/issues/1891) - Fixed error when handling unicode passwords.
* [#1893](https://github.com/foosel/OctoPrint/issues/1893) - CuraEngine plugin: Fixed handling of multiple consecutive uploads of slicing profiles (see also [#1894](https://github.com/foosel/OctoPrint/issues/1894))
* [#1897](https://github.com/foosel/OctoPrint/issues/1897) - Removed possibility to concurrently try to perform multiple tests of the configured snapshot URL.
* [#1906](https://github.com/foosel/OctoPrint/issues/1906) - Fixed interpretation of `G92` in GCODE analysis.
* [#1907](https://github.com/foosel/OctoPrint/issues/1907) - Don't send temperature commands with tool parameter when a shared nozzle is defined.
* [#1917](https://github.com/foosel/OctoPrint/issues/1917) (regression) - Fix job data resetting on print job completion.
* [#1918](https://github.com/foosel/OctoPrint/issues/1918) (regression) - Fix "save as default" checkbox not being disabled when other controls are disabled.
* [#1919](https://github.com/foosel/OctoPrint/issues/1919) (regression) - Fix call to no longer existing function in Plugin Manager UI.
* [#1934](https://github.com/foosel/OctoPrint/issues/1934) (regression) - Fix consecutive timed timelapse captures without configured post roll.
* Fixed API key QR Code being shown (for "n/a" value) when no API key was set.
* Fixed timelapse configuration API not returning 400 status code on some bad parameters.
* Fixed a typo (see also [#1826](https://github.com/foosel/OctoPrint/pull/1826)).
* Fixed `filter` and `force` parameters on `/api/files/<origin>`.
* Fixed message catchall `*` not working in the socket client library.
* Fixed analysis backlog calculation for sub folders.
* Fixed `PrinterInterface.is_ready` to behave as documented.
* Use black listing instead of white listing again to detect if the `daemon` sub command is supported or not. Should resolve issues users of FreeBSD and the like where having with `octoprint daemon`.
* Use `pip` instead of `python setup.py develop` in `octoprint dev plugin:install` command to avoid issues on Windows.
* Docs: Fixed a wrong command in the plugin tutorial (see also [#1860](https://github.com/foosel/OctoPrint/pull/1860)).
### More information
- [Commits](https://github.com/foosel/OctoPrint/compare/1.3.2...1.3.3)
- Release Candidates:
- [1.3.3rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.3rc1)
- [1.3.3rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.3rc2)
- [1.3.3rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.3rc3)
## 1.3.2 (2017-03-16)
### Note for plugin authors
**If you maintain a plugin that extends OctoPrint's [JavaScript Client Library](http://docs.octoprint.org/en/master/jsclientlib/index.html)** like demonstrated in e.g. the bundled Software Update Plugin you'll need to update the way you register your plugin to depend on `OctoPrintClient` and registering your extension as shown [here](https://github.com/foosel/OctoPrint/blob/6e793c2/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js#L1-L84) instead of directly writing to `OctoPrint.plugins` (like it was still done [here](https://github.com/foosel/OctoPrint/blob/23744cd/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js#L1-L81)). That way your extensions will be available on all instances of `OctoPrintClient`, not just the global instance `OctoPrint` that gets created on startup of the core web interface.
If all you plugin does with regards to JavaScript is registering a custom view model and you have no idea what I'm talking about regarding extending the client library, no action is necessary. This heads-up is really only relevant if you extended the JavaScript Client Library.
### Improvements
@@ -8,6 +133,8 @@
`python setup.py clean` for better compatibility with packaging systems
- [#1506](https://github.com/foosel/OctoPrint/issues/1506) - Better handle really long "dwell"/`G4` commands on Repetier firmware (as for example apparently recommended to use with Wanhao D6 and similar printers for nozzle cooling) by actively stalling communication from OctoPrint's side as well. That way we no longer run into a communication timeout produced by a 5min dwell immediately happily acknowledged by the printer with an `ok`.
- [#1542](https://github.com/foosel/OctoPrint/issues/1542) - Support for multi-extruder setups with a shared single nozzle and heater (e.g. E3D Cyclops, Diamond hotend, etc).
- [#1676](https://github.com/foosel/OctoPrint/issues/1676) - Trigger line number reset when connected to printer and seeing `start` message. This should fix issues with printer communication when printer resets but reset goes otherwise undetected.
- [#1681](https://github.com/foosel/OctoPrint/issues/1681) - Support for connecting to multiple OctoPrint instances via the [JavaScript Client Library](http://docs.octoprint.org/en/master/jsclientlib/index.html).
- [#1712](https://github.com/foosel/OctoPrint/issues/1712) - Display current folder name in file list if in sub folder.
- [#1723](https://github.com/foosel/OctoPrint/issues/1723) - Ignore leading `v` or `V` on plugin version numbers for version checks in plugin manager and software updater (see also [#1724](https://github.com/foosel/OctoPrint/pull/1724))
- [#1770](https://github.com/foosel/OctoPrint/issues/1770) - Better resilience against null bytes received from the printer for whatever reason.
@@ -20,11 +147,19 @@
- CLI: Only offer `daemon` sub command on Linux (since that it's the only OS it works on)
- Less throttling of analysis of GCODE files from the analysis backlog. Should still leave Pi and friends air to breathe but allow a slightly faster processing of the backlog.
- Added an explanation of safe mode to the docs.
- Log OctoPrint version & plugin list when detecting log rollover.
- Allow `UiPlugin`s to define additional fields for ETag generation.
- Allow `UiPlugin`s utilizing OctoPrint's stock templates to filter out what they don't need.
- Locales contained in `translations` of plugins will now be registered with the system. That way it's possible to provide translations for the full application through plugins.
- Abort file analysis if file is about to be overwritten
- Software Update Plugin: Refresh cache on startup, prevent concurrent refresh
- More solid parsing of request line number for resend requests. Should improve compatibility with Teacup firmwares. Based on issue reported via PR [#300](https://github.com/foosel/OctoPrint/pull/300)
### Bug fixes
- [#733](https://github.com/foosel/OctoPrint/issues/733) - Fixed multiple event handler commands running concurrently. Now they run one after the other, as expected.
- [#1317](https://github.com/foosel/OctoPrint/issues/1317) - Fixed a color distortion issue when rendering timelapses from higher resolution source snapshots that also need to be rotated by adjusting `ffmpeg` parameters to avoid an unexpected behaviour when a pixel format and a filter chain are required for processing.
- [#1560](https://github.com/foosel/OctoPrint/issues/1560) - Make sure we don't try to use an empty `logging.yaml`
- [#1631](https://github.com/foosel/OctoPrint/issues/1631) - Disable "Slice" button in slice dialog if a print is ongoing and a slicer is selected that runs on the same device as OctoPrint. The server would already deny such requests (simply due to performance reasons), but the UI didn't properly reflect that yet.
- [#1671](https://github.com/foosel/OctoPrint/issues/1671) - Removed "Hide empty folders" option from file list. Didn't really add value and caused usability issues.
- [#1771](https://github.com/foosel/OctoPrint/issues/1771) - Fixed `_config_version` in plugin settings not being properly updated.
@@ -35,6 +170,7 @@
- [#1792](https://github.com/foosel/OctoPrint/issues/1792) - Don't tell Safari we are "web-app-capable" because that means it will throw away all cookies and the user will have to constantly log in again when using a desktop shortcut for the OctoPrint instance.
- [#1812](https://github.com/foosel/OctoPrint/issues/1812) - Don't scroll up navigation in settings when switching between settings screens, very annoying on smaller resolutions (see also [#1814](https://github.com/foosel/OctoPrint/pull/1814))
- Fix settings helper not allowing to delete values for keys that are present in the local config but not in the defaults.
- Fix wrong replacement value for `__progress` in registered command line or GCODE [event handlers](http://docs.octoprint.org/en/master/events/index.html).
- Various fixes in the Software Update Plugin:
- Don't remove manual software update configurations on settings migration.
- Properly delete old restart/reboot commands that are now defined globally since config version 4. An issue with the settings helper prevented us from properly deleting them during migration to version 4.
@@ -42,13 +178,36 @@
- Fixed update configs without a restart of any kind causing an issue due to an undefined variable.
- Fixed broken doctests.
- Upgrade LESS.min.js from 2.7.1 to 2.7.2 to fix the broken contrast function
- Always create a new user session for requests with an API key
- Fixed an error when reading all user settings via the API
- Fixed a bunch of caching issues for the page, was not properly updated on change of snapshot URL presence, system menu entry presence, gcode viewer enabled/disabled, changes in access control availability.
- Fixed wrong bundling of core and plugin assets
- Software Update Plugin: Fixed wrong ETag calculation
- Disable external heatup detection until firmware is detected
- Fixed login dropdown not closing on click outside of it
- Fixed new user settings getting lost until restart
- Don't call `onUserLoggedIn`/`onUserLoggedOut` on user reload
([Commits](https://github.com/foosel/OctoPrint/compare/1.3.1...1.3.2rc1))
### More information
- [Commits](https://github.com/foosel/OctoPrint/compare/1.3.1...1.3.2)
- Release Candidates:
- [1.3.2rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.2rc1)
## 1.3.1 (2017-01-25)
### Note for upgraders
#### If you installed OctoPrint manually and used the included init script, you need to update that
The init script so far shipped with OctoPrint contained a [bug](https://github.com/foosel/OctoPrint/issues/1657) that causes issues with OctoPrint 1.3.0 and higher. Please update your init script to the fixed version OctoPrint now ships under `scripts`:
```
sudo cp /path/to/OctoPrint/scripts/octoprint.init /etc/init.d/octoprint
```
If you are running OctoPi, this does **not** apply to you and you do not need to do anything here!
#### Change in stock terminal filter configuration
1.3.1 fixes an issue with the two terminal filters for suppressing temperature and SD status messages and adds a new filter for filtering out firmware `wait` messages. These changes will only be active automatically though for stock terminal filter configurations. If you have customized your terminal filters, you'll need to apply these changes manually under "Settings > Terminal filters":
+33 -6
View File
@@ -142,6 +142,12 @@ only provided here as some additional information for you), **even if only addin
reproduce your issue in order to fix it and that is not possible if they
don't know what you did to get it to happen in the first place.
Ideally provide exact steps to follow in order to reproduce your problem:
1. ...
2. ...
3. ...
If you encountered a problem with specific files of any sorts, make sure
to also include a link to a file with which to reproduce the problem.]
@@ -149,10 +155,20 @@ only provided here as some additional information for you), **even if only addin
#### What happened instead?
#### Did the same happen when running OctoPrint in safe mode?
[Try to reproduce your problem in safe mode. You can find information
on how to enable safe mode in the Contribution Guidelines.]
#### Branch & Commit or Version of OctoPrint
[Can be found in the lower left corner of the web interface. ALWAYS INCLUDE.]
#### Operating System running OctoPrint
[OctoPi, Linux, Windows, MacOS, something else? With version please,
OctoPi's version can be found in /etc/octopi_version]
#### Printer model & used firmware incl. version
[If applicable, always include if unsure.]
@@ -163,7 +179,8 @@ only provided here as some additional information for you), **even if only addin
#### Link to octoprint.log
[On gist.github.com or pastebin.com. ALWAYS INCLUDE and never truncate.]
[On gist.github.com or pastebin.com. ALWAYS INCLUDE and never truncate.
The Contribution Guidelines tell you where to find that.]
#### Link to contents of terminal tab or serial.log
@@ -178,16 +195,19 @@ only provided here as some additional information for you), **even if only addin
#### Link to contents of Javascript console in the browser
[On gist.github.com or pastebin.com or alternatively a screenshot. If applicable -
always include if unsure or reporting UI issues.]
always include if unsure or reporting UI issues.
#### Screenshot(s) showing the problem:
The Contribution Guidelines tell you where to find that.]
#### Screenshot(s)/video(s) showing the problem:
[If applicable. Always include if unsure or reporting UI issues.]
I have read the FAQ.
Copy-paste this template **completely**. Do not skip any lines or the bot
*will* complain!
Copy-paste this template **completely** (or use the version that gets pre-filled
into the "new issue" form). Do not skip any lines or the bot *will* complain! Provide
all requested information or your ticket will be closed.
### Where can I find which version and branch I'm on?
@@ -345,10 +365,16 @@ There are three main branches in OctoPrint:
the `maintenance` branch and are now being pushed on the "Maintenance"
pre release channel for further testing. Version number follows the scheme
`<x>.<y>.<z>rc<n>` (e.g. `1.2.9rc1`).
* `staging/maintenance`: Any preparation for potential follow-up RCs takes place here.
Version number follows the scheme `<x>.<y>.<z>rc<n+1>.dev<commits since increase of n>` (e.g.
`1.2.9rc1.dev3`) for a current Maintenance RC of `<x>.<y>.<z>rc<n>`.
* `rc/devel`: This branch is reserved for future releases that have graduated from
the `devel` branch and are now being pushed on the "Devel" pre release channel
for further testing. Version number follows the scheme `<x>.<y+1>.0rc<n>` (e.g. `1.3.0rc1`)
for a current stable OctoPrint version of `<x>.<y>.<z>`.
* `staging/devel`: Any preparation for potential follow-up Devel RCs takes place
here. Version number follows the scheme `<x>.<y>.0rc<n+1>.dev<commits since increase of n>` (e.g.
`1.3.0rc1.dev12`) for a current Devel RC of `<x>.<y>.0rc<n>`.
Additionally, from time to time you might see other branches pop up in the repository.
Those usually have one of the following prefixes:
@@ -360,7 +386,7 @@ Those usually have one of the following prefixes:
* `dev/...` or `feature/...`: New functionality under development that is to be merged
into the `devel` branch.
There is also the `gh-pages` branch, which holds OctoPrint's web page, and a couple of
There is also the `gh-pages` branch, which holds OctoPrint's web page, and a few
older development branches that are slowly being migrated or deleted.
## How OctoPrint is versioned
@@ -405,6 +431,7 @@ the local version identifier to allow for an exact determination of the active c
* 2017-03-09: Allow PRs against `maintenance` branch for bugs in stable.
* 2017-03-10: Reproduce bugs in safe mode to make sure they are really caused
by OctoPrint itself and not a misbehaving plugin.
* 2017-03-27: Added safe mode section to ticket template.
## Footnotes
* [1] - If you are wondering why, the problem is that anything that you add
+1 -1
View File
@@ -67,7 +67,7 @@ and at its settings.
## Dependencies
OctoPrint depends on a couple of python modules to do its job. Those are automatically installed when installing
OctoPrint depends on a few python modules to do its job. Those are automatically installed when installing
OctoPrint via `setup.py`:
python setup.py install
+8 -6
View File
@@ -1,4 +1,4 @@
# Supporters
# Supporters
Development of this version of OctoPrint wouldn't have been possible without
[financial support by the community](http://octoprint.org/support-octoprint/) -
@@ -10,11 +10,11 @@ thanks to everyone who contributed!
* Aleph Objects, Inc.
* Andrew Moorby
* Arnljot Arntsen
* BEEVERYCREATIVE
* Boris Hussein
* Brad Jackson
* Brent Fiegle
* Brian E. Tyler
* Christopher Day
* Chris Day
* Christian Petropolis
* CreativeTools
* D Brian Kimmel
@@ -23,12 +23,15 @@ thanks to everyone who contributed!
* E3D BigBox
* Ernesto Martinez
* Exovite
* F. Kunsmann
* Frank Sander
* Gary Deen
* Gary N McKinney
* George Robles
* günter weber
* Ivan Krasin
* James Seigel
* Jamie van Dyke
* Jamie R McGuigan
* Jeff Moe
* Josh Daniels
* Kaile Riser
@@ -58,9 +61,8 @@ thanks to everyone who contributed!
* Stefan Krister
* Stephane Schittly
* Sven Mueller
* Terrance Shaw
* Thomas Hatley
* Timeshell.ca
* Trent Shumay
and 1041 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
and 1098 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
+1 -1
View File
@@ -31,7 +31,7 @@ Printer State
* - ``flags``
- 1
- Printer state flags
- A couple of boolean printer state flags
- A few boolean printer state flags
* - ``flags.operational``
- 1
- Boolean
+20
View File
@@ -68,6 +68,23 @@ Save settings
// ...
}
.. _sec-api-settings-generateapikey:
Regenerate the system wide API key
==================================
.. http:post:: /api/settings/apikey
Generates a new system wide API key.
Does not expect a body. Will return the generated API key as ``apikey``
property in the JSON object contained in the response body.
Requires admin rights.
:status 200: No error
:status 403: No admin rights
.. _sec-api-settings-datamodel:
Data model
@@ -87,6 +104,9 @@ mapped from the same fields in ``config.yaml`` unless otherwise noted:
-
* - ``api.key``
- Only maps to ``api.key`` in ``config.yaml`` if request is sent with admin rights, set to ``n/a`` otherwise.
Starting with OctoPrint 1.3.3 setting this field via :ref:`the API <sec-api-settings-save>` is not possible,
only :ref:`regenerting it <sec-api-settings-generateapikey>` is supported. Setting a custom value is only
possible through `config.yaml`.
* - ``api.allowCrossOrigin``
-
* - ``appearance.name``
+9 -2
View File
@@ -43,6 +43,13 @@ Installing pybonjour
OctoPi versions 0.12.0 and later already come with pybonjour installed and ready to go,
you don't need to perform these steps there.
.. note::
Currently there are no releases for pybonjour available on the Python Package Index PyPI. The latest pybonjour
release is still available in the `Google Code Archive <https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/pybonjour/pybonjour-1.1.1.tar.gz>`_.
Since that URL is hilariously long though, a shortened version is provided with https://goo.gl/SxQZ06 and
used in the installation instructions below.
In order for the Zeroconf discovery to work, the
`pybonjour package <https://pypi.python.org/pypi/pybonjour>`_ needs to be available
to the Python installation running OctoPrint.
@@ -52,7 +59,7 @@ into some folder ``~/OctoPrint``. You executed ``python setup.py install`` withi
virtualenv in the same folder called ``venv``. In order to install ``pybonjour``
so it will be available to OctoPrint you'll need to do the following::
venv/bin/pip install pybonjour
venv/bin/pip install https://goo.gl/SxQZ06
**Linux users:** You'll need to install an additional dependency for this to work, the
libdnssd compatibility layer for libavahi. On Debian/Ubuntu that can be achieved with::
@@ -71,7 +78,7 @@ The plugin supports the following configuration keys:
optional, if not set the port OctoPrint itself was started under will be used
* ``pathPrefix``: Path prefix OctoPrint is running under, optional, if not
set ``/`` will be used
* ``useSsl``: ``true``if OctoPrint should be called via HTTPS, ``false`` otherwise
* ``useSsl``: ``true`` if OctoPrint should be called via HTTPS, ``false`` otherwise
* ``httpUsername``: HTTP Basic Auth username OctoPrint is reachable with, optional
* ``httpPassword``: HTTP Basic Auth password OctoPrint is reachable with, optional
* ``upnpUuid``: uPNP UUID used for SSDP service announcements, usually you will
+36
View File
@@ -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
+10
View File
@@ -188,6 +188,16 @@ Version checks
* ``repo``: (mandatory) Github repository to check
* ``branch``: Branch of the Github repository to check, defaults to
``master`` if not set.
* ``current``: Current commit hash. Will be updated automatically.
* ``bitbucket_commit``: Checks against commits pushed to Bitbucket. Additional
config parameters:
* ``user``: (mandatory) Bitbucket user the repository to check belongs to
* ``repo``: (mandatory) Bitbucket repository to check
* ``branch``: Branch of the Bitbucket repository to check, defaults to
``master`` if not set.
* ``current``: Current commit hash. Will be updated automatically.
* ``git_commit``: Checks a local git repository for new commits on its
configured remote. Additional config parameters:
+1 -1
View File
@@ -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.
+2 -2
View File
@@ -943,8 +943,8 @@ Use the following settings to configure the server:
* ``X-Scheme``: should contain your custom URL scheme to use (if different from ``http``), e.g. ``https``
If you use these headers OctoPrint will work both via the reverse proxy as well as when called directly. Take a look
`into OctoPrint's wiki <https://github.com/foosel/OctoPrint/wiki/Reverse-proxy-configuration-examples>`_ for a couple
of examples on how to configure this.
`into OctoPrint's wiki <https://github.com/foosel/OctoPrint/wiki/Reverse-proxy-configuration-examples>`_ for some
examples on how to configure this.
.. _sec-configuration-config_yaml-slicing:
+71 -7
View File
@@ -152,7 +152,7 @@ File handling
-------------
Upload
A file has been uploaded.
A file has been uploaded through the web interface.
Payload:
* ``name``: the file's name
@@ -165,19 +165,74 @@ Upload
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
FileAdded
A file has been added to a storage.
Payload:
* ``storage``: the storage's identifier
* ``path``: the file's path within its storage location
* ``name``: the file's name
* ``type``: the file's type, a list of the path within the type hierarchy, e.g. ``["machinecode", "gcode"]`` or
``["model", "stl"]``
.. note::
A copied file triggers this for its new path. A moved file first triggers ``FileRemoved`` for its original
path and then ``FileAdded`` for the new one.
FileRemoved
A file has been removed from a storage.
Payload:
* ``storage``: the storage's identifier
* ``path``: the file's path within its storage location
* ``name``: the file's name
* ``type``: the file's type, a list of the path within the type hierarchy, e.g. ``["machinecode", "gcode"]`` or
``["model", "stl"]``
.. note::
A moved file first triggers ``FileRemoved`` for its original path and then ``FileAdded`` for the new one.
FolderAdded
A folder has been added to a storage.
Payload:
* ``storage``: the storage's identifier
* ``path``: the folders's path within its storage location
* ``name``: the folders's name
.. note::
A copied folder triggers this for its new path. A moved folder first triggers ``FolderRemoved`` for its original
path and then ``FolderAdded`` for the new one.
FolderRemoved
A folder has been removed from a storage.
Payload:
* ``storage``: the storage's identifier
* ``path``: the folders's path within its storage location
* ``name``: the folders's name
.. note::
A moved folder first triggers ``FolderRemoved`` for its original path and then ``FolderAdded`` for the new one.
UpdatedFiles
A file list was modified.
Payload:
* ``type``: the type of file list that was modified. Currently only ``printables`` and ``gcode`` (DEPRECATED) are supported here.
* ``type``: the type of file list that was modified. Only ``printables`` is supported here. See the deprecation
note below.
.. note::
.. deprecated:: 1.2.0
The ``gcode`` modification type has been superceeded by ``printables``. It is currently still available for
reasons of backwards compatibility and will also be sent on modification of ``printables``. It will however
be removed with 1.4.0.
The type ``gcode`` has been renamed to ``printables`` with the introduction of a new file management layer that
supports STL files as first class citizens as well. For reasons of backwards compatibility the ``UpdatedFiles``
event for printable files will be fired twice, once with ``type`` set to ``gcode``, once set to ``printables``.
Support for the ``gcode`` type will be removed in the next release after version 1.2.0.
MetadataAnalysisStarted
The metadata analysis of a file has started.
@@ -422,6 +477,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
----------
+32 -11
View File
@@ -13,11 +13,19 @@ Unless :ref:`configured otherwise <sec-configuration-config_yaml-folder>`, OctoP
the ``scripts/gcode`` folder in OctoPrint configuration directory (per default ``~/.octoprint`` on Linux, ``%APPDATA%\OctoPrint``
on Windows and ``~/Library/Application Support/OctoPrint`` on MacOS).
These GCODE scripts are backed by the templating engine `Jinja2 <http://jinja.pocoo.org/>`_, allowing more than just
These GCODE scripts are backed by the templating engine Jinja2, allowing more than just
simple "send-as-is" scripts but making use of a full blown templating language in order to create your scripts. To
this end, OctoPrint injects a couple of variables into the :ref:`template rendering context <sec-features-gcode_scripts-context>`
this end, OctoPrint injects some variables into the :ref:`template rendering context <sec-features-gcode_scripts-context>`
as described below.
You can find the docs on the Jinja templating engine as used in OctoPrint at `jinja.octoprint.org <http://jinja.octoprint.org/templates.html>`_.
.. note::
Due to backwards compatibility issues with Jinja versions 2.9+, OctoPrint currently only supports Jinja 2.8. For this
reason use the template documentation at `jinja.octoprint.org <http://jinja.octoprint.org/templates.html>`_ instead of the
documentation of current stable Jinja versions.
.. _sec-features-gcode_scripts-predefined:
Predefined Scripts
@@ -60,23 +68,35 @@ 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.
There are a couple of additional template variables available for the following specific scripts:
There are a few additional template variables available for the following specific scripts:
* ``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.
* ``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.
* ``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.
See ``last_position`` above for the structure to expect here.
* ``cancel_temperature``: Last known temperature values when the print was cancelled. See ``last_temperature`` above
for the structure to expect here.
.. warning::
@@ -150,6 +170,7 @@ to 0 if a heated bed is configured.
.. seealso::
`Jinja Template Designer Documentation <http://jinja.pocoo.org/docs/dev/templates/>`_
`Jinja Template Designer Documentation <http://jinja.octoprint.org/templates.html>`_
Jinja's Template Designer Documentation describes the syntax and semantics of the template language used
also by OctoPrint's GCODE scripts.
also by OctoPrint's GCODE scripts. Linked here are the docs for Jinja 2.8.1, which OctoPrint still
relies on for backwards compatibility reasons.
+3 -3
View File
@@ -53,12 +53,12 @@ When OctoPrint is running in safe mode the following changes to its normal opera
* OctoPrint will still allow to uninstall third party plugins through the built-in Plugin Manager.
* OctoPrint will still allow to disable (bundled) plugins that are still enabled.
* OctoPrint will not allow to enable third party plugins.
* OctoPrint's web interface will display a persistent notification to remind you that it is running in
* OctoPrint's web interface will display a notification to remind you that it is running in
safe mode.
.. _fig-features-safemode-notification:
.. figure:: ../images/features-safemode-notification.png
:align: center
:alt: Persistent safe mode notification
:alt: Safe mode notification
Persistent safe mode notification
Safe mode notification
+7
View File
@@ -35,6 +35,13 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.settings.generateApiKey(opts)
Generate a new system wide API key.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. seealso::
:ref:`Settings API <sec-api-settings>`
+24 -6
View File
@@ -20,7 +20,7 @@ development environment::
$ virtualenv venv
[...]
$ source venv/bin/activate
(venv) $ pip install -e[develop]
(venv) $ pip install -e .[develop]
[...]
(venv) $ octoprint --help
Usage: octoprint [OPTIONS] COMMAND [ARGS]...
@@ -41,7 +41,15 @@ development environment::
[...]
We'll start at the most basic form a plugin can take - just a couple of simple lines of Python code:
.. important::
This tutorial assumes you are running OctoPrint 1.3.0 and up. Please make sure your version of
OctoPrint is up to date before proceeding. If you did a fresh checkout, that should already
be the case but if not you might have to update first. You can check your version of OctoPrint
by running ``octoprint --version`` or by taking a look into the lower left corner in OctoPrint's
web interface.
We'll start at the most basic form a plugin can take - just a few simple lines of Python code:
.. code-block:: python
:linenos:
@@ -108,7 +116,7 @@ used :func:`~octoprint.plugin.StartupPlugin.on_startup` instead, in which case o
up and ready to serve requests.
You'll also note that we are using ``self._logger`` for logging. Where did that one come from? OctoPrint's plugin system
injects :ref:`a couple of useful objects <sec-plugins-mixins-injectedproperties>` into our plugin implementation classes,
injects :ref:`a some useful objects <sec-plugins-mixins-injectedproperties>` into our plugin implementation classes,
one of those being a fully instantiated `python logger <https://docs.python.org/2/library/logging.html>`_ ready to be
used by your plugin. As you can see in the log output above, that logger uses the namespace ``octoprint.plugins.helloworld``
for our little plugin here, or more generally ``octoprint.plugins.<plugin identifier>``.
@@ -482,7 +490,7 @@ Also adjust your plugin's ``templates/helloworld_navbar.jinja2`` like this:
OctoPrint injects the template variables that your plugin defines prefixed with ``plugin_<plugin identifier>_`` into
the template renderer, so your ``url`` got turned into ``plugin_helloworld_url`` which you can now use as a simple
`Jinja2 Variable <http://jinja.pocoo.org/docs/dev/templates/#variables>`_ in your plugin's template.
`Jinja2 Variable <http://jinja.octoprint.org/templates.html#variables>`_ in your plugin's template.
Restart OctoPrint and shift-reload the page in your browser (to make sure you really get a fresh copy). The link should
still work and point to the URL we defined as default.
@@ -1070,8 +1078,14 @@ For some insight on how to create plugins that react to various events within Oc
add support for a slicer, OctoPrint's own bundled `CuraEngine plugin <https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura>`_
might give some hints. For extending OctoPrint's interface, the `NavbarTemp plugin <https://github.com/imrahil/OctoPrint-NavbarTemp>`_
might show what's possible with a few lines of code already. Finally, just take a look at the
`list of available plugins <https://github.com/foosel/OctoPrint/wiki#plugins>`_ on the OctoPrint wiki if you are
looking for examples.
`official Plugin Repository <http://plugins.octoprint.org>`_ if you are looking for examples.
.. seealso::
`Jinja Template Designer Documentation <http://jinja.octoprint.org/templates.html>`_
Jinja's Template Designer Documentation describes the syntax and semantics of the template language used
by OctoPrint's frontend. Linked here are the docs for Jinja 2.8.1, which OctoPrint still
relies on for backwards compatibility reasons [#f3]_.
.. rubric:: Footnotes
@@ -1084,3 +1098,7 @@ looking for examples.
.. [#f2] Refer to the `LESS documentation <http://lesscss.org/#using-less>`_ on how to do that. If you are developing
your plugin under Windows you might also want to give `WinLESS <http://winless.org/>`_ a look which will run
in the background and keep your CSS files up to date with your various project's LESS files automatically.
.. [#f3] Please always consult the Jinja documentation at `jinja.octoprint.org <http://jinja.octoprint.org>`_ instead of
the current stable documentation available at Jinja's project page. The reason for that is that for backwards
compatibility reasons OctoPrint currently sadly has to rely on an older version of Jinja. The documentation
available at `jinja.octoprint.org <http://jinja.octoprint.org>`_ matches that older version.
+1 -1
View File
@@ -6,7 +6,7 @@ Helpers
Helpers are methods that plugin can exposed to other plugins in order to make common functionality available on the
system. They are registered with the OctoPrint plugin system through the use of the control property ``__plugin_helpers__``.
An example for providing a couple of helper functions to the system can be found in the
An example for providing some helper functions to the system can be found in the
`Discovery Plugin <https://github.com/foosel/OctoPrint/wiki/Plugin:-Discovery>`_,
which provides it's SSDP browsing and Zeroconf browsing and publishing functions as helper methods.
+20 -1
View File
@@ -396,7 +396,8 @@ This describes actually four hooks:
* ``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
@@ -450,6 +451,24 @@ 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.
* 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"),
("M110",),
"M117 echo foo: {}".format(cmd)]
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**
+124
View File
@@ -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>`_
+85 -27
View File
@@ -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)
+1 -1
View File
@@ -3,7 +3,7 @@ description-file = README.md
[versioneer]
VCS = git
style = pep440-post
style = pep440-tag
versionfile_source = src/octoprint/_version.py
versionfile_build = octoprint/_version.py
tag_prefix =
+6 -3
View File
@@ -47,7 +47,9 @@ INSTALL_REQUIRES = [
"chainmap>=1.0.2,<1.1",
"future>=0.15,<0.16",
"scandir>=1.3,<1.4",
"websocket-client>=0.40,<0.41"
"websocket-client>=0.40,<0.41",
"python-dateutil>=2.6,<2.7",
"wrapt>=1.10.10,<1.11"
]
if sys.platform == "darwin":
@@ -63,9 +65,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"
+3 -3
View File
@@ -160,11 +160,11 @@ def octo(ctx, **kwargs):
"start|stop|restart\" is deprecated, please use "
"\"octoprint daemon start|stop|restart\" from now on")
if sys.platform == "linux2":
if sys.platform == "win32" or sys.platform == "darwin":
click.echo("Sorry, daemon mode is not supported under your operating system right now")
else:
from octoprint.cli.server import daemon_command
ctx.invoke(daemon_command, command=daemon, **kwargs)
else:
click.echo("Sorry, daemon mode is only supported under Linux right now")
else:
click.echo("Starting the server via \"octoprint\" is deprecated, "
"please use \"octoprint serve\" from now on.")
+60 -25
View File
@@ -29,6 +29,7 @@ def client_commands():
@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)
@@ -36,11 +37,29 @@ def client_commands():
@click.option("--https", is_flag=True)
@click.option("--prefix", type=click.STRING)
@click.pass_context
def client(ctx, host, port, httpuser, httppass, https, prefix):
def client(ctx, apikey, host, port, httpuser, httppass, https, prefix):
"""Basic API client."""
try:
ctx.obj.settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
octoprint_client.init_client(ctx.obj.settings, https=https, httpuser=httpuser, httppass=httppass, host=host, port=port, prefix=prefix)
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"])
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)
@@ -60,27 +79,33 @@ def log_response(response, status_code=True, body=True, headers=False):
@client.command("get")
@click.argument("path")
def get(path):
@click.option("--timeout", type=float, default=None)
@click.pass_context
def get(ctx, path, timeout):
"""Performs a GET request against the specified server path."""
r = octoprint_client.get(path)
r = ctx.obj.client.get(path, timeout=timeout)
log_response(r)
@client.command("post_json")
@click.argument("path")
@click.argument("data", type=JsonStringParamType())
def post_json(path, data):
@click.option("--timeout", type=float, default=None)
@click.pass_context
def post_json(ctx, path, data, timeout):
"""POSTs JSON data to the specified server path."""
r = octoprint_client.post_json(path, data)
r = ctx.obj.client.post_json(path, data, timeout=timeout)
log_response(r)
@client.command("patch_json")
@click.argument("path")
@click.argument("data", type=JsonStringParamType())
def patch_json(path, data):
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
@click.pass_context
def patch_json(ctx, path, data, timeout):
"""PATCHes JSON data to the specified server path."""
r = octoprint_client.patch(path, data, encoding="json")
r = ctx.obj.client.patch(path, data, encoding="json", timeout=timeout)
log_response(r)
@@ -89,8 +114,10 @@ def patch_json(path, data):
@click.argument("file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True))
@click.option("--json", is_flag=True)
@click.option("--yaml", is_flag=True)
def post_from_file(path, file_path, json_flag, yaml_flag):
"""POSTs JSON data to the specified server path."""
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
@click.pass_context
def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout):
"""POSTs JSON data to the specified server path, taking the data from the specified file."""
if json_flag or yaml_flag:
if json_flag:
with open(file_path, "rb") as fp:
@@ -100,12 +127,12 @@ def post_from_file(path, file_path, json_flag, yaml_flag):
with open(file_path, "rb") as fp:
data = yaml.safe_load(fp)
r = octoprint_client.post_json(path, data)
r = ctx.obj.client.post_json(path, data, timeout=timeout)
else:
with open(file_path, "rb") as fp:
data = fp.read()
r = octoprint_client.post(path, data)
r = ctx.obj.client.post(path, data, timeout=timeout)
log_response(r)
@@ -117,13 +144,15 @@ def post_from_file(path, file_path, json_flag, yaml_flag):
@click.option("--int", "-i", "int_params", multiple=True, nargs=2, type=click.Tuple([unicode, int]))
@click.option("--float", "-f", "float_params", multiple=True, nargs=2, type=click.Tuple([unicode, float]))
@click.option("--bool", "-b", "bool_params", multiple=True, nargs=2, type=click.Tuple([unicode, bool]))
def command(path, command, str_params, int_params, float_params, bool_params):
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
@click.pass_context
def command(ctx, path, command, str_params, int_params, float_params, bool_params, timeout):
"""Sends a JSON command to the specified server path."""
data = dict()
params = str_params + int_params + float_params + bool_params
for param in params:
data[param[0]] = param[1]
r = octoprint_client.post_command(path, command, additional=data)
r = ctx.obj.client.post_command(path, command, additional=data, timeout=timeout)
log_response(r, body=False)
@@ -133,26 +162,32 @@ def command(path, command, str_params, int_params, float_params, bool_params):
@click.option("--parameter", "-P", "params", multiple=True, nargs=2, type=click.Tuple([unicode, unicode]))
@click.option("--file-name", type=click.STRING)
@click.option("--content-type", type=click.STRING)
def upload(path, file_path, params, file_name, content_type):
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
@click.pass_context
def upload(ctx, path, file_path, params, file_name, content_type, timeout):
"""Uploads the specified file to the specified server path."""
data = dict()
for param in params:
data[param[0]] = param[1]
r = octoprint_client.upload(path, file_path, additional=data, file_name=file_name, content_type=content_type)
r = ctx.obj.client.upload(path, file_path,
additional=data, file_name=file_name, content_type=content_type, timeout=timeout)
log_response(r)
@client.command("delete")
@click.argument("path")
def delete(path):
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
@click.pass_context
def delete(ctx, path, timeout):
"""Sends a DELETE request to the specified server path."""
r = octoprint_client.delete(path)
r = ctx.obj.client.delete(path, timeout=timeout)
log_response(r)
@client.command("listen")
def listen():
@click.pass_context
def listen(ctx):
def on_connect(ws):
click.echo(">>> Connected!")
@@ -168,11 +203,11 @@ def listen():
def on_message(ws, message_type, message_payload):
click.echo("Message: {}, Payload: {}".format(message_type, json.dumps(message_payload)))
socket = octoprint_client.connect_socket(on_connect=on_connect,
on_close=on_close,
on_error=on_error,
on_heartbeat=on_heartbeat,
on_message=on_message)
socket = ctx.obj.client.create_socket(on_connect=on_connect,
on_close=on_close,
on_error=on_error,
on_heartbeat=on_heartbeat,
on_message=on_message)
click.echo(">>> Waiting for client to exit")
try:
+3 -1
View File
@@ -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>`_
@@ -204,7 +206,7 @@ class OctoPrintDevelCommands(click.MultiCommand):
click.echo("This doesn't look like an OctoPrint plugin folder")
sys.exit(1)
self.command_caller.call([sys.executable, "setup.py", "develop"], cwd=path)
self.command_caller.call([sys.executable, "-m", "pip", "install", "-e", "."], cwd=path)
return command
+2 -2
View File
@@ -150,8 +150,8 @@ def serve_command(ctx, **kwargs):
allow_root, logging, verbosity, safe_mode)
if sys.platform == "linux2":
# we only support daemon mode under Linux
if sys.platform != "win32" and sys.platform != "darwin":
# we do not support daemon mode under windows or macosx
@server_commands.command(name="daemon")
@server_options
+11 -2
View File
@@ -53,6 +53,11 @@ class Events(object):
METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished"
METADATA_STATISTICS_UPDATED = "MetadataStatisticsUpdated"
FILE_ADDED = "FileAdded",
FILE_REMOVED = "FileRemoved",
FOLDER_ADDED = "FolderAdded",
FOLDER_REMOVED = "FolderRemoved",
# SD Upload
TRANSFER_STARTED = "TransferStarted"
TRANSFER_DONE = "TransferDone"
@@ -79,6 +84,7 @@ class Events(object):
EJECT = "Eject"
E_STOP = "EStop"
POSITION_UPDATE = "PositionUpdate"
TOOL_CHANGE = "ToolChange"
REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived"
# Timelapse
@@ -350,7 +356,10 @@ class CommandTrigger(GenericEventListener):
else:
commandExecutioner(command)
except subprocess.CalledProcessError as e:
self._logger.warn("Command failed with return code %i: %s" % (e.returncode, str(e)))
if debug:
self._logger.warn("Command failed with return code {}: {}".format(e.returncode, str(e)))
else:
self._logger.warn("Command failed with return code {}, enable debug logging on target 'octoprint.events' for details".format(e.returncode))
except:
self._logger.exception("Command failed")
@@ -368,7 +377,7 @@ class CommandTrigger(GenericEventListener):
def _processCommand(self, command, payload):
"""
Performs string substitutions in the command string based on a couple of current parameters.
Performs string substitutions in the command string based on a few current parameters.
The following substitutions are currently supported:
+69 -9
View File
@@ -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")
@@ -409,30 +411,47 @@ class FileManager(object):
queue_entry = self._analysis_queue_entry(destination, path)
self._analysis_queue.dequeue(queue_entry)
file_path = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
path_in_storage = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
if analysis is None:
queue_entry = self._analysis_queue_entry(destination, file_path, printer_profile=printer_profile)
queue_entry = self._analysis_queue_entry(destination, path_in_storage, printer_profile=printer_profile)
if queue_entry:
self._analysis_queue.enqueue(queue_entry, high_priority=True)
else:
self._add_analysis_result(destination, path, analysis)
_, name = self._storage(destination).split_path(path_in_storage)
eventManager().fire(Events.FILE_ADDED, dict(storage=destination,
path=path_in_storage,
name=name,
type=get_file_type(name)))
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
return file_path
return path_in_storage
def remove_file(self, destination, path):
queue_entry = self._analysis_queue_entry(destination, path)
self._analysis_queue.dequeue(queue_entry)
self._storage(destination).remove_file(path)
_, name = self._storage(destination).split_path(path)
eventManager().fire(Events.FILE_REMOVED, dict(storage=destination,
path=path,
name=name,
type=get_file_type(name)))
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def copy_file(self, destination, source, dst):
path = self._storage(destination).copy_file(source, dst)
if not self.has_analysis(destination, path):
queue_entry = self._analysis_queue_entry(destination, path)
path_in_storage = self._storage(destination).copy_file(source, dst)
if not self.has_analysis(destination, path_in_storage):
queue_entry = self._analysis_queue_entry(destination, path_in_storage)
if queue_entry:
self._analysis_queue.enqueue(queue_entry)
_, name = self._storage(destination).split_path(path_in_storage)
eventManager().fire(Events.FILE_ADDED, dict(storage=destination,
path=path_in_storage,
name=name,
type=get_file_type(name)))
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def move_file(self, destination, source, dst):
@@ -443,23 +462,52 @@ class FileManager(object):
queue_entry = self._analysis_queue_entry(destination, path)
if queue_entry:
self._analysis_queue.enqueue(queue_entry)
source_path_in_storage = self._storage(destination).path_in_storage(source)
_, source_name = self._storage(destination).split_path(source_path_in_storage)
dst_path_in_storage = self._storage(destination).path_in_storage(dst)
_, dst_name = self._storage(destination).split_path(dst_path_in_storage)
eventManager().fire(Events.FILE_REMOVED, dict(storage=destination,
path=source_path_in_storage,
name=source_name,
type=get_file_type(source_name)))
eventManager().fire(Events.FILE_ADDED, dict(storage=destination,
path=dst_path_in_storage,
name=dst_name,
type=get_file_type(dst_name)))
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def add_folder(self, destination, path, ignore_existing=True):
folder_path = self._storage(destination).add_folder(path, ignore_existing=ignore_existing)
path_in_storage = self._storage(destination).add_folder(path, ignore_existing=ignore_existing)
_, name = self._storage(destination).split_path(path_in_storage)
eventManager().fire(Events.FOLDER_ADDED, dict(storage=destination,
path=path_in_storage,
name=name))
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
return folder_path
return path_in_storage
def remove_folder(self, destination, path, recursive=True):
self._analysis_queue.dequeue_folder(destination, path)
self._analysis_queue.pause()
self._storage(destination).remove_folder(path, recursive=recursive)
self._analysis_queue.resume()
_, name = self._storage(destination).split_path(path)
eventManager().fire(Events.FOLDER_REMOVED, dict(storage=destination,
path=path,
name=name))
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def copy_folder(self, destination, source, dst):
self._storage(destination).copy_folder(source, dst)
path_in_storage = self._storage(destination).copy_folder(source, dst)
self._determine_analysis_backlog(destination, self._storage(destination), root=dst)
_, name = self._storage(destination).split_path(path_in_storage)
eventManager().fire(Events.FOLDER_ADDED, dict(storage=destination,
path=path_in_storage,
name=name))
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def move_folder(self, destination, source, dst):
@@ -468,6 +516,18 @@ class FileManager(object):
self._storage(destination).move_folder(source, dst)
self._determine_analysis_backlog(destination, self._storage(destination), root=dst)
self._analysis_queue.resume()
source_path_in_storage = self._storage(destination).path_in_storage(source)
_, source_name = self._storage(destination).split_path(source_path_in_storage)
dst_path_in_storage = self._storage(destination).path_in_storage(destination)
_, dst_name = self._storage(destination).split_path(dst_path_in_storage)
eventManager().fire(Events.FOLDER_REMOVED, dict(storage=destination,
path=source_path_in_storage,
name=source_name))
eventManager().fire(Events.FOLDER_ADDED, dict(storage=destination,
path=dst_path_in_storage,
name=dst_name))
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def has_analysis(self, destination, path):
+81 -27
View File
@@ -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"]
interpreter = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "util", "gcodeInterpreter.py"))
command = [sys.executable, interpreter, "--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
+14 -13
View File
@@ -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
@@ -29,7 +31,6 @@ class StorageInterface(object):
Interface of storage adapters for OctoPrint.
"""
@property
def analysis_backlog(self):
"""
@@ -155,7 +156,9 @@ class StorageInterface(object):
def add_folder(self, path, ignore_existing=True):
"""
Adds a folder as ``path``. The ``path`` will be sanitized.
Adds a folder as ``path``
The ``path`` will be sanitized.
:param string path: the path of the new folder
:param bool ignore_existing: if set to True, no error will be raised if the folder to be added already exists
@@ -165,7 +168,7 @@ class StorageInterface(object):
def remove_folder(self, path, recursive=True):
"""
Removes the folder at ``path``.
Removes the folder at ``path``
:param string path: the path of the folder to remove
:param bool recursive: if set to True, contained folders and files will also be removed, otherwise and error will
@@ -212,7 +215,9 @@ class StorageInterface(object):
def remove_file(self, path):
"""
Removes the file at ``path``. Will also take care of deleting the corresponding entries
Removes the file at ``path``
Will also take care of deleting the corresponding entries
in the metadata and deleting all links pointing to the file.
:param string path: path of the file to remove
@@ -486,6 +491,9 @@ class LocalFileStorage(StorageInterface):
return self.analysis_backlog_for_path()
def analysis_backlog_for_path(self, path=None):
if path:
path = self.sanitize_path(path)
for entry in self._analysis_backlog_generator(path):
yield entry
@@ -663,16 +671,9 @@ class LocalFileStorage(StorageInterface):
# save the file's hash to the metadata of the folder
file_hash = self._create_hash(file_path)
metadata = self._get_metadata_entry(path, name, default=dict())
metadata_dirty = False
if not "hash" in metadata or metadata["hash"] != file_hash:
metadata["hash"] = file_hash
metadata_dirty = True
if "analysis" in metadata:
del metadata["analysis"]
metadata_dirty = True
if metadata_dirty:
self._update_metadata_entry(path, name, metadata)
# hash changed -> throw away old metadata
self._update_metadata_entry(path, name, dict(hash=file_hash))
# process any links that were also provided for adding to the file
if not links:
+28 -10
View File
@@ -45,7 +45,8 @@ def _validate_plugin(phase, plugin_info):
return True
def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None, plugin_disabled_list=None,
plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None):
plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None,
plugin_checked_module_dependencies=None):
"""
Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager`
singleton.
@@ -71,6 +72,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
plugin_obsolete_hooks (list): A list of hooks that have been declared obsolete. Plugins implementing them will
not be enabled since they might depend on functionality that is no longer available.
plugin_validators (list): A list of additional plugin validators through which to process each plugin.
plugin_checked_module_dependencies (dict): A dictionary of package name-version-pairs for which to enable
dependency checking during plugin loading.
Returns:
PluginManager: A fully initialized :class:`~octoprint.plugin.core.PluginManager` instance to be used for plugin
@@ -104,7 +107,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"]
@@ -113,6 +117,9 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
plugin_validators = [_validate_plugin]
else:
plugin_validators.append(_validate_plugin)
if plugin_checked_module_dependencies is None:
from octoprint import __version__ as octoprint_version
plugin_checked_module_dependencies = dict(octoprint=octoprint_version)
_instance = PluginManager(plugin_folders,
plugin_types,
@@ -121,7 +128,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
plugin_disabled_list=plugin_disabled_list,
plugin_restart_needing_hooks=plugin_restart_needing_hooks,
plugin_obsolete_hooks=plugin_obsolete_hooks,
plugin_validators=plugin_validators)
plugin_validators=plugin_validators,
plugin_checked_module_dependencies=plugin_checked_module_dependencies)
else:
raise ValueError("Plugin Manager not initialized yet")
return _instance
@@ -239,7 +247,7 @@ class PluginSettings(object):
"""
The :class:`PluginSettings` class is the interface for plugins to their own or globally defined settings.
It provides a couple of convenience methods for directly accessing plugin settings via the regular
It provides some convenience methods for directly accessing plugin settings via the regular
:class:`octoprint.settings.Settings` interfaces as well as means to access plugin specific folder locations.
All getter and setter methods will ensure that plugin settings are stored in their correct location within the
@@ -263,13 +271,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 +297,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)
+133 -32
View File
@@ -31,6 +31,7 @@ import os
import imp
from collections import defaultdict, namedtuple, OrderedDict
import logging
import fnmatch
import pkg_resources
import pkginfo
@@ -40,6 +41,8 @@ try:
except ImportError:
from scandir import scandir
from octoprint.util.version import version_matches_spec
EntryPointOrigin = namedtuple("EntryPointOrigin", "type, entry_point, module_name, package_name, package_version")
FolderOrigin = namedtuple("FolderOrigin", "type, folder")
@@ -71,6 +74,9 @@ class PluginInfo(object):
attr_description = '__plugin_description__'
""" Module attribute from which to retrieve the plugin's description. """
attr_disabling_discouraged = '__plugin_disabling_discouraged__'
""" Module attribute from which to retrieve the reason why disabling the plugin is discouraged. Only effective if ``self.bundled`` is True. """
attr_version = '__plugin_version__'
""" Module attribute from which to retrieve the plugin's version. """
@@ -294,6 +300,19 @@ class PluginInfo(object):
"""
return self._get_instance_attribute(self.__class__.attr_description, default=self._description)
@property
def disabling_discouraged(self):
"""
Reason why disabling of this plugin is discouraged. Only evaluated for bundled plugins! Will be taken from
the disabling_discouraged attribute of the plugin module as defined in :attr:`attr_disabling_discouraged` if
available. False if unset or plugin not bundled.
Returns:
str or None: Reason why disabling this plugin is discouraged (only for bundled plugins)
"""
return self._get_instance_attribute(self.__class__.attr_disabling_discouraged, default=False) if self.bundled \
else False
@property
def version(self):
"""
@@ -447,7 +466,7 @@ class PluginManager(object):
def __init__(self, plugin_folders, plugin_types, plugin_entry_points, logging_prefix=None,
plugin_disabled_list=None, plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None,
plugin_validators=None):
plugin_validators=None, plugin_checked_module_dependencies=None):
self.logger = logging.getLogger(__name__)
if logging_prefix is None:
@@ -468,6 +487,7 @@ class PluginManager(object):
self.plugin_restart_needing_hooks = plugin_restart_needing_hooks
self.plugin_obsolete_hooks = plugin_obsolete_hooks
self.plugin_validators = plugin_validators
self.plugin_dependency_checks = plugin_checked_module_dependencies
self.logging_prefix = logging_prefix
self.enabled_plugins = dict()
@@ -555,6 +575,10 @@ class PluginManager(object):
key = entry.name
elif entry.is_file() and entry.name.endswith(".py"):
key = entry.name[:-3] # strip off the .py extension
if key.startswith("__"):
# might be an __init__.py in our plugins folder, or something else we don't want
# to handle
continue
else:
continue
@@ -598,6 +622,20 @@ class PluginManager(object):
module_name = entry_point.module_name
version = entry_point.dist.version
if self.plugin_dependency_checks:
requires = entry_point.dist.requires()
missing_requirements = []
for require in requires:
if require.key in self.plugin_dependency_checks:
available_version = self.plugin_dependency_checks[require.key]
spec = str(require.specifier)
if not version_matches_spec(available_version, spec, package=require.key, base=True):
missing_requirements.append("{}{}".format(require.key, spec))
if missing_requirements:
self.logger.warn("Plugin \"{}\" is missing requirements, skipping it: {}".format(key, ", ".join(missing_requirements)))
continue
if key in existing or key in result or (ignore_uninstalled and key in self.marked_plugins["uninstalled"]):
# plugin is already defined or marked as uninstalled, ignore it
continue
@@ -640,7 +678,8 @@ class PluginManager(object):
return result
def _import_plugin_from_module(self, key, folder=None, module_name=None, name=None, version=None, summary=None, author=None, url=None, license=None):
def _import_plugin_from_module(self, key, folder=None, module_name=None, name=None, version=None, summary=None,
author=None, url=None, license=None):
# TODO error handling
try:
if folder:
@@ -926,45 +965,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():
+15 -6
View File
@@ -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):
"""
@@ -531,7 +532,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
provided request by calling :meth:`~octoprint.plugin.UiPlugin.will_handle_ui` with the Flask
`Request <http://flask.pocoo.org/docs/0.10/api/#flask.Request>`_ object as
parameter. If you plugin returns `True` here, OctoPrint will next call
:meth:`~octoprint.plugin.UiPlugin.on_ui_render` with a couple of parameters like
:meth:`~octoprint.plugin.UiPlugin.on_ui_render` with a few parameters like
- again - the Flask Request object and the render keyword arguments as
used by the default OctoPrint web interface. For more information see below.
@@ -582,7 +583,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
it only gets re-rendered if the request demands that (by having no-cache headers set) or if
the cache gets invalidated otherwise.
In order to be able to do that, the ``UiPlugin`` offers overriding a couple of cache specific
In order to be able to do that, the ``UiPlugin`` offers overriding some cache specific
methods used for figuring out the source files whose modification time to use for cache invalidation
as well as override possibilities for ETag and LastModified calculation. Additionally there are
methods to allow persisting call parameters to allow for preemptively caching your UI during
@@ -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
@@ -1038,7 +1039,7 @@ class SimpleApiPlugin(OctoPrintPlugin):
mixin offers.
Use this mixin if all you need to do is return some kind of dynamic data to your plugin from the backend
and/or want to react to simple commands which boil down to a type of command and a couple of flat parameters
and/or want to react to simple commands which boil down to a type of command and a few flat parameters
supplied with it.
The simple API constructed by OctoPrint for you will be made available under ``/api/plugin/<plugin identifier>/``.
@@ -1377,6 +1378,14 @@ class SettingsPlugin(OctoPrintPlugin):
Of course, you are always free to completely override both :func:`on_settings_load` and :func:`on_settings_save` if the
default implementations do not fit your requirements.
.. warning::
Make sure to protect sensitive information stored by your plugin that only logged in administrators (or users)
should have access to via :meth:`~octoprint.plugin.SettingsPlugin.get_settings_restricted_paths`. OctoPrint will
return its settings on the REST API even to anonymous clients, but will filter out fields it know are restricted,
therefore you **must** make sure that you specify sensitive information accordingly to limit access as required!
.. attribute:: _settings
The :class:`~octoprint.plugin.PluginSettings` instance to use for accessing the plugin's settings. Injected by
@@ -1548,8 +1557,8 @@ class SettingsPlugin(OctoPrintPlugin):
field="field"),
path=dict(to=dict(never=dict(return="return"))))
def get_settings_restricted_path(self):
return dict(admin=[["some", "admin_only", "path], ["another", "admin_only", "path"],
def get_settings_restricted_paths(self):
return dict(admin=[["some", "admin_only", "path"], ["another", "admin_only", "path"],],
user=[["some", "user_only", "path"],],
never=[["path", "to", "never", "return"],])
+1
View File
@@ -0,0 +1 @@
# make our plugins testable
+138 -40
View File
@@ -18,6 +18,8 @@ import threading
import feedparser
import flask
from collections import OrderedDict
from octoprint.server import admin_permission
from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag
from flask.ext.babel import gettext
@@ -39,40 +41,75 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
# StartupPlugin
def on_after_startup(self):
self._fetch_all_channels()
# decouple channel fetching from server startup
def fetch_data():
self._fetch_all_channels()
thread = threading.Thread(target=fetch_data)
thread.daemon = True
thread.start()
# SettingsPlugin
def get_settings_defaults(self):
return dict(channels=dict(_important=dict(name="Important OctoPrint Announcements",
priority=1,
type="rss",
url="http://octoprint.org/feeds/important.xml"),
_news=dict(name="OctoPrint News",
priority=2,
type="rss",
url="http://octoprint.org/feeds/news.xml"),
_releases=dict(name="OctoPrint Release Announcements",
settings = dict(channels=dict(_important=dict(name="Important Announcements",
description="Important announcements about OctoPrint.",
priority=1,
type="rss",
url="http://octoprint.org/feeds/important.xml"),
_releases=dict(name="Release Announcements",
description="Announcements of new releases and release candidates of OctoPrint.",
priority=2,
type="rss",
url="http://octoprint.org/feeds/releases.xml"),
_blog=dict(name="On the OctoBlog",
description="Development news, community spotlights, OctoPrint On Air episodes and more from the official OctoBlog.",
priority=2,
type="rss",
url="http://octoprint.org/feeds/releases.xml"),
_spotlight=dict(name="OctoPrint Community Spotlights",
priority=2,
type="rss",
url="http://octoprint.org/feeds/spotlight.xml"),
_octopi=dict(name="OctoPi Announcements",
priority=2,
type="rss",
url="http://octoprint.org/feeds/octopi.xml"),
_plugins=dict(name="New Plugins in the Repository",
priority=2,
type="rss",
url="http://plugins.octoprint.org/feed.xml")),
enabled_channels=[],
forced_channels=["_important"],
ttl=6*60,
display_limit=3,
summary_limit=300)
url="http://octoprint.org/feeds/octoblog.xml"),
_plugins=dict(name="New Plugins in the Repository",
description="Announcements of new plugins released on the official Plugin Repository.",
priority=2,
type="rss",
url="http://plugins.octoprint.org/feed.xml"),
_octopi=dict(name="OctoPi News",
description="News around OctoPi, the Raspberry Pi image including OctoPrint.",
priority=2,
type="rss",
url="http://octoprint.org/feeds/octopi.xml")),
enabled_channels=[],
forced_channels=["_important"],
channel_order=["_important", "_releases", "_blog", "_plugins", "_octopi"],
ttl=6*60,
display_limit=3,
summary_limit=300)
settings["enabled_channels"] = settings["channels"].keys()
return settings
def get_settings_version(self):
return 1
def on_settings_migrate(self, target, current):
if current is None:
# first version had different default feeds and only _important enabled by default
channels = self._settings.get(["channels"])
if "_news" in channels:
del channels["_news"]
if "_spotlight" in channels:
del channels["_spotlight"]
self._settings.set(["channels"], channels)
enabled = self._settings.get(["enabled_channels"])
add_blog = False
if "_news" in enabled:
add_blog = True
enabled.remove("_news")
if "_spotlight" in enabled:
add_blog = True
enabled.remove("_spotlight")
if add_blog and not "_blog" in enabled:
enabled.append("_blog")
self._settings.set(["enabled_channels"], enabled)
# AssetPlugin
@@ -97,7 +134,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
def get_channel_data(self):
from octoprint.settings import valid_boolean_trues
result = dict()
result = []
force = flask.request.values.get("force", "false") in valid_boolean_trues
@@ -118,15 +155,17 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
last = entries[0]["published"]
self._mark_read_until(key, last)
result[key] = dict(channel=data["name"],
result.append(dict(key=key,
channel=data["name"],
url=data["url"],
description=data.get("description", ""),
priority=data.get("priority", 2),
enabled=key in enabled or key in forced,
forced=key in forced,
data=entries,
unread=unread)
unread=unread))
return flask.jsonify(result)
return flask.jsonify(channels=result)
def etag():
import hashlib
@@ -141,11 +180,11 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
return hash.hexdigest()
def condition():
return check_etag(etag())
def condition(lm, etag):
return check_etag(etag)
return with_revalidation_checking(etag_factory=lambda *args, **kwargs: etag(),
condition=lambda *args, **kwargs: condition(),
condition=lambda lm, etag: condition(lm, etag),
unless=lambda: force)(view)()
@octoprint.plugin.BlueprintPlugin.route("/channels/<channel>", methods=["POST"])
@@ -208,9 +247,13 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
with self._cached_channel_configs_mutex:
if self._cached_channel_configs is None or force:
configs = self._settings.get(["channels"], merged=True)
result = dict()
for key, config in configs.items():
if "url" not in config or "name" not in config:
order = self._settings.get(["channel_order"])
all_keys = order + [key for key in sorted(configs.keys()) if not key in order]
result = OrderedDict()
for key in all_keys:
config = configs.get(key)
if config is None or "url" not in config or "name" not in config:
# strip invalid entries
continue
result[self._slugify(key)] = config
@@ -287,7 +330,8 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
url = config["url"]
try:
start = time.time()
r = requests.get(url)
r = requests.get(url, timeout=30)
r.raise_for_status()
self._logger.info(u"Loaded channel {} from {} in {:.2}s".format(key, config["url"], time.time() - start))
except Exception as e:
self._logger.exception(
@@ -322,7 +366,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
return dict(title=entry["title"],
title_without_tags=_strip_tags(entry["title"]),
summary=entry["summary"],
summary=_lazy_images(entry["summary"]),
summary_without_images=_strip_images(entry["summary"]),
published=published,
link=entry["link"],
@@ -337,8 +381,57 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
_image_tag_re = re.compile(r'<img.*?/?>')
def _strip_images(text):
"""
>>> _strip_images(u"<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>")
u"<a href='test.html'>I'm a link</a> and this is an image: "
>>> _strip_images(u"One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">")
u'One and two and three and four '
>>> _strip_images(u"No images here")
u'No images here'
"""
return _image_tag_re.sub('', text)
def _replace_images(text, callback):
"""
>>> callback = lambda img: "foobar"
>>> _replace_images(u"<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>", callback)
u"<a href='test.html'>I'm a link</a> and this is an image: foobar"
>>> _replace_images(u"One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">", callback)
u'One foobar and two foobar and three foobar and four foobar'
"""
result = text
for match in _image_tag_re.finditer(text):
tag = match.group(0)
replaced = callback(tag)
result = result.replace(tag, replaced)
return result
_image_src_re = re.compile(r'src=(?P<quote>[\'"]*)(?P<src>.*?)(?P=quote)(?=\s+|>)')
def _lazy_images(text, placeholder=None):
"""
>>> _lazy_images(u"<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>")
u'<a href=\\'test.html\\'>I\\'m a link</a> and this is an image: <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src=\\'foo.jpg\\' alt=\\'foo\\'>'
>>> _lazy_images(u"<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>", placeholder="ph.png")
u'<a href=\\'test.html\\'>I\\'m a link</a> and this is an image: <img src="ph.png" data-src=\\'foo.jpg\\' alt=\\'foo\\'>'
>>> _lazy_images(u"One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">", placeholder="ph.png")
u'One <img src="ph.png" data-src="one.jpg"> and two <img src="ph.png" data-src=\\'two.jpg\\' > and three <img src="ph.png" data-src=three.jpg> and four <img src="ph.png" data-src="four.png" alt="four">'
>>> _lazy_images(u"No images here")
u'No images here'
"""
if placeholder is None:
# 1px transparent gif
placeholder = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
def callback(img_tag):
match = _image_src_re.search(img_tag)
if match is not None:
src = match.group("src")
quote = match.group("quote")
quoted_src = quote + src + quote
img_tag = img_tag.replace(match.group(0), 'src="{}" data-src={}'.format(placeholder, quoted_src))
return img_tag
return _replace_images(text, callback)
def _strip_tags(text):
"""
@@ -374,4 +467,9 @@ def _strip_tags(text):
__plugin_name__ = "Announcement Plugin"
__plugin_author__ = "Gina Häußge"
__plugin_description__ = "Announcements all around OctoPrint"
__plugin_disabling_discouraged__ = gettext("Without this plugin you might miss important announcements "
"regarding security or other critical issues concerning OctoPrint.")
__plugin_license__ = "AGPLv3"
__plugin_implementation__ = AnnouncementPlugin()
@@ -1 +1 @@
table td.settings_plugin_announcements_channels_name,table th.settings_plugin_announcements_channels_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_announcements_channels_actions,table th.settings_plugin_announcements_channels_actions{text-align:center;width:80px}table td.settings_plugin_announcements_channels_actions a,table th.settings_plugin_announcements_channels_actions a{text-decoration:none;color:#000}table td.settings_plugin_announcements_channels_actions a.disabled,table th.settings_plugin_announcements_channels_actions a.disabled{color:#ccc;cursor:default}#plugin_announcements_dialog .unread{font-weight:700}#plugin_announcements_dialog article{padding-right:20px}#plugin_announcements_dialog article.read{opacity:.5}#plugin_announcements_dialog article.read:hover{opacity:1}#plugin_announcements_dialog article .actions{background-color:#f5f5f5;border-radius:2px;padding:2px 5px;margin-top:5px}#plugin_announcements_dialog article .actions .markread{float:right}#plugin_announcements_dialog article .actions a{color:#000}
table td.settings_plugin_announcements_channels_name,table th.settings_plugin_announcements_channels_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_announcements_channels_actions,table th.settings_plugin_announcements_channels_actions{text-align:center;width:80px}table td.settings_plugin_announcements_channels_actions a,table th.settings_plugin_announcements_channels_actions a{text-decoration:none;color:#000}table td.settings_plugin_announcements_channels_actions a.disabled,table th.settings_plugin_announcements_channels_actions a.disabled{color:#ccc;cursor:default}#plugin_announcements_dialog .unread{font-weight:700}#plugin_announcements_dialog article{padding-right:20px}#plugin_announcements_dialog article.read{opacity:.5}#plugin_announcements_dialog article.read:hover{opacity:1}#plugin_announcements_dialog article .actions{background-color:#f5f5f5;border-radius:2px;padding:2px 5px;margin-top:5px}#plugin_announcements_dialog article .actions .markread{float:right}#plugin_announcements_dialog article .actions a{color:#000}#plugin_announcements_dialog .modal-footer .configurelink{float:left}
@@ -40,7 +40,7 @@ $(function() {
};
self.toggleButtonCss = function(data) {
var icon = data.enabled ? "icon-circle" : "icon-circle-blank";
var icon = data.enabled ? "fa fa-circle" : "fa fa-circle-o";
var disabled = (self.enableToggle(data)) ? "" : " disabled";
return icon + disabled;
@@ -120,12 +120,13 @@ $(function() {
};
self.fromResponse = function(data) {
if (!self.loginState.isAdmin()) return;
var currentTab = $("li.active a", self.announcementDialogTabs).attr("href");
var unread = 0;
var channels = [];
_.each(data, function(value, key) {
value.key = key;
_.each(data.channels, function(value) {
value.last = value.data.length ? value.data[0].published : undefined;
value.count = value.data.length;
unread += value.unread;
@@ -140,6 +141,11 @@ $(function() {
};
self.showAnnouncementDialog = function(channel) {
if (!self.loginState.isAdmin()) return;
// lazy load images that still need lazy-loading
$("#plugin_announcements_dialog_content article img").lazyload();
self.announcementDialogContent.scrollTop(0);
if (!self.announcementDialog.hasClass("in")) {
@@ -172,6 +178,8 @@ $(function() {
};
self.displayAnnouncements = function(channels) {
if (!self.loginState.isAdmin()) return;
var displayLimit = self.settings.settings.plugins.announcements.display_limit();
var maxLength = self.settings.settings.plugins.announcements.summary_limit();
@@ -222,7 +230,7 @@ $(function() {
}
var rest = newItems.length - displayedItems.length;
var text = "<ul>";
var text = "<ul style='margin-top: 10px; margin-bottom: 10px'>";
_.each(displayedItems, function(item) {
var limitedSummary = stripParagraphs(item.summary_without_images.trim());
if (limitedSummary.length > maxLength) {
@@ -239,6 +247,8 @@ $(function() {
text += gettext(_.sprintf("... and %(rest)d more.", {rest: rest}));
}
text += "<small>" + gettext("You can edit your announcement subscriptions under Settings > Announcements.") + "</small>";
var options = {
title: channel,
text: text,
@@ -248,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();
}
}]
},
@@ -284,10 +294,25 @@ $(function() {
});
};
self.hideAnnouncements = function() {
_.each(self.channelNotifications, function(notification, key) {
notification.remove();
});
self.channelNotifications = {};
};
self.configureAnnouncements = function() {
self.settings.show("settings_plugin_announcements");
};
self.onUserLoggedIn = function() {
self.retrieveData();
};
self.onUserLoggedOut = function() {
self.hideAnnouncements();
};
self.onStartup = function() {
self.announcementDialog = $("#plugin_announcements_dialog");
self.announcementDialogContent = $("#plugin_announcements_dialog_content");
@@ -53,4 +53,10 @@ table {
}
}
}
.modal-footer {
.configurelink {
float: left;
}
}
}
@@ -11,7 +11,7 @@
<!-- ko foreach: {data: channels.items, afterAdd: setupTabLink} -->
<!-- ko if: $data.enabled || $data.forced -->
<li>
<a data-toggle="tab" target="_blank" data-bind="text: $data.channel + ' (' + $data.unread + '/' + $data.count + ')', attr: {href: '#plugin_announcements_dialog_channel_' + $data.key}, css: {unread: $data.unread}"></a>
<a data-toggle="tab" target="_blank" data-bind="text: $data.channel, attr: {href: '#plugin_announcements_dialog_channel_' + $data.key, title: $data.description}, css: {unread: $data.unread}"></a>
</li>
<!-- /ko -->
<!-- /ko -->
@@ -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,6 +40,7 @@
</div>
</div>
<div class="modal-footer">
<button class="btn btn-block" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</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>
@@ -10,7 +10,8 @@
<tbody data-bind="foreach: channels.paginatedItems">
<tr>
<td class="settings_plugin_announcements_channels_name">
<div data-bind="text: channel, css: {muted: !enabled}"></div>
<div data-bind="css: {muted: !enabled}"><strong data-bind="text: channel"></strong></div>
<div data-bind="text: description, css: {muted: !enabled}"></div>
<div><small class="muted" data-bind="text: url">&nbsp;</small></div>
</td>
<td class="settings_plugin_announcements_channels_actions">
@@ -31,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>
+14 -7
View File
@@ -49,9 +49,12 @@ 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
@@ -74,7 +77,7 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
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")
@@ -119,7 +122,7 @@ 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")
@@ -134,7 +137,7 @@ 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")
@@ -145,7 +148,7 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
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")
@@ -172,5 +175,9 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
__plugin_name__ = "Core Wizard"
__plugin_author__ = "Gina Häußge"
__plugin_description__ = "Provides wizard dialogs for core components and functionality"
__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to perform "
"setup steps that might be required after an update.")
__plugin_license__ = "AGPLv3"
__plugin_implementation__ = CoreWizardPlugin()
@@ -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";
@@ -113,18 +130,29 @@ $(function() {
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();
+14 -6
View File
@@ -17,6 +17,7 @@ import octoprint.slicing
import octoprint.settings
from octoprint.util.paths import normalize as normalize_path
from octoprint.util import to_unicode
from .profile import Profile
from .profile import GcodeFlavors
@@ -236,7 +237,8 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
self._save_profile(path, new_profile, allow_overwrite=allow_overwrite)
def do_slice(self, model_path, printer_profile, machinecode_path=None, profile_path=None, position=None, on_progress=None, on_progress_args=None, on_progress_kwargs=None):
def do_slice(self, model_path, printer_profile, machinecode_path=None, profile_path=None, position=None,
on_progress=None, on_progress_args=None, on_progress_kwargs=None):
try:
with self._job_mutex:
if not profile_path:
@@ -258,7 +260,10 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
if not on_progress_kwargs:
on_progress_kwargs = dict()
self._cura_logger.info(u"### Slicing %s to %s using profile stored at %s" % (model_path, machinecode_path, profile_path))
self._cura_logger.info(u"### Slicing {} to {} using profile stored at {}"
.format(to_unicode(model_path, errors="replace"),
to_unicode(machinecode_path, errors="replace"),
to_unicode(profile_path, errors="replace")))
executable = normalize_path(self._settings.get(["cura_engine"]))
if not executable:
@@ -293,7 +298,9 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
args += ["-s", "%s=%s" % (k, str(v))]
args += ["-o", machinecode_path, model_path]
self._logger.info(u"Running %r in %s" % (" ".join(args), working_dir))
self._logger.info(u"Running {!r} in {}".format(u" ".join(map(lambda x: to_unicode(x, errors="replace"),
args)),
working_dir))
import sarge
p = sarge.run(args, cwd=working_dir, async=True, stdout=sarge.Capture(), stderr=sarge.Capture())
@@ -314,7 +321,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
p.commands[0].poll()
continue
line = octoprint.util.to_unicode(line, errors="replace")
line = to_unicode(line, errors="replace")
self._cura_logger.debug(line.strip())
if on_progress is not None:
@@ -437,7 +444,8 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
command = self._slicing_commands[machinecode_path]
if command is not None:
command.terminate()
self._logger.info(u"Cancelled slicing of %s" % machinecode_path)
self._logger.info(u"Cancelled slicing of {}"
.format(to_unicode(machinecode_path, errors="replace")))
def _load_profile(self, path):
import yaml
@@ -505,7 +513,7 @@ def _get_usage_from_length(filament_length, filament_diameter):
__plugin_name__ = "CuraEngine (<= 15.04)"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura"
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/cura.html"
__plugin_description__ = "Adds support for slicing via CuraEngine versions up to and including version 15.04 from within OctoPrint"
__plugin_license__ = "AGPLv3"
__plugin_implementation__ = CuraPlugin()
+2
View File
@@ -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"
+104 -39
View File
@@ -25,11 +25,35 @@ $(function() {
self.profileAllowOverwrite = ko.observable(true);
self.profileMakeDefault = ko.observable(false);
// make sure to update form data if any of the metadata changes
self.profileName.subscribe(function() { self.copyProfileMetadata(); });
self.profileDisplayName.subscribe(function() {
if (self.profileDisplayName()) {
self.placeholderName(self._sanitize(self.profileDisplayName()).toLowerCase());
}
self.copyProfileMetadata();
});
self.profileDescription.subscribe(function() { self.copyProfileMetadata(); });
self.profileAllowOverwrite.subscribe(function() { self.copyProfileMetadata(); });
self.profileMakeDefault.subscribe(function() { self.copyProfileMetadata(); });
self.unconfiguredCuraEngine = ko.observable();
self.unconfiguredSlicingProfile = ko.observable();
self.uploadDialog = $("#settings_plugin_cura_import");
self.uploadElement = $("#settings-cura-import");
self.uploadButton = $("#settings-cura-import-start");
self.uploadData = ko.observable(undefined);
self.uploadBusy = ko.observable(false);
self.uploadEnabled = ko.pureComputed(function() {
return self.fieldsEnabled();
});
self.fieldsEnabled = ko.pureComputed(function() {
return self.uploadData() && !self.uploadBusy()
&& (self.profileName() || self.placeholderName())
&& (self.profileDisplayName() || self.placeholderDisplayName())
&& (self.profileDescription() || self.placeholderDescription());
});
self.profiles = new ItemListHelper(
"plugin_cura_profiles",
@@ -66,6 +90,53 @@ $(function() {
return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_");
};
self.performUpload = function() {
if (self.uploadData()) {
self.uploadData().submit();
}
};
self.copyProfileMetadata = function(form) {
form = form || (self.uploadData() ? self.uploadData().formData : {});
if (self.profileName() !== undefined) {
form["name"] = self.profileName();
} else if (self.placeholderName() !== undefined) {
form["name"] = self.placeholderName();
}
if (self.profileDisplayName() !== undefined) {
form["displayName"] = self.profileDisplayName();
} else if (self.placeholderDisplayName() !== undefined) {
form["displayName"] = self.placeholderDisplayName();
}
if (self.profileDescription() !== undefined) {
form["description"] = self.profileDescription();
} else if (self.placeholderDescription() !== undefined) {
form["description"] = self.placeholderDescription();
}
if (self.profileMakeDefault()) {
form["default"] = true;
}
return form;
};
self.clearUpload = function() {
self.uploadData(undefined);
self.fileName(undefined);
self.placeholderName(undefined);
self.placeholderDisplayName(undefined);
self.placeholderDescription(undefined);
self.profileName(undefined);
self.profileDisplayName(undefined);
self.profileDescription(undefined);
self.profileAllowOverwrite(true);
self.profileMakeDefault(false);
};
self.uploadElement.fileupload({
dataType: "json",
maxNumberOfFiles: 1,
@@ -73,6 +144,11 @@ $(function() {
headers: OctoPrint.getRequestHeaders(),
add: function(e, data) {
if (data.files.length == 0) {
// no files? ignore
return false;
}
if (self.uploadData()) {
// data already defined? ignore (should never happen)
return false;
}
@@ -83,41 +159,22 @@ $(function() {
self.placeholderDisplayName(name);
self.placeholderDescription("Imported from " + self.fileName() + " on " + formatDate(new Date().getTime() / 1000));
self.uploadButton.unbind("click");
self.uploadButton.on("click", function() {
var form = {
allowOverwrite: self.profileAllowOverwrite()
};
var form = {
allowOverwrite: self.profileAllowOverwrite()
};
data.formData = self.copyProfileMetadata(form);
if (self.profileName() !== undefined) {
form["name"] = self.profileName();
}
if (self.profileDisplayName() !== undefined) {
form["displayName"] = self.profileDisplayName();
}
if (self.profileDescription() !== undefined) {
form["description"] = self.profileDescription();
}
if (self.profileMakeDefault()) {
form["default"] = true;
}
data.formData = form;
data.submit();
});
self.uploadData(data);
},
submit: function(e, data) {
self.copyProfileMetadata();
self.uploadBusy(true);
},
done: function(e, data) {
self.fileName(undefined);
self.placeholderName(undefined);
self.placeholderDisplayName(undefined);
self.placeholderDescription(undefined);
self.profileName(undefined);
self.profileDisplayName(undefined);
self.profileDescription(undefined);
self.profileAllowOverwrite(true);
self.profileMakeDefault(false);
self.uploadBusy(false);
self.clearUpload();
$("#settings_plugin_cura_import").modal("hide");
self.uploadDialog.modal("hide");
self.requestData();
self.slicingViewModel.requestData();
}
@@ -160,12 +217,9 @@ $(function() {
});
};
self.showImportProfileDialog = function(makeDefault) {
if (makeDefault == undefined) {
makeDefault = _.filter(self.profiles.items(), function(profile) { profile.isdefault() }).length == 0;
}
self.profileMakeDefault(makeDefault);
$("#settings_plugin_cura_import").modal("show");
self.showImportProfileDialog = function() {
self.clearUpload();
self.uploadDialog.modal("show");
};
self.testEnginePath = function() {
@@ -207,7 +261,18 @@ $(function() {
self.onBeforeBinding = function () {
self.settings = self.settingsViewModel.settings;
//self.requestData();
};
self.onAllBound = function() {
self.uploadDialog.on("hidden", function(event) {
if (event.target.id == "settings_plugin_cura_import") {
self.clearUpload();
}
});
};
self.onSettingsShown = function() {
self.requestData();
};
self.onSettingsHidden = function() {
@@ -20,31 +20,31 @@
<div class="control-group">
<label class="control-label">{{ _('Identifier') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: profileName, attr: {placeholder: placeholderName}">
<input type="text" class="input-block-level" data-bind="value: profileName, attr: {placeholder: placeholderName}, enable: fieldsEnabled, css: {disabled: !fieldsEnabled()}">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Name') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: profileDisplayName, attr: {placeholder: placeholderDisplayName}">
<input type="text" class="input-block-level" data-bind="value: profileDisplayName, valueUpdate: 'afterkeydown', attr: {placeholder: placeholderDisplayName}, enable: fieldsEnabled, css: {disabled: !fieldsEnabled()}">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Description') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: profileDescription, attr: {placeholder: placeholderDescription}">
<input type="text" class="input-block-level" data-bind="value: profileDescription, attr: {placeholder: placeholderDescription}, enable: fieldsEnabled, css: {disabled: !fieldsEnabled()}">
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<label class="checkbox" data-bind="enable: fieldsEnabled, css: {disabled: !fieldsEnabled()}">
<input type="checkbox" data-bind="checked: profileMakeDefault"> {{ _('Make default profile') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<label class="checkbox" data-bind="enable: fieldsEnabled, css: {disabled: !fieldsEnabled()}">
<input type="checkbox" data-bind="checked: profileAllowOverwrite"> {{ _('Overwrite existing file') }}
</label>
</div>
@@ -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" id="settings-cura-import-start">{{ _('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>&nbsp;|&nbsp;<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>&nbsp;|&nbsp;<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>
+4 -1
View File
@@ -12,6 +12,7 @@ The SSDP/UPNP implementations has been largely inspired by https://gist.github.c
import logging
import os
import flask
from flask.ext.babel import gettext
from builtins import range
import octoprint.plugin
@@ -25,8 +26,10 @@ except:
__plugin_name__ = "Discovery"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Discovery"
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/discovery.html"
__plugin_description__ = "Makes the OctoPrint instance discoverable via Bonjour/Avahi/Zeroconf and uPnP"
__plugin_disabling_discouraged__ = gettext("Without this plugin your OctoPrint instance will no longer be "
"discoverable on the network via Bonjour and uPnP.")
__plugin_license__ = "AGPLv3"
def __plugin_load__():
+347 -117
View File
@@ -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
@@ -13,9 +14,11 @@ from octoprint.settings import valid_boolean_trues
from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag
from octoprint.server import admin_permission, VERSION
from octoprint.util.pip import LocalPipCaller, UnknownPip
from octoprint.util.version import parse_version, version_matches_any_spec
from flask import jsonify, make_response
from flask.ext.babel import gettext
from collections import OrderedDict
import logging
import sarge
@@ -24,6 +27,10 @@ import requests
import re
import os
import pkg_resources
import copy
import dateutil.parser
import time
import threading
class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin,
@@ -35,10 +42,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
ARCHIVE_EXTENSIONS = (".zip", ".tar.gz", ".tgz", ".tar")
OPERATING_SYSTEMS = dict(windows=["win32"],
linux=["linux2"],
macos=["darwin"])
linux=lambda x: x.startswith("linux"),
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()
@@ -53,12 +63,19 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._repository_cache_path = None
self._repository_cache_ttl = 0
self._notices = dict()
self._notices_available = False
self._notices_cache_path = None
self._notices_cache_ttl = 0
self._console_logger = None
def initialize(self):
self._console_logger = logging.getLogger("octoprint.plugins.pluginmanager.console")
self._repository_cache_path = os.path.join(self.get_plugin_data_folder(), "plugins.json")
self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60
self._notices_cache_path = os.path.join(self.get_plugin_data_folder(), "notices.json")
self._notices_cache_ttl = self._settings.get_int(["notices_ttl"]) * 60
self._pip_caller = LocalPipCaller(force_user=self._settings.get_boolean(["pip_force_user"]))
self._pip_caller.on_log_call = self._log_call
@@ -73,7 +90,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
##~~ StartupPlugin
def on_startup(self, host, port):
def on_after_startup(self):
from octoprint.logging.handlers import CleaningTimedRotatingFileHandler
console_logging_handler = CleaningTimedRotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="console"), when="D", backupCount=3)
console_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
@@ -83,7 +100,14 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._console_logger.setLevel(logging.DEBUG)
self._console_logger.propagate = False
self._repository_available = self._fetch_repository_from_disk()
# 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()
##~~ SettingsPlugin
@@ -91,6 +115,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
return dict(
repository="http://plugins.octoprint.org/plugins.json",
repository_ttl=24*60,
notices="http://plugins.octoprint.org/notices.json",
notices_ttl=6*60,
pip_args=None,
pip_force_user=False,
dependency_links=False,
@@ -101,6 +127,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60
self._notices_cache_ttl = self._settings.get_int(["notices_ttl"]) * 60
self._pip_caller.force_user = self._settings.get_boolean(["pip_force_user"])
##~~ AssetPlugin
@@ -192,6 +219,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
if refresh_repository:
self._repository_available = self._refresh_repository()
refresh_notices = request.values.get("refresh_notices", "false") in valid_boolean_trues
if refresh_notices:
self._notices_available = self._refresh_notices()
def view():
return jsonify(plugins=self._get_plugins(),
repository=dict(
@@ -217,6 +248,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
hash.update(repr(self._get_plugins()))
hash.update(str(self._repository_available))
hash.update(repr(self._repository_plugins))
hash.update(str(self._notices_available))
hash.update(repr(self._notices))
hash.update(repr(safe_mode))
return hash.hexdigest()
@@ -225,7 +258,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
return with_revalidation_checking(etag_factory=lambda *args, **kwargs: etag(),
condition=lambda *args, **kwargs: condition(),
unless=lambda: refresh_repository)(view)()
unless=lambda: refresh_repository or refresh_notices)(view)()
def on_api_command(self, command, data):
if not admin_permission.can():
@@ -240,7 +273,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
plugin_name = data["plugin"] if "plugin" in data else None
return self.command_install(url=url,
force="force" in data and data["force"] in valid_boolean_trues,
dependency_links="dependency_links" in data and data["dependency_links"] in valid_boolean_trues,
dependency_links="dependency_links" in data
and data["dependency_links"] in valid_boolean_trues,
reinstall=plugin_name)
elif command == "uninstall":
@@ -261,37 +295,84 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
def command_install(self, url=None, path=None, force=False, reinstall=None, dependency_links=False):
if url is not None:
pip_args = ["install", sarge.shell_quote(url)]
source = url
source_type = "url"
already_installed_check = lambda line: url in line
elif path is not None:
pip_args = ["install", sarge.shell_quote(path)]
path = os.path.abspath(path)
path_url = "file://" + path
if os.sep != "/":
# windows gets special handling
path = path.replace(os.sep, "/").lower()
path_url = "file:///" + path
source = path
source_type = "path"
already_installed_check = lambda line: path_url in line.lower() # lower case in case of windows
else:
raise ValueError("Either URL or path must be provided")
self._logger.info("Installing plugin from {}".format(source))
pip_args = ["install", sarge.shell_quote(source)]
if dependency_links or self._settings.get_boolean(["dependency_links"]):
pip_args.append("--process-dependency-links")
all_plugins_before = self._plugin_manager.find_plugins()
all_plugins_before = self._plugin_manager.find_plugins(existing=dict())
already_installed_string = "Requirement already satisfied (use --upgrade to upgrade)"
success_string = "Successfully installed"
failure_string = "Could not install"
try:
returncode, stdout, stderr = self._call_pip(pip_args)
# pip's output for a package that is already installed looks something like any of these:
#
# Requirement already satisfied (use --upgrade to upgrade): OctoPrint-Plugin==1.0 from \
# https://example.com/foobar.zip in <lib>
# Requirement already satisfied (use --upgrade to upgrade): OctoPrint-Plugin in <lib>
# Requirement already satisfied (use --upgrade to upgrade): OctoPrint-Plugin==1.0 from \
# file:///tmp/foobar.zip in <lib>
# Requirement already satisfied (use --upgrade to upgrade): OctoPrint-Plugin==1.0 from \
# file:///C:/Temp/foobar.zip in <lib>
#
# If we detect any of these matching what we just tried to install, we'll need to trigger a second
# install with reinstall flags.
if not force and any(map(lambda x: x.strip().startswith(already_installed_string) and already_installed_check(x),
stdout)):
self._logger.info("Plugin to be installed from {} was already installed, forcing a reinstall".format(source))
self._log_message("Looks like the plugin was already installed. Forcing a reinstall.")
force = True
except:
self._logger.exception("Could not install plugin from %s" % url)
return make_response("Could not install plugin from URL, see the log for more details", 500)
else:
if force:
# We don't use --upgrade here because that will also happily update all our dependencies - we'd rather
# do that in a controlled manner
pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"]
try:
returncode, stdout, stderr = self._call_pip(pip_args)
except:
self._logger.exception("Could not install plugin from %s" % url)
return make_response("Could not install plugin from URL, see the log for more details", 500)
self._logger.exception("Could not install plugin from {}".format(source))
return make_response("Could not install plugin from source {}, see the log for more details"
.format(source), 500)
try:
result_line = filter(lambda x: x.startswith(success_string) or x.startswith(failure_string), stdout)[-1]
result_line = filter(lambda x: x.startswith(success_string) or x.startswith(failure_string),
stdout)[-1]
except IndexError:
result = dict(result=False, reason="Could not parse output from pip")
self._logger.error("Installing the plugin from {} failed, could not parse output from pip. "
"See plugin_pluginmanager_console.log for generated output".format(source))
result = dict(result=False,
source=source,
source_type=source_type,
reason="Could not parse output from pip, see plugin_pluginmanager_console.log "
"for generated output")
self._send_result_notification("install", result)
return jsonify(result)
@@ -304,8 +385,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
# Successfully installed OctoPrint-Plugin Dependency-One Dependency-Two
# Cleaning up...
#
# So we'll need to fetch the "Successfully installed" line, strip the "Successfully" part, then split by whitespace
# and strip to get all installed packages.
# So we'll need to fetch the "Successfully installed" line, strip the "Successfully" part, then split
# by whitespace and strip to get all installed packages.
#
# We then need to iterate over all known plugins and see if either the package name or the package name plus
# version number matches one of our installed packages. If it does, that's our installed plugin.
@@ -317,58 +398,57 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
result_line = result_line.strip()
if not result_line.startswith(success_string):
result = dict(result=False, reason="Pip did not report successful installation")
self._logger.error("Installing the plugin from {} failed, pip did not report successful installation"
.format(source))
result = dict(result=False,
source=source,
source_type=source_type,
reason="Pip did not report successful installation")
self._send_result_notification("install", result)
return jsonify(result)
installed = map(lambda x: x.strip(), result_line[len(success_string):].split(" "))
all_plugins_after = self._plugin_manager.find_plugins(existing=dict(), ignore_uninstalled=False)
for key, plugin in all_plugins_after.items():
if plugin.origin is None or plugin.origin.type != "entry_point":
continue
package_name = plugin.origin.package_name
package_version = plugin.origin.package_version
versioned_package = "{package_name}-{package_version}".format(**locals())
if package_name in installed or versioned_package in installed:
# exact match, we are done here
new_plugin_key = key
new_plugin = plugin
break
else:
# it might still be a version that got stripped by python's package resources, e.g. 1.4.5a0 => 1.4.5a
found = False
for inst in installed:
if inst.startswith(versioned_package):
found = True
break
if found:
new_plugin_key = key
new_plugin = plugin
break
else:
self._logger.warn("The plugin was installed successfully, but couldn't be found afterwards to initialize properly during runtime. Please restart OctoPrint.")
result = dict(result=True, url=url, needs_restart=True, needs_refresh=True, was_reinstalled=False, plugin="unknown")
new_plugin = self._find_installed_plugin(installed, plugins=all_plugins_after)
if new_plugin is None:
self._logger.warn("The plugin was installed successfully, but couldn't be found afterwards to "
"initialize properly during runtime. Please restart OctoPrint.")
result = dict(result=True,
source=source,
source_type=source_type,
needs_restart=True,
needs_refresh=True,
needs_reconnect=True,
was_reinstalled=False,
plugin="unknown")
self._send_result_notification("install", result)
return jsonify(result)
self._plugin_manager.reload_plugins()
needs_restart = self._plugin_manager.is_restart_needing_plugin(new_plugin) or new_plugin_key in all_plugins_before or reinstall is not None
needs_refresh = new_plugin.implementation and isinstance(new_plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
needs_restart = self._plugin_manager.is_restart_needing_plugin(new_plugin) \
or new_plugin.key in all_plugins_before \
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,
is_reinstall = self._plugin_manager.is_plugin_marked(new_plugin.key, "uninstalled")
self._plugin_manager.mark_plugin(new_plugin.key,
uninstalled=False,
installed=not is_reinstall and needs_restart)
self._plugin_manager.log_all_plugins()
result = dict(result=True, url=url, needs_restart=needs_restart, needs_refresh=needs_refresh, was_reinstalled=new_plugin_key in all_plugins_before or reinstall is not None, plugin=self._to_external_representation(new_plugin))
self._logger.info("The plugin was installed successfully: {}, version {}".format(new_plugin.name, new_plugin.version))
result = dict(result=True,
source=source,
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)
return jsonify(result)
@@ -423,6 +503,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,
@@ -448,7 +529,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_representation(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)
@@ -458,11 +543,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":
@@ -473,13 +560,51 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._logger.exception(u"Problem toggling enabled state of {name}: {reason}".format(name=plugin.key, reason=e.reason))
result = dict(result=False, reason=e.reason)
except octoprint.plugin.core.PluginNeedsRestart:
result = dict(result=True, needs_restart=True, needs_refresh=True, plugin=self._to_external_representation(plugin))
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, plugin=self._to_external_representation(plugin))
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)
return jsonify(result)
def _find_installed_plugin(self, packages, plugins=None):
if plugins is None:
plugins = self._plugin_manager.find_plugins(existing=dict(), ignore_uninstalled=False)
for key, plugin in plugins.items():
if plugin.origin is None or plugin.origin.type != "entry_point":
continue
package_name = plugin.origin.package_name
package_version = plugin.origin.package_version
versioned_package = "{package_name}-{package_version}".format(**locals())
if package_name in packages or versioned_package in packages:
# exact match, we are done here
return plugin
else:
# it might still be a version that got stripped by python's package resources, e.g. 1.4.5a0 => 1.4.5a
found = False
for inst in packages:
if inst.startswith(versioned_package):
found = True
break
if found:
return plugin
return None
def _send_result_notification(self, action, result):
notification = dict(type="result", action=action)
notification.update(result)
@@ -496,7 +621,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)
@@ -572,10 +697,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
return self._refresh_repository(repo_data=repo_data)
def _fetch_repository_from_url(self):
import requests
repository_url = self._settings.get(["repository"])
try:
r = requests.get(repository_url)
r = requests.get(repository_url, timeout=30)
r.raise_for_status()
self._logger.info("Loaded plugin repository data from {}".format(repository_url))
except Exception as e:
self._logger.exception("Could not fetch plugins from repository at {repository_url}: {message}".format(repository_url=repository_url, message=str(e)))
@@ -599,10 +724,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
return False
current_os = self._get_os()
octoprint_version = self._get_octoprint_version(base=True)
parsed_octoprint_version = self._get_octoprint_version()
def map_repository_entry(entry):
result = dict(entry)
result = copy.deepcopy(entry)
if not "follow_dependency_links" in result:
result["follow_dependency_links"] = False
@@ -614,7 +739,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
if "compatibility" in entry:
if "octoprint" in entry["compatibility"] and entry["compatibility"]["octoprint"] is not None and isinstance(entry["compatibility"]["octoprint"], (list, tuple)) and len(entry["compatibility"]["octoprint"]):
result["is_compatible"]["octoprint"] = self._is_octoprint_compatible(octoprint_version, entry["compatibility"]["octoprint"])
result["is_compatible"]["octoprint"] = self._is_octoprint_compatible(parsed_octoprint_version, entry["compatibility"]["octoprint"])
if "os" in entry["compatibility"] and entry["compatibility"]["os"] is not None and isinstance(entry["compatibility"]["os"], (list, tuple)) and len(entry["compatibility"]["os"]):
result["is_compatible"]["os"] = self._is_os_compatible(current_os, entry["compatibility"]["os"])
@@ -624,88 +749,160 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._repository_plugins = map(map_repository_entry, repo_data)
return True
def _fetch_notices_from_disk(self):
notice_data = None
if os.path.isfile(self._notices_cache_path):
import time
mtime = os.path.getmtime(self._notices_cache_path)
if mtime + self._notices_cache_ttl >= time.time() > mtime:
try:
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")
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):
notices_url = self._settings.get(["notices"])
try:
r = requests.get(notices_url, timeout=30)
r.raise_for_status()
self._logger.info("Loaded plugin notices data from {}".format(notices_url))
except Exception as e:
self._logger.exception("Could not fetch notices from {notices_url}: {message}".format(notices_url=notices_url, message=str(e)))
return None
notice_data = r.json()
try:
import json
with octoprint.util.atomic_write(self._notices_cache_path, "wb") as f:
json.dump(notice_data, f)
except Exception as e:
self._logger.exception("Error while saving notices to {}: {}".format(self._notices_cache_path, str(e)))
return notice_data
def _refresh_notices(self, notice_data=None):
if notice_data is None:
notice_data = self._fetch_notices_from_url()
if notice_data is None:
return False
notices = dict()
for notice in notice_data:
if not "plugin" in notice or not "text" in notice or not "date" in notice:
continue
key = notice["plugin"]
try:
parsed_date = dateutil.parser.parse(notice["date"])
notice["timestamp"] = parsed_date.timetuple()
except Exception as e:
self._logger.warn("Error while parsing date {!r} for plugin notice "
"of plugin {}, ignoring notice: {}".format(notice["date"], key, str(e)))
continue
if not key in notices:
notices[key] = []
notices[key].append(notice)
self._notices = notices
return True
def _is_octoprint_compatible(self, octoprint_version, compatibility_entries):
"""
Tests if the current ``octoprint_version`` is compatible to any of the provided ``compatibility_entries``.
"""
for octo_compat in compatibility_entries:
try:
if not any(octo_compat.startswith(c) for c in ("<", "<=", "!=", "==", ">=", ">", "~=", "===")):
octo_compat = ">={}".format(octo_compat)
spec_matcher = ("<", "<=", "!=", "==", ">=", ">", "~=", "===")
specs = map(lambda x: x if any(x.startswith(c) for c in spec_matcher) else ">={}".format(x),
compatibility_entries)
s = next(pkg_resources.parse_requirements("OctoPrint" + octo_compat))
if octoprint_version in s:
break
except:
self._logger.exception("Something is wrong with this compatibility string for OctoPrint: {}".format(octo_compat))
else:
return False
try:
return version_matches_any_spec(octoprint_version, specs, package="OctoPrint", base=True)
except:
self._logger.exception("Something is wrong with these compatibility specs: {!r}".format(specs))
return False
return True
def _is_os_compatible(self, current_os, compatibility_entries):
@staticmethod
def _is_os_compatible(current_os, compatibility_entries):
"""
Tests if the ``current_os`` matches any of the provided ``compatibility_entries``.
Tests if the ``current_os`` or ``sys.platform`` are blacklisted or whitelisted in ``compatibility_entries``
"""
return current_os in filter(lambda x: x in self.__class__.OPERATING_SYSTEMS.keys(), compatibility_entries)
if len(compatibility_entries) == 0:
# shortcut - no compatibility info means we are compatible
return True
def _get_os(self):
for identifier, platforms in self.__class__.OPERATING_SYSTEMS.items():
if sys.platform in platforms:
negative_entries = map(lambda x: x[1:], filter(lambda x: x.startswith("!"), compatibility_entries))
positive_entries = filter(lambda x: not x.startswith("!"), compatibility_entries)
negative_match = False
if negative_entries:
# check if we are blacklisted
negative_match = current_os in negative_entries or any(map(lambda x: sys.platform.startswith(x), negative_entries))
positive_match = True
if positive_entries:
# check if we are whitelisted
positive_match = current_os in positive_entries or any(map(lambda x: sys.platform.startswith(x), positive_entries))
return positive_match and not negative_match
@classmethod
def _get_os(cls):
for identifier, platforms in cls.OPERATING_SYSTEMS.items():
if (callable(platforms) and platforms(sys.platform)) or (isinstance(platforms, list) and sys.platform in platforms):
return identifier
else:
return "unknown"
return "unmapped"
def _get_octoprint_version_string(self):
return VERSION
def _get_octoprint_version(self, base=False):
octoprint_version_string = self._get_octoprint_version_string()
if "-" in octoprint_version_string:
octoprint_version_string = octoprint_version_string[:octoprint_version_string.find("-")]
octoprint_version = pkg_resources.parse_version(octoprint_version_string)
# A leading v is common in github release tags and old setuptools doesn't remove it. While OctoPrint's
# versions should never contains such a prefix, we'll make sure to have stuff behave the same
# regardless of setuptools version anyhow.
if octoprint_version and isinstance(octoprint_version, tuple) and octoprint_version[0].lower() == "*v":
octoprint_version = octoprint_version[1:]
if base:
if isinstance(octoprint_version, tuple):
# old setuptools
base_version = []
for part in octoprint_version:
if part.startswith("*"):
break
base_version.append(part)
base_version.append("*final")
octoprint_version = tuple(base_version)
else:
# new setuptools
octoprint_version = pkg_resources.parse_version(octoprint_version.base_version)
@staticmethod
def _get_octoprint_version_string():
from octoprint import __version__ as octoprint_version
return octoprint_version
@staticmethod
def _get_octoprint_version(base=False):
return parse_version(PluginManagerPlugin._get_octoprint_version_string(), base=base)
@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
hidden = self._settings.get(["hidden"])
result = []
for name, plugin in plugins.items():
if name in hidden:
for key, plugin in plugins.items():
if key in hidden:
continue
result.append(self._to_external_representation(plugin))
result.append(self._to_external_plugin(plugin))
return result
def _to_external_representation(self, plugin):
def _to_external_plugin(self, plugin):
return dict(
key=plugin.key,
name=plugin.name,
description=plugin.description,
disabling_discouraged=gettext(plugin.disabling_discouraged) if plugin.disabling_discouraged else False,
author=plugin.author,
version=plugin.version,
url=plugin.url,
@@ -719,12 +916,45 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
pending_disable=((plugin.enabled or getattr(plugin, "safe_mode_enabled", False)) and plugin.key in self._pending_disable),
pending_install=(self._plugin_manager.is_plugin_marked(plugin.key, "installed")),
pending_uninstall=(self._plugin_manager.is_plugin_marked(plugin.key, "uninstalled")),
origin=plugin.origin.type
origin=plugin.origin.type,
notifications = self._get_notifications(plugin)
)
def _get_notifications(self, plugin):
key = plugin.key
if not plugin.enabled:
return
if key not in self._notices:
return
octoprint_version = self._get_octoprint_version(base=True)
plugin_notifications = self._notices.get(key, [])
def filter_relevant(notification):
return "text" in notification and "date" in notification and \
("versions" not in notification or plugin.version in notification["versions"]) and \
("octoversions" not in notification or self._is_octoprint_compatible(octoprint_version, notification["octoversions"]))
def map_notification(notification):
return self._to_external_notification(key, notification)
return filter(lambda x: x is not None,
map(map_notification,
filter(filter_relevant,
plugin_notifications)))
def _to_external_notification(self, key, notification):
return dict(key=key,
date=time.mktime(notification["timestamp"]),
text=notification["text"],
link=notification.get("link"),
versions=notification.get("versions", []),
important=notification.get("important", False))
__plugin_name__ = "Plugin Manager"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Plugin-Manager"
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/pluginmanager.html"
__plugin_description__ = "Allows installing and managing OctoPrint plugins"
__plugin_license__ = "AGPLv3"
@@ -1 +1 @@
table th.settings_plugin_plugin_manager_plugins_name,table td.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}table th.settings_plugin_plugin_manager_plugins_actions,table td.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}table th.settings_plugin_plugin_manager_plugins_actions a,table td.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}table th.settings_plugin_plugin_manager_plugins_actions a.disabled,table td.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog .slimScrollDiv{margin-bottom:20px}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px;padding-right:10px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url("../img/repo_unavailable.png");text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{overflow:hidden;width:auto;height:300px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px;padding-right:10px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:bold}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
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}
@@ -10,7 +10,20 @@
};
OctoPrintPluginManagerClient.prototype.get = function(refresh, opts) {
return this.base.get(this.base.getSimpleApiUrl("pluginmanager") + ((refresh) ? "?refresh_repository=true" : ""), opts);
var refresh_repo, refresh_notices;
if (_.isPlainObject(refresh)) {
refresh_repo = refresh.repo || false;
refresh_notices = refresh.notices || false;
} else {
refresh_repo = refresh;
refresh_notices = false;
}
var query = [];
if (refresh_repo) query.push("refresh_repository=true");
if (refresh_notices) query.push("refresh_notices=true");
return this.base.get(this.base.getSimpleApiUrl("pluginmanager") + ((query.length) ? "?" + query.join("&") : ""), opts);
};
OctoPrintPluginManagerClient.prototype.getWithRefresh = function(opts) {
@@ -79,6 +92,8 @@ $(function() {
self.config_repositoryUrl = ko.observable();
self.config_repositoryTtl = ko.observable();
self.config_noticesUrl = ko.observable();
self.config_noticesTtl = ko.observable();
self.config_pipAdditionalArgs = ko.observable();
self.config_pipForceUser = ko.observable();
@@ -185,6 +200,20 @@ $(function() {
});
self.notifications = [];
self.noticeNotifications = [];
self.hiddenNoticeNotifications = {};
self.noticeCount = ko.observable(0);
self.noticeCountText = ko.pureComputed(function() {
var count = self.noticeCount();
if (count == 0) {
return gettext("There are no plugin notices. Great!");
} else if (count == 1) {
return gettext("There is a plugin notice for one of your installed plugins.");
} else {
return _.sprintf(gettext("There are %(count)d plugin notices for one or more of your installed plugins."), {count: count});
}
});
self.enableManagement = ko.pureComputed(function() {
return !self.printerState.isPrinting();
@@ -250,7 +279,13 @@ $(function() {
});
},
done: function(e, data) {
self._markDone();
var response = data.result;
if (response.result) {
self._markDone();
} else {
self._markDone(response.reason);
}
self.uploadButton.unbind("click");
self.uploadFilename(undefined);
},
@@ -261,7 +296,7 @@ $(function() {
type: "error",
hide: false
});
self._markDone();
self._markDone("Could not install plugin, unknown error.");
self.uploadButton.unbind("click");
self.uploadFilename(undefined);
}
@@ -280,19 +315,36 @@ $(function() {
return false;
};
self.fromResponse = function(data) {
self._fromPluginsResponse(data.plugins);
self._fromRepositoryResponse(data.repository);
self._fromPipResponse(data.pip);
self.fromResponse = function(data, options) {
self._fromPluginsResponse(data.plugins, options);
self._fromRepositoryResponse(data.repository, options);
self._fromPipResponse(data.pip, options);
self.safeMode(data.safe_mode || false);
};
self._fromPluginsResponse = function(data) {
self._fromPluginsResponse = function(data, options) {
var evalNotices = options.eval_notices || false;
var ignoreNoticeHidden = options.ignore_notice_hidden || false;
var ignoreNoticeIgnored = options.ignore_notice_ignored || false;
if (evalNotices) self._removeAllNoticeNotifications();
var installedPlugins = [];
var noticeCount = 0;
_.each(data, function(plugin) {
installedPlugins.push(plugin.key);
if (evalNotices && plugin.notifications && plugin.notifications.length) {
_.each(plugin.notifications, function(notification) {
noticeCount++;
if (!ignoreNoticeIgnored && self._isNoticeNotificationIgnored(plugin.key, notification.date)) return;
if (!ignoreNoticeHidden && self._isNoticeNotificationHidden(plugin.key, notification.date)) return;
self._showPluginNotification(plugin, notification);
});
}
});
if (evalNotices) self.noticeCount(noticeCount);
self.installedPlugins(installedPlugins);
self.plugins.updateItems(data);
};
@@ -324,13 +376,28 @@ $(function() {
}
};
self.requestData = function(includeRepo) {
self.requestData = function(options) {
if (!self.loginState.isAdmin()) {
return;
}
OctoPrint.plugins.pluginmanager.get(includeRepo)
.done(self.fromResponse);
if (!_.isPlainObject(options)) {
options = {
refresh_repo: options,
refresh_notices: false,
eval_notices: false
};
}
options.refresh_repo = options.refresh_repo || false;
options.refresh_notices = options.refresh_notices || false;
options.eval_notices = options.eval_notices || false;
OctoPrint.plugins.pluginmanager.get({repo: options.refresh_repo, notices: options.refresh_notices})
.done(function(data) {
self.fromResponse(data, options);
});
};
self.togglePlugin = function(data) {
@@ -344,7 +411,9 @@ $(function() {
if (data.key == "pluginmanager") return;
var onSuccess = self.requestData,
var onSuccess = function() {
self.requestData();
},
onError = function() {
new PNotify({
title: gettext("Something went wrong"),
@@ -360,9 +429,26 @@ $(function() {
.done(onSuccess)
.fail(onError);
} else {
OctoPrint.plugins.pluginmanager.disable(data.key)
.done(onSuccess)
.fail(onError);
var perform = function() {
OctoPrint.plugins.pluginmanager.disable(data.key)
.done(onSuccess)
.fail(onError);
};
if (data.disabling_discouraged) {
var message = _.sprintf(gettext("You are about to disable \"%(name)s\"."), {name: data.name})
+ "</p><p>" + data.disabling_discouraged;
showConfirmationDialog({
title: gettext("This is not recommended"),
message: message,
question: gettext("Do you still want to disable it?"),
cancel: gettext("Keep enabled"),
proceed: gettext("Disable anyway"),
onproceed: perform
})
} else {
perform();
}
}
};
@@ -418,32 +504,33 @@ $(function() {
}
self._markWorking(workTitle, workText);
var onSuccess = function() {
var onSuccess = function(response) {
if (response.result) {
self._markDone();
} else {
self._markDone(response.reason)
}
self.requestData();
self.installUrl("");
},
onError = function() {
self._markDone("Could not install plugin, unknown error, please consult octoprint.log for details");
new PNotify({
title: gettext("Something went wrong"),
text: gettext("Please consult octoprint.log for details"),
type: "error",
hide: false
});
},
onAlways = function() {
self._markDone();
};
if (reinstall) {
OctoPrint.plugins.pluginmanager.reinstall(reinstall, url, followDependencyLinks)
.done(onSuccess)
.fail(onError)
.always(onAlways);
.fail(onError);
} else {
OctoPrint.plugins.pluginmanager.install(url, followDependencyLinks)
.done(onSuccess)
.fail(onError)
.always(onAlways);
.fail(onError);
}
};
@@ -462,7 +549,9 @@ $(function() {
self._markWorking(gettext("Uninstalling plugin..."), _.sprintf(gettext("Uninstalling plugin \"%(name)s\""), {name: data.name}));
OctoPrint.plugins.pluginmanager.uninstall(data.key)
.done(self.requestData)
.done(function() {
self.requestData();
})
.fail(function() {
new PNotify({
title: gettext("Something went wrong"),
@@ -480,8 +569,23 @@ $(function() {
if (!self.loginState.isAdmin()) {
return;
}
self.requestData({refresh_repo: true});
};
self.requestData(true);
self.refreshNotices = function() {
if (!self.loginState.isAdmin()) {
return;
}
self.requestData({refresh_notices: true, eval_notices: true, ignore_notice_hidden: true, ignore_notice_ignored: true});
};
self.reshowNotices = function() {
if (!self.loginState.isAdmin()) {
return;
}
self.requestData({eval_notices: true, ignore_notice_hidden: true, ignore_notice_ignored: true});
};
self.showPluginSettings = function() {
@@ -502,6 +606,18 @@ $(function() {
repositoryTtl = null;
}
var notices = self.config_noticesUrl();
if (notices != undefined && notices.trim() == "") {
notices = null;
}
var noticesTtl;
try {
noticesTtl = parseInt(self.config_noticesTtl());
} catch (ex) {
noticesTtl = null;
}
var pipArgs = self.config_pipAdditionalArgs();
if (pipArgs != undefined && pipArgs.trim() == "") {
pipArgs = null;
@@ -512,6 +628,8 @@ $(function() {
pluginmanager: {
repository: repository,
repository_ttl: repositoryTtl,
notices: notices,
notices_ttl: noticesTtl,
pip_args: pipArgs,
pip_force_user: self.config_pipForceUser()
}
@@ -520,13 +638,15 @@ $(function() {
self.settingsViewModel.saveData(data, function() {
self.configurationDialog.modal("hide");
self._copyConfig();
self.refreshRepository();
self.requestData({refresh_repo: true, refresh_notices: true, eval_notices: true});
});
};
self._copyConfig = function() {
self.config_repositoryUrl(self.settingsViewModel.settings.plugins.pluginmanager.repository());
self.config_repositoryTtl(self.settingsViewModel.settings.plugins.pluginmanager.repository_ttl());
self.config_noticesUrl(self.settingsViewModel.settings.plugins.pluginmanager.notices());
self.config_noticesTtl(self.settingsViewModel.settings.plugins.pluginmanager.notices_ttl());
self.config_pipAdditionalArgs(self.settingsViewModel.settings.plugins.pluginmanager.pip_args());
self.config_pipForceUser(self.settingsViewModel.settings.plugins.pluginmanager.pip_force_user());
};
@@ -540,10 +660,10 @@ $(function() {
};
self.installButtonText = function(data) {
return self.isCompatible(data) ? (self.installed(data) ? gettext("Reinstall") : gettext("Install")) : gettext("Incompatible");
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) {
@@ -565,17 +685,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")
@@ -587,6 +711,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;
}
});
}
@@ -596,6 +723,7 @@ $(function() {
notification = PNotify.singleButtonNotify(options);
} else if (response.needs_refresh) {
var refreshClicked = false;
notification = PNotify.singleButtonNotify({
title: titleSuccess,
text: textReload,
@@ -604,6 +732,8 @@ $(function() {
buttons: [{
text: gettext("Reload now"),
click: function () {
if (refreshClicked) return;
refreshClicked = true;
location.reload(true);
}
}]
@@ -617,6 +747,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,
@@ -654,9 +793,14 @@ $(function() {
self.workingDialog.modal({keyboard: false, backdrop: "static", show: true});
};
self._markDone = function() {
self._markDone = function(error) {
self.working(false);
self.loglines.push({line: gettext("Done!"), stream: "message"});
if (error) {
self.loglines.push({line: gettext("Error!"), stream: "error"});
self.loglines.push({line: error, stream: "error"})
} else {
self.loglines.push({line: gettext("Done!"), stream: "message"});
}
self._scrollWorkingOutputToEnd();
};
@@ -670,7 +814,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-circle-o" : "fa fa-circle";
var disabled = (self.enableToggle(data)) ? "" : " disabled";
return icon + disabled;
@@ -689,13 +833,184 @@ $(function() {
}
};
self.showPluginNotifications = function(plugin) {
if (!plugin.notifications || plugin.notifications.length == 0) return;
self._removeAllNoticeNotificationsForPlugin(plugin.key);
_.each(plugin.notifications, function(notification) {
self._showPluginNotification(plugin, notification);
});
};
self.showPluginNotificationsLinkText = function(plugins) {
if (!plugins.notifications || plugins.notifications.length == 0) return;
var count = plugins.notifications.length;
var importantCount = _.filter(plugins.notifications, function(notification) { return notification.important }).length;
if (count > 1) {
if (importantCount) {
return _.sprintf(gettext("There are %(count)d notices (%(important)d marked as important) available regarding this plugin - click to show!"), {count: count, important: importantCount});
} else {
return _.sprintf(gettext("There are %(count)d notices available regarding this plugin - click to show!"), {count: count});
}
} else {
if (importantCount) {
return gettext("There is an important notice available regarding this plugin - click to show!");
} else {
return gettext("There is a notice available regarding this plugin - click to show!");
}
}
};
self._showPluginNotification = function(plugin, notification) {
var name = plugin.name;
var version = plugin.version;
var important = notification.important;
var link = notification.link;
var title;
if (important) {
title = _.sprintf(gettext("Important notice regarding plugin \"%(name)s\""), {name: name});
} else {
title = _.sprintf(gettext("Notice regarding plugin \"%(name)s\""), {name: name});
}
var text = "";
if (notification.versions && notification.versions.length > 0) {
var versions = _.map(notification.versions, function(v) { return (v == version) ? "<strong>" + v + "</strong>" : v; }).join(", ");
text += "<small>" + _.sprintf(gettext("Affected versions: %(versions)s"), {versions: versions}) + "</small>";
} else {
text += "<small>" + gettext("Affected versions: all") + "</small>";
}
text += "<p>" + notification.text + "</p>";
if (link) {
text += "<p><a href='" + link + "' target='_blank'>" + gettext("Read more...") + "</a></p>";
}
var beforeClose = function(notification) {
if (!self.noticeNotifications[plugin.key]) return;
self.noticeNotifications[plugin.key] = _.without(self.noticeNotifications[plugin.key], notification);
};
var options = {
title: title,
text: text,
type: (important) ? "error" : "notice",
before_close: beforeClose,
hide: false,
confirm: {
confirm: true,
buttons: [{
text: gettext("Later"),
click: function(notice) {
self._hideNoticeNotification(plugin.key, notification.date);
notice.remove();
notice.get().trigger("pnotify.cancel", notice);
}
}, {
text: gettext("Mark read"),
click: function(notice) {
self._ignoreNoticeNotification(plugin.key, notification.date);
notice.remove();
notice.get().trigger("pnotify.cancel", notice);
}
}]
},
buttons: {
sticker: false,
closer: false
}
};
if (!self.noticeNotifications[plugin.key]) {
self.noticeNotifications[plugin.key] = [];
}
self.noticeNotifications[plugin.key].push(new PNotify(options));
};
self._removeAllNoticeNotifications = function() {
_.each(_.keys(self.noticeNotifications), function(key) {
self._removeAllNoticeNotificationsForPlugin(key);
});
};
self._removeAllNoticeNotificationsForPlugin = function(key) {
if (!self.noticeNotifications[key] || !self.noticeNotifications[key].length) return;
_.each(self.noticeNotifications[key], function(notification) {
notification.remove();
});
};
self._hideNoticeNotification = function(key, date) {
if (!self.hiddenNoticeNotifications[key]) {
self.hiddenNoticeNotifications[key] = [];
}
if (!_.contains(self.hiddenNoticeNotifications[key], date)) {
self.hiddenNoticeNotifications[key].push(date);
}
};
self._isNoticeNotificationHidden = function(key, date) {
if (!self.hiddenNoticeNotifications[key]) return false;
return _.any(_.map(self.hiddenNoticeNotifications[key], function(d) { return date == d; }));
};
var noticeLocalStorageKey = "plugin.pluginmanager.seen_notices";
self._ignoreNoticeNotification = function(key, date) {
if (!Modernizr.localstorage)
return false;
if (!self.loginState.isAdmin())
return false;
var currentString = localStorage[noticeLocalStorageKey];
var current;
if (currentString === undefined) {
current = {};
} else {
current = JSON.parse(currentString);
}
if (!current[self.loginState.username()]) {
current[self.loginState.username()] = {};
}
if (!current[self.loginState.username()][key]) {
current[self.loginState.username()][key] = [];
}
if (!_.contains(current[self.loginState.username()][key], date)) {
current[self.loginState.username()][key].push(date);
localStorage[noticeLocalStorageKey] = JSON.stringify(current);
}
};
self._isNoticeNotificationIgnored = function(key, date) {
if (!Modernizr.localstorage)
return false;
if (localStorage[noticeLocalStorageKey] == undefined)
return false;
var knownData = JSON.parse(localStorage[noticeLocalStorageKey]);
if (!self.loginState.isAdmin())
return true;
var userData = knownData[self.loginState.username()];
if (userData === undefined)
return false;
return userData[key] && _.contains(userData[key], date);
};
self.onBeforeBinding = function() {
self.settings = self.settingsViewModel.settings;
};
self.onUserLoggedIn = function(user) {
if (user.admin) {
self.requestData();
self.requestData({eval_notices: true});
} else {
self.onUserLoggedOut();
}
@@ -754,7 +1069,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";
@@ -774,35 +1089,58 @@ $(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");
var url = "unknown";
if (data.hasOwnProperty("url")) {
url = data.url;
var source = "unknown";
if (data.hasOwnProperty("source")) {
source = data.source;
}
var sourceType = "unknown";
if (data.hasOwnProperty("source_type")) {
sourceType = data.source_type;
}
if (data.hasOwnProperty("reason")) {
if (data.was_reinstalled) {
textError = _.sprintf(gettext("Reinstalling the plugin from URL \"%(url)s\" failed: %(reason)s"), {reason: data.reason, url: url});
if (sourceType == "path") {
textError = _.sprintf(gettext("Reinstalling the plugin from file failed: %(reason)s"), {reason: data.reason});
} else {
textError = _.sprintf(gettext("Reinstalling the plugin from \"%(source)s\" failed: %(reason)s"), {reason: data.reason, source: source});
}
} else {
textError = _.sprintf(gettext("Installing the plugin from URL \"%(url)s\" failed: %(reason)s"), {reason: data.reason, url: url});
if (sourceType == "path") {
textError = _.sprintf(gettext("Installing the plugin from file failed: %(reason)s"), {reason: data.reason});
} else {
textError = _.sprintf(gettext("Installing the plugin from \"%(source)s\" failed: %(reason)s"), {reason: data.reason, source: source});
}
}
} else {
if (data.was_reinstalled) {
textError = _.sprintf(gettext("Reinstalling the plugin from URL \"%(url)s\" failed, please see the log for details."), {url: url});
if (sourceType == "path") {
textError = gettext("Reinstalling the plugin from file failed, please see the log for details.");
} else {
textError = _.sprintf(gettext("Reinstalling the plugin from \"%(source)s\" failed, please see the log for details."), {source: source});
}
} else {
textError = _.sprintf(gettext("Installing the plugin from URL \"%(url)s\" failed, please see the log for details."), {url: url});
if (sourceType == "path") {
textError = gettext("Installing the plugin from file failed, please see the log for details.");
} else {
textError = _.sprintf(gettext("Installing the plugin from \"%(source)s\" failed, please see the log for details."), {source: source});
}
}
}
@@ -815,6 +1153,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")) {
@@ -832,6 +1171,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")) {
@@ -849,6 +1189,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")) {
@@ -861,7 +1202,7 @@ $(function() {
return;
}
self._displayNotification(data, titleSuccess, textSuccess, textRestart, textReload, titleError, textError);
self._displayNotification(data, titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError);
self.requestData();
}
};
@@ -89,6 +89,11 @@ table {
font-weight: bold;
}
.error {
font-weight: bold;
color: #990000;
}
.stdout {
color: #333333;
}
@@ -25,7 +25,7 @@
{{ 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,17 +40,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></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">&nbsp;</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>&nbsp;</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>&nbsp;|&nbsp;<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>&nbsp;|&nbsp;<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>
@@ -72,8 +73,8 @@
<div class="muted" data-bind="visible: pipAvailable()">
<div>
<small>
<a href="#" 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>
@@ -86,12 +87,28 @@
</div>
</div>
<div class="muted">
<div>
<small>
<a href="javascript:void(0)" class="muted" onclick="$(this).children('i.toggle-arrow').toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')">
<i class="toggle-arrow fa fa-caret-right"></i> <span data-bind="text: noticeCountText"></span>
</a>
</small>
</div>
<div class="hide">
<small>
<!-- ko if: noticeCount() > 0 --><a href="javascript:void(0)" data-bind="click: function() { reshowNotices(); }">{{ _('Reshow current notices') }}</a> &middot;<!-- /ko -->
<a href="javascript:void(0)" data-bind="click: function() { refreshNotices(); }">{{ _('Refresh notices from repository') }}</a>
</small>
</div>
</div>
<div id="settings_plugin_pluginmanager_workingdialog" class="modal hide fade">
<div class="modal-header">
<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'}"></span><br></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>
@@ -111,16 +128,16 @@
{{ _('... 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>
@@ -137,15 +154,16 @@
<div><span data-bind="text: title"></span></div>
<div><small class="muted" data-bind="text: description">&nbsp;</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>&nbsp;</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>
</div>
@@ -191,7 +209,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">
@@ -237,6 +255,24 @@
</div>
</div>
<legend>{{ _('Notices configuration') }}</legend>
<div class="control-group" title="{{ _('URL of the Notices source to use. You should normally not have to change this.') }}">
<label class="control-label">{{ _('Notices URL') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: config_noticesUrl">
</div>
</div>
<div class="control-group" title="{{ _('How long to cache notices, in minutes. You should normally not have to change this.') }}">
<label class="control-label">{{ _('Notices cache TTL') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" class="input-mini" data-bind="value: config_noticesTtl">
<span class="add-on">min</span>
</div>
</div>
</div>
<legend>{{ _('pip configuration') }}</legend>
<div class="control-group" title="{{ _('Additional arguments for the pip command. You should normally not have to change this.') }}">
@@ -18,6 +18,7 @@ import hashlib
from . import version_checks, updaters, exceptions, util, cli
from flask.ext.babel import gettext
from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag
from octoprint.server import admin_permission, VERSION, REVISION, BRANCH
@@ -34,6 +35,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.WizardPlugin):
COMMIT_TRACKING_TYPES = ("github_commit", "bitbucket_commit")
def __init__(self):
self._update_in_progress = False
self._configured_checks_mutex = threading.Lock()
@@ -46,6 +50,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._version_cache_ttl = 0
self._version_cache_path = None
self._version_cache_dirty = False
self._version_cache_timestamp = None
self._console_logger = None
@@ -73,8 +78,14 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._console_logger.propagate = False
def on_after_startup(self):
# refresh cache now if necessary so it's faster once the user connects to the instance
self.get_current_versions()
# refresh cache now if necessary so it's faster once the user connects to the instance - but decouple it from
# the server startup
def fetch_data():
self.get_current_versions()
thread = threading.Thread(target=fetch_data)
thread.daemon = True
thread.start()
def _get_configured_checks(self):
with self._configured_checks_mutex:
@@ -113,7 +124,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
# This used to be part of the settings migration (version 2) due to a bug - it can't
# stay there though since it interferes with manual entries to the checks not
# originating from within a plugin. Hence we do that step now here.
if "type" not in effective_config or effective_config["type"] != "github_commit":
if "type" not in effective_config or effective_config["type"] not in self.COMMIT_TRACKING_TYPES:
deletables = ["current", "displayVersion"]
else:
deletables = []
@@ -152,6 +163,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
try:
with open(self._version_cache_path) as f:
data = yaml.safe_load(f)
timestamp = os.stat(self._version_cache_path).st_mtime
except:
self._logger.exception("Error while loading version cache from disk")
else:
@@ -174,6 +186,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._version_cache = data
self._version_cache_dirty = False
self._version_cache_timestamp = timestamp
self._logger.info("Loaded version cache from disk")
except:
self._logger.exception("Error parsing in version cache data")
@@ -190,6 +203,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
yaml.safe_dump(self._version_cache, stream=file_obj, default_flow_style=False, indent=" ", allow_unicode=True)
self._version_cache_dirty = False
self._version_cache_timestamp = time.time()
self._logger.info("Saved version cache to disk")
#~~ SettingsPlugin API
@@ -204,15 +218,21 @@ 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,
"check_providers": {},
"cache_ttl": 24 * 60,
"notify_users": True
}
def on_settings_load(self):
@@ -260,7 +280,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
def on_settings_save(self, data):
for key in self.get_settings_defaults():
if key in ("checks", "cache_ttl", "octoprint_checkout_folder", "octoprint_type", "octoprint_release_channel"):
if key in ("checks", "cache_ttl", "notify_user", "octoprint_checkout_folder", "octoprint_type", "octoprint_release_channel"):
continue
if key in data:
self._settings.set([key], data[key])
@@ -269,6 +289,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._settings.set_int(["cache_ttl"], data["cache_ttl"])
self._version_cache_ttl = self._settings.get_int(["cache_ttl"]) * 60
if "notify_users" in data:
self._settings.set_boolean(["notify_users"], data["notify_users"])
checks = self._get_configured_checks()
if "octoprint" in checks:
check = checks["octoprint"]
@@ -378,7 +401,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
configured_checks = self._settings.get(["checks"], incl_defaults=False)
if configured_checks is not None and "octoprint" in configured_checks:
octoprint_check = dict(configured_checks["octoprint"])
if "type" not in octoprint_check or octoprint_check["type"] != "github_commit":
if "type" not in octoprint_check or octoprint_check["type"] not in self.COMMIT_TRACKING_TYPES:
deletables=["current", "displayName", "displayVersion"]
else:
deletables=[]
@@ -454,7 +477,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
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))
information=information,
timestamp=self._version_cache_timestamp))
except exceptions.ConfigurationInvalid as e:
return flask.make_response("Update not properly configured, can't proceed: %s" % e.message, 500)
@@ -480,6 +504,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
hash.update(str(data["possible"]))
hash.update(",".join(targets))
hash.update(str(self._version_cache_timestamp))
return hash.hexdigest()
def condition():
@@ -825,7 +850,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._settings.load()
# persist the new version if necessary for check type
if check["type"] == "github_commit":
if check["type"] in self.COMMIT_TRACKING_TYPES:
dummy_default = dict(plugins=dict())
dummy_default["plugins"][self._identifier] = dict(checks=dict())
dummy_default["plugins"][self._identifier]["checks"][target] = dict(current=None)
@@ -847,7 +872,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))
@@ -882,7 +907,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
release_branches += [x["branch"] for x in check["prerelease_branches"]]
result["released_version"] = not release_branches or BRANCH in release_branches
if check["type"] == "github_commit":
if check["type"] in self.COMMIT_TRACKING_TYPES:
result["current"] = REVISION if REVISION else "unknown"
else:
result["current"] = VERSION
@@ -896,8 +921,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
@@ -907,14 +931,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
@@ -936,7 +959,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
# displayVersion AND current missing or None
result["displayVersion"] = u"unknown"
if check["type"] in ("github_commit",):
if check["type"] in self.COMMIT_TRACKING_TYPES:
result["current"] = check.get("current", None)
else:
result["current"] = check.get("current", check.get("displayVersion", None))
@@ -968,18 +991,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
raise exceptions.ConfigurationInvalid("no check type defined")
check_type = check["type"]
if check_type == "github_release":
return version_checks.github_release
elif check_type == "github_commit":
return version_checks.github_commit
elif check_type == "git_commit":
return version_checks.git_commit
elif check_type == "commandline":
return version_checks.commandline
elif check_type == "python_checker":
return version_checks.python_checker
else:
method = getattr(version_checks, check_type)
if method is None:
raise exceptions.UnknownCheckType()
else:
return method
def _get_update_method(self, target, check, valid_methods=None):
"""
@@ -1038,8 +1054,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
__plugin_name__ = "Software Update"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update"
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html"
__plugin_description__ = "Allows receiving update notifications and performing updates of OctoPrint and plugins"
__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to "
"update itself or any of your installed plugins which might put "
"your system at risk.")
__plugin_license__ = "AGPLv3"
def __plugin_load__():
global __plugin_implementation__
@@ -1 +1 @@
td.settings_plugin_softwareupdate_column_update{width:16px}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:bold}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:bold;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:bold;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}#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}
@@ -111,14 +111,21 @@ $(function() {
self.octoprintUnconfigured = ko.observable();
self.octoprintUnreleased = ko.observable();
self.cacheTimestamp = ko.observable();
self.cacheTimestampText = ko.pureComputed(function() {
return formatDate(self.cacheTimestamp());
});
self.config_cacheTtl = ko.observable();
self.config_notifyUsers = ko.observable();
self.config_checkoutFolder = ko.observable();
self.config_checkType = ko.observable();
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([]);
@@ -153,9 +160,20 @@ $(function() {
self.performCheck();
};
self._showPopup = function(options, eventListeners) {
self.onUserLoggedOut = function() {
self._closePopup();
self.popup = new PNotify(options);
};
self._showPopup = function(options, eventListeners, singleButtonNotify) {
singleButtonNotify = singleButtonNotify || false;
self._closePopup();
if (singleButtonNotify) {
self.popup = PNotify.singleButtonNotify(options);
} else {
self.popup = new PNotify(options);
}
if (eventListeners) {
var popupObj = self.popup.get();
@@ -186,12 +204,13 @@ $(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: {
softwareupdate: {
cache_ttl: parseInt(self.config_cacheTtl()),
notify_users: self.config_notifyUsers(),
octoprint_checkout_folder: self.config_checkoutFolder(),
octoprint_type: self.config_checkType(),
octoprint_release_channel: self.config_releaseChannel()
@@ -205,7 +224,7 @@ $(function() {
self.performCheck();
},
complete: function() {
$("i.icon-spinner", target).remove();
$("i.fa-spinner", target).remove();
},
sending: true
});
@@ -231,6 +250,7 @@ $(function() {
self.config_updateMethod(updateMethod);
self.config_cacheTtl(self.settings.settings.plugins.softwareupdate.cache_ttl());
self.config_notifyUsers(self.settings.settings.plugins.softwareupdate.notify_users());
self.config_checkoutFolder(self.settings.settings.plugins.softwareupdate.octoprint_checkout_folder());
self.config_checkType(self.settings.settings.plugins.softwareupdate.octoprint_type());
self.config_releaseChannel(self.settings.settings.plugins.softwareupdate.octoprint_release_channel());
@@ -242,6 +262,8 @@ $(function() {
};
self.fromCheckResponse = function(data, ignoreSeen, showIfNothingNew) {
self.cacheTimestamp(data.timestamp);
var versions = [];
_.each(data.information, function(value, key) {
value["key"] = key;
@@ -288,14 +310,16 @@ $(function() {
}
}
if (!self.loginState.isAdmin() && !self.settings.settings.plugins.softwareupdate.notify_users()) return;
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>";
@@ -303,7 +327,11 @@ $(function() {
});
text += "</ul>";
text += "<small>" + gettext("Those components marked with <i class=\"icon-ok\"></i> can be updated directly.") + "</small>";
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>";
}
text += "</div>";
@@ -314,8 +342,9 @@ $(function() {
};
var eventListeners = {};
var singleButtonNotify = false;
if (data.status == "updatePossible" && self.loginState.isAdmin()) {
// if user is admin, add action buttons
// if update is possible and user is admin, add action buttons for ignore and update
options["confirm"] = {
confirm: true,
buttons: [{
@@ -329,17 +358,38 @@ $(function() {
}, {
text: gettext("Update now"),
addClass: "btn-primary",
click: self.update
click: function() {
if (self._updateClicked) return;
self._updateClicked = true;
self.update();
}
}]
};
options["buttons"] = {
closer: false,
sticker: false
};
} else {
// if update is not possible or user is not admin, only add ignore button
options["confirm"] = {
confirm: true,
buttons: [{
text: gettext("Ignore"),
click: function(notice) {
notice.remove();
self._markNotificationAsSeen(data.information);
}
}]
};
options["buttons"] = {
closer: false,
sticker: false
};
singleButtonNotify = true;
}
if ((ignoreSeen || !self._hasNotificationBeenSeen(data.information)) && !OctoPrint.coreui.wizardOpen) {
self._showPopup(options, eventListeners);
self._showPopup(options, eventListeners, singleButtonNotify);
}
} else if (data.status == "current") {
if (showIfNothingNew) {
@@ -355,7 +405,8 @@ $(function() {
};
self.performCheck = function(showIfNothingNew, force, ignoreSeen) {
if (!self.loginState.isUser()) return;
if (!self.loginState.isAdmin() && !self.settings.settings.plugins.softwareupdate.notify_users()) return;
self.checking(true);
OctoPrint.plugins.softwareupdate.check(force)
.done(function(data) {
@@ -369,7 +420,18 @@ $(function() {
self._markNotificationAsSeen = function(data) {
if (!Modernizr.localstorage)
return false;
localStorage["plugin.softwareupdate.seen_information"] = JSON.stringify(self._informationToRemoteVersions(data));
if (!self.loginState.isUser())
return false;
var currentString = localStorage["plugin.softwareupdate.seen_information"];
var current;
if (currentString === undefined) {
current = {};
} else {
current = JSON.parse(currentString);
}
current[self.loginState.username()] = self._informationToRemoteVersions(data);
localStorage["plugin.softwareupdate.seen_information"] = JSON.stringify(current);
};
self._hasNotificationBeenSeen = function(data) {
@@ -380,11 +442,19 @@ $(function() {
return false;
var knownData = JSON.parse(localStorage["plugin.softwareupdate.seen_information"]);
if (!self.loginState.isUser())
return true;
var userData = knownData[self.loginState.username()];
if (userData === undefined)
return false;
var freshData = self._informationToRemoteVersions(data);
var hasBeenSeen = true;
_.each(freshData, function(value, key) {
if (!_.has(knownData, key) || knownData[key] != freshData[key]) {
if (!_.has(userData, key) || userData[key] != freshData[key]) {
hasBeenSeen = false;
}
});
@@ -400,12 +470,14 @@ $(function() {
};
self.performUpdate = function(force, items) {
if (!self.loginState.isAdmin()) return;
self.updateInProgress = true;
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,
@@ -434,8 +506,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({
@@ -443,6 +521,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");
@@ -451,9 +530,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) {
@@ -511,6 +594,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() {
@@ -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,10 +26,10 @@
<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" title="{{ _('Update not possible, configuration ok?') }}"></i></span><br>
<small class="muted">
{{ _('Installed:') }} <span data-bind="text: information.local.name"></span><br>
{{ _('Available:') }} <span data-bind="text: information.remote.name"></span><br>
@@ -57,13 +57,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">
<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); }">{{ _('Force update now (even if no new versions are available)') }}</button>
<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="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>
@@ -86,6 +87,14 @@
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: config_notifyUsers"> {{ _('Show update notifications to users') }}
<span class="help-block">{{ _('If you uncheck this, only logged in admins will see update notifications. Update notifications shown to users do not include the "Update now" button.') }}</span>
</label>
</div>
</div>
</form>
</div>
<div class="modal-footer">
@@ -99,7 +108,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><br></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>
+2 -2
View File
@@ -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 ""
@@ -5,7 +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) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
from . import commandline, git_commit, github_commit, github_release, python_checker
from . import commandline, git_commit, github_commit, github_release, bitbucket_commit, python_checker
def log_github_ratelimit(logger, r):
ratelimit = r.headers["X-RateLimit-Limit"] if "X-RateLimit-Limit" in r.headers else "?"
@@ -17,4 +17,4 @@ def log_github_ratelimit(logger, r):
except:
reset = "?"
logger.debug("Github rate limit: %s/%s, reset at %s" % (remaining, ratelimit, reset))
logger.debug("Github rate limit: %s/%s, reset at %s" % (remaining, ratelimit, reset))
@@ -0,0 +1,52 @@
# 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 requests
import logging
from ..exceptions import ConfigurationInvalid
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))
if not r.status_code == requests.codes.ok:
return None
reference = r.json()
if not "hash" in reference:
return None
return reference["hash"]
def get_latest(target, check):
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:
branch = check["branch"]
current = None
if "current" in check:
current = check["current"]
remote_commit = _get_latest_commit(check["user"], check["repo"], branch)
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)
)
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))
return information, is_current
@@ -15,7 +15,7 @@ BRANCH_HEAD_URL = "https://api.github.com/repos/{user}/{repo}/git/refs/heads/{br
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))
r = requests.get(BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch), timeout=30)
from . import log_github_ratelimit
log_github_ratelimit(logger, r)
@@ -8,6 +8,8 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import requests
import logging
from octoprint.util.version import parse_version
RELEASE_URL = "https://api.github.com/repos/{user}/{repo}/releases"
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.github_release")
@@ -15,7 +17,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 +28,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 +75,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 +96,10 @@ def _filter_out_latest(releases,
def _get_latest_release(user, repo, compare_type,
include_prerelease=False,
prerelease_channel=None,
commitish=None,
force_base=True):
nothing = None, None, None
r = requests.get(RELEASE_URL.format(user=user, repo=repo))
r = requests.get(RELEASE_URL.format(user=user, repo=repo), timeout=30)
from . import log_github_ratelimit
log_github_ratelimit(logger, r)
@@ -107,7 +121,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):
@@ -127,44 +141,8 @@ def _get_sanitized_version(version_string):
return version_string
def _get_base_from_version_tuple(version_tuple):
"""
Reduces version tuple to base version.
Tests:
>>> _get_base_from_version_tuple(("1", "2", "15"))
('1', '2', '15')
>>> _get_base_from_version_tuple(("1", "2", "15", "*", "dev12"))
('1', '2', '15')
"""
base_version = []
for part in version_tuple:
if part.startswith("*"):
break
base_version.append(part)
return tuple(base_version)
def _get_comparable_version_pkg_resources(version_string, force_base=True):
import pkg_resources
version = pkg_resources.parse_version(version_string)
# A leading v is common in github release tags and old setuptools doesn't remove it.
if version and isinstance(version, tuple) and version[0].lower() == "*v":
version = version[1:]
if force_base:
if isinstance(version, tuple):
# old setuptools
version = _get_base_from_version_tuple(version)
else:
# new setuptools
version = pkg_resources.parse_version(version.base_version)
return version
return parse_version(version_string, base=force_base)
def _get_comparable_version_semantic(version_string, force_base=True):
@@ -257,6 +235,16 @@ def get_latest(target, check, custom_compare=None):
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,7 +253,7 @@ 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(
@@ -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+)")
@@ -108,10 +109,15 @@ class VirtualPrinter(object):
self._brokenM29 = settings().getBoolean(["devel", "virtualPrinter", "brokenM29"])
self._m115FormatString = settings().get(["devel", "virtualPrinter", "m115FormatString"])
self._firmwareName = settings().get(["devel", "virtualPrinter", "firmwareName"])
self._okFormatString = settings().get(["devel", "virtualPrinter", "okFormatString"])
self._capabilities = settings().get(["devel", "virtualPrinter", "capabilities"])
self._temperature_reporter = None
self.currentLine = 0
self.lastN = 0
@@ -401,14 +407,29 @@ class VirtualPrinter(object):
return True
def _gcode_M115(self, data):
output = "FIRMWARE_NAME:{} PROTOCOL_VERSION:1.0".format(self._firmwareName)
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))
@@ -674,9 +695,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:
@@ -708,6 +728,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)
+16 -5
View File
@@ -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``
@@ -292,11 +292,16 @@ class PrinterInterface(object):
Optionally can also directly start the print after selecting the file.
Arguments:
path (str): The path to select for printing. Either an absolute path (local file) or a
filename (SD card).
sd (boolean): Indicates whether the file is on the SD card or not.
path (str): The path to select for printing. Either an absolute path or relative path to a local file in
the uploads folder or a filename on the printer's SD card.
sd (boolean): Indicates whether the file is on the printer's SD card or not.
printAfterSelect (boolean): Indicates whether a print should be started
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
"""
raise NotImplementedError()
@@ -362,7 +367,7 @@ class PrinterInterface(object):
* CLOSED
* ERROR
* CLOSED_WITH_ERROR
* TRANFERING_FILE
* TRANSFERING_FILE
* OFFLINE
* UNKNOWN
* NONE
@@ -586,3 +591,9 @@ class PrinterCallback(object):
class UnknownScript(Exception):
def __init__(self, name, *args, **kwargs):
self.name = name
class InvalidFileLocation(Exception):
pass
class InvalidFileType(Exception):
pass
+76 -45
View File
@@ -204,13 +204,66 @@ class PrinterProfileManager(object):
self._folder = settings().getBaseFolder("printerProfiles")
self._logger = logging.getLogger(__name__)
self._migrate_old_default_profile()
self._verify_default_available()
def _migrate_old_default_profile(self):
default_overrides = settings().get(["printerProfiles", "defaultProfile"])
if not default_overrides:
return
if self.exists("_default"):
return
if not isinstance(default_overrides, dict):
self._logger.warn("Existing default profile from settings is not a valid profile, refusing to migrate: {!r}".format(default_overrides))
return
default_overrides["id"] = "_default"
self.save(default_overrides)
settings().set(["printerProfiles", "defaultProfile"], None)
settings().save()
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(["printerProfiles", "default"])
if default_id is None:
default_id = "_default"
if not self.exists(default_id):
if not self.exists("_default"):
if default_id == "_default":
self._logger.error("Profile _default does not exist, creating _default again and setting it as default")
else:
self._logger.error("Selected default profile {} and _default do not exist, creating _default again and setting it as default".format(default_id))
self.save(self.__class__.default, allow_overwrite=True, make_default=True)
else:
self._logger.error("Selected default profile {} does not exists, resetting to _default".format(default_id))
settings().set(["printerProfiles", "default"], "_default")
settings().save()
default_id = "_default"
profile = self.get(default_id)
if profile is None:
self._logger.error("Selected default profile {} is invalid, resetting to default values".format(default_id))
profile = copy.deepcopy(self.__class__.default)
profile["id"] = default_id
self.save(self.__class__.default, allow_overwrite=True, make_default=True)
def select(self, identifier):
if identifier is None or not self.exists(identifier):
self._current = self.get_default()
return False
else:
self._current = self.get(identifier)
return True
if self._current is None:
self._logger.error("Profile {} is invalid, cannot select, falling back to default".format(identifier))
self._current = self.get_default()
return False
else:
return True
def deselect(self):
self._current = None
@@ -220,9 +273,7 @@ class PrinterProfileManager(object):
def get(self, identifier):
try:
if identifier == "_default":
return self._load_default()
elif self.exists(identifier):
if self.exists(identifier):
return self._load_from_path(self._get_profile_path(identifier))
else:
return None
@@ -230,10 +281,10 @@ class PrinterProfileManager(object):
return None
def remove(self, identifier):
if identifier == "_default":
return False
if self._current is not None and self._current["id"] == identifier:
return False
elif settings().get(["printerProfiles", "default"]) == identifier:
return False
return self._remove_from_path(self._get_profile_path(identifier))
def save(self, profile, allow_overwrite=False, make_default=False):
@@ -246,21 +297,16 @@ class PrinterProfileManager(object):
identifier = self._sanitize(identifier)
profile["id"] = identifier
self._migrate_profile(profile)
profile = dict_sanitize(profile, self.__class__.default)
profile = dict_merge(self.__class__.default, profile)
if identifier == self.__class__.default["id"]:
default_profile = dict_merge(self._load_default(), profile)
if not self._ensure_valid_profile(default_profile):
raise InvalidProfileError()
self._save_to_path(self._get_profile_path(identifier), profile, allow_overwrite=allow_overwrite)
settings().set(["printerProfiles", "defaultProfile"], default_profile, defaults=dict(printerProfiles=dict(defaultProfile=self.__class__.default)))
if make_default:
settings().set(["printerProfiles", "default"], identifier)
settings().save()
else:
self._save_to_path(self._get_profile_path(identifier), profile, allow_overwrite=allow_overwrite)
if make_default:
settings().set(["printerProfiles", "default"], identifier)
settings().save()
if self._current is not None and self._current["id"] == identifier:
self.select(identifier)
@@ -268,8 +314,7 @@ class PrinterProfileManager(object):
def is_default_unmodified(self):
default = settings().get(["printerProfiles", "default"])
default_overrides = settings().get(["printerProfiles", "defaultProfile"])
return (default is None or default == self.__class__.default["id"]) and not default_overrides
return default is None or default == "_default" or not self.exists("_default")
@property
def profile_count(self):
@@ -287,15 +332,17 @@ class PrinterProfileManager(object):
profile = self.get(default)
if profile is not None:
return profile
else:
self._logger.warn("Default profile {} is invalid, falling back to built-in defaults".format(default))
return self._load_default()
return copy.deepcopy(self.__class__.default)
def set_default(self, identifier):
all_identifiers = self._load_all_identifiers().keys()
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):
@@ -310,8 +357,6 @@ class PrinterProfileManager(object):
def exists(self, identifier):
if identifier is None:
return False
elif identifier == "_default":
return True
else:
path = self._get_profile_path(identifier)
return os.path.exists(path) and os.path.isfile(path)
@@ -321,23 +366,21 @@ class PrinterProfileManager(object):
results = dict()
for identifier, path in all_identifiers.items():
try:
if identifier == "_default":
profile = self._load_default()
else:
profile = self._load_from_path(path)
profile = self._load_from_path(path)
except InvalidProfileError:
self._logger.warn("Profile {} is invalid, skipping".format(identifier))
continue
if profile is None:
continue
results[identifier] = dict_merge(self._load_default(), profile)
results[identifier] = dict_merge(self.__class__.default, profile)
return results
def _load_all_identifiers(self):
results = dict(_default=None)
results = dict()
for entry in scandir(self._folder):
if is_hidden_path(entry.name) or not entry.name.endswith(".profile") or entry.name == "_default.profile":
if is_hidden_path(entry.name) or not entry.name.endswith(".profile"):
continue
if not entry.is_file():
@@ -355,6 +398,9 @@ class PrinterProfileManager(object):
with open(path) as f:
profile = yaml.safe_load(f)
if profile is None or not isinstance(profile, dict):
raise InvalidProfileError("Profile is None or not a dictionary")
if self._migrate_profile(profile):
try:
self._save_to_path(path, profile, allow_overwrite=True)
@@ -392,21 +438,6 @@ class PrinterProfileManager(object):
except:
return False
def _load_default(self):
default_overrides = settings().get(["printerProfiles", "defaultProfile"])
if self._migrate_profile(default_overrides):
try:
settings().set(["printerProfiles", "defaultProfile"], default_overrides)
settings().save()
except:
self._logger.exception("Tried to save default profile after migrating it while loading, ran into exception")
profile = self._ensure_valid_profile(dict_merge(copy.deepcopy(self.__class__.default), default_overrides))
if not profile:
self._logger.warn("Invalid default profile after applying overrides")
return copy.deepcopy(self.__class__.default)
return profile
def _get_profile_path(self, identifier):
return os.path.join(self._folder, "%s.profile" % identifier)
+194 -146
View File
@@ -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
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
@@ -70,6 +72,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._sdFilelistAvailable = threading.Event()
self._streamingFinishedCallback = None
self._selectedFileMutex = threading.RLock()
self._selectedFile = None
self._timeEstimationData = None
self._timeEstimationStatsWeighingUntil = settings().getFloat(["estimation", "printTime", "statsWeighingUntil"])
@@ -155,24 +158,28 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
#~~ callback from metadata analysis event
def _on_event_MetadataAnalysisFinished(self, event, data):
if self._selectedFile:
self._setJobData(self._selectedFile["filename"],
self._selectedFile["filesize"],
self._selectedFile["sd"])
with self._selectedFileMutex:
if self._selectedFile:
self._setJobData(self._selectedFile["filename"],
self._selectedFile["filesize"],
self._selectedFile["sd"])
def _on_event_MetadataStatisticsUpdated(self, event, data):
self._setJobData(self._selectedFile["filename"],
self._selectedFile["filesize"],
self._selectedFile["sd"])
with self._selectedFileMutex:
if self._selectedFile:
self._setJobData(self._selectedFile["filename"],
self._selectedFile["filesize"],
self._selectedFile["sd"])
#~~ progress plugin reporting
def _reportPrintProgressToPlugins(self, progress):
if progress is None or not self._selectedFile or not "sd" in self._selectedFile or not "filename" in self._selectedFile:
return
with self._selectedFileMutex:
if progress is None or not self._selectedFile or not "sd" in self._selectedFile or not "filename" in self._selectedFile:
return
storage = "sdcard" if self._selectedFile["sd"] else "local"
filename = self._selectedFile["filename"]
storage = "sdcard" if self._selectedFile["sd"] else "local"
filename = self._selectedFile["filename"]
def call_plugins(storage, filename, progress):
for plugin in self._progressPlugins:
@@ -326,14 +333,15 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if heater.startswith("tool"):
printer_profile = self._printerProfileManager.get_current_or_default()
extruder_count = printer_profile["extruder"]["count"]
if extruder_count > 1:
shared_nozzle = printer_profile["extruder"]["sharedNozzle"]
if extruder_count > 1 and not shared_nozzle:
toolNum = int(heater[len("tool"):])
self.commands("M104 T%d S%f" % (toolNum, value))
self.commands("M104 T{} S{}".format(toolNum, value))
else:
self.commands("M104 S%f" % value)
self.commands("M104 S{}".format(value))
elif heater == "bed":
self.commands("M140 S%f" % value)
self.commands("M140 S{}".format(value))
def set_temperature_offset(self, offsets=None):
if offsets is None:
@@ -364,7 +372,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
factor = int(factor * 100.0)
if factor < min or factor > max:
raise ValueError("factor must be a value between %f and %f" % (min, max))
raise ValueError("factor must be a value between {} and {}".format(min, max))
return factor
@@ -381,6 +389,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._logger.info("Cannot load file: printer not connected or currently busy")
return
self._validateJob(path, sd)
recovery_data = self._fileManager.get_recovery_data()
if recovery_data:
# clean up recovery data if we just selected a different file than is logged in that
@@ -394,7 +404,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._printAfterSelect = printAfterSelect
self._posAfterSelect = pos
self._comm.selectFile("/" + path if sd else path, sd)
self._setProgressData(completion=0)
self._updateProgressData()
self._setCurrentZ(None)
def unselect_file(self):
@@ -402,15 +412,16 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
return
self._comm.unselectFile()
self._setProgressData(completion=0)
self._updateProgressData()
self._setCurrentZ(None)
def get_file_position(self):
if self._comm is None:
return None
if self._selectedFile is None:
return None
with self._selectedFileMutex:
if self._selectedFile is None:
return None
return self._comm.getFilePosition()
@@ -421,21 +432,23 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
"""
if self._comm is None or not self._comm.isOperational() or self._comm.isPrinting():
return
if self._selectedFile is None:
return
with self._selectedFileMutex:
if self._selectedFile is None:
return
# we are happy if the average of the estimates stays within 60s of the prior one
threshold = settings().getFloat(["estimation", "printTime", "stableThreshold"])
rolling_window = None
countdown = None
if self._selectedFile["sd"]:
# we are interesting in a rolling window of roughly the last 15s, so the number of entries has to be derived
# by that divided by the sd status polling interval
rolling_window = 15 / settings().get(["serial", "timeout", "sdStatus"])
with self._selectedFileMutex:
if self._selectedFile["sd"]:
# we are interesting in a rolling window of roughly the last 15s, so the number of entries has to be derived
# by that divided by the sd status polling interval
rolling_window = 15 / settings().get(["serial", "timeout", "sdStatus"])
# we are happy when one rolling window has been stable
countdown = rolling_window
# we are happy when one rolling window has been stable
countdown = rolling_window
self._timeEstimationData = TimeEstimationHelper(rolling_window=rolling_window,
threshold=threshold,
countdown=countdown)
@@ -443,7 +456,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._fileManager.delete_recovery_data()
self._lastProgressReport = None
self._setProgressData(completion=0)
self._updateProgressData()
self._setCurrentZ(None)
self._comm.startPrint(pos=pos)
@@ -478,18 +491,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if self._comm is None:
return
# tell comm layer to cancel - will also trigger our cancelled handler
# for further processing
self._comm.cancelPrint()
# reset progress, height, print time
self._setCurrentZ(None)
self._setProgressData()
# mark print as failure
if self._selectedFile is not None:
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"])
payload = self._payload_for_print_job_event()
eventManager().fire(Events.PRINT_FAILED, payload)
def get_state_string(self, state=None):
if self._comm is None:
return "Offline"
@@ -559,7 +564,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
return self._comm is not None and self._comm.isError()
def is_ready(self):
return self.is_operational() and not self._comm.isStreaming()
return self.is_operational() and not self.is_printing() and not self._comm.isStreaming()
def is_sd_ready(self):
if not settings().getBoolean(["feature", "sdSupport"]) or self._comm is None:
@@ -662,7 +667,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
return result
def _setProgressData(self, completion=None, filepos=None, printTime=None, printTimeLeft=None):
def _updateProgressData(self, completion=None, filepos=None, printTime=None, printTimeLeft=None):
self._stateMonitor.set_progress(dict(completion=int(completion * 100) if completion is not None else None,
filepos=filepos,
printTime=int(printTime) if printTime is not None else None,
@@ -682,10 +687,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
statisticalTotalPrintTime = None
statisticalTotalPrintTimeType = None
if self._selectedFile and "estimatedPrintTime" in self._selectedFile \
and self._selectedFile["estimatedPrintTime"]:
statisticalTotalPrintTime = self._selectedFile["estimatedPrintTime"]
statisticalTotalPrintTimeType = self._selectedFile.get("estimatedPrintTimeType", None)
with self._selectedFileMutex:
if self._selectedFile and "estimatedPrintTime" in self._selectedFile \
and self._selectedFile["estimatedPrintTime"]:
statisticalTotalPrintTime = self._selectedFile["estimatedPrintTime"]
statisticalTotalPrintTimeType = self._selectedFile.get("estimatedPrintTimeType", None)
printTimeLeft, printTimeLeftOrigin = self._estimatePrintTimeLeft(progress, printTime, cleanedPrintTime, statisticalTotalPrintTime, statisticalTotalPrintTimeType)
@@ -841,90 +847,104 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._stateMonitor.add_temperature(data)
def _setJobData(self, filename, filesize, sd):
if filename is not None:
if sd:
name_in_storage = filename
if name_in_storage.startswith("/"):
name_in_storage = name_in_storage[1:]
path_in_storage = name_in_storage
path_on_disk = None
else:
path_in_storage = self._fileManager.path_in_storage(FileDestinations.LOCAL, filename)
path_on_disk = self._fileManager.path_on_disk(FileDestinations.LOCAL, filename)
_, name_in_storage = self._fileManager.split_path(FileDestinations.LOCAL, path_in_storage)
self._selectedFile = {
"filename": path_in_storage,
"filesize": filesize,
"sd": sd,
"estimatedPrintTime": None
}
else:
self._selectedFile = None
self._stateMonitor.set_job_data({
"file": {
"name": None,
"path": None,
"origin": None,
"size": None,
"date": None
},
"estimatedPrintTime": None,
"averagePrintTime": None,
"lastPrintTime": None,
"filament": None,
})
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
estimatedPrintTime = None
lastPrintTime = None
averagePrintTime = None
date = None
filament = None
if path_on_disk:
# Use a string for mtime because it could be float and the
# javascript needs to exact match
if not sd:
date = int(os.stat(path_on_disk).st_mtime)
path_on_disk = self._fileManager.path_on_disk(FileDestinations.LOCAL, filename)
if os.path.isabs(filename) and not filename == path_on_disk:
raise InvalidFileLocation("{} is not located within local storage, cannot select for printing".format(filename))
if not os.path.isfile(path_on_disk):
raise InvalidFileLocation("{} does not exist in local storage, cannot select for printing".format(filename))
try:
fileData = self._fileManager.get_metadata(FileDestinations.SDCARD if sd else FileDestinations.LOCAL, path_on_disk)
except:
fileData = None
if fileData is not None:
if "analysis" in fileData:
if estimatedPrintTime is None and "estimatedPrintTime" in fileData["analysis"]:
estimatedPrintTime = fileData["analysis"]["estimatedPrintTime"]
if "filament" in fileData["analysis"].keys():
filament = fileData["analysis"]["filament"]
if "statistics" in fileData:
printer_profile = self._printerProfileManager.get_current_or_default()["id"]
if "averagePrintTime" in fileData["statistics"] and printer_profile in fileData["statistics"]["averagePrintTime"]:
averagePrintTime = fileData["statistics"]["averagePrintTime"][printer_profile]
if "lastPrintTime" in fileData["statistics"] and printer_profile in fileData["statistics"]["lastPrintTime"]:
lastPrintTime = fileData["statistics"]["lastPrintTime"][printer_profile]
def _setJobData(self, filename, filesize, sd):
with self._selectedFileMutex:
if filename is not None:
if sd:
name_in_storage = filename
if name_in_storage.startswith("/"):
name_in_storage = name_in_storage[1:]
path_in_storage = name_in_storage
path_on_disk = None
else:
path_in_storage = self._fileManager.path_in_storage(FileDestinations.LOCAL, filename)
path_on_disk = self._fileManager.path_on_disk(FileDestinations.LOCAL, filename)
_, name_in_storage = self._fileManager.split_path(FileDestinations.LOCAL, path_in_storage)
self._selectedFile = {
"filename": path_in_storage,
"filesize": filesize,
"sd": sd,
"estimatedPrintTime": None
}
else:
self._selectedFile = None
self._stateMonitor.set_job_data({
"file": {
"name": None,
"path": None,
"origin": None,
"size": None,
"date": None
},
"estimatedPrintTime": None,
"averagePrintTime": None,
"lastPrintTime": None,
"filament": None,
})
return
if averagePrintTime is not None:
self._selectedFile["estimatedPrintTime"] = averagePrintTime
self._selectedFile["estimatedPrintTimeType"] = "average"
elif estimatedPrintTime is not None:
# TODO apply factor which first needs to be tracked!
self._selectedFile["estimatedPrintTime"] = estimatedPrintTime
self._selectedFile["estimatedPrintTimeType"] = "analysis"
estimatedPrintTime = None
lastPrintTime = None
averagePrintTime = None
date = None
filament = None
if path_on_disk:
# Use a string for mtime because it could be float and the
# javascript needs to exact match
if not sd:
date = int(os.stat(path_on_disk).st_mtime)
self._stateMonitor.set_job_data({
"file": {
"name": name_in_storage,
"path": path_in_storage,
"origin": FileDestinations.SDCARD if sd else FileDestinations.LOCAL,
"size": filesize,
"date": date
},
"estimatedPrintTime": estimatedPrintTime,
"averagePrintTime": averagePrintTime,
"lastPrintTime": lastPrintTime,
"filament": filament,
})
try:
fileData = self._fileManager.get_metadata(FileDestinations.SDCARD if sd else FileDestinations.LOCAL, path_on_disk)
except:
fileData = None
if fileData is not None:
if "analysis" in fileData:
if estimatedPrintTime is None and "estimatedPrintTime" in fileData["analysis"]:
estimatedPrintTime = fileData["analysis"]["estimatedPrintTime"]
if "filament" in fileData["analysis"].keys():
filament = fileData["analysis"]["filament"]
if "statistics" in fileData:
printer_profile = self._printerProfileManager.get_current_or_default()["id"]
if "averagePrintTime" in fileData["statistics"] and printer_profile in fileData["statistics"]["averagePrintTime"]:
averagePrintTime = fileData["statistics"]["averagePrintTime"][printer_profile]
if "lastPrintTime" in fileData["statistics"] and printer_profile in fileData["statistics"]["lastPrintTime"]:
lastPrintTime = fileData["statistics"]["lastPrintTime"][printer_profile]
if averagePrintTime is not None:
self._selectedFile["estimatedPrintTime"] = averagePrintTime
self._selectedFile["estimatedPrintTimeType"] = "average"
elif estimatedPrintTime is not None:
# TODO apply factor which first needs to be tracked!
self._selectedFile["estimatedPrintTime"] = estimatedPrintTime
self._selectedFile["estimatedPrintTimeType"] = "analysis"
self._stateMonitor.set_job_data({
"file": {
"name": name_in_storage,
"path": path_in_storage,
"origin": FileDestinations.SDCARD if sd else FileDestinations.LOCAL,
"size": filesize,
"date": date
},
"estimatedPrintTime": estimatedPrintTime,
"averagePrintTime": averagePrintTime,
"lastPrintTime": lastPrintTime,
"filament": filament,
})
def _sendInitialStateUpdate(self, callback):
try:
@@ -977,9 +997,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
# forward relevant state changes to gcode manager
if oldState == comm.MachineCom.STATE_PRINTING:
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"])
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"])
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
@@ -988,7 +1009,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if self._comm is not None:
self._comm = None
self._setProgressData(completion=0)
self._updateProgressData()
self._setCurrentZ(None)
self._setJobData(None, None, None)
self._printerProfileManager.deselect()
@@ -1054,31 +1075,58 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
must_be_set=False)
def on_comm_print_job_done(self):
self._fileManager.delete_recovery_data()
payload = self._payload_for_print_job_event()
if payload:
payload["time"] = self._comm.getPrintTime()
self._updateProgressData(completion=1.0,
filepos=payload["size"],
printTime=payload["time"],
printTimeLeft=0)
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
eventManager().fire(Events.PRINT_DONE, payload)
self.script("afterPrintDone",
context=dict(event=payload),
must_be_set=False)
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), True, self._printerProfileManager.get_current_or_default()["id"])
self._setProgressData(completion=1.0, filepos=self._selectedFile["filesize"], printTime=self._comm.getPrintTime(), printTimeLeft=0)
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
self._fileManager.delete_recovery_data()
self._fileManager.log_print(payload["origin"],
payload["path"],
time.time(),
payload["time"],
True,
self._printerProfileManager.get_current_or_default()["id"])
else:
self._updateProgressData()
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
def on_comm_print_job_failed(self):
payload = self._payload_for_print_job_event()
eventManager().fire(Events.PRINT_FAILED, payload)
def on_comm_print_job_cancelled(self):
self._setCurrentZ(None)
self._updateProgressData()
payload = self._payload_for_print_job_event(position=self._comm.cancel_position.as_dict() if self._comm and self._comm.cancel_position else None)
if payload:
payload["time"] = self._comm.getPrintTime()
eventManager().fire(Events.PRINT_CANCELLED, payload)
self.script("afterPrintCancelled",
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 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)
if payload:
@@ -1099,7 +1147,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._sdStreaming = True
self._setJobData(filename, filesize, True)
self._setProgressData(completion=0.0, filepos=0, printTime=0)
self._updateProgressData(completion=0.0, filepos=0, printTime=0)
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
def on_comm_file_transfer_done(self, filename):
@@ -1112,7 +1160,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._setCurrentZ(None)
self._setJobData(None, None, None)
self._setProgressData()
self._updateProgressData()
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
def on_comm_force_disconnect(self):
@@ -1126,14 +1174,16 @@ 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):
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:
selected_file = self._selectedFile
if not selected_file:
return dict()
with self._selectedFileMutex:
selected_file = self._selectedFile
if not selected_file:
return dict()
print_job_file = selected_file.get("filename", None)
location = FileDestinations.SDCARD if selected_file.get("sd", False) else FileDestinations.LOCAL
print_job_file = selected_file.get("filename", None)
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 location:
return dict()
@@ -1154,6 +1204,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
result= dict(name=name,
path=path,
origin=origin,
size=print_job_size,
# TODO deprecated, remove in 1.4.0
file=full_path,
@@ -1176,15 +1227,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()
+96 -82
View File
@@ -16,7 +16,9 @@ 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
@@ -162,7 +164,7 @@ class Server(object):
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
@@ -194,8 +196,10 @@ class Server(object):
eventManager = events.eventManager()
analysisQueue = octoprint.filemanager.analysis.AnalysisQueue()
slicingManager = octoprint.slicing.SlicingManager(self._settings.getBaseFolder("slicingProfiles"), printerProfileManager)
storage_managers = dict()
storage_managers[octoprint.filemanager.FileDestinations.LOCAL] = octoprint.filemanager.storage.LocalFileStorage(self._settings.getBaseFolder("uploads"))
fileManager = octoprint.filemanager.FileManager(analysisQueue, slicingManager, printerProfileManager, initial_storage_managers=storage_managers)
appSessionManager = util.flask.AppSessionManager()
pluginLifecycleManager = LifecycleManager(pluginManager)
@@ -206,7 +210,7 @@ class Server(object):
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:
@@ -340,7 +344,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()
@@ -355,7 +359,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"]))
@@ -433,9 +438,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)
@@ -473,11 +491,14 @@ class Server(object):
# auto connect
if self._settings.getBoolean(["serial", "autoconnect"]):
(port, baudrate) = self._settings.get(["serial", "port"]), self._settings.getInt(["serial", "baudrate"])
printer_profile = printerProfileManager.get_default()
connectionOptions = printer.__class__.get_connection_options()
if port in connectionOptions["ports"]:
printer.connect(port=port, baudrate=baudrate, profile=printer_profile["id"] if "id" in printer_profile else "_default")
try:
(port, baudrate) = self._settings.get(["serial", "port"]), self._settings.getInt(["serial", "baudrate"])
printer_profile = printerProfileManager.get_default()
connectionOptions = printer.__class__.get_connection_options()
if port in connectionOptions["ports"]:
printer.connect(port=port, baudrate=baudrate, profile=printer_profile["id"] if "id" in printer_profile else "_default")
except:
self._logger.exception("Something went wrong while attempting to automatically connect to the printer")
# start up watchdogs
if self._settings.getBoolean(["feature", "pollWatched"]):
@@ -548,7 +569,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))
@@ -563,13 +584,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:
@@ -788,6 +812,8 @@ class Server(object):
return
def execute_caching():
logger = logging.getLogger(__name__ + ".preemptive_cache")
for route in sorted(cache_data.keys(), key=lambda x: (x.count("/"), x)):
entries = reversed(sorted(cache_data[route], key=lambda x: x.get("_count", 0)))
for kwargs in entries:
@@ -796,18 +822,18 @@ class Server(object):
try:
plugin_info = pluginManager.get_plugin_info(plugin, require_enabled=True)
if plugin_info is None:
self._logger.info("About to preemptively cache plugin {} but it is not installed or enabled, preemptive caching makes no sense".format(plugin))
logger.info("About to preemptively cache plugin {} but it is not installed or enabled, preemptive caching makes no sense".format(plugin))
continue
implementation = plugin_info.implementation
if implementation is None or not isinstance(implementation, octoprint.plugin.UiPlugin):
self._logger.info("About to preemptively cache plugin {} but it is not a UiPlugin, preemptive caching makes no sense".format(plugin))
logger.info("About to preemptively cache plugin {} but it is not a UiPlugin, preemptive caching makes no sense".format(plugin))
continue
if not implementation.get_ui_preemptive_caching_enabled():
self._logger.info("About to preemptively cache plugin {} but it has disabled preemptive caching".format(plugin))
logger.info("About to preemptively cache plugin {} but it has disabled preemptive caching".format(plugin))
continue
except:
self._logger.exception("Error while trying to check if plugin {} has preemptive caching enabled, skipping entry")
logger.exception("Error while trying to check if plugin {} has preemptive caching enabled, skipping entry")
continue
additional_request_data = kwargs.get("_additional_request_data", dict())
@@ -815,10 +841,11 @@ class Server(object):
kwargs.update(additional_request_data)
try:
start = time.time()
if plugin:
self._logger.info("Preemptively caching {} (ui {}) for {!r}".format(route, plugin, kwargs))
logger.info("Preemptively caching {} (ui {}) for {!r}".format(route, plugin, kwargs))
else:
self._logger.info("Preemptively caching {} (ui _default) for {!r}".format(route, kwargs))
logger.info("Preemptively caching {} (ui _default) for {!r}".format(route, kwargs))
headers = kwargs.get("headers", dict())
headers["X-Force-View"] = plugin if plugin else "_default"
@@ -827,8 +854,10 @@ class Server(object):
builder = EnvironBuilder(**kwargs)
app(builder.get_environ(), lambda *a, **kw: None)
logger.info("... done in {:.2f}s".format(time.time() - start))
except:
self._logger.exception("Error while trying to preemptively cache {} for {!r}".format(route, kwargs))
logger.exception("Error while trying to preemptively cache {} for {!r}".format(route, kwargs))
# asynchronous caching
import threading
@@ -1010,7 +1039,6 @@ class Server(object):
enable_gcodeviewer = self._settings.getBoolean(["gcodeViewer", "enabled"])
preferred_stylesheet = self._settings.get(["devel", "stylesheet"])
minify = self._settings.getBoolean(["devel", "webassets", "minify"])
dynamic_core_assets = util.flask.collect_core_assets(enable_gcodeviewer=enable_gcodeviewer)
dynamic_plugin_assets = util.flask.collect_plugin_assets(
@@ -1019,7 +1047,7 @@ class Server(object):
)
js_libs = [
"js/lib/jquery/jquery.min.js" if minify else "js/lib/jquery/jquery.js",
"js/lib/jquery/jquery.js",
"js/lib/modernizr.custom.js",
"js/lib/lodash.min.js",
"js/lib/sprintf.min.js",
@@ -1036,19 +1064,31 @@ 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",
"js/lib/jquery/jquery.qrcode.min.js",
"js/lib/jquery/jquery.bootstrap.wizard.js",
"js/lib/pnotify/pnotify.core.min.js",
"js/lib/pnotify/pnotify.buttons.min.js",
"js/lib/pnotify/pnotify.callbacks.min.js",
"js/lib/pnotify/pnotify.confirm.min.js",
"js/lib/pnotify/pnotify.desktop.min.js",
"js/lib/pnotify/pnotify.history.min.js",
"js/lib/pnotify/pnotify.mobile.min.js",
"js/lib/pnotify/pnotify.nonblock.min.js",
"js/lib/pnotify/pnotify.reference.min.js",
"js/lib/pnotify/pnotify.tooltip.min.js",
"js/lib/moment-with-locales.min.js",
"js/lib/pusher.color.min.js",
"js/lib/detectmobilebrowser.js",
"js/lib/md5.min.js",
"js/lib/pnotify.min.js",
"js/lib/bootstrap-slider-knockout-binding.js",
"js/lib/loglevel.min.js",
"js/lib/sockjs.min.js" if minify else "js/lib/sockjs.js"
"js/lib/sockjs.js"
]
js_client = [
"js/app/client/base.js",
@@ -1076,106 +1116,80 @@ class Server(object):
"js/app/helpers.js",
"js/app/main.js"]
js_plugins = dynamic_plugin_assets["external"]["js"]
js_app = js_plugins + js_core
css_libs = [
"css/bootstrap.min.css",
"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.min.css"
"css/pnotify.core.min.css",
"css/pnotify.buttons.min.css",
"css/pnotify.history.min.css"
]
css_core = list(dynamic_core_assets["css"]) + list(dynamic_plugin_assets["bundled"]["css"])
css_plugins = list(dynamic_plugin_assets["external"]["css"])
css_app = css_core + css_plugins
less_core = list(dynamic_core_assets["less"]) + list(dynamic_plugin_assets["bundled"]["less"])
less_plugins = list(dynamic_plugin_assets["external"]["less"])
less_app = less_core + less_plugins
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")
if minify:
js_client_bundle = Bundle(*js_client, output="webassets/packed_client.js", filters="rjsmin, js_delimiter_bundler")
js_core_bundle = Bundle(*js_core, output="webassets/packed_core.js", filters="rjsmin, js_delimiter_bundler")
if len(js_plugins) == 0:
js_plugins_bundle = Bundle(*[])
else:
js_plugins_bundle = Bundle(*js_plugins, output="webassets/packed_plugins.js", filters="rjsmin, js_delimiter_bundler")
js_app_bundle = Bundle(*js_app, output="webassets/packed_app.js", filters="rjsmin, js_delimiter_bundler")
js_filters = ["sourcemap_remove", "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_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")
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_app_bundle = Bundle(*js_app, output="webassets/packed_app.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=",".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))
if len(css_app) == 0:
css_app_bundle = Bundle(*[])
else:
css_app_bundle = Bundle(*css_app, 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))
if len(less_app) == 0:
less_app_bundle = Bundle(*[])
else:
less_app_bundle = Bundle(*less_app, 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)
+1 -1
View File
@@ -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()))
+2 -2
View File
@@ -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"],
+13 -18
View File
@@ -63,7 +63,7 @@ def _create_lastmodified(path, recursive):
return None
def _create_etag(path, recursive, lm=None):
def _create_etag(path, filter, recursive, lm=None):
if lm is None:
lm = _create_lastmodified(path, recursive)
@@ -72,6 +72,7 @@ def _create_etag(path, recursive, lm=None):
hash = hashlib.sha1()
hash.update(str(lm))
hash.update(str(filter))
hash.update(str(recursive))
if path.endswith("/files") or path.endswith("/files/sdcard"):
@@ -83,20 +84,18 @@ def _create_etag(path, recursive, lm=None):
@api.route("/files", methods=["GET"])
@with_revalidation_checking(etag_factory=lambda lm=None: _create_etag(request.path,
request.values.get("filter", False),
request.values.get("recursive", False),
lm=lm),
lastmodified_factory=lambda: _create_lastmodified(request.path,
request.values.get("recursive", False)),
unless=lambda: request.values.get("force", False) or request.values.get("_refresh", False))
def readGcodeFiles():
filter = request.values.get("filter", "false") in valid_boolean_trues
filter = request.values.get("filter", False)
recursive = request.values.get("recursive", "false") in valid_boolean_trues
force = request.values.get("force", "false") in valid_boolean_trues
if force:
_clear_file_cache()
files = _getFileList(FileDestinations.LOCAL, filter=filter, recursive=recursive)
files = _getFileList(FileDestinations.LOCAL, filter=filter, recursive=recursive, allow_from_cache=not force)
files.extend(_getFileList(FileDestinations.SDCARD))
usage = psutil.disk_usage(settings().getBaseFolder("uploads"))
@@ -105,6 +104,7 @@ def readGcodeFiles():
@api.route("/files/<string:origin>", methods=["GET"])
@with_revalidation_checking(etag_factory=lambda lm=None: _create_etag(request.path,
request.values.get("filter", False),
request.values.get("recursive", False),
lm=lm),
lastmodified_factory=lambda: _create_lastmodified(request.path,
@@ -114,17 +114,11 @@ def readGcodeFilesForOrigin(origin):
if origin not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
return make_response("Unknown origin: %s" % origin, 404)
filter = request.values.get("filter", False)
recursive = request.values.get("recursive", "false") in valid_boolean_trues
force = request.values.get("force", "false") in valid_boolean_trues
if force:
with _file_cache_mutex:
try:
del _file_cache[origin]
except KeyError:
pass
files = _getFileList(origin, recursive=recursive)
files = _getFileList(origin, filter=filter, recursive=recursive, allow_from_cache=not force)
if origin == FileDestinations.LOCAL:
usage = psutil.disk_usage(settings().getBaseFolder("uploads"))
@@ -144,7 +138,7 @@ def _getFileDetails(origin, path, recursive=True):
return None
def _getFileList(origin, path=None, filter=None, recursive=False):
def _getFileList(origin, path=None, filter=None, recursive=False, allow_from_cache=True):
if origin == FileDestinations.SDCARD:
sdFileList = printer.get_sd_files()
@@ -169,11 +163,12 @@ def _getFileList(origin, path=None, filter=None, recursive=False):
filter_func = lambda entry, entry_data: octoprint.filemanager.valid_file_type(entry, type=filter)
with _file_cache_mutex:
files, lastmodified = _file_cache.get("{}:{}:{}:{}".format(origin, path, recursive, filter), ([], None))
if lastmodified is None or lastmodified < fileManager.last_modified(origin, path=path, recursive=recursive):
cache_key = "{}:{}:{}:{}".format(origin, path, recursive, filter)
files, lastmodified = _file_cache.get(cache_key, ([], None))
if not allow_from_cache or lastmodified is None or lastmodified < fileManager.last_modified(origin, path=path, recursive=recursive):
files = fileManager.list_files(origin, path=path, filter=filter_func, recursive=recursive)[origin].values()
lastmodified = fileManager.last_modified(origin, path=path, recursive=recursive)
_file_cache["{}:{}:{}:{}".format(origin, path, recursive, filter)] = (files, lastmodified)
_file_cache[cache_key] = (files, lastmodified)
def analyse_recursively(files, path=None):
if path is None:
+10 -3
View File
@@ -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
@@ -105,8 +106,14 @@ def printerProfilesGet(identifier):
@api.route("/printerprofiles/<string:identifier>", methods=["DELETE"])
@restricted_access
def printerProfilesDelete(identifier):
if printerProfileManager.get_current_or_default()["id"] == identifier:
return make_response("Cannot delete currently selected profile: %s" % identifier, 409)
current_profile = printerProfileManager.get_current()
if current_profile and current_profile["id"] == identifier:
return make_response("Cannot delete currently selected profile: {}".format(identifier), 409)
default_profile = printerProfileManager.get_default()
if default_profile and default_profile["id"] == identifier:
return make_response("Cannot delete default profile: {}".format(identifier), 409)
printerProfileManager.remove(identifier)
return NO_CONTENT
+89 -55
View File
@@ -15,7 +15,7 @@ from octoprint.events import eventManager, Events
from octoprint.settings import settings, valid_boolean_trues
from octoprint.server import admin_permission, printer
from octoprint.server.api import api
from octoprint.server.api import api, NO_CONTENT
from octoprint.server.util.flask import restricted_access, with_revalidation_checking
import octoprint.plugin
@@ -83,7 +83,7 @@ def getSettings():
data = {
"api": {
"enabled": s.getBoolean(["api", "enabled"]),
"key": s.get(["api", "key"]) if admin_permission.can() else "n/a",
"key": s.get(["api", "key"]) if admin_permission.can() else None,
"allowCrossOrigin": s.get(["api", "allowCrossOrigin"])
},
"appearance": {
@@ -98,6 +98,8 @@ 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"]),
@@ -127,7 +129,8 @@ def getSettings():
"modelSizeDetection": s.getBoolean(["feature", "modelSizeDetection"]),
"firmwareDetection": s.getBoolean(["feature", "firmwareDetection"]),
"printCancelConfirmation": s.getBoolean(["feature", "printCancelConfirmation"]),
"blockWhileDwelling": s.getBoolean(["feature", "blockWhileDwelling"])
"blockWhileDwelling": s.getBoolean(["feature", "blockWhileDwelling"]),
"g90InfluencesExtruder": s.getBoolean(["feature", "g90InfluencesExtruder"])
},
"serial": {
"port": connectionOptions["portPreference"],
@@ -140,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"]),
@@ -164,7 +168,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"]),
@@ -180,6 +186,8 @@ def getSettings():
"afterPrintDone": None,
"beforePrintPaused": None,
"afterPrintResumed": None,
"beforeToolChange": None,
"afterToolChange": None,
"snippets": dict()
}
},
@@ -255,9 +263,30 @@ def setSettings():
except BadRequest:
return make_response("Malformed JSON body in request", 400)
if not isinstance(data, dict):
return make_response("Malformed request, need settings dictionary, "
"got a {} instead: {!r}".format(type(data).__name__, data), 400)
_saveSettings(data)
return getSettings()
@api.route("/settings/apikey", methods=["POST"])
@restricted_access
@admin_permission.require(403)
def generateApiKey():
apikey = settings().generateApiKey()
return jsonify(apikey=apikey)
@api.route("/settings/apikey", methods=["DELETE"])
@restricted_access
@admin_permission.require(403)
def deleteApiKey():
settings().deleteApiKey()
return NO_CONTENT
def _saveSettings(data):
logger = logging.getLogger(__name__)
@@ -267,14 +296,13 @@ def _saveSettings(data):
# is changed, added or removed here
if "api" in data.keys():
if "enabled" in data["api"].keys(): s.setBoolean(["api", "enabled"], data["api"]["enabled"])
if "key" in data["api"].keys(): s.set(["api", "key"], data["api"]["key"], True)
if "allowCrossOrigin" in data["api"].keys(): s.setBoolean(["api", "allowCrossOrigin"], data["api"]["allowCrossOrigin"])
if "enabled" in data["api"]: s.setBoolean(["api", "enabled"], data["api"]["enabled"])
if "allowCrossOrigin" in data["api"]: s.setBoolean(["api", "allowCrossOrigin"], data["api"]["allowCrossOrigin"])
if "appearance" in data.keys():
if "name" in data["appearance"].keys(): s.set(["appearance", "name"], data["appearance"]["name"])
if "color" in data["appearance"].keys(): s.set(["appearance", "color"], data["appearance"]["color"])
if "colorTransparent" in data["appearance"].keys(): s.setBoolean(["appearance", "colorTransparent"], data["appearance"]["colorTransparent"])
if "name" in data["appearance"]: s.set(["appearance", "name"], data["appearance"]["name"])
if "color" in data["appearance"]: s.set(["appearance", "color"], data["appearance"]["color"])
if "colorTransparent" in data["appearance"]: s.setBoolean(["appearance", "colorTransparent"], data["appearance"]["colorTransparent"])
if "defaultLanguage" in data["appearance"]: s.set(["appearance", "defaultLanguage"], data["appearance"]["defaultLanguage"])
if "showFahrenheitAlso" in data["appearance"]: s.setBoolean(["appearance", "showFahrenheitAlso"], data["appearance"]["showFahrenheitAlso"])
@@ -282,48 +310,52 @@ def _saveSettings(data):
if "defaultExtrusionLength" in data["printer"]: s.setInt(["printerParameters", "defaultExtrusionLength"], data["printer"]["defaultExtrusionLength"])
if "webcam" in data.keys():
if "streamUrl" in data["webcam"].keys(): s.set(["webcam", "stream"], data["webcam"]["streamUrl"])
if "snapshotUrl" in data["webcam"].keys(): s.set(["webcam", "snapshot"], data["webcam"]["snapshotUrl"])
if "ffmpegPath" in data["webcam"].keys(): s.set(["webcam", "ffmpeg"], data["webcam"]["ffmpegPath"])
if "bitrate" in data["webcam"].keys(): s.set(["webcam", "bitrate"], data["webcam"]["bitrate"])
if "ffmpegThreads" in data["webcam"].keys(): s.setInt(["webcam", "ffmpegThreads"], data["webcam"]["ffmpegThreads"])
if "watermark" in data["webcam"].keys(): s.setBoolean(["webcam", "watermark"], data["webcam"]["watermark"])
if "flipH" in data["webcam"].keys(): s.setBoolean(["webcam", "flipH"], data["webcam"]["flipH"])
if "flipV" in data["webcam"].keys(): s.setBoolean(["webcam", "flipV"], data["webcam"]["flipV"])
if "rotate90" in data["webcam"].keys(): s.setBoolean(["webcam", "rotate90"], data["webcam"]["rotate90"])
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"])
if "ffmpegThreads" in data["webcam"]: s.setInt(["webcam", "ffmpegThreads"], data["webcam"]["ffmpegThreads"])
if "watermark" in data["webcam"]: s.setBoolean(["webcam", "watermark"], data["webcam"]["watermark"])
if "flipH" in data["webcam"]: s.setBoolean(["webcam", "flipH"], data["webcam"]["flipH"])
if "flipV" in data["webcam"]: s.setBoolean(["webcam", "flipV"], data["webcam"]["flipV"])
if "rotate90" in data["webcam"]: s.setBoolean(["webcam", "rotate90"], data["webcam"]["rotate90"])
if "feature" in data.keys():
if "gcodeViewer" in data["feature"].keys(): s.setBoolean(["gcodeViewer", "enabled"], data["feature"]["gcodeViewer"])
if "sizeThreshold" in data["feature"].keys(): s.setInt(["gcodeViewer", "sizeThreshold"], data["feature"]["sizeThreshold"])
if "mobileSizeThreshold" in data["feature"].keys(): s.setInt(["gcodeViewer", "mobileSizeThreshold"], data["feature"]["mobileSizeThreshold"])
if "temperatureGraph" in data["feature"].keys(): s.setBoolean(["feature", "temperatureGraph"], data["feature"]["temperatureGraph"])
if "waitForStart" in data["feature"].keys(): s.setBoolean(["feature", "waitForStartOnConnect"], data["feature"]["waitForStart"])
if "alwaysSendChecksum" in data["feature"].keys(): s.setBoolean(["feature", "alwaysSendChecksum"], data["feature"]["alwaysSendChecksum"])
if "neverSendChecksum" in data["feature"].keys(): s.setBoolean(["feature", "neverSendChecksum"], data["feature"]["neverSendChecksum"])
if "sdSupport" in data["feature"].keys(): s.setBoolean(["feature", "sdSupport"], data["feature"]["sdSupport"])
if "sdRelativePath" in data["feature"].keys(): s.setBoolean(["feature", "sdRelativePath"], data["feature"]["sdRelativePath"])
if "sdAlwaysAvailable" in data["feature"].keys(): s.setBoolean(["feature", "sdAlwaysAvailable"], data["feature"]["sdAlwaysAvailable"])
if "swallowOkAfterResend" in data["feature"].keys(): s.setBoolean(["feature", "swallowOkAfterResend"], data["feature"]["swallowOkAfterResend"])
if "repetierTargetTemp" in data["feature"].keys(): s.setBoolean(["feature", "repetierTargetTemp"], data["feature"]["repetierTargetTemp"])
if "externalHeatupDetection" in data["feature"].keys(): s.setBoolean(["feature", "externalHeatupDetection"], data["feature"]["externalHeatupDetection"])
if "keyboardControl" in data["feature"].keys(): s.setBoolean(["feature", "keyboardControl"], data["feature"]["keyboardControl"])
if "gcodeViewer" in data["feature"]: s.setBoolean(["gcodeViewer", "enabled"], data["feature"]["gcodeViewer"])
if "sizeThreshold" in data["feature"]: s.setInt(["gcodeViewer", "sizeThreshold"], data["feature"]["sizeThreshold"])
if "mobileSizeThreshold" in data["feature"]: s.setInt(["gcodeViewer", "mobileSizeThreshold"], data["feature"]["mobileSizeThreshold"])
if "temperatureGraph" in data["feature"]: s.setBoolean(["feature", "temperatureGraph"], data["feature"]["temperatureGraph"])
if "waitForStart" in data["feature"]: s.setBoolean(["feature", "waitForStartOnConnect"], data["feature"]["waitForStart"])
if "alwaysSendChecksum" in data["feature"]: s.setBoolean(["feature", "alwaysSendChecksum"], data["feature"]["alwaysSendChecksum"])
if "neverSendChecksum" in data["feature"]: s.setBoolean(["feature", "neverSendChecksum"], data["feature"]["neverSendChecksum"])
if "sdSupport" in data["feature"]: s.setBoolean(["feature", "sdSupport"], data["feature"]["sdSupport"])
if "sdRelativePath" in data["feature"]: s.setBoolean(["feature", "sdRelativePath"], data["feature"]["sdRelativePath"])
if "sdAlwaysAvailable" in data["feature"]: s.setBoolean(["feature", "sdAlwaysAvailable"], data["feature"]["sdAlwaysAvailable"])
if "swallowOkAfterResend" in data["feature"]: s.setBoolean(["feature", "swallowOkAfterResend"], data["feature"]["swallowOkAfterResend"])
if "repetierTargetTemp" in data["feature"]: s.setBoolean(["feature", "repetierTargetTemp"], data["feature"]["repetierTargetTemp"])
if "externalHeatupDetection" in data["feature"]: s.setBoolean(["feature", "externalHeatupDetection"], data["feature"]["externalHeatupDetection"])
if "keyboardControl" in data["feature"]: s.setBoolean(["feature", "keyboardControl"], data["feature"]["keyboardControl"])
if "pollWatched" in data["feature"]: s.setBoolean(["feature", "pollWatched"], data["feature"]["pollWatched"])
if "ignoreIdenticalResends" in data["feature"]: s.setBoolean(["feature", "ignoreIdenticalResends"], data["feature"]["ignoreIdenticalResends"])
if "modelSizeDetection" in data["feature"]: s.setBoolean(["feature", "modelSizeDetection"], data["feature"]["modelSizeDetection"])
if "firmwareDetection" in data["feature"]: s.setBoolean(["feature", "firmwareDetection"], data["feature"]["firmwareDetection"])
if "printCancelConfirmation" in data["feature"]: s.setBoolean(["feature", "printCancelConfirmation"], data["feature"]["printCancelConfirmation"])
if "blockWhileDwelling" in data["feature"]: s.setBoolean(["feature", "blockWhileDwelling"], data["feature"]["blockWhileDwelling"])
if "g90InfluencesExtruder" in data["feature"]: s.setBoolean(["feature", "g90InfluencesExtruder"], data["feature"]["g90InfluencesExtruder"])
if "serial" in data.keys():
if "autoconnect" in data["serial"].keys(): s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
if "port" in data["serial"].keys(): s.set(["serial", "port"], data["serial"]["port"])
if "baudrate" in data["serial"].keys(): s.setInt(["serial", "baudrate"], data["serial"]["baudrate"])
if "timeoutConnection" in data["serial"].keys(): s.setFloat(["serial", "timeout", "connection"], data["serial"]["timeoutConnection"])
if "timeoutDetection" in data["serial"].keys(): s.setFloat(["serial", "timeout", "detection"], data["serial"]["timeoutDetection"])
if "timeoutCommunication" in data["serial"].keys(): s.setFloat(["serial", "timeout", "communication"], data["serial"]["timeoutCommunication"])
if "timeoutTemperature" in data["serial"].keys(): s.setFloat(["serial", "timeout", "temperature"], data["serial"]["timeoutTemperature"])
if "timeoutTemperatureTargetSet" in data["serial"].keys(): s.setFloat(["serial", "timeout", "temperatureTargetSet"], data["serial"]["timeoutTemperatureTargetSet"])
if "timeoutSdStatus" in data["serial"].keys(): s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"])
if "autoconnect" in data["serial"]: s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
if "port" in data["serial"]: s.set(["serial", "port"], data["serial"]["port"])
if "baudrate" in data["serial"]: s.setInt(["serial", "baudrate"], data["serial"]["baudrate"])
if "timeoutConnection" in data["serial"]: s.setFloat(["serial", "timeout", "connection"], data["serial"]["timeoutConnection"])
if "timeoutDetection" in data["serial"]: s.setFloat(["serial", "timeout", "detection"], data["serial"]["timeoutDetection"])
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"])
if "longRunningCommands" in data["serial"] and isinstance(data["serial"]["longRunningCommands"], (list, tuple)): s.set(["serial", "longRunningCommands"], data["serial"]["longRunningCommands"])
@@ -338,7 +370,7 @@ def _saveSettings(data):
if "maxTimeoutsLong" in data["serial"]: s.setInt(["serial", "maxCommunicationTimeouts", "long"], data["serial"]["maxTimeoutsLong"])
oldLog = s.getBoolean(["serial", "log"])
if "log" in data["serial"].keys(): s.setBoolean(["serial", "log"], data["serial"]["log"])
if "log" in data["serial"]: s.setBoolean(["serial", "log"], data["serial"]["log"])
if oldLog and not s.getBoolean(["serial", "log"]):
# disable debug logging to serial.log
logging.getLogger("SERIAL").debug("Disabling serial logging")
@@ -349,22 +381,24 @@ def _saveSettings(data):
logging.getLogger("SERIAL").debug("Enabling serial logging")
if "folder" in data.keys():
if "uploads" in data["folder"].keys(): s.setBaseFolder("uploads", data["folder"]["uploads"])
if "timelapse" in data["folder"].keys(): s.setBaseFolder("timelapse", data["folder"]["timelapse"])
if "timelapseTmp" in data["folder"].keys(): s.setBaseFolder("timelapse_tmp", data["folder"]["timelapseTmp"])
if "logs" in data["folder"].keys(): s.setBaseFolder("logs", data["folder"]["logs"])
if "watched" in data["folder"].keys(): s.setBaseFolder("watched", data["folder"]["watched"])
if "uploads" in data["folder"]: s.setBaseFolder("uploads", data["folder"]["uploads"])
if "timelapse" in data["folder"]: s.setBaseFolder("timelapse", data["folder"]["timelapse"])
if "timelapseTmp" in data["folder"]: s.setBaseFolder("timelapse_tmp", data["folder"]["timelapseTmp"])
if "logs" in data["folder"]: s.setBaseFolder("logs", data["folder"]["logs"])
if "watched" in data["folder"]: s.setBaseFolder("watched", data["folder"]["watched"])
if "temperature" in data.keys():
if "profiles" in data["temperature"].keys(): s.set(["temperature", "profiles"], data["temperature"]["profiles"])
if "cutoff" in data["temperature"].keys(): s.setInt(["temperature", "cutoff"], data["temperature"]["cutoff"])
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"])
if "system" in data.keys():
if "actions" in data["system"].keys(): s.set(["system", "actions"], data["system"]["actions"])
if "events" in data["system"].keys(): s.set(["system", "events"], data["system"]["events"])
if "actions" in data["system"]: s.set(["system", "actions"], data["system"]["actions"])
if "events" in data["system"]: s.set(["system", "events"], data["system"]["events"])
if "scripts" in data:
if "gcode" in data["scripts"] and isinstance(data["scripts"]["gcode"], dict):
@@ -375,9 +409,9 @@ def _saveSettings(data):
if "server" in data:
if "commands" in data["server"]:
if "systemShutdownCommand" in data["server"]["commands"].keys(): s.set(["server", "commands", "systemShutdownCommand"], data["server"]["commands"]["systemShutdownCommand"])
if "systemRestartCommand" in data["server"]["commands"].keys(): s.set(["server", "commands", "systemRestartCommand"], data["server"]["commands"]["systemRestartCommand"])
if "serverRestartCommand" in data["server"]["commands"].keys(): s.set(["server", "commands", "serverRestartCommand"], data["server"]["commands"]["serverRestartCommand"])
if "systemShutdownCommand" in data["server"]["commands"]: s.set(["server", "commands", "systemShutdownCommand"], data["server"]["commands"]["systemShutdownCommand"])
if "systemRestartCommand" in data["server"]["commands"]: s.set(["server", "commands", "systemRestartCommand"], data["server"]["commands"]["systemRestartCommand"])
if "serverRestartCommand" in data["server"]["commands"]: s.set(["server", "commands", "serverRestartCommand"], data["server"]["commands"]["serverRestartCommand"])
if "diskspace" in data["server"]:
if "warning" in data["server"]["diskspace"]: s.setInt(["server", "diskspace", "warning"], data["server"]["diskspace"]["warning"])
if "critical" in data["server"]["diskspace"]: s.setInt(["server", "diskspace", "critical"], data["server"]["diskspace"]["critical"])
+16 -16
View File
@@ -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()
@@ -197,43 +203,37 @@ def setTimelapseConfig():
return make_response("Invalid value for fps: %d" % fps, 400)
if "interval" in data:
config["options"] = {
"interval": 10
}
try:
interval = int(data["interval"])
except ValueError:
return make_response("Invalid value for interval: %r" % data["interval"])
return make_response("Invalid value for interval: %r" % data["interval"], 400)
else:
if interval > 0:
config["options"]["interval"] = interval
else:
return make_response("Invalid value for interval: %d" % interval)
return make_response("Invalid value for interval: %d" % interval, 400)
if "capturePostRoll" in data:
config["options"]["capturePostRoll"] = True
try:
capturePostRoll = bool(data["capturePostRoll"])
except ValueError:
return make_response("Invalid value for capturePostRoll: %r" % data["capturePostRoll"])
return make_response("Invalid value for capturePostRoll: %r" % data["capturePostRoll"], 400)
else:
config["options"]["capturePostRoll"] = capturePostRoll
if capturePostRoll >= 0:
config["options"]["capturePostRoll"] = capturePostRoll
else:
return make_response("Invalid value for capturePostRoll: %d" % capturePostRoll, 400)
if "retractionZHop" in data:
config["options"] = {
"retractionZHop": 0
}
try:
retractionZHop = float(data["retractionZHop"])
except ValueError:
return make_response("Invalid value for retraction Z-Hop: %r" % data["retractionZHop"])
return make_response("Invalid value for retraction Z-Hop: %r" % data["retractionZHop"], 400)
else:
if retractionZHop >= 0:
config["options"]["retractionZHop"] = retractionZHop
else:
return make_response("Invalid value for retraction Z-Hop: %d" % retractionZHop)
return make_response("Invalid value for retraction Z-Hop: %d" % retractionZHop, 400)
if admin_permission.can() and "save" in data and data["save"] in valid_boolean_trues:
+5 -3
View File
@@ -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:
@@ -484,8 +486,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 +505,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()))
+36 -10
View File
@@ -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))
+53 -3
View File
@@ -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
+100
View File
@@ -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")
+3 -1
View File
@@ -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
@@ -520,7 +522,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"))
)
+74 -14
View File
@@ -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": {
@@ -155,6 +157,8 @@ default_settings = {
},
"webcam": {
"stream": None,
"streamRatio": "16:9",
"streamTimeout": 5,
"snapshot": None,
"ffmpeg": None,
"ffmpegThreads": 1,
@@ -204,7 +208,8 @@ default_settings = {
"modelSizeDetection": True,
"firmwareDetection": True,
"printCancelConfirmation": True,
"blockWhileDwelling": False
"blockWhileDwelling": False,
"g90InfluencesExtruder": False
},
"folder": {
"uploads": None,
@@ -226,11 +231,12 @@ 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,
"defaultProfile": {}
"default": None
},
"printerParameters": {
"pauseTriggers": [],
@@ -296,7 +302,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"}
],
@@ -328,7 +334,6 @@ default_settings = {
"preemptive": True
},
"webassets": {
"minify": False,
"bundle": True,
"clean_on_startup": True
},
@@ -361,7 +366,12 @@ default_settings = {
"sendBusy": False,
"simulateReset": True,
"preparedOks": [],
"okFormatString": "ok"
"okFormatString": "ok",
"m115FormatString": "FIRMWARE_NAME: {firmware_name} PROTOCOL_VERSION:1.0",
"m115ReportCapabilities": False,
"capabilities": {
"AUTOREPORT_TEMP": True
}
}
}
}
@@ -556,9 +566,9 @@ class Settings(object):
self._configfile = os.path.join(self._basedir, "config.yaml")
self.load(migrate=True)
if self.get(["api", "key"]) is None:
self.set(["api", "key"], ''.join('%02X' % z for z in bytes(uuid.uuid4().bytes)))
self.save(force=True)
apikey = self.get(["api", "key"])
if not apikey or apikey == "n/a":
self.generateApiKey()
self._script_env = self._init_script_templating()
@@ -1267,23 +1277,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
@@ -1311,11 +1341,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
@@ -1436,8 +1469,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
@@ -1449,8 +1490,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
@@ -1497,6 +1546,17 @@ class Settings(object):
with atomic_write(filename, "wb", max_permissions=0o666) as f:
f.write(script)
def generateApiKey(self):
apikey = ''.join('%02X' % z for z in bytes(uuid.uuid4().bytes))
self.set(["api", "key"], apikey)
self.save(force=True)
return apikey
def deleteApiKey(self):
self.set(["api", "key"], None)
self.save(force=True)
def _default_basedir(applicationName):
# taken from http://stackoverflow.com/questions/1084697/how-do-i-store-desktop-application-data-in-a-cross-platform-way-for-python
if sys.platform == "darwin":
-403
View File
@@ -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
View File
@@ -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
+1
View File
@@ -0,0 +1 @@
.ui-pnotify-closer,.ui-pnotify-sticker{float:right;margin-left:.2em}
+1
View File
@@ -0,0 +1 @@
.ui-pnotify{top:25px;right:25px;position:absolute;height:auto;z-index:9999}html>body>.ui-pnotify{position:fixed}.ui-pnotify .ui-pnotify-shadow{-webkit-box-shadow:0 2px 10px rgba(50,50,50,.5);-moz-box-shadow:0 2px 10px rgba(50,50,50,.5);box-shadow:0 2px 10px rgba(50,50,50,.5)}.ui-pnotify-container{background-position:0 0;padding:.8em;height:100%;margin:0}.ui-pnotify-container.ui-pnotify-sharp{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.ui-pnotify-title{display:block;margin-bottom:.4em;margin-top:0}.ui-pnotify-text{display:block}.ui-pnotify-icon,.ui-pnotify-icon span{display:block;float:left;margin-right:.2em}.ui-pnotify.stack-bottomleft,.ui-pnotify.stack-topleft{left:25px;right:auto}.ui-pnotify.stack-bottomleft,.ui-pnotify.stack-bottomright{bottom:25px;top:auto}
+1
View File
@@ -0,0 +1 @@
.ui-pnotify-history-container{position:absolute;top:0;right:18px;width:70px;border-top:none;padding:0;-webkit-border-top-left-radius:0;-moz-border-top-left-radius:0;border-top-left-radius:0;-webkit-border-top-right-radius:0;-moz-border-top-right-radius:0;border-top-right-radius:0;z-index:10000}.ui-pnotify-history-container.ui-pnotify-history-fixed{position:fixed}.ui-pnotify-history-container .ui-pnotify-history-header{padding:2px;text-align:center}.ui-pnotify-history-container button{cursor:pointer;display:block;width:100%}.ui-pnotify-history-container .ui-pnotify-history-pulldown{display:block;margin:0 auto}
-1
View File
@@ -1 +0,0 @@
.ui-pnotify{top:25px;right:25px;position:absolute;height:auto;z-index:9999}html>body>.ui-pnotify{position:fixed}.ui-pnotify .ui-pnotify-shadow{-webkit-box-shadow:0 2px 10px rgba(50,50,50,.5);-moz-box-shadow:0 2px 10px rgba(50,50,50,.5);box-shadow:0 2px 10px rgba(50,50,50,.5)}.ui-pnotify-container{background-position:0 0;padding:.8em;height:100%;margin:0}.ui-pnotify-sharp{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.ui-pnotify-title{display:block;margin-bottom:.4em;margin-top:0}.ui-pnotify-text{display:block}.ui-pnotify-icon,.ui-pnotify-icon span{display:block;float:left;margin-right:.2em}.ui-pnotify.stack-bottomleft,.ui-pnotify.stack-topleft{left:25px;right:auto}.ui-pnotify.stack-bottomleft,.ui-pnotify.stack-bottomright{bottom:25px;top:auto}.ui-pnotify-closer,.ui-pnotify-sticker{float:right;margin-left:.2em}.ui-pnotify-history-container{position:absolute;top:0;right:18px;width:70px;border-top:none;padding:0;-webkit-border-top-left-radius:0;-moz-border-top-left-radius:0;border-top-left-radius:0;-webkit-border-top-right-radius:0;-moz-border-top-right-radius:0;border-top-right-radius:0;z-index:10000}.ui-pnotify-history-container.ui-pnotify-history-fixed{position:fixed}.ui-pnotify-history-container .ui-pnotify-history-header{padding:2px;text-align:center}.ui-pnotify-history-container button{cursor:pointer;display:block;width:100%}.ui-pnotify-history-container .ui-pnotify-history-pulldown{display:block;margin:0 auto}
+152 -80
View File
@@ -9,11 +9,15 @@ var firstReport;
var toolOffsets = [
{x: 0, y: 0}
];
var g90InfluencesExtruder = false;
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;
@@ -75,6 +79,7 @@ var sendAnalyzeDone = function () {
max: max,
min: min,
modelSize: modelSize,
boundingBox: boundingBox,
totalFilament: totalFilament,
filamentByLayer: filamentByLayer,
printTime: printTime,
@@ -105,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;
@@ -112,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;
@@ -119,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;
@@ -164,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;
@@ -232,8 +289,8 @@ var doParse = function () {
var center_i, center_j, direction;
var prevX = 0, prevY = 0, prevZ = 0;
var f, lastF = 4000;
var extrude = false, extrudeRelative = false, retract = 0;
var positionRelative = false;
var extrude = false, relativeE = false, retract = 0;
var relativeMode = false;
var zLift = false;
var zLiftZ = undefined;
var zLiftMoves = [];
@@ -244,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;
@@ -268,30 +331,30 @@ var doParse = function () {
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 (positionRelative) {
x = prevX + Number(args[j].slice(1)) + offset.x;
if (relativeMode) {
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 (positionRelative) {
y = prevY + Number(args[j].slice(1)) + offset.y;
if (relativeMode) {
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;
case 'z':
if (positionRelative) {
if (relativeMode) {
z = prevZ + Number(args[j].slice(1));
} else {
z = Number(args[j].slice(1));
@@ -306,20 +369,20 @@ var doParse = function () {
assumeNonDC = true;
numSlice = Number(args[j].slice(1));
if (!extrudeRelative) {
if (relativeMode || relativeE) {
prev_extrude[tool]["abs"] = numSlice;
prev_extrude[tool][argChar] += numSlice;
} else {
// absolute extrusion positioning
prev_extrude[tool]["abs"] = numSlice - prev_extrude[tool][argChar];
prev_extrude[tool][argChar] = numSlice;
} else {
prev_extrude[tool]["abs"] = numSlice;
prev_extrude[tool][argChar] += numSlice;
}
extrude = prev_extrude[tool]["abs"] > 0;
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;
@@ -341,9 +404,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;
}
@@ -354,31 +417,35 @@ 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;
}
} else if (/^(?:M82)/i.test(line)) {
extrudeRelative = false;
relativeE = false;
} else if (/^(?:G91)/i.test(line)) {
positionRelative = true;
extrudeRelative = true;
relativeMode = true;
if (g90InfluencesExtruder) {
relativeE = true;
}
} else if (/^(?:G90)/i.test(line)) {
positionRelative = false;
extrudeRelative = false;
relativeMode = false;
if (g90InfluencesExtruder) {
relativeE = false;
}
} else if (/^(?:M83)/i.test(line)) {
extrudeRelative = true;
relativeE = true;
} else if (/^(?:M101)/i.test(line)) {
dcExtrude = true;
} 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;
@@ -390,11 +457,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':
@@ -407,10 +474,10 @@ var doParse = function () {
case 'b':
case 'c':
numSlice = Number(args[j].slice(1));
if (!extrudeRelative)
prev_extrude[tool][argChar] = 0;
else {
if (relativeMode || relativeE) {
prev_extrude[tool][argChar] = numSlice;
} else {
prev_extrude[tool][argChar] = 0;
}
break;
}
@@ -423,9 +490,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;
@@ -449,11 +516,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;
}
@@ -462,13 +529,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;
}
@@ -477,7 +544,7 @@ var doParse = function () {
zLift = false;
}
if (typeof(z) !== 'undefined' && z != prevZ) {
if (typeof(z) !== 'undefined' && z !== prevZ) {
if (z_heights[z]) {
layer = z_heights[z];
} else {
@@ -488,7 +555,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 {
@@ -548,7 +615,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 = [];
@@ -568,7 +635,10 @@ 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();
gcode = [];
@@ -589,6 +659,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;
@@ -601,6 +672,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;
@@ -24,7 +27,16 @@ GCODE.gCodeReader = (function(){
analyzeModel: false,
toolOffsets: [
{x: 0, y: 0}
]
],
bed: {
x: undefined,
y: undefined,
r: undefined,
circular: undefined,
centeredOrigin: undefined
},
ignoreOutsideBed: false,
g90InfluencesExtruder: false
};
var percentageTree = undefined;
@@ -122,6 +134,12 @@ 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){
@@ -138,7 +156,10 @@ GCODE.gCodeReader = (function(){
gcode: gcode,
options: {
firstReport: 5,
toolOffsets: gCodeOptions["toolOffsets"]
toolOffsets: gCodeOptions["toolOffsets"],
bed: gCodeOptions["bed"],
ignoreOutsideBed: gCodeOptions["ignoreOutsideBed"],
g90InfluencesExtruder: gCodeOptions["g90InfluencesExtruder"]
}
}
}
@@ -180,6 +201,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;
@@ -201,6 +223,7 @@ GCODE.gCodeReader = (function(){
min: min,
max: max,
modelSize: modelSize,
boundingBox: boundingBox,
totalFilament: totalFilament,
speeds: speeds,
speedsByLayer: speedsByLayer,
+67 -20
View File
@@ -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);
},
+2 -1
View File
@@ -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);
+40 -6
View File
@@ -11,6 +11,13 @@
background-color: #ffffff;
}
a,
a:hover,
a:active,
a:visited {
color: #333333;
}
#startup-overlay {
position: fixed;
top: 0;
@@ -53,6 +60,10 @@
text-align: center;
}
.normal {
color: #333333;
}
.green {
color: #169300;
}
@@ -166,9 +177,22 @@
var cachedTimeout;
var message = window.document.getElementById("message");
var reloadnow = window.document.getElementById("reloadnow");
var reloadnowlink = window.document.getElementById("reloadnowlink");
var reload = function() {
var reloadUrl = baseUrl + currentQuery + currentFragment;
if (reloadUrl == window.location.href) {
window.location.reload(false);
} else {
window.location.href = reloadUrl;
}
};
var indexCached = false;
var indexCachedCallback = function(result) {
if (indexCached) return;
if (result == "load") {
if (indexCached) {
return;
@@ -178,13 +202,9 @@
indexCached = true;
message.className = "pulsate1 green";
message.innerText = "OctoPrint server ready, reloading page...";
reloadnow.style.display = "none";
var reloadUrl = baseUrl + currentQuery + currentFragment;
if (reloadUrl == window.location.href) {
window.location.reload(false);
} else {
window.location.href = reloadUrl;
}
reload();
} else {
// cached.gif still not available, let's look at it again in a second
cachedTimeout = setTimeout(function() {
@@ -198,6 +218,19 @@
if (result == "load") {
// our online.gif loaded, so the server is up, let's wait for it to become ready
serverIsOnline = true;
message.innerText = "OctoPrint server started, waiting for it to get ready...";
reloadnowlink.onclick = function() {
indexCached = true; // not really, but we fake it
message.className = "pulsate1";
message.innerText = "Reloading page...";
reloadnow.style.display = "none";
reload();
};
reloadnow.style.display = "block";
ping(indexCachedUrl, timeout, indexCachedCallback);
} else {
// online.gif still not available, let's look at it again later
@@ -255,6 +288,7 @@
<div class="inner">
<div class="content">
<h1 id="message" class="pulsate3">OctoPrint is still starting up, please wait...</h1>
<small id="reloadnow" style="display: none"><a id="reloadnowlink" class="normal" href="javascript:void(0)">Don't wait, reload now!</a></small>
</div>
</div>
</div>
@@ -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) {
@@ -6,6 +6,7 @@
}
})(this, function(OctoPrintClient, $) {
var url = "api/settings";
var apiKeyUrl = url + "/apikey";
var OctoPrintSettingsClient = function(base) {
this.base = base;
@@ -40,6 +41,10 @@
return this.save(data, opts);
};
OctoPrintSettingsClient.prototype.generateApiKey = function (opts) {
return this.base.postJson(apiKeyUrl, opts);
};
OctoPrintClient.registerComponent("settings", OctoPrintSettingsClient);
return OctoPrintSettingsClient;
});
+5 -4
View File
@@ -27,10 +27,6 @@
};
OctoPrintSocketClient.prototype.propagateMessage = function(event, data) {
if (!this.registeredHandlers.hasOwnProperty(event)) {
return;
}
var start = new Date().getTime();
var eventObj = {event: event, data: data};
@@ -110,6 +106,7 @@
var onOpen = function() {
self.reconnecting = false;
self.reconnectTrial = 0;
self.onConnected();
};
var onClose = function(e) {
@@ -121,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);
@@ -164,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();
+150 -97
View File
@@ -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)
+209 -8
View File
@@ -162,6 +162,12 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
return undefined;
};
self.resetPage = function() {
if (self.currentPage() > self.lastPage()) {
self.currentPage(self.lastPage());
}
};
//~~ searching
self.changeSearchFunction = function(searchFunction) {
@@ -392,7 +398,7 @@ function formatFuzzyPrintTime(totalSeconds) {
*
* Accuracy decreases the higher the estimation is:
*
* * less than 30s: "a couple of seconds"
* * less than 30s: "a few seconds"
* * 30s to a minute: "less than a minute"
* * 1 to 30min: rounded to full minutes, above 30s is minute + 1 ("27 minutes", "2 minutes")
* * 30min to 40min: "40 minutes"
@@ -489,7 +495,7 @@ function formatFuzzyPrintTime(totalSeconds) {
} else {
// only seconds
if (seconds < 30) {
text = gettext("a couple of seconds");
text = gettext("a few seconds");
} else {
text = gettext("less than a minute");
}
@@ -518,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&deg;C (%.1f&deg;F)", temp, temp * 9 / 5 + 32);
} else {
@@ -640,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">&times;</a><h3>' + title + '</h3>');
@@ -657,23 +666,198 @@ 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;
}
/**
* Shows a progress modal depending on a supplied promise.
*
* 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:
*
* * 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.
*
* To determine the progress, calling code should supply the prognosed maximum number of
* progress events. An internal counter will increment on each progress event and used together
* with the max value to calculate the percentage to display on the progress bar.
*
* If no max value is set, the progress bar will show a striped animation at 100% fill status
* to visualize "unknown but ongoing" status.
*
* Available options:
*
* * title: the title of the modal, defaults to "Progress"
* * message: the message of the modal, defaults to ""
* * buttonText: the text on the close button, defaults to "Close"
* * max: maximum number of expected progress events (when 100% will be reached), defaults
* to undefined
* * close: whether to close the dialog on completion, defaults to false
* * output: whether to display the progress texts in an output field, defaults to false
* * dialogClass: additional class to apply to the dialog div
* * barClassSuccess: additional class for the progress bar while all progress events are
* successful
* * barClassFailure: additional class for the progress bar when a progress event was
* unsuccessful
* * outputClassSuccess: additional class for successful output lines
* * outputClassFailure: additional class for unsuccessful output lines
*
* @param options modal options
* @param promise promise to monitor
* @returns {*|jQuery} the modal object
*/
function showProgressModal(options, promise) {
var title = options.title || gettext("Progress");
var message = options.message || "";
var buttonText = options.button || gettext("Close");
var max = options.max || undefined;
var close = options.close || false;
var output = options.output || false;
var dialogClass = options.dialogClass || "";
var barClassSuccess = options.barClassSuccess || "";
var barClassFailure = options.barClassFailure || "bar-danger";
var outputClassSuccess = options.outputClassSuccess || "";
var outputClassFailure = options.outputClassFailure || "text-error";
var modalHeader = $('<h3>' + title + '</h3>');
var paragraph = $('<p>' + message + '</p>');
var progress = $('<div class="progress progress-text-centered"></div>');
var progressBar = $('<div class="bar"></div>')
.addClass(barClassSuccess);
var progressTextBack = $('<span class="progress-text-back"></span>');
var progressTextFront = $('<span class="progress-text-front"></span>')
.width(progress.width());
if (max == undefined) {
progress.addClass("progress-striped active");
progressBar.width("100%");
}
progressBar
.append(progressTextFront);
progress
.append(progressTextBack)
.append(progressBar);
var button = $('<button class="btn">' + buttonText + '</button>')
.prop("disabled", true)
.attr("data-dismiss", "modal")
.attr("aria-hidden", "true");
var modalBody = $('<div></div>')
.addClass('modal-body')
.append(paragraph)
.append(progress);
var pre;
if (output) {
pre = $("<pre class='pre-scrollable pre-output' style='height: 70px; font-size: 0.8em'></pre>");
modalBody.append(pre);
}
var modal = $('<div></div>')
.addClass('modal hide fade')
.addClass(dialogClass)
.append($('<div></div>').addClass('modal-header').append(modalHeader))
.append(modalBody)
.append($('<div></div>').addClass('modal-footer').append(button));
modal.modal({keyboard: false, backdrop: "static", show: true});
var counter = 0;
promise
.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) {
value = 100;
} else {
counter++;
value = Math.max(Math.min(counter * 100 / max, 100), 0);
}
// update progress bar
progressBar.width(String(value) + "%");
progressTextFront.text(short);
progressTextBack.text(short);
progressTextFront.width(progress.width());
// if not successful, apply failure class
if (!success && !progressBar.hasClass(barClassFailure)) {
progressBar
.removeClass(barClassSuccess)
.addClass(barClassFailure);
}
if (output && pre) {
if (success) {
pre.append($("<span class='" + outputClassSuccess + "'>" + long + "</span>"));
} else {
pre.append($("<span class='" + outputClassFailure + "'>" + long + "</span>"));
}
pre.scrollTop(pre[0].scrollHeight - pre.height());
}
})
.done(function() {
button.prop("disabled", false);
if (close) {
modal.modal("hide");
}
})
.fail(function() {
button.prop("disabled", false);
});
return modal;
}
function showReloadOverlay() {
$("#reloadui_overlay").show();
}
function wrapPromiseWithAlways(p) {
var deferred = $.Deferred();
p.always(function() { deferred.resolve.apply(deferred, arguments); });
return deferred.promise();
}
function commentableLinesToArray(lines) {
return splitTextToArray(lines, "\n", true, function(item) {return !_.startsWith(item, "#")});
}
@@ -799,6 +983,22 @@ 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) {
callViewModelsIf(allViewModels, method, undefined, callback);
}
@@ -889,8 +1089,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
@@ -904,7 +1105,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 {
+127 -26
View File
@@ -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
@@ -444,6 +473,18 @@ $(function() {
}
};
$.fn.lazyload = function() {
return this.each(function() {
if (this.tagName.toLowerCase() != "img") return;
var src = this.getAttribute("data-src");
if (src) {
this.setAttribute("src", src);
this.removeAttribute("data-src");
}
});
};
// Use bootstrap tabdrop for tabs and pills
$('.nav-pills, .nav-tabs').tabdrop();
@@ -482,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...");
@@ -551,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();
@@ -563,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) {
@@ -573,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);
});
});
}
);
Loaded 100 of 209 files, more files were not shown because too many files have changed in this diff. Show more