Compare commits

..
220 Commits
Author SHA1 Message Date
Gina Häußge dedadbc9ac Added another little fix to the change log 2015-12-07 13:23:58 +01:00
Gina Häußge cda399f11a Merge branch 'fix/ignoreCannotOpenSubdir' into maintenance 2015-12-07 13:21:57 +01:00
Gina Häußge ec42c45204 Explained a bit better how the update bug in 1.2.7 actually manifests 2015-12-07 12:56:54 +01:00
Gina Häußge c98d3d1655 Also assume presence of heated bed in "add profile" dialog 2015-12-07 11:53:41 +01:00
Gina Häußge 5e96bd8b6a Fix: "Server Offline" should always win against "Please reload"
Nothing to reload if the server is offline, so show the offline message above
the reload one.
2015-12-07 11:51:20 +01:00
Gina Häußge 2b4a985d85 Assume the presence of a heated bed in the default profile 2015-12-07 11:04:09 +01:00
Gina Häußge 56a51a3800 Let's try releasing 1.2.8 2015-12-07 10:19:57 +01:00
Gina Häußge 0982c8cc62 Ignore the "cannot (open|error) subdir" errors from Marlin 2015-12-07 09:26:25 +01:00
Mark Bastiaans 682e78c256 Added name to authors
(cherry picked from commit 406fe75)
2015-12-04 17:37:27 +01:00
Mark Bastiaans d90a9e7fc4 Fixed checks with os.path.realpath() for systems with symlinked paths
(cherry picked from commit b7c9949)
2015-12-04 17:36:49 +01:00
Gina Häußge 9d6b6cf103 Going to release 1.2.8 after the weekend 2015-12-03 12:02:36 +01:00
Gina Häußge bad88da2fe Fixed a scrolling issue on the terminal tab 2015-12-02 18:12:08 +01:00
Gina Häußge 1e9ea8e85e Updated Changelog again 2015-12-02 17:12:17 +01:00
Gina Häußge c5bc000b56 Increased timeout for waiting for restart after update
20sec is too little.
2015-12-02 17:12:04 +01:00
Gina Häußge 42d288c0e2 Updatefix 1.2.7 plugin needs restart after all 2015-12-02 16:34:57 +01:00
Gina Häußge 935c1da30f Updated Changelog for 1.2.8 again
Now includes note about updatefix plugin and changelog
entry about fixed softwareupdate issue.
2015-12-02 14:06:49 +01:00
Gina Häußge 612005c4f6 Fixed a bug preventing OctoPrint from updating via github releases
Noticed while testing update path from 1.2.7 to 1.2.8

*bangs her head against a wall*
2015-12-02 09:25:15 +01:00
Gina Häußge ee1f9029d1 Preparing release of version 1.2.8 2015-12-01 13:18:11 +01:00
Gina Häußge 1d8cf86215 Updated translation source files and german translation 2015-12-01 11:42:57 +01:00
Gina Häußge b8283b2499 And of course now I spotted another left-over... 2015-12-01 10:29:11 +01:00
Gina Häußge da0f1fa3c8 Some more small changes and updated the flow chart 2015-12-01 10:22:23 +01:00
Gina Häußge 0d18ca421b Typos are my nemesis 2015-11-30 19:46:28 +01:00
Gina Häußge 48dd2657e9 Some more rewording and fixing of typos 2015-11-30 19:40:31 +01:00
Gina Häußge 62f2d11f8b Major overhaul of CONTRIBUTING.md
Now includes all bug reporting related information
as well plus a little flow chart regarding ticket creation.

Also reworded large sections.
2015-11-30 19:31:33 +01:00
Gina Häußge 93bbedae86 Only process bed temps & commands if printer profile has heated bed
Solves #1125
2015-11-30 11:11:35 +01:00
Gina Häußge 40fe74ef45 Cut off terminal after 3000 lines
When autoscroll was disabled, terminal could run on endlessly, eating
memory until the browser crashes. Now a hard upper limit ensures
that not more than 3000 lines are ever stored in the terminal. If autoscroll
is disabled and the limit is reached, no more log lines will be added. That
ensures that the log will not scroll and the current log excerpt will stay put.
2015-11-27 15:05:55 +01:00
Gina Häußge 043b213a96 Move event processing for gcodefiles into corresponding viewmodel
Also fixes a javascript error (gcodeFileViewModel unknown)
2015-11-27 11:31:17 +01:00
Gina Häußge 6db57122b4 Catch and log all exceptions that might be raised in the watchdog
Solves #1120
2015-11-26 16:07:29 +01:00
Gina Häußge d0eca800fb Make the current request's baseurl to a part of the cache key
This way we create separate caches for URLs access via different schemes/prefixes/etc.
Otherwise our generated page might not work when accessing OctoPrint from external
after accessing it from internal once.
2015-11-23 12:17:57 +01:00
Gina Häußge a6c24e174d Fixed version reporting on detached HEADs
HEAD "branch" also should disable usage of lookup table.
2015-11-20 13:54:09 +01:00
Gina Häußge a52a5ca338 GCodeViewer: Even if off screen render 100% view on PrintDone event
Otherwise the GCODE Viewer will get stuck "half way through" if
"sync with progress" is enabled but the tab/browser tab loses focus
during printing and only regains it after the print has finished.
2015-11-20 11:40:06 +01:00
Gina Häußge acc85127c5 Track browser tab visibility, only activate webcam/gcode viewer when visible
This might help with #1065 if indeed is related to background tab suspending behaviours in
browsers, but is a completely blind guess at this point since I still have not been able to
reproduce that issue myself.

Backported.

(cherry picked from commit 720cdad)
2015-11-20 11:06:25 +01:00
Gina Häußge 454f16a7c3 Fixed a broken unit test (pro tip: test new tests before committing...) 2015-11-20 10:12:15 +01:00
Gina Häußge a731f748d9 Moved existing hidden file checks to utilize octoprint.util.is_hidden_path 2015-11-20 10:02:06 +01:00
Gina Häußge 9a7bddd530 Also don't include hidden files in other templates 2015-11-19 19:03:04 +01:00
Gina Häußge 83f66e133e Do not include hidden files in listed gcode scripts 2015-11-19 18:58:56 +01:00
Gina Häußge ab97abf13e Some fixes and unit tests for octoprint.util.atomic_write, .bom_aware_open and .tempdir
(cherry picked from commit 4fcb853)
2015-11-19 15:15:35 +01:00
Gina Häußge 7820c17d08 [Cura] Make plugin a bit more verbose regarding usage & setup 2015-11-19 11:42:12 +01:00
Salandora 9ed79adb8d Fix SD Support deactivated bug and added "unknown command" to the whitelist of errors 2015-11-17 19:32:34 +01:00
Gina Häußge b98348de02 Cache rendered page and translation files indefinitely 2015-11-06 11:46:12 +01:00
Gina Häußge a5094d403a Merge branch 'maintenance' of github.com:foosel/OctoPrint into maintenance 2015-11-05 17:58:51 +01:00
Gina Häußge 6b0dee26e5 Interpret M25 as a pause when not printing from SD too 2015-11-05 17:33:27 +01:00
Gina Häußge a44eb43f0f Added @kevingelion to AUTHORS.md 2015-10-30 16:53:17 +01:00
Gina Häußge b6a5cb47a1 Merge branch 'km/hotfix-flot-yaxis-cutoff' of https://github.com/kevingelion/OctoPrint into pr/kevingelion/km/hotfix-flot-yaxis-cutoff 2015-10-30 16:49:35 +01:00
Kevin Murphy 65efcec008 Change instance of row to row-fluid to avoid conflict with responsive CSS 2015-10-30 11:18:44 -04:00
Andres 37730616c1 Fixed wrong urls
(cherry picked from commit 119f3ba)
2015-10-29 09:41:17 +01:00
Gina Häußge a53195d2a0 Added Unit Tests for BlueprintPlugin mixin
(cherry picked from commit 53a62ab)
2015-10-26 09:15:54 +01:00
Marcel Hellwig 084fd8d433 add errorhandler decorator to blueprintplugin
This will allow you to add an errorhandler for your blueprint easily.
(cherry picked from commit b6053c1)
2015-10-26 09:12:17 +01:00
Gina Häußge 33306b6787 Fixed an earlier merge error 2015-10-26 09:11:44 +01:00
Gina Häußge b4cb0dec87 Unit tests and some fixes for improved plugin settings processing
(cherry picked from commit bcd0f34)
2015-10-26 08:53:08 +01:00
Gina Häußge 063251fe03 Use get_all_data instead of get([], ...) construct
(cherry picked from commit ffcbdba)
2015-10-26 08:52:58 +01:00
Gina Häußge 9b3ef8b693 Fix: Persist all data different from default, not just current changes
We need to merge with our current data since we only might get partial data
from our caller.
(cherry picked from commit 7ea1578)
2015-10-26 08:52:46 +01:00
Gina Häußge a5ce071939 Make sure only difference to default config is persisted for plugins
This change should make sure that only those settings actually make it into config.yaml
per plugin that do differ from the default settings. Up until now the full dictionary as received
e.g. from the REST API was saved, regardless whether it contained (only) default values or not.
That led to a lot of "null" entries in the config.yaml file, which for one looked horrible and also
led to problems when a plugin actually wanted to change its default values.

With this commit, two things are done. One, upon saving a configuration the default
implementation of the save routine in the settings plugin now first diffs the new data against
the defaults and only saves what is different. Two, upon server startup a cleanup method is
now called on settings plugins whose default implementation fetches the current data stored
in config.yaml, diffs that against the defaults and only writes back the diff result. If that is empty
the entry is completely deleted from config.yaml.
(cherry picked from commit d70fe32)
2015-10-26 08:52:05 +01:00
Gina Häußge e8fa2e44e0 Travis: Let's see if we can't get the git depth upped a bit
(cherry picked from commit 5fc8e22)
2015-10-23 13:36:39 +02:00
Gina Häußge e223341ece Travis: Migrate from legacy infrastructure
http://docs.travis-ci.com/user/migrating-from-legacy/
(cherry picked from commit bec0013)
2015-10-23 13:36:33 +02:00
Gina Häußge 5c8d9007f6 Fixed some missing exception capturing
(cherry picked from commit 2f86a6a)
2015-10-23 13:36:27 +02:00
Gina Häußge 91163dc4f4 Fixed existing doctests, added some new ones, enabled doctests in nosetests
(cherry picked from commit 02c3bf8)
2015-10-23 13:36:18 +02:00
Gina Häußge 2a8e084b51 Added a missing comma that broke the build... 2015-10-23 13:27:24 +02:00
Gina Häußge ce00a069fa Added conversion for README.md to rst for PyPi 2015-10-23 12:08:36 +02:00
Gina Häußge bdadab6993 We want pep440-post by default 2015-10-23 10:07:15 +02:00
Gina Häußge 05d6cac67a Define where our README is located so that it gets rendered correctly on pypi 2015-10-23 10:02:05 +02:00
Gina Häußge 528192b3c0 Fixed a merge error while migrating versioneer update 2015-10-23 09:55:14 +02:00
Gina Häußge 729d23b2c0 Fixed versioneer lookup file again
Runaway regex ;)
(cherry picked from commit 78277ac)
2015-10-23 09:54:46 +02:00
Koen Kooi 2e566c5ee1 versioneer lookup: add support for detached checkouts
When doing 'git checkout <rev>' or 'git checkout <tag>' there will be no
branch info:

	$ git branch
	* (detached from 96fc70b)

After whitelisting '\(detached.*' we get:

	$ python setup.py version
	running version
	got version from git {'version': '1.2.5-1-gfd73e02', 'branch': 'HEAD',
	'full': 'fd73e02f4fa9f286407ad688feeeee3ebaffea60'}
	Version is currently: 1.2.5-1-gfd73e02

The '-1-gfd73e02' is this commit on top of the 1.2.5 tag.

While detached checkouts should be discouraged some buildsystems (e.g.
OpenEmbedded) have no real way to avoid it, which is what this patch
fixes. Actual people doing a checkout should use a branch.

Signed-off-by: Koen Kooi <koen@dominion.thruhere.net>
(cherry picked from commit 987e637)
2015-10-23 09:54:21 +02:00
Gina Häußge e875d042a7 Refreshed versioneer again
(cherry picked from commit 7cd0adb)
2015-10-23 09:53:25 +02:00
Gina Häußge f05f850175 Switched to new version of versioneer
Versions should now be PEP440 compatible.
(cherry picked from commit 711810d)
2015-10-23 09:53:13 +02:00
Gina Häußge 9ce9af28c3 Updating versioneer & switch to PEP440 versioning
(cherry picked from commit 137db0b)
2015-10-23 09:51:50 +02:00
Gina Häußge 57bf457d97 Fix: current filename in job data should never be prefixed with /
That was a tiny detail missing in 8bef18c2a8 that
caused issues with detecting which file was currently selected on the printer's
SD card (for "do not delete that" checks on the API).
2015-10-22 13:42:57 +02:00
Gina Häußge adf39cdf21 maintenance branch is now 1.2.8-dev 2015-10-20 14:54:16 +02:00
Gina Häußge 6c622f7c43 Fixed indentation of change log 2015-10-20 12:24:23 +02:00
Gina Häußge d34790e74e Unit tests for octoprint.util.RepeatedTimer
(cherry picked from commit 7362067)
2015-10-20 12:07:31 +02:00
Gina Häußge aa5099340e Two new callbacks for RepeatedTimer when cancelled or condition untrue
(cherry picked from commit 9b9ecfe)
2015-10-20 12:07:24 +02:00
Gina Häußge 693633bd1d RepeatedTimer now supports callback when timer stops
(cherry picked from commit 3c5a976)
2015-10-20 12:05:12 +02:00
Gina Häußge 758062133c Updated changelog for 1.2.7 2015-10-20 11:55:34 +02:00
Gina Häußge c55fea666d Updated required versions of psutil and netifaces
Also see #1090
2015-10-19 09:33:48 +02:00
Gina Häußge c932e496fa SWU: Show reload dialog after update
The notification and the (forced) dialog afterwards were way too
redundant.
2015-10-08 17:08:36 +02:00
Gina Häußge bbbdb3dde6 Note that z-based timelapses don't work when printing from SD 2015-10-08 10:22:09 +02:00
Gina Häußge b9460b4890 Merge branch 'fix/uiEscaping' into maintenance 2015-10-08 09:52:08 +02:00
Gina Häußge 947f4c89cc Fixed a win-only issue causing the gcode view not to reload on file modification 2015-10-07 18:52:18 +02:00
Gina Häußge 5f982ec6c8 Merge branch 'fix/atomicWrites' into maintenance 2015-10-07 17:53:43 +02:00
Gina Häußge dcf2e51b21 Moved filemanager method tests to test_filemanager.py 2015-10-07 17:50:08 +02:00
Gina Häußge 85e6ae8e82 Fixed a unit test that broke by switching to atomic_write 2015-10-07 17:45:07 +02:00
Gina Häußge 859ea0d0e4 Added mime type guessing for downloads to Tornado 2015-10-07 17:19:18 +02:00
Gina Häußge 9cf21aa036 Also set caching headers for downloads to discourage client-side caching
At least if necessary (added new boolean flag to the constructor of
LargeResponseHandler for that). While at it also rename UrlForwardHandler
to UrlProxyHandler (it does not forward, it proxies) and make it aware of
ETag and Expires headers.
2015-10-07 12:25:25 +02:00
Gina Häußge 637adc3095 Fix: LargeResponseHandler was wrongly caching ETag value
ETag values returned with download responses were cached internally within
the LargeResponseHandler class, with the file's path as key. That let to
problems once the content changed and hence the ETag value actually
becoming invalid. Since the path however stayed the same, the same ETag
value for the modified file was assumed and a 304 Not Modified response
was generated.

This patch changes the behaviour of LargeResponseHandler to use
the last modified date of the file as the ETag value and alternatively allowing
an etag generator function to be provided as constructor parameter as well
to use for calculating (or disabling) the ETag header dependant on the
situation.
2015-10-06 18:19:53 +02:00
Gina Häußge 548f976d35 Some more defensive escaping for various settings in the UI
Entering HTML fragments into the webcam stream URL could cause
issues, anything injected via Jinja should now be escaped properly.
2015-10-06 13:41:54 +02:00
Gina Häußge 45c92cb1f4 Fix: Open GCODE files als utf-8, replacing encoding errors
Also detect files that contain a BOM and strip it.
Internal handling of GCODE file contents switched to unicode.

 Should take care of #1077
2015-10-05 19:43:40 +02:00
Gina Häußge f83d5aa89f Fix: Use atomic writes for all save processes
That includes uploaded files, profiles, caching files, settings and user
directories.
2015-10-05 18:07:43 +02:00
Gina Häußge abf073340f Fixed reporting of duration needed for capturing timelapse postroll
Needs to be calculated differently for time based and z-triggered. Capture interval
was not taken properly into account.
(cherry picked from commit 9284ff4)
2015-10-02 18:22:44 +02:00
Gina Häußge 918ffa2557 Refactored timelapse core
Capturing is now queue based, rendering will not start until all images have been captured,
and timed postroll does not depend on system time anymore.

Also refactored some of the names to be python naming compliant while at it.
(cherry picked from commit 4f5dc70)
2015-10-02 18:18:31 +02:00
Gina Häußge 5cc8ec5cc3 Better wording for plugin system startup & sorted plugin list of ALL plugins 2015-09-30 16:00:32 +02:00
Gina Häußge fce7b40b51 pip: Use string representation of version for display in UI 2015-09-28 20:20:56 +02:00
Gina Häußge 1178fe9e95 Support sudo for installing plugins, but warn about it 2015-09-28 19:53:30 +02:00
Gina Häußge 2f24e73fcb Merge branch 'fix/logsDocsBug' into maintenance 2015-09-28 13:08:57 +02:00
Gina Häußge 9ff5c36370 Fixed a documentation bug 2015-09-28 13:08:35 +02:00
Gina Häußge 1b4ea75466 Fix: Don't have file upload widgets listen to drop events by default
That way they won't be triggered by gcode uploads when all they are interested in
are uploads via a single file input.
2015-09-28 12:55:32 +02:00
Gina Häußge b4b5689bc4 Fix: Correctly handle unset Content-Type header for command requests 2015-09-22 15:23:50 +02:00
Gina Häußge fd4271a962 PipCaller: Added back missing member variable 2015-09-22 11:39:45 +02:00
Gina Häußge 65bc28a03e PMGR: Added configuration dialog and info re used pip binary & version 2015-09-22 11:36:57 +02:00
Gina Häußge c26515c13d PipCaller: Allow update of used pip command 2015-09-22 11:35:47 +02:00
Gina Häußge 25a4d4b79b SWU: Track check origins, ignore if from unavailable plugin
There was a problem with software update checks configurations stored in
config.yaml for which the providing plugin was then removed, since those
check definitions then lacked their default values to be merged on whatever
was stored in config.yaml, causing incomplete check configurations as a
consequence over which the plugin tripped.

This patch fixes that in that it tracks which check config keys are provided
by plugins and only returns those as the active check configurations that
belong to plugins that are still in the system.

TODO: This is only half of the solution. Check configurations of plugins
that are being uninstalled should be removed from the config if the
user decides to remove any settings by the plugin too. We need some
adjustments in the lifecycle tracking in order to make this possible
however, so for now this must suffice to at least prevent any errors from
occuring when incomplete configs are encountered.
(cherry picked from commit 8af8b8f)
2015-09-21 16:46:44 +02:00
Gina Häußge 43ca4d8252 SWU: Do not overwrite check information again
Current version information of OctoPrint from a check definition
could be overwritten for checks under certain circumstances.
2015-09-21 16:42:11 +02:00
Gina Häußge b56ba6589c Ignore update definitions that are lacking the type
Caused a KeyError so far, update definitions that are broken like that
will now just be ignored instead.

Closes #1057
(cherry picked from commit 2efc5c4)
2015-09-11 08:36:02 +02:00
Gina Häußge 5c9b507cb7 User user id, not user name, for all user operations
(cherry picked from commit 7021b9f)
2015-09-11 08:35:08 +02:00
Gina Häußge cd7ac032f4 Fixed an issue that cause user sessions to not be properly associated
Sessions could get duplicated, wrongly saved etc. The reason was not
persisting the actual user object to the internal session map (but the
LocalProxy instead). That could lead to multiple sessions being
created for one login, or the session user being set to an
anonymous user, or various other odd effects depending on timing.
(cherry picked from commit 8aeac51)
2015-09-11 08:20:16 +02:00
Gina Häußge a2e5fc0c5c maintenance branch is now 1.2.7-dev 2015-09-02 20:18:18 +02:00
Gina Häußge 536bb31965 Forgot the commit link in the changelog 2015-09-02 19:59:49 +02:00
Gina Häußge ef46a49430 Also included #1041 in 1.2.6 2015-09-02 19:55:24 +02:00
Gina Häußge 8e28ddd6a4 Fixed versioneer lookup file again
Runaway regex ;)
(cherry picked from commit 78277ac)
2015-09-02 19:53:18 +02:00
Koen Kooi ab8b0230bd versioneer lookup: add support for detached checkouts
When doing 'git checkout <rev>' or 'git checkout <tag>' there will be no
branch info:

	$ git branch
	* (detached from 96fc70b)

After whitelisting '\(detached.*' we get:

	$ python setup.py version
	running version
	got version from git {'version': '1.2.5-1-gfd73e02', 'branch': 'HEAD',
	'full': 'fd73e02f4fa9f286407ad688feeeee3ebaffea60'}
	Version is currently: 1.2.5-1-gfd73e02

The '-1-gfd73e02' is this commit on top of the 1.2.5 tag.

While detached checkouts should be discouraged some buildsystems (e.g.
OpenEmbedded) have no real way to avoid it, which is what this patch
fixes. Actual people doing a checkout should use a branch.

Signed-off-by: Koen Kooi <koen@dominion.thruhere.net>
(cherry picked from commit 987e637)
2015-09-02 19:51:11 +02:00
Gina Häußge 754ef428a0 Preparing release of 1.2.6 2015-09-02 19:49:49 +02:00
Gina Häußge 455474841e Pinned psutil version to 3.1.1 (and all other dependencies)
Something in the recently released psutil 3.2.0 version causes installations via
python setup.py install to fail that list psutil as requirement.

Pinning to 3.1.1 solves that problem for now.
2015-09-02 19:38:18 +02:00
Gina Häußge ae4e4f22c4 maintenance branch is now 1.2.6-dev 2015-08-31 15:57:11 +02:00
Gina Häußge 96fc70bdb2 Preparing release of 1.2.5 2015-08-31 10:28:52 +02:00
Gina Häußge 8ed0befd62 Fixed bug that made browser crash when trying to log in
Trying to serialize view models or browser events as username/password probably was not the best of ideas ;)
(cherry picked from commit c7fd480)
2015-08-31 09:44:52 +02:00
Gina Häußge 766c0c21d4 Adjusted README
(cherry picked from commit 92c02df)
2015-08-31 09:26:28 +02:00
Salandora 7d50563666 Custom Control fix in less file
(cherry picked from commit 10ad8dd)
2015-08-31 09:26:20 +02:00
Salandora 4011f60ff9 Edge Fix
Thanks @foosel for the Informations

Conflicts:
	src/octoprint/server/views.py
2015-08-28 09:36:47 +02:00
Gina Häußge 37950cb466 Fixing some more merge errors 2015-08-28 08:58:12 +02:00
Gina Häußge 2824b967ff Fixed a merge error 2015-08-28 08:20:20 +02:00
Gina Häußge 7b8bf2cf5c M112 support or the virtual printer
(cherry picked from commit 22a6604)
2015-08-28 08:19:03 +02:00
Gina Häußge 9299cb54a4 Improved M112 handling
Use new synchronized sending method and also make sure that heaters
will get disabled in case M112 is NOT understood by the firmware
before disconnecting. That's about all we can do for now.
(cherry picked from commit 5406b2b)
2015-08-28 08:12:12 +02:00
Gina Häußge b965d4cbde comm: Synchronized write access to line number
New method wraps line sending and incrementing
(cherry picked from commit f8e72c9)
2015-08-28 08:11:56 +02:00
Mark Walker 7d922f3c77 Clean up the comment
(cherry picked from commit f519070)
2015-08-28 08:09:16 +02:00
Mark Walker 7e894d2ac2 ClearableQueue redundant with self.close
Closing the printer connection and then reopening (when the users clicks
connect) will create a new fresh MachineCom object so the queues will
start out empty.  Plus ClearableQueue was even more tied to the Queue
implementation that the current _get/_put overrides.
(cherry picked from commit e7584cd)
2015-08-28 08:09:02 +02:00
Mark Walker 948e20b269 Send M112 to printer immediately
Address #1031 with an immediate send of M112 followed by closing the
serial connection to reset the host state
(cherry picked from commit 3d1d745)
2015-08-28 08:08:26 +02:00
Gina Häußge 0e863ad776 Made diskspace running low a bit more obvious
* Added "total" space to "free" in file list
  * Added configurable space thresholds. If free space is below "warning"
    threshold, exclamation sign will be added to report. If free space is below
    "critical" threshold, report will be styled bold and red.
(cherry picked from commit 097800a)
2015-08-27 17:14:10 +02:00
Gina Häußge 13d7d5f2f6 SWU: Various improvements for better usability
* Allow configuration of checkout folder and version tracking type
    via Plugin Configuration
  * Display message to use if checkout folder is not configured or a
    non-release version is running and version tracking against releases
    is enabled
  * Clear version cache when a change in the check configuration is
    detected
  * Mark check configurations for which an update is not possible with
    a little exclamation mark
(cherry picked from commit 8666a28)
2015-08-26 16:03:11 +02:00
Gina Häußge ac8faf7910 Also provide branch info to UI/on socket
(cherry picked from commit cc8dcef)
2015-08-26 16:02:29 +02:00
Gina Häußge bf049ddee4 Fixed two swapped vars
(cherry picked from commit 14c1069)
2015-08-26 15:56:50 +02:00
Gina Häußge e435d55cb1 Added documentation for server commands
(cherry picked from commit 21350fa)
2015-08-26 15:56:35 +02:00
Gina Häußge 2c50237699 Reordered and tooltipped new server commands
(cherry picked from commit e2e6318)
2015-08-26 15:56:24 +02:00
Gina Häußge 93763a5563 Remove left over observables that are no longer needed
(cherry picked from commit 7986a2f)
2015-08-26 15:56:09 +02:00
Gina Häußge 7a74f5348d Only migrate server commands when not already set
Also migrate for any config version < 4 (incl. None) and make sure
the other migrations may happen on top of that if necessary. Added
some comments to explain necessary migrations.
(cherry picked from commit f1075f6)
2015-08-26 15:55:32 +02:00
Gina Häußge b25c2220d1 Allow deletion of a key from settings that is no longer in defaults
(cherry picked from commit b04da70)
2015-08-26 15:55:14 +02:00
Nicanor Romero Venier 57161dd9c3 Added migration step for new settings.
(cherry picked from commit 1cdd61f)
2015-08-26 15:54:17 +02:00
Nicanor Romero Venier 1343a4a253 Added settings to specify server commands.
Added commands for system shutdown and restart and
for server restart.
(cherry picked from commit dab3285)
2015-08-26 15:53:30 +02:00
Gina Häußge 6de7eabca2 Fixed another merge error 2015-08-24 15:59:49 +02:00
Gina Häußge 2247f30c87 Fixed indentation after a merge error 2015-08-24 15:30:26 +02:00
Gina Häußge ba6a6723a6 Settings dialog for new resend setting
(cherry picked from commit 4525a3a)
2015-08-24 14:59:51 +02:00
Gina Häußge f9a0cb94f7 Moved new resend setting into feature section
That's where all other protocol specific settings are currently located.
Will be migrated at a later date into the printer profile instead (that
makes way more sense).
(cherry picked from commit d0f61e5)
2015-08-24 14:59:44 +02:00
Gina Häußge e689a2c733 Handle Repetier resend repetitions
Repetier might resend the same resend request to make sure it arrives.
This commit makes OctoPrint not react to such a repeated request and
instead ignore up to a configurable amount of repeated requests for
the same (current) line.
(cherry picked from commit 6f83695)
2015-08-24 14:59:11 +02:00
Gina Häußge d07c81f312 Fixed regex groups for GCODE parameters
(cherry picked from commit 168d32e)
2015-08-24 14:56:40 +02:00
Gina Häußge 32f4f8d95b Added warning to UI regarding Z timelapses and spiralized objects
(cherry picked from commit d956773)
2015-08-24 14:56:18 +02:00
Gina Häußge 7f2e0161a8 atomic_write context to save configs first to temp file, then move
Should prevent corruption of files
(cherry picked from commit c6d0290)
2015-08-24 14:56:12 +02:00
Gina Häußge 59993bfca4 Fixed & refactored temperature parsing
T-only lines were not properly parsed. Should now be fixed to
be associated to currently selected extruder. Also added unit
tests for the temperature parsing.

While at it also extracted regexes and added unit tests for command
parsing (gcode & parameters)
(cherry picked from commit f6a259f)
2015-08-24 14:55:42 +02:00
Salandora 0782dda20f Add Repetier's Format Error to exception whitelist
(cherry picked from commit d037379)
2015-08-24 14:54:28 +02:00
Gina Häußge 8c1a79558b Always include timelapse view model in bundled js files
Even if the webcam URLs and the FFMPEG path is not yet configured. Otherwise
setting those URLs and the path will require a restart of OctoPrint to enable properly -
that's overkill.
(cherry picked from commit 1425b20)
2015-08-24 14:52:50 +02:00
Mark Walker 0705a7054c Hint about why timelapse configuration is disabled
while printing.

Fixes #1028
(cherry picked from commit 8496827)
2015-08-24 14:51:55 +02:00
Gina Häußge 54bd7766b9 SWU: Don't use display versions for "current" in github_commit configs
(cherry picked from commit 58c6abc)
2015-08-24 14:51:25 +02:00
Gina Häußge ed215fc5fa FileMgr: Only remove callback if it exists.
(cherry picked from commit 4a49948)
2015-08-24 14:45:14 +02:00
Gina Häußge 5f53b704dd Use connection closing flag only for exception handling
Otherwise we kill the beforePrinterDisconnected gcode script...

See #1021
(cherry picked from commit 2fe956e)
2015-08-24 14:44:56 +02:00
Gina Häußge e8ef0ba8a4 Properly handle serial close on Macs
Readline could still be stuck in a read loop, leading to an exception on Mac
when closing the connection from another thread. This should now be captured
correctly.

Fixes #1021
(cherry picked from commit c829b27)
2015-08-24 14:44:31 +02:00
Salandora 49f62bc655 Fix positioning of ContextMenu
(cherry picked from commit 2bf5624)
2015-08-24 14:40:52 +02:00
Salandora 0ff43def3a Fix sorting of templates
(cherry picked from commit 3866c1a)
2015-08-14 09:01:02 +02:00
Gina Häußge cc14b77487 Use connection closing flag only for exception handling
Otherwise we kill the beforePrinterDisconnected gcode script...

See #1021
(cherry picked from commit 2fe956e)
2015-08-14 09:00:40 +02:00
Gina Häußge 7f10c317f1 Properly handle serial close on Macs
Readline could still be stuck in a read loop, leading to an exception on Mac
when closing the connection from another thread. This should now be captured
correctly.

Fixes #1021
(cherry picked from commit c829b27)
2015-08-14 09:00:19 +02:00
Gina Häußge ba1f8c58b4 Log exception on error while reading from serial
(cherry picked from commit ac3409a)
2015-08-14 08:55:29 +02:00
Gina Häußge 273bb45741 Fixed broken GCODE viewer / concurrent settings requests
The GCODE viewer settings callback was not properly called, hence the
viewer was not initialized properly.

Changed prevention of concurrent settings requests to properly handle
the situation where the registered settings callbacks might be extended
through another callback.
(cherry picked from commit 7d6462b)
2015-08-12 12:31:23 +02:00
Gina Häußge e33f69917f Made webassets folder cleanup win32-proof
If re-creation of the folder fails due to an access error, perform three retries. It might
be caused by the folder being open in the file explorer. Waiting a bit before retrying
seems to do the trick.

See also #1019
(cherry picked from commit a43de42)
2015-08-11 18:14:39 +02:00
Gina Häußge 4b8bdd244e Improved settings dialog behaviour
* Show when settings are saving
  * Show when settings are being retrieved
  * Disable Send/Cancel buttons while settings are saving
  * Prevent concurrent retrieval
(cherry picked from commit 88eb124)
2015-08-11 15:30:38 +02:00
Gina Häußge 202f93426a Capture compilation errors on additional templates
Shouldn't cause the whole page not to render but log an error. Should
provide more resilience against bad plugins.
(cherry picked from commit d25202d)
2015-08-11 15:30:19 +02:00
Gina Häußge c538604cd5 Added tooltip for additional data in file list
Also fixed tooltips to those buttons instead of the icons within the buttons.

Fixes #986
(cherry picked from commit 8772162)
2015-08-11 14:08:10 +02:00
Gina Häußge 0c44762f6f Fix: Better error handling for webassets + cache
(cherry picked from commit 38be47c)
2015-08-11 14:08:04 +02:00
Gina Häußge 6df57bc1d1 Evaluate return code of pip while updating
Should not report a successful update anymore when the pip call failes for whatever reason.
(cherry picked from commit 54b981b)
2015-08-11 14:07:38 +02:00
Gina Häußge e328695100 Do not hiccup on unset Content-Type fields in multipart file uploads
Just don't set the content_type parameter in that case.

Fixes #985
(cherry picked from commit 4bb5be7)
2015-08-11 14:07:31 +02:00
Mark Walker 738c699a6e Fix for #1001 connection tab not unfolding
Defer collapsing the connection element until the whole wrapper part is
visible (it's hidden for non-admins).
(cherry picked from commit af67d8b)
2015-08-11 14:07:11 +02:00
Gina Häußge 8a28220e63 responsive => snappy
Finally found a replacement for the word "responsive", which these
days is almost inclusively understood as "viewport adjusting"
instead of its original meaning "reacting quickly".

Thanks to the javascript world, even "reactive" isn't an option
anymore, this term has now been hijacked as well.
(cherry picked from commit 2e27b94)
2015-08-11 14:06:43 +02:00
Gina Häußge 5808c1bd8a Added @masterhou to AUTHORS.md
(cherry picked from commit 7c90fe5)
2015-07-29 09:19:51 +02:00
Thomas Hou 8bbb642a56 fixed bug: when new job start, job progress is last 100%.
(cherry picked from commit 200ad3b)
2015-07-29 09:19:44 +02:00
Gina Häußge 1f0dbf8f7f maintenance branch is now 1.2.5-dev 2015-07-23 12:19:27 +02:00
Gina Häußge 9a6099ffc2 PMGR: Dependency links can make pip install take longer
Depending on the pip version pip might first fetch the full index of packages available
on PyPI instead of just directly processing the provided link.

Display corresponding message to user from backend to make sure they don't
think something broke.
2015-07-23 10:54:39 +02:00
Gina Häußge 25de95dc93 Preparing release of 1.2.4 2015-07-23 09:54:27 +02:00
Gina Häußge 57f6e1e1bc Some more hints where to find documentation and support 2015-07-23 08:48:11 +02:00
Gina Häußge edf9c40941 Re-added dependency_links option for create_plugin_setup_parameters
(cherry picked from commit a59642b)
2015-07-22 22:10:31 +02:00
Gina Häußge 4dd4a2cc9c Revert "Remove dependency_links support again"
This reverts commit be423e49fd.

Conflicts:
	src/octoprint/plugins/pluginmanager/__init__.py
	src/octoprint/plugins/softwareupdate/updaters/pip.py
(cherry picked from commit c24ba82)
2015-07-22 19:06:39 +02:00
Gina Häußge 81bc8c784a Don't reopen notification on mouse-over while closing
(cherry picked from commit 9839f4b)
2015-07-21 16:57:39 +02:00
Gina Häußge 294e7fc2db Patch for the js warnings referred to in #966 2015-07-21 11:54:06 +02:00
Marc 6e632d02a0 Fixes usersettings never reached the client's browser
(cherry picked from commit 8e235af)
2015-07-20 10:10:00 +02:00
Gina Häußge 50ff0d810f Fixed a missing self.buffer()
(cherry picked from commit 0fa22937e0)
2015-07-20 10:09:33 +02:00
Mark Walker d4be7f18e2 transpose=2 is counter clockwise, plus filter order should be rotation
last to match the css application order
(cherry picked from commit bdb55e0)
2015-07-20 09:37:56 +02:00
Nicanor Romero Venier 6d24a46e88 Fixed form field truncation in upload requests
(cherry picked from commit 1f6c852)
2015-07-15 10:35:59 +02:00
Gina Häußge db866d2310 Finally added a proper AUTHORS file
Also adjusted contribution guidelines to ask people to include themselves when filing
a PR.
(cherry picked from commit 1b594b2)
2015-07-15 10:35:38 +02:00
Gina Häußge bb7e15be84 Fixed a typo in the docs
logger => loggers in logging.yaml
(cherry picked from commit d0733d8)
2015-07-14 09:26:30 +02:00
Gina Häußge 7a007a6417 Stop RepeatedTimers on server shutdown by default
daemon flag was missing, leading to the timer staying active even when a shutdown
 was triggered. Added new daemon flag to timer constructor, defaulting to true, that
 fixes that behaviour.
(cherry picked from commit 48fe23b)
2015-07-14 09:26:25 +02:00
Gina Häußge 96aad9d34f Better resilience against errors within plugins
(cherry picked from commit 75992ef)
2015-07-14 09:26:20 +02:00
Gina Häußge 4d3334caf1 Updated README 2015-07-10 09:58:20 +02:00
Gina Häußge 2745f49d28 Fixed white panes in settings dialog on Safari 8
Absolute positioning caused panes to sometimes not render when being
selected. Switching to static positioning again makes the dialog look a bit
weird, but that's probably still preferable to no content showing. It seems
to be a browser bug that not's present with Safari 7, more tests to pinpoint
what exactly is causing this are probably necessary, but this at least is a
functional workaround for now.
(cherry picked from commit a18cbf7)
2015-07-09 21:52:59 +02:00
Gina Häußge 5470aaaa3a Set no-cache headers on page while firstRun is True
(cherry picked from commit f1afb70)
2015-07-09 09:45:35 +02:00
Gina Häußge f89cbc9133 Allow to not cache responses that set no-cache headers
(cherry picked from commit 163100b)
2015-07-09 09:45:29 +02:00
Gina Häußge 5dfffc36e3 maintenance branch is now 1.2.4-dev 2015-07-09 09:44:51 +02:00
Gina Häußge 3761995aff Removed unneeded parameter and added missing semicolon
(cherry picked from commit 29b3b62)
2015-07-08 17:42:47 +02:00
Gina Häußge e62cef590b Fixed preventDefault issues also for files search
(cherry picked from commit 4894c6e)
2015-07-08 17:42:41 +02:00
Mark Walker 677e583345 pluginmanager: case handling and submit binding
- Convert query term to lower case so that it is case insensitive both ways
    - Knockout submit binding takes the form element as parameter and return
    value determines whether the form submit occurs. See http://knockoutjs.com/documentation/submit-binding.html
(cherry picked from commit 4a2cc53)
2015-07-08 17:42:35 +02:00
Gina Häußge abbf937e7f Preparing release of 1.2.3 2015-07-08 17:22:18 +02:00
Gina Häußge 8d14ea6093 Rewrite urls in packed css and less files
See also #962
(cherry picked from commit 7ea2ee2)
2015-07-08 16:46:46 +02:00
Gina Häußge 97826b2f3b Fix: More resilience against missing plugin assets
Two changes:

  * Asset existence will now be checked before they get included
    in the assets to bundle by webassets, logging a warning if a
    file isn't present.
  * Monkey-patched webassets filter chain to not die when a file
    doesn't exist, but to log an error instead and just return
    an empty file instead.
(cherry picked from commit 2a5ec33)
2015-07-08 16:46:38 +02:00
Gina Häußge a1e0078ce5 Updated translation
(cherry picked from commit 7d43bca)
2015-07-07 19:00:11 +02:00
Gina Häußge a5bf3c3be1 Log serial write exceptions to octoprint.log
(cherry picked from commit 367ba06)
2015-07-07 18:39:54 +02:00
Gina Häußge 19a5613e59 Made "Software Update" and "CuraEngine" translateable
Also fixed a typo in a notification.
(cherry picked from commit 430e47d)
2015-07-07 18:39:47 +02:00
Gina Häußge ced286854c Fixed sorting by size of file list
(cherry picked from commit 6906584)
2015-07-07 18:39:06 +02:00
Gina Häußge 811ffc760f Added "pollWatched" setting to UI
(cherry picked from commit b8cf5ef)
2015-07-06 10:21:21 +02:00
Gina Häußge 549b60edb1 Allow polling for changes in watched folder
Some underlying file systems might not trigger change events (e.g.
mounted remote file systems). Added a feature flag to allow for
switching to a (less performant) polling method.
(cherry picked from commit f2df174)
2015-07-06 10:20:57 +02:00
Gina Häußge 8735b10653 Better resilience against senseless polling intervals
(cherry picked from commit 6600d24)
2015-07-05 16:50:33 +02:00
Gina Häußge 29d49179a9 SWU Fix: properly sanitize version strings for comparison 2015-07-05 10:04:06 +02:00
Gina Häußge 19b4a0f403 Fix: Always delete files from watched folder
Wasn't ensure previously when using file preprocessors.
2015-07-05 09:35:49 +02:00
Gina Häußge d854b41ffb Migrated access control docs from wiki 2015-07-05 00:09:13 +02:00
Gina Häußge 329a575031 Merge branch 'master' into maintenance 2015-07-04 23:51:58 +02:00
Gina Häußge 85ad85bdfa Also refer to wiki from docs until everything "official" is migrated 2015-07-04 23:51:29 +02:00
Gina Häußge 95c26a7850 Fix: Don't automatically persist or return _config_version
Should only ever be read or written by the plugin system itself, not
by on_settings_save or on_settings_load
(cherry picked from commit 77f7d59)
2015-07-02 15:27:35 +02:00
Gina Häußge 885e6f916c Fix: Don't persists checks when saving SWUpdate settings
(cherry picked from commit 8d10be6)
2015-07-02 15:27:27 +02:00
Gina Häußge d7a86a4d28 Use UTF-8 for _all_ output from sarge
Lines taking from the asynchronous processing of stdout/stderr where
left as str, leading to encoding problems when utf8 characters showed
up in the stream and were being interpreted as ascii encoding.
(cherry picked from commit 9373be3)
2015-07-02 15:27:17 +02:00
Gina Häußge 7b3e0563cc SWUpdate: Only use version cache from same version of OP
When using the version cache only use the version cache if the OctoPrint
version stored within it matches the one of the currently running
instance. Otherwise we might report false positives with regards to
available updates under some circumstances.
(cherry picked from commit bb7b0cb)
2015-07-02 15:26:02 +02:00
Gina Häußge 50a62bf00a maintenance branch is now 1.2.3-dev 2015-06-30 21:49:37 +02:00
Gina Häußge 1c6b0554c7 Preparing release of 1.2.2 2015-06-30 21:19:50 +02:00
Gina Häußge 537c205757 Use lowercase when matching extensions
(cherry picked from commit 29cee16)
2015-06-30 19:12:58 +02:00
Gina Häußge f07b2477f5 Fixed some comments that were outdated
(cherry picked from commit 18816b6)
2015-06-30 19:12:52 +02:00
Gina Häußge 5e5531f6d8 Verify extension of uploaded language packs & plugins
Should be valid zip archives/tarballs. Also use only the extension
of an uploaded plugin archive as suffix for the temporary file that's
used for installing it.
(cherry picked from commit a1ff698)
2015-06-30 19:12:45 +02:00
Gina Häußge eadc9ee795 Fix: We don't need the shell for pip
(cherry picked from commit 2db3228)
2015-06-30 19:12:37 +02:00
Gina Häußge 0b3f94b6bd maintenance branch is now 1.2.2-dev 2015-06-30 10:12:14 +02:00
114 changed files with 9881 additions and 4187 deletions

No files matched your search

+4 -1
View File
@@ -6,4 +6,7 @@ python:
install:
- pip install -e .[develop]
script:
- nosetests tests/
- nosetests --with-doctest
sudo: false
git:
depth: 250
+8 -4
View File
@@ -10,10 +10,14 @@
# master shall not use the lookup table, only tags
master
# maintenance is currently the branch for preparation of maintenance release 1.2.1
# neither should disconnected checkouts, e.g. 'git checkout <tag>'
HEAD
\(detached.*
# maintenance is currently the branch for preparation of maintenance release 1.2.8
# so are any fix/... branches
maintenance 1.2.1-dev cfa4cb2a7c5f1af10dc8
fix/.* 1.2.1-dev cfa4cb2a7c5f1af10dc8
maintenance 1.2.8 6c622f7c4332b71c6ece59552ffc87c146155c84 pep440-dev
fix/.* 1.2.8 6c622f7c4332b71c6ece59552ffc87c146155c84 pep440-dev
# every other branch is a development branch and thus gets resolved to 1.3.0-dev for now
.* 1.3.0-dev 198d3450d94be1a2
.* 1.3.0 198d3450d94be1a2 pep440-dev
+62
View File
@@ -0,0 +1,62 @@
# Authors
The following people have contributed to OctoPrint's code base (ordered by
date of first contribution):
* [Gina Häußge](https://github.com/foosel)
* [Thomas Sanladerer](https://github.com/imitation)
* [Alex Ustyantsev](https://github.com/hudbrog)
* [Andrew Dalgleish](https://github.com/ajd4096)
* [Dale Price](https://github.com/daprice)
* [Václav "ax" Hůla](https://github.com/AxTheB)
* [Tom Perry](https://github.com/daftscience)
* [Andreas Gohr](https://github.com/splitbrain)
* [Lars Norpchen](https://github.com/norpchen)
* [Marlon Wünnemann](https://github.com/marwue)
* ["algspd"](https://github.com/algspd)
* [Peter Uithoven](https://github.com/peteruithoven)
* [Bryan Mayland](https://github.com/CapnBry)
* [Ross Hendrickson](https://github.com/savorywatt)
* [Dan Lipsitt](https://github.com/DanLipsitt)
* [James Gao](https://github.com/jamesgao)
* [Tonnerre Lombard](https://github.com/tonnerre)
* [Marc Hannappel](https://github.com/Salandora)
* [Brad Pitcher](https://github.com/brad)
* [Gabe Rosenhouse](https://github.com/rosenhouse)
* [chriskoz](https://github.com/chriskoz)
* [Ilya Novoselov](https://github.com/nullie)
* [Corey C](https://github.com/C-o-r-E)
* [Jarek Szczepanski](https://github.com/imrahil)
* [Jon Nordby](https://github.com/jonnor)
* [Aaron Bieber](https://github.com/qbit)
* [Guy Sheffer](https://github.com/guysoft)
* [Dattas Moonchaser](https://github.com/dattas)
* [Pim Rutgers](https://github.com/Booli)
* [Koen Kooi](https://github.com/koenkooi)
* [Colin Wallace](https://github.com/Wallacoloo)
* [Michael Ang](https://github.com/mangtronix)
* [Philipp Engel](https://github.com/nosyjoe)
* [Giles Hall](https://github.com/vishnubob)
* [Bevaz](https://github.com/Bevaz)
* [Bortek](https://github.com/bortek)
* [Rob Speed](https://github.com/rspeed)
* [Renha](https://github.com/Renha)
* [Antoine Bertin](https://github.com/Diaoul)
* [Teja Philipp](https://github.com/hungerpirat)
* ["matobago"](https://github.com/matobago)
* ["nophead"](https://github.com/nophead)
* [Bob Clough](https://github.com/thinkl33t)
* [Mikk Kiilaspää](https://github.com/Mikk36)
* [Jack Minardi](https://github.com/jminardi)
* [Mark Walker](https://github.com/markwal)
* [Lucas Clemente](https://github.com/lucas-clemente)
* [Andrew Erickson](https://github.com/aerickson)
* [Nicanor Romero Venier](https://github.com/nicanor-romero)
* [Thomas Hou](https://github.com/masterhou)
* [Mark Bastiaans](https://github.com/markbastiaans)
* [Kevin Murphy](https://github.com/kevingelion)
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
[Daid Braam](https://github.com/daid). Parts of its communication layer and
the server side GCODE interpreter are still based on Cura's code base from
December 2012 and hence on the work of its authors up until then.
+341
View File
@@ -1,5 +1,346 @@
# OctoPrint Changelog
## 1.2.8 (2015-12-07)
### Notes for Upgraders
#### A bug in 1.2.7 prevents directly updating to 1.2.8, here's what to do
A bug in OctoPrint 1.2.7 (fixed in 1.2.8) prevents updating OctoPrint to version
1.2.8. If you try to perform the update, you will simply be told that "the update
was successful", but the update won't actually have taken place. To solve this
hen-egg-problem, a plugin has been made available that fixes said bug (through
monkey patching).
The plugin is called "Updatefix 1.2.7" and can be found
[in the plugin repository](http://plugins.octoprint.org/plugins/updatefix127/)
and [on Github](https://github.com/OctoPrint/OctoPrint-Updatefix-1.2.7/).
Before attempting to update your installation from version 1.2.7 to version 1.2.8,
please install the plugin via your plugin manager and restart your server. Note that
you will only see it in the Plugin Manager if you need it, since it's only compatible with
OctoPrint version 1.2.7. After you installed the plugin and restarted your server
you can update as usual. The plugin will self-uninstall once it detects that it's
running under OctoPrint 1.2.8. After the self-uninstall another restart of your server
will be triggered (if you have setup your server's restart command, defaults to
`sudo service octoprint restart` on OctoPi) in order to really get rid of any
left-overs, so don't be alarmed when that happens, it is intentional.
**If you cannot or don't want to use the plugin**, alternatively you can switch
OctoPrint to "Commit" based tracking via the settings of the Software Update plugin,
update, then switch back to "Release" based tracking (see [this screenshot](https://i.imgur.com/wvkgiGJ.png)).
#### Bed temperatures are now only displayed if printer profile has a heated bed configured
This release fixes a [bug](https://github.com/foosel/OctoPrint/issues/1125)
that caused bed temperature display and controls to be available even if the
selected printer profile didn't have a heated bed configured.
If your printer does have a heated bed but you are not seeing its temperature
in the "Temperature" tab after updating to 1.2.8, please make sure to check
the "Heated Bed" option in your printer profile (under Settings > Printer Profiles)
as shown [in this short GIF](http://i.imgur.com/wp1j9bs.gif).
### Improvements
* Version numbering now follows [PEP440](https://www.python.org/dev/peps/pep-0440/).
* Prepared some things for publishing OctoPrint on [PyPi](https://pypi.python.org/pypi)
in the future.
* [BlueprintPlugin mixin](http://docs.octoprint.org/en/master/plugins/mixins.html#blueprintplugin)
now has an `errorhandler` decorator that serves the same purpose as
[Flask's](http://flask.pocoo.org/docs/0.10/patterns/errorpages/#error-handlers)
([#1059](https://github.com/foosel/OctoPrint/pull/1059))
* Interpret `M25` in a GCODE file that is being streamed from OctoPrint as
indication to pause, like `M0` and `M1`.
* Cache rendered page and translation files indefinitely. That should
significantly improve performance on reloads of the web interface.
* Added the string "unknown command" to the list of ignored printer errors.
This should help with general firmware compatibility in case a firmware
lacks features.
* Added the strings "cannot open" and "cannot enter" to the list of ignored
printer errors. Those are errors that Marlin may report if there is an issue
with the printer's SD card.
* The "CuraEngine" plugin now makes it more obvious that it only targets
CuraEngine versions up to and including 15.04 and also links to the plugin's
homepage with more information right within the settings dialog.
* Browser tab visibility is now tracked by the web interface, disabling the
webcam and the GCODE viewer if the tab containing OctoPrint is not active.
That should reduce the amount of resource utilized by the web interface on
the client when it is not actively monitored. Might also help to mitigate
[#1065](https://github.com/foosel/OctoPrint/issues/1065), the final verdict
on that one is still out though.
* The printer log in the terminal tab will now be cut off after 3000 lines
even if autoscroll is disabled. If the limit is reached, no more log lines
will be added to the client's buffer. That ensures that the log will not
scroll and the current log excerpt will stay put while also not causing
the browser to run into memory errors due to trying to buffer an endless
amount of log lines.
* Increased timeout of "waiting for restart" after an update from 20 to 60sec
(20sec turned out to be too little for OctoPi for whatever reason).
* Added a couple of unit tests
### Bug Fixes
* [#1120](https://github.com/foosel/OctoPrint/issues/1120) - Made the watchdog
that monitors and handles the `watched` folder more resilient towards errors.
* [#1125](https://github.com/foosel/OctoPrint/issues/1125) - Fixed OctoPrint
displaying bed temperature and controls and allowing the sending of GCODE
commands targeting the bed (`M140`, `M190`) if the printer profile doesn't
have a heated bed configured.
* Fixed an issue that stopped the software updater working for OctoPrint. The
updater reports success updating, but no update has actually taken place. A
fix can be applied for this issue to OctoPrint version 1.2.7 via
[the Updatefix 1.2.7 plugin](https://github.com/OctoPrint/OctoPrint-Updatefix-1.2.7).
For more information please refer to the [Important information for people updating from version 1.2.7](#important-information-for-people-updating-from-version-127)
above.
* Fix: Current filename in job data should never be prefixed with `/`
* Only persist plugin settings that differ from the defaults. This way the
`config.yaml` won't be filled with lots of redundant data. It's the
responsibility of the plugin authors to responsibly handle changes in default
settings of their plugins and add data migration where necessary.
* Fixed a documentation bug ([#1067](https://github.com/foosel/OctoPrint/pull/1067))
* Fixed a conflict with bootstrap-responsive, e.g. when using the
[ScreenSquish Plugin](http://plugins.octoprint.org/plugins/screensquish/)
([#1103](https://github.com/foosel/OctoPrint/pull/1067))
* Fixed OctoPrint still sending SD card related commands to the printer even
if SD card support is disabled (e.g. `M21`).
* Hidden files are no longer visible to the template engine, neither as (GCODE)
scripts nor as interface templates.
* The hostname and URL prefix via which the OctoPrint web interface is accessed
is now part of the cache key. Without that being the case the cache could
be created referring to something like `/octoprint/prefix/api/` for its API
endpoint (if accessed via `http://somehost:someport/octoprint/prefix/` first
time), which would then cause the interface to not work if accessed later
via another route (e.g. `http://someotherhost/`).
* Fixed a JavaScript error on finishing streaming of a file to SD.
* Fixed version reporting on detached HEADs (when the branch detection
reported "HEAD" instead of "(detached"
* Fixed some path checks for systems with symlinked paths
([#1051](https://github.com/foosel/OctoPrint/pull/1051))
* Fixed a bug causing the "Server Offline" overlay to pop _under_ the
"Please reload" overlay, which could lead to "Connection refused" browser
messages when clicking "Reload now" in the wrong moment.
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.7...1.2.8))
## 1.2.7 (2015-10-20)
### Improvements
* [#1062](https://github.com/foosel/OctoPrint/issues/1062) - Plugin Manager
now has a configuration dialog that among other things allows defining the
used `pip` command if auto detection proves to be insufficient here.
* Allow defining additional `pip` parameters in Plugin Manager. That might
make `sudo`-less installation of plugins possible in situations where it's
tricky otherwise.
* Improved timelapse processing (backported from `devel` branch):
* Individually captured frames cannot "overtake" each other anymore through
usage of a capture queue.
* Notifications will now be shown when the capturing of the timelapse's
post roll happens, including an approximation of how long that will take.
* Usage of `requests` instead of `urllib` for fetching the snapshot,
appears to also have [positive effects on webcam compatibility](https://github.com/foosel/OctoPrint/issues/1078).
* Some more defensive escaping for various settings in the UI (e.g. webcam URL)
* Switch to more error resilient saving of configuration files and other files
modified during runtime (save to temporary file & move). Should reduce risk
of file corruption.
* Downloading GCODE and STL files should now set more fitting `Content-Type`
headers (`text/plain` and `application/sla`) for better client side support
for "Open with" like usage scenarios.
* Selecting z-triggered timelapse mode will now inform about that not working
when printing from SD card.
* Software Update Plugin: Removed "The web interface will now be reloaded"
notification after successful update since that became obsolete with
introduction of the "Reload Now" overlay.
* Updated required version of `psutil` and `netifaces` dependencies.
### Bug Fixes
* [#1057](https://github.com/foosel/OctoPrint/issues/1057) - Better error
resilience of the Software Update plugin against broken/incomplete update
configurations.
* [#1075](https://github.com/foosel/OctoPrint/issues/1075) - Fixed support
of `sudo` for installing plugins, but added big visible warning about it
as it's **not** recommended.
* [#1077](https://github.com/foosel/OctoPrint/issues/1077) - Do not hiccup
on [UTF-8 BOMs](https://en.wikipedia.org/wiki/Byte_order_mark) (or other
BOMs for that matter) at the beginning of GCODE files.
* Fixed an issue that caused user sessions to not be properly associated,
leading to Sessions getting duplicated, wrongly saved etc.
* Fixed internal server error (HTTP 500) response on REST API calls with
unset `Content-Type` header.
* Fixed an issue leading to drag-and-drop file uploads to trigger frontend
processing in various other file upload widgets.
* Fixed a documentation error.
* Fixed caching behaviour on GCODE/STL downloads, was setting the `ETag`
header improperly.
* Fixed GCODE viewer not properly detecting change of currently visualized
file on Windows systems.
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.6...1.2.7))
## 1.2.6 (2015-09-02)
### Improvements
* Added support for version reporting on detached checkouts
(see [#1041](https://github.com/foosel/OctoPrint/pull/1041))
### Bug Fixes
* Pinned requirement for [psutil](https://pypi.python.org/pypi/psutil)
dependency to version 3.1.1 of that library due to an issue when
installing version 3.2.0 of that library released on 2015-09-02 through
a `python setup.py install` on OctoPrint. Also pinned all other requirements
to definitive versions that definitely work while at it to keep that from
happening again.
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.5...1.2.6))
## 1.2.5 (2015-08-31)
### Improvements
* [#986](https://github.com/foosel/OctoPrint/issues/986) - Added tooltip for
"additional data" button in file list.
* [#1028](https://github.com/foosel/OctoPrint/issues/1028) - Hint about why
timelapse configuration is disabled.
* New central configuration option for commands to restart OctoPrint and to
restart and shut down the system OctoPrint is running on. This allows plugins
(like the Software Update Plugin or the Plugin Manager) and core functionality
to perform these common administrative tasks without the user needing to define
everything redundantly.
* Settings dialog now visualizes when settings are saving and when they being
retrieved. Also the Send/Cancel buttons are disabled while settings are saving
to prevent duplicated requests and concurrent retrieval of the settings by
multiple viewmodels is disabled as well.
* Better protection against rendering errors from templates provided by third
party plugins.
* Better protection against corrupting the configuration by using a temporary
file as intermediate buffer.
* Added warning to UI regarding Z timelapses and spiralized objects.
* Better compatibility with Repetier firmware:
* Added "Format Error" to whitelisted recoverable communication errors
(see also [#1032](https://github.com/foosel/OctoPrint/pull/1032)).
* Added option to ignore repeated resend requests for the same line (see
also discussion in [#1015](https://github.com/foosel/OctoPrint/pull/1015)).
* Software Update Plugin:
* Adjusted to utilize new centralized restart commands (see above).
* Allow configuration of checkout folder and version tracking type via
Plugin Configuration.
* Display message to user if OctoPrint's checkout folder is not configured
or a non-release version is running and version tracking against releases
is enabled.
* Clear version cache when a change in the check configuration is detected.
* Mark check configurations for which an update is not possible.
* Made disk space running low a bit more obvious through visual warning on
configurable thresholds.
### Bug Fixes
* [#985](https://github.com/foosel/OctoPrint/issues/985) - Do not hiccup on
unset `Content-Type` part headers for multipart file uploads.
* [#1001](https://github.com/foosel/OctoPrint/issues/1001) - Fixed connection
tab not unfolding properly (see also [#1002](https://github.com/foosel/OctoPrint/pull/1002)).
* [#1012](https://github.com/foosel/OctoPrint/issues/1012) - All API
responses now set no-cache headers, making the Edge browser behave a bit better
* [#1019](https://github.com/foosel/OctoPrint/issues/1019) - Better error
handling of problems when trying to write the webassets cache.
* [#1021](https://github.com/foosel/OctoPrint/issues/1021) - Properly handle
serial close on Macs.
* [#1031](https://github.com/foosel/OctoPrint/issues/1031) - Special
handling of `M112` (emergency stop) command:
* Jump send queue
* In case the printer's firmware doesn't understand it yet, at least
shutdown all of the heaters
* Disconnect
* Properly reset job progress to 0% when restarting a previously completed
printjob (see [#998](https://github.com/foosel/OctoPrint/pull/998)).
* Report an update as failed if the `pip` command returns a return code that
indicates failure.
* Fixed sorting of templates: could only be sorted by name, individual
configurations were ignored (see [#1022](https://github.com/foosel/OctoPrint/pull/1022)).
* Fixed positioning of custom context menus: were offset due to changes in
overall positioning settings (see [#1023](https://github.com/foosel/OctoPrint/pull/1023)).
* Software Update: Don't use display version for comparison of git commit
hashs.
* Fixed temperature parsing for multi extruder setups.
* Fixed nested vertical and horizontal custom control layouts.
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.4...1.2.5))
## 1.2.4 (2015-07-23)
### Improvements
* `RepeatedTimer` now defaults to `daemon` set to `True`. This makes sure
plugins using it don't have to remember to set that flag themselves in
order for the server to properly shut down when timers are still active.
* Fixed a typo in the docs about `logging.yaml` (top level element is
`loggers`, not `logger`).
* Support for plugins with external dependencies (`dependency_links` in
setuptools), interesting for plugin authors who need to depend on Python
libraries that are (not yet) available on PyPI.
* Better resilience against errors within plugins.
### Bug Fixes
* Do not cache web page when running for the first time, to avoid caching
the first run dialog popup along side with it. This should solve issues
people were having when configuring OctoPrint for the first time, then
reloading the page without clearing the cache, being again prompted with
the dialog with no chance to clear it.
* Fix/workaround for occasional white panes in settings dialog on Safari 8,
which appears to have an issue with fixed positioning.
* Fixed form field truncation in upload requests that could lead to problems
when trying to import Cura profiles with names longer than 28 characters.
* Fixed webcam rotation for timelapse rendering.
* Fixed user settings not reaching the editor in the frontend.
* Notifications that are in process of being closed don't open again on
mouse over (that was actually more of an unwanted feature).
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.3...1.2.4))
## 1.2.3 (2015-07-09)
### Improvements
* New option to actively poll the watched folder. This should make it work also
if it is mounted on a filesystem that doesn't allow getting notifications
about added files through notification by the operating system (e.g.
network shares).
* Better resilience against senseless temperature/SD-status-polling intervals
(such as 0).
* Log exceptions during writing to the serial port to `octoprint.log`.
### Bug Fixes
* [#961](https://github.com/foosel/OctoPrint/pull/961) - Fixed a JavaScript error that caused an error to be logged when "enter" was pressed in file or plugin search.
* [#962](https://github.com/foosel/OctoPrint/pull/962) - ``url(...)``s in packed CSS and LESS files should now be rewritten properly too to refer to correct paths
* Update notifications were not vanishing properly after updating:
* Only use version cache for update notifications if the OctoPrint version still is the same to make sure the cache gets invalidated after an external update of OctoPrint.
* Do not persist version information when saving settings of the Software Update plugin
* Always delete files from the ``watched`` folder after importing then. Using file preprocessor plugins could lead to the files staying there.
* Fixed an encoding problem causing OctoPrint's Plugin Manager and Software Update plugins to choke on UTF-8 characters in the update output.
* Fixed sorting by file size in file list
* More resilience against missing plugin assets:
* Asset existence will now be checked before they get included
in the assets to bundle by webassets, logging a warning if a
file isn't present.
* Monkey-patched webassets filter chain to not die when a file
doesn't exist, but to log an error instead and just return
an empty file instead.
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.2...1.2.3))
## 1.2.2 (2015-06-30)
### Bug Fixes
* Fixed an admin-only security issue introduced in 1.2.0, updating is strongly advised.
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.1...1.2.2))
## 1.2.1 (2015-06-30)
### Improvements
+256 -41
View File
@@ -1,49 +1,264 @@
Issues, Tickets, however you may call them
------------------------------------------
# Contribution Guidelines
Read the following short instructions **fully** and **follow them** if you want your ticket to be taken care of and not closed again directly! They are linked on top of every new issue form, so don't say nobody warned you afterwards.
This document outlines what you need to know before **[creating tickets](#issues-tickets-however-you-may-call-them)**
or **[creating pull requests](#pull-requests)**.
- **Read the [FAQ](https://github.com/foosel/OctoPrint/wiki/FAQ)**
- Always create **one ticket for one purpose**. So don't mix two or more feature requests, support requests, bugs etc into one ticket. If you do, your ticket will be closed!
- If you want to report a bug, **READ AND FOLLOW [How to file a bug report](https://github.com/foosel/OctoPrint/wiki/How-to-file-a-bug-report)!** Tickets will be automatically checked if they comply with the requirements outlined in that wiki node! Other then what's written in there (**and really EVERYTHING that is written in there!**) you don't have to do anything special with your ticket. Listen to what GitIssueBot might have to say to you!
- If you want to post a **request** of any kind (feature request, documentation request, ...), **add [Request] to your issue's title!**
- If you need **support** with a problem of your installation (e.g. if you have problems getting the webcam to work) or have a general **question**, the issue tracker is not the right place. Consult the [Mailinglist](https://groups.google.com/group/octoprint) or the [Google+ Community](https://plus.google.com/communities/102771308349328485741) instead!
- If you are a developer that wants to brainstorm a pull request or possible changes to the plugin system, **add [Brainstorming] to your issue's title!** (see below).
- If you have another reason for creating a ticket that doesn't fit any of the above categories, it's something better suited for the [Mailinglist](https://groups.google.com/group/octoprint) or the [Google+ Community](https://plus.google.com/communities/102771308349328485741).
## Contents
Following these guidelines (**especially EVERYTHING mentioned in ["How to file a bug report"](https://github.com/foosel/OctoPrint/wiki/How-to-file-a-bug-report)**) is necessary so the tickets stay manageable - you are not the only one with an open issue, so please respect that you have to **play by the rules** so that your problem can be taken care of. Tickets not playing by the rules **will be closed without further investigation!**.
* [Issues, Tickets, however you may call them](#issues-tickets-however-you-may-call-them)
* [How to file a bug report](#how-to-file-a-bug-report)
* [What should I do before submitting a bug report?](#what-should-i-do-before-submitting-a-bug-report)
* [What should I include in a bug report?](#what-should-i-include-in-a-bug-report)
* [Where can I find which version and branch I'm on?](#where-can-i-find-which-version-and-branch-im-on)
* [Where can I find those log files you keep talking about?](#where-can-i-find-those-log-files-you-keep-talking-about)
* [Where can I find my browser's error console?](#where-can-i-find-my-browsers-error-console)
* [Pull requests](#pull-requests)
* [History](#history)
* [Footnotes](#footnotes)
Pull Requests
-------------
## Issues, Tickets, however you may call them
1. If you want to add a new feature to OctoPrint, **please always first consider if it wouldn't be better suited for a
plugin.** As a general rule of thumb, any feature that is only of interest to a small sub group should be moved into a
plugin. If the current plugin system doesn't allow you to implement your feature as a plugin, create a "Brainstorming"
ticket to get the discussion going how best to solve *this* in OctoPrint's plugin system - maybe that's the actual PR
you have been waiting for to contribute :)
2. If you plan to make **any large changes to the code or appearance, please open a "Brainstorming" ticket first** so that
we can determine if it's a good time for your specific pull request. It might be that I'm currently in the process of
making heavy changes to the code locations you'd target as well, or your approach doesn't fit the general "project
vision", and that would just cause unnecessary work and frustration for everyone or possibly get the PR rejected.
3. When adding code to OctoPrint, make sure you **follow the current coding style**. That means tabs instead of spaces in the
python files (yes, I know that this goes against PEP-8, I don't care) and space instead of tabs in the Javascript sources,
english language (that means code, variables, comments!), comments where necessary (tell why the code does something like
it does it, structure your code), following the general architecture. If your PR needs to make changes to the Stylesheets,
change the ``.less`` files from which the CSS is compiled. PRs that contain direct changes to the compiled
CSS will be closed.
4. **Test your changes thoroughly**. That also means testing with usage scenarios you don't normally use, e.g. if you only
use access control, test without and vice versa. If you only test with your printer, test with the virtual printer and
vice versa. State in your pull request how your tested your changes.
5. Please create all pull requests **against the `devel` branch**.
6. Create **one pull request per feature/bug fix**.
7. Create a **custom branch** for your feature/bug fix and use that as base for your pull request. Pull requests directly
against your version of `devel` will be closed.
7. In your pull request's description, **state what your pull request is doing**, as in, what feature does it implement, what
bug does it fix. The more thoroughly you explain your intent behind the PR here, the higher the chances it will get merged
fast.
Please read the following short instructions fully and follow them. You can
help the project tremendously this way: not only do you help the maintainers
to **address problems in a timely manner** but also keep it possible for them
to **fix bugs, add new and improve on existing functionality** instead of doing
nothing but ticket management.
History
-------
![Ticket flow chart](http://i.imgur.com/qYSZyuw.png)
* 2015-01-23: More guidelines for creating pull requests, support/questions redirected to Mailinglist/G+ community
- **[Read the FAQ](https://github.com/foosel/OctoPrint/wiki/FAQ)**
- If you want to report a **bug**, [read "How to file a bug report" below](#how-to-file-a-bug-report)
and *[use the provided template](#what-should-i-include-in-a-ticket)*.
You do not need to do anything else with your ticket.
- If you want to post a **request** of any kind (feature request, documentation
request, ...), add `[Request]` to your issue's title (e.g. `[Request] Awesome new feature`).
- If you are a **developer** that wants to brainstorm a pull request or possible
changes to the plugin system, add [Brainstorming] to your issue's title (e.g.
`[Brainstorming] New plugin hook for doing some cool stuff`).
- If you need **support**, have a **question** or some **other reason** that
doesn't fit any of the above categories, the issue tracker is not the right place.
Consult the [Mailinglist](https://groups.google.com/group/octoprint) or the
[Google+ Community](https://plus.google.com/communities/102771308349328485741) instead.
No matter what kind of ticket you create, never mix two or more "ticket reasons"
into one ticket: One ticket per bug, request, brainstorming thread please.
----
**Note**: A bot is in place that monitors new tickets, automatically
categorizes them and checks new bug reports for usage of the provided template.
That bot will only bother you if you open a ticket that appears to be a bug (no
`[Request]` or `[Brainstorming]` in the title) without the template, and it
will do that only to ensure that all information needed to solve the issue is
available for the maintainers to directly start tackling that problem.
----
## How to file a bug report
If you encounter an issue with OctoPrint, you are welcome to
[submit a bug report](https://goo.gl/GzkGv9).
Before you do that for the first time though please take a moment to read the
following section *completely*. Thank you! :)
### What should I do before submitting a bug report?
1. **Make sure you are at the right location**. This is the Github repository
of the official version of OctoPrint, which is the 3D print server and
corresponding web interface itself.
**This is not the Github respository of OctoPi**, which is the preconfigured
Raspberry Pi image including OctoPrint among other things - that one can be found
[here](https://github.com/guysoft/OctoPi). Please note that while we do have
some entries regarding OctoPi in the FAQ, any bugs should be reported in the
[proper bug tracker](https://github.com/guysoft/OctoPi/issues) which - again -
is not here.
**This is also not the Github repository of any OctoPrint Plugins you
might have installed**. Report any issues with those in their corresponding
bug tracker (probably linked to from the plugin's homepage).
Finally, **this is also not the right issue tracker if you are running an
forked version of OctoPrint**. Seek help for such unofficial versions from
the people maintaining them instead.
2. Please make sure to **test out the current version** of OctoPrint to see
whether the problem you are encountering still exists.
If you are feeling up to it you might also want to try the current development
version of OctoPrint (if you aren't already). Refer to the [FAQ](https://github.com/foosel/OctoPrint/wiki/FAQ)
for information on how to do this.
3. The problem still exists? Then please **look through the
[existing tickets](https://github.com/foosel/OctoPrint/issues?state=open)
(use the [search](https://github.com/foosel/OctoPrint/search?q=&ref=cmdform&type=Issues))**
to check if there already exists a report of the issue you are encountering.
Sorting through duplicates of the same issue sometimes causes more work than
fixing it. Take the time to filter through possible duplicates and be really
sure that your problem definitely is a new one. Try more than one search query
(e.g. do not only search for "webcam" if you happen to run into an issue
with your webcam, also search for "timelapse" etc).
### What should I include in a bug report?
Always use the following template (you can remove what's within `[...]`, that's
only provided here as some additional information for you):
#### What were you doing?
[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. 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?
#### What happened instead?
#### Branch & Commit or Version of OctoPrint
[Can be found in the lower left corner of the web interface.]
#### Printer model & used firmware incl. version
[If applicable, always include if unsure.]
#### Browser and Version of Browser, Operating System running Browser
[If applicable, always include if unsure.]
#### Link to octoprint.log
[On gist.github.com or pastebin.com. Always include and never truncate.]
#### Link to contents of terminal tab or serial.log
[On gist.github.com or pastebin.com. If applicable, always include if unsure or
reporting communication issues. Never truncate.]
#### 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.]
#### Screenshot(s) showing the problem:
[If applicable. Always include if unsure or reporting UI issues.]
I have read the FAQ.
### Where can I find which version and branch I'm on?
You can find out all of them by taking a look into the lower left corner of the
OctoPrint UI:
![Current version and git branch info in OctoPrint's UI](http://i.imgur.com/HyHMlY2.png)
If you don't have access to the UI you can find out that information via the
command line as well. Either `octoprint --version` or `python setup.py version`
in OctoPrint's folder will tell you the version of OctoPrint you are running
(note: if it doesn't then you are running a version older than 1.1.0,
*upgrade now*). A `git branch` in your OctoPrint installation folder will mark
the branch you are on with a little *. `git rev-parse HEAD` will tell you the
current commit.
### Where can I find those log files you keep talking about?
OctoPrint by default provides two log outputs, a third one can be enabled if
more information is needed.
One is contained in the **"Terminal" tab** within OctoPrint's UI and is a log
of the last 300 lines of communication with the printer. Please copy-paste
this somewhere (disable auto scroll to make copying the contents easier) -
e.g. http://pastebin.com or http://gist.github.com - and include a link in
your bug report.
There is also **OctoPrint's application log file** or in short `octoprint.log`,
which is by default located at `~/.octoprint/logs/octoprint.log` on Linux,
`%APPDATA%\OctoPrint\logs\octoprint.log` on Windows and
`~/Library/Application Support/OctoPrint/logs/octoprint.log` on MacOS. Please
copy-paste this to pastebin or gist as well and include a link in your bug
report.
It might happen that you are asked to provide a more **thorough log of the
communication with the printer** if you haven't already done so, the `serial.log`.
This is not written by default due to performance reasons, but you can enable
it in the settings dialog. After enabling that log, please reproduce the problem
again (connect to the printer, do whatever triggers it), then copy-paste
`~/.octoprint/logs/serial.log` (Windows: `%APPDATA%\OctoPrint\logs\serial.log`,
MacOS: `~/Library/Application Support/OctoPrint/logs/serial.log`) to pastebin
or gist and include the link in the bug report.
You might also be asked to provide a log with an increased log level. You can
find information on how to do just that in the
[docs](http://docs.octoprint.org/en/master/configuration/logging_yaml.html).
### Where can I find my browser's error console?
See [How to open the Javascript Console in different browsers](https://webmasters.stackexchange.com/questions/8525/how-to-open-the-javascript-console-in-different-browsers)
## Pull requests
1. If you want to add a new feature to OctoPrint, **please always first
consider if it wouldn't be better suited for a plugin.** As a general rule
of thumb, any feature that is only of interest to a small sub group should
be moved into a plugin. If the current plugin system doesn't allow you to
implement your feature as a plugin, create a "Brainstorming" ticket to get
the discussion going on how best to solve *this* in OctoPrint's plugin
system - maybe that's the actual PR you have been waiting for to contribute :)
2. If you plan to make **any large changes to the code or appearance, please
open a "Brainstorming" ticket first** so that we can determine if it's a
good time for your specific pull request. It might be that we're currently
in the process of making heavy changes to the code locations you'd target
as well, or your approach doesn't fit the general "project vision", and
that would just cause unnecessary work and frustration for everyone or
possibly get the PR rejected.
3. Create your pull request **from a custom branch** on your end (e.g.
`dev/myNewFeature`)[1] **against the `devel` branch**. Create **one pull request
per feature/bug fix**. If your PR contains an important bug fix, we will
make sure to backport it to the `maintenance` branch to also include it in
the next release.
4. Make sure you **follow the current coding style**. This means:
* Tabs instead of spaces in the Python files[2]
* Spaces instead of tabs in the Javascript sources
* English language (code, variables, comments, ...)
* Comments where necessary: Tell why the code does something like it does
it, structure your code
* Following the general architecture
If your PR needs to make changes to the Stylesheets, change the ``.less`` files
from which the CSS is compiled.
5. **Test your changes thoroughly**. That also means testing with usage
scenarios you don't normally use, e.g. if you only use access control, test
without and vice versa. If you only test with your printer, test with the
virtual printer and vice versa. State in your pull request how your tested
your changes. Ideally **add unit tests** - OctoPrint severly lacks in that
department, but we are trying to change that, so any new code already covered
with a test suite helps a lot!
6. In your pull request's description, **state what your pull request is doing**,
as in, what feature does it implement, what bug does it fix. The more
thoroughly you explain your intent behind the PR here, the higher the
chances it will get merged fast.
7. Important: Don't forget to **add yourself to the [AUTHORS](./AUTHORS.md)
file** :)
## History
* 2015-01-23: More guidelines for creating pull requests, support/questions
redirected to Mailinglist/G+ community
* 2015-01-27: Added another explicit link to the FAQ
* 2015-07-07: Added step to add yourself to AUTHORS when creating a PR :)
* 2015-12-01: Heavily reworked to include examples, better structure and
all information in one document.
## Footnotes
* [1] - If you are wondering why, the problem is that anything that you add
to your PR's branch will also become part of your PR, so if you create a
PR from your version of `devel` chances are high you'll add changes to the
PR that do not belong to the PR.
* [2] - Yes, we know that this goes against PEP-8. OctoPrint started out as
a fork of Cura and hence stuck to the coding style found therein. Changing
it now would make the history and especially `git blame` completely
unusable, so for now we'll have to deal with it (this decision might be
revisited in the future).
+62 -8
View File
@@ -1,26 +1,68 @@
OctoPrint
=========
[![Flattr this git repo](http://api.flattr.com/button/flattr-badge-large.png)](https://flattr.com/submit/auto?user_id=foosel&url=https://github.com/foosel/OctoPrint&title=OctoPrint&language=&tags=github&category=software)
OctoPrint provides a responsive web interface for controlling a 3D printer (RepRap, Ultimaker, ...). It is Free Software
OctoPrint provides a snappy web interface for controlling a 3D printer (RepRap, Ultimaker, ...). It is Free Software
and released under the [GNU Affero General Public License V3](http://www.gnu.org/licenses/agpl.html).
Its website can be found at [octoprint.org](http://octoprint.org).
The documentation is located at [docs.octoprint.org](http://docs.octoprint.org).
The official plugin repository can be reached at [plugins.octoprint.org](http://plugins.octoprint.org).
![Screenshot](http://i.imgur.com/dF3noFp.png)
You are currently looking at the source code repository of OctoPrint. If you already installed it
(e.g. by using the Raspberry Pi targeted distribution [OctoPi](https://github.com/guysoft/OctoPi)) and only
want to find out how to use it, [the documentation](http://docs.octoprint.org/) and [the public wiki](https://github.com/foosel/OctoPrint/wiki)
might be of more interest for you. You might also want to subscribe to [the mailing list](https://groups.google.com/group/octoprint)
or the [G+ Community](https://plus.google.com/communities/102771308349328485741) where there are other active users who might be
able to help you with any questions you might have.
Contributing
------------
Please see the project's [Contribution Guidelines](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md).
Contributions of all kinds are welcome, not only in the form of code but also with regards to the
[official documentation](http://docs.octoprint.org/) or [the public wiki](https://github.com/foosel/OctoPrint/wiki), support
of other users in the [bug tracker](https://github.com/foosel/OctoPrint/issues),
[the Mailinglist](https://groups.google.com/group/octoprint) or
[the G+ Community](https://plus.google.com/communities/102771308349328485741).
If you think something is bad as it is about OctoPrint or its documentation the way it is, please help
in any way to make it better instead of just complaining about it -- this is an Open Source Project
after all :)
For information about how to go about contributions of any kind, please see the project's
[Contribution Guidelines](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md).
Installation
------------
Installation instructions for installing from source for different operating systems can be found [on the wiki](https://github.com/foosel/OctoPrint/wiki#assorted-guides).
Installation instructions for installing from source for different operating
systems can be found [on the wiki](https://github.com/foosel/OctoPrint/wiki#assorted-guides).
If you want to run OctoPrint on a Raspberry Pi you might want to take a look at [OctoPi](https://github.com/guysoft/OctoPi)
which is a custom SD card image that includes OctoPrint plus dependencies.
The generic steps that should basically be done regardless of operating system
and runtime environment are the following (as *regular
user*, please keep your hands *off* of the `sudo` command here!) - this assumes
you already have Python 2.7, pip and virtualenv set up:
1. Checkout OctoPrint: `git clone https://github.com/foosel/OctoPrint.git`
2. Change into the OctoPrint folder: `cd OctoPrint`
3. Create a user-owned virtual environment therein: `virtualenv --system-site-packages venv`
4. Install OctoPrint *into that virtual environment*: `./venv/bin/python setup.py install`
You may then start the OctoPrint server via `/path/to/OctoPrint/venv/bin/octoprint`, see [Usage](#usage)
for details.
After installation, please make sure you follow the first-run wizard and set up
access control as necessary. If you want to not only be notified about new
releases but also be able to automatically upgrade to them from within
OctoPrint, take a look [at the documentation of the Software Update Plugin](https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update#making-octoprint-updateable-on-existing-installations)
and at its settings.
Dependencies
------------
@@ -36,7 +78,11 @@ OctoPrint currently only supports Python 2.7.
Usage
-----
Running the `setup.py` script installs the `octoprint` script in your Python installation's scripts folder
Running the `setup.py` script via
python setup.py install
installs the `octoprint` script in your Python installation's scripts folder
(which depending on whether you installed OctoPrint globally or into a virtual env will be on your `PATH` or not). The
following usage examples assume that said `octoprint` script is on your `PATH`.
@@ -77,5 +123,13 @@ which is located at `~/.octoprint` on Linux, at `%APPDATA%/OctoPrint` on Windows
at `~/Library/Application Support/OctoPrint` on MacOS.
A comprehensive overview of all available configuration settings can be found
[on the wiki](https://github.com/foosel/OctoPrint/wiki/Configuration). Please note that the most commonly used
configuration settings can also easily be edited from OctoPrint's settings dialog.
[in the docs](http://docs.octoprint.org/en/master/configuration/config_yaml.html).
Please note that the most commonly used configuration settings can also easily
be edited from OctoPrint's settings dialog.
Special Thanks
--------------
The development of OctoPrint is sponsored and maintained by [BQ](http://www.bq.com/).
Cross-browser testing services are kindly provided by [BrowserStack](http://www.browserstack.com/).
Profiling is done with the help of [PyVmMonitor](http://www.pyvmmonitor.com).
+4 -4
View File
@@ -37,7 +37,7 @@ Issue a job command
.. sourcecode:: http
POST /api/control/job HTTP/1.1
POST /api/job HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
@@ -54,7 +54,7 @@ Issue a job command
.. sourcecode:: http
POST /api/control/job HTTP/1.1
POST /api/job HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
@@ -71,7 +71,7 @@ Issue a job command
.. sourcecode:: http
POST /api/control/job HTTP/1.1
POST /api/job HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
@@ -88,7 +88,7 @@ Issue a job command
.. sourcecode:: http
POST /api/control/job HTTP/1.1
POST /api/job HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
+1 -1
View File
@@ -15,7 +15,7 @@ Log file management
Retrieve a list of available log files
======================================
.. http:post:: /api/logs
.. http:get:: /api/logs
Retrieve information regarding all log files currently available and regarding the disk space still available
in the system on the location the log files are being stored.
+15 -5
View File
@@ -25,7 +25,8 @@ Tool
See :ref:`sec-api-printer-toolcommand`.
Bed
Bed commands allow setting the temperature and temperature offset for the printer's heated bed. Querying the
corresponding resource returns temperature information including an optional history.
corresponding resource returns temperature information including an optional history. Note that Bed commands
are only available if the currently selected printer profile has a heated bed.
See :ref:`sec-api-printer-bedcommand`.
SD card
SD commands allow initialization, refresh and release of the printer's SD card (if available). Querying the
@@ -564,6 +565,9 @@ Issue a bed command
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
If no heated bed is configured for the currently selected printer profile, the resource will return
an :http:statuscode:`409`.
**Example Target Temperature Request**
Set the target temperature for the printer's heated bed to 75°C.
@@ -610,7 +614,8 @@ Issue a bed command
:statuscode 204: No error
:statuscode 400: If ``target`` or ``offset`` is not a valid number or outside of the supported range, or if the
request is otherwise invalid.
:statuscode 409: If the printer is not operational.
:statuscode 409: If the printer is not operational or the selected printer profile
does not have a heated bed.
.. _sec-api-printer-bedstate:
@@ -627,6 +632,9 @@ Retrieve the current bed state
Returns a :http:statuscode:`200` with a Temperature Response in the body upon success.
If no heated bed is configured for the currently selected printer profile, the resource will return
an :http:statuscode:`409`.
.. note::
If you want both tool and bed temperature information at the same time, take a look at
:ref:`Retrieve the current printer state <sec-api-printer-state>`.
@@ -675,7 +683,8 @@ Retrieve the current bed state
:query limit: If set to an integer (``n``), only the last ``n`` data points from the printer's temperature history
will be returned. Will be ignored if ``history`` is not enabled.
:statuscode 200: No error
:statuscode 409: If the printer is not operational.
:statuscode 409: If the printer is not operational or the selected printer profile
does not have a heated bed.
.. _sec-api-printer-sdcommand:
@@ -856,7 +865,7 @@ Send an arbitrary command to the printer
.. sourcecode:: http
HTTP/1.1 204 No Content
:json string command: Single command to send to the printer, mutually exclusive with ``commands``.
:json string commands: List of commands to send to the printer, mutually exclusive with ``command``.
:statuscode 204: No error
@@ -913,7 +922,8 @@ Temperature State
* - ``bed``
- 0..1
- :ref:`Temperature Data <sec-api-datamodel-printer-tempdata>`
- Current temperature stats for the printer's heated bed. Not included if querying only tool state.
- Current temperature stats for the printer's heated bed. Not included if querying only tool state or if
the currently selected printer profile does not have a heated bed.
* - ``history``
- 0..1
- List of :ref:`Historic Temperature Datapoint <sec-api-datamodel-printer-temphistory>`
+14 -1
View File
@@ -621,7 +621,8 @@ Use the following settings to configure the server:
.. code-block:: yaml
server:
# Use this option to define the host to which to bind the server, defaults to "0.0.0.0" (= all interfaces)
# Use this option to define the host to which to bind the server, defaults to "0.0.0.0" (= all
# interfaces)
host: 0.0.0.0
# Use this option to define the port to which to bind the server, defaults to 5000
@@ -691,6 +692,18 @@ Use the following settings to configure the server:
# Maximum size of requests other than file uploads in bytes, defaults to 100KB.
maxSize: 102400
# Commands to restart/shutdown octoprint or the system it's running on
commands:
# Command to restart OctoPrint, defaults to being unset
serverRestartCommand: sudo service octoprint restart
# Command to restart the system OctoPrint is running on, defaults to being unset
systemRestartCommand: sudo shutdown -r now
# Command to shut down the system OctoPrint is running on, defaults to being unset
systemShutdownCommand: sudo shutdown -h now
.. note::
+3 -3
View File
@@ -17,7 +17,7 @@ Changing log levels
If you need to change the default logging level within OctoPrint, create the file with a text editor of your choice
(it's usually not there). The general format is this::
logger:
loggers:
<component>:
level: <loglevel>
@@ -27,7 +27,7 @@ new log level to set. An example for increasing the log level of the events and
.. code-block:: yaml
logger:
loggers:
octoprint.events:
level: DEBUG
octoprint.filemanager:
@@ -97,4 +97,4 @@ expressed in YAML as follows:
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
The possible keys for the logging format can be found in the
`Python documentation on LogRecord attributes <https://docs.python.org/2/library/logging.html#logrecord-attributes>`_.
`Python documentation on LogRecord attributes <https://docs.python.org/2/library/logging.html#logrecord-attributes>`_.
+69
View File
@@ -0,0 +1,69 @@
.. _sec-features-access_control:
Access Control
==============
When Access Control is enabled, anonymous users (not logged in) will only see
the read-only parts of the UI which are the following:
* printer state
* available gcode files and stats (upload is disabled)
* temperature
* webcam
* gcode viewer
* terminal output (sending commands is disabled)
* available timelapse movies
* any components provided through plugins which are enabled for anonymous
users
Logged in users will get access to everything besides the Settings and System
Commands, which are admin-only.
If Access Control is disabled, everything is directly accessible. **That also
includes all administrative functionality as well as full control over the
printer!**
Upon first start a configuration wizard is provided which allows configuration
of the first administrator account or alternatively disabling Access Control
(which is **NOT** recommended for systems that are directly accessible via the
Internet!).
.. hint::
If you plan to have your OctoPrint instance accessible over the internet,
**always enable Access Control**.
.. _sec-features-access_control-rerunning_wizard:
Rerunning the wizard
--------------------
In case Access Control was disabled in the configuration wizard, it is
possibly to re-run it by editing ``config.yaml`` [#f1]_ and setting ``firstRun``
in the ``server`` section and ``enabled`` in the ``accessControl`` section to
``true``:
.. code-block-ext:: yaml
accessControl:
enabled: true
# ...
server:
firstRun: true
Then restart the server and connect to the web interface - the wizard should
be shown again.
.. note::
If user accounts were created prior to disabling Access Control and those
user accounts are not to be used any more, remove ``.octoprint/users.yaml``.
If you don't remove this file, the above changes won't lead to the
configuration being shown again, instead Access Control will just be
enabled using the already existing login data. This is to prevent you from
resetting access control by accident.
.. rubric:: Footnotes
.. [#f1] For Linux that will be ``~/.octoprint/config.yaml``, for Windows it will be ``%APPDATA%/OctoPrint/config.yaml`` and for
Mac ``~/Library/Application Support/OctoPrint/config.yaml``
+14 -2
View File
@@ -10,7 +10,7 @@ buttons which trigger sending of one or more lines of GCODE to the printer over
parameterization of these commands with values entered by the user to full blown GCODE script templates backed by
`Jinja2 <http://jinja.pocoo.org/>`_.
Custom controls are configured within :ref:`config.yaml <sec-configuration-config_yaml>` in a ``controls`` section which
Custom controls are configured within :ref:`config.yaml <sec-configuration-config_yaml>` [#f1]_ in a ``controls`` section which
basically represents a hierarchical structure of all configured custom controls of various types.
.. note::
@@ -94,6 +94,13 @@ button that sends one or more commands to the printer when clicked, displaying o
controls that just serve as *container* for other controls, the latter being identified by having a ``children``
attribute wrapping more controls.
.. hint::
Take a look at the `Custom Control Editor plugin <http://plugins.octoprint.org/plugins/customControl/>`_
which allows you configuring your Custom Controls through OctoPrint's
settings interface without the need to manually edit the configuration
file.
.. _sec-features-custom_controls-types:
Types
@@ -278,4 +285,9 @@ Parameterized GCODE Script
G28 X0 Y0
Note the usage of the ``parameters.repetitions`` template variable in the GCODE script template, which will contain
the value selected by the user for the "Go arounds" slider.
the value selected by the user for the "Go arounds" slider.
.. rubric:: Footnotes
.. [#f1] For Linux that will be ``~/.octoprint/config.yaml``, for Windows it will be ``%APPDATA%/OctoPrint/config.yaml`` and for
Mac ``~/Library/Application Support/OctoPrint/config.yaml``
+14 -3
View File
@@ -86,7 +86,7 @@ Out of the box, OctoPrint defaults to the following script setup for ``afterPrin
;disable all heaters
{% snippet 'disable_hotends' %}
M140 S0
[% snippet 'disable_bed' %}
;disable fan
M106 S0
@@ -100,8 +100,19 @@ The ``disable_hotends`` snippet is defined as follows:
M104 T{{ tool }} S0
{% endfor %}
As you can see, the ``disable_hotends`` snippet utilizes the ``printer_profile`` context variable in order to
iterate through all available extruders and set their temperature to 0.
The ``disable_bed`` snippet is defined as follows:
.. code-block:: jinja
:caption: Default ``disable_bed`` snippet
{% if printer_profile.heatedBed %}
M140 S0
{% endif %}
As you can see, the ``disable_hotends`` and ``disable_bed`` snippets utilize the
``printer_profile`` context variable in order to iterate through all available
extruders and set their temperature to 0, and to also set the bed temperature
to 0 if a heated bed is configured.
.. seealso::
+1
View File
@@ -7,6 +7,7 @@ Features
.. toctree::
:maxdepth: 2
accesscontrol.rst
custom_controls.rst
gcode_scripts.rst
action_commands.rst
+1 -1
View File
@@ -64,7 +64,7 @@ See :ref:`Developing Plugins <sec-plugins>`.
.. rubric:: Footnotes
.. [#f1] For Linux that will be ``~/.octoprint/plugins``, for Windows it will be ``%APPDATA%/OctoPrint/plugins`` and for
Mac ``~/Library/Application Support/OctoPrint``
Mac ``~/Library/Application Support/OctoPrint/plugins``
.. [#f2] Make sure to use the exact same Python installation for installing the plugin that you also used for
installing & running OctoPrint. For OctoPi this means using ``~/oprint/bin/pip`` for installing plugins
instead of just ``pip``.
+4
View File
@@ -6,6 +6,10 @@ Welcome to OctoPrint's documentation!
:alt: The OctoPrint Logo
:align: right
This documentation is still in the process of being migrated from
`OctoPrint's wiki <https://github.com/foosel/OctoPrint/wiki>`_, so also take
a look there!
Contents
========
+11
View File
@@ -0,0 +1,11 @@
[metadata]
description-file = README.md
[versioneer]
VCS = git
style = pep440-post
versionfile_source = src/octoprint/_version.py
versionfile_build = octoprint/_version.py
tag_prefix =
parentdir_prefix =
lookupfile = .versioneer-lookup
+34 -24
View File
@@ -16,22 +16,23 @@ INSTALL_REQUIRES = [
"flask>=0.9,<0.11",
"werkzeug==0.8.3",
"tornado==4.0.1",
"sockjs-tornado>=1.0.0",
"sockjs-tornado==1.0.1",
"PyYAML==3.10",
"Flask-Login==0.2.2",
"Flask-Principal==0.3.5",
"Flask-Babel==0.9",
"Flask-Assets==0.10",
"pyserial",
"netaddr",
"watchdog",
"sarge>=0.1.4",
"netifaces",
"pylru",
"rsa",
"pkginfo",
"requests",
"semantic_version"
"pyserial==2.7",
"netaddr==0.7.17",
"watchdog==0.8.3",
"sarge==0.1.4",
"netifaces==0.10",
"pylru==1.0.9",
"rsa==3.2",
"pkginfo==1.2.1",
"requests==2.7.0",
"semantic_version==2.4.2",
"psutil==3.2.1"
]
# Additional requirements for optional install options
@@ -46,7 +47,10 @@ EXTRA_REQUIRES = dict(
# Documentation dependencies
"sphinx>=1.3",
"sphinxcontrib-httpdomain",
"sphinx_rtd_theme"
"sphinx_rtd_theme",
# PyPi upload related
"pypandoc"
],
# Dependencies for developing OctoPrint plugins
@@ -55,17 +59,12 @@ EXTRA_REQUIRES = dict(
]
)
# Additional requirements for setup
SETUP_REQUIRES = []
# Dependency links for any of the aforementioned dependencies
DEPENDENCY_LINKS = []
# Versioneer configuration
versioneer.VCS = 'git'
versioneer.versionfile_source = 'src/octoprint/_version.py'
versioneer.versionfile_build = 'octoprint/_version.py'
versioneer.tag_prefix = ''
versioneer.parentdir_prefix = ''
versioneer.lookupfile = '.versioneer-lookup'
#-----------------------------------------------------------------------------------------------------------------------
# Anything below here is just command setup and general setup configuration
@@ -89,8 +88,22 @@ def params():
version = versioneer.get_version()
cmdclass = get_cmdclass()
description = "A responsive web interface for 3D printers"
description = "A snappy web interface for 3D printers"
long_description = open("README.md").read()
install_requires = INSTALL_REQUIRES
extras_require = EXTRA_REQUIRES
dependency_links = DEPENDENCY_LINKS
setup_requires = SETUP_REQUIRES
try:
import pypandoc
setup_requires += ["setuptools-markdown"]
long_description_markdown_filename = "README.md"
del pypandoc
except:
pass
classifiers = [
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
@@ -125,9 +138,6 @@ def params():
include_package_data = True
zip_safe = False
install_requires = INSTALL_REQUIRES
extras_require = EXTRA_REQUIRES
dependency_links = DEPENDENCY_LINKS
if os.environ.get('READTHEDOCS', None) == 'True':
# we can't tell read the docs to please perform a pip install -e .[develop], so we help
+539 -157
View File
@@ -1,28 +1,81 @@
# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag
# feature). Distribution tarballs (build by setup.py sdist) and build
# feature). Distribution tarballs (built by setup.py sdist) and build
# directories (produced by setup.py build) will contain a much shorter file
# that just contains the computed version number.
# This file is released into the public domain. Generated by
# versioneer-0.10 (https://github.com/warner/python-versioneer)
# these strings will be replaced by git during git-archive
git_refnames = "$Format:%d$"
git_full = "$Format:%H$"
# versioneer-0.15+dev (https://github.com/warner/python-versioneer)
"""Git implementation of _version.py."""
import errno
import os
import re
import subprocess
import sys
import errno
def get_keywords():
"""Get the keywords needed to look up the version information."""
# these strings will be replaced by git during git-archive.
# setup.py/versioneer.py will grep for the variable names, so they must
# each be defined on a line of their own. _version.py will just call
# get_keywords().
git_refnames = "$Format:%d$"
git_full = "$Format:%H$"
keywords = {"refnames": git_refnames, "full": git_full}
return keywords
class VersioneerConfig:
"""Container for Versioneer configuration parameters."""
def get_config():
"""Create, populate and return the VersioneerConfig() object."""
# these strings are filled in when 'setup.py versioneer' creates
# _version.py
cfg = VersioneerConfig()
cfg.VCS = "git"
cfg.style = "pep440"
cfg.tag_prefix = ""
cfg.parentdir_prefix = ""
cfg.versionfile_source = "src/octoprint/_version.py"
cfg.lookupfile = None
cfg.verbose = False
return cfg
class NotThisMethod(Exception):
"""Exception raised if a method is not valid for the current scenario."""
LONG_VERSION_PY = {}
HANDLERS = {}
def register_vcs_handler(vcs, method): # decorator
"""Decorator to mark a method as the handler for a particular VCS."""
def decorate(f):
"""Store f in HANDLERS[vcs][method]."""
if vcs not in HANDLERS:
HANDLERS[vcs] = {}
HANDLERS[vcs][method] = f
return f
return decorate
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
"""Call the given command(s)."""
assert isinstance(commands, list)
p = None
for c in commands:
try:
dispcmd = str([c] + args)
# remember shell=False, so use git.cmd on windows, not just git
p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,
stderr=(subprocess.PIPE if hide_stderr
@@ -33,7 +86,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
if e.errno == errno.ENOENT:
continue
if verbose:
print("unable to run %s" % args[0])
print("unable to run %s" % dispcmd)
print(e)
return None
else:
@@ -41,59 +94,67 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
print("unable to find command, tried %s" % (commands,))
return None
stdout = p.communicate()[0].strip()
if sys.version >= '3':
if sys.version_info[0] >= 3:
stdout = stdout.decode()
if p.returncode != 0:
if verbose:
print("unable to run %s (error)" % args[0])
print("unable to run %s (error)" % dispcmd)
return None
return stdout
import sys
import re
import os.path
def versions_from_parentdir(parentdir_prefix, root, verbose):
"""Try to determine the version from the parent directory name.
def get_gits(root, verbose=False):
if not os.path.exists(os.path.join(root, ".git")):
Source tarballs conventionally unpack into a directory that includes
both the project name and a version string.
"""
dirname = os.path.basename(root)
if not dirname.startswith(parentdir_prefix):
if verbose:
print("no .git in %s" % root)
return None
GITS = ["git"]
if sys.platform == "win32":
GITS = ["git.cmd", "git.exe"]
return GITS
print("guessing rootdir is '%s', but '%s' doesn't start with "
"prefix '%s'" % (root, dirname, parentdir_prefix))
raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
return {"version": dirname[len(parentdir_prefix):],
"full-revisionid": None,
"dirty": False, "error": None}
def get_expanded_variables(versionfile_abs):
@register_vcs_handler("git", "get_keywords")
def git_get_keywords(versionfile_abs):
"""Extract version information from the given file."""
# the code embedded in _version.py can just fetch the value of these
# variables. When used from setup.py, we don't want to import
# _version.py, so we do it with a regexp instead. This function is not
# used from _version.py.
variables = {}
# keywords. When used from setup.py, we don't want to import _version.py,
# so we do it with a regexp instead. This function is not used from
# _version.py.
keywords = {}
try:
f = open(versionfile_abs,"r")
f = open(versionfile_abs, "r")
for line in f.readlines():
if line.strip().startswith("git_refnames ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
variables["refnames"] = mo.group(1)
keywords["refnames"] = mo.group(1)
if line.strip().startswith("git_full ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
variables["full"] = mo.group(1)
keywords["full"] = mo.group(1)
f.close()
except EnvironmentError:
pass
return variables
return keywords
def versions_from_expanded_variables(variables, tag_prefix, verbose=False):
refnames = variables["refnames"].strip()
@register_vcs_handler("git", "keywords")
def git_versions_from_keywords(keywords, tag_prefix, verbose):
"""Get version information from git keywords."""
if not keywords:
raise NotThisMethod("no keywords at all, weird")
refnames = keywords["refnames"].strip()
if refnames.startswith("$Format"):
if verbose:
print("variables are unexpanded, not using")
return {} # unexpanded, so not in an unpacked git-archive tarball
print("keywords are unexpanded, not using")
raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
refs = set([r.strip() for r in refnames.strip("()").split(",")])
# starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
# just "foo-1.0". If we see a "tag: " prefix, prefer those.
@@ -110,6 +171,15 @@ def versions_from_expanded_variables(variables, tag_prefix, verbose=False):
tags = set([r for r in refs if re.search(r'\d', r)])
if verbose:
print("discarding '%s', no digits" % ",".join(refs-tags))
branches = [r for r in refs if not r.startswith(TAG)
and r != "HEAD" and not r.startswith("refs/")]
if verbose:
print("likely branches: %s" % ",".join(sorted(branches)))
branch = None
if branches:
branch = branches[0]
if verbose:
print("likely tags: %s" % ",".join(sorted(tags)))
for ref in sorted(tags):
@@ -118,161 +188,473 @@ def versions_from_expanded_variables(variables, tag_prefix, verbose=False):
r = ref[len(tag_prefix):]
if verbose:
print("picking %s" % r)
return { "version": r,
"full": variables["full"].strip() }
# no suitable tags, so we use the full revision id
result = {"version": r,
"full-revisionid": keywords["full"].strip(),
"dirty": False, "error": None}
if branch is not None:
result["branch"] = branch
return result
# no suitable tags, so version is "0+unknown", but full hex is still there
if verbose:
print("no suitable tags, using full revision id")
return { "version": variables["full"].strip(),
"full": variables["full"].strip() }
print("no suitable tags, using unknown + full revision id")
return {"version": "0+unknown",
"full-revisionid": keywords["full"].strip(),
"dirty": False, "error": "no suitable tags"}
def versions_from_lookup(lookup, root, verbose=False):
GITS = get_gits(root, verbose=verbose)
if GITS is None:
return {}
stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"],
cwd=root)
if stdout is None:
return {}
@register_vcs_handler("git", "pieces_from_vcs")
def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
"""Get version from 'git describe' in the root of the source tree.
current_branch = stdout.strip()
for matcher, tag, ref_commit in lookup:
if matcher.match(current_branch):
if tag is None or ref_commit is None:
return {}
stdout = run_command(GITS, ["rev-list", "%s..HEAD" % ref_commit, "--count"], cwd=root)
if stdout is None:
return {}
num_commits = stdout.strip()
stdout =run_command(GITS, ["rev-parse", "--short", "HEAD"], cwd=root)
if stdout is None:
return {}
short_hash = stdout.strip()
stdout = run_command(GITS, ["describe", "--tags", "--dirty", "--always"], cwd=root)
if stdout is None:
return {}
dirty = stdout.strip().endswith("-dirty")
stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
if stdout is None:
return {}
full = stdout.strip()
version = "%s-%s-g%s" % (tag, num_commits, short_hash)
if dirty:
version += "-dirty"
full += "-dirty"
return {"version": version, "full": full, "branch": current_branch}
return {}
def versions_from_vcs(tag_prefix, root, verbose=False):
# this runs 'git' from the root of the source tree. This only gets called
# if the git-archive 'subst' variables were *not* expanded, and
# _version.py hasn't already been rewritten with a short version string,
# meaning we're inside a checked out source tree.
GITS = get_gits(root, verbose=verbose)
if GITS is None:
return {}
stdout = run_command(GITS, ["describe", "--tags", "--dirty", "--always"],
cwd=root)
if stdout is None:
return {}
if not stdout.startswith(tag_prefix):
This only gets called if the git-archive 'subst' keywords were *not*
expanded, and _version.py hasn't already been rewritten with a short
version string, meaning we're inside a checked out source tree.
"""
if not os.path.exists(os.path.join(root, ".git")):
if verbose:
print("tag '%s' doesn't start with prefix '%s'" % (stdout, tag_prefix))
return {}
tag = stdout[len(tag_prefix):]
stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
if stdout is None:
return {}
full = stdout.strip()
if tag.endswith("-dirty"):
full += "-dirty"
print("no .git in %s" % root)
raise NotThisMethod("no .git directory")
GITS = ["git"]
if sys.platform == "win32":
GITS = ["git.cmd", "git.exe"]
# if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
# if there isn't one, this yields HEX[-dirty] (no NUM)
describe_out = run_command(GITS, ["describe", "--tags", "--dirty",
"--always", "--long",
"--match", "%s*" % tag_prefix],
cwd=root)
# --long was added in git-1.5.5
if describe_out is None:
raise NotThisMethod("'git describe' failed")
describe_out = describe_out.strip()
full_out = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
if full_out is None:
raise NotThisMethod("'git rev-parse' failed")
full_out = full_out.strip()
pieces = {}
pieces["long"] = full_out
pieces["short"] = full_out[:7] # maybe improved later
pieces["error"] = None
# parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
# TAG might have hyphens.
git_describe = describe_out
# look for -dirty suffix
dirty = git_describe.endswith("-dirty")
pieces["dirty"] = dirty
if dirty:
git_describe = git_describe[:git_describe.rindex("-dirty")]
# figure out our branch
abbrev_ref_out = run_command(GITS,
["rev-parse", "--abbrev-ref", "HEAD"],
cwd=root)
if abbrev_ref_out is not None:
pieces["branch"] = abbrev_ref_out.strip()
# now we have TAG-NUM-gHEX or HEX
if "-" in git_describe:
# TAG-NUM-gHEX
mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
if not mo:
# unparseable. Maybe git-describe is misbehaving?
pieces["error"] = ("unable to parse git-describe output: '%s'"
% describe_out)
return pieces
# tag
full_tag = mo.group(1)
if not full_tag.startswith(tag_prefix):
if verbose:
fmt = "tag '%s' doesn't start with prefix '%s'"
print(fmt % (full_tag, tag_prefix))
pieces["error"] = ("tag '%s' doesn't start with prefix '%s'"
% (full_tag, tag_prefix))
return pieces
pieces["closest-tag"] = full_tag[len(tag_prefix):]
# distance: number of commits since tag
pieces["distance"] = int(mo.group(2))
# commit: short hex revision ID
pieces["short"] = mo.group(3)
stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"],
cwd=root)
if stdout is None:
branch = None
else:
branch = stdout.strip()
return {"version": tag, "full": full, "branch": branch}
# HEX: no tags
pieces["closest-tag"] = None
count_out = run_command(GITS, ["rev-list", "HEAD", "--count"],
cwd=root)
pieces["distance"] = int(count_out) # total number of commits
return pieces
def versions_from_parentdir(parentdir_prefix, root, verbose=False):
# Source tarballs conventionally unpack into a directory that includes
# both the project name and a version string.
dirname = os.path.basename(root)
if not dirname.startswith(parentdir_prefix):
if verbose:
print("guessing rootdir is '%s', but '%s' doesn't start with prefix '%s'" %
(root, dirname, parentdir_prefix))
return None
return {"version": dirname[len(parentdir_prefix):], "full": "", "branch": ""}
@register_vcs_handler("git", "parse_lookup_file")
def git_parse_lookup_file(path):
"""Parse a versioneer lookup file.
tag_prefix = ""
parentdir_prefix = ""
versionfile_source = "src/octoprint/_version.py"
lookupfile = ".versioneer-lookup"
def parse_lookup_file(root, lookup_path=None):
if not lookup_path:
lookup_path = lookupfile
if not lookup_path:
return []
path = os.path.join(root, lookup_path)
This file allows definition of branch specific data like virtual tags or
custom styles to use for version rendering.
"""
if not os.path.exists(path):
return []
import re
lookup = []
with open(os.path.join(root, lookup_path), "r") as f:
with open(path, "r") as f:
for line in f:
if '#' in line:
line = line[:line.rindex('#')]
line = line[:line.rindex("#")]
line = line.strip()
if not line:
continue
try:
split_line = line.split()
if len(split_line) == 3:
pattern, tag, ref_commit = split_line
lookup.append([re.compile(pattern), tag, ref_commit])
elif len(split_line) >= 1:
lookup.append([re.compile(split_line[0]), None, None])
split_line = map(lambda x: x.strip(), line.split())
if not len(split_line):
continue
matcher = re.compile(split_line[0])
if len(split_line) == 1:
entry = [matcher, None, None, None]
elif len(split_line) == 2:
render = split_line[1]
entry = [matcher, render, None, None]
elif len(split_line) == 3:
tag, ref_commit = split_line[1:]
entry = [matcher, None, tag, ref_commit]
elif len(split_line) == 4:
tag, ref_commit, render = split_line[1:]
entry = [matcher, render, tag, ref_commit]
else:
continue
lookup.append(entry)
except:
break
return lookup
def get_versions(default={"version": "unknown", "full": "", "branch": "unknown"}, lookup_path=None, verbose=False):
@register_vcs_handler("git", "pieces_from_lookup")
def git_pieces_from_lookup(lookup, root, verbose, run_command=run_command):
"""Extract version information based on provided lookup data."""
GITS = ["git"]
if sys.platform == "win32":
GITS = ["git.cmd", "git.exe"]
stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"],
cwd=root)
if stdout is None:
raise NotThisMethod("git rev-parse --abbrev-ref HEAD failed")
current_branch = stdout.strip()
for matcher, render, tag, ref_commit in lookup:
if matcher.match(current_branch):
if tag is None or ref_commit is None:
raise NotThisMethod("tag or ref_commit is unset for "
"this branch")
stdout = run_command(GITS,
["rev-list", "%s..HEAD" % ref_commit,
"--count"],
cwd=root)
if stdout is None:
raise NotThisMethod("git rev-list %s..HEAD "
"--count failed" % ref_commit)
try:
num_commits = int(stdout.strip())
except ValueError:
raise NotThisMethod("git rev-list %s..HEAD --count didn't "
"return a valid number" % ref_commit)
stdout = run_command(GITS,
["rev-parse", "--short", "HEAD"],
cwd=root)
if stdout is None:
raise NotThisMethod("git describe rev-parse "
"--short HEAD failed")
short_hash = stdout.strip()
stdout = run_command(GITS,
["describe", "--tags",
"--dirty", "--always"],
cwd=root)
if stdout is None:
raise NotThisMethod("git describe --tags --dirty "
"--always failed")
dirty = stdout.strip().endswith("-dirty")
stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
if stdout is None:
raise NotThisMethod("git rev-parse HEAD failed")
full = stdout.strip()
return {
"long": full,
"short": short_hash,
"dirty": dirty,
"branch": current_branch,
"closest-tag": tag,
"distance": num_commits,
"error": None,
"render": render
}
raise NotThisMethod("no matching lookup definition found")
def plus_or_dot(pieces):
"""Return a + if we don't already have one, else return a ."""
if "+" in pieces.get("closest-tag", ""):
return "."
return "+"
def render_pep440(pieces):
"""Build up version string, with post-release "local version identifier".
Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
Exceptions:
1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"] or pieces["dirty"]:
rendered += plus_or_dot(pieces)
rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
if pieces["dirty"]:
rendered += ".dirty"
else:
# exception #1
rendered = "0+untagged.%d.g%s" % (pieces["distance"],
pieces["short"])
if pieces["dirty"]:
rendered += ".dirty"
return rendered
def render_pep440_pre(pieces):
"""TAG[.post.devDISTANCE] -- No -dirty.
Exceptions:
1: no tags. 0.post.devDISTANCE
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"]:
rendered += ".post.dev%d" % pieces["distance"]
else:
# exception #1
rendered = "0.post.dev%d" % pieces["distance"]
return rendered
def render_pep440_post(pieces):
"""TAG[.postDISTANCE[.dev0]+gHEX] .
The ".dev0" means dirty. Note that .dev0 sorts backwards
(a dirty tree will appear "older" than the corresponding clean one),
but you shouldn't be releasing software with -dirty anyways.
Exceptions:
1: no tags. 0.postDISTANCE[.dev0]
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"] or pieces["dirty"]:
rendered += ".post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
rendered += plus_or_dot(pieces)
rendered += "g%s" % pieces["short"]
else:
# exception #1
rendered = "0.post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
rendered += "+g%s" % pieces["short"]
return rendered
def render_pep440_dev(pieces):
"""TAG[.devDISTANCE]+gHEX[.dirty] .
Exceptions:
1: no tags. 0.devDISTANCE+gHEX[.dirty]
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"]:
rendered += ".dev%d" % pieces["distance"]
rendered += plus_or_dot(pieces)
else:
# exception #1
rendered = "0.dev%d" % pieces["distance"]
rendered += "+"
rendered += "g%s" % pieces["short"]
if pieces["dirty"]:
rendered += ".dirty"
return rendered
def render_pep440_old(pieces):
"""TAG[.postDISTANCE[.dev0]] .
The ".dev0" means dirty.
Eexceptions:
1: no tags. 0.postDISTANCE[.dev0]
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"] or pieces["dirty"]:
rendered += ".post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
else:
# exception #1
rendered = "0.post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
return rendered
def render_git_describe(pieces):
"""TAG[-DISTANCE-gHEX][-dirty].
Like 'git describe --tags --dirty --always'.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"]:
rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
else:
# exception #1
rendered = pieces["short"]
if pieces["dirty"]:
rendered += "-dirty"
return rendered
def render_git_describe_long(pieces):
"""TAG-DISTANCE-gHEX[-dirty].
Like 'git describe --tags --dirty --always -long'.
The distance/hash is unconditional.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
else:
# exception #1
rendered = pieces["short"]
if pieces["dirty"]:
rendered += "-dirty"
return rendered
def render(pieces, style):
"""Render the given version pieces into the requested style."""
if pieces["error"]:
return {"version": "unknown",
"full-revisionid": pieces.get("long"),
"dirty": None,
"error": pieces["error"]}
if "render" in pieces and pieces["render"] is not None:
style = pieces["render"]
if not style or style == "default":
style = "pep440" # the default
if style == "pep440":
rendered = render_pep440(pieces)
elif style == "pep440-pre":
rendered = render_pep440_pre(pieces)
elif style == "pep440-post":
rendered = render_pep440_post(pieces)
elif style == "pep440-old":
rendered = render_pep440_old(pieces)
elif style == "pep440-dev":
rendered = render_pep440_dev(pieces)
elif style == "git-describe":
rendered = render_git_describe(pieces)
elif style == "git-describe-long":
rendered = render_git_describe_long(pieces)
else:
raise ValueError("unknown style '%s'" % style)
result = {"version": rendered, "full-revisionid": pieces["long"],
"dirty": pieces["dirty"], "error": None}
if "branch" in pieces and pieces["branch"] is not None:
result["branch"] = pieces["branch"]
return result
def get_versions():
"""Get version information or return default if unable to do so."""
# I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
# __file__, we can work backwards from there to the root. Some
# py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
# case we can only use expanded variables.
# case we can only use expanded keywords.
variables = { "refnames": git_refnames, "full": git_full }
ver = versions_from_expanded_variables(variables, tag_prefix, verbose)
if ver:
return ver
cfg = get_config()
verbose = cfg.verbose
try:
root = os.path.abspath(__file__)
return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,
verbose)
except NotThisMethod:
pass
try:
root = os.path.realpath(__file__)
# versionfile_source is the relative path from the top of the source
# tree (where the .git directory might live) to this file. Invert
# this to find the root from __file__.
for i in range(len(versionfile_source.split("/"))):
for i in cfg.versionfile_source.split('/'):
root = os.path.dirname(root)
except NameError:
return default
return {"version": "0+unknown", "full-revisionid": None,
"dirty": None,
"error": "unable to find root of source tree"}
lookup = parse_lookup_file(root, lookup_path=lookup_path)
return (versions_from_lookup(lookup, root, verbose)
or versions_from_vcs(tag_prefix, root, verbose)
or versions_from_parentdir(parentdir_prefix, root, verbose)
or default)
lookupfile = cfg.lookupfile if cfg.lookupfile is not None else ".versioneer-lookup"
lookuppath = os.path.join(root, lookupfile)
if os.path.exists(lookuppath):
try:
lookup_data = git_parse_lookup_file(lookuppath)
pieces = git_pieces_from_lookup(lookup_data, root, verbose)
return render(pieces, cfg.style)
except NotThisMethod:
pass
try:
pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)
return render(pieces, cfg.style)
except NotThisMethod:
pass
try:
if cfg.parentdir_prefix:
return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
except NotThisMethod:
pass
return {"version": "0+unknown", "full-revisionid": None,
"dirty": None,
"error": "unable to compute version"}
+6
View File
@@ -74,6 +74,9 @@ class Events(object):
# Timelapse
CAPTURE_START = "CaptureStart"
CAPTURE_DONE = "CaptureDone"
CAPTURE_FAILED = "CaptureFailed"
POSTROLL_START = "PostRollStart"
POSTROLL_END = "PostRollEnd"
MOVIE_RENDERING = "MovieRendering"
MOVIE_DONE = "MovieDone"
MOVIE_FAILED = "MovieFailed"
@@ -298,6 +301,9 @@ class CommandTrigger(GenericEventListener):
def commandExecutioner(command):
if debug:
self._logger.info("Executing system command: %s" % command)
# we run this with shell=True since we have to trust whatever
# our admin configured as command and since we want to allow
# shell-alike handling here...
subprocess.Popen(command, shell=True)
try:
+55 -5
View File
@@ -18,6 +18,11 @@ from .analysis import QueueEntry, AnalysisQueue
from .storage import LocalFileStorage
from .util import AbstractFileWrapper, StreamWrapper, DiskFileWrapper
from collections import namedtuple
ContentTypeMapping = namedtuple("ContentTypeMapping", "extensions, content_type")
ContentTypeDetector = namedtuple("ContentTypeDetector", "extensions, detector")
extensions = dict(
)
@@ -25,11 +30,11 @@ def full_extension_tree():
result = dict(
# extensions for 3d model files
model=dict(
stl=["stl"]
stl=ContentTypeMapping(["stl"], "application/sla")
),
# extensions for printable machine code
machinecode=dict(
gcode=["gcode", "gco", "g"]
gcode=ContentTypeMapping(["gcode", "gco", "g"], "text/plain")
)
)
@@ -68,8 +73,12 @@ def get_all_extensions(subtree=None):
for key, value in subtree.items():
if isinstance(value, dict):
result += get_all_extensions(value)
elif isinstance(value, (ContentTypeMapping, ContentTypeDetector)):
result += value.extensions
elif isinstance(value, (list, tuple)):
result += value
elif isinstance(subtree, (ContentTypeMapping, ContentTypeDetector)):
result = subtree.extensions
elif isinstance(subtree, (list, tuple)):
result = subtree
return result
@@ -79,7 +88,9 @@ def get_path_for_extension(extension, subtree=None):
subtree = full_extension_tree()
for key, value in subtree.items():
if isinstance(value, (list, tuple)) and extension in value:
if isinstance(value, (ContentTypeMapping, ContentTypeDetector)) and extension in value.extensions:
return [key]
elif isinstance(value, (list, tuple)) and extension in value:
return [key]
elif isinstance(value, dict):
path = get_path_for_extension(extension, subtree=value)
@@ -88,6 +99,23 @@ def get_path_for_extension(extension, subtree=None):
return None
def get_content_type_mapping_for_extension(extension, subtree=None):
if not subtree:
subtree = full_extension_tree()
for key, value in subtree.items():
content_extension_matches = isinstance(value, (ContentTypeMapping, ContentTypeDetector)) and extension in value. extensions
list_extension_matches = isinstance(value, (list, tuple)) and extension in value
if content_extension_matches or list_extension_matches:
return value
elif isinstance(value, dict):
result = get_content_type_mapping_for_extension(extension, subtree=value)
if result is not None:
return result
return None
def valid_extension(extension, type=None):
if not type:
return extension in get_all_extensions()
@@ -106,6 +134,19 @@ def get_file_type(filename):
extension = extension[1:].lower()
return get_path_for_extension(extension)
def get_mime_type(filename):
_, extension = os.path.splitext(filename)
extension = extension[1:].lower()
mapping = get_content_type_mapping_for_extension(extension)
if mapping:
if isinstance(mapping, ContentTypeMapping) and mapping.content_type is not None:
return mapping.content_type
elif isinstance(mapping, ContentTypeDetector) and callable(mapping.detector):
result = mapping.detector(filename)
if result is not None:
return result
return "application/octet-stream"
class NoSuchStorage(Exception):
pass
@@ -155,7 +196,11 @@ class FileManager(object):
self._slicing_progress_callbacks.append(callback)
def unregister_slicingprogress_callback(self, callback):
self._slicing_progress_callbacks.remove(callback)
try:
self._slicing_progress_callbacks.remove(callback)
except ValueError:
# callback was not registered
pass
def _determine_analysis_backlog(self, storage_type, storage_manager):
counter = 0
@@ -314,7 +359,12 @@ class FileManager(object):
printer_profile = self._printer_profile_manager.get_current_or_default()
for hook in self._preprocessor_hooks.values():
hook_file_object = hook(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
try:
hook_file_object = hook(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
except:
self._logger.exception("Error when calling preprocessor hook {}, ignoring".format(hook))
continue
if hook_file_object is not None:
file_object = hook_file_object
file_path = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
+4 -54
View File
@@ -13,6 +13,8 @@ import tempfile
import octoprint.filemanager
from octoprint.util import is_hidden_path
class StorageInterface(object):
"""
Interface of storage adapters for OctoPrint.
@@ -357,7 +359,7 @@ class LocalFileStorage(StorageInterface):
if not metadata:
metadata = dict()
for entry in os.listdir(path):
if entry.startswith(".") or not octoprint.filemanager.valid_file_type(entry):
if is_hidden_path(entry) or not octoprint.filemanager.valid_file_type(entry):
continue
absolute_path = os.path.join(path, entry)
@@ -584,24 +586,6 @@ class LocalFileStorage(StorageInterface):
Note that for a ``path`` without a trailing slash the last part will be considered a file name and
hence be returned at second position. If you only need to convert a folder path, be sure to
include a trailing slash for a string ``path`` or an empty last element for a list ``path``.
Examples::
>>> storage = LocalFileStorage("/some/base/folder")
>>> storage.sanitize("some/folder/and/some file.gco")
("/some/base/folder/some/folder/and", "some_file.gco")
>>> storage.sanitize(("some", "folder", "and", "some file.gco"))
("/some/base/folder/some/folder/and", "some_file.gco")
>>> storage.sanitize("some file.gco")
("/some/base/folder", "some_file.gco")
>>> storage.sanitize(("some file.gco",))
("/some/base/folder", "some_file.gco")
>>> storage.sanitize("")
("/some/base/folder", "")
>>> storage.sanitize("some/folder/with/trailing/slash/")
("/some/base/folder/some/folder/with/trailing/slash", "")
>>> storage.sanitize("some", "folder", "")
("/some/base/folder/some/folder", "")
"""
name = None
if isinstance(path, (str, unicode, basestring)):
@@ -628,24 +612,6 @@ class LocalFileStorage(StorageInterface):
Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\``. Otherwise strips any characters from the
given ``name`` that are not any of the ASCII characters, digits, ``-``, ``_``, ``.``, ``(``, ``)`` or space and
replaces and spaces with ``_``.
Examples::
>>> storage = LocalFileStorage("/some/base/folder")
>>> storage.sanitize_name("some_file.gco")
"some_file.gco"
>>> storage.sanitize_name("some_file with (parentheses) and ümläuts and digits 123.gco")
"some_file_with_(parentheses)_and_mluts_and_digits_123.gco"
>>> storage.sanitize_name("pengüino pequeño.stl")
"pengino_pequeo.stl"
>>> storage.sanitize_name("some/folder/still/left.gco")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: name must not contain / or \
>>> storage.sanitize_name("also\\no\\backslashes.gco")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: name must not contain / or \
"""
if name is None:
return None
@@ -664,22 +630,6 @@ class LocalFileStorage(StorageInterface):
Ensures that the on disk representation of ``path`` is located under the configured basefolder. Resolves all
relative path elements (e.g. ``..``) and sanitizes folder names using :func:`sanitize_name`. Final path is the
absolute path including leading ``basefolder`` path.
Examples::
>>> storage = LocalFileStorage("/some/base/folder")
>>> storage.sanitize_path("folder/with/subfolder")
"/some/base/folder/folder/with/subfolder"
>>> storage.sanitize_path("folder/with/subfolder/../other/folder")
"/some/base/folder/folder/with/other/folder"
>>> storage.sanitize_path("/folder/with/leading/slash")
"/some/base/folder/folder/with/leading/slash"
>>> storage.sanitize_path(".folder/with/leading/dot")
"/some/base/folder/folder/with/leading/dot
>>> storage.sanitize_path("../../folder/out/of/the/basefolder")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: path not contained in base folder: /some/folder/out/of/the/basefolder
"""
if path[0] == "/" or path[0] == ".":
path = path[1:]
@@ -939,7 +889,7 @@ class LocalFileStorage(StorageInterface):
result = dict()
for entry in os.listdir(path):
if entry.startswith("."):
if is_hidden_path(entry):
# no hidden files and folders
continue
+3 -1
View File
@@ -7,6 +7,8 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
import io
from octoprint.util import atomic_write
class AbstractFileWrapper(object):
"""
Wrapper for file representations to save to storages.
@@ -85,7 +87,7 @@ class StreamWrapper(AbstractFileWrapper):
"""
import shutil
with open(path, "wb") as dest:
with atomic_write(path, "wb") as dest:
with self.stream() as source:
shutil.copyfileobj(source, dest)
+34 -6
View File
@@ -293,19 +293,16 @@ class PluginSettings(object):
self.set_preprocessors = dict(plugins=dict())
self.set_preprocessors["plugins"][plugin_key] = set_preprocessors
def prefix_path(path):
return ['plugins', self.plugin_key] + path
def prefix_path_in_args(args, index=0):
result = []
if index == 0:
result.append(prefix_path(args[0]))
result.append(self._prefix_path(args[0]))
result.extend(args[1:])
else:
args_before = args[:index - 1]
args_after = args[index + 1:]
result.extend(args_before)
result.append(prefix_path(args[index]))
result.append(self._prefix_path(args[index]))
result.extend(args_after)
return result
@@ -324,6 +321,7 @@ class PluginSettings(object):
return kwargs
self.access_methods = dict(
has =("has", prefix_path_in_args, add_getter_kwargs),
get =("get", prefix_path_in_args, add_getter_kwargs),
get_int =("getInt", prefix_path_in_args, add_getter_kwargs),
get_float =("getFloat", prefix_path_in_args, add_getter_kwargs),
@@ -331,7 +329,8 @@ class PluginSettings(object):
set =("set", prefix_path_in_args, add_setter_kwargs),
set_int =("setInt", prefix_path_in_args, add_setter_kwargs),
set_float =("setFloat", prefix_path_in_args, add_setter_kwargs),
set_boolean=("setBoolean", prefix_path_in_args, add_setter_kwargs)
set_boolean=("setBoolean", prefix_path_in_args, add_setter_kwargs),
remove =("remove", prefix_path_in_args)
)
self.deprecated_access_methods = dict(
getInt ="get_int",
@@ -342,6 +341,17 @@ class PluginSettings(object):
setBoolean="set_boolean"
)
def _prefix_path(self, path=None):
if path is None:
path = list()
return ['plugins', self.plugin_key] + path
def global_has(self, path, **kwargs):
return self.settings.has(path, **kwargs)
def global_remove(self, path, **kwargs):
return self.settings.remove(path, **kwargs)
def global_get(self, path, **kwargs):
"""
Getter for retrieving settings not managed by the plugin itself from the core settings structure. Use this
@@ -435,6 +445,24 @@ class PluginSettings(object):
os.makedirs(path)
return path
def get_all_data(self, **kwargs):
merged = kwargs.get("merged", True)
asdict = kwargs.get("asdict", True)
defaults = kwargs.get("defaults", self.defaults)
preprocessors = kwargs.get("preprocessors", self.get_preprocessors)
kwargs.update(dict(
merged=merged,
asdict=asdict,
defaults=defaults,
preprocessors=preprocessors
))
return self.settings.get(self._prefix_path(), **kwargs)
def clean_all_data(self):
self.settings.remove(self._prefix_path())
def __getattr__(self, item):
all_access_methods = self.access_methods.keys() + self.deprecated_access_methods.keys()
if item in all_access_methods:
+8 -10
View File
@@ -861,7 +861,7 @@ class PluginManager(object):
additional_pre_inits=additional_pre_inits,
additional_post_inits=additional_post_inits)
self.logger.info("Initialized {count} plugin(s)".format(count=len(self.plugin_implementations)))
self.logger.info("Initialized {count} plugin implementation(s)".format(count=len(self.plugin_implementations)))
def initialize_implementation_of_plugin(self, name, plugin, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None):
if plugin.implementation is None:
@@ -955,15 +955,13 @@ class PluginManager(object):
self.logger.info("No plugins available")
else:
self.logger.info("{count} plugin(s) registered with the system:\n{plugins}".format(count=len(all_plugins), plugins="\n".join(
sorted(
map(lambda x: "| " + x.long_str(show_bundled=show_bundled,
bundled_strs=bundled_str,
show_location=show_location,
location_str=location_str,
show_enabled=show_enabled,
enabled_strs=enabled_str),
self.enabled_plugins.values())
)
map(lambda x: "| " + x.long_str(show_bundled=show_bundled,
bundled_strs=bundled_str,
show_location=show_location,
location_str=location_str,
show_enabled=show_enabled,
enabled_strs=enabled_str),
sorted(self.plugins.values(), key=lambda x: str(x).lower()))
)))
def get_plugin(self, identifier, require_enabled=True):
+118 -5
View File
@@ -651,6 +651,24 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
return f
return decorator
@staticmethod
def errorhandler(code_or_exception):
"""
A decorator to mark errorhandlings methods in your BlueprintPlugin subclass. Works just the same as Flask's
own ``errorhandler`` decorator available on blueprints.
See `the documentation for flask.Blueprint.errorhandler <http://flask.pocoo.org/docs/0.10/api/#flask.Blueprint.errorhandler>`_
and `the documentation for flask.Flask.errorhandler <http://flask.pocoo.org/docs/0.10/api/#flask.Flask.errorhandler>`_ for more
information.
"""
from collections import defaultdict
def decorator(f):
if not hasattr(f, "_blueprint_error_handler") or f._blueprint_error_handler is None:
f._blueprint_error_handler = defaultdict(list)
f._blueprint_error_handler[f.__name__].append(code_or_exception)
return f
return decorator
def get_blueprint(self):
"""
Creates and returns the blueprint for your plugin. Override this if you want to define and handle your blueprint yourself.
@@ -660,15 +678,34 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
:return: the blueprint ready to be registered with Flask
"""
if hasattr(self, "_blueprint"):
# if we already constructed the blueprint and hence have it cached,
# return that instance - we don't want to instance it multiple times
return self._blueprint
import flask
kwargs = self.get_blueprint_kwargs()
blueprint = flask.Blueprint("plugin." + self._identifier, self._identifier, **kwargs)
# we now iterate over all members of ourselves and look if we find an attribute
# that has data originating from one of our decorators - we ignore anything
# starting with a _ to only handle public stuff
for member in [member for member in dir(self) if not member.startswith("_")]:
f = getattr(self, member)
if hasattr(f, "_blueprint_rules") and member in f._blueprint_rules:
# this attribute was annotated with our @route decorator
for blueprint_rule in f._blueprint_rules[member]:
rule, options = blueprint_rule
blueprint.add_url_rule(rule, options.pop("endpoint", f.__name__), view_func=f, **options)
if hasattr(f, "_blueprint_error_handler") and member in f._blueprint_error_handler:
# this attribute was annotated with our @error_handler decorator
for code_or_exception in f._blueprint_error_handler[member]:
blueprint.errorhandler(code_or_exception)(f)
# cache and return the blueprint object
self._blueprint = blueprint
return blueprint
def get_blueprint_kwargs(self):
@@ -764,6 +801,9 @@ class SettingsPlugin(OctoPrintPlugin):
the plugin core system upon initialization of the implementation.
"""
config_version_key = "_config_version"
"""Key of the field in the settings that holds the configuration format version."""
def on_settings_load(self):
"""
Loads the settings for the plugin, called by the Settings API view in order to retrieve all settings from
@@ -781,7 +821,10 @@ class SettingsPlugin(OctoPrintPlugin):
:return: the current settings of the plugin, as a dictionary
"""
return self._settings.get([], asdict=True, merged=True)
data = self._settings.get_all_data()
if self.config_version_key in data:
del data[self.config_version_key]
return data
def on_settings_save(self, data):
"""
@@ -792,7 +835,8 @@ class SettingsPlugin(OctoPrintPlugin):
.. note::
The default implementation will persist your plugin's settings as is, so just in the structure and in the
types that were received by the Settings API view.
types that were received by the Settings API view. Values identical to the default settings values
will *not* be persisted.
If you need more granular control here, e.g. over the used data types, you'll need to override this method
and iterate yourself over all your settings, retrieving them (if set) from the supplied received ``data``
@@ -800,12 +844,38 @@ class SettingsPlugin(OctoPrintPlugin):
Arguments:
data (dict): The settings dictionary to be saved for the plugin
Returns:
dict: The settings that differed from the defaults and were actually saved.
"""
import octoprint.util
current = self._settings.get([], asdict=True, merged=True)
data = octoprint.util.dict_merge(current, data)
self._settings.set([], data)
# get the current data
current = self._settings.get_all_data()
if current is None:
current = dict()
# merge our new data on top of it
new_current = octoprint.util.dict_merge(current, data)
if self.config_version_key in new_current:
del new_current[self.config_version_key]
# determine diff dict that contains minimal set of changes against the
# default settings - we only want to persist that, not everything
diff = octoprint.util.dict_minimal_mergediff(self.get_settings_defaults(), new_current)
version = self.get_settings_version()
to_persist = dict(diff)
if version:
to_persist[self.config_version_key] = version
if to_persist:
self._settings.set([], to_persist)
else:
self._settings.clean_all_data()
return diff
def get_settings_defaults(self):
"""
@@ -888,6 +958,49 @@ class SettingsPlugin(OctoPrintPlugin):
"""
pass
def on_settings_cleanup(self):
"""
Called after migration and initialization but before call to :func:`on_settings_initialized`.
Plugins may overwrite this method to perform additional clean up tasks.
The default implementation just minimizes the data persisted on disk to only contain
the differences to the defaults (in case the current data was persisted with an older
version of OctoPrint that still duplicated default data).
"""
import octoprint.util
from octoprint.settings import NoSuchSettingsPath
try:
# let's fetch the current persisted config (so only the data on disk,
# without the defaults)
config = self._settings.get_all_data(merged=False, incl_defaults=False, error_on_path=True)
except NoSuchSettingsPath:
# no config persisted, nothing to do => get out of here
return
if config is None:
# config is set to None, that doesn't make sense, kill it and leave
self._settings.clean_all_data()
return
if self.config_version_key in config and config[self.config_version_key] is None:
# delete None entries for config version - it's the default, no need
del config[self.config_version_key]
# calculate a minimal diff between the settings and the current config -
# anything already in the settings will be removed from the persisted
# config, no need to duplicate it
defaults = self.get_settings_defaults()
diff = octoprint.util.dict_minimal_mergediff(defaults, config)
if not diff:
# no diff to defaults, no need to have anything persisted
self._settings.clean_all_data()
else:
# diff => persist only that
self._settings.set([], diff)
def on_settings_initialized(self):
"""
Called after the settings have been initialized and - if necessary - also been migrated through a call to
+33 -26
View File
@@ -35,6 +35,13 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
self._cancelled_jobs = []
self._job_mutex = threading.Lock()
##~~ TemplatePlugin API
def get_template_vars(self):
return dict(
homepage=__plugin_url__
)
##~~ StartupPlugin API
def on_startup(self, host, port):
@@ -218,7 +225,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
if not on_progress_kwargs:
on_progress_kwargs = dict()
self._cura_logger.info("### Slicing %s to %s using profile stored at %s" % (model_path, machinecode_path, profile_path))
self._cura_logger.info(u"### Slicing %s to %s using profile stored at %s" % (model_path, machinecode_path, profile_path))
engine_settings = self._convert_to_engine(profile_path, printer_profile, posX, posY)
@@ -227,16 +234,15 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
return False, "Path to CuraEngine is not configured "
working_dir, _ = os.path.split(executable)
args = ['"%s"' % executable, '-v', '-p']
args = [executable, '-v', '-p']
for k, v in engine_settings.items():
args += ["-s", '"%s=%s"' % (k, str(v))]
args += ['-o', '"%s"' % machinecode_path, '"%s"' % model_path]
args += ["-s", "%s=%s" % (k, str(v))]
args += ["-o", machinecode_path, model_path]
self._logger.info(u"Running %r in %s" % (" ".join(args), working_dir))
import sarge
command = " ".join(args)
self._logger.info("Running %r in %s" % (command, working_dir))
p = sarge.run(command, cwd=working_dir, async=True, stdout=sarge.Capture(), stderr=sarge.Capture())
p = sarge.run(args, cwd=working_dir, async=True, stdout=sarge.Capture(), stderr=sarge.Capture())
p.wait_events()
self._slicing_commands[machinecode_path] = p.commands[0]
@@ -254,6 +260,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
p.commands[0].poll()
continue
line = octoprint.util.to_unicode(line, errors="replace")
self._cura_logger.debug(line.strip())
if on_progress is not None:
@@ -282,14 +289,14 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
#
# with <step_factor> being 0 for "inset", 1 for "skin" and 2 for "export".
if line.startswith("Layer count:") and layer_count is None:
if line.startswith(u"Layer count:") and layer_count is None:
try:
layer_count = float(line[len("Layer count:"):].strip())
layer_count = float(line[len(u"Layer count:"):].strip())
except:
pass
elif line.startswith("Progress:"):
split_line = line[len("Progress:"):].strip().split(":")
elif line.startswith(u"Progress:"):
split_line = line[len(u"Progress:"):].strip().split(":")
if len(split_line) == 3:
step, current_layer, _ = split_line
try:
@@ -302,21 +309,21 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
on_progress_kwargs["_progress"] = (step_factor[step] * layer_count + current_layer) / (layer_count * 3)
on_progress(*on_progress_args, **on_progress_kwargs)
elif line.startswith("Print time:"):
elif line.startswith(u"Print time:"):
try:
print_time = int(line[len("Print time:"):].strip())
print_time = int(line[len(u"Print time:"):].strip())
if analysis is None:
analysis = dict()
analysis["estimatedPrintTime"] = print_time
except:
pass
elif line.startswith("Filament:") or line.startswith("Filament2:"):
if line.startswith("Filament:"):
filament_str = line[len("Filament:"):].strip()
elif line.startswith(u"Filament:") or line.startswith(u"Filament2:"):
if line.startswith(u"Filament:"):
filament_str = line[len(u"Filament:"):].strip()
tool_key = "tool0"
else:
filament_str = line[len("Filament2:"):].strip()
filament_str = line[len(u"Filament2:"):].strip()
tool_key = "tool1"
try:
@@ -339,20 +346,20 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
with self._job_mutex:
if machinecode_path in self._cancelled_jobs:
self._cura_logger.info("### Cancelled")
self._cura_logger.info(u"### Cancelled")
raise octoprint.slicing.SlicingCancelled()
self._cura_logger.info("### Finished, returncode %d" % p.returncode)
self._cura_logger.info(u"### Finished, returncode %d" % p.returncode)
if p.returncode == 0:
return True, dict(analysis=analysis)
else:
self._logger.warn("Could not slice via Cura, got return code %r" % p.returncode)
self._logger.warn(u"Could not slice via Cura, got return code %r" % p.returncode)
return False, "Got returncode %r" % p.returncode
except octoprint.slicing.SlicingCancelled as e:
raise e
except:
self._logger.exception("Could not slice via Cura, got an unknown error")
self._logger.exception(u"Could not slice via Cura, got an unknown error")
return False, "Unknown error, please consult the log file"
finally:
@@ -371,7 +378,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
command = self._slicing_commands[machinecode_path]
if command is not None:
command.terminate()
self._logger.info("Cancelled slicing of %s" % machinecode_path)
self._logger.info(u"Cancelled slicing of %s" % machinecode_path)
def _load_profile(self, path):
import yaml
@@ -385,7 +392,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
def _save_profile(self, path, profile, allow_overwrite=True):
import yaml
with open(path, "wb") as f:
with octoprint.util.atomic_write(path, "wb") as f:
yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True)
def _convert_to_engine(self, profile_path, printer_profile, posX, posY):
@@ -405,9 +412,9 @@ def _sanitize_name(name):
sanitized_name = sanitized_name.replace(" ", "_")
return sanitized_name.lower()
__plugin_name__ = "CuraEngine"
__plugin_name__ = "CuraEngine (<= 15.04)"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura"
__plugin_description__ = "Adds support for slicing via CuraEngine from within OctoPrint"
__plugin_description__ = "Adds support for slicing via CuraEngine versions up to and including version 15.04 from within OctoPrint"
__plugin_license__ = "AGPLv3"
__plugin_implementation__ = CuraPlugin()
@@ -1,5 +1,12 @@
<h4>{{ _('General') }}</h4>
<p>{% trans %}
Specify the path to the CuraEngine binary. Note that only
<strong>versions up to and including 15.04</strong> are supported.
CuraEngine version 15.06 or newer is <strong>not</strong>
compatible with this plugin.
{% endtrans %}</p>
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="settings-cura-path">{{ _('Path to CuraEngine') }}</label>
@@ -10,7 +17,7 @@
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.plugins.cura.debug_logging"> {{ _('Log the output of CuraEngine to plugin_cura_engine.log') }}
<input type="checkbox" data-bind="checked: settings.plugins.cura.debug_logging"> {{ _('Log the output of CuraEngine to <code>plugin_cura_engine.log</code>') }}
</label>
</div>
</div>
@@ -53,6 +60,10 @@
<button class="btn pull-right" data-bind="click: function() { $root.showImportProfileDialog() }">{{ _('Import Profile...') }}</button>
<div style="clear: both">
<small>{% trans %}For more information on configuration and usage please <a href="{{ plugin_cura_homepage }}" target="_blank">see the Plugin's homepage</a>.{% endtrans %}</small>
</div>
<div id="settings_plugin_cura_import" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
@@ -98,6 +109,13 @@
</div>
</div>
</form>
<small>{% trans %}
You can import your existing profile <code>.ini</code> files from Cura (version up to and
including 15.04) here. Please be aware that neither the <code>.json</code> profile format
from Cura versions starting with 15.06 is supported, nor are the custom Cura profile formats
that third party tools like e.g. Repetier create.
{% endtrans %}</small>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
+63 -11
View File
@@ -39,6 +39,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._pending_uninstall = set()
self._pip_caller = None
self._pip_version_dependency_links = pkg_resources.parse_version("1.5")
self._repository_available = False
self._repository_plugins = []
@@ -80,13 +81,24 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
return dict(
repository="http://plugins.octoprint.org/plugins.json",
repository_ttl=24*60,
pip=None
pip=None,
pip_args=None,
dependency_links=False,
hidden=[]
)
def on_settings_save(self, data):
old_pip = self._settings.get(["pip"])
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
new_pip = self._settings.get(["pip"])
self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60
self._pip_caller.refresh = True
if old_pip != new_pip:
self._pip_caller.configured = new_pip
try:
self._pip_caller.trigger_refresh()
except:
self._pip_caller
##~~ AssetPlugin
@@ -121,11 +133,17 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
upload_path = flask.request.values[input_upload_path]
upload_name = flask.request.values[input_upload_name]
exts = filter(lambda x: upload_name.lower().endswith(x), (".zip", ".tar.gz", ".tgz", ".tar"))
if not len(exts):
return flask.make_response("File doesn't have a valid extension for a plugin archive", 400)
ext = exts[0]
import tempfile
import shutil
import os
archive = tempfile.NamedTemporaryFile(delete=False, suffix="-{upload_name}".format(**locals()))
archive = tempfile.NamedTemporaryFile(delete=False, suffix="{ext}".format(**locals()))
try:
archive.close()
shutil.copy(upload_path, archive.name)
@@ -160,7 +178,20 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
if "refresh_repository" in request.values and request.values["refresh_repository"] in valid_boolean_trues:
self._repository_available = self._refresh_repository()
return jsonify(plugins=result, repository=dict(available=self._repository_available, plugins=self._repository_plugins), os=self._get_os(), octoprint=self._get_octoprint_version())
return jsonify(plugins=result,
repository=dict(
available=self._repository_available,
plugins=self._repository_plugins
),
os=self._get_os(),
octoprint=self._get_octoprint_version(),
pip=dict(
available=self._pip_caller.available,
command=self._pip_caller.command,
version=self._pip_caller.version_string,
use_sudo=self._pip_caller.use_sudo,
additional_args=self._settings.get(["pip_args"])
))
def on_api_command(self, command, data):
if not admin_permission.can():
@@ -175,6 +206,7 @@ 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,
reinstall=plugin_name)
elif command == "uninstall":
@@ -193,14 +225,17 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
plugin = self._plugin_manager.plugins[plugin_name]
return self.command_toggle(plugin, command)
def command_install(self, url=None, path=None, force=False, reinstall=None):
def command_install(self, url=None, path=None, force=False, reinstall=None, dependency_links=False):
if url is not None:
pip_args = ["install", sarge.shell_quote(url)]
elif path is not None:
pip_args = ["install", path]
pip_args = ["install", sarge.shell_quote(path)]
else:
raise ValueError("Either url or path must be provided")
if dependency_links or self._settings.get_boolean(["dependency_links"]):
pip_args.append("--process-dependency-links")
all_plugins_before = self._plugin_manager.find_plugins()
success_string = "Successfully installed"
@@ -409,16 +444,29 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
def _call_pip(self, args):
if self._pip_caller is None or not self._pip_caller.available:
raise RuntimeError(u"No pip available, can't operate".format(**locals()))
if "--process-dependency-links" in args:
self._log_message(u"Installation needs to process external dependencies, that might make it take a bit longer than usual depending on the pip version")
if self._pip_caller < self._pip_version_dependency_links:
args.remove("--process-dependency-links")
additional_args = self._settings.get(["pip_args"])
if additional_args:
args.append(additional_args)
return self._pip_caller.execute(*args)
def _log_message(self, *lines):
self._log(lines, prefix=u"*", stream="message")
def _log_call(self, *lines):
self._log(lines, prefix=" ", stream="call")
self._log(lines, prefix=u" ", stream="call")
def _log_stdout(self, *lines):
self._log(lines, prefix=">", stream="stdout")
self._log(lines, prefix=u">", stream="stdout")
def _log_stderr(self, *lines):
self._log(lines, prefix="!", stream="stderr")
self._log(lines, prefix=u"!", stream="stderr")
def _log(self, lines, prefix=None, stream=None, strip=True):
if strip:
@@ -488,7 +536,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
try:
import json
with open(self._repository_cache_path, "w+b") as f:
with octoprint.util.atomic_write(self._repository_cache_path, "wb") as f:
json.dump(repo_data, f)
except Exception as e:
self._logger.exception("Error while saving repository data to {}: {}".format(self._repository_cache_path, str(e)))
@@ -509,6 +557,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
def map_repository_entry(entry):
result = dict(entry)
if not "follow_dependency_links" in result:
result["follow_dependency_links"] = False
result["is_compatible"] = dict(
octoprint=True,
os=True
@@ -578,7 +629,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
pending_enable=(not plugin.enabled and plugin.key in self._pending_enable),
pending_disable=(plugin.enabled and plugin.key in self._pending_disable),
pending_install=(plugin.key in self._pending_install),
pending_uninstall=(plugin.key in self._pending_uninstall)
pending_uninstall=(plugin.key in self._pending_uninstall),
origin=plugin.origin.type
)
__plugin_name__ = "Plugin Manager"
@@ -6,6 +6,13 @@ $(function() {
self.settingsViewModel = parameters[1];
self.printerState = parameters[2];
self.config_repositoryUrl = ko.observable();
self.config_repositoryTtl = ko.observable();
self.config_pipCommand = ko.observable();
self.config_pipAdditionalArgs = ko.observable();
self.configurationDialog = $("#settings_plugin_pluginmanager_configurationdialog");
self.plugins = new ItemListHelper(
"plugin.pluginmanager.installedplugins",
{
@@ -70,6 +77,14 @@ $(function() {
self.loglines = ko.observableArray([]);
self.installedPlugins = ko.observableArray([]);
self.followDependencyLinks = ko.observable(false);
self.pipAvailable = ko.observable(false);
self.pipCommand = ko.observable();
self.pipVersion = ko.observable();
self.pipUseSudo = ko.observable();
self.pipAdditionalArgs = ko.observable();
self.working = ko.observable(false);
self.workingTitle = ko.observable();
self.workingDialog = undefined;
@@ -84,11 +99,15 @@ $(function() {
};
self.enableUninstall = function(data) {
return self.enableManagement() && !data.bundled && data.key != 'pluginmanager' && !data.pending_uninstall;
return self.enableManagement()
&& (data.origin != "entry_point" || self.pipAvailable())
&& !data.bundled
&& data.key != 'pluginmanager'
&& !data.pending_uninstall;
};
self.enableRepoInstall = function(data) {
return self.enableManagement() && self.isCompatible(data);
return self.enableManagement() && self.pipAvailable() && self.isCompatible(data);
};
self.invalidUrl = ko.computed(function() {
@@ -98,7 +117,7 @@ $(function() {
self.enableUrlInstall = ko.computed(function() {
var url = self.installUrl();
return self.enableManagement() && url !== undefined && url.trim() != "" && !self.invalidUrl();
return self.enableManagement() && self.pipAvailable() && url !== undefined && url.trim() != "" && !self.invalidUrl();
});
self.invalidArchive = ko.computed(function() {
@@ -108,7 +127,7 @@ $(function() {
self.enableArchiveInstall = ko.computed(function() {
var name = self.uploadFilename();
return self.enableManagement() && name !== undefined && name.trim() != "" && !self.invalidArchive();
return self.enableManagement() && self.pipAvailable() && name !== undefined && name.trim() != "" && !self.invalidArchive();
});
self.uploadElement.fileupload({
@@ -125,6 +144,9 @@ $(function() {
self.uploadButton.unbind("click");
self.uploadButton.bind("click", function() {
self._markWorking(gettext("Installing plugin..."), gettext("Installing plugin from uploaded archive..."));
data.formData = {
dependency_links: self.followDependencyLinks()
};
data.submit();
return false;
});
@@ -147,24 +169,23 @@ $(function() {
}
});
self.performRepositorySearch = function(e) {
if (e !== undefined) {
e.preventDefault();
}
self.performRepositorySearch = function() {
var query = self.repositorySearchQuery();
if (query !== undefined && query.trim() != "") {
query = query.toLocaleLowerCase();
self.repositoryplugins.changeSearchFunction(function(entry) {
return entry && (entry["title"].toLocaleLowerCase().indexOf(query) > -1 || entry["description"].toLocaleLowerCase().indexOf(query) > -1);
});
} else {
self.repositoryplugins.resetSearch();
}
return false;
};
self.fromResponse = function(data) {
self._fromPluginsResponse(data.plugins);
self._fromRepositoryResponse(data.repository)
self._fromRepositoryResponse(data.repository);
self._fromPipResponse(data.pip);
};
self._fromPluginsResponse = function(data) {
@@ -185,6 +206,21 @@ $(function() {
}
};
self._fromPipResponse = function(data) {
self.pipAvailable(data.available);
if (data.available) {
self.pipCommand(data.command);
self.pipVersion(data.version);
self.pipUseSudo(data.use_sudo);
self.pipAdditionalArgs(data.additional_args);
} else {
self.pipCommand(undefined);
self.pipVersion(undefined);
self.pipUseSudo(undefined);
self.pipAdditionalArgs(undefined);
}
};
self.requestData = function(includeRepo) {
if (!self.loginState.isAdmin()) {
return;
@@ -242,13 +278,13 @@ $(function() {
}
if (self.installed(data)) {
self.installPlugin(data.archive, data.title, data.id);
self.installPlugin(data.archive, data.title, data.id, data.follow_dependency_links || self.followDependencyLinks());
} else {
self.installPlugin(data.archive, data.title, undefined);
self.installPlugin(data.archive, data.title, undefined, data.follow_dependency_links || self.followDependencyLinks());
}
};
self.installPlugin = function(url, name, reinstall) {
self.installPlugin = function(url, name, reinstall, followDependencyLinks) {
if (!self.loginState.isAdmin()) {
return;
}
@@ -262,6 +298,10 @@ $(function() {
}
if (!url) return;
if (followDependencyLinks === undefined) {
followDependencyLinks = self.followDependencyLinks();
}
var workTitle, workText;
if (!reinstall) {
workTitle = gettext("Installing plugin...");
@@ -277,7 +317,7 @@ $(function() {
self._markWorking(workTitle, workText);
var command = "install";
var payload = {url: url};
var payload = {url: url, dependency_links: followDependencyLinks};
if (reinstall) {
payload["plugin"] = reinstall;
payload["force"] = true;
@@ -336,6 +376,58 @@ $(function() {
self.requestData(true);
};
self.showPluginSettings = function() {
self._copyConfig();
self.configurationDialog.modal();
};
self.savePluginSettings = function() {
var pipCommand = self.config_pipCommand();
if (pipCommand != undefined && pipCommand.trim() == "") {
pipCommand = null;
}
var repository = self.config_repositoryUrl();
if (repository != undefined && repository.trim() == "") {
repository = null;
}
var repositoryTtl;
try {
repositoryTtl = parseInt(self.config_repositoryTtl());
} catch (ex) {
repositoryTtl = null;
}
var pipArgs = self.config_pipAdditionalArgs();
if (pipArgs != undefined && pipArgs.trim() == "") {
pipArgs = null;
}
var data = {
plugins: {
pluginmanager: {
repository: repository,
repository_ttl: repositoryTtl,
pip: pipCommand,
pip_args: pipArgs
}
}
};
self.settingsViewModel.saveData(data, function() {
self.configurationDialog.modal("hide");
self._copyConfig();
self.refreshRepository();
});
};
self._copyConfig = function() {
self.config_repositoryUrl(self.settingsViewModel.settings.plugins.pluginmanager.repository());
self.config_repositoryTtl(self.settingsViewModel.settings.plugins.pluginmanager.repository_ttl());
self.config_pipCommand(self.settingsViewModel.settings.plugins.pluginmanager.pip());
self.config_pipAdditionalArgs(self.settingsViewModel.settings.plugins.pluginmanager.pip_args());
};
self.installed = function(data) {
return _.includes(self.installedPlugins(), data.id);
};
@@ -4,7 +4,31 @@
</div>
{% endmacro %}
{% macro pluginmanager_nopip() %}
<div class="alert" data-bind="visible: !pipAvailable()">{% trans %}
The <code>pip</code> command could not be found.
Please configure it manually. No installation and uninstallation of plugin
packages is possible while <code>pip</code> is unavailable.
{% endtrans %}</div>
{% endmacro %}
{% macro pluginmanager_sudopip() %}
<div class="alert alert-error" data-bind="visible: pipUseSudo()">{% trans %}
The <code>pip</code> command is configured to use <code>sudo</code>. This
is <strong>not</strong> recommended due to security reasons. It is <strong>strongly</strong>
suggested you install OctoPrint under a
<a href="https://github.com/foosel/OctoPrint/#installation">user-owned virtual environment</a>
so that the use of <code>sudo</code> is not needed for plugin management.
{% endtrans %}</div>
{% endmacro %}
{{ pluginmanager_printing() }}
{{ pluginmanager_nopip() }}
{{ pluginmanager_sudopip() }}
<div class="pull-right">
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="icon-wrench"></i></button>
</div>
<h3>{{ _('Installed Plugins') }}</h3>
@@ -47,6 +71,10 @@
<button class="btn btn-block" data-bind="click: $root.showRepository">{{ _('Get More...') }}</button>
<p class="muted" data-bind="visible: pipAvailable()">
<small>Using pip at "<span data-bind="text: pipCommand"></span>" (Version <span data-bind="text: pipVersion"></span><span data-bind="visible: pipAdditionalArgs">, additional arguments: <span data-bind="text: pipAdditionalArgs"></span></span>)</small>
</p>
<div id="settings_plugin_pluginmanager_workingdialog" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
@@ -67,6 +95,8 @@
</div>
<div class="modal-body">
{{ pluginmanager_printing() }}
{{ pluginmanager_nopip() }}
{{ pluginmanager_sudopip() }}
<h4 style="position: relative">
{{ _('... from the <a href="%(url)s" target="_blank">Plugin Repository</a>', url='http://plugins.octoprint.org') }}
<a class="dropdown-toggle pull-right" data-toggle="dropdown" href="#">
@@ -147,8 +177,67 @@
</div>
<span class="help-block" data-bind="visible: invalidArchive">{{ _('This does not look like a valid plugin archive. Valid plugin archives should be either zip files or tarballs and have the extension ".zip", ".tar.gz", ".tgz" or ".tar"') }}</span>
</form>
<div>
<div><small><a href="#" class="muted" onclick="$(this).children().toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="icon-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div class="hide">
<form class="form-horizontal">
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: followDependencyLinks"> {{ _('Use <code>--process-dependency-links</code> with <code>pip install</code>') }}
</label>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</button>
</div>
</div>
<div id="settings_plugin_pluginmanager_configurationdialog" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>{{ _('Plugin Configuration') }}</h3>
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="control-group" title="{{ _('pip command to use for managing plugins. You might have to configure this if auto detection fails.') }}">
<label class="control-label">{{ _('pip command') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: config_pipCommand" placeholder="{{ _('Autodetect') }}">
<span class="help-inline">{{ _('<strong>Only</strong> set this if OctoPrint cannot autodetect the path to <code>pip</code> to use for managing plugins.') }}</span>
</div>
</div>
<div class="control-group" title="{{ _('Additional arguments for pip command. You should normally not have to change this.') }}">
<label class="control-label">{{ _('Additional pip arguments') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: config_pipAdditionalArgs">
</div>
</div>
<div class="control-group" title="{{ _('URL of the Plugin Repository to use. You should normally not have to change this.') }}">
<label class="control-label">{{ _('Repository URL') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: config_repositoryUrl">
</div>
</div>
<div class="control-group" title="{{ _('How long to cache repository data, in minutes. You should normally not have to change this.') }}">
<label class="control-label">{{ _('Repository cache TTL') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" class="input-mini" data-bind="value: config_repositoryTtl">
<span class="add-on">min</span>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</button>
<button class="btn btn-primary" data-bind="click: savePluginSettings" aria-hidden="true">{{ _('Save') }}</button>
</div>
</div>
+224 -59
View File
@@ -12,6 +12,7 @@ import flask
import os
import threading
import time
import hashlib
from . import version_checks, updaters, exceptions, util
@@ -58,6 +59,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._refresh_configured_checks = False
self._configured_checks = self._settings.get(["checks"], merged=True)
update_check_hooks = self._plugin_manager.get_hooks("octoprint.plugin.softwareupdate.check_config")
check_providers = self._settings.get(["check_providers"], merged=True)
for name, hook in update_check_hooks.items():
try:
hook_checks = hook()
@@ -65,9 +67,23 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._logger.exception("Error while retrieving update information from plugin {name}".format(**locals()))
else:
for key, data in hook_checks.items():
check_providers[key] = name
if key in self._configured_checks:
data = dict_merge(data, self._configured_checks[key])
self._configured_checks[key] = data
self._settings.set(["check_providers"], check_providers)
self._settings.save()
# we only want to process checks that came from plugins for
# which the plugins are still installed and enabled
config_checks = self._settings.get(["checks"])
plugin_and_not_enabled = lambda k: k in check_providers and \
not check_providers[k] in self._plugin_manager.enabled_plugins
obsolete_plugin_checks = filter(plugin_and_not_enabled,
config_checks.keys())
for key in obsolete_plugin_checks:
self._logger.debug("Check for key {} was provided by plugin {} that's no longer available, ignoring it".format(key, check_providers[key]))
del self._configured_checks[key]
return self._configured_checks
@@ -82,29 +98,42 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
except:
self._logger.exception("Error while loading version cache from disk")
else:
self._version_cache = data
self._version_cache_dirty = False
self._logger.info("Loaded version cache from disk")
try:
if not isinstance(data, dict):
self._logger.info("Version cache was created in a different format, not using it")
return
if "__version" in data:
data_version = data["__version"]
else:
self._logger.info("Can't determine version of OctoPrint version cache was created for, not using it")
return
from octoprint._version import get_versions
octoprint_version = get_versions()["version"]
if data_version != octoprint_version:
self._logger.info("Version cache was created for another version of OctoPrint, not using it")
return
self._version_cache = data
self._version_cache_dirty = False
self._logger.info("Loaded version cache from disk")
except:
self._logger.exception("Error parsing in version cache data")
def _save_version_cache(self):
import tempfile
import yaml
import shutil
from octoprint.util import atomic_write
from octoprint._version import get_versions
file_obj = tempfile.NamedTemporaryFile(delete=False)
try:
octoprint_version = get_versions()["version"]
self._version_cache["__version"] = octoprint_version
with atomic_write(self._version_cache_path) as file_obj:
yaml.safe_dump(self._version_cache, stream=file_obj, default_flow_style=False, indent=" ", allow_unicode=True)
file_obj.close()
shutil.move(file_obj.name, self._version_cache_path)
self._version_cache_dirty = False
self._logger.info("Saved version cache to disk")
finally:
try:
if os.path.exists(file_obj.name):
os.remove(file_obj.name)
except Exception as e:
self._logger.warn("Could not delete file {}: {}".format(file_obj.name, str(e)))
self._version_cache_dirty = False
self._logger.info("Saved version cache to disk")
#~~ SettingsPlugin API
@@ -119,39 +148,118 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
"restart": "octoprint"
},
},
"octoprint_restart_command": None,
"environment_restart_command": None,
"pip_command": None,
"check_providers": {},
"cache_ttl": 24 * 60,
}
def on_settings_load(self):
data = dict(octoprint.plugin.SettingsPlugin.on_settings_load(self))
if "checks" in data:
del data["checks"]
checks = self._get_configured_checks()
if "octoprint" in checks:
if "checkout_folder" in checks["octoprint"]:
data["octoprint_checkout_folder"] = checks["octoprint"]["checkout_folder"]
elif "update_folder" in checks["octoprint"]:
data["octoprint_checkout_folder"] = checks["octoprint"]["update_folder"]
else:
data["octoprint_checkout_folder"] = None
data["octoprint_type"] = checks["octoprint"].get("type", None)
else:
data["octoprint_checkout_folder"] = None
data["octoprint_type"] = None
return data
def on_settings_save(self, data):
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
for key in self.get_settings_defaults():
if key == "checks" or key == "cache_ttl" or key == "octoprint_checkout_folder" or key == "octoprint_type":
continue
if key in data:
self._settings.set([key], data[key])
if "cache_ttl" in data:
self._settings.set_int(["cache_ttl"], data["cache_ttl"])
self._version_cache_ttl = self._settings.get_int(["cache_ttl"]) * 60
checks = self._get_configured_checks()
if "octoprint" in checks:
check = checks["octoprint"]
update_type = check.get("type", None)
checkout_folder = check.get("checkout_folder", None)
update_folder = check.get("update_folder", None)
defaults = dict(
plugins=dict(softwareupdate=dict(
checks=dict(
octoprint=dict(
type=update_type,
checkout_folder=checkout_folder,
update_folder=update_folder
)
)
))
)
if "octoprint_checkout_folder" in data:
self._settings.set(["checks", "octoprint", "checkout_folder"], data["octoprint_checkout_folder"], defaults=defaults, force=True)
if update_folder and data["octoprint_checkout_folder"]:
self._settings.set(["checks", "octoprint", "update_folder"], None, defaults=defaults, force=True)
self._refresh_configured_checks = True
if "octoprint_type" in data and data["octoprint_type"] in ("github_release", "git_commit"):
self._settings.set(["checks", "octoprint", "type"], data["octoprint_type"], defaults=defaults, force=True)
self._refresh_configured_checks = True
def get_settings_version(self):
return 2
return 4
def on_settings_migrate(self, target, current=None):
if current is None:
# there might be some left over data from the time we still persisted everything to settings,
# even the stuff that shouldn't be persisted but always provided by the hook - let's
# clean up
if current is None or current < 4:
# config version 4 and higher moves octoprint_restart_command and
# environment_restart_command to the core configuration
# current plugin commands
configured_octoprint_restart_command = self._settings.get(["octoprint_restart_command"])
configured_environment_restart_command = self._settings.get(["environment_restart_command"])
# current global commands
configured_system_restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"])
configured_server_restart_command = self._settings.global_get(["server", "commands", "serverRestartCommand"])
# only set global commands if they are not yet set
if configured_system_restart_command is None and configured_environment_restart_command is not None:
self._settings.global_set(["server", "commands", "systemRestartCommand"], configured_environment_restart_command)
if configured_server_restart_command is None and configured_octoprint_restart_command is not None:
self._settings.global_set(["server", "commands", "serverRestartCommand"], configured_octoprint_restart_command)
# delete current plugin commands from config
self._settings.set(["environment_restart_command"], None)
self._settings.set(["octoprint_restart_command"], None)
if current is None or current == 2:
# No config version and config version 2 need the same fix, stripping
# accidentally persisted data off the checks
configured_checks = self._settings.get(["checks"], incl_defaults=False)
if configured_checks is None:
configured_checks = dict()
check_keys = configured_checks.keys()
# take care of the octoprint entry
if "octoprint" in configured_checks:
octoprint_check = dict(configured_checks["octoprint"])
if "type" in octoprint_check and not octoprint_check["type"] == "github_commit":
deletables=["current"]
if "type" not in octoprint_check or octoprint_check["type"] != "github_commit":
deletables=["current", "displayName", "displayVersion"]
else:
deletables=[]
octoprint_check = self._clean_settings_check("octoprint", octoprint_check, self.get_settings_defaults()["checks"]["octoprint"], delete=deletables, save=False)
check_keys.remove("octoprint")
# and the hooks
update_check_hooks = self._plugin_manager.get_hooks("octoprint.plugin.softwareupdate.check_config")
@@ -165,14 +273,26 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
if key in configured_checks:
settings_check = dict(configured_checks[key])
merged = dict_merge(data, settings_check)
if "type" in merged and not merged["type"] == "github_commit":
if "type" not in merged or merged["type"] != "github_commit":
deletables = ["current", "displayVersion"]
else:
deletables = []
self._clean_settings_check(key, settings_check, data, delete=deletables, save=False)
check_keys.remove(key)
# and anything that's left over we'll just remove now
for key in check_keys:
dummy_defaults = dict(plugins=dict())
dummy_defaults["plugins"][self._identifier] = dict(checks=dict())
dummy_defaults["plugins"][self._identifier]["checks"][key] = None
self._settings.set(["checks", key], None, defaults=dummy_defaults)
elif current == 1:
# config version 1 had the error that the octoprint check got accidentally
# included in checks["octoprint"], leading to recursion and hence to
# yaml parser errors
configured_checks = self._settings.get(["checks"], incl_defaults=False)
if configured_checks is None:
return
@@ -183,7 +303,6 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
dummy_defaults["plugins"][self._identifier] = dict(checks=dict())
dummy_defaults["plugins"][self._identifier]["checks"]["octoprint"] = None
self._settings.set(["checks", "octoprint"], None, defaults=dummy_defaults)
self._settings.save()
def _clean_settings_check(self, key, data, defaults, delete=None, save=True):
if delete is None:
@@ -270,8 +389,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
##~~ TemplatePlugin API
def get_template_configs(self):
from flask.ext.babel import gettext
return [
dict(type="settings", name="Software Update")
dict(type="settings", name=gettext("Software Update"))
]
#~~ Updater
@@ -297,43 +417,51 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
continue
try:
target_information, target_update_available, target_update_possible = self._get_current_version(target, check, force=force)
populated_check = self._populated_check(target, check)
target_information, target_update_available, target_update_possible = self._get_current_version(target, populated_check, force=force)
if target_information is None:
continue
target_information = dict()
except exceptions.UnknownCheckType:
self._logger.warn("Unknown update check type for %s" % target)
self._logger.warn("Unknown update check type for target {}: {}".format(target, check.get("type", "<n/a>")))
continue
target_information = dict_merge(dict(local=dict(name="unknown", value="unknown"), remote=dict(name="unknown", value="unknown")), target_information)
update_available = update_available or target_update_available
update_possible = update_possible or (target_update_possible and target_update_available)
information[target] = dict(updateAvailable=target_update_available, updatePossible=target_update_possible, information=target_information)
if "displayName" in check:
information[target]["displayName"] = check["displayName"]
from octoprint._version import get_versions
octoprint_version = get_versions()["version"]
local_name = target_information["local"]["name"]
local_value = target_information["local"]["value"]
if "displayVersion" in check:
from octoprint._version import get_versions
octoprint_version = get_versions()["version"]
local_name = target_information["local"]["name"]
local_value = target_information["local"]["value"]
information[target]["displayVersion"] = check["displayVersion"].format(octoprint_version=octoprint_version, local_name=local_name, local_value=local_value)
information[target] = dict(updateAvailable=target_update_available,
updatePossible=target_update_possible,
information=target_information,
displayName=populated_check["displayName"],
displayVersion=populated_check["displayVersion"].format(octoprint_version=octoprint_version, local_name=local_name, local_value=local_value),
check=populated_check)
if self._version_cache_dirty:
self._save_version_cache()
return information, update_available, update_possible
def _get_check_hash(self, check):
hash = hashlib.md5()
hash.update(repr(check))
return hash.hexdigest()
def _get_current_version(self, target, check, force=False):
"""
Determines the current version information for one target based on its check configuration.
"""
current_hash = self._get_check_hash(check)
if target in self._version_cache and not force:
timestamp, information, update_available, update_possible = self._version_cache[target]
if timestamp + self._version_cache_ttl >= time.time() > timestamp:
data = self._version_cache[target]
if data["hash"] == current_hash and data["timestamp"] + self._version_cache_ttl >= time.time() > data["timestamp"]:
# we also check that timestamp < now to not get confused too much by clock changes
return information, update_available, update_possible
return data["information"], data["available"], data["possible"]
information = dict()
update_available = False
@@ -356,7 +484,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
except:
update_possible = False
self._version_cache[target] = (time.time(), information, update_available, update_possible)
self._version_cache[target] = dict(timestamp=time.time(),
hash=current_hash,
information=information,
available=update_available,
possible=update_possible)
self._version_cache_dirty = True
return information, update_available, update_possible
@@ -371,19 +503,28 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
"""
checks = self._get_configured_checks()
populated_checks = dict()
for target, check in checks.items():
try:
populated_checks[target] = self._populated_check(target, check)
except exceptions.UnknownCheckType:
self._logger.debug("Ignoring unknown check type for target {}".format(target))
except:
self._logger.exception("Error while populating check prior to update for target {}".format(target))
if check_targets is None:
check_targets = checks.keys()
to_be_updated = sorted(set(check_targets) & set(checks.keys()))
check_targets = populated_checks.keys()
to_be_updated = sorted(set(check_targets) & set(populated_checks.keys()))
if "octoprint" in to_be_updated:
to_be_updated.remove("octoprint")
tmp = ["octoprint"] + to_be_updated
to_be_updated = tmp
updater_thread = threading.Thread(target=self._update_worker, args=(checks, to_be_updated, force))
updater_thread = threading.Thread(target=self._update_worker, args=(populated_checks, to_be_updated, force))
updater_thread.daemon = False
updater_thread.start()
return to_be_updated, dict((key, check["displayName"] if "displayName" in check else key) for key, check in checks.items() if key in to_be_updated)
return to_be_updated, dict((key, check["displayName"] if "displayName" in check else key) for key, check in populated_checks.items() if key in to_be_updated)
def _update_worker(self, checks, check_targets, force):
@@ -440,7 +581,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
if restart_type is not None and restart_type in ("octoprint", "environment"):
# one of our updates requires a restart of either type "octoprint" or "environment". Let's see if
# we can actually perform that
restart_command = self._settings.get(["%s_restart_command" % restart_type])
if restart_type == "octoprint":
restart_command = self._settings.global_get(["server", "commands", "serverRestartCommand"])
elif restart_type == "environment":
restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"])
if restart_command is not None:
self._send_client_message("restarting", dict(restart_type=restart_type, results=target_results))
@@ -533,6 +678,33 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._logger.warn("Restart stderr:\n%s" % e.stderr)
raise exceptions.RestartFailed()
def _populated_check(self, target, check):
if not "type" in check:
raise exceptions.UnknownCheckType()
result = dict(check)
if target == "octoprint":
from flask.ext.babel import gettext
result["displayName"] = check.get("displayName", gettext("OctoPrint"))
result["displayVersion"] = check.get("displayVersion", "{octoprint_version}")
from octoprint._version import get_versions
versions = get_versions()
if check["type"] == "github_commit":
result["current"] = versions.get("full-revisionid", versions.get("full", "unknown"))
else:
result["current"] = versions["version"]
else:
result["displayName"] = check.get("displayName", target)
result["displayVersion"] = check.get("displayVersion", check.get("current", "unknown"))
if check["type"] in ("github_commit"):
result["current"] = check.get("current", None)
else:
result["current"] = check.get("current", check.get("displayVersion", None))
return result
def _get_version_checker(self, target, check):
"""
Retrieves the version checker to use for given target and check configuration. Will raise an UnknownCheckType
@@ -542,13 +714,6 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
if not "type" in check:
raise exceptions.ConfigurationInvalid("no check type defined")
if target == "octoprint":
from octoprint._version import get_versions
from flask.ext.babel import gettext
check["displayName"] = gettext("OctoPrint")
check["displayVersion"] = "{octoprint_version}"
check["current"] = get_versions()["version"]
check_type = check["type"]
if check_type == "github_release":
return version_checks.github_release
@@ -13,12 +13,22 @@ $(function() {
self.currentlyBeingUpdated = [];
self.config_restartCommand = ko.observable();
self.config_rebootCommand = ko.observable();
self.octoprintUnconfigured = ko.observable();
self.octoprintUnreleased = ko.observable();
self.config_cacheTtl = ko.observable();
self.config_checkoutFolder = ko.observable();
self.config_checkType = ko.observable();
self.configurationDialog = $("#settings_plugin_softwareupdate_configurationdialog");
self.config_availableCheckTypes = [
{"key": "github_release", "name": gettext("Release")},
{"key": "git_commit", "name": gettext("Commit")}
];
self.reloadOverlay = $("#reloadui_overlay");
self.versions = new ItemListHelper(
"plugin.softwareupdate.versions",
{
@@ -78,19 +88,23 @@ $(function() {
var data = {
plugins: {
softwareupdate: {
octoprint_restart_command: self.config_restartCommand(),
environment_restart_command: self.config_rebootCommand(),
cache_ttl: parseInt(self.config_cacheTtl())
cache_ttl: parseInt(self.config_cacheTtl()),
octoprint_checkout_folder: self.config_checkoutFolder(),
octoprint_type: self.config_checkType()
}
}
};
self.settings.saveData(data, function() { self.configurationDialog.modal("hide"); self._copyConfig(); });
self.settings.saveData(data, function() {
self.configurationDialog.modal("hide");
self._copyConfig();
self.performCheck();
});
};
self._copyConfig = function() {
self.config_restartCommand(self.settings.settings.plugins.softwareupdate.octoprint_restart_command());
self.config_rebootCommand(self.settings.settings.plugins.softwareupdate.environment_restart_command());
self.config_cacheTtl(self.settings.settings.plugins.softwareupdate.cache_ttl());
self.config_checkoutFolder(self.settings.settings.plugins.softwareupdate.octoprint_checkout_folder());
self.config_checkType(self.settings.settings.plugins.softwareupdate.octoprint_type());
};
self.fromCheckResponse = function(data, ignoreSeen, showIfNothingNew) {
@@ -109,6 +123,25 @@ $(function() {
});
self.versions.updateItems(versions);
var octoprint = data.information["octoprint"];
if (octoprint && octoprint.hasOwnProperty("check")) {
var check = octoprint.check;
if (BRANCH != "master" && check["type"] == "github_release") {
self.octoprintUnreleased(true);
} else {
self.octoprintUnreleased(false);
}
var checkoutFolder = (check["checkout_folder"] || "").trim();
var updateFolder = (check["update_folder"] || "").trim();
var checkType = check["type"] || "";
if ((checkType == "github_release" || checkType == "git_commit") && checkoutFolder == "" && updateFolder == "") {
self.octoprintUnconfigured(true);
} else {
self.octoprintUnconfigured(false);
}
}
if (data.status == "updateAvailable" || data.status == "updatePossible") {
var text = gettext("There are updates available for the following components:");
@@ -142,7 +175,7 @@ $(function() {
click: function() {
self._markNotificationAsSeen(data.information);
self._showPopup({
text: gettext("You can make this message display again via \"Settings\" > \"SoftwareUpdate\" > \"Check for update now\"")
text: gettext("You can make this message display again via \"Settings\" > \"Software Update\" > \"Check for update now\"")
});
}
}, {
@@ -298,18 +331,10 @@ $(function() {
self.onDataUpdaterReconnect = function() {
if (self.waitingForRestart) {
self.waitingForRestart = false;
var options = {
title: gettext("Restart successful!"),
text: gettext("The server was restarted successfully. The page will now reload automatically."),
type: "success",
hide: false
};
self._showPopup(options);
self.updateInProgress = false;
var delay = 5 + Math.floor(Math.random() * 5) + 1;
setTimeout(function() {location.reload(true);}, delay * 1000);
if (!self.reloadOverlay.is(":visible")) {
self.reloadOverlay.show();
}
}
};
@@ -362,7 +387,7 @@ $(function() {
}
});
self.waitingForRestart = false;
}, 20000);
}, 60000);
break;
}
@@ -1,3 +1,21 @@
<div class="alert" data-bind="visible: octoprintUnconfigured()">{% trans %}
Please configure the <strong>checkout folder</strong> of OctoPrint, otherwise
this plugin won't be able to update it. Click on the <i class="icon-wrench"></i> button
to do this. Also refer to the <a href="https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update" target="_blank">Documentation</a>.
{% endtrans %}</div>
<div class="alert" data-bind="visible: !octoprintUnconfigured() && octoprintUnreleased()">{% trans %}
<p>
<strong>You are running a non-release version of OctoPrint but are tracking OctoPrint
releases.</strong>
</p><p>
You probably want OctoPrint to track the matching development version instead.
If you have a local OctoPrint checkout folder switched to another branch,
<strong>simply switching over to "Commit" tracking</strong> will already
take care of that. Otherwise please take a look at the
<a href="https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update" target="_blank">Documentation</a>.
</p>
{% endtrans %}</div>
<div class="pull-right">
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="icon-wrench"></i></button>
</div>
@@ -11,7 +29,7 @@
<span data-bind="invisible: !updateAvailable"><i class="icon-bell" title="{{ _('Update available') }}"></i></span>
</td>
<td class="settings_plugin_softwareupdate_column_information">
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span><br>
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span> <span data-bind="invisible: updatePossible"><i class="icon-exclamation-sign" title="{{ _('Update not possible, configuration ok?') }}"></i></span><br>
<small class="muted">
{{ _('Installed:') }} <span data-bind="text: information.local.name"></span><br>
{{ _('Available:') }} <span data-bind="text: information.remote.name"></span>
@@ -44,7 +62,7 @@
<div><small><a href="#" class="muted" onclick="$(this).children().toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="icon-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div class="hide">
<button class="btn btn-block" data-bind="click: function() { $root.performCheck(true, true, true); }">{{ _('Force check for update (overrides cache used for update checks)') }}</button>
<button class="btn btn-block btn-danger" data-bind="click: function() { $root.update(true); }">{{ _('Force update now (even if no new versions are available)') }}</button>
<button class="btn btn-block btn-danger" data-bind="visible: CONFIG_DEBUG, click: function() { $root.update(true); }">{{ _('Force update now (even if no new versions are available)') }}</button>
</div>
</div>
@@ -56,15 +74,15 @@
<div class="modal-body">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Restart Command') }}</label>
<label class="control-label">{{ _('OctoPrint checkout folder') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: config_restartCommand">
<input type="text" class="input-block-level" data-bind="value: config_checkoutFolder">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Reboot Command') }}</label>
<label class="control-label">{{ _('OctoPrint version tracking') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: config_rebootCommand">
<select data-bind="value: config_checkType, options: config_availableCheckTypes, optionsText: 'name', optionsValue: 'key'"></select>
</div>
</div>
<div class="control-group">
@@ -7,13 +7,16 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import logging
import pkg_resources
from octoprint.util.pip import PipCaller, UnknownPip
from .. import exceptions
logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pip")
console_logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pip.console")
_pip_callers = dict()
_pip_version_dependency_links = pkg_resources.parse_version("1.5")
def can_perform_update(target, check):
pip_caller = _get_pip_caller(command=check["pip_command"] if "pip_command" in check else None)
@@ -42,30 +45,37 @@ def perform_update(target, check, target_version):
pip_caller = _get_pip_caller(command=pip_command)
if pip_caller is None:
raise RuntimeError("Can't run pip")
raise exceptions.UpdateError("Can't run pip", None)
install_arg = check["pip"].format(target_version=target_version)
logger.debug("Target: %s, executing pip install %s" % (target, install_arg))
logger.debug(u"Target: %s, executing pip install %s" % (target, install_arg))
pip_args = ["install", check["pip"].format(target_version=target_version, target=target_version)]
pip_caller.execute(*pip_args)
if "dependency_links" in check and check["dependency_links"] and pip_caller >= _pip_version_dependency_links:
pip_args += ["--process-dependency-links"]
logger.debug("Target: %s, executing pip install %s --ignore-reinstalled --force-reinstall --no-deps" % (target, install_arg))
returncode, stdout, stderr = pip_caller.execute(*pip_args)
if returncode != 0:
raise exceptions.UpdateError("Error while executing pip install", (stdout, stderr))
logger.debug(u"Target: %s, executing pip install %s --ignore-reinstalled --force-reinstall --no-deps" % (target, install_arg))
pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"]
pip_caller.execute(*pip_args)
returncode, stdout, stderr = pip_caller.execute(*pip_args)
if returncode != 0:
raise exceptions.UpdateError("Error while executing pip install --force-reinstall", (stdout, stderr))
return "ok"
def _log_call(*lines):
_log(lines, prefix=" ")
_log(lines, prefix=u" ")
def _log_stdout(*lines):
_log(lines, prefix=">")
_log(lines, prefix=u">")
def _log_stderr(*lines):
_log(lines, prefix="!")
_log(lines, prefix=u"!")
def _log(lines, prefix=None):
lines = map(lambda x: x.strip(), lines)
@@ -13,7 +13,17 @@ from ..util import execute
def can_perform_update(target, check):
return "update_script" in check and ("checkout_folder" in check or "update_folder" in check)
import os
script_configured = bool("update_script" in check and check["update_script"])
folder = None
if "update_folder" in check:
folder = check["update_folder"]
elif "checkout_folder" in check:
folder = check["checkout_folder"]
folder_configured = bool(folder and os.path.isdir(folder))
return script_configured and folder_configured
def perform_update(target, check, target_version):
@@ -44,35 +44,71 @@ def _get_latest_release(user, repo, include_prerelease=False):
return latest["name"], latest["tag_name"]
def _is_current(release_information, compare_type, custom=None):
def _get_sanitized_version(version_string):
if "-" in version_string:
version_string = version_string[:version_string.find("-")]
return version_string
def _get_comparable_version_pkg_resources(version_string, force_base=True):
import pkg_resources
version = pkg_resources.parse_version(version_string)
if force_base:
if isinstance(version, tuple):
# old setuptools
base_version = []
for part in version:
if part.startswith("*"):
break
base_version.append(part)
version = tuple(base_version)
else:
# new setuptools
version = pkg_resources.parse_version(version.base_version)
return version
def _get_comparable_version_semantic(version_string, force_base=True):
import semantic_version
version = semantic_version.Version.coerce(version_string, partial=False)
if force_base:
version_string = "{}.{}.{}".format(version.major, version.minor, version.patch)
version = semantic_version.Version.coerce(version_string, partial=False)
return version
def _is_current(release_information, compare_type, custom=None, force_base=True):
if release_information["remote"]["value"] is None:
return True
if not compare_type in ("python", "semantic", "unequal", "custom") or compare_type == "custom" and custom is None:
compare_type = "python"
sanitized_local = _get_sanitized_version(release_information["local"]["value"])
sanitized_remote = _get_sanitized_version(release_information["remote"]["value"])
try:
if compare_type == "python":
import pkg_resources
local_version = pkg_resources.parse_version(release_information["local"]["value"])
remote_version = pkg_resources.parse_version(release_information["remote"]["value"])
local_version = _get_comparable_version_pkg_resources(sanitized_local, force_base=force_base)
remote_version = _get_comparable_version_pkg_resources(sanitized_remote, force_base=force_base)
return local_version >= remote_version
elif compare_type == "semantic":
import semantic_version
local_version = semantic_version.Version(release_information["local"]["value"])
remote_version = semantic_version.Version(release_information["remote"]["value"])
local_version = _get_comparable_version_semantic(sanitized_local, force_base=force_base)
remote_version = _get_comparable_version_semantic(sanitized_remote, force_base=force_base)
return local_version >= remote_version
elif compare_type == "custom":
return custom(release_information["local"], release_information["remote"])
return custom(sanitized_local, sanitized_remote)
else:
return release_information["local"]["value"] == release_information["remote"]["value"]
return sanitized_local == sanitized_remote
except:
logger.exception("Could not check if version is current due to an error, assuming it is")
return True
@@ -82,11 +118,13 @@ def get_latest(target, check, custom_compare=None):
if not "user" in check or not "repo" in check:
raise ConfigurationInvalid("github_release update configuration for %s needs user and repo set" % target)
current = None
if "current" in check:
current = check["current"]
current = check.get("current", None)
include_prerelease = check.get("prerelease", False)
force_base = check.get("force_base", True)
remote_name, remote_tag = _get_latest_release(check["user"], check["repo"], include_prerelease=check["prerelease"] == True if "prerelease" in check else False)
remote_name, remote_tag = _get_latest_release(check["user"],
check["repo"],
include_prerelease=include_prerelease)
compare_type = check["release_compare"] if "release_compare" in check else "python"
information =dict(
@@ -96,4 +134,7 @@ def get_latest(target, check, custom_compare=None):
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_tag))
return information, _is_current(information, compare_type, custom=custom_compare)
return information, _is_current(information,
compare_type,
custom=custom_compare,
force_base=force_base)
@@ -65,6 +65,7 @@ class VirtualPrinter():
self._heatupThread = None
self._okBeforeCommandOutput = settings().getBoolean(["devel", "virtualPrinter", "okBeforeCommandOutput"])
self._supportM112 = settings().getBoolean(["devel", "virtualPrinter", "supportM112"])
self._sendWait = settings().getBoolean(["devel", "virtualPrinter", "sendWait"])
self._waitInterval = settings().getFloat(["devel", "virtualPrinter", "waitInterval"])
@@ -83,6 +84,7 @@ class VirtualPrinter():
self._action_hooks = plugin_manager().get_hooks("octoprint.plugin.virtual_printer.custom_action")
self._killed = False
waitThread = threading.Thread(target=self._sendWaitAfterTimeout)
waitThread.start()
@@ -106,7 +108,7 @@ class VirtualPrinter():
def _processIncoming(self):
next_wait_timeout = time.time() + self._waitInterval
while self.incoming is not None:
while self.incoming is not None and not self._killed:
self._simulateTemps()
try:
@@ -266,9 +268,10 @@ class VirtualPrinter():
elif "G92" in data:
self._setPosition(data)
elif data.startswith("G0") or data.startswith("G1") or data.startswith("G2") or data.startswith("G3") \
or data.startswith("G28") or data.startswith("G29") or data.startswith("G30") \
or data.startswith("G31") or data.startswith("G32"):
elif data.startswith("G28"):
self._performMove(data)
elif data.startswith("G0") or data.startswith("G1") or data.startswith("G2") or data.startswith("G3"):
# simulate reprap buffered commands via a Queue with maxsize which internally simulates the moves
self.buffered.put(data)
@@ -291,6 +294,12 @@ class VirtualPrinter():
if len(data.strip()) > 0 and not self._okBeforeCommandOutput:
self._sendOk()
def _kill(self):
if not self._supportM112:
return
self._killed = True
self.outgoing.put("echo:EMERGENCY SHUTDOWN DETECTED. KILLED.")
def _triggerResend(self, expected=None, actual=None):
with self._incoming_lock:
if expected is None:
@@ -303,8 +312,13 @@ class VirtualPrinter():
else:
self.outgoing.put("Error: expected line %d got %d" % (expected, actual))
self.outgoing.put("Resend:%d" % expected)
self.outgoing.put("ok")
def request_resend():
self.outgoing.put("Resend:%d" % expected)
self.outgoing.put("ok")
if settings().getBoolean(["devel", "virtualPrinter", "repetierStyleResends"]):
request_resend()
request_resend()
def _debugTrigger(self, data):
if data == "action_pause":
@@ -516,14 +530,10 @@ class VirtualPrinter():
pass
if duration:
if settings().getBoolean(["devel", "virtualPrinter", "waitOnLongMoves"]):
slept = 0
while duration - slept > self._read_timeout:
time.sleep(self._read_timeout)
self.outgoing.put("wait")
slept += self._read_timeout
else:
time.sleep(duration)
slept = 0
while duration - slept > self._read_timeout and not self._killed:
time.sleep(self._read_timeout)
slept += self._read_timeout
def _setPosition(self, line):
matchX = re.search("X([0-9.]+)", line)
@@ -577,6 +587,9 @@ class VirtualPrinter():
self._selectedSdFilePos = 0
with open(self._selectedSdFile, "r") as f:
for line in iter(f.readline, ""):
if self._killed:
break
# reset position if requested by client
if self._newSdFilePos is not None:
f.seek(self._newSdFilePos)
@@ -606,12 +619,12 @@ class VirtualPrinter():
delay = 1
if heater.startswith("tool"):
toolNum = int(heater[len("tool"):])
while self.temp[toolNum] < self.targetTemp[toolNum] - delta or self.temp[toolNum] > self.targetTemp[toolNum] + delta:
while not self._killed and (self.temp[toolNum] < self.targetTemp[toolNum] - delta or self.temp[toolNum] > self.targetTemp[toolNum] + delta):
self._simulateTemps(delta=delta)
self.outgoing.put("T:%0.2f" % self.temp[toolNum])
time.sleep(delay)
elif heater == "bed":
while self.bedTemp < self.bedTargetTemp - delta or self.bedTemp > self.bedTargetTemp + delta:
while not self._killed and (self.bedTemp < self.bedTargetTemp - delta or self.bedTemp > self.bedTargetTemp + delta):
self._simulateTemps(delta=delta)
self.outgoing.put("B:%0.2f" % self.bedTemp)
time.sleep(delay)
@@ -662,6 +675,11 @@ class VirtualPrinter():
with self._incoming_lock:
if self.incoming is None or self.outgoing is None:
return
if "M112" in data and self._supportM112:
self._kill()
return
try:
self.incoming.put(data, timeout=self._write_timeout)
except Queue.Full:
@@ -685,6 +703,9 @@ class VirtualPrinter():
self.buffered = None
def _sendOk(self):
if self.outgoing is None:
return
if settings().getBoolean(["devel", "virtualPrinter", "okWithLinenumber"]):
self.outgoing.put("ok %d" % self.lastN)
else:
+12 -10
View File
@@ -12,7 +12,7 @@ import re
import logging
from octoprint.settings import settings
from octoprint.util import dict_merge, dict_clean, dict_contains_keys
from octoprint.util import dict_merge, dict_sanitize, dict_contains_keys, is_hidden_path
class SaveError(Exception):
pass
@@ -151,7 +151,7 @@ class PrinterProfileManager(object):
formFactor = BedTypes.RECTANGULAR,
origin = BedOrigin.LOWERLEFT
),
heatedBed = False,
heatedBed = True,
extruder=dict(
count = 1,
offsets = [
@@ -214,7 +214,7 @@ class PrinterProfileManager(object):
identifier = self._sanitize(identifier)
profile["id"] = identifier
profile = dict_clean(profile, self.__class__.default)
profile = dict_sanitize(profile, self.__class__.default)
if identifier == "_default":
default_profile = dict_merge(self._load_default(), profile)
@@ -289,7 +289,7 @@ class PrinterProfileManager(object):
def _load_all_identifiers(self):
results = dict(_default=None)
for entry in os.listdir(self._folder):
if entry.startswith(".") or not entry.endswith(".profile") or entry == "_default.profile":
if is_hidden_path(entry) or not entry.endswith(".profile") or entry == "_default.profile":
continue
path = os.path.join(self._folder, entry)
@@ -329,12 +329,14 @@ class PrinterProfileManager(object):
if os.path.exists(path) and not allow_overwrite:
raise SaveError("Profile %s already exists and not allowed to overwrite" % profile["id"])
from octoprint.util import atomic_write
import yaml
with open(path, "wb") as f:
try:
try:
with atomic_write(path, "wb") as f:
yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True)
except Exception as e:
raise SaveError("Cannot save profile %s: %s" % (profile["id"], str(e)))
except Exception as e:
self._logger.exception("Error while trying to save profile %s" % profile["id"])
raise SaveError("Cannot save profile %s: %s" % (profile["id"], str(e)))
def _remove_from_path(self, path):
try:
@@ -406,7 +408,7 @@ class PrinterProfileManager(object):
for path in (("volume", "width"), ("volume", "depth"), ("volume", "height"), ("extruder", "nozzleDiameter")):
try:
convert_value(profile, path, float)
except:
except Exception as e:
self._logger.warn("Profile has invalid value for path {path!r}: {msg}".format(path=".".join(path), msg=str(e)))
return False
@@ -414,7 +416,7 @@ class PrinterProfileManager(object):
for path in (("axes", "x", "inverted"), ("axes", "y", "inverted"), ("axes", "z", "inverted")):
try:
convert_value(profile, path, bool)
except:
except Exception as e:
self._logger.warn("Profile has invalid value for path {path!r}: {msg}".format(path=".".join(path), msg=str(e)))
return False
+4 -1
View File
@@ -389,6 +389,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._timeEstimationData = TimeEstimationHelper(rolling_window=rolling_window, threshold=threshold, countdown=countdown)
self._lastProgressReport = None
self._setProgressData(0, None, None, None)
self._setCurrentZ(None)
self._comm.startPrint()
@@ -644,6 +645,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if filename is not None:
if sd:
path_in_storage = filename
if path_in_storage.startswith("/"):
path_in_storage = path_in_storage[1:]
path_on_disk = None
else:
path_in_storage = self._fileManager.path_in_storage(FileDestinations.LOCAL, filename)
@@ -679,7 +682,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
# Use a string for mtime because it could be float and the
# javascript needs to exact match
if not sd:
date = int(os.stat(path_on_disk).st_ctime)
date = int(os.stat(path_on_disk).st_mtime)
try:
fileData = self._fileManager.get_metadata(FileDestinations.SDCARD if sd else FileDestinations.LOCAL, path_on_disk)
+116 -27
View File
@@ -14,6 +14,7 @@ from flask.ext.babel import Babel, gettext, ngettext
from flask.ext.assets import Environment, Bundle
from babel import Locale
from watchdog.observers import Observer
from watchdog.observers.polling import PollingObserver
from collections import defaultdict
import os
@@ -80,7 +81,7 @@ def on_identity_loaded(sender, identity):
if user is None:
return
identity.provides.add(UserNeed(user.get_name()))
identity.provides.add(UserNeed(user.get_id()))
if user.is_user():
identity.provides.add(RoleNeed("user"))
if user.is_admin():
@@ -97,9 +98,9 @@ def load_user(id):
if userManager is not None:
if sessionid:
return userManager.findUser(username=id, session=sessionid)
return userManager.findUser(userid=id, session=sessionid)
else:
return userManager.findUser(username=id)
return userManager.findUser(userid=id)
return users.DummyUser()
@@ -212,7 +213,7 @@ class Server():
set_preprocessors=set_preprocessors)
return dict(settings=plugin_settings)
def settings_plugin_config_migration(name, implementation):
def settings_plugin_config_migration_and_cleanup(name, implementation):
if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
return
@@ -220,11 +221,13 @@ class Server():
settings_migrator = implementation.on_settings_migrate
if settings_version is not None and settings_migrator is not None:
stored_version = implementation._settings.get_int(["_config_version"])
stored_version = implementation._settings.get_int([octoprint.plugin.SettingsPlugin.config_version_key])
if stored_version is None or stored_version < settings_version:
settings_migrator(settings_version, stored_version)
implementation._settings.set_int(["_config_version"], settings_version)
implementation._settings.save()
implementation._settings.set_int([octoprint.plugin.SettingsPlugin.config_version_key], settings_version)
implementation.on_settings_cleanup()
implementation._settings.save()
implementation.on_settings_initialized()
@@ -233,9 +236,12 @@ class Server():
settingsPlugins = pluginManager.get_implementations(octoprint.plugin.SettingsPlugin)
for implementation in settingsPlugins:
settings_plugin_config_migration(implementation._identifier, implementation)
try:
settings_plugin_config_migration_and_cleanup(implementation._identifier, implementation)
except:
self._logger.exception("Error while trying to migrate settings for plugin {}, ignoring it".format(implementation._identifier))
pluginManager.implementation_post_inits=[settings_plugin_config_migration]
pluginManager.implementation_post_inits=[settings_plugin_config_migration_and_cleanup]
pluginManager.log_all_plugins()
@@ -326,13 +332,34 @@ class Server():
upload_suffixes = dict(name=s.get(["server", "uploads", "nameSuffix"]), path=s.get(["server", "uploads", "pathSuffix"]))
def mime_type_guesser(path):
from octoprint.filemanager import get_mime_type
return get_mime_type(path)
download_handler_kwargs = dict(
as_attachment=True,
allow_client_caching=False
)
additional_mime_types=dict(mime_type_guesser=mime_type_guesser)
admin_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))
no_hidden_files_validator = dict(path_validation=util.tornado.path_validation_factory(lambda path: not octoprint.util.is_hidden_path(path), status_code=404))
def joined_dict(*dicts):
if not len(dicts):
return dict()
joined = dict()
for d in dicts:
joined.update(d)
return joined
server_routes = self._router.urls + [
# various downloads
(r"/downloads/timelapse/([^/]*\.mpg)", util.tornado.LargeResponseHandler, dict(path=s.getBaseFolder("timelapse"), as_attachment=True)),
(r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, dict(path=s.getBaseFolder("uploads"), as_attachment=True, path_validation=util.tornado.path_validation_factory(lambda path: not os.path.basename(path).startswith("."), status_code=404))),
(r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, dict(path=s.getBaseFolder("logs"), as_attachment=True, access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.admin_validator))),
(r"/downloads/timelapse/([^/]*\.mpg)", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("timelapse")), download_handler_kwargs, no_hidden_files_validator)),
(r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("uploads")), download_handler_kwargs, no_hidden_files_validator, additional_mime_types)),
(r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("logs")), download_handler_kwargs, admin_validator)),
# camera snapshot
(r"/downloads/camera/current", util.tornado.UrlForwardHandler, dict(url=s.get(["webcam", "snapshot"]), as_attachment=True, access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))),
(r"/downloads/camera/current", util.tornado.UrlProxyHandler, dict(url=s.get(["webcam", "snapshot"]), as_attachment=True, access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))),
# generated webassets
(r"/static/webassets/(.*)", util.tornado.LargeResponseHandler, dict(path=os.path.join(s.getBaseFolder("generated"), "webassets")))
]
@@ -399,7 +426,12 @@ class Server():
printer.connect(port=port, baudrate=baudrate, profile=printer_profile["id"] if "id" in printer_profile else "_default")
# start up watchdogs
observer = Observer()
if s.getBoolean(["feature", "pollWatched"]):
# use less performant polling observer if explicitely configured
observer = PollingObserver()
else:
# use os default
observer = Observer()
observer.schedule(util.watchdog.GcodeWatchdogHandler(fileManager, printer), s.getBaseFolder("watched"))
observer.start()
@@ -538,6 +570,9 @@ class Server():
},
"tornado.general": {
"level": "INFO"
},
"octoprint.server.util.flask": {
"level": "WARN"
}
},
"root": {
@@ -614,7 +649,9 @@ class Server():
# configure additional template folders for jinja2
import jinja2
filesystem_loader = jinja2.FileSystemLoader([])
import octoprint.util.jinja
filesystem_loader = octoprint.util.jinja.FilteredFileSystemLoader([],
path_filter=lambda x: not octoprint.util.is_hidden_path(x))
filesystem_loader.searchpath = self._template_searchpaths
jinja_loader = jinja2.ChoiceLoader([
@@ -629,7 +666,10 @@ class Server():
def _register_template_plugins(self):
template_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin)
for plugin in template_plugins:
self._register_additional_template_plugin(plugin)
try:
self._register_additional_template_plugin(plugin)
except:
self._logger.exception("Error while trying to register templates of plugin {}, ignoring it".format(plugin._identifier))
def _register_additional_template_plugin(self, plugin):
folder = plugin.get_template_folder()
@@ -664,14 +704,22 @@ class Server():
def _register_blueprint_plugins(self):
blueprint_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.BlueprintPlugin)
for plugin in blueprint_plugins:
self._register_blueprint_plugin(plugin)
try:
self._register_blueprint_plugin(plugin)
except:
self._logger.exception("Error while registering blueprint of plugin {}, ignoring it".format(plugin._identifier))
continue
def _register_asset_plugins(self):
asset_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.AssetPlugin)
for plugin in asset_plugins:
if isinstance(plugin, octoprint.plugin.BlueprintPlugin):
continue
self._register_asset_plugin(plugin)
try:
self._register_asset_plugin(plugin)
except:
self._logger.exception("Error while registering assets of plugin {}, ignoring it".format(plugin._identifier))
continue
def _register_blueprint_plugin(self, plugin):
name = plugin._identifier
@@ -706,22 +754,65 @@ class Server():
global pluginManager
util.flask.fix_webassets_cache()
util.flask.fix_webassets_filtertool()
base_folder = settings().getBaseFolder("generated")
# clean the folder
if settings().getBoolean(["devel", "webassets", "clean_on_startup"]):
import shutil
import errno
import sys
for entry in ("webassets", ".webassets-cache"):
path = os.path.join(base_folder, entry)
self._logger.debug("Deleting {path}...".format(**locals()))
# delete path if it exists
if os.path.isdir(path):
shutil.rmtree(path, ignore_errors=True)
elif os.path.isfile(path):
try:
os.remove(path)
self._logger.debug("Deleting {path}...".format(**locals()))
shutil.rmtree(path)
except:
self._logger.exception("Exception while trying to delete {entry} from {base_folder}".format(**locals()))
self._logger.exception("Error while trying to delete {path}, leaving it alone".format(**locals()))
continue
# re-create path
self._logger.debug("Creating {path}...".format(**locals()))
error_text = "Error while trying to re-create {path}, that might cause errors with the webassets cache".format(**locals())
try:
os.makedirs(path)
except OSError as e:
if e.errno == errno.EACCES:
# that might be caused by the user still having the folder open somewhere, let's try again after
# waiting a bit
import time
for n in xrange(3):
time.sleep(0.5)
self._logger.debug("Creating {path}: Retry #{retry} after {time}s".format(path=path, retry=n+1, time=(n + 1)*0.5))
try:
os.makedirs(path)
break
except:
if self._logger.isEnabledFor(logging.DEBUG):
self._logger.exception("Ignored error while creating directory {path}".format(**locals()))
pass
else:
# this will only get executed if we never did
# successfully execute makedirs above
self._logger.exception(error_text)
continue
else:
# not an access error, so something we don't understand
# went wrong -> log an error and stop
self._logger.exception(error_text)
continue
except:
# not an OSError, so something we don't understand
# went wrong -> log an error and stop
self._logger.exception(error_text)
continue
self._logger.info("Reset webasset folder {path}...".format(**locals()))
AdjustedEnvironment = type(Environment)(Environment.__name__, (Environment,), dict(
resolver_class=util.flask.PluginAssetResolver
@@ -740,12 +831,10 @@ class Server():
assets.updater = UpdaterType
enable_gcodeviewer = settings().getBoolean(["gcodeViewer", "enabled"])
enable_timelapse = (settings().get(["webcam", "snapshot"]) and settings().get(["webcam", "ffmpeg"]))
preferred_stylesheet = settings().get(["devel", "stylesheet"])
dynamic_assets = util.flask.collect_plugin_assets(
enable_gcodeviewer=enable_gcodeviewer,
enable_timelapse=enable_timelapse,
preferred_stylesheet=preferred_stylesheet
)
@@ -839,9 +928,9 @@ class Server():
js_app_bundle = Bundle(*js_app, output="webassets/packed_app.js", filters="js_delimiter_bundler")
css_libs_bundle = Bundle(*css_libs, output="webassets/packed_libs.css")
css_app_bundle = Bundle(*css_app, output="webassets/packed_app.css")
css_app_bundle = Bundle(*css_app, output="webassets/packed_app.css", filters="cssrewrite")
all_less_bundle = Bundle(*less_app, output="webassets/packed_app.less", filters="less_importrewrite")
all_less_bundle = Bundle(*less_app, output="webassets/packed_app.less", filters="cssrewrite, less_importrewrite")
assets.register("js_libs", js_libs_bundle)
assets.register("js_app", js_app_bundle)
+7 -7
View File
@@ -19,7 +19,7 @@ import octoprint.server
import octoprint.plugin
from octoprint.server import admin_permission, NO_CONTENT
from octoprint.settings import settings as s, valid_boolean_trues
from octoprint.server.util import apiKeyRequestHandler, corsResponseHandler
from octoprint.server.util import noCachingResponseHandler, apiKeyRequestHandler, corsResponseHandler
from octoprint.server.util.flask import restricted_access, get_json_command_from_request, passive_login
@@ -42,6 +42,8 @@ from . import languages as api_languages
VERSION = "0.1"
api.after_request(noCachingResponseHandler)
api.before_request(apiKeyRequestHandler)
api.after_request(corsResponseHandler)
@@ -156,12 +158,10 @@ def performSystemAction():
ignore = availableAction["ignore"] if "ignore" in availableAction else False
logger.info("Performing command: %s" % availableAction["command"])
try:
# Note: we put the command in brackets since sarge (up to the most recently released version) has
# a bug concerning shell=True commands. Once sarge 0.1.4 we can upgrade to that and remove this
# workaround again
#
# See https://bitbucket.org/vinay.sajip/sarge/issue/21/behavior-is-not-like-popen-using-shell
p = sarge.run([availableAction["command"]], stderr=sarge.Capture(), shell=True, async=async)
# we run this with shell=True since we have to trust whatever
# our admin configured as command and since we want to allow
# shell-alike handling here...
p = sarge.run(availableAction["command"], stderr=sarge.Capture(), shell=True, async=async)
if not async:
if not ignore and p.returncode != 0:
returncode = p.returncode
+6 -3
View File
@@ -7,7 +7,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
from flask import request, jsonify, make_response, url_for
import octoprint.util as util
from octoprint.filemanager.destinations import FileDestinations
from octoprint.settings import settings, valid_boolean_trues
from octoprint.server import printer, fileManager, slicingManager, eventManager, NO_CONTENT
@@ -18,6 +17,8 @@ import octoprint.filemanager
import octoprint.filemanager.util
import octoprint.slicing
import psutil
#~~ GCODE file handling
@@ -29,7 +30,8 @@ def readGcodeFiles():
filter = request.values["filter"]
files = _getFileList(FileDestinations.LOCAL, filter=filter)
files.extend(_getFileList(FileDestinations.SDCARD))
return jsonify(files=files, free=util.get_free_bytes(settings().getBaseFolder("uploads")))
usage = psutil.disk_usage(settings().getBaseFolder("uploads"))
return jsonify(files=files, free=usage.free, total=usage.total)
@api.route("/files/<string:origin>", methods=["GET"])
@@ -40,7 +42,8 @@ def readGcodeFilesForOrigin(origin):
files = _getFileList(origin)
if origin == FileDestinations.LOCAL:
return jsonify(files=files, free=util.get_free_bytes(settings().getBaseFolder("uploads")))
usage = psutil.disk_usage(settings().getBaseFolder("uploads"))
return jsonify(files=files, free=usage.free, total=usage.total)
else:
return jsonify(files=files)
+7 -1
View File
@@ -90,11 +90,17 @@ def getInstalledLanguagePacks():
def uploadLanguagePack():
input_name = "file"
input_upload_path = input_name + "." + settings().get(["server", "uploads", "pathSuffix"])
if not input_upload_path in request.values:
input_upload_name = input_name + "." + settings().get(["server", "uploads", "nameSuffix"])
if not input_upload_path in request.values or not input_upload_name in request.values:
return make_response("No file included", 400)
upload_name = request.values[input_upload_name]
upload_path = request.values[input_upload_path]
exts = filter(lambda x: upload_name.lower().endswith(x), (".zip", ".tar.gz", ".tgz", ".tar"))
if not len(exts):
return make_response("File doesn't have a valid extension for a plugin archive", 400)
target_path = settings().getBaseFolder("translations")
if tarfile.is_tarfile(upload_path):
+5 -2
View File
@@ -15,15 +15,18 @@ from octoprint.settings import settings
from octoprint.server import NO_CONTENT, admin_permission
from octoprint.server.util.flask import redirect_to_tornado, restricted_access
from octoprint.server.api import api
from octoprint.util import get_free_bytes
@api.route("/logs", methods=["GET"])
@restricted_access
@admin_permission.require(403)
def getLogFiles():
import psutil
usage = psutil.disk_usage(settings().getBaseFolder("logs"))
files = _getLogFiles()
return jsonify(files=files, free=get_free_bytes(settings().getBaseFolder("logs")))
return jsonify(files=files, free=usage.free, total=usage.total)
@api.route("/logs/<path:filename>", methods=["GET"])
+31 -22
View File
@@ -10,10 +10,9 @@ from werkzeug.exceptions import BadRequest
import re
from octoprint.settings import settings, valid_boolean_trues
from octoprint.server import printer, NO_CONTENT
from octoprint.server import printer, printerProfileManager, NO_CONTENT
from octoprint.server.api import api
from octoprint.server.util.flask import restricted_access, get_json_command_from_request
import octoprint.util as util
from octoprint.printer import UnknownScript
@@ -34,9 +33,13 @@ def printerState():
result = {}
processor = lambda x: x
if not printerProfileManager.get_current_or_default()["heatedBed"]:
processor = _delete_bed
# add temperature information
if not "temperature" in excludes:
result.update({"temperature": _getTemperatureData(lambda x: x)})
result.update({"temperature": _get_temperature_data(processor)})
# add sd information
if not "sd" in excludes and settings().getBoolean(["feature", "sdSupport"]):
@@ -145,14 +148,7 @@ def printerToolState():
if not printer.is_operational():
return make_response("Printer is not operational", 409)
def deleteBed(x):
data = dict(x)
if "bed" in data.keys():
del data["bed"]
return data
return jsonify(_getTemperatureData(deleteBed))
return jsonify(_get_temperature_data(_delete_bed))
##~~ Heated bed
@@ -164,6 +160,9 @@ def printerBedCommand():
if not printer.is_operational():
return make_response("Printer is not operational", 409)
if not printerProfileManager.get_current_or_default()["heatedBed"]:
return make_response("Printer does not have a heated bed", 409)
valid_commands = {
"target": ["target"],
"offset": ["offset"]
@@ -204,15 +203,10 @@ def printerBedState():
if not printer.is_operational():
return make_response("Printer is not operational", 409)
def deleteTools(x):
data = dict(x)
if not printerProfileManager.get_current_or_default()["heatedBed"]:
return make_response("Printer does not have a heated bed", 409)
for k in data.keys():
if k.startswith("tool"):
del data[k]
return data
data = _getTemperatureData(deleteTools)
data = _get_temperature_data(_delete_tools)
if isinstance(data, Response):
return data
else:
@@ -382,7 +376,7 @@ def getCustomControls():
return jsonify(controls=customControls)
def _getTemperatureData(filter):
def _get_temperature_data(preprocessor):
if not printer.is_operational():
return make_response("Printer is not operational", 409)
@@ -399,8 +393,23 @@ def _getTemperatureData(filter):
limit = min(limit, len(history))
tempData.update({
"history": map(lambda x: filter(x), history[-limit:])
"history": map(lambda x: preprocessor(x), history[-limit:])
})
return filter(tempData)
return preprocessor(tempData)
def _delete_tools(x):
return _delete_from_data(x, lambda k: k.startswith("tool"))
def _delete_bed(x):
return _delete_from_data(x, lambda k: k == "bed")
def _delete_from_data(x, key_matcher):
data = dict(x)
for k in data.keys():
if key_matcher(k):
del data[k]
return data
+25 -1
View File
@@ -68,7 +68,9 @@ def getSettings():
"swallowOkAfterResend": s.getBoolean(["feature", "swallowOkAfterResend"]),
"repetierTargetTemp": s.getBoolean(["feature", "repetierTargetTemp"]),
"externalHeatupDetection": s.getBoolean(["feature", "externalHeatupDetection"]),
"keyboardControl": s.getBoolean(["feature", "keyboardControl"])
"keyboardControl": s.getBoolean(["feature", "keyboardControl"]),
"pollWatched": s.getBoolean(["feature", "pollWatched"]),
"ignoreIdenticalResends": s.getBoolean(["feature", "ignoreIdenticalResends"])
},
"serial": {
"port": connectionOptions["portPreference"],
@@ -111,6 +113,17 @@ def getSettings():
"afterPrintResumed": None,
"snippets": dict()
}
},
"server": {
"commands": {
"systemShutdownCommand": s.get(["server", "commands", "systemShutdownCommand"]),
"systemRestartCommand": s.get(["server", "commands", "systemRestartCommand"]),
"serverRestartCommand": s.get(["server", "commands", "serverRestartCommand"])
},
"diskspace": {
"warning": s.getInt(["server", "diskspace", "warning"]),
"critical": s.getInt(["server", "diskspace", "critical"])
}
}
}
@@ -199,6 +212,8 @@ def setSettings():
if "repetierTargetTemp" in data["feature"].keys(): s.setBoolean(["feature", "repetierTargetTemp"], data["feature"]["repetierTargetTemp"])
if "externalHeatupDetection" in data["feature"].keys(): s.setBoolean(["feature", "externalHeatupDetection"], data["feature"]["externalHeatupDetection"])
if "keyboardControl" in data["feature"].keys(): s.setBoolean(["feature", "keyboardControl"], data["feature"]["keyboardControl"])
if "pollWatched" in data["feature"]: s.setBoolean(["feature", "pollWatched"], data["feature"]["pollWatched"])
if "ignoreIdenticalResends" in data["feature"]: s.setBoolean(["feature", "ignoreIdenticalResends"], data["feature"]["ignoreIdenticalResends"])
if "serial" in data.keys():
if "autoconnect" in data["serial"].keys(): s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
@@ -248,6 +263,15 @@ def setSettings():
continue
s.saveScript("gcode", name, script.replace("\r\n", "\n").replace("\r", "\n"))
if "server" in data:
if "commands" in data["server"]:
if "systemShutdownCommand" in data["server"]["commands"].keys(): s.set(["server", "commands", "systemShutdownCommand"], data["server"]["commands"]["systemShutdownCommand"])
if "systemRestartCommand" in data["server"]["commands"].keys(): s.set(["server", "commands", "systemRestartCommand"], data["server"]["commands"]["systemRestartCommand"])
if "serverRestartCommand" in data["server"]["commands"].keys(): s.set(["server", "commands", "serverRestartCommand"], data["server"]["commands"]["serverRestartCommand"])
if "diskspace" in data["server"]:
if "warning" in data["server"]["diskspace"]: s.setInt(["server", "diskspace", "warning"], data["server"]["diskspace"]["warning"])
if "critical" in data["server"]["diskspace"]: s.setInt(["server", "diskspace", "critical"], data["server"]["diskspace"]["critical"])
if "plugins" in data:
for plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin):
plugin_id = plugin._identifier
+5 -5
View File
@@ -29,14 +29,14 @@ def getTimelapseData():
config = {"type": "off"}
if timelapse is not None and isinstance(timelapse, octoprint.timelapse.ZTimelapse):
config["type"] = "zchange"
config["postRoll"] = timelapse.postRoll()
config["fps"] = timelapse.fps()
config["postRoll"] = timelapse.post_roll
config["fps"] = timelapse.fps
elif timelapse is not None and isinstance(timelapse, octoprint.timelapse.TimedTimelapse):
config["type"] = "timed"
config["postRoll"] = timelapse.postRoll()
config["fps"] = timelapse.fps()
config["postRoll"] = timelapse.post_roll
config["fps"] = timelapse.fps
config.update({
"interval": timelapse.interval()
"interval": timelapse.interval
})
files = octoprint.timelapse.getFinishedTimelapses()
+5
View File
@@ -10,10 +10,15 @@ from flask import Blueprint, request, make_response, jsonify
import octoprint.server
import octoprint.plugin
from octoprint.server.util import noCachingResponseHandler, corsResponseHandler
from octoprint.settings import settings as s
apps = Blueprint("apps", __name__)
apps.after_request(noCachingResponseHandler)
apps.after_request(corsResponseHandler)
@apps.route("/auth", methods=["GET"])
def getSessionKey():
unverified_key, valid_until = octoprint.server.appSessionManager.create()
+12
View File
@@ -80,6 +80,18 @@ def corsResponseHandler(resp):
return resp
def noCachingResponseHandler(resp):
"""
``after_request`` handler for blueprints which shall set no caching headers
on their responses.
Sets ``Cache-Control``, ``Pragma`` and ``Expires`` headers accordingly
to prevent all client side caching from taking place.
"""
return flask.add_non_caching_response_headers(resp)
def optionsAllowOrigin(request):
"""
Shortcut for request handling for CORS OPTIONS requests to set CORS headers.
+162 -15
View File
@@ -19,13 +19,14 @@ import uuid
import threading
import logging
import netaddr
import os
from octoprint.settings import settings
import octoprint.server
import octoprint.users
import octoprint.plugin
from werkzeug.contrib.cache import SimpleCache
from werkzeug.contrib.cache import BaseCache
#~~ monkey patching
@@ -122,12 +123,19 @@ def enable_additional_translations(default_locale="en", additional_folders=None)
def fix_webassets_cache():
from webassets import cache
import os
import tempfile
import pickle
import shutil
error_logger = logging.getLogger(__name__ + ".fix_webassets_cache")
def fixed_set(self, key, data):
import os
import tempfile
import pickle
import shutil
if not os.path.exists(self.directory):
error_logger.warn("Cache directory {} doesn't exist, not going "
"to attempt to write cache file".format(self.directory))
md5 = '%s' % cache.make_md5(self.V, key)
filename = os.path.join(self.directory, md5)
fd, temp_filename = tempfile.mkstemp(prefix='.' + md5,
@@ -147,6 +155,11 @@ def fix_webassets_cache():
import warnings
from webassets.cache import make_md5
if not os.path.exists(self.directory):
error_logger.warn("Cache directory {} doesn't exist, not going "
"to attempt to read cache file".format(self.directory))
return None
try:
hash = make_md5(self.V, key)
except IOError as e:
@@ -174,6 +187,37 @@ def fix_webassets_cache():
cache.FilesystemCache.set = fixed_set
cache.FilesystemCache.get = fixed_get
def fix_webassets_filtertool():
from webassets.merge import FilterTool, log, MemoryHunk
error_logger = logging.getLogger(__name__ + ".fix_webassets_filtertool")
def fixed_wrap_cache(self, key, func):
"""Return cache value ``key``, or run ``func``.
"""
if self.cache:
if not self.no_cache_read:
log.debug('Checking cache for key %s', key)
content = self.cache.get(key)
if not content in (False, None):
log.debug('Using cached result for %s', key)
return MemoryHunk(content)
try:
content = func().getvalue()
if self.cache:
try:
log.debug('Storing result in cache with key %s', key,)
self.cache.set(key, content)
except:
error_logger.exception("Got an exception while trying to save file to cache, not caching")
return MemoryHunk(content)
except:
error_logger.exception("Got an exception while trying to apply filter, ignoring file")
return MemoryHunk(u"")
FilterTool._wrap_cache = fixed_wrap_cache
#~~ passive login helper
def passive_login():
@@ -183,8 +227,10 @@ def passive_login():
user = flask.ext.login.current_user
if user is not None and not user.is_anonymous():
flask.g.user = user
flask.ext.principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask.ext.principal.Identity(user.get_id()))
if hasattr(user, "get_session"):
flask.session["usersession.id"] = user.get_session()
flask.g.user = user
return flask.jsonify(user.asDict())
elif settings().getBoolean(["accessControl", "autologinLocal"]) \
and settings().get(["accessControl", "autologinAs"]) is not None \
@@ -208,14 +254,66 @@ def passive_login():
logger = logging.getLogger(__name__)
logger.exception("Could not autologin user %s for networks %r" % (autologinAs, localNetworks))
return ("", 204)
return "", 204
#~~ cache decorator for cacheable views
_cache = SimpleCache()
class LessSimpleCache(BaseCache):
"""
Slightly improved version of :class:`SimpleCache`.
def cached(timeout=5 * 60, key=lambda: "view/%s" % flask.request.path, unless=None, refreshif=None):
Setting ``default_timeout`` or ``timeout`` to ``-1`` will have no timeout be applied at all.
"""
def __init__(self, threshold=500, default_timeout=300):
BaseCache.__init__(self, default_timeout=default_timeout)
self._cache = {}
self.clear = self._cache.clear
self._threshold = threshold
def _prune(self):
if self.over_threshold():
now = time.time()
for idx, (key, (expires, _)) in enumerate(self._cache.items()):
if expires is not None and expires <= now or idx % 3 == 0:
self._cache.pop(key, None)
def get(self, key):
import pickle
now = time.time()
expires, value = self._cache.get(key, (0, None))
if expires is None or expires > now:
return pickle.loads(value)
def set(self, key, value, timeout=None):
import pickle
self._prune()
self._cache[key] = (self.calculate_timeout(timeout=timeout),
pickle.dumps(value, pickle.HIGHEST_PROTOCOL))
def add(self, key, value, timeout=None):
self.set(key, value, timeout=None)
self._cache.setdefault(key, self._cache[key])
def delete(self, key):
self._cache.pop(key, None)
def calculate_timeout(self, timeout=None):
if timeout is None:
timeout = self.default_timeout
if timeout is -1:
return None
return time.time() + timeout
def over_threshold(self):
if self._threshold is None:
return False
return len(self._cache) > self._threshold
_cache = LessSimpleCache()
def cached(timeout=5 * 60, key=lambda: "view:%s" % flask.request.path, unless=None, refreshif=None, unless_response=None):
def decorator(f):
@functools.wraps(f)
def decorated_function(*args, **kwargs):
@@ -241,9 +339,14 @@ def cached(timeout=5 * 60, key=lambda: "view/%s" % flask.request.path, unless=No
return rv
# get value from wrapped function
logger.debug("No cache entry or refreshing cache for {path}, calling wrapped function".format(path=flask.request.path))
logger.debug("No cache entry or refreshing cache for {path} (key: {key}), calling wrapped function".format(path=flask.request.path, key=cache_key))
rv = f(*args, **kwargs)
# do not store if the "unless_response" condition is true
if callable(unless_response) and unless_response(rv):
logger.debug("Not caching result for {path}, bypassed".format(path=flask.request.path))
return rv
# store it in the cache
_cache.set(cache_key, rv, timeout=timeout)
@@ -256,6 +359,31 @@ def cached(timeout=5 * 60, key=lambda: "view/%s" % flask.request.path, unless=No
def cache_check_headers():
return "no-cache" in flask.request.cache_control or "no-cache" in flask.request.pragma
def cache_check_response_headers(response):
if not isinstance(response, flask.Response):
return False
headers = response.headers
if "Cache-Control" in headers and "no-cache" in headers["Cache-Control"]:
return True
if "Pragma" in headers and "no-cache" in headers["Pragma"]:
return True
if "Expires" in headers and headers["Expires"] in ("0", "-1"):
return True
return False
def add_non_caching_response_headers(response):
response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "-1"
return response
#~~ access validators for use with tornado
@@ -454,7 +582,8 @@ def get_remote_address(request):
def get_json_command_from_request(request, valid_commands):
if not "application/json" in request.headers["Content-Type"]:
content_type = request.headers.get("Content-Type", None)
if content_type is None or not "application/json" in content_type:
return None, None, make_response("Expected content-type JSON", 400)
data = request.json
@@ -534,7 +663,9 @@ class SettingsCheckUpdater(webassets.updater.BaseUpdater):
##~~ plugin assets collector
def collect_plugin_assets(enable_gcodeviewer=True, enable_timelapse=True, preferred_stylesheet="css"):
def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
logger = logging.getLogger(__name__ + ".collect_plugin_assets")
supported_stylesheets = ("css", "less")
assets = dict(
js=[],
@@ -555,6 +686,7 @@ def collect_plugin_assets(enable_gcodeviewer=True, enable_timelapse=True, prefer
'js/app/viewmodels/slicing.js',
'js/app/viewmodels/temperature.js',
'js/app/viewmodels/terminal.js',
'js/app/viewmodels/timelapse.js',
'js/app/viewmodels/users.js',
'js/app/viewmodels/log.js',
'js/app/viewmodels/usersettings.js'
@@ -566,8 +698,6 @@ def collect_plugin_assets(enable_gcodeviewer=True, enable_timelapse=True, prefer
'gcodeviewer/js/gCodeReader.js',
'gcodeviewer/js/renderer.js'
]
if enable_timelapse:
assets["js"].append('js/app/viewmodels/timelapse.js')
if preferred_stylesheet == "less":
assets["less"].append('less/octoprint.less')
@@ -577,14 +707,29 @@ def collect_plugin_assets(enable_gcodeviewer=True, enable_timelapse=True, prefer
asset_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.AssetPlugin)
for implementation in asset_plugins:
name = implementation._identifier
all_assets = implementation.get_assets()
try:
all_assets = implementation.get_assets()
basefolder = implementation.get_asset_folder()
except:
logger.exception("Got an error while trying to collect assets from {}, ignoring assets from the plugin".format(name))
continue
def asset_exists(category, asset):
exists = os.path.exists(os.path.join(basefolder, asset))
if not exists:
logger.warn("Plugin {} is referring to non existing {} asset {}".format(name, category, asset))
return exists
if "js" in all_assets:
for asset in all_assets["js"]:
if not asset_exists("js", asset):
continue
assets["js"].append('plugin/{name}/{asset}'.format(**locals()))
if preferred_stylesheet in all_assets:
for asset in all_assets[preferred_stylesheet]:
if not asset_exists(preferred_stylesheet, asset):
continue
assets[preferred_stylesheet].append('plugin/{name}/{asset}'.format(**locals()))
else:
for stylesheet in supported_stylesheets:
@@ -592,6 +737,8 @@ def collect_plugin_assets(enable_gcodeviewer=True, enable_timelapse=True, prefer
continue
for asset in all_assets[stylesheet]:
if not asset_exists(stylesheet, asset):
continue
assets[stylesheet].append('plugin/{name}/{asset}'.format(**locals()))
break
+7 -1
View File
@@ -59,7 +59,13 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.
plugin_hash.update(",".join(ui_plugins))
# connected => update the API key, might be necessary if the client was left open while the server restarted
self._emit("connected", {"apikey": octoprint.server.UI_API_KEY, "version": octoprint.server.VERSION, "display_version": octoprint.server.DISPLAY_VERSION, "plugin_hash": plugin_hash.hexdigest()})
self._emit("connected", {
"apikey": octoprint.server.UI_API_KEY,
"version": octoprint.server.VERSION,
"display_version": octoprint.server.DISPLAY_VERSION,
"branch": octoprint.server.BRANCH,
"plugin_hash": plugin_hash.hexdigest()
})
self._printer.register_callback(self)
self._fileManager.register_slicingprogress_callback(self)
+48 -8
View File
@@ -245,7 +245,7 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
self._on_part_header(self._buffer[delimiter_len+2:end_of_header])
self._buffer = self._buffer[end_of_header + 4:]
if delimiter_loc != -1 and self._buffer[delimiter_len:delimiter_len+2] == "--":
if delimiter_loc != -1 and self._buffer.strip() == delimiter + "--":
# we saw the last boundary and are at the end of our request
if self._current_part:
self._on_part_finish(self._current_part)
@@ -360,13 +360,24 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
for name, part in self._parts.iteritems():
if "filename" in part:
# add form fields for filename, path, size and content_type for all files contained in the request
fields = dict((self._suffixes[key], value) for (key, value) in dict(name=part["filename"], path=part["path"], size=str(os.stat(part["path"]).st_size), content_type=part["content_type"]).iteritems())
if not "path" in part:
continue
parameters = dict(
name=part["filename"],
path=part["path"],
size=str(os.stat(part["path"]).st_size)
)
if "content_type" in part:
parameters["content_type"] = part["content_type"]
fields = dict((self._suffixes[key], value) for (key, value) in parameters.iteritems())
for n, p in fields.iteritems():
key = name + "." + n
self._new_body += b"--%s\r\n" % self._multipart_boundary
self._new_body += b"Content-Disposition: form-data; name=\"%s\"\r\n" % key
self._new_body += b"\r\n"
self._new_body += p + b"\r\n"
self._new_body += b"%s\r\n" % p
elif "data" in part:
self._new_body += b"--%s\r\n" % self._multipart_boundary
value = part["data"]
@@ -757,6 +768,8 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
:class:``~tornado.web.StaticFileHandler`` as the ``default_filename`` keyword parameter). Defaults to ``None``.
as_attachment (bool): Whether to serve requested files with ``Content-Disposition: attachment`` header (``True``)
or not. Defaults to ``False``.
allow_client_caching (bool): Whether to allow the client to cache (by not setting any ``Cache-Control`` or
``Expires`` headers on the response) or not.
access_validation (function): Callback to call in the ``get`` method to validate access to the resource. Will
be called with ``self.request`` as parameter which contains the full tornado request object. Should raise
a ``tornado.web.HTTPError`` if access is not allowed in which case the request will not be further processed.
@@ -765,13 +778,22 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
with the requested path as parameter. Should raise a ``tornado.web.HTTPError`` (e.g. an 404) if the requested
path does not pass validation in which case the request will not be further processed.
Defaults to ``None`` and hence no path validation being performed.
etag_generator (function): Callback to call for generating the value of the ETag response header. Will be
called with the response handler as parameter. May return ``None`` to prevent the ETag response header
from being set. If not provided the last modified time of the file in question will be used as returned
by ``get_content_version``.
"""
def initialize(self, path, default_filename=None, as_attachment=False, access_validation=None, path_validation=None):
def initialize(self, path, default_filename=None, as_attachment=False, allow_client_caching=True,
access_validation=None, path_validation=None, etag_generator=None,
mime_type_guesser=None):
tornado.web.StaticFileHandler.initialize(self, os.path.abspath(path), default_filename)
self._as_attachment = as_attachment
self._allow_client_caching = allow_client_caching
self._access_validation = access_validation
self._path_validation = path_validation
self._etag_generator = etag_generator
self._mime_type_guesser = mime_type_guesser
def get(self, path, include_body=True):
if self._access_validation is not None:
@@ -785,6 +807,24 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
if self._as_attachment:
self.set_header("Content-Disposition", "attachment")
if not self._allow_client_caching:
self.set_header("Cache-Control", "max-age=0, must-revalidate, private")
self.set_header("Expires", "-1")
def compute_etag(self):
if self._etag_generator is not None:
return self._etag_generator(self)
else:
return self.get_content_version(self.absolute_path)
def get_content_type(self):
if self._mime_type_guesser is not None:
type = self._mime_type_guesser(self.absolute_path)
if type is not None:
return type
return tornado.web.StaticFileHandler.get_content_type(self)
@classmethod
def get_content_version(cls, abspath):
import os
@@ -794,7 +834,7 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
##~~ URL Forward Handler for forwarding requests to a preconfigured static URL
class UrlForwardHandler(tornado.web.RequestHandler):
class UrlProxyHandler(tornado.web.RequestHandler):
"""
`tornado.web.RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>`_ that proxies
requests to a preconfigured url and returns the response. Allows delivery of the requested content as attachment
@@ -804,7 +844,7 @@ class UrlForwardHandler(tornado.web.RequestHandler):
for making the request to the configured endpoint and return the body of the client response with the status code
from the client response and the following headers:
* ``Date``, ``Cache-Control``, ``Server``, ``Content-Type`` and ``Location`` will be copied over.
* ``Date``, ``Cache-Control``, ``Expires``, ``ETag``, ``Server``, ``Content-Type`` and ``Location`` will be copied over.
* If ``as_attachment`` is set to True, ``Content-Disposition`` will be set to ``attachment``. If ``basename`` is
set including the attachement's ``filename`` attribute will be set to the base name followed by the extension
guessed based on the MIME type from the ``Content-Type`` header of the response. If no extension can be guessed
@@ -854,7 +894,7 @@ class UrlForwardHandler(tornado.web.RequestHandler):
filename = None
self.set_status(response.code)
for name in ("Date", "Cache-Control", "Server", "Content-Type", "Location"):
for name in ("Date", "Cache-Control", "Server", "Content-Type", "Location", "Expires", "ETag"):
value = response.headers.get(name)
if value:
self.set_header(name, value)
@@ -924,4 +964,4 @@ def path_validation_factory(path_filter, status_code=404):
def f(path):
if not path_filter(path):
raise tornado.web.HTTPError(status_code)
return f
return f
+36 -27
View File
@@ -6,6 +6,7 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
import os
import watchdog.events
import octoprint.filemanager
@@ -14,6 +15,7 @@ import octoprint.util
class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
"""
Takes care of automatically "uploading" files that get added to the watched folder.
"""
@@ -27,35 +29,42 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
self._printer = printer
def _upload(self, path):
import os
file_wrapper = octoprint.filemanager.util.DiskFileWrapper(os.path.basename(path), path)
# determine current job
currentFilename = None
currentOrigin = None
currentJob = self._printer.get_current_job()
if currentJob is not None and "file" in currentJob.keys():
currentJobFile = currentJob["file"]
if "name" in currentJobFile.keys() and "origin" in currentJobFile.keys():
currentFilename = currentJobFile["name"]
currentOrigin = currentJobFile["origin"]
# determine future filename of file to be uploaded, abort if it can't be uploaded
try:
futureFilename = self._file_manager.sanitize_name(octoprint.filemanager.FileDestinations.LOCAL, file_wrapper.filename)
file_wrapper = octoprint.filemanager.util.DiskFileWrapper(os.path.basename(path), path)
# determine current job
currentFilename = None
currentOrigin = None
currentJob = self._printer.get_current_job()
if currentJob is not None and "file" in currentJob.keys():
currentJobFile = currentJob["file"]
if "name" in currentJobFile.keys() and "origin" in currentJobFile.keys():
currentFilename = currentJobFile["name"]
currentOrigin = currentJobFile["origin"]
# determine future filename of file to be uploaded, abort if it can't be uploaded
try:
futureFilename = self._file_manager.sanitize_name(octoprint.filemanager.FileDestinations.LOCAL, file_wrapper.filename)
except:
futureFilename = None
if futureFilename is None or (len(self._file_manager.registered_slicers) == 0 and not octoprint.filemanager.valid_file_type(futureFilename)):
return
# prohibit overwriting currently selected file while it's being printed
if futureFilename == currentFilename and currentOrigin == octoprint.filemanager.FileDestinations.LOCAL and self._printer.is_printing() or self._printer.is_paused():
return
self._file_manager.add_file(octoprint.filemanager.FileDestinations.LOCAL,
file_wrapper.filename,
file_wrapper,
allow_overwrite=True)
if os.path.exists(path):
try:
os.remove(path)
except:
self._logger.exception("Error while trying to clear a file from the watched folder")
except:
futureFilename = None
if futureFilename is None or (len(self._file_manager.registered_slicers) == 0 and not octoprint.filemanager.valid_file_type(futureFilename)):
return
# prohibit overwriting currently selected file while it's being printed
if futureFilename == currentFilename and currentOrigin == octoprint.filemanager.FileDestinations.LOCAL and self._printer.is_printing() or self._printer.is_paused():
return
self._file_manager.add_file(octoprint.filemanager.FileDestinations.LOCAL,
file_wrapper.filename,
file_wrapper,
allow_overwrite=True)
self._logger.exception("There was an error while processing the file {} in the watched folder".format(path))
def on_created(self, event):
self._upload(event.src_path)
+67 -14
View File
@@ -12,16 +12,25 @@ from flask import request, g, url_for, make_response, render_template, send_from
import octoprint.plugin
from octoprint.server import app, userManager, pluginManager, gettext, debug, LOCALES, VERSION, DISPLAY_VERSION, UI_API_KEY
from octoprint.server import app, userManager, pluginManager, gettext, \
debug, LOCALES, VERSION, DISPLAY_VERSION, UI_API_KEY, BRANCH
from octoprint.settings import settings
import re
from . import util
import logging
_logger = logging.getLogger(__name__)
_valid_id_re = re.compile("[a-z_]+")
_valid_div_re = re.compile("[a-zA-Z_-]+")
@app.route("/")
@util.flask.cached(refreshif=lambda: util.flask.cache_check_headers() or "_refresh" in request.values, key=lambda: "view/%s/%s" % (request.path, g.locale))
@util.flask.cached(timeout=-1,
refreshif=lambda: util.flask.cache_check_headers() or "_refresh" in request.values,
key=lambda: "view:{}:{}".format(request.base_url, g.locale),
unless_response=util.flask.cache_check_response_headers)
def index():
#~~ a bunch of settings
@@ -148,6 +157,7 @@ def index():
folders=(gettext("Folders"), dict(template="dialogs/settings/folders.jinja2", _div="settings_folders", custom_bindings=False)),
appearance=(gettext("Appearance"), dict(template="dialogs/settings/appearance.jinja2", _div="settings_appearance", custom_bindings=False)),
logs=(gettext("Logs"), dict(template="dialogs/settings/logs.jinja2", _div="settings_logs")),
server=(gettext("Server"), dict(template="dialogs/settings/server.jinja2", _div="settings_server", custom_bindings=False)),
)
if enable_accesscontrol:
templates["settings"]["entries"]["accesscontrol"] = (gettext("Access Control"), dict(template="dialogs/settings/accesscontrol.jinja2", _div="settings_users", custom_bindings=False))
@@ -170,17 +180,21 @@ def index():
name = implementation._identifier
plugin_names.add(name)
vars = implementation.get_template_vars()
try:
vars = implementation.get_template_vars()
configs = implementation.get_template_configs()
except:
_logger.exception("Error while retrieving template data for plugin {}, ignoring it".format(name))
continue
if not isinstance(vars, dict):
vars = dict()
if not isinstance(configs, (list, tuple)):
configs = []
for var_name, var_value in vars.items():
plugin_vars["plugin_" + name + "_" + var_name] = var_value
configs = implementation.get_template_configs()
if not isinstance(configs, (list, tuple)):
configs = []
includes = _process_template_configs(name, implementation, configs, template_rules)
for t in template_types:
@@ -223,9 +237,30 @@ def index():
# finally add anything that's not included in our order yet
sorted_missing = list(missing_in_order)
if template_sorting[t]["key"] is not None:
# anything but navbar and generic components get sorted by their name
if template_sorting[t]["key"] == "name":
sorted_missing = sorted(missing_in_order, key=lambda x: templates[t]["entries"][x][0])
# default extractor: works with entries that are dicts and entries that are 2-tuples with the
# entry data at index 1
def extractor(item, key):
if isinstance(item, dict) and key in item:
return item[key]
elif isinstance(item, tuple) and len(item) > 1 and isinstance(item[1], dict) and key in item[1]:
return item[1][key]
return None
# if template type provides custom extractor, make sure its exceptions are handled
if "key_extractor" in template_sorting[t] and callable(template_sorting[t]["key_extractor"]):
def create_safe_extractor(extractor):
def f(x, k):
try:
return extractor(x, k)
except:
_logger.exception("Error while extracting sorting keys for template {}".format(t))
return None
return f
extractor = create_safe_extractor(template_sorting[t]["key_extractor"])
sort_key = template_sorting[t]["key"]
sorted_missing = sorted(missing_in_order, key=lambda x: extractor(templates[t]["entries"][x], sort_key))
if template_sorting[t]["add"] == "prepend":
templates[t]["order"] = sorted_missing + templates[t]["order"]
@@ -240,15 +275,17 @@ def index():
#~~ prepare full set of template vars for rendering
first_run = settings().getBoolean(["server", "firstRun"]) and (userManager is None or not userManager.hasBeenCustomized())
render_kwargs = dict(
webcamStream=settings().get(["webcam", "stream"]),
enableTemperatureGraph=settings().get(["feature", "temperatureGraph"]),
enableAccessControl=userManager is not None,
enableSdSupport=settings().get(["feature", "sdSupport"]),
firstRun=settings().getBoolean(["server", "firstRun"]) and (userManager is None or not userManager.hasBeenCustomized()),
firstRun=first_run,
debug=debug,
version=VERSION,
display_version=DISPLAY_VERSION,
branch=BRANCH,
gcodeMobileThreshold=settings().get(["gcodeViewer", "mobileSizeThreshold"]),
gcodeThreshold=settings().get(["gcodeViewer", "sizeThreshold"]),
uiApiKey=UI_API_KEY,
@@ -260,10 +297,18 @@ def index():
#~~ render!
return render_template(
import datetime
response = make_response(render_template(
"index.jinja2",
**render_kwargs
)
))
response.headers["Last-Modified"] = datetime.datetime.now()
if first_run:
response = util.flask.add_non_caching_response_headers(response)
return response
def _process_template_configs(name, implementation, configs, rules):
@@ -302,6 +347,8 @@ def _process_template_configs(name, implementation, configs, rules):
app.jinja_env.get_or_select_template(data["template"])
except TemplateNotFound:
pass
except:
_logger.exception("Error in template {}, not going to include it".format(data["template"]))
else:
includes[template_type].append(rule["to_entry"](data))
@@ -326,6 +373,9 @@ def _process_template_config(name, implementation, rule, config=None, counter=1)
data["_div"] = rule["div"](name)
if "suffix" in data:
data["_div"] = data["_div"] + data["suffix"]
if not _valid_div_re.match(data["_div"]):
_logger.warn("Template config {} contains invalid div identifier {}, skipping it".format(name, data["_div"]))
return None
if not "template" in data:
data["template"] = rule["template"](name)
@@ -337,6 +387,7 @@ def _process_template_config(name, implementation, rule, config=None, counter=1)
data_bind = "allowBindings: true"
if "data_bind" in data:
data_bind = data_bind + ", " + data["data_bind"]
data_bind = data_bind.replace("\"", "\\\"")
data["data_bind"] = data_bind
data["_key"] = "plugin_" + name
@@ -351,7 +402,9 @@ def robotsTxt():
@app.route("/i18n/<string:locale>/<string:domain>.js")
@util.flask.cached(refreshif=lambda: util.flask.cache_check_headers() or "_refresh" in request.values, key=lambda: "view/%s/%s" % (request.path, g.locale))
@util.flask.cached(timeout=-1,
refreshif=lambda: util.flask.cache_check_headers() or "_refresh" in request.values,
key=lambda: "view:{}:{}".format(request.base_url, g.locale))
def localeJs(locale, domain):
messages = dict()
plural_expr = None
+117 -40
View File
@@ -30,6 +30,8 @@ import logging
import re
import uuid
from octoprint.util import atomic_write, is_hidden_path
_APPNAME = "OctoPrint"
_instance = None
@@ -104,6 +106,15 @@ default_settings = {
"pathSuffix": "path"
},
"maxSize": 100 * 1024, # 100 KB
"commands": {
"systemShutdownCommand": None,
"systemRestartCommand": None,
"serverRestartCommand": None
},
"diskspace": {
"warning": 500 * 1024 * 1024, # 500 MB
"critical": 200 * 1024 * 1024, # 200 MB
}
},
"webcam": {
"stream": None,
@@ -142,7 +153,10 @@ default_settings = {
"repetierTargetTemp": False,
"externalHeatupDetection": True,
"supportWait": True,
"keyboardControl": True
"keyboardControl": True,
"pollWatched": False,
"ignoreIdenticalResends": False,
"identicalResendsCountdown": 7
},
"folder": {
"uploads": None,
@@ -187,7 +201,7 @@ default_settings = {
"settings": [
"section_printer", "serial", "printerprofiles", "temperatures", "terminalfilters", "gcodescripts",
"section_features", "features", "webcam", "accesscontrol", "api",
"section_octoprint", "folders", "appearance", "logs", "plugin_pluginmanager", "plugin_softwareupdate"
"section_octoprint", "server", "folders", "appearance", "logs", "plugin_pluginmanager", "plugin_softwareupdate"
],
"usersettings": ["access", "interface"],
"generic": []
@@ -239,9 +253,10 @@ default_settings = {
},
"scripts": {
"gcode": {
"afterPrintCancelled": "; disable motors\nM84\n\n;disable all heaters\n{% snippet 'disable_hotends' %}\nM140 S0\n\n;disable fan\nM106 S0",
"afterPrintCancelled": "; disable motors\nM84\n\n;disable all heaters\n{% snippet 'disable_hotends' %}\n{% snippet 'disable_bed' %}\n;disable fan\nM106 S0",
"snippets": {
"disable_hotends": "{% for tool in range(printer_profile.extruder.count) %}M104 T{{ tool }} S0\n{% endfor %}"
"disable_hotends": "{% for tool in range(printer_profile.extruder.count) %}M104 T{{ tool }} S0\n{% endfor %}",
"disable_bed": "{% if printer_profile.heatedBed %}M140 S0\n{% endif %}"
}
}
},
@@ -270,6 +285,7 @@ default_settings = {
},
"hasBed": True,
"repetierStyleTargetTemperature": False,
"repetierStyleResends": False,
"okBeforeCommandOutput": False,
"smoothieTemperatureReporting": False,
"extendedSdFileList": False,
@@ -279,7 +295,8 @@ default_settings = {
"txBuffer": 40,
"commandBuffer": 4,
"sendWait": True,
"waitInterval": 1.0
"waitInterval": 1.0,
"supportM112": True
}
}
}
@@ -288,6 +305,11 @@ default_settings = {
valid_boolean_trues = [True, "true", "yes", "y", "1"]
""" Values that are considered to be equivalent to the boolean ``True`` value, used for type conversion in various places."""
class NoSuchSettingsPath(BaseException):
pass
class Settings(object):
"""
The :class:`Settings` class allows managing all of OctoPrint's settings. It takes care of initializing the settings
@@ -320,14 +342,14 @@ class Settings(object):
"/dev/ttyACM0"
``["serial", "timeouts"]`` ::
``["serial", "timeout"]`` ::
communication: 20.0
temperature: 5.0
sdStatus: 1.0
connection: 10.0
``["serial", "timeouts", "temperature"]`` ::
``["serial", "timeout", "temperature"]`` ::
5.0
@@ -384,10 +406,12 @@ class Settings(object):
return folder
def _init_script_templating(self):
from jinja2 import Environment, BaseLoader, FileSystemLoader, ChoiceLoader, TemplateNotFound
from jinja2.nodes import Include, Const
from jinja2 import Environment, BaseLoader, ChoiceLoader, TemplateNotFound
from jinja2.nodes import Include
from jinja2.ext import Extension
from octoprint.util.jinja import FilteredFileSystemLoader
class SnippetExtension(Extension):
tags = {"snippet"}
fields = Include.fields
@@ -476,10 +500,14 @@ class Settings(object):
else:
return template
file_system_loader = FileSystemLoader(self.getBaseFolder("scripts"))
path_filter = lambda path: not is_hidden_path(path)
file_system_loader = FilteredFileSystemLoader(self.getBaseFolder("scripts"),
path_filter=path_filter)
settings_loader = SettingsScriptLoader(self)
choice_loader = ChoiceLoader([file_system_loader, settings_loader])
select_loader = SelectLoader(choice_loader, dict(bundled=settings_loader, file=file_system_loader))
select_loader = SelectLoader(choice_loader,
dict(bundled=settings_loader,
file=file_system_loader))
return RelEnvironment(loader=select_loader, extensions=[SnippetExtension])
def _get_script_template(self, script_type, name, source=False):
@@ -773,11 +801,17 @@ class Settings(object):
if not self._dirty and not force:
return False
with open(self._configfile, "wb") as configFile:
yaml.safe_dump(self._config, configFile, default_flow_style=False, indent=" ", allow_unicode=True)
self._dirty = False
self.load()
return True
from octoprint.util import atomic_write
try:
with atomic_write(self._configfile, "wb", prefix="octoprint-config-", suffix=".yaml") as configFile:
yaml.safe_dump(self._config, configFile, default_flow_style=False, indent=" ", allow_unicode=True)
self._dirty = False
except:
self._logger.exception("Error while saving config.yaml!")
raise
else:
self.load()
return True
@property
def last_modified(self):
@@ -788,13 +822,13 @@ class Settings(object):
stat = os.stat(self._configfile)
return stat.st_mtime
#~~ getter
##~~ Internal getter
def get(self, path, asdict=False, config=None, defaults=None, preprocessors=None, merged=False, incl_defaults=True):
def _get_value(self, path, asdict=False, config=None, defaults=None, preprocessors=None, merged=False, incl_defaults=True):
import octoprint.util as util
if len(path) == 0:
return None
raise NoSuchSettingsPath()
if config is None:
config = self._config
@@ -812,7 +846,7 @@ class Settings(object):
config = {}
defaults = defaults[key]
else:
return None
raise NoSuchSettingsPath()
if preprocessors and isinstance(preprocessors, dict) and key in preprocessors:
preprocessors = preprocessors[key]
@@ -836,7 +870,7 @@ class Settings(object):
elif incl_defaults and key in defaults:
value = defaults[key]
else:
value = None
raise NoSuchSettingsPath()
if preprocessors and isinstance(preprocessors, dict) and key in preprocessors and callable(preprocessors[key]):
value = preprocessors[key](value)
@@ -854,8 +888,34 @@ class Settings(object):
else:
return results
def getInt(self, path, config=None, defaults=None, preprocessors=None, incl_defaults=True):
value = self.get(path, config=config, defaults=defaults, preprocessors=preprocessors, incl_defaults=incl_defaults)
#~~ has
def has(self, path, **kwargs):
try:
self._get_value(path, **kwargs)
except NoSuchSettingsPath:
return False
else:
return True
#~~ getter
def get(self, path, **kwargs):
error_on_path = kwargs.get("error_on_path", False)
new_kwargs = dict(kwargs)
if "error_on_path" in new_kwargs:
del new_kwargs["error_on_path"]
try:
return self._get_value(path, **new_kwargs)
except NoSuchSettingsPath:
if error_on_path:
raise
else:
return None
def getInt(self, path, **kwargs):
value = self.get(path, **kwargs)
if value is None:
return None
@@ -865,8 +925,8 @@ class Settings(object):
self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path))
return None
def getFloat(self, path, config=None, defaults=None, preprocessors=None, incl_defaults=True):
value = self.get(path, config=config, defaults=defaults, preprocessors=preprocessors, incl_defaults=incl_defaults)
def getFloat(self, path, **kwargs):
value = self.get(path, **kwargs)
if value is None:
return None
@@ -876,8 +936,8 @@ class Settings(object):
self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path))
return None
def getBoolean(self, path, config=None, defaults=None, preprocessors=None, incl_defaults=True):
value = self.get(path, config=config, defaults=defaults, preprocessors=preprocessors, incl_defaults=incl_defaults)
def getBoolean(self, path, **kwargs):
value = self.get(path, **kwargs)
if value is None:
return None
if isinstance(value, bool):
@@ -930,6 +990,23 @@ class Settings(object):
return script
#~~ remove
def remove(self, path, config=None):
if config is None:
config = self._config
while len(path) > 1:
key = path.pop(0)
if not isinstance(config, dict) or key not in config:
return
config = config[key]
key = path.pop(0)
if isinstance(config, dict) and key in config:
del config[key]
self._dirty = True
#~~ setter
def set(self, path, value, force=False, defaults=None, config=None, preprocessors=None):
@@ -969,16 +1046,16 @@ class Settings(object):
if not force and key in defaults and key in config and defaults[key] == value:
del config[key]
self._dirty = True
elif force or (not key in config and defaults[key] != value) or (key in config and config[key] != value):
elif force or (not key in config and key in defaults and defaults[key] != value) or (key in config and config[key] != value):
if value is None and key in config:
del config[key]
else:
config[key] = value
self._dirty = True
def setInt(self, path, value, force=False, defaults=None, config=None, preprocessors=None):
def setInt(self, path, value, **kwargs):
if value is None:
self.set(path, None, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
self.set(path, None, **kwargs)
return
try:
@@ -987,11 +1064,11 @@ class Settings(object):
self._logger.warn("Could not convert %r to a valid integer when setting option %r" % (value, path))
return
self.set(path, intValue, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
self.set(path, intValue, **kwargs)
def setFloat(self, path, value, force=False, defaults=None, config=None, preprocessors=None):
def setFloat(self, path, value, **kwargs):
if value is None:
self.set(path, None, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
self.set(path, None, **kwargs)
return
try:
@@ -1000,15 +1077,15 @@ class Settings(object):
self._logger.warn("Could not convert %r to a valid integer when setting option %r" % (value, path))
return
self.set(path, floatValue, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
self.set(path, floatValue, **kwargs)
def setBoolean(self, path, value, force=False, defaults=None, config=None, preprocessors=None):
def setBoolean(self, path, value, **kwargs):
if value is None or isinstance(value, bool):
self.set(path, value, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
self.set(path, value, **kwargs)
elif value.lower() in valid_boolean_trues:
self.set(path, True, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
self.set(path, True, **kwargs)
else:
self.set(path, False, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
self.set(path, False, **kwargs)
def setBaseFolder(self, type, path, force=False):
if type not in default_settings["folder"].keys():
@@ -1030,14 +1107,14 @@ class Settings(object):
def saveScript(self, script_type, name, script):
script_folder = self.getBaseFolder("scripts")
filename = os.path.realpath(os.path.join(script_folder, script_type, name))
if not filename.startswith(script_folder):
if not filename.startswith(os.path.realpath(script_folder)):
# oops, jail break, that shouldn't happen
raise ValueError("Invalid script path to save to: {filename} (from {script_type}:{name})".format(**locals()))
path, _ = os.path.split(filename)
if not os.path.exists(path):
os.makedirs(path)
with open(filename, "w+") as f:
with atomic_write(filename, "wb") as f:
f.write(script)
def _default_basedir(applicationName):
+12 -3
View File
@@ -22,8 +22,11 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import os
import octoprint.plugin
import octoprint.events
import octoprint.util
from octoprint.settings import settings
import logging
from .exceptions import *
@@ -102,6 +105,8 @@ class SlicingManager(object):
"""
def __init__(self, profile_path, printer_profile_manager):
self._logger = logging.getLogger(__name__)
self._profile_path = profile_path
self._printer_profile_manager = printer_profile_manager
@@ -123,7 +128,11 @@ class SlicingManager(object):
plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SlicerPlugin)
slicers = dict()
for plugin in plugins:
slicers[plugin.get_slicer_properties()["type"]] = plugin
try:
slicers[plugin.get_slicer_properties()["type"]] = plugin
except:
self._logger.exception("Error while getting properties from slicer {}, ignoring it".format(plugin._identifier))
continue
self._slicers = slicers
@property
@@ -470,7 +479,7 @@ class SlicingManager(object):
profiles = dict()
slicer_profile_path = self.get_slicer_profile_path(slicer)
for entry in os.listdir(slicer_profile_path):
if not entry.endswith(".profile") or entry.startswith("."):
if not entry.endswith(".profile") or octoprint.util.is_hidden_path(entry):
# we are only interested in profiles and no hidden files
continue
@@ -531,7 +540,7 @@ class SlicingManager(object):
name = self._sanitize(name)
path = os.path.join(self.get_slicer_profile_path(slicer), "{name}.profile".format(name=name))
if not os.path.realpath(path).startswith(self._profile_path):
if not os.path.realpath(path).startswith(os.path.realpath(self._profile_path)):
raise IOError("Path to profile {name} tried to break out of allows sub path".format(**locals()))
if must_exist and not (os.path.exists(path) and os.path.isfile(path)):
raise UnknownProfile(slicer, name)
+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,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-warning:hover,.btn-warning:focus,.btn-warning:aLine truncated
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-warning:hover,.btn-warning:focus,.btn-warning:aLine truncated
@@ -379,7 +379,7 @@ GCODE.renderer = (function(){
};
var drawLayer = function(layerNum, fromProgress, toProgress, isNotCurrentLayer){
console.log("Drawing layer " + layerNum + " from " + fromProgress + " to " + toProgress + " (current: " + !isNotCurrentLayer + ")");
log.trace("Drawing layer " + layerNum + " from " + fromProgress + " to " + toProgress + " (current: " + !isNotCurrentLayer + ")");
var i;
+27 -2
View File
@@ -122,6 +122,7 @@ function DataUpdater(allViewModels) {
var oldVersion = VERSION;
VERSION = data["version"];
DISPLAY_VERSION = data["display_version"];
BRANCH = data["branch"];
$("span.version").text(DISPLAY_VERSION);
var oldPluginHash = self._pluginHash;
@@ -176,6 +177,7 @@ function DataUpdater(allViewModels) {
var type = data["type"];
var payload = data["payload"];
var html = "";
var format = {};
log.debug("Got event " + type + " with payload: " + JSON.stringify(payload));
@@ -186,7 +188,31 @@ function DataUpdater(allViewModels) {
} else if (type == "MovieFailed") {
html = "<p>" + _.sprintf(gettext("Rendering of timelapse %(movie_basename)s failed with return code %(returncode)s"), payload) + "</p>";
html += pnotifyAdditionalInfo('<pre style="overflow: auto">' + payload.error + '</pre>');
new PNotify({title: gettext("Rendering failed"), text: html, type: "error", hide: false});
new PNotify({
title: gettext("Rendering failed"),
text: html,
type: "error",
hide: false
});
} else if (type == "PostRollStart") {
var title = gettext("Capturing timelapse postroll");
var text;
if (!payload.postroll_duration) {
text = _.sprintf(gettext("Now capturing timelapse post roll, this will take only a moment..."), format);
} else {
if (payload.postroll_duration > 60) {
format = {duration: _.sprintf(gettext("%(minutes)d min"), {minutes: payload.postroll_duration / 60})};
} else {
format = {duration: _.sprintf(gettext("%(seconds)d sec"), {seconds: payload.postroll_duration})};
}
text = _.sprintf(gettext("Now capturing timelapse post roll, this will take approximately %(duration)s..."), format);
}
new PNotify({
title: title,
text: text
});
} else if (type == "SlicingStarted") {
gcodeUploadProgress.addClass("progress-striped").addClass("active");
gcodeUploadProgressBar.css("width", "100%");
@@ -224,7 +250,6 @@ function DataUpdater(allViewModels) {
text: _.sprintf(gettext("Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds"), payload),
type: "success"
});
gcodeFilesViewModel.requestData(payload.remote, "sdcard");
}
var legacyEventHandlers = {
+42
View File
@@ -333,6 +333,34 @@ function formatSize(bytes) {
return _.sprintf("%.1f%s", bytes, "TB");
}
function bytesFromSize(size) {
if (size == undefined || size.trim() == "") return undefined;
var parsed = size.match(/^([+]?[0-9]*\.?[0-9]+)(?:\s*)?(.*)$/);
var number = parsed[1];
var unit = parsed[2].trim();
if (unit == "") return parseFloat(number);
var units = {
b: 1,
byte: 1,
bytes: 1,
kb: 1024,
mb: Math.pow(1024, 2),
gb: Math.pow(1024, 3),
tb: Math.pow(1024, 4)
};
unit = unit.toLowerCase();
if (!units.hasOwnProperty(unit)) {
return undefined;
}
var factor = units[unit];
return number * factor;
}
function formatDuration(seconds) {
if (!seconds) return "-";
if (seconds < 0) return "00:00:00";
@@ -461,3 +489,17 @@ function splitTextToArray(text, sep, stripEmpty, filter) {
function(item) { return (stripEmpty ? item : true) && (filter ? filter(item) : true); }
);
}
var sizeObservable = function(observable) {
return ko.computed({
read: function() {
return formatSize(observable());
},
write: function(value) {
var result = bytesFromSize(value);
if (result != undefined) {
observable(result);
}
}
})
};
+113 -6
View File
@@ -7,6 +7,72 @@ $(function() {
log.setLevel(CONFIG_DEBUG ? "debug" : "info");
//~~ setup browser and internal tab tracking (in 1.3.0 that will be
// much nicer with the global OctoPrint object...)
var tabTracking = (function() {
var exports = {
browserTabVisibility: undefined,
selectedTab: undefined
};
var browserVisibilityCallbacks = [];
var getHiddenProp = function() {
var prefixes = ["webkit", "moz", "ms", "o"];
// if "hidden" is natively supported just return it
if ("hidden" in document) {
return "hidden"
}
// otherwise loop over all the known prefixes until we find one
var vendorPrefix = _.find(prefixes, function(prefix) {
return (prefix + "Hidden" in document);
});
if (vendorPrefix !== undefined) {
return vendorPrefix + "Hidden";
}
// nothing found
return undefined;
};
var isHidden = function() {
var prop = getHiddenProp();
if (!prop) return false;
return document[prop];
};
var updateBrowserVisibility = function() {
var visible = !isHidden();
exports.browserTabVisible = visible;
_.each(browserVisibilityCallbacks, function(callback) {
callback(visible);
})
};
// register for browser visibility tracking
var prop = getHiddenProp();
if (!prop) return undefined;
var eventName = prop.replace(/[H|h]idden/, "") + "visibilitychange";
document.addEventListener(eventName, updateBrowserVisibility);
updateBrowserVisibility();
// exports
exports.isVisible = function() { return !isHidden() };
exports.onBrowserVisibilityChange = function(callback) {
browserVisibilityCallbacks.push(callback);
};
return exports;
})();
//~~ AJAX setup
// work around a stupid iOS6 bug where ajax requests get cached and only work once, as described at
@@ -21,6 +87,15 @@ $(function() {
headers: {"X-Api-Key": UI_API_KEY}
});
//~~ Initialize file upload plugin
$.widget("blueimp.fileupload", $.blueimp.fileupload, {
options: {
dropZone: null,
pasteZone: null
}
});
//~~ Initialize i18n
var catalog = window["BABEL_TO_LOAD_" + LOCALE];
@@ -51,14 +126,27 @@ $(function() {
//~~ Initialize PNotify
PNotify.prototype.options.styling = "bootstrap2";
PNotify.prototype.options.mouse_reset = false;
//~~ Initialize view models
// the view model map is our basic look up table for dependencies that may be injected into other view models
var viewModelMap = {};
// We put our tabTracking into the viewModelMap as a workaround until
// our global OctoPrint object becomes available in 1.3.0. This way
// we'll still be able to access it in our view models.
//
// NOTE TO DEVELOPERS: Do NOT depend on this dependency in your custom
// view models. It is ONLY provided for the core application to be able
// to backport a fix from the 1.3.0 development branch and WILL BE
// REMOVED once 1.3.0 gets released without any fallback!
//
// TODO: Remove with release of 1.3.0
viewModelMap.tabTracking = tabTracking;
// Fix Function#name on browsers that do not support it (IE):
// see: http://stackoverflow.com/questions/6903762/function-name-not-supported-in-ie
// see: http://stackoverflow.com/questions/6903762/function-name-not-supported-in-ie
if (!(function f() {}).name) {
Object.defineProperty(Function.prototype, 'name', {
get: function() {
@@ -320,7 +408,7 @@ $(function() {
.data("contextParent", $(this))
.show()
.css({
position: "absolute",
position: "fixed",
left: getMenuPosition(e.clientX, 'width', 'scrollLeft'),
top: getMenuPosition(e.clientY, 'height', 'scrollTop'),
"z-index": 9999
@@ -361,16 +449,22 @@ $(function() {
$('.nav-pills, .nav-tabs').tabdrop();
// Allow components to react to tab change
var tabs = $('#tabs a[data-toggle="tab"]');
tabs.on('show', function (e) {
var current = e.target.hash;
var previous = e.relatedTarget.hash;
var onTabChange = function(current, previous) {
log.debug("Selected OctoPrint tab changed: previous = " + previous + ", current = " + current);
tabTracking.selectedTab = current;
_.each(allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onTabChange")) {
viewModel.onTabChange(current, previous);
}
});
};
var tabs = $('#tabs a[data-toggle="tab"]');
tabs.on('show', function (e) {
var current = e.target.hash;
var previous = e.relatedTarget.hash;
onTabChange(current, previous);
});
tabs.on('shown', function (e) {
@@ -384,6 +478,8 @@ $(function() {
});
});
onTabChange(OCTOPRINT_INITIAL_TAB);
// Fix input element click problems on dropdowns
$(".dropdown input, .dropdown label").click(function(e) {
e.stopPropagation();
@@ -475,11 +571,22 @@ $(function() {
});
log.info("... binding done");
// startup complete
_.each(allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onStartupComplete")) {
viewModel.onStartupComplete();
}
});
// make sure we can track the browser tab visibility
tabTracking.onBrowserVisibilityChange(function(status) {
log.debug("Browser tab is now " + (status ? "visible" : "hidden"));
_.each(allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onBrowserTabVisibilityChange")) {
viewModel.onBrowserTabVisibilityChange(status);
}
});
});
};
if (!_.has(viewModelMap, "settingsViewModel")) {
@@ -86,6 +86,15 @@ $(function() {
self._processStateData(data.state);
};
self.openOrCloseOnStateChange = function() {
var connectionTab = $("#connection");
if (self.isOperational() && connectionTab.hasClass("in")) {
connectionTab.collapse("hide");
} else if (!self.isOperational() && !connectionTab.hasClass("in")) {
connectionTab.collapse("show");
}
}
self._processStateData = function(data) {
self.previousIsOperational = self.isOperational();
@@ -97,15 +106,10 @@ $(function() {
self.isReady(data.flags.ready);
self.isLoading(data.flags.loading);
var connectionTab = $("#connection");
if (self.previousIsOperational != self.isOperational()) {
if (self.isOperational() && connectionTab.hasClass("in")) {
// connection just got established, close connection tab for now
connectionTab.collapse("hide");
} else if (!connectionTab.hasClass("in")) {
// connection just dropped, make sure connection tab is open
connectionTab.collapse("show");
}
if (self.loginState.isAdmin() && self.previousIsOperational != self.isOperational()) {
// only open or close if the panel is visible (for admins) and
// the state just changed to avoid thwarting manual open/close
self.openOrCloseOnStateChange();
}
};
@@ -147,6 +151,16 @@ $(function() {
self.onStartup = function() {
self.requestData();
// when isAdmin becomes true the first time, set the panel open or
// closed based on the connection state
var subscription = self.loginState.isAdmin.subscribe(function(newValue) {
if (newValue) {
// wait until after the isAdmin state has run through all subscriptions
setTimeout(self.openOrCloseOnStateChange, 0);
subscription.dispose();
}
});
};
}
@@ -5,6 +5,9 @@ $(function() {
self.loginState = parameters[0];
self.settings = parameters[1];
// TODO remove with release of 1.3.0 and switch to OctoPrint.coreui usage
self.tabTracking = parameters[2];
self._createToolEntry = function () {
return {
name: ko.observable(),
@@ -415,31 +418,51 @@ $(function() {
self.onSettingsBeforeSave = self.updateRotatorWidth;
self._disableWebcam = function() {
// only disable webcam stream if tab is out of focus for more than 5s, otherwise we might cause
// more load by the constant connection creation than by the actual webcam stream
self.webcamDisableTimeout = setTimeout(function () {
$("#webcam_image").attr("src", "");
}, 5000);
};
self._enableWebcam = function() {
if (self.tabTracking.selectedTab != "#control" || !self.tabTracking.browserTabVisible) {
return;
}
if (self.webcamDisableTimeout != undefined) {
clearTimeout(self.webcamDisableTimeout);
}
var webcamImage = $("#webcam_image");
var currentSrc = webcamImage.attr("src");
if (currentSrc === undefined || currentSrc.trim() == "") {
var newSrc = CONFIG_WEBCAM_STREAM;
if (CONFIG_WEBCAM_STREAM.lastIndexOf("?") > -1) {
newSrc += "&";
} else {
newSrc += "?";
}
newSrc += new Date().getTime();
self.updateRotatorWidth();
webcamImage.attr("src", newSrc);
}
};
self.onTabChange = function (current, previous) {
if (current == "#control") {
if (self.webcamDisableTimeout != undefined) {
clearTimeout(self.webcamDisableTimeout);
}
var webcamImage = $("#webcam_image");
var currentSrc = webcamImage.attr("src");
if (currentSrc === undefined || currentSrc.trim() == "") {
var newSrc = CONFIG_WEBCAM_STREAM;
if (CONFIG_WEBCAM_STREAM.lastIndexOf("?") > -1) {
newSrc += "&";
} else {
newSrc += "?";
}
newSrc += new Date().getTime();
self.updateRotatorWidth();
webcamImage.attr("src", newSrc);
}
self._enableWebcam();
} else if (previous == "#control") {
// only disable webcam stream if tab is out of focus for more than 5s, otherwise we might cause
// more load by the constant connection creation than by the actual webcam stream
self.webcamDisableTimeout = setTimeout(function () {
$("#webcam_image").attr("src", "");
}, 5000);
self._disableWebcam();
}
};
self.onBrowserTabVisibilityChange = function(status) {
if (status) {
self._enableWebcam();
} else {
self._disableWebcam();
}
};
@@ -565,7 +588,7 @@ $(function() {
OCTOPRINT_VIEWMODELS.push([
ControlViewModel,
["loginStateViewModel", "settingsViewModel"],
["loginStateViewModel", "settingsViewModel", "tabTracking"],
"#control"
]);
});
+42 -10
View File
@@ -2,9 +2,10 @@ $(function() {
function GcodeFilesViewModel(parameters) {
var self = this;
self.printerState = parameters[0];
self.settingsViewModel = parameters[0];
self.loginState = parameters[1];
self.slicing = parameters[2];
self.printerState = parameters[2];
self.slicing = parameters[3];
self.isErrorOrClosed = ko.observable(undefined);
self.isOperational = ko.observable(undefined);
@@ -21,11 +22,35 @@ $(function() {
});
self.freeSpace = ko.observable(undefined);
self.totalSpace = ko.observable(undefined);
self.freeSpaceString = ko.computed(function() {
if (!self.freeSpace())
return "-";
return formatSize(self.freeSpace());
});
self.totalSpaceString = ko.computed(function() {
if (!self.totalSpace())
return "-";
return formatSize(self.totalSpace());
});
self.diskusageWarning = ko.computed(function() {
return self.freeSpace() != undefined
&& self.freeSpace() < self.settingsViewModel.server_diskspace_warning();
});
self.diskusageCritical = ko.computed(function() {
return self.freeSpace() != undefined
&& self.freeSpace() < self.settingsViewModel.server_diskspace_critical();
});
self.diskusageString = ko.computed(function() {
if (self.diskusageCritical()) {
return gettext("Your available free disk space is critically low.");
} else if (self.diskusageWarning()) {
return gettext("Your available free disk space is starting to run low.");
} else {
return gettext("Your current disk usage.");
}
});
self.uploadButton = undefined;
@@ -47,8 +72,8 @@ $(function() {
},
"size": function(a, b) {
// sorts descending
if (b["bytes"] === undefined || a["bytes"] > b["bytes"]) return -1;
if (a["bytes"] < b["bytes"]) return 1;
if (b["size"] === undefined || a["size"] > b["size"]) return -1;
if (a["size"] < b["size"]) return 1;
return 0;
}
},
@@ -155,10 +180,14 @@ $(function() {
}
}
if (response.free) {
if (response.free != undefined) {
self.freeSpace(response.free);
}
if (response.total != undefined) {
self.totalSpace(response.total);
}
self.highlightFilename(self.printerState.filename());
};
@@ -309,18 +338,17 @@ $(function() {
};
self.performSearch = function(e) {
if (e !== undefined) {
e.preventDefault();
}
var query = self.searchQuery();
if (query !== undefined && query.trim() != "") {
query = query.toLocaleLowerCase();
self.listHelper.changeSearchFunction(function(entry) {
return entry && entry["name"].toLocaleLowerCase().indexOf(query) > -1;
});
} else {
self.listHelper.resetSearch();
}
return false;
};
self.onDataUpdaterReconnect = function() {
@@ -572,11 +600,15 @@ $(function() {
self.onEventMetadataStatisticsUpdated = function(payload) {
self.requestData();
};
self.onEventTransferDone = function(payload) {
self.requestData(payload.remote, "sdcard");
};
}
OCTOPRINT_VIEWMODELS.push([
GcodeFilesViewModel,
["printerStateViewModel", "loginStateViewModel", "slicingViewModel"],
["settingsViewModel", "loginStateViewModel", "printerStateViewModel", "slicingViewModel"],
"#files_wrapper"
]);
});
+31 -15
View File
@@ -5,6 +5,9 @@ $(function() {
self.loginState = parameters[0];
self.settings = parameters[1];
// TODO remove with release of 1.3.0 and switch to OctoPrint.coreui usage
self.tabTracking = parameters[2];
self.ui_progress_percentage = ko.observable();
self.ui_progress_type = ko.observable();
self.ui_progress_text = ko.computed(function() {
@@ -339,6 +342,21 @@ $(function() {
self._processData(data);
};
self._renderPercentage = function(percentage) {
var cmdIndex = GCODE.gCodeReader.getCmdIndexForPercentage(percentage);
if (!cmdIndex) return;
GCODE.renderer.render(cmdIndex.layer, 0, cmdIndex.cmd);
GCODE.ui.updateLayerInfo(cmdIndex.layer);
if (self.layerSlider != undefined) {
self.layerSlider.slider("setValue", cmdIndex.layer);
}
if (self.layerCommandSlider != undefined) {
self.layerCommandSlider.slider("setValue", [0, cmdIndex.cmd]);
}
};
self._processData = function(data) {
if (!data.job.file || !data.job.file.name && (self.loadedFilename || self.loadedFileDate)) {
self.waitForApproval(false);
@@ -358,19 +376,8 @@ $(function() {
if(self.loadedFilename
&& self.loadedFilename == data.job.file.name
&& self.loadedFileDate == data.job.file.date) {
if (self.currentlyPrinting && self.renderer_syncProgress() && !self.waitForApproval()) {
var cmdIndex = GCODE.gCodeReader.getCmdIndexForPercentage(data.progress.completion);
if(cmdIndex){
GCODE.renderer.render(cmdIndex.layer, 0, cmdIndex.cmd);
GCODE.ui.updateLayerInfo(cmdIndex.layer);
if (self.layerSlider != undefined) {
self.layerSlider.slider("setValue", cmdIndex.layer);
}
if (self.layerCommandSlider != undefined) {
self.layerCommandSlider.slider("setValue", [0, cmdIndex.cmd]);
}
}
if (self.tabTracking.browserTabVisible && self.tabActive && self.currentlyPrinting && self.renderer_syncProgress() && !self.waitForApproval()) {
self._renderPercentage(data.progress.completion);
}
self.errorCount = 0
} else {
@@ -394,6 +401,12 @@ $(function() {
}
};
self.onEventPrintDone = function() {
if (self.renderer_syncProgress() && !self.waitForApproval()) {
self._renderPercentage(100.0);
}
};
self.approveLargeFile = function() {
self.waitForApproval(false);
self.loadFile(self.selectedFile.name(), self.selectedFile.date());
@@ -504,13 +517,16 @@ $(function() {
self.onBeforeBinding = function() {
self.initialize();
}
};
self.onTabChange = function(current, previous) {
self.tabActive = current == "#gcode";
};
}
OCTOPRINT_VIEWMODELS.push([
GcodeViewModel,
["loginStateViewModel", "settingsViewModel"],
["loginStateViewModel", "settingsViewModel", "tabTracking"],
"#gcode"
]);
});
@@ -15,7 +15,7 @@ $(function() {
height: 200,
origin: "lowerleft"
},
heatedBed: false,
heatedBed: true,
axes: {
x: {speed: 6000, inverted: false},
y: {speed: 6000, inverted: false},
@@ -6,6 +6,10 @@ $(function() {
self.users = parameters[1];
self.printerProfiles = parameters[2];
self.receiving = ko.observable(false);
self.sending = ko.observable(false);
self.callbacks = [];
self.api_enabled = ko.observable(undefined);
self.api_key = ko.observable(undefined);
self.api_allowCrossOrigin = ko.observable(undefined);
@@ -113,6 +117,8 @@ $(function() {
self.feature_repetierTargetTemp = ko.observable(undefined);
self.feature_disableExternalHeatupDetection = ko.observable(undefined);
self.feature_keyboardControl = ko.observable(undefined);
self.feature_pollWatched = ko.observable(undefined);
self.feature_ignoreIdenticalResends = ko.observable(undefined);
self.serial_port = ko.observable();
self.serial_baudrate = ko.observable();
@@ -148,6 +154,15 @@ $(function() {
self.terminalFilters = ko.observableArray([]);
self.server_commands_systemShutdownCommand = ko.observable(undefined);
self.server_commands_systemRestartCommand = ko.observable(undefined);
self.server_commands_serverRestartCommand = ko.observable(undefined);
self.server_diskspace_warning = ko.observable();
self.server_diskspace_critical = ko.observable();
self.server_diskspace_warning_str = sizeObservable(self.server_diskspace_warning);
self.server_diskspace_critical_str = sizeObservable(self.server_diskspace_critical);
self.settings = undefined;
self.addTemperatureProfile = function() {
@@ -256,13 +271,42 @@ $(function() {
};
self.requestData = function(callback) {
if (self.receiving()) {
if (callback) {
self.callbacks.push(callback);
}
return;
}
self.receiving(true);
$.ajax({
url: API_BASEURL + "settings",
type: "GET",
dataType: "json",
success: function(response) {
self.fromResponse(response);
if (callback) callback();
if (callback) {
self.callbacks.push(callback);
}
try {
self.fromResponse(response);
var cb;
while (self.callbacks.length) {
cb = self.callbacks.shift();
try {
cb();
} catch(exc) {
log.error("Error calling settings callback", cb, ":", (exc.stack || exc));
}
}
} finally {
self.receiving(false);
self.callbacks = [];
}
},
error: function(xhr) {
self.receiving(false);
}
});
};
@@ -377,6 +421,7 @@ $(function() {
self.feature_repetierTargetTemp(response.feature.repetierTargetTemp);
self.feature_disableExternalHeatupDetection(!response.feature.externalHeatupDetection);
self.feature_keyboardControl(response.feature.keyboardControl);
self.feature_pollWatched(response.feature.pollWatched);
self.serial_port(response.serial.port);
self.serial_baudrate(response.serial.baudrate);
@@ -413,12 +458,18 @@ $(function() {
self.system_actions(response.system.actions);
self.terminalFilters(response.terminalFilters);
self.server_commands_systemShutdownCommand(response.server.commands.systemShutdownCommand);
self.server_commands_systemRestartCommand(response.server.commands.systemRestartCommand);
self.server_commands_serverRestartCommand(response.server.commands.serverRestartCommand);
};
self.saveData = function (data, successCallback) {
self.settingsDialog.trigger("beforeSave");
if (data == undefined) {
// we only set sending to true when we didn't include data
self.sending(true);
data = ko.mapping.toJS(self.settings);
data = _.extend(data, {
@@ -457,7 +508,8 @@ $(function() {
"swallowOkAfterResend": self.feature_swallowOkAfterResend(),
"repetierTargetTemp": self.feature_repetierTargetTemp(),
"externalHeatupDetection": !self.feature_disableExternalHeatupDetection(),
"keyboardControl": self.feature_keyboardControl()
"keyboardControl": self.feature_keyboardControl(),
"pollWatched": self.feature_pollWatched()
},
"serial": {
"port": self.serial_port(),
@@ -496,6 +548,13 @@ $(function() {
"beforePrintResumed": self.scripts_gcode_beforePrintResumed(),
"afterPrinterConnected": self.scripts_gcode_afterPrinterConnected()
}
},
"server": {
"commands": {
"systemShutdownCommand": self.server_commands_systemShutdownCommand(),
"systemRestartCommand": self.server_commands_systemRestartCommand(),
"serverRestartCommand": self.server_commands_serverRestartCommand()
}
}
});
}
@@ -507,11 +566,24 @@ $(function() {
contentType: "application/json; charset=UTF-8",
data: JSON.stringify(data),
success: function(response) {
self.fromResponse(response);
if (successCallback) successCallback(response);
self.receiving(true);
self.sending(false);
try {
self.fromResponse(response);
if (successCallback) successCallback(response);
} finally {
self.receiving(false);
}
},
error: function(xhr) {
self.sending(false);
}
});
};
self.onEventSettingsUpdated = function() {
self.requestData();
};
}
OCTOPRINT_VIEWMODELS.push([
@@ -36,7 +36,7 @@ $(function() {
self.heaterOptions = ko.observable({});
self._numExtrudersUpdated = function() {
self._printerProfileUpdated = function() {
var graphColors = ["red", "orange", "green", "brown", "purple"];
var heaterOptions = {};
var tools = self.tools();
@@ -69,15 +69,21 @@ $(function() {
}
// print bed
heaterOptions["bed"] = {name: gettext("Bed"), color: "blue"};
if (self.settingsViewModel.printerProfiles.currentProfileData().heatedBed()) {
self.hasBed(true);
heaterOptions["bed"] = {name: gettext("Bed"), color: "blue"};
} else {
self.hasBed(false);
}
// write back
self.heaterOptions(heaterOptions);
self.tools(tools);
};
self.settingsViewModel.printerProfiles.currentProfileData.subscribe(function() {
self._numExtrudersUpdated();
self.settingsViewModel.printerProfiles.currentProfileData().extruder.count.subscribe(self._numExtrudersUpdated);
self._printerProfileUpdated();
self.settingsViewModel.printerProfiles.currentProfileData().extruder.count.subscribe(self._printerProfileUpdated);
self.settingsViewModel.printerProfiles.currentProfileData().heatedBed.subscribe(self._printerProfileUpdated());
});
self.temperatures = [];
@@ -152,11 +158,8 @@ $(function() {
}
if (lastData.hasOwnProperty("bed")) {
self.hasBed(true);
self.bedTemp["actual"](lastData.bed.actual);
self.bedTemp["target"](lastData.bed.target);
} else {
self.hasBed(false);
}
if (!CONFIG_TEMPERATURE_GRAPH) return;
@@ -208,8 +211,6 @@ $(function() {
if (!d[type]) return;
result[type].actual.push([time, d[type].actual]);
result[type].target.push([time, d[type].target]);
self.hasBed(self.hasBed() || (type == "bed"));
})
});
@@ -375,4 +376,4 @@ $(function() {
["loginStateViewModel", "settingsViewModel"],
"#temp"
]);
});
});
@@ -7,6 +7,7 @@ $(function() {
self.log = ko.observableArray([]);
self.buffer = ko.observable(300);
self.upperLimit = ko.observable(3000);
self.command = ko.observable(undefined);
@@ -34,7 +35,8 @@ $(function() {
var filtered = false;
var result = [];
_.each(self.log(), function(entry) {
var lines = self.log();
_.each(lines, function(entry) {
if (lineVisible(entry)) {
result.push(entry);
filtered = false;
@@ -46,19 +48,30 @@ $(function() {
return result;
});
self.displayedLines.subscribe(function() {
self.updateOutput();
});
self.lineCount = ko.computed(function() {
var total = self.log().length;
var displayed = _.filter(self.displayedLines(), function(entry) { return entry.type == "line" }).length;
var regex = self.filterRegex();
var lineVisible = function(entry) {
return regex == undefined || !entry.line.match(regex);
};
var lines = self.log();
var total = lines.length;
var displayed = _.filter(lines, lineVisible).length;
var filtered = total - displayed;
if (total == displayed) {
return _.sprintf(gettext("showing %(displayed)d lines"), {displayed: displayed});
if (filtered > 0) {
if (total > self.upperLimit()) {
return _.sprintf(gettext("showing %(displayed)d lines (%(filtered)d of %(total)d total lines filtered, buffer full)"), {displayed: displayed, total: total, filtered: filtered});
} else {
return _.sprintf(gettext("showing %(displayed)d lines (%(filtered)d of %(total)d total lines filtered)"), {displayed: displayed, total: total, filtered: filtered});
}
} else {
return _.sprintf(gettext("showing %(displayed)d lines (%(filtered)d of %(total)d total lines filtered)"), {displayed: displayed, total: total, filtered: filtered});
if (total > self.upperLimit()) {
return _.sprintf(gettext("showing %(displayed)d lines (buffer full)"), {displayed: displayed});
} else {
return _.sprintf(gettext("showing %(displayed)d lines"), {displayed: displayed});
}
}
});
@@ -84,14 +97,31 @@ $(function() {
};
self._processCurrentLogData = function(data) {
self.log(self.log().concat(_.map(data, function(line) { return self._toInternalFormat(line) })));
if (self.autoscrollEnabled()) {
self.log(self.log.slice(-300));
var length = self.log().length;
if (length >= self.upperLimit()) {
var cutoff = "--- too many lines to buffer, cut off ---";
var last = self.log()[length-1];
if (!last || last.type != "cut" || last.line != cutoff) {
self.log(self.log().concat(self._toInternalFormat(cutoff, "cut")));
}
return;
}
var newLog = self.log().concat(_.map(data, function(line) { return self._toInternalFormat(line) }));
if (self.autoscrollEnabled()) {
// we only keep the last <buffer> entries
newLog = newLog.slice(-self.buffer());
} else if (newLog.length > self.upperLimit()) {
// we only keep the first <upperLimit> entries
newLog = newLog.slice(0, self.upperLimit());
}
self.log(newLog);
self.updateOutput();
};
self._processHistoryLogData = function(data) {
self.log(_.map(data, function(line) { return self._toInternalFormat(line) }));
self.updateOutput();
};
self._toInternalFormat = function(line, type) {
@@ -141,7 +171,7 @@ $(function() {
self.scrollToEnd = function() {
var container = $("#terminal-output");
if (container.length) {
container.scrollTop(container[0].scrollHeight - container.height())
container.scrollTop(container[0].scrollHeight);
}
};
@@ -232,4 +262,4 @@ $(function() {
["loginStateViewModel", "settingsViewModel"],
"#term"
]);
});
});
+4 -3
View File
@@ -726,8 +726,9 @@
selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
}
$parent = $(selector)
$parent.length || ($parent = $this.parent())
$parent = selector && (selector != "#") && $(selector)
if (!$parent || !$parent.length) $parent = $this.parent()
return $parent
}
@@ -2156,4 +2157,4 @@
})
}(window.jQuery);
}(window.jQuery);
@@ -1,6 +0,0 @@
/*!
* Bootstrap.js by @fat & @mdo
* Copyright 2012 Twitter, Inc.
* http://www.apache.org/licenses/LICENSE-2.0.txt
*/
!function($){"use strict";$(function(){$.support.transition=function(){var transitionEnd=function(){var name,el=document.createElement("bootstrap"),transEndEventNames={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(name in transEndEventNames)if(void 0!==el.style[name])return transEndEventNames[name]}();return transitionEnd&&{end:transitionEnd}}()})}(window.jQuery),!function($){"use strict";var dismiss='[data-dismiss="alert"]',Alert=function(el){$(el).on("click",dismiss,this.close)};Alert.prototype.close=function(e){function removeElement(){$parent.trigger("closed").remove()}var $parent,$this=$(this),selector=$this.attr("data-target");selector||(selector=$this.attr("href"),selector=selector&&selector.replace(/.*(?=#[^\s]*$)/,"")),$parent=$(selector),e&&e.preventDefault(),$parent.length||($parent=$this.hasClass("alert")?$this:$this.parent()),$parent.trigger(e=$.Event("close")),e.isDefaultPrevented()||($parent.removeClass("in"),$.support.transition&&$parent.hasClass("fade")?$parent.on($.support.transition.end,removeElement):removeElement())};var old=$.fn.alert;$.fn.alert=function(option){return this.each(function(){var $this=$(this),data=$this.data("alert");data||$this.data("alert",data=new Alert(this)),"string"==typeof option&&data[option].call($this)})},$.fn.alert.Constructor=Alert,$.fn.alert.noConflict=function(){return $.fn.alert=old,this},$(document).on("click.alert.data-api",dismiss,Alert.prototype.close)}(window.jQuery),!function($){"use strict";var Button=function(element,options){this.$element=$(element),this.options=$.extend({},$.fn.button.defaults,options)};Button.prototype.setState=function(state){var d="disabled",$el=this.$element,data=$el.data(),val=$el.is("input")?"val":"html";state+="Text",data.resetText||$el.data("resetText",$el[val]()),$el[val](data[state]||this.options[state]),setTimeout(function(){"loadingText"==state?$el.addClass(d).attr(d,d):$el.removeClass(d).removeAttr(d)},0)},Button.prototype.toggle=function(){var $parent=this.$element.closest('[data-toggle="buttons-radio"]');$parent&&$parent.find(".active").removeClass("active"),this.$element.toggleClass("active")};var old=$.fn.button;$.fn.button=function(option){return this.each(function(){var $this=$(this),data=$this.data("button"),options="object"==typeof option&&option;data||$this.data("button",data=new Button(this,options)),"toggle"==option?data.toggle():option&&data.setState(option)})},$.fn.button.defaults={loadingText:"loading..."},$.fn.button.Constructor=Button,$.fn.button.noConflict=function(){return $.fn.button=old,this},$(document).on("click.button.data-api","[data-toggle^=button]",function(e){var $btn=$(e.target);$btn.hasClass("btn")||($btn=$btn.closest(".btn")),$btn.button("toggle")})}(window.jQuery),!function($){"use strict";var Carousel=function(element,options){this.$element=$(element),this.options=options,"hover"==this.options.pause&&this.$element.on("mouseenter",$.proxy(this.pause,this)).on("mouseleave",$.proxy(this.cycle,this))};Carousel.prototype={cycle:function(e){return e||(this.paused=!1),this.options.interval&&!this.paused&&(this.interval=setInterval($.proxy(this.next,this),this.options.interval)),this},to:function(pos){var $active=this.$element.find(".item.active"),children=$active.parent().children(),activePos=children.index($active),that=this;if(!(pos>children.length-1||0>pos))return this.sliding?this.$element.one("slid",function(){that.to(pos)}):activePos==pos?this.pause().cycle():this.slide(pos>activePos?"next":"prev",$(children[pos]))},pause:function(e){return e||(this.paused=!0),this.$element.find(".next, .prev").length&&$.support.transition.end&&(this.$element.trigger($.support.transition.end),this.cycle()),clearInterval(this.interval),this.interval=null,this},next:function(){return this.sliding?void 0:this.slide("next")},prev:function(){return this.sliding?void 0:this.slide("prev")},slide:function(type,next){var e,$active=this.$element.find(".item.active"),$next=next||$active[type](),isCycling=this.interval,direction="next"==type?"left":"right",fallback="next"==type?"first":"last",that=this;if(this.sliding=!0,isCycling&&this.pause(),$next=$next.length?$next:this.$element.find(".item")[fallback](),e=$.Event("slide",{relatedTarget:$next[0]}),!$next.hasClass("active")){if($.support.transition&&this.$element.hasClass("slide")){if(this.$element.trigger(e),e.isDefaultPrevented())return;$next.addClass(type),$next[0].offsetWidth,$active.addClass(direction),$next.addClass(direction),this.$element.one($.support.transition.end,function(){$next.removeClass([type,direction].join(" ")).addClass("active"),$active.removeClass(["active",direction].join(" ")),that.sliding=!1,setTimeout(function(){that.$element.trigger("slid")},0)})}else{if(this.$element.trigger(e),e.isDefaultPrevented())return;$active.removeClass("active"),$next.addClass("active"),this.sliding=!1,this.$element.trigger("slid")}return isCycling&&this.cycle()Line truncated
+24 -3
View File
@@ -396,10 +396,17 @@ ul.dropdown-menu li a {
left: 0;
width: 100%;
height: 100%;
z-index: 10001;
display: none;
}
#offline_overlay {
z-index: 10002;
}
#reloadui_overlay {
z-index: 10001;
}
#offline_overlay_background,
#reloadui_overlay_background {
position: fixed;
@@ -611,11 +618,11 @@ ul.dropdown-menu li a {
}
}
.custom_section_horizontal .custom_control {
.custom_section_horizontal > .custom_control {
display: inline-block;
}
.custom_section_vertical .custom_control {
.custom_section_vertical > .custom_control {
display:block;
}
@@ -975,6 +982,20 @@ textarea.block {
}
}
// Special delivery for Safari browsers... because Safari >= 8 sometimes just
// shows us white panes on the settings dialog when the full-sized-box has
// an absolute position (which it needs for both scrollbars to work), at least
// until the page is resized or otherwise a rerender is triggered, we'll have
// our styling resolve to static positioning on that browser for now.
//
// This btw also means that the dialog will change in size. Yay.
//
// Better use something else if you have the option, that thing is really
// weird.
_::-webkit-full-page-media, _:future, :root .full-sized-box {
position: static;
}
.scrollable {
height: 100%;
overflow: auto;
@@ -1,7 +1,7 @@
<div id="settings_dialog" class="modal hide fade large" tabindex="-1" role="dialog" aria-labelledby="settings_dialog_label" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">&times;</button>
<h3 id="settings_dialog_label">{{ _('OctoPrint Settings') }}</h3>
<h3 id="settings_dialog_label">{{ _('OctoPrint Settings') }} <i class="icon-spinner icon-spin" data-bind="visible: receiving"></i></h3>
</div>
<div class="modal-body">
<div class="full-sized-box">
@@ -20,7 +20,7 @@
class="{% if mark_active %}active{% set mark_active = False %}{% endif %} {% if "classes_link" in data %}{{ data.classes_link|join(' ') }}{% elif "classes" in data %}{{ data.classes|join(' ') }}{% endif %}"
{% if "styles_link" in data %} style="{{ data.styles_link|join(', ') }}" {% elif "styles" in data %} style="{{ data.styles|join(', ') }}" {% endif %}
>
<a href="#{{ data._div }}" data-toggle="tab">{{ entry }}</a>
<a href="#{{ data._div }}" data-toggle="tab">{{ entry|e }}</a>
</li>
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
{% endif %}
@@ -49,6 +49,6 @@
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</button>
<button class="btn btn-primary" data-bind="click: function() { saveData(undefined, $root.hide) }">{{ _('Save') }}</button>
<button class="btn btn-primary" data-bind="click: function() { saveData(undefined, $root.hide) }, enable: !sending(), css: {disabled: sending()}"><i class="icon-spinner icon-spin" data-bind="visible: sending"></i> {{ _('Save') }}</button>
</div>
</div>
@@ -48,6 +48,13 @@
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_ignoreIdenticalResends" id="settings-ignoreIdenticalResends"> {{ _('Ignore consecutive resend requests for the same line') }} <span class="label">{{ _('Repetier') }}</span>
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
@@ -62,11 +69,4 @@
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_swallowOkAfterResend" id="settings-swallowOkAfterResend"> {{ _('Swallow the first "ok" after a resend response') }}
</label>
</div>
</div>
</form>
@@ -1,4 +1,6 @@
<form class="form-horizontal">
<h3>{{ _('Folders') }}</h3>
<div class="control-group">
<label class="control-label" for="settings-folderUploads">{{ _('Upload Folder') }}</label>
<div class="controls">
@@ -29,4 +31,28 @@
<input type="text" class="input-block-level" data-bind="value: folder_watched" id="settings-folderWatched">
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_pollWatched" id="settings-featurePollWatched"> {{ _('Actively poll the watched folder. Check this if files in your watched folder aren\'t automatically added otherwise.') }}
</label>
</div>
</div>
<h3>{{ _('Disk space thresholds') }}</h3>
<p>{{ _('If the free disk space falls below these thresholds, OctoPrint will warn the user.') }}</p>
<div class="control-group" title="{{ ('Threshold after which to warn about the remaining free space on disk.') }}">
<label class="control-label" for="settings.serverDiskusageWarning">{{ _('Warning') }}</label>
<div class="controls">
<input type="text" class="input-mini text-right" data-bind="value: server_diskspace_warning_str">
</div>
</div>
<div class="control-group" title="{{ ('Threshold after which to consider remaining free space on disk as critical.') }}">
<label class="control-label" for="settings.serverDiskusageCritical">{{ _('Critical') }}</label>
<div class="controls">
<input type="text" class="input-mini text-right" data-bind="value: server_diskspace_critical_str">
</div>
</div>
</form>
@@ -22,7 +22,7 @@
<label class="control-label" for="settings-serialTimeoutTemperature">{{ _('Temperature interval') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="any" min="0" class="input-mini text-right" data-bind="value: serial_timeoutTemperature" id="settings-serialTimeoutTemperature">
<input type="number" step="any" min="1" class="input-mini text-right" data-bind="value: serial_timeoutTemperature" id="settings-serialTimeoutTemperature">
<span class="add-on">s</span>
</div>
</div>
@@ -0,0 +1,22 @@
<form class="form-horizontal">
<h3>{{ _('Commands') }}</h3>
<div class="control-group" title="{{ _('Command to restart the OctoPrint server') }}">
<label class="control-label" for="settings-serverRestartCommand">{{ _('Restart OctoPrint') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: server_commands_serverRestartCommand" id="settings-serverRestartCommand">
</div>
</div>
<div class="control-group" title="{{ _('Command to restart the system OctoPrint is running on') }}">
<label class="control-label" for="settings-systemRestartCommand">{{ _('Restart system') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: server_commands_systemRestartCommand" id="settings-systemRestartCommand">
</div>
</div>
<div class="control-group" title="{{ _('Command to shut down the system OctoPrint is running on') }}">
<label class="control-label" for="settings-systemShutdownCommand">{{ _('Shutdown system') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: server_commands_systemShutdownCommand" id="settings-systemShutdownCommand">
</div>
</div>
</form>
@@ -17,7 +17,7 @@
class="{% if mark_active %}active{% set mark_active = False %}{% endif %} {% if "classes_link" in data %}{{ data.classes_link|join(' ') }}{% elif "classes" in data %}{{ data.classes|join(' ') }}{% endif %}"
{% if "styles_link" in data %} style="{{ data.styles_link|join(', ') }}" {% elif "styles" in data %} style="{{ data.styles|join(', ') }}" {% endif %}
>
<a href="#{{ data._div }}" data-toggle="tab">{{ entry }}</a>
<a href="#{{ data._div }}" data-toggle="tab">{{ entry|e }}</a>
</li>
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
{% endif %}
+3 -3
View File
@@ -55,7 +55,7 @@
>
<div class="accordion-heading">
<a class="accordion-toggle" data-toggle="collapse" data-target="#{{ data._div }}">
{% if "icon" in data %}<i class="icon-{{ data.icon }}"></i> {% endif %}{{ entry }}
{% if "icon" in data %}<i class="icon-{{ data.icon }}"></i> {% endif %}{{ entry|e }}
</a>
{% if "template_header" in data %}
{% include data.template_header ignore missing %}
@@ -87,7 +87,7 @@
{% if "data_bind" in data %}data-bind="{{ data.data_bind }}"{% endif %}
{% if "styles_link" in data %} style="{{ data.styles_link|join(', ') }}" {% elif "styles" in data %} style="{{ data.styles|join(', ') }}" {% endif %}
>
<a href="#{{ data._div }}" data-toggle="tab">{{ entry }}</a>
<a href="#{{ data._div }}" data-toggle="tab">{{ entry|e }}</a>
</li>
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
{% endfor %}
@@ -112,7 +112,7 @@
</div>
<div class="footer">
<ul class="pull-left muted">
<li><small>{{ _('Version') }}: <span class="version">{{ display_version }}</span></small></li>
<li><small>{{ _('Version') }}: <span class="version">{{ display_version|e }}</span></small></li>
</ul>
<ul class="pull-right">
<li><a href="http://octoprint.org"><i class="icon-home"></i> {{ _('Homepage') }}</a></li>
+17 -8
View File
@@ -10,26 +10,35 @@
var CONFIG_TIMELAPSEFILESPERPAGE = 10;
var CONFIG_LOGFILESPERPAGE = 10;
var CONFIG_USERSPERPAGE = 10;
var CONFIG_WEBCAM_STREAM = "{{ webcamStream }}";
var CONFIG_WEBCAM_STREAM = "{{ webcamStream|e }}";
var CONFIG_ACCESS_CONTROL = {% if enableAccessControl -%} true; {% else %} false; {%- endif %}
var CONFIG_SD_SUPPORT = {% if enableSdSupport -%} true; {% else %} false; {%- endif %}
var CONFIG_FIRST_RUN = {% if firstRun -%} true; {% else %} false; {%- endif %}
var CONFIG_TEMPERATURE_GRAPH = {% if enableTemperatureGraph -%} true; {% else %} false; {%- endif %}
var CONFIG_GCODE_SIZE_THRESHOLD = {{ gcodeThreshold }};
var CONFIG_GCODE_MOBILE_SIZE_THRESHOLD = {{ gcodeMobileThreshold }};
var CONFIG_GCODE_SIZE_THRESHOLD = {{ gcodeThreshold|e }};
var CONFIG_GCODE_MOBILE_SIZE_THRESHOLD = {{ gcodeMobileThreshold|e }};
var SOCKJS_URI = "{{ url_for('index') }}" + "sockjs";
var SOCKJS_DEBUG = CONFIG_DEBUG;
// sockjs should define CLOSE_NORMAL for us, but they don't (from ws spec)
var SOCKJS_CLOSE_NORMAL = 1000
var SOCKJS_CLOSE_NORMAL = 1000;
var UI_API_KEY = "{{ uiApiKey }}";
var VERSION = "{{ version }}";
var DISPLAY_VERSION = "{{ display_version }}";
var LOCALE = "{{ g.locale }}";
var UI_API_KEY = "{{ uiApiKey|e }}";
var VERSION = "{{ version|e }}";
var DISPLAY_VERSION = "{{ display_version|e }}";
var BRANCH = "{{ branch|e }}";
var LOCALE = "{{ g.locale|e }}";
var AVAILABLE_LOCALES = {{ locales|tojson }};
var OCTOPRINT_VIEWMODELS = [];
var ADDITIONAL_VIEWMODELS = [];
var OCTOPRINT_ADDITIONAL_BINDINGS = [];
{% if templates.tab.order %}
{% set first_tab = templates.tab.order[0] %}
{% set entry, data = templates.tab.entries[first_tab] %}
var OCTOPRINT_INITIAL_TAB = "#{{ data._div }}";
{% else %}
var OCTOPRINT_INITIAL_TAB = undefined;
{% endif %}
</script>
+1 -1
View File
@@ -10,7 +10,7 @@
<label class="checkbox">
<input type="checkbox" id="login_remember" data-bind="checked: loginState.loginRemember"> {{ _('Remember me') }}
</label>
<button class="btn btn-block btn-primary" id="login_button" data-bind="click: loginState.login">{{ _('Login') }}</button>
<button class="btn btn-block btn-primary" id="login_button" data-bind="click: function() { loginState.login(); }">{{ _('Login') }}</button>
</div>
<ul id="login_dropdown_loggedin" class="hide" data-bind="css: {hide: !loginState.loggedIn(), 'dropdown-menu': loginState.loggedIn()}">
<li><a href="#" id="usersettings_button" data-bind="click: function() { usersettings.show(); }">{{ _('User Settings') }}</a></li>
+10 -10
View File
@@ -10,11 +10,11 @@
<div class="size">{{ _('Size') }}: <span data-bind="text: formatSize(size)"></span></div>
<div class="additionalInfo hide" data-bind="html: $root.getAdditionalData($data)"></div>
<div class="btn-group action-buttons">
<div class="btn btn-mini toggleAdditionalData" data-bind="click: function() { if ($root.enableAdditionalData($data)) { $root.toggleAdditionalData($data); } else { return; } }, css: { disabled: !$root.enableAdditionalData($data) }"><i class="icon-chevron-down"></i></div>
<a class="btn btn-mini" data-bind="attr: {href: $root.downloadLink($data), css: {disabled: !$root.downloadLink($data)}}"><i class="icon-download-alt" title="{{ _('Download') }}"></i></a>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableRemove($data)) { $root.removeFile($data); } else { return; } }, css: {disabled: !$root.enableRemove($data)}"><i class="icon-trash" title="{{ _('Remove') }}"></i></div>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, false); } else { return; } }, css: {disabled: !$root.enableSelect($data)}"><i class="icon-folder-open" title="{{ _('Load') }}"></i></div>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, true); } else { return; } }, css: {disabled: !$root.enableSelect($data)}"><i class="icon-print" title="{{ _('Load and Print') }}"></i></div>
<div class="btn btn-mini toggleAdditionalData" data-bind="click: function() { if ($root.enableAdditionalData($data)) { $root.toggleAdditionalData($data); } else { return; } }, css: { disabled: !$root.enableAdditionalData($data) }" title="{{ _('Additional data') }}"><i class="icon-chevron-down"></i></div>
<a class="btn btn-mini" data-bind="attr: {href: $root.downloadLink($data), css: {disabled: !$root.downloadLink($data)}}" title="{{ _('Download') }}"><i class="icon-download-alt"></i></a>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableRemove($data)) { $root.removeFile($data); } else { return; } }, css: {disabled: !$root.enableRemove($data)}" title="{{ _('Remove') }}"><i class="icon-trash"></i></div>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, false); } else { return; } }, css: {disabled: !$root.enableSelect($data)}" title="{{ _('Load') }}"><i class="icon-folder-open"></i></div>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, true); } else { return; } }, css: {disabled: !$root.enableSelect($data)}" title="{{ _('Load and Print') }}"><i class="icon-print"></i></div>
</div>
</script>
@@ -23,9 +23,9 @@
<div class="uploaded">{{ _('Uploaded') }}: <span data-bind="text: formatTimeAgo(date)"></span></div>
<div class="size">{{ _('Size') }}: <span data-bind="text: formatSize(size)"></span></div>
<div class="btn-group action-buttons">
<a class="btn btn-mini" data-bind="attr: {href: $root.downloadLink($data), css: {disabled: !$root.downloadLink($data)}}"><i class="icon-download-alt" title="{{ _('Download') }}"></i></a>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableRemove($data)) { $root.removeFile($data); } else { return; } }, css: {disabled: !$root.enableRemove($data)}"><i class="icon-trash" title="{{ _('Remove') }}"></i></div>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSlicing($data)) { $root.sliceFile($data); } else { return; } }, css: {disabled: !$root.enableSlicing($data)}"><i class="icon-magic" title="{{ _('Slice') }}"></i></div>
<a class="btn btn-mini" data-bind="attr: {href: $root.downloadLink($data), css: {disabled: !$root.downloadLink($data)}}" title="{{ _('Download') }}"><i class="icon-download-alt"></i></a>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableRemove($data)) { $root.removeFile($data); } else { return; } }, css: {disabled: !$root.enableRemove($data)}" title="{{ _('Remove') }}"><i class="icon-trash"></i></div>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSlicing($data)) { $root.sliceFile($data); } else { return; } }, css: {disabled: !$root.enableSlicing($data)}" title="{{ _('Slice') }}"><i class="icon-magic"></i></div>
</div>
</script>
@@ -33,8 +33,8 @@
<div class="title" data-bind="text: name"></div>
</script>
</div>
<div class="muted text-right">
<small>{{ _('Free') }}: <span data-bind="text: freeSpaceString"></span></small>
<div class="text-right muted" data-bind="attr: {title: diskusageString}, css: {'text-error': diskusageCritical}, style: {'font-weight': diskusageCritical() || diskusageWarning() ? 'bold' : 'normal'}">
<small>{{ _('Free') }}: <span data-bind="text: freeSpaceString"></span> / {{ _('Total') }}: <span data-bind="text: totalSpaceString"></span> <i class="icon-exclamation-sign" data-bind="visible: diskusageWarning" style="display: none"></i></small>
</div>
<div style="display: none;" data-bind="visible: loginState.isUser">
<div class="row-fluid upload-buttons">
@@ -1,5 +1,5 @@
{% if enableTemperatureGraph %}
<div class="row" style="padding-left: 20px">
<div class="row-fluid">
<div id="temperature-graph"></div>
</div>
{% endif %}
+1 -1
View File
@@ -1,5 +1,5 @@
<div class="terminal">
<pre id="terminal-output" class="pre-scrollable" data-bind="foreach: displayedLines"><span data-bind="text: line, css: {muted: type == 'filtered'}"></span><br></pre>
<pre id="terminal-output" class="pre-scrollable" data-bind="foreach: displayedLines"><span data-bind="text: line, css: {muted: type == 'filtered' || type == 'cut'}"></span><br></pre>
<small class="pull-left"><button class="btn btn-mini" data-bind="click: toggleAutoscroll, css: {active: autoscrollEnabled}">{{ _('Autoscroll') }}</button> <span data-bind="text: lineCount"></span></small>
<small class="pull-right"><a href="#" data-bind="click: scrollToEnd">{{ _("Scroll to end") }}</a>&nbsp;|&nbsp;<a href="#" data-bind="click: selectAll">{{ _("Select all") }}</a></small>
</div>
@@ -1,12 +1,17 @@
<div style="display: none;" data-bind="visible: loginState.isUser">
<div class="alert" data-bind="visible: isPrinting()">
{{ _('Take note that timelapse configuration is disabled while your printer is printing.') }}
</div>
<h1>{{ _('Timelapse Configuration') }}</h1>
<label for="webcam_timelapse_mode">{{ _('Timelapse Mode') }}</label>
<select id="webcam_timelapse_mode" data-bind="value: timelapseType, enable: isOperational() && !isPrinting() && loginState.isUser()">
<option value="off">{{ _('Off') }}</option>
<option value="zchange">{{ _('On Z Change') }}</option>
<option value="timed">{{ _('Timed') }}</option>
<option value="zchange">{{ _('On Z Change') }}</option>
</select>
<span class="help-block" data-bind="visible: timelapseType() == 'zchange'"><span class="label label-warning">{{ _('Warning') }}</span> {{ _('Do not use with spiralized ("Joris") vases or similar continuous Z models.') }}</span>
<span class="help-block" data-bind="visible: timelapseType() == 'zchange'"><span class="label label-info">{{ _('Note') }}</span> {% trans %}Does not work when printing from the printer's SD Card (no way to detect the change in Z reliably). Use "Timed" mode for those prints instead.{% endtrans %}</span>
<label for="webcam_timelapse_fps">{{ _('Timelapse frame rate (in frames per second)') }}</label>
<div class="input-append">
+207 -135
View File
@@ -6,13 +6,13 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
import logging
import os
import threading
import urllib
import time
import subprocess
import fnmatch
import datetime
import sys
import shutil
import Queue
import requests
import octoprint.util as util
@@ -58,7 +58,7 @@ def notifyCallbacks(timelapse):
if timelapse is None:
config = None
else:
config = timelapse.configData()
config = timelapse.config_data()
for callback in updateCallbacks:
try: callback.sendTimelapseConfig(config)
except: logging.getLogger(__name__).exception("Exception while pushing timelapse configuration")
@@ -86,12 +86,12 @@ def configureTimelapse(config=None, persist=False):
if type is None or "off" == type:
current = None
elif "zchange" == type:
current = ZTimelapse(postRoll=postRoll, fps=fps)
current = ZTimelapse(post_roll=postRoll, fps=fps)
elif "timed" == type:
interval = 10
if "options" in config and "interval" in config["options"] and config["options"]["interval"] > 0:
interval = config["options"]["interval"]
current = TimedTimelapse(postRoll=postRoll, interval=interval, fps=fps)
current = TimedTimelapse(post_roll=postRoll, interval=interval, fps=fps)
notifyCallbacks(current)
@@ -101,72 +101,83 @@ def configureTimelapse(config=None, persist=False):
class Timelapse(object):
def __init__(self, postRoll=0, fps=25):
QUEUE_ENTRY_TYPE_CAPTURE = "capture"
QUEUE_ENTRY_TYPE_CALLBACK = "callback"
def __init__(self, post_roll=0, fps=25):
self._logger = logging.getLogger(__name__)
self._imageNumber = None
self._inTimelapse = False
self._gcodeFile = None
self._image_number = None
self._in_timelapse = False
self._gcode_file = None
self._postRoll = postRoll
self._postRollStart = None
self._onPostRollDone = None
self._post_roll = post_roll
self._on_post_roll_done = None
self._captureDir = settings().getBaseFolder("timelapse_tmp")
self._movieDir = settings().getBaseFolder("timelapse")
self._snapshotUrl = settings().get(["webcam", "snapshot"])
self._ffmpegThreads = settings().get(["webcam", "ffmpegThreads"])
self._capture_dir = settings().getBaseFolder("timelapse_tmp")
self._movie_dir = settings().getBaseFolder("timelapse")
self._snapshot_url = settings().get(["webcam", "snapshot"])
self._ffmpeg_threads = settings().get(["webcam", "ffmpegThreads"])
self._fps = fps
self._renderThread = None
self._captureMutex = threading.Lock()
self._render_thread = None
self._capture_mutex = threading.Lock()
self._capture_queue = Queue.Queue()
self._capture_queue_active = True
self._capture_queue_thread = threading.Thread(target=self._capture_queue_worker)
self._capture_queue_thread.daemon = True
self._capture_queue_thread.start()
# subscribe events
eventManager().subscribe(Events.PRINT_STARTED, self.onPrintStarted)
eventManager().subscribe(Events.PRINT_FAILED, self.onPrintDone)
eventManager().subscribe(Events.PRINT_DONE, self.onPrintDone)
eventManager().subscribe(Events.PRINT_RESUMED, self.onPrintResumed)
for (event, callback) in self.eventSubscriptions():
eventManager().subscribe(Events.PRINT_STARTED, self.on_print_started)
eventManager().subscribe(Events.PRINT_FAILED, self.on_print_done)
eventManager().subscribe(Events.PRINT_DONE, self.on_print_done)
eventManager().subscribe(Events.PRINT_RESUMED, self.on_print_resumed)
for (event, callback) in self.event_subscriptions():
eventManager().subscribe(event, callback)
def postRoll(self):
return self._postRoll
@property
def post_roll(self):
return self._post_roll
@property
def fps(self):
return self._fps
def unload(self):
if self._inTimelapse:
self.stopTimelapse(doCreateMovie=False)
if self._in_timelapse:
self.stop_timelapse(doCreateMovie=False)
# unsubscribe events
eventManager().unsubscribe(Events.PRINT_STARTED, self.onPrintStarted)
eventManager().unsubscribe(Events.PRINT_FAILED, self.onPrintDone)
eventManager().unsubscribe(Events.PRINT_DONE, self.onPrintDone)
eventManager().unsubscribe(Events.PRINT_RESUMED, self.onPrintResumed)
for (event, callback) in self.eventSubscriptions():
eventManager().unsubscribe(Events.PRINT_STARTED, self.on_print_started)
eventManager().unsubscribe(Events.PRINT_FAILED, self.on_print_done)
eventManager().unsubscribe(Events.PRINT_DONE, self.on_print_done)
eventManager().unsubscribe(Events.PRINT_RESUMED, self.on_print_resumed)
for (event, callback) in self.event_subscriptions():
eventManager().unsubscribe(event, callback)
def onPrintStarted(self, event, payload):
def on_print_started(self, event, payload):
"""
Override this to perform additional actions upon start of a print job.
"""
self.startTimelapse(payload["file"])
self.start_timelapse(payload["file"])
def onPrintDone(self, event, payload):
def on_print_done(self, event, payload):
"""
Override this to perform additional actions upon the stop of a print job.
"""
self.stopTimelapse(success=(event==Events.PRINT_DONE))
self.stop_timelapse(success=(event==Events.PRINT_DONE))
def onPrintResumed(self, event, payload):
def on_print_resumed(self, event, payload):
"""
Override this to perform additional actions upon the pausing of a print job.
"""
if not self._inTimelapse:
self.startTimelapse(payload["file"])
if not self._in_timelapse:
self.start_timelapse(payload["file"])
def eventSubscriptions(self):
def event_subscriptions(self):
"""
Override this method to subscribe to additional events by returning an array of (event, callback) tuples.
@@ -178,7 +189,7 @@ class Timelapse(object):
"""
return []
def configData(self):
def config_data(self):
"""
Override this method to return the current timelapse configuration data. The data should have the following
form:
@@ -188,105 +199,153 @@ class Timelapse(object):
"""
return None
def startTimelapse(self, gcodeFile):
def start_timelapse(self, gcodeFile):
self._logger.debug("Starting timelapse for %s" % gcodeFile)
self.cleanCaptureDir()
self.clean_capture_dir()
self._imageNumber = 0
self._inTimelapse = True
self._gcodeFile = os.path.basename(gcodeFile)
self._image_number = 0
self._in_timelapse = True
self._gcode_file = os.path.basename(gcodeFile)
def stopTimelapse(self, doCreateMovie=True, success=True):
def stop_timelapse(self, doCreateMovie=True, success=True):
self._logger.debug("Stopping timelapse")
self._inTimelapse = False
self._in_timelapse = False
def resetImageNumber():
self._imageNumber = None
self._image_number = None
def createMovie():
self._renderThread = threading.Thread(target=self._createMovie, kwargs={"success": success})
self._renderThread.daemon = True
self._renderThread.start()
self._render_thread = threading.Thread(target=self._create_movie, kwargs={"success": success})
self._render_thread.daemon = True
self._render_thread.start()
def resetAndCreate():
resetImageNumber()
createMovie()
if self._postRoll > 0:
self._postRollStart = time.time()
def waitForCaptures(callback):
self._capture_queue.put(dict(type=self.__class__.QUEUE_ENTRY_TYPE_CALLBACK, callback=callback))
def getWaitForCaptures(callback):
def f():
waitForCaptures(callback)
return f
if self._post_roll > 0:
eventManager().fire(Events.POSTROLL_START, dict(postroll_duration=self.calculate_post_roll(), postroll_length=self.post_roll, postroll_fps=self.fps))
self._post_roll_start = time.time()
if doCreateMovie:
self._onPostRollDone = resetAndCreate
self._on_post_roll_done = getWaitForCaptures(resetAndCreate)
else:
self._onPostRollDone = resetImageNumber
self.processPostRoll()
self._on_post_roll_done = resetImageNumber
self.process_post_roll()
else:
self._postRollStart = None
self._post_roll_start = None
if doCreateMovie:
resetAndCreate()
waitForCaptures(resetAndCreate)
else:
resetImageNumber()
def processPostRoll(self):
pass
def calculate_post_roll(self):
return None
def process_post_roll(self):
self.post_roll_finished()
def post_roll_finished(self):
if self.post_roll:
eventManager().fire(Events.POSTROLL_END)
if self._on_post_roll_done is not None:
self._on_post_roll_done()
def captureImage(self):
if self._captureDir is None:
if self._capture_dir is None:
self._logger.warn("Cannot capture image, capture directory is unset")
return
if self._imageNumber is None:
self._logger.warn("Cannot capture image, image number is unset")
return
with self._capture_mutex:
if self._image_number is None:
self._logger.warn("Cannot capture image, image number is unset")
return
filename = os.path.join(self._capture_dir, "tmp_%05d.jpg" % self._image_number)
self._image_number += 1
with self._captureMutex:
filename = os.path.join(self._captureDir, "tmp_%05d.jpg" % self._imageNumber)
self._imageNumber += 1
self._logger.debug("Capturing image to %s" % filename)
captureThread = threading.Thread(target=self._captureWorker, kwargs={"filename": filename})
captureThread.daemon = True
captureThread.start()
entry = dict(type=self.__class__.QUEUE_ENTRY_TYPE_CAPTURE,
filename=filename,
onerror=self._on_capture_error)
self._capture_queue.put(entry)
return filename
def _captureWorker(self, filename):
def _on_capture_error(self):
with self._capture_mutex:
if self._image_number is not None and self._image_number > 0:
self._image_number -= 1
def _capture_queue_worker(self):
while self._capture_queue_active:
entry = self._capture_queue.get(block=True)
if entry["type"] == self.__class__.QUEUE_ENTRY_TYPE_CAPTURE and "filename" in entry:
filename = entry["filename"]
onerror = entry.pop("onerror", None)
self._perform_capture(filename, onerror=onerror)
elif entry["type"] == self.__class__.QUEUE_ENTRY_TYPE_CALLBACK and "callback" in entry:
args = entry.pop("args", [])
kwargs = entry.pop("kwargs", dict())
entry["callback"](*args, **kwargs)
def _perform_capture(self, filename, onerror=None):
eventManager().fire(Events.CAPTURE_START, {"file": filename})
try:
urllib.urlretrieve(self._snapshotUrl, filename)
self._logger.debug("Image %s captured from %s" % (filename, self._snapshotUrl))
self._logger.debug("Going to capture %s from %s" % (filename, self._snapshot_url))
r = requests.get(self._snapshot_url, stream=True)
with open (filename, "wb") as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
f.flush()
self._logger.debug("Image %s captured from %s" % (filename, self._snapshot_url))
except:
self._logger.exception("Could not capture image %s from %s, decreasing image counter again" % (filename, self._snapshotUrl))
with self._captureMutex:
if self._imageNumber is not None and self._imageNumber > 0:
self._imageNumber -= 1
eventManager().fire(Events.CAPTURE_DONE, {"file": filename})
self._logger.exception("Could not capture image %s from %s" % (filename, self._snapshot_url))
if callable(onerror):
onerror()
eventManager().fire(Events.CAPTURE_FAILED, {"file": filename})
return False
else:
eventManager().fire(Events.CAPTURE_DONE, {"file": filename})
return True
def _createMovie(self, success=True):
def _create_movie(self, success=True):
ffmpeg = settings().get(["webcam", "ffmpeg"])
bitrate = settings().get(["webcam", "bitrate"])
if ffmpeg is None or bitrate is None:
self._logger.warn("Cannot create movie, path to ffmpeg or desired bitrate is unset")
return
input = os.path.join(self._captureDir, "tmp_%05d.jpg")
input = os.path.join(self._capture_dir, "tmp_%05d.jpg")
if success:
output = os.path.join(self._movieDir, "%s_%s.mpg" % (os.path.splitext(self._gcodeFile)[0], time.strftime("%Y%m%d%H%M%S")))
output = os.path.join(self._movie_dir, "%s_%s.mpg" % (os.path.splitext(self._gcode_file)[0], time.strftime("%Y%m%d%H%M%S")))
else:
output = os.path.join(self._movieDir, "%s_%s-failed.mpg" % (os.path.splitext(self._gcodeFile)[0], time.strftime("%Y%m%d%H%M%S")))
output = os.path.join(self._movie_dir, "%s_%s-failed.mpg" % (os.path.splitext(self._gcode_file)[0], time.strftime("%Y%m%d%H%M%S")))
# prepare ffmpeg command
command = [
ffmpeg, '-framerate', str(self._fps), '-loglevel', 'error', '-i', input, '-vcodec', 'mpeg2video', '-threads', str(self._ffmpegThreads), '-pix_fmt', 'yuv420p', '-r', str(self._fps), '-y', '-b', bitrate,
ffmpeg, '-framerate', str(self._fps), '-loglevel', 'error', '-i', input, '-vcodec', 'mpeg2video', '-threads', str(self._ffmpeg_threads), '-pix_fmt', 'yuv420p', '-r', str(self._fps), '-y', '-b', bitrate,
'-f', 'vob']
filters = []
# flip video if configured
if settings().getBoolean(["webcam", "rotate90"]):
filters.append('transpose=1')
if settings().getBoolean(["webcam", "flipH"]):
filters.append('hflip')
if settings().getBoolean(["webcam", "flipV"]):
filters.append('vflip')
if settings().getBoolean(["webcam", "rotate90"]):
filters.append('transpose=2')
# add watermark if configured
watermarkFilter = None
@@ -315,7 +374,7 @@ class Timelapse(object):
# finalize command with output file
self._logger.debug("Rendering movie to %s" % output)
command.append("\"" + output + "\"")
eventManager().fire(Events.MOVIE_RENDERING, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output)})
eventManager().fire(Events.MOVIE_RENDERING, {"gcode": self._gcode_file, "movie": output, "movie_basename": os.path.basename(output)})
command_str = " ".join(command)
self._logger.debug("Executing command: %s" % command_str)
@@ -323,75 +382,74 @@ class Timelapse(object):
try:
p = sarge.run(command_str, stderr=sarge.Capture())
if p.returncode == 0:
eventManager().fire(Events.MOVIE_DONE, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output)})
eventManager().fire(Events.MOVIE_DONE, {"gcode": self._gcode_file, "movie": output, "movie_basename": os.path.basename(output)})
else:
returncode = p.returncode
stderr_text = p.stderr.text
self._logger.warn("Could not render movie, got return code %r: %s" % (returncode, stderr_text))
eventManager().fire(Events.MOVIE_FAILED, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output), "returncode": returncode, "error": stderr_text})
eventManager().fire(Events.MOVIE_FAILED, {"gcode": self._gcode_file, "movie": output, "movie_basename": os.path.basename(output), "returncode": returncode, "error": stderr_text})
except:
self._logger.exception("Could not render movie due to unknown error")
eventManager().fire(Events.MOVIE_FAILED, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output), "returncode": 255, "error": "Unknown error"})
eventManager().fire(Events.MOVIE_FAILED, {"gcode": self._gcode_file, "movie": output, "movie_basename": os.path.basename(output), "returncode": 255, "error": "Unknown error"})
def cleanCaptureDir(self):
if not os.path.isdir(self._captureDir):
def clean_capture_dir(self):
if not os.path.isdir(self._capture_dir):
self._logger.warn("Cannot clean capture directory, it is unset")
return
for filename in os.listdir(self._captureDir):
for filename in os.listdir(self._capture_dir):
if not fnmatch.fnmatch(filename, "*.jpg"):
continue
os.remove(os.path.join(self._captureDir, filename))
os.remove(os.path.join(self._capture_dir, filename))
class ZTimelapse(Timelapse):
def __init__(self, postRoll=0, fps=25):
Timelapse.__init__(self, postRoll=postRoll, fps=fps)
def __init__(self, post_roll=0, fps=25):
Timelapse.__init__(self, post_roll=post_roll, fps=fps)
self._logger.debug("ZTimelapse initialized")
def eventSubscriptions(self):
def event_subscriptions(self):
return [
(Events.Z_CHANGE, self._onZChange)
(Events.Z_CHANGE, self._on_z_change)
]
def configData(self):
def config_data(self):
return {
"type": "zchange"
}
def processPostRoll(self):
Timelapse.processPostRoll(self)
def process_post_roll(self):
with self._capture_mutex:
filename = os.path.join(self._capture_dir, "tmp_%05d.jpg" % self._image_number)
self._image_number += 1
filename = os.path.join(self._captureDir, "tmp_%05d.jpg" % self._imageNumber)
self._imageNumber += 1
with self._captureMutex:
self._captureWorker(filename)
if self._perform_capture(filename):
for _ in range(self._post_roll * self._fps):
newFile = os.path.join(self._capture_dir, "tmp_%05d.jpg" % self._image_number)
self._image_number += 1
shutil.copyfile(filename, newFile)
for i in range(self._postRoll * self._fps):
newFile = os.path.join(self._captureDir, "tmp_%05d.jpg" % (self._imageNumber))
self._imageNumber += 1
shutil.copyfile(filename, newFile)
Timelapse.process_post_roll(self)
if self._onPostRollDone is not None:
self._onPostRollDone()
def _onZChange(self, event, payload):
def _on_z_change(self, event, payload):
self.captureImage()
class TimedTimelapse(Timelapse):
def __init__(self, postRoll=0, interval=1, fps=25):
Timelapse.__init__(self, postRoll=postRoll, fps=fps)
def __init__(self, post_roll=0, interval=1, fps=25):
Timelapse.__init__(self, post_roll=post_roll, fps=fps)
self._interval = interval
if self._interval < 1:
self._interval = 1 # force minimum interval of 1s
self._timerThread = None
self._postroll_captures = 0
self._timer = None
self._logger.debug("TimedTimelapse initialized")
@property
def interval(self):
return self._interval
def configData(self):
def config_data(self):
return {
"type": "timed",
"options": {
@@ -399,25 +457,39 @@ class TimedTimelapse(Timelapse):
}
}
def onPrintStarted(self, event, payload):
Timelapse.onPrintStarted(self, event, payload)
if self._timerThread is not None:
def on_print_started(self, event, payload):
Timelapse.on_print_started(self, event, payload)
if self._timer is not None:
return
self._timerThread = threading.Thread(target=self._timerWorker)
self._timerThread.daemon = True
self._timerThread.start()
def onPrintDone(self, event, payload):
Timelapse.onPrintDone(self, event, payload)
self._timerThread = None
def _timerWorker(self):
self._logger.debug("Starting timer for interval based timelapse")
while self._inTimelapse or (self._postRollStart and time.time() - self._postRollStart <= self._postRoll * self._fps):
self.captureImage()
time.sleep(self._interval)
from octoprint.util import RepeatedTimer
self._timer = RepeatedTimer(self._interval, self._timer_task,
run_first=True, condition=self._timer_active,
on_finish=self._on_timer_finished)
self._timer.start()
if self._postRollStart is not None and self._onPostRollDone is not None:
self._onPostRollDone()
self._postRollStart = None
def on_print_done(self, event, payload):
self._postroll_captures = self.post_roll * self.fps
Timelapse.on_print_done(self, event, payload)
def calculate_post_roll(self):
return self.post_roll * self.fps * self.interval
def process_post_roll(self):
pass
def post_roll_finished(self):
Timelapse.post_roll_finished(self)
self._timer = None
def _timer_active(self):
return self._in_timelapse or self._postroll_captures > 0
def _timer_task(self):
self.captureImage()
if self._postroll_captures > 0:
self._postroll_captures -= 1
def _on_timer_finished(self):
self.post_roll_finished()
File diff suppressed because it is too large. Load diff
+39 -29
View File
@@ -17,29 +17,37 @@ import logging
from octoprint.settings import settings
from octoprint.util import atomic_write
class UserManager(object):
valid_roles = ["user", "admin"]
def __init__(self):
self._logger = logging.getLogger(__name__)
self._session_users_by_session = dict()
self._session_users_by_username = dict()
self._session_users_by_userid = dict()
def login_user(self, user):
self._cleanup_sessions()
if user is None \
or (isinstance(user, LocalProxy) and not isinstance(user._get_current_object(), User)) \
or (not isinstance(user, LocalProxy) and not isinstance(user, User)):
if user is None:
return
if isinstance(user, LocalProxy):
user = user._get_current_object()
if not isinstance(user, User):
return None
if not isinstance(user, SessionUser):
user = SessionUser(user)
self._session_users_by_session[user.get_session()] = user
if not user.get_name() in self._session_users_by_username:
self._session_users_by_username[user.get_name()] = []
self._session_users_by_username[user.get_name()].append(user)
userid = user.get_id()
if not userid in self._session_users_by_userid:
self._session_users_by_userid[userid] = []
self._session_users_by_userid[userid].append(user)
self._logger.debug("Logged in user: %r" % user)
@@ -49,14 +57,18 @@ class UserManager(object):
if user is None:
return
if isinstance(user, LocalProxy):
user = user._get_current_object()
if not isinstance(user, SessionUser):
return
if user.get_name() in self._session_users_by_username:
users_by_username = self._session_users_by_username[user.get_name()]
for u in users_by_username:
userid = user.get_id()
if userid in self._session_users_by_userid:
users_by_userid = self._session_users_by_userid[userid]
for u in users_by_userid:
if u.get_session() == user.get_session():
users_by_username.remove(u)
users_by_userid.remove(u)
break
if user.get_session() in self._session_users_by_session:
@@ -137,21 +149,19 @@ class UserManager(object):
pass
def removeUser(self, username):
if username in self._session_users_by_username:
users = self._session_users_by_username[username]
if username in self._session_users_by_userid:
users = self._session_users_by_userid[username]
sessions = [user.get_session() for user in users if isinstance(user, SessionUser)]
for session in sessions:
if session in self._session_users_by_session:
del self._session_users_by_session[session]
del self._session_users_by_username[username]
del self._session_users_by_userid[username]
def findUser(self, username=None, session=None):
if session is not None:
for session in self._session_users_by_session:
user = self._session_users_by_session[session]
if username is None or username == user.get_name():
return user
break
def findUser(self, userid=None, session=None):
if session is not None and session in self._session_users_by_session:
user = self._session_users_by_session[session]
if userid is None or userid == user.get_id():
return user
return None
@@ -209,7 +219,7 @@ class FilebasedUserManager(UserManager):
"settings": user._settings
}
with open(self._userfile, "wb") as f:
with atomic_write(self._userfile, "wb") as f:
yaml.safe_dump(data, f, default_flow_style=False, indent=" ", allow_unicode=True)
self._dirty = False
self._load()
@@ -345,16 +355,16 @@ class FilebasedUserManager(UserManager):
self._dirty = True
self._save()
def findUser(self, username=None, apikey=None, session=None):
user = UserManager.findUser(self, username=username, session=session)
def findUser(self, userid=None, apikey=None, session=None):
user = UserManager.findUser(self, userid=userid, session=session)
if user is not None:
return user
if username is not None:
if username not in self._users.keys():
if userid is not None:
if userid not in self._users.keys():
return None
return self._users[username]
return self._users[userid]
elif apikey is not None:
for user in self._users.values():
@@ -413,7 +423,7 @@ class User(UserMixin):
return self._passwordHash == passwordHash
def get_id(self):
return self._username
return self.get_name()
def get_name(self):
return self._username
@@ -474,7 +484,7 @@ class User(UserMixin):
class SessionUser(User):
def __init__(self, user):
User.__init__(self, user._username, user._passwordHash, user._active, user._roles, user._apikey)
User.__init__(self, user._username, user._passwordHash, user._active, user._roles, user._apikey, user._settings)
import string
import random
+211 -45
View File
@@ -17,7 +17,7 @@ import shutil
import threading
from functools import wraps
import warnings
import contextlib
logger = logging.getLogger(__name__)
@@ -197,29 +197,12 @@ def get_exception_string():
return "%s: '%s' @ %s:%s:%d" % (str(sys.exc_info()[0].__name__), str(sys.exc_info()[1]), os.path.basename(locationInfo[0]), locationInfo[2], locationInfo[1])
@deprecated("get_free_bytes has been deprecated and will be removed in the future",
includedoc="Replaced by `psutil.disk_usage <http://pythonhosted.org/psutil/#psutil.disk_usage>`_.",
since="1.2.5")
def get_free_bytes(path):
"""
Retrieves the number of free bytes on the partition ``path`` is located at and returns it. Works on both Windows and
Unix/Linux.
Taken from http://stackoverflow.com/a/2372171/2028598
Arguments:
path (string): The path for which to check the remaining partition space.
Returns:
int: The amount of bytes still left on the partition.
"""
path = os.path.abspath(path)
if sys.platform == "win32":
import ctypes
freeBytes = ctypes.c_ulonglong(0)
ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(path), None, None, ctypes.pointer(freeBytes))
return freeBytes.value
else:
st = os.statvfs(path)
return st.f_bavail * st.f_frsize
import psutil
return psutil.disk_usage(path).free
def get_dos_filename(origin, existing_filenames=None, extension=None, **kwargs):
@@ -352,9 +335,7 @@ def silent_remove(file):
def sanitize_ascii(line):
if not isinstance(line, basestring):
raise ValueError("Expected either str or unicode but got {} instead".format(line.__class__.__name__ if line is not None else None))
if isinstance(line, str):
line = unicode(line, 'ascii', 'replace')
return line.encode('ascii', 'replace').rstrip()
return to_unicode(line, encoding="ascii", errors="replace").rstrip()
def filter_non_ascii(line):
@@ -369,18 +350,42 @@ def filter_non_ascii(line):
"""
try:
unicode(line, 'ascii').encode('ascii')
to_str(to_unicode(line, encoding="ascii"), encoding="ascii")
return False
except ValueError:
return True
def to_str(s_or_u, encoding="utf-8", errors="strict"):
"""Make sure ``s_or_u`` is a str."""
if isinstance(s_or_u, unicode):
return s_or_u.encode(encoding, errors=errors)
else:
return s_or_u
def to_unicode(s_or_u, encoding="utf-8", errors="strict"):
"""Make sure ``s_or_u`` is a unicode string."""
if isinstance(s_or_u, str):
return s_or_u.decode(encoding, errors=errors)
else:
return s_or_u
def dict_merge(a, b):
"""
Recursively deep-merges two dictionaries.
Taken from https://www.xormedia.com/recursively-merge-dictionaries-in-python/
Example::
>>> a = dict(foo="foo", bar="bar", fnord=dict(a=1))
>>> b = dict(foo="other foo", fnord=dict(b=2, l=["some", "list"]))
>>> expected = dict(foo="other foo", bar="bar", fnord=dict(a=1, b=2, l=["some", "list"]))
>>> dict_merge(a, b) == expected
True
Arguments:
a (dict): The dictionary to merge ``b`` into
b (dict): The dictionary to merge into ``a``
@@ -402,14 +407,24 @@ def dict_merge(a, b):
return result
def dict_clean(a, b):
def dict_sanitize(a, b):
"""
Recursively deep-cleans ``b`` from ``a``, removing all keys and corresponding values from ``a`` that appear in
``b``.
Recursively deep-sanitizes ``a`` based on ``b``, removing all keys (and
associated values) from ``a`` that do not appear in ``b``.
Example::
>>> a = dict(foo="foo", bar="bar", fnord=dict(a=1, b=2, l=["some", "list"]))
>>> b = dict(foo=None, fnord=dict(a=None, b=None))
>>> expected = dict(foo="foo", fnord=dict(a=1, b=2))
>>> dict_sanitize(a, b) == expected
True
>>> dict_clean(a, b) == expected
True
Arguments:
a (dict): The dictionary to clean from ``b``.
b (dict): The dictionary to clean ``b`` from.
a (dict): The dictionary to clean against ``b``.
b (dict): The dictionary containing the key structure to clean from ``a``.
Results:
dict: A new dict based on ``a`` with all keys (and corresponding values) found in ``b`` removed.
@@ -424,21 +439,87 @@ def dict_clean(a, b):
if not k in b:
del result[k]
elif isinstance(v, dict):
result[k] = dict_clean(v, b[k])
result[k] = dict_sanitize(v, b[k])
else:
result[k] = deepcopy(v)
return result
dict_clean = deprecated("dict_clean has been renamed to dict_sanitize",
includedoc="Replaced by :func:`dict_sanitize`")(dict_sanitize)
def dict_contains_keys(a, b):
def dict_minimal_mergediff(source, target):
"""
Recursively deep-checks if ``a`` contains all keys found in ``b``.
Recursively calculates the minimal dict that would be needed to be deep merged with
a in order to produce the same result as deep merging a and b.
Example::
>>> dict_contains_keys(dict(foo="bar", fnord=dict(a=1, b=2, c=3)), dict(foo="some_other_bar", fnord=dict(b=100)))
>>> a = dict(foo=dict(a=1, b=2), bar=dict(c=3, d=4))
>>> b = dict(bar=dict(c=3, d=5), fnord=None)
>>> c = dict_minimal_mergediff(a, b)
>>> c == dict(bar=dict(d=5), fnord=None)
True
>>> dict_contains_keys(dict(foo="bar", fnord=dict(a=1, b=2, c=3)), dict(foo="some_other_bar", fnord=dict(b=100, d=20)))
>>> dict_merge(a, c) == dict_merge(a, b)
True
Arguments:
source (dict): Source dictionary
target (dict): Dictionary to compare to source dictionary and derive diff for
Returns:
dict: The minimal dictionary to deep merge on ``source`` to get the same result
as deep merging ``target`` on ``source``.
"""
if not isinstance(source, dict) or not isinstance(target, dict):
raise ValueError("source and target must be dictionaries")
if source == target:
# shortcut: if both are equal, we return an empty dict as result
return dict()
from copy import deepcopy
all_keys = set(source.keys() + target.keys())
result = dict()
for k in all_keys:
if k not in target:
# key not contained in target => not contained in result
continue
if k in source:
# key is present in both dicts, we have to take a look at the value
value_source = source[k]
value_target = target[k]
if value_source != value_target:
# we only need to look further if the values are not equal
if isinstance(value_source, dict) and isinstance(value_target, dict):
# both are dicts => deeper down it goes into the rabbit hole
result[k] = dict_minimal_mergediff(value_source, value_target)
else:
# new b wins over old a
result[k] = deepcopy(value_target)
else:
# key is new, add it
result[k] = deepcopy(target[k])
return result
def dict_contains_keys(keys, dictionary):
"""
Recursively deep-checks if ``dictionary`` contains all keys found in ``keys``.
Example::
>>> positive = dict(foo="some_other_bar", fnord=dict(b=100))
>>> negative = dict(foo="some_other_bar", fnord=dict(b=100, d=20))
>>> dictionary = dict(foo="bar", fnord=dict(a=1, b=2, c=3))
>>> dict_contains_keys(positive, dictionary)
True
>>> dict_contains_keys(negative, dictionary)
False
Arguments:
@@ -449,14 +530,14 @@ def dict_contains_keys(a, b):
boolean: True if all keys found in ``b`` are also present in ``a``, False otherwise.
"""
if not isinstance(a, dict) or not isinstance(b, dict):
if not isinstance(keys, dict) or not isinstance(dictionary, dict):
return False
for k, v in a.iteritems():
if not k in b:
for k, v in keys.iteritems():
if not k in dictionary:
return False
elif isinstance(v, dict):
if not dict_contains_keys(v, b[k]):
if not dict_contains_keys(v, dictionary[k]):
return False
return True
@@ -499,6 +580,65 @@ def address_for_client(host, port):
except:
continue
@contextlib.contextmanager
def atomic_write(filename, mode="w+b", prefix="tmp", suffix=""):
temp_config = tempfile.NamedTemporaryFile(mode=mode, prefix=prefix, suffix=suffix, delete=False)
try:
yield temp_config
finally:
temp_config.close()
shutil.move(temp_config.name, filename)
def bom_aware_open(filename, encoding="ascii", mode="r", **kwargs):
import codecs
codec = codecs.lookup(encoding)
encoding = codec.name
if kwargs is None:
kwargs = dict()
potential_bom_attribute = "BOM_" + codec.name.replace("utf-", "utf").upper()
if "r" in mode and hasattr(codecs, potential_bom_attribute):
# these encodings might have a BOM, so let's see if there is one
bom = getattr(codecs, potential_bom_attribute)
with open(filename, "rb") as f:
header = f.read(4)
if header.startswith(bom):
encoding += "-sig"
return codecs.open(filename, encoding=encoding, mode=mode, **kwargs)
def is_hidden_path(path):
if path is None:
# we define a None path as not hidden here
return False
filename = os.path.basename(path)
if filename.startswith("."):
# filenames starting with a . are hidden
return True
if sys.platform == "win32":
# if we are running on windows we also try to read the hidden file
# attribute via the windows api
try:
import ctypes
attrs = ctypes.windll.kernel32.GetFileAttributesW(unicode(path))
assert attrs != -1 # INVALID_FILE_ATTRIBUTES == -1
return bool(attrs & 2) # FILE_ATTRIBUTE_HIDDEN == 2
except (AttributeError, AssertionError):
pass
# if we reach that point, the path is not hidden
return False
class RepeatedTimer(threading.Thread):
"""
This class represents an action that should be run repeatedly in an interval. It is similar to python's
@@ -556,9 +696,18 @@ class RepeatedTimer(threading.Thread):
run_first (boolean): If set to True, the function will be run for the first time *before* the first wait period.
If set to False (the default), the function will be run for the first time *after* the first wait period.
condition (callable): Condition that needs to be True for loop to continue. Defaults to ``lambda: True``.
on_condition_false (callable): Callback to call when the timer finishes due to condition becoming false. Will
be called before the ``on_finish`` callback.
on_cancelled (callable): Callback to call when the timer finishes due to being cancelled. Will be called
before the ``on_finish`` callback.
on_finish (callable): Callback to call when the timer finishes, either due to being cancelled or since
the condition became false.
daemon (bool): daemon flag to set on underlying thread.
"""
def __init__(self, interval, function, args=None, kwargs=None, run_first=False, condition=None):
def __init__(self, interval, function, args=None, kwargs=None,
run_first=False, condition=None, on_condition_false=None,
on_cancelled=None, on_finish=None, daemon=True):
threading.Thread.__init__(self)
if args is None:
@@ -580,8 +729,14 @@ class RepeatedTimer(threading.Thread):
self.run_first = run_first
self.condition = condition
self.on_condition_false = on_condition_false
self.on_cancelled = on_cancelled
self.on_finish = on_finish
self.daemon = daemon
def cancel(self):
self.finished.set()
self._finish(self.on_cancelled)
def run(self):
while self.condition():
@@ -596,15 +751,26 @@ class RepeatedTimer(threading.Thread):
# wait, but break if we are cancelled
self.finished.wait(self.interval())
if self.finished.is_set():
break
return
if not self.run_first:
# if we are to run the function AFTER waiting for the first time
self.function(*self.args, **self.kwargs)
# make sure we set our finished event so we can detect that the loop was finished
# we'll only get here if the condition was false
self._finish(self.on_condition_false)
def _finish(self, *callbacks):
self.finished.set()
for callback in callbacks:
if not callable(callback):
continue
callback()
if callable(self.on_finish):
self.on_finish()
class CountedEvent(object):
+415 -160
View File
@@ -24,13 +24,86 @@ from octoprint.settings import settings, default_settings
from octoprint.events import eventManager, Events
from octoprint.filemanager import valid_file_type
from octoprint.filemanager.destinations import FileDestinations
from octoprint.util import get_exception_string, sanitize_ascii, filter_non_ascii, CountedEvent, RepeatedTimer
from octoprint.util import get_exception_string, sanitize_ascii, filter_non_ascii, CountedEvent, RepeatedTimer, to_unicode, bom_aware_open
try:
import _winreg
except:
pass
_logger = logging.getLogger(__name__)
# a bunch of regexes we'll need for the communication parsing...
regex_float_pattern = "[-+]?[0-9]*\.?[0-9]+"
regex_positive_float_pattern = "[+]?[0-9]*\.?[0-9]+"
regex_int_pattern = "\d+"
regex_command = re.compile("^\s*((?P<commandGM>[GM]\d+)|(?P<commandT>T)\d+)")
"""Regex for a GCODE command."""
regex_float = re.compile(regex_float_pattern)
"""Regex for a float value."""
regexes_parameters = dict(
floatP=re.compile("(^|[^A-Za-z])[Pp](?P<value>%s)" % regex_float_pattern),
floatS=re.compile("(^|[^A-Za-z])[Ss](?P<value>%s)" % regex_float_pattern),
floatZ=re.compile("(^|[^A-Za-z])[Zz](?P<value>%s)" % regex_float_pattern),
intN=re.compile("(^|[^A-Za-z])[Nn](?P<value>%s)" % regex_int_pattern),
intT=re.compile("(^|[^A-Za-z])[Tt](?P<value>%s)" % regex_int_pattern)
)
"""Regexes for parsing various GCODE command parameters."""
regex_minMaxError = re.compile("Error:[0-9]\n")
"""Regex matching first line of min/max errors from the firmware."""
regex_sdPrintingByte = re.compile("(?P<current>[0-9]*)/(?P<total>[0-9]*)")
"""Regex matching SD printing status reports.
Groups will be as follows:
* ``current``: current byte position in file being printed
* ``total``: total size of file being printed
"""
regex_sdFileOpened = re.compile("File opened:\s*(?P<name>.*?)\s+Size:\s*(?P<size>%s)" % regex_int_pattern)
"""Regex matching "File opened" messages from the firmware.
Groups will be as follows:
* ``name``: name of the file reported as having been opened (str)
* ``size``: size of the file in bytes (int)
"""
regex_temp = re.compile("(?P<tool>B|T(?P<toolnum>\d*)):\s*(?P<actual>%s)(\s*\/?\s*(?P<target>%s))?" % (regex_positive_float_pattern, regex_positive_float_pattern))
"""Regex matching temperature entries in line.
Groups will be as follows:
* ``tool``: whole tool designator, incl. optional ``toolnum`` (str)
* ``toolnum``: tool number, if provided (int)
* ``actual``: actual temperature (float)
* ``target``: target temperature, if provided (float)
"""
regex_repetierTempExtr = re.compile("TargetExtr(?P<toolnum>\d+):(?P<target>%s)" % regex_positive_float_pattern)
"""Regex for matching target temp reporting from Repetier.
Groups will be as follows:
* ``toolnum``: number of the extruder to which the target temperature
report belongs (int)
* ``target``: new target temperature (float)
"""
regex_repetierTempBed = re.compile("TargetBed:(?P<target>%s)" % regex_positive_float_pattern)
"""Regex for matching target temp reporting from Repetier for beds.
Groups will be as follows:
* ``target``: new target temperature (float)
"""
def serialList():
baselist=[]
if os.name=="nt":
@@ -151,6 +224,7 @@ class MachineCom(object):
self._long_running_command = False
self._heating = False
self._connection_closing = False
self._timeout = None
@@ -158,12 +232,15 @@ class MachineCom(object):
self._sendChecksumWithUnknownCommands = settings().getBoolean(["feature", "sendChecksumWithUnknownCommands"])
self._unknownCommandsNeedAck = settings().getBoolean(["feature", "unknownCommandsNeedAck"])
self._currentLine = 1
self._line_mutex = threading.RLock()
self._resendDelta = None
self._lastLines = deque([], 50)
self._lastCommError = None
self._lastResendNumber = None
self._currentResendCount = 0
self._resendSwallowNextOk = False
self._resendSwallowRepetitions = settings().getBoolean(["feature", "ignoreIdenticalResends"])
self._resendSwallowRepetitionsCounter = 0
self._clear_to_send = CountedEvent(max=10, name="comm.clear_to_send")
self._send_queue = TypedQueue()
@@ -185,6 +262,7 @@ class MachineCom(object):
self._serial_factory_hooks = self._pluginManager.get_hooks("octoprint.comm.transport.serial.factory")
# SD status data
self._sdEnabled = settings().getBoolean(["feature", "sdSupport"])
self._sdAvailable = False
self._sdFileList = False
self._sdFiles = []
@@ -195,28 +273,6 @@ class MachineCom(object):
self._currentFile = None
# regexes
floatPattern = "[-+]?[0-9]*\.?[0-9]+"
positiveFloatPattern = "[+]?[0-9]*\.?[0-9]+"
intPattern = "\d+"
self._regex_command = re.compile("^\s*([GM]\d+|T)")
self._regex_float = re.compile(floatPattern)
self._regex_paramZFloat = re.compile("Z(%s)" % floatPattern)
self._regex_paramSInt = re.compile("S(%s)" % intPattern)
self._regex_paramNInt = re.compile("N(%s)" % intPattern)
self._regex_paramTInt = re.compile("T(%s)" % intPattern)
self._regex_minMaxError = re.compile("Error:[0-9]\n")
self._regex_sdPrintingByte = re.compile("([0-9]*)/([0-9]*)")
self._regex_sdFileOpened = re.compile("File opened:\s*(.*?)\s+Size:\s*(%s)" % intPattern)
# Regex matching temperature entries in line. Groups will be as follows:
# - 1: whole tool designator incl. optional toolNumber ("T", "Tn", "B")
# - 2: toolNumber, if given ("", "n", "")
# - 3: actual temperature
# - 4: whole target substring, if given (e.g. " / 22.0")
# - 5: target temperature
self._regex_temp = re.compile("(B|T(\d*)):\s*(%s)(\s*\/?\s*(%s))?" % (positiveFloatPattern, positiveFloatPattern))
self._regex_repetierTempExtr = re.compile("TargetExtr([0-9]+):(%s)" % positiveFloatPattern)
self._regex_repetierTempBed = re.compile("TargetBed:(%s)" % positiveFloatPattern)
self._long_running_commands = settings().get(["serial", "longRunningCommands"])
@@ -383,6 +439,10 @@ class MachineCom(object):
##~~ external interface
def close(self, isError = False):
if self._connection_closing:
return
self._connection_closing = True
if self._temperature_timer is not None:
try:
self._temperature_timer.cancel()
@@ -400,11 +460,15 @@ class MachineCom(object):
printing = self.isPrinting() or self.isPaused()
if self._serial is not None:
try:
self._serial.close()
except:
self._logger.exception("Error while trying to close serial port")
isError = True
if isError:
self._changeState(self.STATE_CLOSED_WITH_ERROR)
else:
self._changeState(self.STATE_CLOSED)
self._serial.close()
self._serial = None
if settings().get(["feature", "sdSupport"]):
@@ -428,7 +492,7 @@ class MachineCom(object):
self._clear_to_send.set()
def sendCommand(self, cmd, cmd_type=None, processed=False):
cmd = cmd.encode('ascii', 'replace')
cmd = to_unicode(cmd, errors="replace")
if not processed:
cmd = process_gcode_line(cmd)
if not cmd:
@@ -529,7 +593,7 @@ class MachineCom(object):
self.sendCommand("M24")
self._sd_status_timer = RepeatedTimer(lambda: get_interval("sdStatus"), self._poll_sd_status, run_first=True)
self._sd_status_timer = RepeatedTimer(lambda: get_interval("sdStatus", default_value=1.0), self._poll_sd_status, run_first=True)
self._sd_status_timer.start()
else:
line = self._getNext()
@@ -656,21 +720,28 @@ class MachineCom(object):
return self._sdFiles
def startSdFileTransfer(self, filename):
if not self.isOperational() or self.isBusy():
if not self._sdEnabled:
return
if not self.isOperational() or self.isBusy():
return
self._changeState(self.STATE_TRANSFERING_FILE)
self.sendCommand("M28 %s" % filename.lower())
def endSdFileTransfer(self, filename):
if not self.isOperational() or self.isBusy():
if not self._sdEnabled:
return
if not self.isOperational() or self.isBusy():
return
self.sendCommand("M29 %s" % filename.lower())
self._changeState(self.STATE_OPERATIONAL)
self.refreshSdFiles()
def deleteSdFile(self, filename):
if not self._sdEnabled:
return
if not self.isOperational() or (self.isBusy() and
isinstance(self._currentFile, PrintingSdFileInformation) and
self._currentFile.getFilename() == filename):
@@ -681,13 +752,21 @@ class MachineCom(object):
self.refreshSdFiles()
def refreshSdFiles(self):
if not self._sdEnabled:
return
if not self.isOperational() or self.isBusy():
return
self.sendCommand("M20")
def initSdCard(self):
if not self._sdEnabled:
return
if not self.isOperational():
return
self.sendCommand("M21")
if settings().getBoolean(["feature", "sdAlwaysAvailable"]):
self._sdAvailable = True
@@ -695,6 +774,9 @@ class MachineCom(object):
self._callback.on_comm_sd_state_change(self._sdAvailable)
def releaseSdCard(self):
if not self._sdEnabled:
return
if not self.isOperational() or (self.isBusy() and self.isSdFileSelected()):
# do not release the sd card if we are currently printing from it
return
@@ -708,51 +790,9 @@ class MachineCom(object):
##~~ communication monitoring and handling
def _parseTemperatures(self, line):
result = {}
maxToolNum = 0
for match in re.finditer(self._regex_temp, line):
tool = match.group(1)
toolNumber = int(match.group(2)) if match.group(2) and len(match.group(2)) > 0 else None
if toolNumber > maxToolNum:
maxToolNum = toolNumber
try:
actual = float(match.group(3))
target = None
if match.group(4) and match.group(5):
target = float(match.group(5))
result[tool] = (toolNumber, actual, target)
except ValueError:
# catch conversion issues, we'll rather just not get the temperature update instead of killing the connection
pass
if "T0" in result.keys() and "T" in result.keys():
del result["T"]
return maxToolNum, result
def _processTemperatures(self, line):
maxToolNum, parsedTemps = self._parseTemperatures(line)
# extruder temperatures
if not "T0" in parsedTemps.keys() and not "T1" in parsedTemps.keys() and "T" in parsedTemps.keys():
# no T1 so only single reporting, "T" is our one and only extruder temperature
toolNum, actual, target = parsedTemps["T"]
if target is not None:
self._temp[0] = (actual, target)
elif 0 in self._temp.keys() and self._temp[0] is not None and isinstance(self._temp[0], tuple):
(oldActual, oldTarget) = self._temp[0]
self._temp[0] = (actual, oldTarget)
else:
self._temp[0] = (actual, None)
elif not "T0" in parsedTemps.keys() and "T" in parsedTemps.keys():
# Smoothieware sends multi extruder temperature data this way: "T:<first extruder> T1:<second extruder> ..." and therefore needs some special treatment...
_, actual, target = parsedTemps["T"]
del parsedTemps["T"]
parsedTemps["T0"] = (0, actual, target)
current_tool = self._currentTool if self._currentTool is not None else 0
maxToolNum, parsedTemps = parse_temperature_line(line, current_tool)
if "T0" in parsedTemps.keys():
for n in range(maxToolNum + 1):
@@ -760,18 +800,18 @@ class MachineCom(object):
if not tool in parsedTemps.keys():
continue
toolNum, actual, target = parsedTemps[tool]
actual, target = parsedTemps[tool]
if target is not None:
self._temp[toolNum] = (actual, target)
elif toolNum in self._temp.keys() and self._temp[toolNum] is not None and isinstance(self._temp[toolNum], tuple):
(oldActual, oldTarget) = self._temp[toolNum]
self._temp[toolNum] = (actual, oldTarget)
self._temp[n] = (actual, target)
elif n in self._temp and self._temp[n] is not None and isinstance(self._temp[n], tuple):
(oldActual, oldTarget) = self._temp[n]
self._temp[n] = (actual, oldTarget)
else:
self._temp[toolNum] = (actual, None)
self._temp[n] = (actual, None)
# bed temperature
if "B" in parsedTemps.keys():
toolNum, actual, target = parsedTemps["B"]
actual, target = parsedTemps["B"]
if target is not None:
self._bedTemp = (actual, target)
elif self._bedTemp is not None and isinstance(self._bedTemp, tuple):
@@ -844,7 +884,11 @@ class MachineCom(object):
self._callback.on_comm_force_disconnect()
else:
for hook in self._printer_action_hooks:
self._printer_action_hooks[hook](self, line, action_command)
try:
self._printer_action_hooks[hook](self, line, action_command)
except:
self._logger.exception("Error while calling hook {} with action command {}".format(self._printer_action_hooks[hook], action_command))
continue
else:
continue
@@ -895,8 +939,8 @@ class MachineCom(object):
self._callback.on_comm_temperature_update(self._temp, self._bedTemp)
elif supportRepetierTargetTemp and ('TargetExtr' in line or 'TargetBed' in line):
matchExtr = self._regex_repetierTempExtr.match(line)
matchBed = self._regex_repetierTempBed.match(line)
matchExtr = regex_repetierTempExtr.match(line)
matchBed = regex_repetierTempBed.match(line)
if matchExtr is not None:
toolNum = int(matchExtr.group(1))
@@ -950,18 +994,18 @@ class MachineCom(object):
self._callback.on_comm_sd_files(self._sdFiles)
elif 'SD printing byte' in line and self.isSdPrinting():
# answer to M27, at least on Marlin, Repetier and Sprinter: "SD printing byte %d/%d"
match = self._regex_sdPrintingByte.search(line)
self._currentFile.setFilepos(int(match.group(1)))
match = regex_sdPrintingByte.search(line)
self._currentFile.setFilepos(int(match.group("current")))
self._callback.on_comm_progress()
elif 'File opened' in line and not self._ignore_select:
# answer to M23, at least on Marlin, Repetier and Sprinter: "File opened:%s Size:%d"
match = self._regex_sdFileOpened.search(line)
match = regex_sdFileOpened.search(line)
if self._sdFileToSelect:
name = self._sdFileToSelect
self._sdFileToSelect = None
else:
name = match.group(1)
self._currentFile = PrintingSdFileInformation(name, int(match.group(2)))
name = match.group("name")
self._currentFile = PrintingSdFileInformation(name, int(match.group("size")))
elif 'File selected' in line:
if self._ignore_select:
self._ignore_select = False
@@ -1181,7 +1225,7 @@ class MachineCom(object):
def _onConnected(self):
self._serial.timeout = settings().getFloat(["serial", "timeout", "communication"])
self._temperature_timer = RepeatedTimer(lambda: get_interval("temperature"), self._poll_temperature, run_first=True)
self._temperature_timer = RepeatedTimer(lambda: get_interval("temperature", default_value=4.0), self._poll_temperature, run_first=True)
self._temperature_timer.start()
self._changeState(self.STATE_OPERATIONAL)
@@ -1289,23 +1333,32 @@ class MachineCom(object):
return False
def _handleErrors(self, line):
if line is None:
return
lower_line = line.lower()
# No matter the state, if we see an error, goto the error state and store the error for reference.
if line.startswith('Error:') or line.startswith('!!'):
#Oh YEAH, consistency.
# Marlin reports an MIN/MAX temp error as "Error:x\n: Extruder switched off. MAXTEMP triggered !\n"
# But a bed temp error is reported as "Error: Temperature heated bed switched off. MAXTEMP triggered !!"
# So we can have an extra newline in the most common case. Awesome work people.
if self._regex_minMaxError.match(line):
if regex_minMaxError.match(line):
line = line.rstrip() + self._readline()
if 'line number' in line.lower() or 'checksum' in line.lower() or 'expected line' in line.lower():
if 'line number' in lower_line or 'checksum' in lower_line or 'format error' in lower_line or 'expected line' in lower_line:
#Skip the communication errors, as those get corrected.
self._lastCommError = line[6:] if line.startswith("Error:") else line[2:]
pass
elif 'volume.init' in line.lower() or "openroot" in line.lower() or 'workdir' in line.lower()\
or "error writing to file" in line.lower():
elif 'volume.init' in lower_line or "openroot" in lower_line or 'workdir' in lower_line\
or "error writing to file" in lower_line or "cannot open" in lower_line\
or "cannot enter" in lower_line:
#Also skip errors with the SD card
pass
elif 'unknown command' in lower_line:
#Ignore unkown command errors, it could be a typo or some missing feature
pass
elif not self.isError():
self._errorValue = line[6:] if line.startswith("Error:") else line[2:]
self._changeState(self.STATE_ERROR)
@@ -1313,14 +1366,17 @@ class MachineCom(object):
return line
def _readline(self):
if self._serial == None:
if self._serial is None:
return None
try:
ret = self._serial.readline()
except:
self._log("Unexpected error while reading serial port: %s" % (get_exception_string()))
self._errorValue = get_exception_string()
self.close(True)
if not self._connection_closing:
self._logger.exception("Unexpected error while reading from serial port")
self._log("Unexpected error while reading serial port, please consult octoprint.log for details: %s" % (get_exception_string()))
self._errorValue = get_exception_string()
self.close(True)
return None
if ret == '':
#self._log("Recv: TIMEOUT")
@@ -1397,9 +1453,18 @@ class MachineCom(object):
self._currentResendCount += 1
return
# If we ignore resend repetitions (Repetier firmware...), check if we
# need to do this now. If the same line number has been requested we
# already saw and resent, we'll ignore it up to <counter> times.
if self._resendSwallowRepetitions and lineToResend == self._lastResendNumber and self._resendSwallowRepetitionsCounter > 0:
self._logger.debug("Ignoring resend request for line %d, that is probably a repetition sent by the firmware to ensure it arrives, not a real request" % lineToResend)
self._resendSwallowRepetitionsCounter -= 1
return
self._resendDelta = resendDelta
self._lastResendNumber = lineToResend
self._currentResendCount = 0
self._resendSwallowRepetitionsCounter = settings().getInt(["feature", "identicalResendsCountdown"])
if self._resendDelta > len(self._lastLines) or len(self._lastLines) == 0 or self._resendDelta < 0:
self._errorValue = "Printer requested line %d but no sufficient history is available, can't resend" % lineToResend
@@ -1456,25 +1521,6 @@ class MachineCom(object):
# trigger the "queued" phase only if we are not streaming to sd right now
self._process_command_phase("queued", cmd, cmd_type, gcode=gcode)
def gcode_command_for_cmd(self, cmd):
"""
Tries to parse the provided ``cmd`` and extract the GCODE command identifier from it (e.g. "G0" for "G0 X10.0").
Arguments:
cmd (str): The command to try to parse.
Returns:
str or None: The GCODE command identifier if it could be parsed, or None if not.
"""
if not cmd:
return None
gcode = self._regex_command.search(cmd)
if not gcode:
return None
return gcode.group(1)
##~~ send loop handling
def _enqueue_for_sending(self, command, linenumber=None, command_type=None):
@@ -1515,7 +1561,7 @@ class MachineCom(object):
# some firmwares (e.g. Smoothie) might support additional in-band communication that will not
# stick to the acknowledgement behaviour of GCODE, so we check here if we have a GCODE command
# at hand here and only clear our clear_to_send flag later if that's the case
gcode = self.gcode_command_for_cmd(command)
gcode = gcode_command_for_cmd(command)
if linenumber is not None:
# line number predetermined - this only happens for resends, so we'll use the number and
@@ -1531,13 +1577,11 @@ class MachineCom(object):
continue
# now comes the part where we increase line numbers and send stuff - no turning back now
command_to_send = command.encode("ascii", errors="replace")
if (gcode is not None or self._sendChecksumWithUnknownCommands) and (self.isPrinting() or self._alwaysSendChecksum):
linenumber = self._currentLine
self._addToLastLines(command)
self._currentLine += 1
self._doSendWithChecksum(command, linenumber)
self._doIncrementAndSendWithChecksum(command_to_send)
else:
self._doSendWithoutChecksum(command)
self._doSendWithoutChecksum(command_to_send)
# trigger "sent" phase and use up one "ok"
self._process_command_phase("sent", command, command_type, gcode=gcode)
@@ -1563,7 +1607,7 @@ class MachineCom(object):
return command, command_type, gcode
if gcode is None:
gcode = self.gcode_command_for_cmd(command)
gcode = gcode_command_for_cmd(command)
# send it through the phase specific handlers provided by plugins
for name, hook in self._gcode_hooks[phase].items():
@@ -1618,11 +1662,18 @@ class MachineCom(object):
# handler returned a tuple of an unexpected length
return original_tuple
gcode = self.gcode_command_for_cmd(command)
gcode = gcode_command_for_cmd(command)
return command, command_type, gcode
##~~ actual sending via serial
def _doIncrementAndSendWithChecksum(self, cmd):
with self._line_mutex:
linenumber = self._currentLine
self._addToLastLines(cmd)
self._currentLine += 1
self._doSendWithChecksum(cmd, linenumber)
def _doSendWithChecksum(self, cmd, lineNumber):
commandToSend = "N%d %s" % (lineNumber, cmd)
checksum = reduce(lambda x,y:x^y, map(ord, commandToSend))
@@ -1630,6 +1681,9 @@ class MachineCom(object):
self._doSendWithoutChecksum(commandToSend)
def _doSendWithoutChecksum(self, cmd):
if self._serial is None:
return
self._log("Send: %s" % cmd)
try:
self._serial.write(cmd + '\n')
@@ -1638,27 +1692,31 @@ class MachineCom(object):
try:
self._serial.write(cmd + '\n')
except:
self._log("Unexpected error while writing serial port: %s" % (get_exception_string()))
if not self._connection_closing:
self._logger.exception("Unexpected error while writing to serial port")
self._log("Unexpected error while writing to serial port: %s" % (get_exception_string()))
self._errorValue = get_exception_string()
self.close(True)
except:
if not self._connection_closing:
self._logger.exception("Unexpected error while writing to serial port")
self._log("Unexpected error while writing to serial port: %s" % (get_exception_string()))
self._errorValue = get_exception_string()
self.close(True)
except:
self._log("Unexpected error while writing serial port: %s" % (get_exception_string()))
self._errorValue = get_exception_string()
self.close(True)
##~~ command handlers
def _gcode_T_sent(self, cmd, cmd_type=None):
toolMatch = self._regex_paramTInt.search(cmd)
toolMatch = regexes_parameters["intT"].search(cmd)
if toolMatch:
self._currentTool = int(toolMatch.group(1))
self._currentTool = int(toolMatch.group("value"))
def _gcode_G0_sent(self, cmd, cmd_type=None):
if 'Z' in cmd:
match = self._regex_paramZFloat.search(cmd)
match = regexes_parameters["floatZ"].search(cmd)
if match:
try:
z = float(match.group(1))
z = float(match.group("value"))
if self._currentZ != z:
self._currentZ = z
self._callback.on_comm_z_change(z)
@@ -1671,15 +1729,27 @@ class MachineCom(object):
return None, # Don't send the M0 or M1 to the machine, as M0 and M1 are handled as an LCD menu pause.
_gcode_M1_queuing = _gcode_M0_queuing
def _gcode_M25_queuing(self, cmd, cmd_type=None):
# M25 while not printing from SD will be handled as pause. This way it can be used as another marker
# for GCODE induced pausing. Send it to the printer anyway though.
if self.isPrinting() and not self.isSdPrinting():
self.setPause(True)
def _gcode_M140_queuing(self, cmd, cmd_type=None):
if not self._printerProfileManager.get_current_or_default()["heatedBed"]:
self._log("Warn: Not sending \"{}\", printer profile has no heated bed".format(cmd))
return None, # Don't send bed commands if we don't have a heated bed
_gcode_M190_queuing = _gcode_M140_queuing
def _gcode_M104_sent(self, cmd, cmd_type=None):
toolNum = self._currentTool
toolMatch = self._regex_paramTInt.search(cmd)
toolMatch = regexes_parameters["intT"].search(cmd)
if toolMatch:
toolNum = int(toolMatch.group(1))
match = self._regex_paramSInt.search(cmd)
toolNum = int(toolMatch.group("value"))
match = regexes_parameters["floatS"].search(cmd)
if match:
try:
target = float(match.group(1))
target = float(match.group("value"))
if toolNum in self._temp.keys() and self._temp[toolNum] is not None and isinstance(self._temp[toolNum], tuple):
(actual, oldTarget) = self._temp[toolNum]
self._temp[toolNum] = (actual, target)
@@ -1689,10 +1759,10 @@ class MachineCom(object):
pass
def _gcode_M140_sent(self, cmd, cmd_type=None):
match = self._regex_paramSInt.search(cmd)
match = regexes_parameters["floatS"].search(cmd)
if match:
try:
target = float(match.group(1))
target = float(match.group("value"))
if self._bedTemp is not None and isinstance(self._bedTemp, tuple):
(actual, oldTarget) = self._bedTemp
self._bedTemp = (actual, target)
@@ -1715,37 +1785,62 @@ class MachineCom(object):
def _gcode_M110_sending(self, cmd, cmd_type=None):
newLineNumber = None
match = self._regex_paramNInt.search(cmd)
match = regexes_parameters["intN"].search(cmd)
if match:
try:
newLineNumber = int(match.group(1))
newLineNumber = int(match.group("value"))
except:
pass
else:
newLineNumber = 0
# send M110 command with new line number
self._currentLine = newLineNumber
with self._line_mutex:
# send M110 command with new line number
self._currentLine = newLineNumber
# after a reset of the line number we have no way to determine what line exactly the printer now wants
self._lastLines.clear()
# after a reset of the line number we have no way to determine what line exactly the printer now wants
self._lastLines.clear()
self._resendDelta = None
def _gcode_M112_queuing(self, cmd, cmd_type=None): # It's an emergency what todo? Canceling the print should be the minimum
self.cancelPrint()
def _gcode_M112_queuing(self, cmd, cmd_type=None):
# emergency stop, jump the queue with the M112
self._doSendWithoutChecksum("M112")
self._doIncrementAndSendWithChecksum("M112")
# No idea if the printer is still listening or if M112 won. Just in case
# we'll now try to also manually make sure all heaters are shut off - better
# safe than sorry. We do this ignoring the queue since at this point it
# is irrelevant whether the printer has sent enough ack's or not, we
# are going to shutdown the connection in a second anyhow.
for tool in range(self._printerProfileManager.get_current_or_default()["extruder"]["count"]):
self._doIncrementAndSendWithChecksum("M104 T{tool} S0".format(tool=tool))
if self._printerProfileManager.get_current_or_default()["heatedBed"]:
self._doIncrementAndSendWithChecksum("M140 S0")
# close to reset host state
self._errorValue = "Closing serial port due to emergency stop M112."
self._log(self._errorValue)
self.close(isError=True)
# fire the M112 event since we sent it and we're going to prevent the caller from seeing it
gcode = "M112"
if gcode in gcodeToEvent:
eventManager().fire(gcodeToEvent[gcode])
# return None 1-tuple to eat the one that is queuing because we don't want to send it twice
# I hope it got it the first time because as far as I can tell, there is no way to know
return None,
def _gcode_G4_sent(self, cmd, cmd_type=None):
# we are intending to dwell for a period of time, increase the timeout to match
cmd = cmd.upper()
p_idx = cmd.find('P')
s_idx = cmd.find('S')
p_match = regexes_parameters["floatP"].search(cmd)
s_match = regexes_parameters["floatS"].search(cmd)
_timeout = 0
if p_idx != -1:
# dwell time is specified in milliseconds
_timeout = float(cmd[p_idx+1:]) / 1000.0
elif s_idx != -1:
# dwell time is specified in seconds
_timeout = float(cmd[s_idx+1:])
if p_match:
_timeout = float(p_match.group("value")) / 1000.0
elif s_match:
_timeout = float(s_match.group("value"))
self._timeout = get_new_timeout("communication") + _timeout
##~~ command phase handlers
@@ -1899,7 +1994,7 @@ class PrintingGcodeFileInformation(PrintingFileInformation):
Opens the file for reading and determines the file size.
"""
PrintingFileInformation.start(self)
self._handle = open(self._filename, "r")
self._handle = bom_aware_open(self._filename, encoding="utf-8", errors="replace")
def close(self):
"""
@@ -1929,7 +2024,7 @@ class PrintingGcodeFileInformation(PrintingFileInformation):
if self._handle is None:
# file got closed just now
return None
line = self._handle.readline()
line = to_unicode(self._handle.readline())
if not line:
self.close()
processed = process_gcode_line(line, offsets=offsets, current_tool=current_tool)
@@ -1997,11 +2092,15 @@ def get_new_timeout(type):
return now + get_interval(type)
def get_interval(type):
def get_interval(type, default_value=0.0):
if type not in default_settings["serial"]["timeout"]:
return 0
return default_value
else:
return settings().getFloat(["serial", "timeout", type])
value = settings().getFloat(["serial", "timeout", type])
if not value:
return default_value
else:
return value
_temp_command_regex = re.compile("^M(?P<command>104|109|140|190)(\s+T(?P<tool>\d+)|\s+S(?P<temperature>[-+]?\d*\.?\d*))+")
@@ -2131,3 +2230,159 @@ def convert_feedback_controls(configured_controls):
return feedback_controls, feedback_matcher
def canonicalize_temperatures(parsed, current):
"""
Canonicalizes the temperatures provided in parsed.
Will make sure that returned result only contains extruder keys
like Tn, so always qualified with a tool number.
The algorithm for cleaning up the parsed keys is the following:
* If ``T`` is not included with the reported extruders, return
* If more than just ``T`` is reported:
* If both ``T`` and ``T0`` are reported set ``Tc`` to ``T``, remove
``T`` from the result.
* Else set ``T0`` to ``T`` and delete ``T`` (Smoothie extra).
* If only ``T`` is reported, set ``Tc`` to ``T`` and delete ``T``
* return
Arguments:
parsed (dict): the parsed temperatures (mapping tool => (actual, target))
to canonicalize
current (int): the current active extruder
Returns:
dict: the canonicalized version of ``parsed``
"""
reported_extruders = filter(lambda x: x.startswith("T"), parsed.keys())
if not "T" in reported_extruders:
# Our reported_extruders are either empty or consist purely
# of Tn keys, no need for any action
return parsed
current_tool_key = "T%d" % current
result = dict(parsed)
if len(reported_extruders) > 1:
if "T0" in reported_extruders:
# Both T and T0 are present, so T contains the current
# extruder's temperature, e.g. for current_tool == 1:
#
# T:<T1> T0:<T0> T2:<T2> ... B:<B>
#
# becomes
#
# T0:<T1> T1:<T1> T2:<T2> ... B:<B>
#
# Same goes if Tc is already present, it will be overwritten:
#
# T:<T1> T0:<T0> T1:<T1> T2:<T2> ... B:<B>
#
# becomes
#
# T0:<T0> T1:<T1> T2:<T2> ... B:<B>
result[current_tool_key] = result["T"]
del result["T"]
else:
# So T is there, but T0 isn't. That looks like Smoothieware which
# always reports the first extruder T0 as T:
#
# T:<T0> T1:<T1> T2:<T2> ... B:<B>
#
# becomes
#
# T0:<T0> T1:<T1> T2:<T2> ... B:<B>
result["T0"] = result["T"]
del result["T"]
else:
# We only have T. That can mean two things:
#
# * we only have one extruder at all, or
# * we are currently parsing a response to M109/M190, which on
# some firmwares doesn't report the full M105 output while
# waiting for the target temperature to be reached but only
# reports the current tool and bed
#
# In both cases it is however safe to just move our T over
# to T<current> in the parsed data, current should always stay
# 0 for single extruder printers. E.g. for current_tool == 1:
#
# T:<T1>
#
# becomes
#
# T1:<T1>
result[current_tool_key] = result["T"]
del result["T"]
return result
def parse_temperature_line(line, current):
"""
Parses the provided temperature line.
The result will be a dictionary mapping from the extruder or bed key to
a tuple with current and target temperature. The result will be canonicalized
with :func:`canonicalize_temperatures` before returning.
Arguments:
line (str): the temperature line to parse
current (int): the current active extruder
Returns:
tuple: a 2-tuple with the maximum tool number and a dict mapping from
key to (actual, target) tuples, with key either matching ``Tn`` for ``n >= 0`` or ``B``
"""
result = {}
maxToolNum = 0
for match in re.finditer(regex_temp, line):
values = match.groupdict()
tool = values["tool"]
toolnum = values.get("toolnum", None)
toolNumber = int(toolnum) if toolnum is not None and len(toolnum) else None
if toolNumber > maxToolNum:
maxToolNum = toolNumber
try:
actual = float(match.group(3))
target = None
if match.group(4) and match.group(5):
target = float(match.group(5))
result[tool] = (actual, target)
except ValueError:
# catch conversion issues, we'll rather just not get the temperature update instead of killing the connection
pass
return max(maxToolNum, current), canonicalize_temperatures(result, current)
def gcode_command_for_cmd(cmd):
"""
Tries to parse the provided ``cmd`` and extract the GCODE command identifier from it (e.g. "G0" for "G0 X10.0").
Arguments:
cmd (str): The command to try to parse.
Returns:
str or None: The GCODE command identifier if it could be parsed, or None if not.
"""
if not cmd:
return None
gcode = regex_command.search(cmd)
if not gcode:
return None
values = gcode.groupdict()
if "commandGM" in values and values["commandGM"]:
return values["commandGM"]
elif "commandT" in values and values["commandT"]:
return values["commandT"]
else:
# this should never happen
return None
+3 -1
View File
@@ -35,7 +35,9 @@ class gcode(object):
if os.path.isfile(filename):
self.filename = filename
self._fileSize = os.stat(filename).st_size
with open(filename, "r") as f:
import codecs
with codecs.open(filename, encoding="utf-8", errors="replace") as f:
self._load(f, printer_profile, throttle=throttle)
def abort(self):
+50
View File
@@ -0,0 +1,50 @@
# coding=utf-8
from __future__ import absolute_import
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import os
from jinja2.loaders import FileSystemLoader, TemplateNotFound, split_template_path
class FilteredFileSystemLoader(FileSystemLoader):
"""
Jinja2 ``FileSystemLoader`` subclass that allows filtering templates.
Only such templates will be accessible for whose paths the provided
``path_filter`` filter function returns True.
``path_filter`` will receive the actual path on disc and should behave just
like callables provided to Python's internal ``filter`` function, returning
``True`` if the path is cleared and ``False`` if it is supposed to be removed
from results and hence ``filter(path_filter, iterable)`` should be
equivalent to ``[item for item in iterable if path_filter(item)]``.
If ``path_filter`` is not set or not a ``callable``, the loader will
behave just like the regular Jinja2 ``FileSystemLoader``.
"""
def __init__(self, searchpath, path_filter=None, **kwargs):
FileSystemLoader.__init__(self, searchpath, **kwargs)
self.path_filter = path_filter
def get_source(self, environment, template):
if callable(self.path_filter):
pieces = split_template_path(template)
if not self._combined_filter(os.path.join(*pieces)):
raise TemplateNotFound(template)
return FileSystemLoader.get_source(self, environment, template)
def list_templates(self):
result = FileSystemLoader.list_templates(self)
if callable(self.path_filter):
result = sorted(filter(self._combined_filter, result))
return result
def _combined_filter(self, path):
filter_results = map(lambda x: not os.path.exists(os.path.join(x, path)) or self.path_filter(os.path.join(x, path)),
self.searchpath)
return all(filter_results)
+46 -11
View File
@@ -11,6 +11,9 @@ import sys
import logging
from octoprint.util import to_unicode
class UnknownPip(Exception):
pass
@@ -18,14 +21,16 @@ class PipCaller(object):
def __init__(self, configured=None):
self._logger = logging.getLogger(__name__)
self._configured = configured
self.configured = configured
self.refresh = False
self._command = None
self._version = None
self._version_string = None
self._use_sudo = False
self._command, self._version = self._find_pip()
self.trigger_refresh()
self.refresh = False
self.on_log_call = lambda *args, **kwargs: None
self.on_log_stdout = lambda *args, **kwargs: None
self.on_log_stderr = lambda *args, **kwargs: None
@@ -50,26 +55,43 @@ class PipCaller(object):
def version(self):
return self._version
@property
def version_string(self):
return self._version_string
@property
def use_sudo(self):
return self._use_sudo
@property
def available(self):
return self._command is not None
def trigger_refresh(self):
try:
self._command, self._version, self._version_string, self._use_sudo = self._find_pip()
except:
self._logger.exception("Error while discovering pip command")
self._command = None
self._version = None
self.refresh = False
def execute(self, *args):
if self.refresh:
self._command, self._version = self._find_pip()
self.refresh = False
self.trigger_refresh()
if self._command is None:
raise UnknownPip()
command = [self._command] + list(args)
if self._use_sudo:
command = ["sudo"] + command
joined_command = " ".join(command)
self._logger.debug(u"Calling: {}".format(joined_command))
self.on_log_call(joined_command)
p = sarge.run(joined_command, shell=True, async=True, stdout=sarge.Capture(), stderr=sarge.Capture())
p = sarge.run(command, async=True, stdout=sarge.Capture(), stderr=sarge.Capture())
p.wait_events()
all_stdout = []
@@ -78,11 +100,13 @@ class PipCaller(object):
while p.returncode is None:
line = p.stderr.readline(timeout=0.5)
if line:
line = to_unicode(line, errors="replace")
self._log_stderr(line)
all_stderr.append(line)
line = p.stdout.readline(timeout=0.5)
if line:
line = to_unicode(line, errors="replace")
self._log_stdout(line)
all_stdout.append(line)
@@ -107,8 +131,16 @@ class PipCaller(object):
def _find_pip(self):
pip_command = self._configured
pip_command = self.configured
if pip_command is not None and pip_command.startswith("sudo "):
pip_command = pip_command[len("sudo "):]
pip_sudo = True
else:
pip_sudo = False
pip_version = None
version_segment = None
if pip_command is None:
import os
@@ -140,8 +172,11 @@ class PipCaller(object):
if pip_command is not None:
self._logger.debug("Found pip at {}, going to figure out its version".format(pip_command))
command = [pip_command, "--version"]
p = sarge.run(" ".join(command), shell=True, stdout=sarge.Capture(), stderr=sarge.Capture())
sarge_command = [pip_command, "--version"]
if pip_sudo:
sarge_command = ["sudo"] + sarge_command
p = sarge.run(sarge_command, stdout=sarge.Capture(), stderr=sarge.Capture())
if p.returncode != 0:
self._logger.warn("Error while trying to run pip --version: {}".format(p.stderr.text))
@@ -171,7 +206,7 @@ class PipCaller(object):
else:
self._logger.info("Found pip at {}, version is {}".format(pip_command, version_segment))
return pip_command, pip_version
return pip_command, pip_version, version_segment, pip_sudo
def _log_stdout(self, *lines):
self.on_log_stdout(*lines)
+5 -1
View File
@@ -439,7 +439,7 @@ def get_babel_commandclasses(pot_file=None,
def create_plugin_setup_parameters(identifier="todo", name="TODO", version="0.1", description="TODO", author="TODO",
mail="todo@example.com", url="TODO", license="AGPLv3", source_folder=".", additional_data=None,
additional_packages=None, ignored_packages=None, requires=None, extra_requires=None,
cmdclass=None, eggs=None, package=None):
cmdclass=None, eggs=None, package=None, dependency_links=None):
import pkg_resources
if package is None:
@@ -454,6 +454,9 @@ def create_plugin_setup_parameters(identifier="todo", name="TODO", version="0.1"
if ignored_packages is None:
ignored_packages = list()
if dependency_links is None:
dependency_links = list()
if requires is None:
requires = ["OctoPrint"]
if not isinstance(requires, list):
@@ -519,6 +522,7 @@ def create_plugin_setup_parameters(identifier="todo", name="TODO", version="0.1"
install_requires=requires,
extras_require=extra_requires,
dependency_links=dependency_links,
# Hook the plugin into the "octoprint.plugin" entry point, mapping the plugin_identifier to the plugin_package.
# That way OctoPrint will be able to find the plugin and load it.
-1
View File
@@ -8,4 +8,3 @@ from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
+96 -4
View File
@@ -13,6 +13,98 @@ import mock
import octoprint.filemanager
import octoprint.filemanager.util
class FilemanagerMethodTest(unittest.TestCase):
def setUp(self):
# mock plugin manager
self.plugin_manager_patcher = mock.patch("octoprint.plugin.plugin_manager")
self.plugin_manager_getter = self.plugin_manager_patcher.start()
self.plugin_manager = mock.MagicMock()
hook_extensions = dict(
some_plugin=lambda: dict(dict(machinecode=dict(foo=["foo", "f"]))),
other_plugin=lambda: dict(dict(model=dict(amf=["amf"]))),
mime_map=lambda: dict(
mime_map=dict(
mime_map_yes=octoprint.filemanager.ContentTypeMapping(["mime_map_yes"], "application/mime_map_yes")
)
),
mime_detect=lambda: dict(
dict(
machinecode=dict(
mime_detect_yes=octoprint.filemanager.ContentTypeDetector(["mime_detect_yes"], lambda x: "application/mime_detect_yes"),
mime_detect_no=octoprint.filemanager.ContentTypeDetector(["mime_detect_no"], lambda x: None)
)
)
)
)
self.plugin_manager.get_hooks.return_value = hook_extensions
self.plugin_manager_getter.return_value = self.plugin_manager
def tearDown(self):
self.plugin_manager_patcher.stop()
def test_full_extension_tree(self):
full = octoprint.filemanager.full_extension_tree()
self.assertTrue("machinecode" in full)
self.assertTrue("gcode" in full["machinecode"])
self.assertTrue(isinstance(full["machinecode"]["gcode"], octoprint.filemanager.ContentTypeMapping))
self.assertItemsEqual(["gcode", "gco", "g"], full["machinecode"]["gcode"].extensions)
self.assertTrue("foo" in full["machinecode"])
self.assertTrue(isinstance(full["machinecode"]["foo"], list))
self.assertItemsEqual(["f", "foo"], full["machinecode"]["foo"])
self.assertTrue("model" in full)
self.assertTrue("stl" in full["model"])
self.assertTrue(isinstance(full["model"]["stl"], octoprint.filemanager.ContentTypeMapping))
self.assertItemsEqual(["stl"], full["model"]["stl"].extensions)
self.assertTrue("amf" in full["model"])
self.assertTrue(isinstance(full["model"]["amf"], list))
self.assertItemsEqual(["amf"], full["model"]["amf"])
def test_get_mimetype(self):
self.assertEquals(octoprint.filemanager.get_mime_type("foo.stl"), "application/sla")
self.assertEquals(octoprint.filemanager.get_mime_type("foo.gcode"), "text/plain")
self.assertEquals(octoprint.filemanager.get_mime_type("foo.unknown"), "application/octet-stream")
self.assertEquals(octoprint.filemanager.get_mime_type("foo.mime_map_yes"), "application/mime_map_yes")
self.assertEquals(octoprint.filemanager.get_mime_type("foo.mime_map_no"), "application/octet-stream")
self.assertEquals(octoprint.filemanager.get_mime_type("foo.mime_detect_yes"), "application/mime_detect_yes")
self.assertEquals(octoprint.filemanager.get_mime_type("foo.mime_detect_no"), "application/octet-stream")
def test_valid_file_type(self):
self.assertTrue(octoprint.filemanager.valid_file_type("foo.stl", type="model"))
self.assertTrue(octoprint.filemanager.valid_file_type("foo.stl", type="stl"))
self.assertFalse(octoprint.filemanager.valid_file_type("foo.stl", type="machinecode"))
self.assertTrue(octoprint.filemanager.valid_file_type("foo.foo", type="machinecode"))
self.assertTrue(octoprint.filemanager.valid_file_type("foo.foo", type="foo"))
self.assertTrue(octoprint.filemanager.valid_file_type("foo.foo"))
self.assertTrue(octoprint.filemanager.valid_file_type("foo.mime_map_yes"))
self.assertTrue(octoprint.filemanager.valid_file_type("foo.mime_detect_yes"))
self.assertFalse(octoprint.filemanager.valid_file_type("foo.unknown"))
def test_get_file_type(self):
self.assertEquals(["machinecode", "gcode"], octoprint.filemanager.get_file_type("foo.gcode"))
self.assertEquals(["machinecode", "gcode"], octoprint.filemanager.get_file_type("foo.gco"))
self.assertEquals(["machinecode", "foo"], octoprint.filemanager.get_file_type("foo.f"))
self.assertEquals(["model", "stl"], octoprint.filemanager.get_file_type("foo.stl"))
self.assertEquals(["model", "amf"], octoprint.filemanager.get_file_type("foo.amf"))
self.assertIsNone(octoprint.filemanager.get_file_type("foo.unknown"))
def test_hook_failure(self):
def hook():
raise RuntimeError("Boo!")
self.plugin_manager.get_hooks.return_value = dict(hook=hook)
with mock.patch("octoprint.filemanager.logging") as patched_logging:
logger = mock.MagicMock()
patched_logging.getLogger.return_value = logger
octoprint.filemanager.get_all_extensions()
self.assertEquals(1, len(logger.mock_calls))
class FileManagerTest(unittest.TestCase):
def setUp(self):
@@ -109,13 +201,13 @@ class FileManagerTest(unittest.TestCase):
self.assertEquals(metadata, expected)
self.local_storage.get_metadata.assert_called_once_with("test.file")
@mock.patch("__builtin__.open", new_callable=mock.mock_open)
@mock.patch("octoprint.filemanager.util.atomic_write")
@mock.patch("io.FileIO")
@mock.patch("shutil.copyfileobj")
@mock.patch("os.remove")
@mock.patch("tempfile.NamedTemporaryFile")
@mock.patch("time.time", side_effect=[1411979916.422, 1411979932.116])
def test_slice(self, mocked_time, mocked_tempfile, mocked_os, mocked_shutil, mocked_fileio, mocked_open):
def test_slice(self, mocked_time, mocked_tempfile, mocked_os, mocked_shutil, mocked_fileio, mocked_atomic_write):
callback = mock.MagicMock()
callback_args = ("one", "two", "three")
@@ -187,8 +279,8 @@ class FileManagerTest(unittest.TestCase):
self.local_storage.add_file.assert_called_once_with("dest.file", mock.ANY, printer_profile=expected_printer_profile, allow_overwrite=True, links=expected_links)
# assert that the generated gcode was manipulated as required
expected_open_calls = [mock.call("prefix/dest.file", "wb")]
self.assertEquals(mocked_open.call_args_list, expected_open_calls)
expected_atomic_write_calls = [mock.call("prefix/dest.file", "wb")]
self.assertEquals(mocked_atomic_write.call_args_list, expected_atomic_write_calls)
#mocked_open.return_value.write.assert_called_once_with(";Generated from source.file aabbccddeeff\r")
# assert that shutil was asked to copy the concatenated multistream
+139
View File
@@ -0,0 +1,139 @@
import unittest
import mock
import octoprint.plugin
class BlueprintPluginTest(unittest.TestCase):
def setUp(self):
self.basefolder = "/some/funny/basefolder"
self.plugin = octoprint.plugin.BlueprintPlugin()
self.plugin._basefolder = self.basefolder
class MyAssetPlugin(octoprint.plugin.BlueprintPlugin, octoprint.plugin.AssetPlugin):
def get_asset_folder(self):
return "/some/asset/folder"
class MyTemplatePlugin(octoprint.plugin.BlueprintPlugin, octoprint.plugin.TemplatePlugin):
def get_template_folder(self):
return "/some/template/folder"
self.assetplugin = MyAssetPlugin()
self.assetplugin._basefolder = self.basefolder
self.templateplugin = MyTemplatePlugin()
self.templateplugin._basefolder = self.basefolder
def test_route(self):
def test_method():
pass
octoprint.plugin.BlueprintPlugin.route("/test/method", methods=["GET"])(test_method)
octoprint.plugin.BlueprintPlugin.route("/test/method/{foo}", methods=["PUT"])(test_method)
self.assertTrue(hasattr(test_method, "_blueprint_rules"))
self.assertTrue("test_method" in test_method._blueprint_rules)
self.assertTrue(len(test_method._blueprint_rules["test_method"]) == 2)
self.assertListEqual(test_method._blueprint_rules["test_method"], [
("/test/method", dict(methods=["GET"])),
("/test/method/{foo}", dict(methods=["PUT"]))
])
def test_errorhandler(self):
def test_method():
pass
octoprint.plugin.BlueprintPlugin.errorhandler(404)(test_method)
self.assertTrue(hasattr(test_method, "_blueprint_error_handler"))
self.assertTrue("test_method" in test_method._blueprint_error_handler)
self.assertTrue(len(test_method._blueprint_error_handler["test_method"]) == 1)
self.assertListEqual(test_method._blueprint_error_handler["test_method"], [
404
])
def test_get_blueprint_kwargs(self):
import os
expected = dict(
static_folder=os.path.join(self.basefolder, "static"),
template_folder=os.path.join(self.basefolder, "templates")
)
result = self.plugin.get_blueprint_kwargs()
self.assertEquals(result, expected)
def test_get_blueprint_kwargs_assetplugin(self):
import os
expected = dict(
static_folder=self.assetplugin.get_asset_folder(),
template_folder=os.path.join(self.basefolder, "templates")
)
result = self.assetplugin.get_blueprint_kwargs()
self.assertEquals(result, expected)
def test_get_blueprint_kwargs_templateplugin(self):
import os
expected = dict(
static_folder=os.path.join(self.basefolder, "static"),
template_folder=self.templateplugin.get_template_folder()
)
result = self.templateplugin.get_blueprint_kwargs()
self.assertEquals(result, expected)
def test_get_blueprint(self):
import os
expected_kwargs = dict(
static_folder=os.path.join(self.basefolder, "static"),
template_folder=os.path.join(self.basefolder, "templates")
)
class MyPlugin(octoprint.plugin.BlueprintPlugin):
@octoprint.plugin.BlueprintPlugin.route("/some/path", methods=["GET"])
def route_method(self):
pass
@octoprint.plugin.BlueprintPlugin.errorhandler(404)
def errorhandler_method(self):
pass
@octoprint.plugin.BlueprintPlugin.route("/hidden/path", methods=["GET"])
def _hidden_method(self):
pass
plugin = MyPlugin()
plugin._basefolder = self.basefolder
plugin._identifier = "myplugin"
with mock.patch("flask.Blueprint") as MockBlueprint:
blueprint = mock.MagicMock()
MockBlueprint.return_value = blueprint
errorhandler = mock.MagicMock()
blueprint.errorhandler.return_value = errorhandler
result = plugin.get_blueprint()
self.assertEquals(result, blueprint)
MockBlueprint.assert_called_once_with("plugin.myplugin", "myplugin", **expected_kwargs)
blueprint.add_url_rule.assert_called_once_with("/some/path", "route_method", view_func=plugin.route_method, methods=["GET"])
blueprint.errorhandler.assert_called_once_with(404)
errorhandler.assert_called_once_with(plugin.errorhandler_method)
def test_get_blueprint_cached(self):
blueprint = mock.MagicMock()
self.plugin._blueprint = blueprint
result = self.plugin.get_blueprint()
self.assertEquals(blueprint, result)
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff. Show more