Compare commits

..
571 Commits
Author SHA1 Message Date
Gina Häußge 6976ac9edd Preparing release of 1.2.17 2016-11-08 11:31:16 +01:00
Gina Häußge 2f79d9d226 Preparing release of 1.2.17rc4 2016-10-17 12:25:51 +02:00
Gina Häußge 88f8077b77 Plugin JS files might be empty, need to handle that
Otherwise webassets will explode with empty file list on bundle creation.
2016-10-17 12:16:53 +02:00
Gina Häußge eabff453cd Preparing release of 1.2.17rc3 2016-10-13 16:12:57 +02:00
Gina Häußge 6cd6b98c2b Core JS needs to go after plugin JS, or we might run into race conditions 2016-10-13 16:11:13 +02:00
Gina Häußge 91ef5480b1 Preparing release of 1.2.17rc2 2016-10-13 12:12:09 +02:00
Gina Häußge 419f3370a2 Split JS/CSS/LESS assets between core+bundled plugins and external plugins
That way a JS error in an external plugin won't nuke the whole UI, which IMHO
is worth the additional requests needed to load the split up files.

See #1544 for an example of such a situation.
2016-10-13 12:07:00 +02:00
Gina Häußge 1370c7a9cc Inject plugin_info object into plugin implementations as well 2016-10-13 12:03:05 +02:00
Gina Häußge 982d121d3b Revert "Preparing release of 1.2.17"
This reverts commit 28de87441f.
2016-10-12 18:36:41 +02:00
Gina Häußge 67634e4f7c Merge branch 'improve/loggingHandlers' into maintenance 2016-10-12 18:15:12 +02:00
Gina Häußge 3d26e478e3 Fix a bug causing the update of OctoPrint to not work under certain circumstances
The bug only manifests if a user had installed 1.2.16 earlier and never once hit "Save" in the
settings before attempting to update to 1.2.17. With 1.2.16 the updater script and settings for
OctoPrint's own update mechanism were changed to prefer "checkout_folder" instead of
"update_folder". In earlier versions however "update_folder" was still used. Saving settings
even once (even without any changes!) will migrate the data. But if that's not done a
KeyError will be raised when trying to retrieve "update_folder" from the check config, with
"checkout_folder" as its fallback.

Rather stupid error really.
2016-10-12 18:13:46 +02:00
Gina Häußge 28de87441f Preparing release of 1.2.17 2016-10-12 16:50:22 +02:00
Gina Häußge 688a998dd2 Use CleaningTimedRotatingFileHandler in bundled plugins 2016-10-11 10:54:16 +02:00
Gina Häußge 343631b3c6 Custom SerialLoggingHandler
Does roll overs on next connections to the printer
2016-10-11 10:53:37 +02:00
Gina Häußge 139b2277d1 Fix missing absolute import declarations 2016-10-10 19:45:34 +02:00
Gina Häußge e8123a6ab1 Custom logging handler that cleans files on startup 2016-10-10 19:27:18 +02:00
Gina Häußge 891fd18f0e Preparing release of 1.2.17rc1 2016-10-06 15:31:28 +02:00
Gina Häußge 41fe997af4 Make sure to also delete any un-suffixed cookies when deleting a cookie
Follow-up to a161feb
2016-10-06 15:25:13 +02:00
Gina Häußge 6c21ee32a8 Fix broken filtering on ItemListHelper
Filter toggling didn't remove the specific filter but always the last item
in the filter list. No, I don't know either why I didn't notice this earlier m(
2016-10-05 19:52:28 +02:00
Gina Häußge bcef804a4a Updated less.js to current version 2.7.1 2016-10-05 12:54:57 +02:00
Gina Häußge 39d5446789 Fixed encoding bug in HTTP request processing, causing weird flask issues
If a content type header was present on a multipart form data part it would turn
the rewritten body into a unicode instead of a byte array, causing a later conversion
to a byte stream to not capture.

Fixed both the fact that the rewritten body would turn into unicode by making
sure the content type header was provided as byte array and fixed the byte stream
conversion to also trigger on unicode instances.

Solves #1531
2016-10-05 12:33:02 +02:00
Gina Häußge a161feb106 Fix bug causing remember_me cookie not to deleted properly on logout 2016-10-04 18:34:45 +02:00
Gina Häußge 8c74b9e74d SettingsPlugins may now mark paths as restricted
That way they can ensure that no sensitive settings data may be
 sent on the REST API.
2016-10-04 16:10:01 +02:00
Gina Häußge bc0880711b Log full stack trace on socket connection errors when debug logging
Might help bring some clarity for #1523
2016-10-04 10:18:48 +02:00
Gina Häußge e038cfa4dc Track bypassed views on cache too
Only keep the cache keys, but that way we know when
we were going to cache something and then didn't
due to environmental factors, e.g. headers on request
or response.

Necessary to be able to track if the preliminary caching
has been done during startup to properly reflect that
on cached.gif
2016-09-28 13:44:59 +02:00
Gina Häußge e700891dba Marked some paths for github's linguist 2016-09-23 14:26:58 +02:00
Gina Häußge 080a6e9ccd Extend atomic_write to allow setting & persisting file permissions 2016-09-23 14:26:33 +02:00
Gina Häußge 3a13dd9022 Fixed printerParameters config migrator
Was marking the config as dirty just when printerParameters entry existed,
which always exists - various sub entries of that are what needs to be checked
instead.
2016-09-23 12:37:41 +02:00
Gina Häußge 3d959c1d5f maintenance branch is now 1.2.17.dev 2016-09-23 12:29:56 +02:00
Gina Häußge 354042b84d Preparing release of 1.2.16 2016-09-23 09:51:45 +02:00
Gina Häußge 26fb208f48 Preparing release of 1.2.16rc2 2016-09-16 12:54:48 +02:00
Gina Häußge 2fc86e095f 1.2.16rc1 was actually pushed out on 2016-09-09, not -08 2016-09-12 12:49:04 +02:00
Gina Häußge 0167015b46 Fix generate/delete API key functionality in user settings
Closes #1491
2016-09-12 12:48:10 +02:00
Gina Häußge 8b99c89acf Return 400 Bad Request if a multipart request lacks the boundary
It's mandatory according to RFC2046, section 5.1

See also #1486
2016-09-12 12:48:10 +02:00
Gina Häußge 0bb6f5215d "prerelease" key might not be in check if tracking stable releases 2016-09-12 09:25:34 +02:00
Gina Häußge 079430e3c8 Preparing release of 1.2.16rc1 2016-09-09 11:52:56 +02:00
Gina Häußge 7efa311b04 Updated the german translation again after adding a sentence 2016-09-09 11:52:54 +02:00
Gina Häußge c6d9575127 Added link to "Using Release Channels" to the SWU settings dialog 2016-09-09 11:34:25 +02:00
Gina Häußge bbe6e44d44 Only use non-postfixed cookie if no postfixed one exists
Example:

  * both "session" and "session_P5000" cookies available: "session" value from "session_P5000"
  * only "session" cookie available: "session" value from "session"
  * only "session_P5000" cookie available: "session" value from "session_P5000"
2016-09-08 15:42:51 +02:00
Gina Häußge 53b74f9caa Only construct HTTP_HOST header from SERVER_NAME and _PORT if it's unset
If HTTP_HOST is set, following PEP333 it takes precedence over SERVER_NAME and
_PORT, so we set those from it.
2016-09-08 15:18:09 +02:00
Gina Häußge a7bd770180 Allow overriding file name sanitization by sub classes of LocalStorage 2016-09-08 12:50:04 +02:00
Gina Häußge 2b22d26eac Fixed a small issue with RFC 5987 headers arriving as unicode in parser
Also added API docs regarding header encoding, incl support for RFC 5987
for filename fields in Content-Disposition headers in multipart/form-data
parts, incl. an example of an upload request with a utf-8 encoded filename.
2016-09-07 18:44:46 +02:00
Gina Häußge 13728c231c Also explicitely support ISO-8859-1 encoded multipart headers
Solves an issue with clients encoding filenames in multipart
 headers in ISO-8859-1, causing an HTTP 500 response code.

 This change makes ISO-8859-1 encoded headers work, sends
 a 400 Bad Request instead of 500 Internal Server Error if the
 request multipart headers cannot be decoded as either UTF-8
 or ISO-8859-1, defines UTF-8 content type for multipart text
 fields in rebuilt body and also adds support for RFC 5987 for the
 multipart file upload "filename" header component.
2016-09-07 17:03:59 +02:00
Gina Häußge 209a88bd6a And consequently yet another update of the german translation 2016-09-07 12:10:34 +02:00
Gina Häußge 2256a1e825 Found an untranslated piece of UI 2016-09-07 12:05:54 +02:00
Gina Häußge 122ec39728 And another update of the german translation 2016-09-07 11:55:31 +02:00
Gina Häußge d4428de9a0 Some rewording 2016-09-07 11:55:17 +02:00
Gina Häußge 536d46f15d Updated german translation 2016-09-07 10:21:21 +02:00
Gina Häußge 62d5f04373 Merge branch 'fix/portRestrictedCookies' into maintenance 2016-09-05 12:11:12 +02:00
Gina Häußge b48af7133e Fixed validator for tornado 2016-09-05 12:10:58 +02:00
Gina Häußge 9a9502b281 "prerelease" might not be in check (chances for that are actually high), don't hiccup on that 2016-09-05 12:09:13 +02:00
Gina Häußge 9d9eb3390d Cookie names are now port specific, based on the request associated with a response
* make sure server_port headers are properly set in reverse proxied scenarios
  * overwrite request and response classes to
    * always apply reverse proxy environment changes (so far missing for tornado
      context)
    * strip cookie name suffixes from cookie names on requests and
    * be sure to set cookie name suffixes for cookie names on responses
    * include script root in path used for cookies
  * some minor refactoring in octoprint.server setup routines
  * removed ReverseProxied class (didn't work for tornado context)
  * add unit tests for the whole reverse proxy, request and response customization
2016-09-05 12:06:56 +02:00
Gina Häußge ce28b637ab Better solution for access to .md files when running from source
The SelectedFileSystemLoader doesn't collect everything and the
kitchen sink from disk...
2016-08-29 17:50:14 +02:00
Gina Häußge 21b7339187 SWU: Move branch config to update check & fix release version detection again 2016-08-26 14:18:17 +02:00
Gina Häußge df1a97b0e1 SWU: Only enforce unequality comparison on release channel switch 2016-08-26 10:40:01 +02:00
Gina Häußge 66da377b64 SWU: Minor fixes in the octoprint check population 2016-08-26 10:19:20 +02:00
Gina Häußge 34e5b5d50f SWU: Sort github releases by version, not publication date
We can't rely on the publication date anymore with the introduction of prerelease
channels, since e.g. a current devel prerelease might have been published
earlier than the latest stable but should still be considered the latest release for
this release channel
2016-08-26 10:18:35 +02:00
Gina Häußge 882cf3a142 SWU: git reset => git reset --hard for forced version 2016-08-25 16:49:18 +02:00
Gina Häußge d9a4ff47b6 Make sure to switch back to master for stable release channel 2016-08-25 16:30:35 +02:00
Gina Häußge d538b3fd38 Adjust swu plugin settings to selected update method 2016-08-25 15:45:25 +02:00
Gina Häußge f8386649bf Fix release channel selector 2016-08-25 13:32:18 +02:00
Gina Häußge b5bc03e711 First throw at release channels
We start out with master (Stable), rc/maintenance (Maintenance) and rc/devel (Devel)
2016-08-25 09:41:12 +02:00
Gina Häußge 0a78c92407 Do access logging via custom request header instead of global flag
We don't want any weird things to happen due to multithreading...
2016-08-18 16:14:03 +02:00
Gina Häußge 60c46a3fc4 Fixed use of preemptive cache exceptions in "unless" implementation 2016-08-18 14:05:12 +02:00
Gina Häußge 8782f77577 Slightly modified logging for cached.gif 2016-08-18 14:01:25 +02:00
Gina Häußge 08f9529c6d Merge remote-tracking branch 'origin/maintenance' into maintenance 2016-08-18 13:58:38 +02:00
Gina Häußge 6499bd160f Only wait for preemptive cache if it's enabled for path & view 2016-08-18 13:56:46 +02:00
Gina Häußge 599098a589 Have intermediary reload only after preliminary caching 2016-08-18 12:27:30 +02:00
Gina Häußge aa57277ff8 Only report files as enqueued for analysis which actually are 2016-08-18 08:39:19 +02:00
Gina Häußge 74a94469b6 Fix an issue with global_get from 3rd party plugins 2016-08-17 14:50:53 +02:00
Gina Häußge 217e54d81c Make sure we are still in printing state before sending next line
We might just have "eaten" a line used for triggering a pause (e.g. an M0)
and thus might not be eligible to send the next line from the streamed file
anymore.

Solves #1448
2016-08-16 09:29:29 +02:00
Gina Häußge b05beb27b5 Don't sanitize . or .. folder names 2016-08-15 16:13:35 +02:00
Gina Häußge d81ec15f43 Improvements in fuzzy print time algorithm
Also use new fuzzy print time in gcode viewer to have some consistency.
2016-08-15 15:42:06 +02:00
Gina Häußge 39372a9475 Also sanitize leading .
That way hidden files that are uploaded will be "de-hidden".

Note that NO "de-hiding" of existing files will take place!
2016-08-15 14:19:36 +02:00
Gina Häußge e8cac14c2f Make sure uploads folder only has sanitized entries
Should make sure stuff doesn't break when people perform manual
file operations on the uploads folder (e.g. uploading files
that don't match the sanitization scheme).

Should solve #1434
2016-08-15 14:19:35 +02:00
Gina Häußge 5bef0926a6 Add [ and ] to valid chars in filenames
See #1434
2016-08-15 14:19:34 +02:00
Gina Häußge 7772fdc7bf Tooltips for state panel 2016-08-15 14:19:33 +02:00
Gina Häußge cd736c44df Improved fuzzy print time display 2016-08-15 14:19:32 +02:00
Gina Häußge 11bdc176a0 Fix minute comparison for dumb estimate fallback
Probably solves the core reason that caused #1428 to be
reported in the first place, totally inaccurate early linear
approximations (when nothing better is available) making
it to the user.

It should now display "Calcuting..." until the approximation
stabilizes OR the configured max percentage or max time without
an estimate are reached.
2016-08-15 14:17:27 +02:00
Gina Häußge fe97a8d6bd maintenance is now 1.2.16.dev 2016-07-30 09:56:49 +02:00
Gina Häußge afdb98a92f Postponing the release of 1.2.15 until tomorrow 2016-07-29 21:50:45 +02:00
Gina Häußge 7b48270239 Preparing release of 1.2.15 2016-07-29 16:30:55 +02:00
Gina Häußge 90340487f7 Merge branch 'fix/revertTimeoutAdjustment' into maintenance 2016-07-29 08:54:11 +02:00
Gina Häußge 1f19fd1e1d Partially revert 937487037
This commit might be at the root of the problems reported
in #1423
2016-07-29 07:45:03 +02:00
Gina Häußge 9b13eb8a6c Support serial hook handlers to not return written bytes 2016-07-29 00:13:03 +02:00
Gina Häußge 444a36d0f0 state_string must always be initialized
See #1425
2016-07-28 23:24:29 +02:00
Gina Häußge 7c5cc8d256 Make sure we have at least two timestamps in lastmodified calculation
Otherwise our max(*timestamps) call might fail
2016-07-28 15:19:34 +02:00
Gina Häußge e76a3ea54f maintenance is now 1.2.15.dev 2016-07-28 14:30:21 +02:00
Gina Häußge 14969e5508 Preparing release of 1.2.14 2016-07-28 12:15:22 +02:00
Gina Häußge f671006582 Use circle instead of info symbol for print time left quality indicator 2016-07-28 11:37:27 +02:00
Gina Häußge bd352f4658 Make sure to clear_to_send in timeout handling for active resends 2016-07-28 11:30:23 +02:00
Gina Häußge 046536dd70 If a line is filtered while printing, read next line to continue sending
We want to make sure that while printing we always continue sending something,
either from the command queue or the printed file.
2016-07-28 11:18:57 +02:00
Gina Häußge f9cb29ac91 A bunch of documentation fixes and updates 2016-07-28 09:43:41 +02:00
Gina Häußge fad2e8f1b8 Visual distinction of state panel UI clusters 2016-07-27 18:38:40 +02:00
Gina Häußge f2ecb96c83 Add indicator of origin of print time left estimate to UI 2016-07-27 18:38:17 +02:00
Gina Häußge 0a81e8b161 Use centered text in progress bars
* print progress shows percentage
  * upload progress shows what it always showed, but fully centered
  * GCODE viewer progress shows what it always showed, but fully centered
2016-07-27 15:05:16 +02:00
Gina Häußge eb822c83a3 Add LESS/CSS for (centered) text in progress bars & knockout helper 2016-07-27 15:04:07 +02:00
Gina Häußge ec8427cbb8 Fix a bug causing the "Streaming ..." text to vanish on transfer to SD 2016-07-27 14:46:00 +02:00
Gina Häußge 3585eb05a2 Fix a tiny typo 2016-07-27 10:13:11 +02:00
Gina Häußge 1fd776153c Another attempt at saner print time estimation
Seriously though, this topic is driving me nuts...

  * track origin of print time left estimate
  * less draconian threshold for estimation helper for all prints, not just
    sd prints
  * sanity check estimated/statistical total print time, if not sane force "dumb"
    estimate
  * force "dumb" estimate if no other estimate is available after set percentage or
    print time
2016-07-26 18:06:21 +02:00
Gina Häußge 75012472a2 Revert "Synchronize access to selected file"
This reverts commit b5e19f0676.
2016-07-26 11:18:10 +02:00
Gina Häußge 55d5df7f14 Report CLOSED/CLOSED_WITH_ERROR states as "Offline"
Provide error string for the latter case in state as well.
2016-07-22 10:51:38 +02:00
Gina Häußge 6e73c31a68 Report correct printer state even after disconnecting
Error string on close with error would get lost, that happens no longer
2016-07-22 10:50:48 +02:00
Gina Häußge d7ae147764 Tickle printer on timeout when idle and blocked 2016-07-22 09:46:58 +02:00
Gina Häußge 9eb1485e84 Add max timeouts configuration to settings 2016-07-21 18:46:54 +02:00
Gina Häußge 4f11f6362b Saner defaults for max timeouts
10 max consecutive with 30s default communication timeout
is a bit too long to wait
2016-07-21 18:46:34 +02:00
Gina Häußge 4f1a55c2df Added AWOL debug command to virtual printer 2016-07-21 16:25:49 +02:00
Gina Häußge cfc5f45aa5 Merge branch 'maintenance' into fix/timeoutDetection
Conflicts:
	src/octoprint/settings.py
	src/octoprint/util/comm.py
2016-07-21 16:13:35 +02:00
Gina Häußge 2f26104b98 Better sleep debug command in virtual printer 2016-07-21 16:11:09 +02:00
Gina Häußge b5e19f0676 Synchronize access to selected file 2016-07-21 16:10:57 +02:00
Gina Häußge 3614033b0d No endless circles if we can't write any bytes to serial 2016-07-21 16:10:00 +02:00
Gina Häußge 44ec821294 Track consecutive timeouts
Should allow to detect if a device actually has gone missing.

See #1388
2016-07-21 16:02:28 +02:00
Gina Häußge c6225aa834 Introduce single output method in virtual printer for easier debugging 2016-07-21 13:25:39 +02:00
Gina Häußge 5d21399a73 Custom markdown filter, 3rd party one wasn't thread safe 2016-07-21 11:50:29 +02:00
Gina Häußge d61371a495 Make sure to include all md files in manifest 2016-07-18 12:13:16 +02:00
Gina Häußge 92f9ed465e Removed two unused locks from StateMonitor 2016-07-14 19:46:44 +02:00
Gina Häußge 0a8a7ba589 Fixed some imports 2016-07-14 19:43:22 +02:00
Gina Häußge bfcd00e466 Fix: Send non-protocol messages from the printer to clients
Solves #1385
2016-07-14 19:42:43 +02:00
Gina Häußge 20fc7f25bc Fix: Ensure log entries and messages from printer are unicode
Otherwise even one line that can't be converted while sending the
backlog to the client can kill the whole backlog.
2016-07-14 19:20:05 +02:00
Gina Häußge 297c434d64 Ease up a bit on the version pinning 2016-07-14 11:41:39 +02:00
Gina Häußge 1e7ea28195 Merge branch 'fix/serialRxBufferHandling' into maintenance 2016-07-13 17:24:13 +02:00
Gina Häußge 937487037a Shorter timeout during heatup & no scary message on end
Set read timeout on serial port to a much shorter value (default 2.0s)
during a heatup. Firmware should usually send the current temperature
back every second, so if that stops we can consider the heatup to be finished
even if we don't see an ok.

That is important in cases such as SD printing, where we might see a
heatup sequence we didn't trigger ourselves, during which we shouldn't spam
the printer with commands it potentially can't process but after which we
still should take up normal communication again. In case of a heatup sequence
triggered by an SD print we won't see an ok and hence only can now through a
timeout that things are now done printer side. In such a case the user should not
get thrown a scary timeout message in their general direction either.

Solves #1409
2016-07-13 17:21:45 +02:00
Gina Häußge 2cc9631791 Reset printAfterSelect once it's triggered
Should solve #1407
2016-07-13 13:01:33 +02:00
Gina Häußge 2b9aef5874 Keep sending if serial line was only sent partially
So far the sending routine did not track the amount of bytes that were
actually sent. This is now fixed such that if the number of sent bytes
is less then the number of bytes of the whole message, the sending
rountine will continue to send the unsent parts of the message until
it succeeds (or a timeout occurs).

Also adjusted the virtual printer to imitate a real serial interface with
regards to having it return the written bytes and allowing a partial
sending (returning the number of bytes that actually were sent).
2016-07-12 17:48:47 +02:00
Gina Häußge 0fec3aeca9 Merge branch 'patch-1' of https://github.com/cvignac/OctoPrint into maintenance 2016-07-12 11:52:27 +02:00
cvignac 12fcfda481 Typo correction in slicing.rst
In 'Retrieve all slicing profiles' :
'GET /api/slicing/profiles' -> 'GET /api/slicing'
2016-07-10 15:40:24 +03:00
Gina Häußge 58ee5f17f7 Fix simulation of moves on virtual printer 2016-07-08 16:44:40 +02:00
Gina Häußge a7fe2d5148 Clean up old AND invalid entries in preemptive cache config 2016-07-07 10:22:37 +02:00
Gina Häußge d96a91ecc3 Fix modal background of update confirmation not vanishing 2016-07-06 15:30:36 +02:00
Gina Häußge 924d5c8d7d More error resilience in template rendering
Wrapped potentially external and problematic includes in
custom try-endtry-blocks
2016-07-06 15:09:38 +02:00
Gina Häußge 5126fc1093 Fixed an import error introduced through moving the jinja trycatch extension
(cherry picked from commit 3ea77c7)
2016-07-06 15:03:43 +02:00
Gina Häußge 162c4f11dd Moved jinja ExceptionHandlerExtension to octoprint.util.jinja
(cherry picked from commit 3d0fc8d)
2016-07-06 15:03:34 +02:00
Gina Häußge 240fe70902 Custom try-catch block for jinja
Allows some more error checking in templates. Not used at the moment but
might come in handy in the future.
(cherry picked from commit 7708eea)
2016-07-06 15:01:55 +02:00
Gina Häußge bef989961d Added @MoonshineSG to AUTHORS.md 2016-07-06 13:30:28 +02:00
Gina Häußge eeaf68d61a Better timeout defaults for intermediary page
In some situations an error could be displayed otherwise since
online.gif was available, intermediary.gif wasn't anymore, but pinging
the latter timed out before the next ping of the former.

(cherry picked from commit 7809ba8)
2016-07-06 13:16:01 +02:00
Gina Häußge 674d625150 Transfer query & fragment on intermediary page reload
Also user window.location.reload if URL to reload is the same as the current one,
otherwise reloading will be a no-op if a fragment is provided.

(cherry picked from commit a367902)
2016-07-06 13:15:50 +02:00
MoonshineSG bfecb5fadf fix intermediary.html for url with parameters
(cherry picked from commit 2cc5eaf)
2016-07-06 13:15:34 +02:00
Mark Walker 5eefee3a4d RepRapFirmware style M23 select file
RepRapFirmware enumerates the gcode files starting at /gcode, it will
also interpret any relative path as being relative to that folder.
However a full absolute path will actually interpret as from the real
root of the SD card :-(

(cherry-picked from ac68570)
2016-07-06 05:17:44 +00:00
Mark Walker 02b0e906f1 Allow M23 "File opened" response with no filename
(cherry-picked from ba4b7c0)
2016-07-06 05:17:29 +00:00
Mark Walker 3069e05766 Add RepRapPro style file opened to virtual printer
(cherry-picked from 257c4ed)
Conflicts:
	src/octoprint/plugins/virtual_printer/virtual.py
2016-07-06 05:14:10 +00:00
Gina Häußge 8c80e3ac4a Scalar3D => Vector3D 2016-07-05 14:53:16 +02:00
Gina Häußge 79d660f377 Further GCODE interpreter fixes & optimizations
* Introduce Vector3D type to help with coordinate back and
    forth calculations
  * Fix typo in movement calculation (Y twice instead of Y and Z)
  * Removed some code duplication
2016-07-05 13:22:16 +02:00
Salandora 2ae2405792 Add diff part to retract too because of things like G1 X-10 Y-10 Z1 E-5
(cherry picked from commit de325c3)
2016-07-05 13:16:07 +02:00
Salandora 6e42e3e0ef Add calculation for moves in Z direction
(cherry picked from commit b9cf42f)
2016-07-05 13:16:02 +02:00
Salandora ad3ae405f6 Check for moveType == move instead of x,y,z is not None, otherwise x,y,z,e moves wouldn't be seen as extrude/retract moves
(cherry picked from commit 1b6a46c)
2016-07-05 13:15:55 +02:00
Gina Häußge 93b247b088 Display fuzzy time estimates in frontend 2016-07-05 13:15:20 +02:00
Gina Häußge 6018bf8428 Fix overeager preemptive caching, even on broken protocols 2016-07-04 19:28:20 +02:00
Gina Häußge a49bc9ca75 Fixed wrong placeholders in format string for exception 2016-07-04 19:02:12 +02:00
Gina Häußge cdbc8fcfbd Merge branch 'improve/wrongUploadError' into maintenance 2016-07-04 13:20:30 +02:00
Gina Häußge e453201c1a Better "upload error" message with supported extensions 2016-07-04 13:20:15 +02:00
Gina Häußge ec97765c80 Scroll to uploaded file, highlight it 2016-07-04 13:17:16 +02:00
Gina Häußge be34f7309d Scroll to uploaded file, highlight it 2016-07-04 13:14:38 +02:00
Gina Häußge dbf1273e9d Use first destination extension for default target name 2016-07-02 18:10:05 +02:00
Gina Häußge 944775abde Fixed registered destination extensions in cura plugin 2016-07-02 18:07:59 +02:00
Gina Häußge e7c21b1978 Support alternative source file types in SlicerPlugin
Also limit list of slicers in slicer dialog to compatible slicers.

Implements #935
2016-07-02 18:05:11 +02:00
Gina Häußge 73a85646c5 Added only pause/resume sub commands to job API
Implements #1393
2016-06-30 12:56:18 +02:00
Gina Häußge 0376bc4235 Only use first value for X-Scheme for reverse proxy setup
Solves #1391
2016-06-29 12:16:28 +02:00
Gina Häußge c70708e915 Fixed changelog for 1.2.13
Will stay this way now for 1.2.13 though, already released. Follow up versions
should reflect the contents of the release notes however.
2016-06-16 13:26:30 +02:00
Gina Häußge 01c5b77f7b maintenance branch is now 1.2.14.dev 2016-06-16 13:14:33 +02:00
Gina Häußge cb2e0d449f Preparing release of 1.2.13 2016-06-16 12:19:17 +02:00
Gina Häußge 6c20e58529 Handle browsers w/o support for visibility tracking 2016-06-16 12:10:14 +02:00
Gina Häußge 611c1ccf4a Disable GCODE viewer if browser is unsupported 2016-06-16 12:08:46 +02:00
Gina Häußge 397f762182 Don't trigger initial passive login before viewmodels are available
Closes #1374
2016-06-15 17:15:57 +02:00
Gina Häußge ad201b040d Don't parse B: in position as bed temperature
Closes #1373
2016-06-15 16:27:51 +02:00
Gina Häußge 0274b0f25b Have virtual printer report back with "B:" in line
Similar to Marlin with enabled COREXY. Useful for testing
parser behaviour.
2016-06-15 16:22:37 +02:00
Gina Häußge 0bb467e884 Ensure temperature graph to be properly initialized 2016-06-09 13:41:14 +02:00
Gina Häußge be711dd691 maintenance branch is now 1.2.13.dev 2016-06-09 12:16:27 +02:00
Gina Häußge 685ce16c85 Preparing release of 1.2.12 (part three)
Forgot to add the news category of the blog to the announcement
plugin and also updated the list of patrons again.
2016-06-09 09:31:36 +02:00
Gina Häußge 885b48911e Preparing release of 1.2.12 (part two)
Another update of the CHANGELOG after fixing a bug. Shifted release date
to tomorrow to leave more time for final tests that was now eaten up by the
last minute bug fix.

Also updated CONTRIBUTING file to explain new prerelease branch.
2016-06-08 16:48:39 +02:00
Gina Häußge d7ef60b4d2 Slight change in function definition of reused functions (JS) 2016-06-08 16:33:08 +02:00
Gina Häußge 63cec660ca Solve a race condition that could cause 401 responses and a broken UI
Closes #1364. See ticket for details.
2016-06-08 16:21:25 +02:00
Gina Häußge 4c34cb84c7 Preparing release of 1.2.12 2016-06-08 13:09:04 +02:00
Gina Häußge d3d4d4e407 Merge branch 'prerelease' into maintenance 2016-06-08 11:21:22 +02:00
Gina Häußge e9f80c6616 Added new prerelease branch to versioneer config
Can be used in the future for tracking prereleases and testing
proper version updates without having to push to master directly.
2016-06-08 11:19:21 +02:00
Gina Häußge 5006b019af Add events for slicing profile manipulation
Events SlicingProfile(Added|Modified|Deleted). Initially thought to be necessary
to properly refresh available profiles in slicing dialog, not needed for that after
all but still left in and documented, might be useful for someone.
2016-06-06 18:12:32 +02:00
Gina Häußge 4f3e4f7f38 Force rescanning of available slicing profiles for slicer on update
Should make newly uploaded profiles available in the slicing dialog without
having to first deselect and then reselected the current slicer.
2016-06-06 16:20:47 +02:00
Gina Häußge a0697f8bad Use movie prefix for timelapse notifications
Also added a missing lock.

Also part of the fix for #1320
2016-06-02 12:03:57 +02:00
Gina Häußge 2833372603 Allow deletion of *.mp4 timelapse files
That one was missing in a00faf2.

Fixes #1320
2016-06-02 11:11:06 +02:00
Gina Häußge 8ce1eafd5d Properly track unrendered timelapses that are being processed
UI removes action buttons for them and displays a spinner
indicating that the timelapse in question is either being
recorded or being rendered at the moment.

Should prevent users from accidentally trying to render an
incomplete timelapse.
2016-06-02 10:11:54 +02:00
Gina Häußge 21a4033f73 Don't concurrently delete unrendered timelapses
Could trigger lots of errors if an unrendered timelapse currently
being collected was deleted from a separate thread from right
under the collection thread.

Also only log errors while processing already deleted files
if debug logging is enabled.

Finally trigger MovieDone event AFTER deleting unrendered
files (otherwise just rendered timelapse might still be present
when list of timelapses is queried right after).

Should solve #1326
2016-06-02 10:05:44 +02:00
Gina Häußge 51a1953d99 Move timelapse event processing to timelapse viewmodel 2016-06-01 13:24:29 +02:00
Gina Häußge 30b6211157 Whitelist .g extensions on sd file upload
That way uploading something like auto0.g will not
cause a rename to auto0.gco anymore.

Closes #1314
2016-06-01 12:29:42 +02:00
Gina Häußge 36ec9c4741 Do not sort events in the event queue alphabetically
This should never have been a PriorityQueue, or at the very least it should
never have the data itself in a sortable structure.

Thanks to processing speed of the event queue that seldomly showed,
only in cases where two events entered the queue almost simultanously,
e.g. when starting to render a timelapse movie and immediately failing.

Should solve #1343
2016-06-01 10:29:47 +02:00
Gina Häußge 1581ebbead Fix error when trying to confirm the edit-user-dialog
Closes #1357
2016-05-31 13:32:14 +02:00
Gina Häußge 436ebd7c18 Add help text re units for disk space thresholds
Closes #1338
2016-05-20 11:04:42 +02:00
Gina Häußge 801d60388a Also report 0% print progress to plugins
Fixes #1344
2016-05-20 10:24:47 +02:00
Gina Häußge 821fa4299b Let's go all in and use keyword parameters
Way less error prone than positional arguments!
2016-05-19 18:35:02 +02:00
Gina Häußge b018a56e4c Merge branch 'maintenance-pid_cleanup' of https://github.com/kevans91/OctoPrint into fix/1324 2016-05-19 18:32:46 +02:00
Gina Häußge b1e75a1033 Make connection dialog visible for users again
Should actually not have been limited to admins-only, that was an accident
during switching to 1.2.0 implementation.

Once #1110 is tackled, this should be something configurable based on the role
as well.
2016-05-19 10:42:27 +02:00
Kyle Evans 86fbbefb6e Complete backport of pid cleanup fix for #1324 2016-05-15 09:16:53 -05:00
Gina Häußge 2c0fa7c1d1 Added @kevans91 to AUTHORS.md
(cherry picked from commit 425fa8e)
2016-05-12 10:52:25 +02:00
Kyle Evans 8263c6072a Make Server class octoprint_daemon-aware, make sure terminated() gets invoked on it upon SIGTERM and update respective test
(cherry picked from commit 75f8fac)
2016-05-12 10:44:27 +02:00
Gina Häußge 91b5fc6b0d Force synchronization of sockjs message sending 2016-05-10 09:48:20 +02:00
Gina Häußge 1225a2501d Fix a stupid mistake in the german translation 2016-05-09 15:27:17 +02:00
Gina Häußge 34c068b964 maintenance branch is now 1.2.12.dev 2016-05-09 10:12:46 +02:00
Gina Häußge e79703ba6e Preparing release of 1.2.11 2016-05-04 13:36:06 +02:00
Gina Häußge fb1fd37482 Updated list of supporters for May 2016-05-04 13:29:06 +02:00
Gina Häußge 4830d60269 Announcements: Ensure validity of channel keys, made refreshable 2016-05-04 13:28:28 +02:00
Gina Häußge 76959e06c9 Updated german translation 2016-05-04 09:57:25 +02:00
Gina Häußge 5a8c3654c4 We leave the About dialog untranslated for now 2016-05-04 09:51:50 +02:00
Gina Häußge a9756c4c36 Announcements: no read_until -> take latest from feed 2016-05-03 17:36:43 +02:00
Gina Häußge 9919de9a6c Added padding to announcement reader content pane 2016-05-03 10:22:23 +02:00
Gina Häußge 5091099f83 Added "About" link to settings dialog 2016-05-03 10:21:59 +02:00
Gina Häußge 7c6b9eac48 Added externalize_links filter for jinja2
Links from documents (like changelog, licenses etc) should
also be target blank & rel noopener/noreferrer
2016-05-03 09:59:37 +02:00
Gina Häußge 7a8e6b6b6d Use UTC for feed reader timestamps 2016-05-03 09:17:48 +02:00
Gina Häußge 50ae34dc4f Forgot the css file of the announcements plugin 2016-05-02 17:49:32 +02:00
Gina Häußge cbb692de30 Forgot to rename SPONSORS.md in .gitignore 2016-05-02 17:41:03 +02:00
Gina Häußge cc7dcbf6b6 Added support link to README 2016-05-02 17:38:50 +02:00
Gina Häußge 8f621eca43 Merge branch 'improve/announcementPlugin' into maintenance 2016-05-02 17:38:21 +02:00
Gina Häußge 9e73f1563d Strip paragraphs from summaries for announcement notifications 2016-05-02 17:32:36 +02:00
Gina Häußge 3a570f8ab0 Added OctoPi + Spotlight feeds, article link, better reader design 2016-05-02 17:14:48 +02:00
Gina Häußge 62aee50701 rel="noopener noreferrer" for external links 2016-05-02 11:48:08 +02:00
Gina Häußge 789e9922d1 Some improvements in the about dialog
* Sponsors => Supporters
  * Links to individual About dialog tabs from start page
  * Slight rewording here and there
  * rel="noopener noreferrer" for external links
2016-05-02 11:25:05 +02:00
Gina Häußge 58fc67bd99 Fixed feed links in feed viewer 2016-05-02 11:02:53 +02:00
Gina Häußge d322c365ce Updated feeds 2016-05-02 10:12:18 +02:00
Gina Häußge 652158d17a WIP: Announcement plugin 2016-05-02 10:12:17 +02:00
Gina Häußge 73d981ed6b Show - instead of None in About dialog if plugin has no license set 2016-05-02 10:10:27 +02:00
BillyBlaze 8e98e9c40c Allow an invalid session to logout from logedin state 2016-04-30 10:36:03 +00:00
BillyBlaze 119f727c8d Knockify the distance on the control tab 2016-04-21 19:39:28 +00:00
Gina Häußge 5e6a7ef605 Added sponsor list 2016-04-21 11:56:56 +02:00
Gina Häußge a319e8c497 Added trademark note to about dialog
(cherry picked from commit 48b984c)
2016-04-19 16:42:04 +02:00
Gina Häußge 3cc1c012bb Reset scroll position and selected tab in about dialog
(cherry picked from commit 4e84d62)
2016-04-19 16:41:43 +02:00
Gina Häußge e0b888b2d0 First throw at an "About" dialog
(cherry picked from commit f2c07e8)
2016-04-19 16:41:30 +02:00
Gina Häußge f050b4e5cb Merge remote-tracking branch 'origin/maintenance' into maintenance 2016-04-19 14:57:46 +02:00
BillyBlaze 5a3e9e7aba Fix wrong css data-binding 2016-04-09 21:46:32 +00:00
Salandora 8f0b7dd6d1 Fix timelapse postroll
Images got captured with wrong filename
Additionally fixed some refactoring mistakes
2016-04-02 15:41:27 +02:00
Mark Walker 183ca3291b If no SD card support, remove SD file filter
When SD card support is disabled on the server, remove any client side
filtering to just SD files since there aren't any and there won't be UI
turn remove the filter either.  Should address #1300
2016-03-28 12:59:08 -07:00
Gina Häußge b54e1b44a4 Added checksum checking to virtual printer 2016-03-18 15:00:03 +01:00
Gina Häußge 1a4c06d6f6 Added flag to trigger ok for resend requests
That's necessary to keep communications going in case of a resend request
for firmwares that do not send an ok after a resend request.
2016-03-18 14:59:13 +01:00
Gina Häußge a229cbfd49 maintenance branch is now 1.2.11.dev 2016-03-16 10:55:08 +01:00
Gina Häußge 692166f067 Preparing release of 1.2.10 2016-03-16 09:38:58 +01:00
Gina Häußge 69dca5b58c Updated german translation 2016-03-16 09:22:10 +01:00
Gina Häußge 6305c4d2eb Timeout for comm closing, also wait for send queue on close
We don't want to wait indefinitely for our send and command queues to empty, so
we don't use .join but instead a busy timeout wait routine.

Also fixed a couple of small issues found while preparing comm unit tests.
2016-03-15 17:09:01 +01:00
Gina Häußge b5cf20a1de Have comm layer wait until all lines are sent before disconnect
Added parameter "wait" to "close" method, defaults to True. Will have the
close method wait for all lines to be sent that are currently in the send queue.

In case of an error, no waiting will be done.

Made it necessary to correctly track task completion in the send queue, also
made that change to the command queue while at it.

Backported from devel, commit 7f2476e513
2016-03-14 11:59:02 +01:00
Gina Häußge 5807b606f0 Added @2bitoperations to AUTHORS.md
Was missing from PR #1255
2016-03-14 11:50:50 +01:00
Andrew Malota 398eaf58a9 allow download/management of mp4 timelapse too
(cherry picked from commit a00faf2)
2016-03-14 11:48:58 +01:00
Gina Häußge 4a933228c7 Added PR and issue templates, updated CONTRIBUTING.md 2016-03-14 11:43:15 +01:00
Gina Häußge 56caa7750c Twice as fast checksum calculation
Thanks @nophead!
2016-03-12 09:40:33 +01:00
Gina Häußge 38a47bb2a8 Change wording: not firmware error, but communication error
"Error:" lines can also be produced by OctoPrint itself in case of serial exceptions or
connection failures, so "the firmware reported" was misleading.
2016-03-11 18:06:14 +01:00
Gina Häußge e6f9003549 Reset line numbers before entering sd upload state
Otherwise M110 N0 will not be processed to be prefixed with N0 and hence
not reset the line numbers on the printer to 0.

That was as bug in 1a308a1bc7
2016-03-11 18:01:22 +01:00
Gina Häußge 5cadf85401 Only report transfer rates in the log for sd uploads
For real prints they are misleading - mechanical movement takes time.
2016-03-11 17:58:00 +01:00
Gina Häußge baab1ce70a Use new generic TypedQueue for send queue and command queue
That way no M105 cascades can be triggered by the  M105 polling timer (or the M27
polling timer).

Adjusted logging output to make clear which queue rejected typed entry.

Made timeout handler send M105 with type "temperature" as well to make sure
we don't suddenly have two M105 directly after each other in the send_queue,
one from the polling timer, one from the timeout handler.

Fixes #1275
2016-03-11 17:25:39 +01:00
Gina Häußge cbaf848711 Move TypedQueue to octoprint.util & make generic
put and get are now overwritten to create t-tuple out of provided item
and item_type on put, and to only return item on get.

_put and _get extract item_type and use that for managing the
lookup set.
2016-03-11 17:20:26 +01:00
Gina Häußge 85060b972a Fix _handle_timeout not correctly honoring long runners
Issue was introduced through #1271 fix.
2016-03-11 17:20:13 +01:00
Gina Häußge 29aefdec08 Don't send M20 twice after streaming to SD
Fixes #1274
2016-03-11 16:48:03 +01:00
Gina Häußge 6e01a361c5 Make "Fake Acknowledge" button really fake an ok
So far it only set the clear_to_send flag, now it actually does everything
else a read ok would do.
2016-03-11 16:35:15 +01:00
Gina Häußge 542ccb5421 Slight simplification of setProgressData calls in standard printer 2016-03-11 16:29:59 +01:00
Gina Häußge 6d8eb682c1 Use concatenation instead of format strings in comm layer 2016-03-11 12:45:30 +01:00
Gina Häußge d701c261c3 Less processing overhead when uploading to SD
Better structured "don't handle phases" checks and adjusted
job wrapper that doesn't try to apply tool tracking or temperature
offsets.
2016-03-11 12:35:53 +01:00
Gina Häußge 7b16f38ba3 Fetch timeouts for communication only once from settings 2016-03-11 11:16:27 +01:00
Gina Häußge 337329eda0 Added test stub for quick performance tests of the comm layer
Running comm.py with parameters port, baudrate, local file, remote file will
upload local file to remote file on the printer's sd using the provided connection
parameters.

Example:

    python -m octoprint.util.comm /dev/ttyUSB0 115200 /path/to/some.gcode test.gco

No plugin support! Only regular serial connection supported.
2016-03-11 10:43:02 +01:00
Gina Häußge 47b7552f91 Decouple comm progress reporting from processing 2016-03-11 08:48:18 +01:00
Gina Häußge 6736224962 Removed logging from CountedEvent 2016-03-11 08:28:39 +01:00
Gina Häußge c9009496f6 Don't trigger an M105 on timeout during a resend
Had to reorder message processing a bit in order to be able to
properly handle further resends in timeout situations.

Has the added benefit that "ok" now gets processed very early
and now extra state based processing is needed anymore.
2016-03-10 19:05:16 +01:00
Gina Häußge d393a6730c Don't have M28 response generate extra "ok"
Fixes #1272
2016-03-10 16:03:52 +01:00
Gina Häußge 069bfdd9f8 New flag to have M29 response inject "ok"
Adjusted virtual printer to allow marking of M29 as broken re sending
of ok.

Fixes #1273
2016-03-10 15:58:59 +01:00
Gina Häußge 23d2cdec76 Use 0 as default bed temperature in slicer
Should prevent slicing result to contain bed temperature settings even if
printer has a heated bed configured unless slicing profile also contains a
temperature.

Fixes #1268
2016-03-10 11:55:17 +01:00
Gina Häußge 1a308a1bc7 Reset line numbers for sd streaming as well 2016-03-09 15:44:23 +01:00
Gina Häußge 13098dde00 Removed unused "{start|end}SdFileTransfer" 2016-03-09 15:37:33 +01:00
Gina Häußge 27d1a6ca37 Virtual printer: request correct line in dummy resend 2016-03-09 15:33:17 +01:00
Gina Häußge 1616fb4de8 Better error reporting in comm layer
Option to log last terminal lines before a resend (defaults to off for now),
more exception logging in octoprint.log in various error cases, also log
unsolvable resend requests with requested and current line number.
2016-03-09 15:24:40 +01:00
Gina Häußge 07d8d4b88d Made virtual printer a bit faster 2016-03-09 12:09:44 +01:00
Gina Häußge 2a3d9c291d Fixed a merge error 2016-03-09 11:54:05 +01:00
Gina Häußge b36290a1f2 Added new serial config options to UI
Also pushed more advanced config option into an initially hidden
"Advanced Options" section, similar to other places.
(cherry picked from commit 84b343a)
2016-03-09 11:41:49 +01:00
Gina Häußge 48d74ef2fd Improved handshake procedure on comm layer
"Hello" command sent to printer to trigger initial handshake can now be
configured. Commands that _always_ necessitate to be sent with checksum/
line number (e.g. M110 on Marlin) can be configured as such too.

Also fixed an issue causing the "Hello" command to not be actually enqueued
first thing on opening a connection. Seems to not have caused harm in the
wild, but was unintentional.
(cherry picked from commit 5c2ae37)
2016-03-09 11:23:50 +01:00
Gina Häußge 35e20162ec Revert "Improved connecting phase"
Improved connecting for some printers, destroyed it
completely for others, so this needs some more work/
thought before it's ready for prime time.

This reverts commit c82ec3d3af.
2016-02-22 13:33:34 +01:00
Gina Häußge c82ec3d3af Improved connecting phase
M110 is now sent every second until either a connection is established or the connection
attempt times out. That should prevent connection handshakes from failing due to
some initial garbage on the line that swallows an ok.
2016-02-17 11:33:49 +01:00
Gina Häußge 5c06bd5036 Kill background tasks of virtual printer on disconnect
Otherwise there might be errors with wait-for-heatup or sd printing
situations where self.outgoing is gone suddenly.
2016-02-16 15:09:22 +01:00
Gina Häußge 21034b381c Cancelling a print that is not ongoing doesn't make sense 2016-02-16 10:04:06 +01:00
Gina Häußge beb5850361 Only try to record recovery data if a print was ongoing 2016-02-16 10:03:02 +01:00
Gina Häußge 1ea0cf9213 Always reset the job data on disconnect
If former state was "Printing", so far the full disconnect state handling
wasn't done properly.
2016-02-16 09:52:56 +01:00
Gina Häußge 4081a25f48 Merge branch 'fix/errorOnSdCardFail' into maintenance 2016-02-16 09:28:43 +01:00
Gina Häußge 718a102d44 Merge branch 'fix/wrongTrackingOfM109ForMultiextruder' into maintenance 2016-02-16 09:24:44 +01:00
Gina Häußge 49f4a0c5b0 line == "ok" => line.startswith("ok")
Fixes an issue introduced with M109 fix that causes
"SD card ok" not to be parsed correctly anymore.
2016-02-16 09:23:25 +01:00
Gina Häußge d267a752cd Capture NoSuchStorage error on SD card fails
We currently do not have a storage configured for SD card since
that hasn't yet been ported to the storage interface. So on an
SD card fail we need to capture that error when attempting to log
the print recovery data, or there will be issues processing
the cancel properly. A bit more of error handling is a good
idea here in any case too.

Fixes #1226
2016-02-16 09:13:22 +01:00
Gina Häußge 632724a023 Updated CONTRIBUTING.md
* Don't add red herrings to tickets
  * Provide all information when actually experiencing the same
     symptoms as an existing ticket
2016-02-16 08:42:05 +01:00
Gina Häußge eb48a50139 Fixed wrong tracking of current tool for M109 Tn heat-ups 2016-02-15 19:44:21 +01:00
Gina Häußge 0a3dc4b354 Fixed a bug that prevented the "Upload to SD" button from working
Introduced with the bug fix for #1196

Closes #1224
2016-02-15 09:58:04 +01:00
Gina Häußge fe134e7986 Added back the "test without plugins" clause to the bug reporting guide 2016-02-12 12:10:19 +01:00
Gina Häußge b5f40cfd69 Always read all available lines from stdout and stderr
Should produce faster output.
2016-02-11 10:36:19 +01:00
Gina Häußge 3fb9248d2a More timelapse unit tests 2016-02-10 16:44:46 +01:00
Gina Häußge 3dd0ace076 maintenance branch is now 1.2.10.dev 2016-02-10 16:44:18 +01:00
Gina Häußge abe68adac8 Preparing release of 1.2.9 2016-02-10 14:47:18 +01:00
Gina Häußge 99c65b8cf4 Unit test for unrendered timelapse cleanup 2016-02-10 14:40:10 +01:00
Gina Häußge 742818c2ca Delete unrendered legacy timelapses when encountering them 2016-02-10 14:34:33 +01:00
Gina Häußge d4072a3afd Updated translation files & german translation 2016-02-10 12:43:13 +01:00
Gina Häußge 92c65cb21c Added info about branches and versioning to contribution guide 2016-02-10 11:09:31 +01:00
Gina Häußge d20a9f64a2 Updated AUTHORS.md
(cherry picked from commit ab52e28)
2016-02-10 10:16:04 +01:00
geoporalis ed82488c5b typo fixed
(cherry picked from commit 4e91284)
2016-02-10 10:15:41 +01:00
Gina Häußge 5955d3d32e Added estimates total time from gcode viewer to gcode viewer tab
Implements request in #1204
2016-02-10 09:58:40 +01:00
Gina Häußge 682c3dd8e3 Limit file upload dialogs to supported file extensions
See #1196
2016-02-09 18:03:04 +01:00
Gina Häußge 56f2dc9d8e Make improve/... branches behave as maintenance branches
Felt too wrong to call improvements fixes all the time.
2016-02-09 17:55:29 +01:00
Gina Häußge 71941f337d Include cursor control characters in CSI ANSI regex pattern 2016-02-09 14:48:30 +01:00
Gina Häußge b347e96748 Pip 8 outputs ANSI codes which we don't want in our output 2016-02-09 12:54:59 +01:00
Gina Häußge 8069d08d3b Do not hiccup on manually sent M28 commands
In case of trying to switch to state printing with no selected file that
scenario is now caught by setting an internal manualStreaming flag.
That will stop the M105 polling until M29 is sent (through whatever
means).

Note that printing is not disabled... this is merely for testing stuff and
not encouraged to be used for actually streaming files to the printer,
use the built-in functionality for that!
2016-02-09 11:32:56 +01:00
Gina Häußge 4b7552e56e Fixed file manager unit tests, added tests for print recovery functionality 2016-02-09 10:45:54 +01:00
Gina Häußge c4a1ed2590 Merge branch 'maintenance' into fix/persistPrintRecoveryData 2016-02-08 19:28:40 +01:00
Gina Häußge e443c7df2f Use path in storage instead of full path for print recovery 2016-02-08 16:44:37 +01:00
Gina Häußge b9372d7300 Fixed wrongly positioned parenthesis
Caused an internal server error if / was requested with a different default language than
english that was not available in the i18n bundles.
2016-02-08 13:04:02 +01:00
Gina Häußge 9e8b5312d5 Persist print recovery data on print failures 2016-02-08 12:47:13 +01:00
Gina Häußge f79d496c7c Revert "Only trigger drag overlay for files, not texts"
This reverts commit 1e429606e1.

Commit used functionality that currently is only available in
Chrome and maybe Opera. No alternative solution could be found
that works reliably across browsers.
2016-02-03 11:43:55 +01:00
Gina Häußge 73a587b3e4 Added missing entries to AUTHORS.md 2016-02-03 09:04:27 +01:00
Gina Häußge fac4aad05f Merge branch 'master' of https://github.com/2ndalpha/OctoPrint into pr/2ndalpha/master 2016-02-03 08:58:59 +01:00
Gina Häußge c53c263805 Merge branch 'fix/includeReleasenotesInUpdateNotifications' into maintenance
Conflicts:
	src/octoprint/plugins/softwareupdate/__init__.py
	src/octoprint/static/css/octoprint.css
2016-02-02 20:23:02 +01:00
Gina Häußge 4e31ccf4c5 Big overhaul of timelapse handling
* persistent notification on ongoing timelapse render job (#485)
  * non-colliding timelapse snapshot name generation to not delete
     existing snapshots when new print starts and timelapse has not
     yet been rendered, also only delete snapshots if timelapse rendered (#318)
  * list of unrendered timelapses, with option to delete files
    or to render timelapse
2016-02-02 18:03:56 +01:00
Siim Raud c4e2a8982f Fixed formating 2016-02-02 00:40:52 +02:00
Siim Raud 42dafd7565 Fixed parsing of "retraction_combing" 2016-02-02 00:35:52 +02:00
Gina Häußge 6ce82ceb00 Merge branch 'fix/optionToIgnoreFirmwareErrors' into maintenance 2016-02-01 18:02:29 +01:00
Gina Häußge 6583691e85 Added setting to only cancel ongoing print on firmware error
Also added error popup in such a case so the error will be known even
if the terminal tab scrolled past it.
2016-02-01 18:02:21 +01:00
Gina Häußge 2f44f10eb0 Merge branch 'fix/knockout3.4' into maintenance 2016-02-01 16:56:13 +01:00
Gina Häußge 0e817d43cc Added option to ignore any errors reported by the firmware
Use this carefully. An error reported by your firmware usually hints
at something being off about your printer (e.g. thermistor troubles)
or the firmware not being fully compatible to OctoPrint since
it doesn't recognize a lot of commands.

If you print with this option enabled, it will still fail if you firmware goes
into lockdown, but now it will keep trying to send data to your printer.

That might cause issues. So best not use that option, only if you absolutely
have no other way to get some misbehaving printer to work with
OctoPrint.
2016-02-01 16:55:13 +01:00
Gina Häußge 7f1394a8d6 Migrated ko.computed to ko.pureComputed where it made sense 2016-01-27 17:33:03 +01:00
Gina Häußge caaf1d229c Updated Knockout dependency to version 3.4.0
Closes #939
2016-01-27 17:32:40 +01:00
Gina Häußge 36ae6dd6b9 Added adaptive rate limiting to client
The client now tries to detect if it's fast enough to process the
state updates usually send every 500ms, and if not notifies the
server to throttle the rate (e.g. to 1/1s, 1/1.5s etc).

Additionally, since the terminal tab of the client turned out to
be quite CPU intense when line number calculation, filtering etc
is enabled, the terminal tab now also falls back into a bit less
fancy mode if it detects its being processed too slow and optionally
even disables logging completely during printing (where a lot
of log messages need to be processed in a minimum amount of
time).

That way the UI should stay responsive even on very low powered
clients (e.g. chromium on a Pi), while printing.
2016-01-27 12:04:17 +01:00
Gina Häußge bcd7bb4d20 Don't enable Print button if no job is selected
Fixes #1007
2016-01-25 16:28:52 +01:00
Gina Häußge 8151e617cc Merge branch 'maintenance' of github.com:foosel/OctoPrint into maintenance 2016-01-25 14:41:52 +01:00
Gina Häußge 1e429606e1 Only trigger drag overlay for files, not texts 2016-01-25 14:39:48 +01:00
Gina Häußge 7fbfaadc21 Do not read no return value as "False" return value for onServerDisconnect 2016-01-25 13:51:46 +01:00
Gina Häußge 814355e281 Do not show drag-n-drop overlay if server is offline
Fixes #1196
2016-01-25 13:51:10 +01:00
Gina Häußge c720cc3a4a Added note to not misuse (feature) requests for support questions 2016-01-21 10:58:00 +01:00
Gina Häußge 660de61997 Merge remote-tracking branch 'origin/maintenance' into maintenance 2016-01-19 11:51:15 +01:00
Gina Häußge f4b3206d49 Disable the settings dialog's save button while sending or receiving 2016-01-19 11:19:51 +01:00
Gina Häußge 4abfa6c3b3 Updated installation instructions 2016-01-13 17:12:41 +01:00
Gina Häußge 2a059cf0cb Reset scroll position and selected tab in settings dialog
Also added means to open settings dialog navigating directly to a specific tab
2016-01-12 13:30:10 +01:00
Gina Häußge 7743372ee4 Slugify file names on local storage
Just stripping anything non-ASCII leads to errors with UTF-8 only
filenames.

Closes #1181
2016-01-11 16:42:05 +01:00
Gina Häußge 59027d349f Added button to refresh file list
Also added tooltips for all three file list buttons
2016-01-11 15:41:38 +01:00
Gina Häußge 9fd8b09e34 Fixed custom control M114 example to also match negative coordinates 2016-01-05 11:48:55 +01:00
Gina Häußge 450e24bbc2 Added missing AUTHORS.md entry 2016-01-05 11:42:38 +01:00
Gina Häußge c020c7afe0 Merge branch 'master' of https://github.com/richjoyce/OctoPrint into pr/richjoyce/settings_remove_fix 2016-01-05 11:40:18 +01:00
Richard Joyce 0d7965ebf1 Fix missing kwargs in PluginSettings remove 2016-01-04 09:25:58 -08:00
Paul de Vries 34ceb93509 Initialize loginUser and loginPass with an empty string
Clear loginUser and loginPass after a successful login (e.g. the user made a typo)
2016-01-03 22:02:49 +01:00
Gina Häußge c120261e2b Increased backend fail counter for intermediary page
Also made sure that baseURL always ends in a /
2015-12-18 17:39:30 +01:00
Gina Häußge f0acacec6a Intermediary page needs to remove fragments for baseUrl
Otherwise image pinging won't work properly.
2015-12-18 14:30:53 +01:00
Gina Häußge 9fbe130169 Merge branch 'fix/aclFirstRun' into maintenance 2015-12-17 13:19:26 +01:00
Gina Häußge b96d1b51e0 Disabled ACL is now tracked through enabled flag on UserManager
That allows us to properly enable and disable it at runtime (during first run).
2015-12-17 13:08:45 +01:00
Gina Häußge 570c66b6f3 Trigger command processing on unknown commands
We suffer from the same problem as commands being suppressed in the
send queue here. If a non-GCODE-command we send to the printer
produces no output, our _monitor loop will wait until the next response
produced by another command. Which we won't send though since
we are stuck waiting in the _monitor loop waiting for a response. Hence
we need to manually trigger further command processing from the
send loop here in order to ensure things keep going.
2015-12-17 10:44:43 +01:00
Salandora ccd2ddc056 Fixed a bug with access control during first run
Requests against restricted resources could fail even though the
first run wizard had been completed successfully.
2015-12-16 11:59:45 +01:00
Salandora 54f24b43f0 If no system actions were configured during rendering of the page, no system menu was added to the template.
hat caused system actions added during runtime (e.g. by API) to not show up until a re-rendering of the page.
2015-12-16 11:35:25 +01:00
Gina Häußge eae68f04ca Use PEP440 compatible version compatibility check
Also make sure that if we have a pkg_resources version that returns
tuples we not only remove any intermediary version parts if the base
version is requested, but we also append "*final" to the tuple afterwards,
otherwise the compatibility check will fail.
2015-12-14 14:14:44 +01:00
Gina Häußge 7fcd04ae61 Also use pre-calculated revision information instead of fetching anew 2015-12-14 10:16:29 +01:00
Gina Häußge 1a4920fc36 Display remote version in update message, not local one... 2015-12-10 17:12:02 +01:00
Gina Häußge 8149a3b4a8 Include release notes in update notification
... and confirmation dialog and settings dialog.

github_release fetches release notes link from github. Check configurations
can always set individual release notes links via the new `release_notes`
property. The URL also supports placeholders `{octoprint_version}`,
`{target_version}` and `{target_name}`. A custom release note URL
hence could be configured by a plugin via

    def get_update_information(self):
        return dict(
            myplugin=dict(
                [...]
                release_notes="https://me.github.io/MyPlugin/my/custom/releasenotes.html#version_{target_version}"
                [...]
            )
        )

and if a new release "1.3.4" was now to be released would be displayed to the user as

    https://me.github.io/MyPlugin/my/custom/releasenotes.html#version_1.3.4

The same of course is possible via config.yaml:

    plugins:
      softwareupdate:
        checks:
          myplugin:
            release_notes: 'https://me.github.io/MyPlugin/my/custom/releasenotes.html#version_{target_version}'
2015-12-10 14:41:46 +01:00
Salandora e8bd29ef99 Replace get_versions() calls with octoprint.server.VERSION, to get some time improvment 2015-12-09 10:29:24 +01:00
Gina Häußge 8a7d234571 Merge branch 'fix/commTimeoutOnSupressedScriptCommands' into maintenance 2015-12-08 14:24:47 +01:00
Gina Häußge c5c5383e0e Fixed clean up of preemptive cache entries 2015-12-08 14:23:40 +01:00
Gina Häußge b4d25db9c8 Merge branch 'fix/betterUiCaching' into maintenance 2015-12-08 13:45:37 +01:00
Gina Häußge ef876cfd35 Fire up intermediary server on host and port
That way people will not see connection failed messages while the server is
still starting up.

Served intermediary page als "pings" an image on the backend to detect if
a) the backend is still responding at all ("intermediary.gif") and b) whether the
server has fully started up ("online.gif").

If the backend stops responding for 5s, a message is output that tells the user
that something went really wrong and to please check the log file.

Once the server becomes online, the intermediary page reloads/switches to the
actual UI.
2015-12-08 13:28:12 +01:00
Gina Häußge 547dcdd725 maintenance branch is now 1.2.9.dev 2015-12-07 14:58:19 +01:00
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 090671a044 Merge branch 'maintenance' into fix/commTimeoutOnSupressedScriptCommands 2015-12-02 17:26:25 +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 c0774d0dd8 Fix: Do not stall comm when a command is supressed while printing 2015-12-02 11:08:51 +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 fbc0b8af91 Merge branch 'maintenance' into fix/betterUiCaching 2015-12-01 10:40: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 63d095ab00 Refactored implementation of get_all_template_paths 2015-11-26 19:48:44 +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 c595d02f22 reload(true) shouldn't be necessary any more
UI + assets should actually have ETag and LastModified headers and proper
IfMatch handling on the server side and hence the server should do the
right thing on its own.
2015-11-26 14:15:06 +01:00
Gina Häußge 2e23cd39a4 Added ETag and LastModified headers + processing to UI index
That should improve performance tremendously.

Both ETag and LastModified depend on all files the template rendering
depends on. If any of the depended on files changes, both values will
change as well. That allows us to track whether our cached copy is
still current (and force a refresh if not) and also process IfMatch request
headers and reply with a 304 directly so that we do not even have to
transfer the data if nothing changed and the browser still has it.
2015-11-26 13:32:32 +01:00
Gina Häußge 3de4f91f50 Decoupled decorator from PreemptiveCache class
Coupling it led to problems (naturally) when there was no
PreemptiveCache instance available yet.
2015-11-24 18:41:53 +01:00
Gina Häußge 6473937b75 Refactore preemptive flask cache into a proper class
Also now tracks timestamps of last access to a preemptively cached
resource and cleans up stuff that hasn't been accessed in a while (7 days
by default)
2015-11-24 14:37:30 +01:00
Gina Häußge fab5fc4899 Added preemptive caching of / and /i18n/<locale>/messages.js
Introduced a @preemptively_cached decorator that for decorated views
persists the provided data in ~/.octoprint/data/preemptive_flask_cache.yaml
in a list indexed by the view's path if the data is not yet part of the list.

During initialization the server will iterate over the persisted paths and data
and for each persisted path and entry in the list initialize a temporary WSGI
environment based on the data (which is interpretated as keyword arguments
to werkzeug's EnvironmentBuilder) which will then be used to call the view
function in the correct context.

The current implementation for / and /i18n/<locale>/messages.js utilizes
that decorator to allow preemptive caching of those views (/ being probably
the most expensive one in the whole core application) utilizing request base URLs
(internal access, external access, reverse proxy with prefix url etc) that had been
encountered in the past.

Through the new config setting server.preemptiveCaching.exceptions it is
possible to define a set of base URLs to never cache. Preemptive caching can
be globally disabled by setting devel.cache.preemptive to false.
2015-11-23 17:35:25 +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
191 changed files with 21794 additions and 5555 deletions

No files matched your search

+9
View File
@@ -1 +1,10 @@
src/octoprint/_version.py export-subst
src/octoprint/static/js/lib/* linguist-vendored
src/octoprint/static/less/bootstrap/* linguist-vendored
src/octoprint/static/less/font-awesome.less linguist-vendored
src/octoprint/static/less/mixins.less linguist-vendored
src/octoprint/static/less/variables.less linguist-vendored
versioneer.py linguist-vendored
docs/* linguist-documentation
+79
View File
@@ -0,0 +1,79 @@
READ THE FOLLOWING FIRST:
If not already done, please read the "guidelines for contributing"
that are linked ^-- just up there in the big yellow box. Also read
the FAQ: https://github.com/foosel/OctoPrint/wiki/FAQ.
This is a bug and feature tracker, please only use it to report bugs
or request features within OctoPrint (not OctoPi, not any OctoPrint
plugins and not unofficial OctoPrint versions).
Do not seek support here ("I need help with ..."), that belongs on
the mailing list or the G+ community (both linked in the "guidelines
for contributing" linked above, read it!), NOT here.
Mark requests with a "[Request]" prefix in the title please. Fully fill
out the bug reporting template for bug reports (if you don't know where
to find some information - it's all described in the contribution
guidelines linked up there in the big yellow box). Do not delete any
lines from the template but those enclosed in [ and ] - and those please
DO delete, they are only provided for your information and removing them
makes your ticket more readable :)
Thank you!
(Before submitting your ticket, please delete this text up to and
including the line too - it's only here for you, we already know it
by heart ;))
----
#### 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. ALWAYS INCLUDE.]
#### 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.
serial.log is usually not written due to performance reasons and must be
enabled explicitly. Provide at the very least the FULL contents of your
terminal tab at the time of the bug occurrence, even if you do not have
a serial.log.]
#### 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.
+50
View File
@@ -0,0 +1,50 @@
Thank you for your interest into contributing to OctoPrint, it's
highly appreciated!
Please make sure you have read the "guidelines for contributing" as
linked just above this form, there's a section on Pull Requests in there
as well that contains important information.
As a summary, please make sure you have ticked all points on this
checklist:
* [ ] Your changes are not possible to do through a plugin and relevant
to a large audience (ideally all users of OctoPrint)
* [ ] If your changes are large or otherwise disruptive: You have
made sure your changes don't interfere with current development by
talking it through with the maintainers, e.g. through a
Brainstorming ticket
* [ ] Your PR targets OctoPrint's devel branch (not master,
maintenance or anything else)
* [ ] Your PR was opened from a custom branch on your repository
(no PRs from your version of master, maintenance or devel please),
e.g. dev/my_new_feature
* [ ] Your PR only contains relevant changes: no unrelated files,
no dead code, ideally only one commit - rebase your PR if necessary!
* [ ] Your changes follow the coding style
* [ ] If your changes include style sheets: You have modified the
.less source files, not the .css files (those are generated with
lessc)
* [ ] You have tested your changes (please state how!) - ideally you
have added unit tests
* [ ] You have run the existing unit tests against your changes and
nothing broke
* [ ] You have added yourself to the AUTHORS.md file :)
Feel free to delete all this help text, then describe
your PR further. You may use the template provided below to do that.
The more details the better!
----
#### What does this PR do and why is it necessary?
#### How was it tested? How can it be tested by the reviewer?
#### Any background context you want to provide?
#### What are the relevant tickets if any?
#### Screenshots (if appropriate)
#### Further notes
+7
View File
@@ -1,3 +1,10 @@
src/octoprint/templates/_data/AUTHORS.md
src/octoprint/templates/_data/CHANGELOG.md
src/octoprint/templates/_data/SUPPORTERS.md
src/octoprint/templates/_data/THIRDPARTYLICENSES.md
devtools
*.tar.bz2
*.tar.gz
*.7z
+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
+13 -6
View File
@@ -7,13 +7,20 @@
# The file is processed from top to bottom, the first matching line wins. If <tag> or <reference commit> are left out,
# the lookup table does not apply to the matched branches
# master shall not use the lookup table, only tags
# master and rc shall not use the lookup table, only tags
master
rc/.*
prerelease
# maintenance is currently the branch for preparation of maintenance release 1.2.2
# so are any fix/... branches
maintenance 1.2.2-dev 9f8d30a66c2fcc5cd0e8984c72dc36f7e84fde10
fix/.* 1.2.2-dev 9f8d30a66c2fcc5cd0e8984c72dc36f7e84fde10
# neither should disconnected checkouts, e.g. 'git checkout <tag>'
HEAD
\(detached.*
# maintenance is currently the branch for preparation of maintenance release 1.2.17
# so are any fix/... and improve/... branches
maintenance 1.2.17 354042b84d488db38ac1917bb69bd164f4e7f750 pep440-dev
fix/.* 1.2.17 354042b84d488db38ac1917bb69bd164f4e7f750 pep440-dev
improve/.* 1.2.17 354042b84d488db38ac1917bb69bd164f4e7f750 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
+69
View File
@@ -0,0 +1,69 @@
# 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)
* [Richard Joyce](https://github.com/richjoyce)
* ["bwgan"](https://github.com/bwgan)
* [Siim Raud](https://github.com/2ndalpha)
* ["geoporalis"](https://github.com/geoporalis)
* [Andrew Malota](https://github.com/2bitoperations)
* [Kyle Evans](https://github.com/kevans91)
* [Ovidiu Hossu](https://github.com/MoonshineSG)
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.
+573 -1
View File
@@ -1,5 +1,577 @@
# OctoPrint Changelog
## 1.2.17 (2016-11-08)
### Improvements
* Files like `config.yaml` etc will now persist their permissions, with a lower and upper permission bounds for sanitization (e.g. removing executable flags on configuration files but keeping group read/write permissions if found).
* Log full stack trace on socket connection errors when debug logging for `octoprint.server.util.sockjs` is enabled
* ``SettingsPlugin``s may now mark configuration paths as restricted so that they are not returned on the REST API
* Updated LESS.js version
* Improved the `serial.log` logging handler to roll over serial log on new connections to the printer instead of continuously appending to the same file. Please note that `serial.log` is a debugging tool only and should *not* be left enabled unless you are trying to troubleshoot something in your printer communication.
* Split JS/CSS/LESS asset bundles according into asset bundles for core + bundled plugins ("packed_core.{js|css|less}") and third party plugins ("packed_plugins.{js|css|less}"). That will allow the core UI to still function properly even if an installed third party plugin produces invalid JS and therefore causes a parser error for the whole plugin JS file. See [#1544](https://github.com/foosel/OctoPrint/issues/1544) for an example of such a situation.
### Bug fixes
* [#1531](https://github.com/foosel/OctoPrint/issues/1531) - Fixed encoding bug in HTTP request processing triggered by content type headers on form data fields
* Fixed forced `config.yaml` save on startup caused by mistakenly assuming that printer parameters were always migrated.
* Fixed issue causing ``remember_me`` cookie not to be deleted properly on logout
* Fixed broken filter toggling on ``ItemListHelper`` class used for various lists throughout the web interface
* Fixed an issue with the preliminary page never reporting that the server is now up if the page generated during preliminary caching had no cache headers set (e.g. because it contained the first run setup wizard)
* Fixed a bug causing the update of OctoPrint to not work under certain circumstances: If 1.2.16 was installed and the settings were *never* saved via the "Settings" dialog's "Save", the update of OctoPrint would fail due to a `KeyError` in the updater. Reason is a renamed property, properly switched to when saving the settings.
* Fixed the logging subsystem to properly clean up after itself.
* Fixed a wrong order in loading JS files on the client introduced in 1.2.17rc2 to make the UI more resilient against broken plugin JS.
* Properly handle empty JS file list from plugins. Solves a 500 on OctoPrint instances without any third party plugins installed generated during web asset bundling introduced in 1.2.17rc2.
### More information
* [Commits](https://github.com/foosel/OctoPrint/compare/1.2.16...1.2.17)
* Release Candidates:
* [1.2.17rc1](https://github.com/foosel/OctoPrint/releases/tag/1.2.17rc1)
* [1.2.17rc2](https://github.com/foosel/OctoPrint/releases/tag/1.2.17rc2)
* [1.2.17rc3](https://github.com/foosel/OctoPrint/releases/tag/1.2.17rc3)
* [1.2.17rc4](https://github.com/foosel/OctoPrint/releases/tag/1.2.17rc4)
## 1.2.16 (2016-09-23)
### Improvements
* [#1434](https://github.com/foosel/OctoPrint/issues/1434): Make sure to sanitize any file names in the upload folder that do not match OctoPrint's file name "sanitization standard" automatically when creating a file listing. This should solve issues with UI functionality like selecting a file for printing or deleting a file to not work with files that were uploaded manually to the ``uploads`` folder. As a side note: Please don't do this, use the ``watched`` folder if you want to SCP/FTP/copy files directly to OctoPrint.
* [#1434](https://github.com/foosel/OctoPrint/issues/1434): Allow `[` and `]` in uploaded file names.
* [#1481](https://github.com/foosel/OctoPrint/issues/1481): Bring back non-fuzzy layer time estimates in the GCODE viewer.
* Improved fuzzy print time displays in the frontend. Rounding now takes overall duration into account - durations over a day will be rounded up/down to half days, durations over an hour will be rounded up/down to half hours, durations over 30min will be rounded to 10min segments, durations below 30min will be rounded up or down to the next minute depending on the seconds and finally if we are talking about less than a minute, durations over 30s will return "less than a minute", durations under 30s will return "a couple of seconds".
* Improved intermediary loading page: Don't report server as ready and reload until preliminary caching has been done, IF preliminary caching will be done.
* Added release channels to OctoPrint's bundled Software Update plugin. You will now be able to subscribe to OctoPrint's `maintenance` or `devel` release candidates in addition to stable versions. [Read more about Release Channels on the wiki](https://github.com/foosel/OctoPrint/wiki/Using-Release-Channels).
* Return a "400 Bad Request" instead of a "500 Internal Server Error" if a `multipart/form-data` request (e.g. a file upload) is sent which lacks the `boundary` field.
### Bug Fixes
* [#1448](https://github.com/foosel/OctoPrint/issues/1448): Don't "eat" first line of the pause script after a pause triggering `M0` but send it to the printer instead
* [#1477](https://github.com/foosel/OctoPrint/issues/1477): Only report files enqueued for analysis which actually are (as in, don't claim to have queued STL files for GCODE analysis)
* [#1478](https://github.com/foosel/OctoPrint/issues/1478): Don't display inaccurate linear estimate ("6 days remaining") until 30 *minutes* have passed, even if nothing else is available. Potentially related to [#1428](https://github.com/foosel/OctoPrint/issues/1428).
* [#1479](https://github.com/foosel/OctoPrint/issues/1479): Make sure set cookies are post fixed with a port specific suffix and that the path they are set on takes the script root from the request into account.
* [#1483](https://github.com/foosel/OctoPrint/issues/1483): Filenames in file uploads may also now be encoded in ISO-8859-1, as defined in [RFC 7230](https://tools.ietf.org/html/rfc7230#section-3.2.4). Solves an issue when sending files with non-ASCII-characters in the file name from Slic3r.
* [#1491](https://github.com/foosel/OctoPrint/issues/1491): Fixed generate/delete API key in the user settings
* [#1492](https://github.com/foosel/OctoPrint/issues/1492): Fixed a bug in the software update plugin depending on the presence of the ``prerelease`` flag which is only present when added manually or using a non stable release channel.
### More information
* [Commits](https://github.com/foosel/OctoPrint/compare/1.2.15...1.2.16)
* Release Candidates:
* [1.2.16rc1](https://github.com/foosel/OctoPrint/releases/tag/1.2.16rc1)
* [1.2.16rc2](https://github.com/foosel/OctoPrint/releases/tag/1.2.16rc2)
## 1.2.15 (2016-07-30)
### Improvements
* [#1425](https://github.com/foosel/OctoPrint/issues/1425) - Added a compatibility work around for plugins implementing the [`octoprint.comm.transport.serial_factory` hook](http://docs.octoprint.org/en/master/plugins/hooks.html#octoprint-comm-transport-serial-factory) but whose handler's `write` method did not return the number of written bytes (e.g. [GPX plugin including v2.5.2](http://plugins.octoprint.org/plugins/gpx/), [M33 Fio plugin including v1.2](http://plugins.octoprint.org/plugins/m33fio/)).
### Bug Fixes
* [#1423](https://github.com/foosel/OctoPrint/issues/1423) - Fixed an issue with certain printers dropping or garbling communication when setting the read timeout of the serial line. Removed the dynamic timeout setting introduced by [#1409](https://github.com/foosel/OctoPrint/issues/1409) to solve this.
* [#1425](https://github.com/foosel/OctoPrint/issues/1425) - Fixed an error when trying to close a printer connection that had not yet been opened and was `None`
* Fixed "Last Modified" header calculation for views where only one source file was present
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.14...1.2.15))
## 1.2.14 (2016-07-28)
### Improvements
* [#935](https://github.com/foosel/OctoPrint/issues/935) - Support alternative source file types and target extensions in [SlicerPlugins](http://docs.octoprint.org/en/master/plugins/mixins.html#slicerplugin).
* [#1393](https://github.com/foosel/OctoPrint/issues/1393) - Added dedicated sub commands on the job API to pause and resume a print job (instead of only offering a toggle option).
* Better "upload error" message with a list of supported extensions (instead of hardcoded ones)
* Use fuzzy times for print time estimation from GCODE analysis
* Allow M23 "File opened" response with no filename (RepRapPro)
* Allow intermediary startup page to forward query parameters and fragments from initial call to actual web frontend
* More error resilience when rendering templates (e.g. from plugins)
* Make sure that all bytes of a line to send to the printer have actually been sent
* "Tickle" printer when encountering a communication timeout while idle
* Report `CLOSED`/`CLOSED_WITH_ERROR` states as "Offline" in frontend for more consistency with startup `NONE` state which already was reported as "Offline"
* Another attempt at a saner print time estimation: Force linear (way less accurate) estimate if calculation of more accurate version takes too long, sanity check calculated estimate and use linear estimate if it looks wrong, improved threshold values for calculation. Read [the second half of this post on the mailing list](https://groups.google.com/forum/#!msg/octoprint/WWpm1FCUkAs/X3HomTM5DgAJ) on why accurate print time estimation is so difficult to achieve.
* Display print job progress percentage on progress bar.
* Added an indicator for print time left prediction accuracy and explanation of its origin as tooltip.
* Improved visual distinction of "State" sidebar panel info clusters.
### Bug Fixes
* [#1385](https://github.com/foosel/OctoPrint/issues/1385) - Send all non-protocol messages from printer to clients.
* [#1388](https://github.com/foosel/OctoPrint/issues/1388) - Track consecutive timeouts even when idle and disconnect from printer when it's not responding any longer.
* [#1391](https://github.com/foosel/OctoPrint/issues/1391) - Only use the first value from the X-Scheme header for the reverse proxy setup. Otherwise there could be problems when multiple reverse proxies were configured chained together, each adding their own header to the mix.
* [#1407](https://github.com/foosel/OctoPrint/issues/1407) - If a file is uploaded with the "print" flag set to true, make sure to clear that flag after the print job has been triggered so that now all following uploaded or selected files will start printing on their own.
* [#1409](https://github.com/foosel/OctoPrint/issues/1409) - Don't report a communication timeout after a heatup triggered by a print from SD.
* Fixed scrolling to freshly uploaded files, also now highlighting the file entry for better visibility.
* Fixed overeager preemptive caching of invalid protocols.
* Fix modal background of update confirmation not vanishing
* Ensure log entries and messages from printer are sent to frontend already converted to utf-8. Otherwise even one line in the log that can't be converted automatically without error can cause updates from the backend to not arrive.
* Report correct printer state including error strings even after disconnecting
* While printing, be sure to read the next line from file and send that if the current line was filtered
* Small fixes in the GCODE analysis
* Small fixes in the documentation
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.13...1.2.14))
## 1.2.13 (2016-06-16)
### Bug Fixes
* [#1373](https://github.com/foosel/OctoPrint/issues/1373): Don't parse `B:` as bed temperature when it shows up as part of a position report from `M114`.
* [#1374](https://github.com/foosel/OctoPrint/issues/1374): Don't try to perform a passive login when the components we'd need to inform about a change in login state aren't yet available. Solves a bug that lead - among other things - to the Plugin Manager and the Software Update Plugin not showing anything but misleading errors until the user logged out and back in.
* Fixed the temperature graph staying uninitialized until a connection to a printer was established.
* Fixed an error causing issues during frontend startup if the browser doesn't support tracking browser visibility.
* Fixed an error causing issues during frontend startup if the browser doesn't support the capabilities needed for the GCODE viewer.
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.12...1.2.13))
## 1.2.12 (2016-06-09)
### Improvements
* [#1338](https://github.com/foosel/OctoPrint/issues/1338): Threshold configuration fields now include information about how to specify the thresholds.
* Mark unrendered timelapses currently being processed (recording or rendering) in the list and remove action buttons so no accidental double-processing can take place.
* Removed file extension from "rendering" and "rendered" notifications, was misleading when using the [mp4 wrapper script](https://github.com/guysoft/OctoPi/issues/184).
* Added some new events for manipulation of slicing profiles.
* Small fix of the german translation.
### Bug Fixes
* [#1314](https://github.com/foosel/OctoPrint/issues/1314): Do not change the extension of `.g` files being uploaded to SD (e.g. `auto0.g`)
* [#1320](https://github.com/foosel/OctoPrint/issues/1320): Allow deletion of *.mp4 timelapse files (see [this wrapper script](https://github.com/guysoft/OctoPi/issues/184)).
* [#1324](https://github.com/foosel/OctoPrint/issues/1324): Make daemonized OctoPrint properly clean up its pid file again (see also [#1330](https://github.com/foosel/OctoPrint/pull/1330)).
* [#1326](https://github.com/foosel/OctoPrint/issues/1326): Do not try to clean up an unrendered timelapse while it is already being deleted (and produce way too much logging output in the process).
* [#1343](https://github.com/foosel/OctoPrint/issues/1343): Events are now processed in the order they are fired in, making e.g. the "timelapse rendering" message always appear before "timelapse failed" and hence not stay on forever in case of a failed timelapse.
* [#1344](https://github.com/foosel/OctoPrint/issues/1344): `ProgressPlugin`s now get also notified about a progress of 0%.
* [#1357](https://github.com/foosel/OctoPrint/issues/1357): Fixed wrongly named method call on editing access control options for a user, causing that to not work properly.
* [#1361](https://github.com/foosel/OctoPrint/issues/1361): Properly reload profile list for currently selected slicer in the slicing dialog on change of profiles.
* [#1364](https://github.com/foosel/OctoPrint/issues/1364): Fixed a race condition that could cause the UI to not initialize correctly due to 401 errors, leaving it in an unusable state until a reload.
* Fixed concurrent message pushing to the frontend being able to break push messages for the session by forcing synchronization of SockJS message sending.
* Do not require admin rights for connecting/disconnecting, like it was in 1.1.x (note that this is supposed to become configurable behaviour once [#1110](https://github.com/foosel/OctoPrint/issues/1110) gets implemented)
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.11...1.2.12))
## 1.2.11 (2016-05-04)
### Important Announcement
Due to a recent change in the financial situation of the project, the funding of OctoPrint is at stake. If you love OctoPrint and want to see its development continue at the pace of the past two years, please read on about its current funding situation and how you can help: ["I need your support"](http://octoprint.org/blog/2016/04/13/i-need-your-support/).
### Improvements
* Added option to treat resend requests as `ok` for such firmwares that do not send an `ok` after requesting a resend. If you printer communication gets stalled after a resend request from the firmware, try checking this option.
* Added an "About" dialog to properly inform about OctoPrint's license, contributors and supporters.
* Added a announcement plugin that utilizes the RSS feeds of the [OctoPrint Blog](http://octoprint.org/blog/) and the [plugin repository](http://plugins.octoprint.org) to display news to the user. By default only the "important announcement" category is enabled. This category will only be used for very rare situations such as making you aware of critical updates or important news. You can enable further categories (with more announcements to be expected) in the plugin's settings dialog.
### Bug Fixes
* [#1300](https://github.com/foosel/OctoPrint/issues/1300) - Removed possibility to accidentally disabling local file list by first limiting view to files from SD and then disabling SD support.
* [#1315](https://github.com/foosel/OctoPrint/issues/1315) - Fixed broken post roll on z-based timelapses.
* Fixed CSS data binding syntax on the download link in the files list
* Changed control distance from jQuery data into a knockout observerable and observerableArray
* Allow an unauthorized user to logout from a logedin interface state
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.10...1.2.11))
## 1.2.10 (2016-03-16)
### Improvements
* Improved performance of console output during plugin installation/deinstallation
* Slight performance improvements in the communication layer
* Log small log excerpt to `octoprint.log` upon encountering a communication error.
* Changed wording in "firmware error" notifications to better reflect that there was an error while communicating with the printer, since the error condition can also be triggered by serial errors while trying to establish a connection to the printer or when already connected.
* Support downloading ".mp4" timelapse files. You'll need a [custom wrapper script for timelapse rendering](https://github.com/guysoft/OctoPi/issues/184) for this to be relevant to you. See also [#1255](https://github.com/foosel/OctoPrint/pull/1255)
* The communication layer will now wait up to 10s after clicking disconnect in order to send any left-over lines from its buffers.
* Moved less commonly used configuration options in Serial settings into "Advanced options" roll-out.
### Bug Fixes
* [#1224](https://github.com/foosel/OctoPrint/issues/1224) - Fixed an issue introduced by the fix for [#1196](https://github.com/foosel/OctoPrint/issues/1196) that had the "Upload to SD" button stop working correctly.
* [#1226](https://github.com/foosel/OctoPrint/issues/1226) - Fixed an issue causing an error on disconnect after or cancelling of an SD print, caused by the unsuccessful attempt to record print recovery data for the file on the printer's SD card.
* [#1268](https://github.com/foosel/OctoPrint/issues/1268) - Only add bed temperature line to temperature management specific start gcode in CuraEngine invocation if a bed temperature is actually set in the slicing profile.
* [#1271](https://github.com/foosel/OctoPrint/issues/1271) - If a communication timeout occurs during an active resend request, OctoPrint will now not send an `M105` with an increased line number anymore but repeat the last resent command instead.
* [#1272](https://github.com/foosel/OctoPrint/issues/1272) - Don't add an extra `ok` for `M28` response.
* [#1273](https://github.com/foosel/OctoPrint/issues/1273) - Add an extra `ok` for `M29` response, but only if configured such in "Settings" > "Serial" > "Advanced options" > "Generate additional ok for M29"
* [#1274](https://github.com/foosel/OctoPrint/issues/1274) - Trigger `M20` only once after finishing uploading to SD
* [#1275](https://github.com/foosel/OctoPrint/issues/1275) - Prevent `M105` "cascade" due to communication timeouts
* Fixed wrong tracking of extruder heating up for `M109 Tn` commands in multi-extruder setups.
* Fixed start of SD file uploads not sending an `M110`.
* Fixed job data not being reset when disconnecting while printing.
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.9...1.2.10))
## 1.2.9 (2016-02-10)
### Improvements
* [#318](https://github.com/foosel/OctoPrint/issues/318) - Snapshots for timelapses are now named in a non-colliding, job-based way, allowing a new timelapse to start while the other is still being rendered (although printing with an active timelapse rendering job is not recommended and will be solved with a proper render job queue in a later version). Timelapses that were not successfully rendered are kept for 7 days (configurable, although not via the UI so far) and can be manually rendered or deleted through a new UI component within the timelapse tab that shows up if unrendered timelapses are detected.
* [#485](https://github.com/foosel/OctoPrint/issues/485) - "Timelapse rendering" notification is now persistent, even across reloads/client switches. That should make it easier to see that a rendering job is currently in progress.
* [#939](https://github.com/foosel/OctoPrint/issues/939) - Updated to Knockout 3.4.0
* [#1204](https://github.com/foosel/OctoPrint/issues/1204) - Display total print time as estimated by GCODE viewer on GCODE viewer tab. That will allow access to an estimate even if the server hadn't yet calculated that when a print started. Note that due to slightly different implementation server and client side the resulting estimate might differ.
* OctoPrint now serves an intermediary page upon start that informs the user about the server still starting up. Once the server is detected as running, the page automatically switches to the standard interface.
* OctoPrint now displays a link to the release notes of an updated component in the update notification, the update confirmation and the version overview in the settings dialog. Please always make sure to at least skim over the release notes for new OctoPrint releases, they might contain important information that you need to know before updating.
* Improved initial page loading speeds by introducing a preemptive cache. OctoPrint will now record how you access it and on server start pre-render the page so it's ideally available in the server-side cache when you try to access it.
* Initialize login user name and password with an empty string and clear both on successful login (see [#1175](https://github.com/foosel/OctoPrint/pull/1175)).
* Added a "Refresh" button to the file list for people who modify the stored files externally (doing this is not encouraged however due to reasons of book keeping, e.g. metadata tracking etc).
* "Save" button on settings dialog is now disabled while background tasks (getting or receiving config data from the backend) are in progress.
* Improved performance of terminal tab on lower powered clients. Adaptive rate limiting now ensures the server backs off with log updates if the client can't process them fast enough. If the client is really slow, log updates get disabled automatically during printing. This behaviour can be disabled with override buttons in the terminal tab's advanced options if necessary.
* Added option to ignore any unhandled errors reported by the firmware and another option to only cancel ongoing prints on unhandled errors from the firmware (instead of instant disconnect that so far was the default).
* Made version compatibility check PEP440 compliant (important for plugin authors).
* Do not hiccup on manually sent `M28` commands.
* Persist print recovery data on print failures (origin and name of printed file, position in file when print was aborted, time and date of print failure). Currently this data isn't used anywhere, but it [can be accessed from plugins in order to add recovery functionality](https://github.com/foosel/OctoPrint-PrintRecoveryPoc) to OctoPrint.
* Small performance improvements in update checks.
* The file upload dialog will now only display files having an extension that's supported for upload (if the browser supports it, also see [#1196](https://github.com/foosel/OctoPrint/issues/1196)).
### Bug Fixes
* [#1007](https://github.com/foosel/OctoPrint/issues/1007) - Don't enable the "Print" button if no print job is selected.
* [#1181](https://github.com/foosel/OctoPrint/issues/1181) - Properly slugify UTF-8 only file names.
* [#1196](https://github.com/foosel/OctoPrint/issues/1196) - Do not show drag-n-drop overlay if server is offline.
* [#1208](https://github.com/foosel/OctoPrint/issues/1208) - Fixed `retraction_combing` profile setting being incorrectly used by bundled Cura plugin (see [#1209](https://github.com/foosel/OctoPrint/pull/1209))
* Fixed OctoPrint compatibility check in the plugin manager, could report `False` for development versions against certain versions of Python's `setuptools` (thanks to @ignaworm who stumbled over this).
* Fixed a missing parameter in `PluginSettings.remove` call (see [#1177](https://github.com/foosel/OctoPrint/pull/1177)).
* Docs: Fixed the example for a custom `M114` control to also match negative coordinates.
* Reset scroll position in settings dialog properly when re-opening it or switching tabs.
* Fixed an issue that prevented system menu entries that were added to a so far empty system menu make the menu show up.
* Fixed an issue that made requests to restricted resources fail even though the first run wizard had been completed successfully.
* Fixed an issue where an unknown command or the suppression of a command could cause the communication to stall until a communication timeout was triggered.
* Strip [unwanted ANSI characters](https://github.com/pypa/pip/issues/3418) from output produced by pip versions 8.0.0, 8.0.1 and 8.0.3 that prevents our plugin installation detection from working correctly.
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.8...1.2.9))
## 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
@@ -176,7 +748,7 @@
changed under "Temperatures" in the Settings ([#343](https://github.com/foosel/OctoPrint/issues/343)).
* High-DPI support for the GCode viewer ([#837](https://github.com/foosel/OctoPrint/issues/837)).
* Stop websocket connections from multiplying ([#888](https://github.com/foosel/OctoPrint/pull/888)).
* New setting to rotate webcam by 90° counter clockwise ([#895](https://github.com/foosel/OctoPrint/issues/895) and
* New setting to rotate webcam by 90° counter clockwise ([#895](https://github.com/foosel/OctoPrint/issues/895) and
[#906](https://github.com/foosel/OctoPrint/pull/906))
* System commands now be set to a) run asynchronized by setting their `async` property to `true` and b) to ignore their
result by setting their `ignore` property to `true`.
+396 -41
View File
@@ -1,49 +1,404 @@
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)
* [What do the branches mean?](#what-do-the-branches-mean)
* [How OctoPrint is versioned](#how-octoprint-is-versioned)
* [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 **feature request** or a **documentation request**, add `[Request]`
to your issue's title (e.g. `[Request] Awesome new feature`). A question on how to run/change/setup
something is **not** what qualifies as a request here, use the
[Mailinglist](https://groups.google.com/group/octoprint) or the
[Google+ Community](https://plus.google.com/communities/102771308349328485741) for
such support issues.
- 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://github.com/foosel/OctoPrint/issues/new).
Before you do that for the first time though please take a moment to read the
following section *completely* and also follow the instructions in the
"new issue" form. 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 a
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, and **test without
any non-bundled plugins enabled** to make sure it's not a misbehaving
plugin causing the issue at hand.
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). Do not only read the subject lines
of tickets that look like they might be related, but also read the ticket itself!
**Very important:** Please make absolutely sure that if you find a bug that looks like
it is the same as your's, it actually behaves the same as your's. E.g. if someone gives steps
to reproduce his bug that looks like your's, reproduce the bug like that if possible,
and only add a "me too" if you actually can reproduce the same
issue. Also **provide all information** as [described below](#what-should-i-include-in-a-bug-report)
and whatever was additionally requested over the course of the ticket
even if you "only" add to an existing ticket. The more information available regarding a bug, the higher
the chances of reproducing and solving it. But "me too" on an actually unrelated ticket
makes it more difficult due to on top of having to figure out the original problem
there's now also a [red herring](https://en.wikipedia.org/wiki/Red_herring) interfering - so please be
very diligent here!
### What should I include in a bug report?
First of all make sure your use **a descriptive title**. "It doesn't work"
and similar unspecific complaints are NOT descriptive titles.
**Always use the following template** (please remove what's within `[...]`, that's
only provided here as some additional information for you), **even if only adding a
"me too" to an existing ticket**:
#### 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. ALWAYS INCLUDE.]
#### 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.
serial.log is usually not written due to performance reasons and must be
enabled explicitly. Provide at the very least the FULL contents of your
terminal tab at the time of the bug occurrence, even if you do not have
a serial.log.]
#### 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.
Copy-paste this template **completely**. Do not skip any lines or the bot
*will* complain!
### 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 *completely* 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. You can
also access it directly through OctoPrint via Settings > Logs. Please
copy-paste this *completely* 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 or otherwise disruptive 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 there are **only relevant changes** included in your PR. No
changes to unrelated files, no additional files that don't belong (e.g.
commits of your full virtual environment). Make sure your PR consists
**ideally of only one commit** (use git's rebase and squash functionality).
5. 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.
* Make sure you do not add dead code (e.g. commented out left-overs
from experiments).
6. Ensure your changes **pass the existing unit tests**. PRs that break
those cannot be accepted.
7. **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!
8. In your pull request's description, **state what your pull request does**,
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. There is a template provided below
that can help you here.
9. Don't forget to **add yourself to the [AUTHORS](./AUTHORS.md)
file** :)
Template to use for Pull Request descriptions:
```
#### What does this PR do and why is it necessary?
#### How was it tested? How can it be tested by the reviewer?
#### Any background context you want to provide?
#### What are the relevant tickets if any?
#### Screenshots (if appropriate)
#### Further notes
```
## What do the branches mean?
There are three main branches in OctoPrint:
* `master`: The master branch always contains the current stable release. It
is *only* updated on new releases. Will have a version number following
the scheme `<x>.<y>.<z>` (e.g. `1.2.9`) or - if it's absolutely necessary to
add a commit after release to this branch - `<x>.<y>.<z>.post<commits since x.y.z>`
(e.g. `1.2.9.post1`).
* `maintenance`: Improvements and fixes of the current release that make up
the next release go here. More or less continously updated. You can consider
this a preview of the next release version. It should be very stable at all
times. Anything you spot in here helps tremendously with getting a rock solid
next stable release, so if you want to help out development, running the
`maintenance` branch and reporting back anything you find is a very good way
to do that. Will usually have a version number following the scheme
`<x>.<y>.<z+1>.dev<commits since increase of z>` for an OctoPrint version of `<x>.<y>.<z>`
(e.g. `1.2.10.dev12`).
* `devel`: Ongoing development of new features that will go into the next bigger
release (MINOR version number increases) will happen on this branch. Usually
kept stable, sometimes stuff can break though or lose backwards compatibility
temporarily. Can be considered the "bleeding edge". All PRs should target
*this* branch. Important improvements and fixes from PRs here are backported to
`maintenance` as needed. Will usually have a version number following the
scheme `<x>.<y+1>.0.dev<commits since increase of y>` for a current OctoPrint version
of `<x>.<y>.<z>` (e.g. `1.3.0.dev123`).
* `rc/maintenance`: This branch is reserved for future releases that have graduated from
the `maintenance` branch and are now being pushed on the "Maintenance"
pre release channel for further testing. Version number follows the scheme
`<x>.<y>.<z>rc<n>` (e.g. `1.2.9rc1`).
* `rc/devel`: This branch is reserved for future releases that have graduated from
the `devel` branch and are now being pushed on the "Devel" pre release channel
for further testing. Version number follows the scheme `<x>.<y+1>.0rc<n>` (e.g. `1.3.0rc1`)
for a current stable OctoPrint version of `<x>.<y>.<z>`.
Additionally, from time to time you might see other branches pop up in the repository.
Those usually have one of the following prefixes:
* `fix/...`: Fixes under development that are to be merged into the `maintenance`
and `devel` branches.
* `improve/...`: Improvements under development that are to be merged into the
`maintenance` and `devel` branches.
* `dev/...` or `feature/...`: New functionality under development that is to be merged
into the `devel` branch.
There is also the `gh-pages` branch, which holds OctoPrint's web page, and a couple of
older development branches that are slowly being migrated or deleted.
## How OctoPrint is versioned
OctoPrint follows the [semantic versioning scheme](http://semver.org/) of **MAJOR.MINOR.PATCH**.
The **PATCH** version number is the one increasing most often due to OctoPrint's maintenance releases.
Releases that only change the patch number indicate that they contain bug fixes and small improvements
of existing functionality. Example: 1.2.8 to 1.2.9.
The **MINOR** version number increases with releases that add a lot of new functionality and
large features. Example: 1.2.x to 1.3.0.
Finally, the **MAJOR** version number increases if there are breaking API changes that concern any of the
documented interfaces (REST API, plugin interfaces, ...). So far this hasn't happened. Example: 1.x.y to 2.0.0.
OctoPrint's version numbers are automatically generated using [versioneer](https://github.com/warner/python-versioneer)
and depend on the selected git branch, nearest git tag and commits. The generated version number
should always be [PEP440](https://www.python.org/dev/peps/pep-0440/) compatible. Unless a git tag
is used for version number determination, the version number will also contain the git hash within
the local version identifier to allow for an exact determination of the active code base
(e.g. `1.2.9.dev68+g46c7a9c`). Additionally, instances with active uncommitted changes will contain
`.dirty` in the local version identifier.
## 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.
* 2016-02-10: Added information about branch structure and versioning.
* 2016-02-16: Added requirement to add information from template to existing
tickets as well, explained issue with "me too" red herrings.
* 2016-03-14: Some more requirements for PRs, and a PR template.
* 2016-06-08: New `prerelease` and `rc` branches explained.
* 2016-09-09: New `rc/*` branches explained.
* 2016-09-23: Some more work on "How to file a bug report" based on recent
experiences
## 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).
+2 -1
View File
@@ -4,5 +4,6 @@ recursive-include src/octoprint/plugins *
recursive-include src/octoprint/translations *
include versioneer.py
include src/octoprint/_version.py
include README.md
include requirements.txt
include *.md
exclude CONTRIBUTING.md
+69 -20
View File
@@ -1,28 +1,69 @@
OctoPrint
=========
# 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).
Contributing
------------
The documentation is located at [docs.octoprint.org](http://docs.octoprint.org).
Please see the project's [Contribution Guidelines](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md).
The official plugin repository can be reached at [plugins.octoprint.org](http://plugins.octoprint.org).
Installation
------------
OctoPrint's development wouldn't be possible without the [financial support by its community](http://octoprint.org/support-octoprint/).
If you enjoy OctoPrint, please consider becoming a regular supporter!
Installation instructions for installing from source for different operating systems can be found [on the wiki](https://github.com/foosel/OctoPrint/wiki#assorted-guides).
![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
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) and also [financially](http://octoprint.org/support-octoprint/).
If you think something is bad 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).
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.
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 on your system:
1. Checkout OctoPrint: `git clone https://github.com/foosel/OctoPrint.git`
2. Change into the OctoPrint folder: `cd OctoPrint`
3. Create a user-owned virtual environment therein: `virtualenv venv`
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
OctoPrint depends on a couple of python modules to do its job. Those are automatically installed when installing
OctoPrint via `setup.py`:
@@ -33,10 +74,13 @@ You should also do this every time after pulling from the repository, since the
OctoPrint currently only supports Python 2.7.
Usage
-----
## 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`.
@@ -69,13 +113,18 @@ See `octoprint --help` for further information.
OctoPrint also ships with a `run` script in its source directory. You can also invoke that to start up the server, it
takes the same command line arguments as the `octoprint` script.
Configuration
-------------
## Configuration
If not specified via the commandline, the configfile `config.yaml` for OctoPrint is expected in the settings folder,
which is located at `~/.octoprint` on Linux, at `%APPDATA%/OctoPrint` on Windows and
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
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).
+77
View File
@@ -0,0 +1,77 @@
# Supporters
Development of this version of OctoPrint wouldn't have been possible without
[financial support by the community](http://octoprint.org/support-octoprint/) -
thanks to everyone who contributed!
## Patreon Patrons
* 3D Moniak
* Aleph Objects, Inc.
* Andrew Moorby
* Arnljot Arntsen
* Aurelio Bernal
* Bart Zudell
* Boris Hussein
* Brad Jackson
* Brad Mooneyham
* Brent Fiegle
* Brian E. Tyler
* Charles Mitchell
* Christopher Day
* Christian Petropolis
* COLLE+McVOY
* CreativeTools
* D Brian Kimmel
* DeltaMaker 3D Printers
* Doug Johnson
* E3D BigBox
* Erik de Bruijn
* Ernesto Martinez
* Exovite
* Frank Sander
* Gary Deen
* Gary N McKinney
* George Robles
* Gregor Lütolf
* J. Eckert
* Jason Galarneau
* Joe Korzeniewski
* Josh Daniels
* Joshua David Gregory
* Kaile Riser
* Kale Stedman
* Kazuhiro Ogura
* Korneel Bullens
* Lamin Kivelä
* M Khorakiwala
* Makespace Madrid
* Mark Lane
* Mark Qvist
* Mark Walker
* Masayoshi Mitsui
* Michael Aumock
* Michael McDargh Sr
* Miles Flavel
* Nikolai Langer
* Noe Ruiz
* Patrick McGinnis
* Peter Grace
* Peter Schmehl
* PRINT3Dforum.com
* Robert Gusek
* Roger Strolz
* Roy Cortes
* Samer Najia
* SD3D
* SeeMeCNC
* Shane Ekerbicer
* Simon Hallam
* Stefan Krister
* Steven Pearson
* Sven Mueller
* Terrance Shaw
* Thomas Hatley
* Trent Shumay
and 968 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
+55
View File
@@ -0,0 +1,55 @@
# Third Party Licenses
## Web Interface
* [AVLTree](https://gist.github.com/viking/2424106) (modified): GPL, LGPL (dual licensed)
* [Babel JavaScript Support](https://github.com/mitsuhiko/babel/blob/master/contrib/babel.js): BSD
* [Bootstrap](http://getbootstrap.com/): Apache License 2.0
* [Bootstrap Modal](http://jschr.github.io/bootstrap-modal/): Apache License 2.0
* [Bootstrap Slider Knockout Bindings](https://github.com/cosminstefanxp/bootstrap-slider-knockout-binding): MIT
* [Bootstrap Slider](http://seiyria.com/bootstrap-slider/): Apache License 2.0
* [Bootstrap Tabdrop](http://www.eyecon.ro/bootstrap-tabdrop): Apache License 2.0
* [Detect Mobile Browser](http://detectmobilebrowsers.com/): Public Domain
* [Flot](http://www.flotcharts.org/): MIT
* [JavaScript MD5](https://github.com/blueimp/JavaScript-MD5): MIT
* [JQuery](http://jquery.com/): MIT
* [JQuery Bootstrap Wizard](http://github.com/VinceG/twitter-bootstrap-wizard): MIT, GPL (dual licensed)
* [JQuery File Upload](https://github.com/blueimp/jQuery-File-Upload): MIT
* [JQuery iframe transport](https://github.com/blueimp/jQuery-File-Upload/blob/master/js/jquery.iframe-transport.js): MIT
* [JQuery QRCode](http://larsjung.de/jquery-qrcode/): MIT
* [JQuery Slimscroll](http://rocha.la/jQuery-slimScroll): MIT, GPL (dual licensed)
* [JQuery UI Core, Mouse, Slider and Widget](http://jqueryui.com): MIT
* [Knockout](http://knockoutjs.com/): MIT
* [LESS](http://lesscss.org): Apache License 2.0
* [lodash](https://lodash.com): MIT
* [Loglevel](https://github.com/pimterry/loglevel): MIT
* [Modernizr](http://modernizr.com): MIT
* [Moment.js](http://momentjs.com/): MIT
* [PNotify](http://sciactive.com/pnotify/): GPL, LGPL, MPL (triple licensed)
* [pusher.color.js](http://cache.preserve.io/5g18q0pw/index.html) (original link dead): MIT
* [SockJS](https://github.com/sockjs/sockjs-client): MIT
* [sprintf-js](http://alexei.ro/): BSD
## Server
* [feedparser](https://github.com/kurtmckee/feedparser): BSD
* [Flask](http://flask.pocoo.org/): BSD
* [Flask-Assets](http://github.com/miracle2k/flask-assets): BSD
* [Flask-Babel](http://github.com/mitsuhiko/flask-babel): BSD
* [Flask-Login](https://github.com/maxcountryman/flask-login): MIT
* [Flask-Markdown](http://github.com/dcolish/flask-markdown): BSD
* [Flask-Principal](http://packages.python.org/Flask-Principal/): MIT
* [netaddr](https://github.com/drkjam/netaddr/): BSD
* [netifaces](https://bitbucket.org/al45tair/netifaces): MIT
* [pkginfo](http://pypi.python.org/pypi/pkginfo/): Python
* [psutil](https://github.com/giampaolo/psutil): BSD
* [pylru](https://github.com/jlhutch/pylru): GPLv2
* [pyserial](http://pyserial.sourceforge.net/): Python
* [PyYAML](http://pyyaml.org/wiki/PyYAML): MIT
* [requests](http://python-requests.org/): Apache License 2.0
* [rsa](http://stuvel.eu/rsa): Apache License 2.0
* [sarge](http://sarge.readthedocs.org/): BSD
* [semantic_version](https://github.com/rbarrois/python-semanticversion): BSD
* [SockJS-Tornado](http://github.com/mrjoes/sockjs-tornado/): MIT
* [Tornado](http://www.tornadoweb.org/): Apache License 2.0
* [watchdog](http://github.com/gorakhargosh/watchdog): Apache License 2.0
+46 -13
View File
@@ -161,18 +161,10 @@ Upload file
Content-Disposition: form-data; name="file"; filename="whistle_v2.gcode"
Content-Type: application/octet-stream
;Generated with Cura_SteamEngine 13.11.2
M109 T0 S220.000000
T0
;Sliced at: Wed 11-12-2013 16:53:12
;Basic settings: Layer height: 0.2 Walls: 0.8 Fill: 20
;Print time: #P_TIME#
;Filament used: #F_AMNT#m #F_WGHT#g
;Filament cost: #F_COST#
;M190 S70 ;Uncomment to add your own bed temperature line
;M109 S220 ;Uncomment to add your own temperature line
G21 ;metric values
G90 ;absolute positioning
G21
G90
...
------WebKitFormBoundaryDeC2E3iWbTv1PwMC
Content-Disposition: form-data; name="select"
@@ -188,7 +180,7 @@ Upload file
HTTP/1.1 200 OK
Content-Type: application/json
Location: http://example.com/api/files/sdcard/whistle_.gcode
Location: http://example.com/api/files/sdcard/whistle_v2.gcode
{
"files": {
@@ -208,6 +200,46 @@ Upload file
}
}
},
"done": false
}
**Example with UTF-8 encoded filename following RFC 5987**
.. sourcecode:: http
POST /api/files/local HTTP/1.1
Host: example.com
X-Api-Key: abcdef...
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryDeC2E3iWbTv1PwMC
------WebKitFormBoundaryDeC2E3iWbTv1PwMC
Content-Disposition: form-data; name="file"; filename*=utf-8''20mm-%C3%BCml%C3%A4ut-b%C3%B6x.gcode
Content-Type: application/octet-stream
M109 T0 S220.000000
T0
G21
G90
...
------WebKitFormBoundaryDeC2E3iWbTv1PwMC--
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
Location: http://example.com/api/files/local/20mm-umlaut-box.gcode
{
"files": {
"local": {
"name": "20mm-umlaut-box",
"origin": "local",
"refs": {
"resource": "http://example.com/api/files/local/whistle_v2.gcode",
"download": "http://example.com/downloads/files/local/whistle_v2.gcode"
}
}
},
"done": true
}
@@ -390,8 +422,9 @@ Issue a file command
}
:param target: The target location on which to delete the file, either ``local`` (for OctoPrint's ``uploads``
folder) or ``sdcard`` for the printer's SD card (if available)
:param target: The target location on which the file to send the command for is located, either
``local`` (for OctoPrint's ``uploads`` folder) or ``sdcard`` for the printer's SD card
(if available)
:param filename: The filename of the file for which to issue the command
:json string command: The command to issue for the file, currently only ``select`` is supported
:json boolean print: ``select`` and ``slice`` command: Optional, whether to start printing the file directly after selection
+13 -1
View File
@@ -74,7 +74,19 @@ Encoding
OctoPrint uses UTF-8 as charset.
.. _sec-api-cross-origin:
That also includes headers in ``multipart/form-data`` requests, in order to allow the full UTF-8 range of characters
for uploaded filenames. If a ``multipart/form-data`` sub header cannot be decoded as UTF-8, OctoPrint will also attempt
to decode it as ISO-8859-1.
Additionally, OctoPrint supports replacing the ``filename`` field in the ``Content-Disposition`` header of a
multipart field with a ``filename*`` field following `RFC 5987, Section 3.2 <https://tools.ietf.org/html/rfc5987#section-3.2>`_,
which allows defining the charset used for encoding the filename. If both ``filename`` and ``filename*`` fields are
present, following the recommendation of the RFC ``filename*`` will be used.
For an example on how to send a request utilizing RFC 5987 for the ``filename*`` attribute, see the second example
in :ref:`Upload file <sec-api-fileops-uploadfile>`.
.. _sec-api-general-crossorigin:
Cross-origin requests
=====================
+71 -13
View File
@@ -19,17 +19,38 @@ Issue a job command
Starts the print of the currently selected file. For selecting a file, see :ref:`Issue a file command <sec-api-fileops-filecommand>`.
If a print job is already active, a :http:statuscode:`409` will be returned.
cancel
Cancels the current print job. If no print job is active (either paused or printing), a :http:statuscode:`409`
will be returned.
restart
Restart the print of the currently selected file from the beginning. There must be an active print job for this to work
and the print job must currently be paused. If either is not the case, a :http:statuscode:`409` will be returned.
pause
Pauses/unpauses the current print job. If no print job is active (either paused or printing), a :http:statuscode:`409`
will be returned.
Equivalent to issuing a ``cancel`` command while paused, directly followed by a ``start`` command.
cancel
Cancels the current print job. If no print job is active (either paused or printing), a :http:statuscode:`409`
will be returned.
pause
Pauses/resumes/toggles the current print job. Accepts one optional additional parameter ``action``
specifying which action to take. Valid values for this parameter are:
pause
Pauses the current job if it's printing, does nothing if it's already paused.
resume
Resumes the current job if it's paused, does nothing if it's printing.
toggle
Toggles the pause state of the job, pausing it if it's printing and resuming it if it's currently paused.
In order to stay backwards compatible to earlier iterations of this API, the default
action to take if no ``action`` parameter is supplied is to toggle the print job status.
If no print job is active (either paused or printing), a :http:statuscode:`409` will be returned.
.. note::
While the approach to implement pause/resume/toggle behaviour through sub commands via the ``action``
parameter instead of having dedicated ``pause``, ``resume`` and ``toggle`` commands seems clumsy, this path
was chosen to have the API stay backwards compatible to prior versions which only offered the toggle
behaviour under the ``pause`` command.
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
@@ -37,7 +58,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...
@@ -50,11 +71,28 @@ Issue a job command
HTTP/1.1 204 No Content
**Example Cancel Request**
.. sourcecode:: http
POST /api/job HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
{
"command": "cancel"
}
.. sourcecode:: http
HTTP/1.1 204 No Content
**Example Restart Request**
.. 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,30 +109,50 @@ 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...
{
"command": "pause"
"command": "pause",
"action": "pause"
}
.. sourcecode:: http
HTTP/1.1 204 No Content
**Example Cancel Request**
**Example Resume Request**
.. 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...
{
"command": "cancel"
"command": "pause",
"action": "resume"
}
.. sourcecode:: http
HTTP/1.1 204 No Content
**Example Pause Toggle Request**
.. sourcecode:: http
POST /api/job HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
{
"command": "pause",
"action": "toggle"
}
.. sourcecode:: http
+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>`
+19 -1
View File
@@ -12,7 +12,7 @@ Push updates
.. contents::
To enable real time information exchange between client and server, OctoPrint uses
To enable real time information exchange between client and server, OctoPrint uses
`SockJS <https://github.com/sockjs/sockjs-protocol>`_ to push
status updates, temperature changes etc to connected web interface instances.
@@ -43,6 +43,24 @@ Clients must ignore any unknown messages.
The data model of the attached payloads is described further below.
OctoPrint's SockJS socket also accepts one command from the client to the server,
the ``throttle`` command. Usually, OctoPrint will push the general state update
in the ``current`` message twice per second. For some clients that might still
be too fast, so they can signal a different factor to OctoPrint utilizing the
``throttle`` message. OctoPrint expects a single integer here which represents
the multiplier for the base rate limit of one message every 500ms. A value of
1 hence will produce the default behaviour of getting every update. A value of
2 will set the rate limit to maximally one message every 1s, 3 to maximally one
message every 1.5s and so on.
Example for a ``throttle`` client-server-message:
.. sourcecode:: javascript
{
"throttle": 2
}
.. _sec-api-push-datamodel:
Datamodel
+1 -1
View File
@@ -32,7 +32,7 @@ List All Slicers and Slicing Profiles
.. sourcecode:: http
GET /api/slicing/profiles HTTP/1.1
GET /api/slicing HTTP/1.1
Host: example.com
X-Api-Key: abcdef...
+149 -2
View File
@@ -244,6 +244,9 @@ The following settings are only relevant to you if you want to do OctoPrint deve
# be fully rerendered on request to / on the server.
enabled: true
# Whether to enable the preemptive cache
preemptive: true
# Settings for stylesheet preference. OctoPrint will prefer to use the stylesheet type
# specified here. Usually (on a production install) that will be the compiled css (default).
# Developers may specify less here too.
@@ -260,6 +263,9 @@ The following settings are only relevant to you if you want to do OctoPrint deve
# set to false, no minification will take place either.
minify: true
# Whether to delete generated web assets on server startup (forcing a regeneration)
clean_on_startup: true
# Settings for the virtual printer
virtualPrinter:
@@ -290,6 +296,14 @@ The following settings are only relevant to you if you want to do OctoPrint deve
# < ok T0:34.3/0.0 T1:23.5/0.0 B:43.2/0.0
includeCurrentToolInTemps: true
# Whether to include the selected filename in the M23 File opened response.
#
# True: > M23 filename.gcode
# < File opened: filename.gcode Size: 27
# False: > M23 filename.gcode
# > File opened
includeFilenameInOpened: true
# The maximum movement speeds of the simulated printer's axes, in mm/s
movementSpeed:
x: 6000
@@ -313,6 +327,10 @@ The following settings are only relevant to you if you want to do OctoPrint deve
# < ok T0:34.3/220.0 T1:23.5/0.0 B:43.2/0.0
repetierStyleTargetTemperature: false
# If enabled, uses repetier style resends, sending multiple resends for the same line
# to make sure nothing gets lost on the line
repetierStyleResends: false
# If enabled, reports the first extruder in M105 responses as T instead of T0
#
# True: > M105
@@ -340,9 +358,54 @@ The following settings are only relevant to you if you want to do OctoPrint deve
# side will block
rxBuffer: 64
# Size of
# Size of simulated command buffer
commandBuffer: 4
# Whether to support the M112 command with simulated kill
supportM112: true
# Whether to send messages received via M117 back as "echo:" lines
echoOnM117: true
# Whether to simulate broken M29 behaviour (missing ok after response)
brokenM29: true
.. _sec-configuration-config_yaml-estimation:
Estimation
----------
The following settings provide parameters for estimators within OctoPrint. Currently only
the estimation of the left print time during an active job utilizes this section.
.. code-block:: yaml
estimation:
# Parameters for the print time estmation during an ongoing print job
printTime:
# Until which percentage to do a weighted mixture of statistical duration (analysis or
# past prints) with the result from the calculated estimate if that's already available.
# Utilized to compensate for the fact that the earlier in a print job, the least accuracy
# even a stable calculated estimate provides.
statsWeighingUntil: 0.5
# Range the assumed percentage (based on current estimated statistical, calculated or mixed
# total vs elapsed print time so far) needs to be around the actual percentage for the
# result to be used
validityRange: 0.15
# If no estimate could be calculated until this percentage and no statistical data is available,
# use dumb linear estimate
forceDumbFromPercent: 0.3
# If no estimate could be calculated until this many minutes into the print and no statistical
# data is available, use dumb linear estimate
forceDumbAfterMin: 30
# Average fluctuation between individual calculated estimates to consider in stable range. Seconds
# of difference.
stableThreshold: 60
.. _sec-configuration-config_yaml-events:
Events
@@ -426,6 +489,9 @@ Use the following settings to enable or disable OctoPrint features:
# Specifies whether support for SD printing and file management should be enabled
sdSupport: true
# Specifies whether firmware expects relative paths for selecting SD files
sdRelativePath: false
# Whether to always assume that an SD card is present in the printer.
# Needed by some firmwares which don't report the SD card status properly.
sdAlwaysAvailable: false
@@ -443,6 +509,16 @@ Use the following settings to enable or disable OctoPrint features:
# Whether to enable the keyboard control feature in the control tab
keyboardControl: true
# Whether to actively poll the watched folder (true) or to rely on the OS's file system
# notifications instead (false)
pollWatched: false
# Whether to ignore identical resends from the printer (true, repetier) or not (false)
ignoreIdenticalResends: false
# If ignoredIdenticalResends is true, how many consecutive identical resends to ignore
identicalResendsCount: 7
.. _sec-configuration-config_yaml-folder:
Folder
@@ -611,6 +687,43 @@ Use the following settings to configure the serial connection to the printer:
additionalPorts:
- /dev/myPrinterSymlink
# Commands which are known to take a long time to be acknowledged by the firmware. E.g.
# homing, dwelling, auto leveling etc. Defaults to the below commands.
longRunningCommands:
- G4
- G28
- G29
- G30
- G32
- M400
- M226
# Commands which need to always be send with a checksum. Defaults to only M110
checksumRequiringCommands:
- M110
# Command to send in order to initiate a handshake with the printer.
# Defaults to "M110 N0" which simply resets the line numbers in the firmware and which
# should be acknowledged with a simple "ok".
helloCommand: M110 N0
# Whether to disconnect on errors or not
disconnectOnErrors: true
# Whether to completely ignore errors from the firmware or not
ignoreErrorsFromFirmware: false
# Whether to log resends to octoprint.log or not. Invaluable debug tool without performance
# impact, leave on if possible please
logResends: true
# Whether to support resends without follow-up ok or not
supportResendsWithoutOk: false
# Whether to "manually" trigger an ok for M29 (a lot of versions of this command are buggy and
# the responds skips on the ok)
triggerOkForM29: true
.. _sec-configuration-config_yaml-server:
Server
@@ -621,7 +734,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 +805,39 @@ 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
# Settings of when to display what disk space warning
diskspace:
# Threshold (bytes) after which to consider disk space becoming sparse,
# defaults to 500MB
warning: 63488000
# Threshold (bytes) after which to consider disk space becoming critical,
# defaults to 200MB
critical: 209715200
# Configuration of the preemptive cache
preemptiveCache:
# which server paths to exclude from the preemptive cache
exceptions:
- /some/path
# How many days to leave unused entries in the preemptive cache config
until: 7
.. 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>`_.
+24
View File
@@ -365,6 +365,30 @@ SlicingFailed
* ``gcode``: the sliced GCODE's filename
* ``reason``: the reason for the slicing having failed
SlicingProfileAdded
A new slicing profile was added.
Payload:
* ``slicer``: the slicer for which the profile was added
* ``profile``: the profile that was added
SlicingProfileModified
A new slicing profile was modified.
Payload:
* ``slicer``: the slicer for which the profile was modified
* ``profile``: the profile that was modified
SlicingProfileDeleted
A slicing profile was deleted.
Payload:
* ``slicer``: the slicer for which the profile was deleted
* ``profile``: the profile that was deleted
Settings
--------
+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``
+15 -3
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::
@@ -65,7 +65,7 @@ a GCODE script including user input.
children:
- name: Get Position
command: M114
regex: "X:([0-9.]+) Y:([0-9.]+) Z:([0-9.]+) E:([0-9.]+)"
regex: "X:([-+]?[0-9.]+) Y:([-+]?[0-9.]+) Z:([-+]?[0-9.]+) E:([-+]?[0-9.]+)"
template: "Position: X={0}, Y={1}, Z={2}, E={3}"
- name: Fun stuff
children:
@@ -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
========
+2
View File
@@ -299,6 +299,8 @@ An overview of these properties follows.
The plugin's name, as taken from either the ``__plugin_name__`` control property or the package info.
``self._plugin_version``
The plugin's version, as taken from either the ``__plugin_version__`` control property or the package info.
``self._plugin_info``
The :class:`octoprint.plugin.core.PluginInfo` object associated with the plugin.
``self._basefolder``
The plugin's base folder where it's installed. Can be used to refer to files relative to the plugin's installation
location, e.g. included scripts, templates or assets.
+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
+85 -36
View File
@@ -2,6 +2,7 @@
# coding=utf-8
from setuptools import setup, find_packages
from distutils.command.build_py import build_py as _build_py
import os
import versioneer
@@ -14,24 +15,28 @@ import octoprint_setuptools
# Requirements for our application
INSTALL_REQUIRES = [
"flask>=0.9,<0.11",
"werkzeug==0.8.3",
"tornado==4.0.1",
"sockjs-tornado>=1.0.0",
"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"
"werkzeug>=0.8.3,<0.9",
"tornado>=4.0.1,<4.1",
"sockjs-tornado>=1.0.1,<1.1",
"PyYAML>=3.10,<3.11",
"Flask-Login>=0.2.2,<0.3",
"Flask-Principal>=0.3.5,<0.4",
"Flask-Babel>=0.9,<0.10",
"Flask-Assets>=0.10,<0.11",
"markdown>=2.6.4,<2.7",
"pyserial>=2.7,<2.8",
"netaddr>=0.7.17,<0.8",
"watchdog>=0.8.3,<0.9",
"sarge>=0.1.4,<0.2",
"netifaces>=0.10,<0.11",
"pylru>=1.0.9,<1.1",
"rsa>=3.2,<3.3",
"pkginfo>=1.2.1,<1.3",
"requests>=2.7.0,<2.8",
"semantic_version>=2.4.2,<2.5",
"psutil>=3.2.1,<3.3",
"awesome-slugify>=1.6.5,<1.7",
"feedparser>=5.2.1,<5.3"
]
# Additional requirements for optional install options
@@ -39,36 +44,60 @@ EXTRA_REQUIRES = dict(
# Dependencies for developing OctoPrint
develop=[
# Testing dependencies
"mock>=1.0.1",
"nose>=1.3.0",
"mock>=1.0.1,<1.1",
"nose>=1.3.0,<1.4",
"ddt",
# Documentation dependencies
"sphinx>=1.3",
"sphinx>=1.3,<1.4",
"sphinxcontrib-httpdomain",
"sphinx_rtd_theme"
"sphinx_rtd_theme",
# PyPi upload related
"pypandoc"
],
# Dependencies for developing OctoPrint plugins
plugins=[
"cookiecutter"
"cookiecutter>=1.4,<1.5"
]
)
# 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
def data_copy_build_py_factory(files, baseclass):
class data_copy_build_py(baseclass):
files = dict()
def run(self):
import shutil
if not self.dry_run:
for directory, files in self.__class__.files.items():
target_dir = os.path.join(self.build_lib, directory)
self.mkpath(target_dir)
for entry in files:
if isinstance(entry, tuple):
if len(entry) != 2:
continue
source, dest = entry
else:
source = dest = entry
shutil.copy(source, os.path.join(target_dir, dest))
baseclass.run(self)
return type(data_copy_build_py)(data_copy_build_py.__name__,
(data_copy_build_py,),
dict(files=files))
def get_cmdclass():
cmdclass = versioneer.get_cmdclass()
@@ -81,6 +110,15 @@ def get_cmdclass():
bundled_dir = os.path.join("src", "octoprint", "translations")
cmdclass.update(octoprint_setuptools.get_babel_commandclasses(pot_file=pot_file, output_dir=translation_dir, pack_name_prefix="OctoPrint-i18n-", pack_path_prefix="", bundled_dir=bundled_dir))
cmdclass["build_py"] = data_copy_build_py_factory({
"octoprint/templates/_data": [
"AUTHORS.md",
"CHANGELOG.md",
"SUPPORTERS.md",
"THIRDPARTYLICENSES.md",
]
}, cmdclass["build_py"] if "build_py" in cmdclass else _build_py)
return cmdclass
@@ -89,8 +127,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",
@@ -117,7 +169,7 @@ def params():
packages = find_packages(where="src")
package_dir = {
"": "src"
"": "src",
}
package_data = {
"octoprint": octoprint_setuptools.package_data_dirs('src/octoprint', ['static', 'templates', 'plugins', 'translations'])
@@ -125,9 +177,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
+17 -2
View File
@@ -1,4 +1,6 @@
#!/usr/bin/env python
from __future__ import absolute_import
import sys
from octoprint.daemon import Daemon
from octoprint.server import Server
@@ -24,7 +26,14 @@ class Main(Daemon):
self._logConf = logConf
def run(self):
octoprint = Server(self._configfile, self._basedir, self._host, self._port, self._debug, self._allowRoot)
octoprint = Server(configfile=self._configfile,
basedir=self._basedir,
host=self._host,
port=self._port,
debug=self._debug,
allowRoot=self._allowRoot,
logConf=self._logConf,
octoprint_daemon=self)
octoprint.run()
def main():
@@ -77,7 +86,13 @@ def main():
elif "restart" == args.daemon:
daemon.restart()
else:
octoprint = Server(args.config, args.basedir, args.host, args.port, args.debug, args.allowRoot, args.logConf)
octoprint = Server(configfile=args.config,
basedir=args.basedir,
host=args.host,
port=args.port,
debug=args.debug,
allowRoot=args.allowRoot,
logConf=args.logConf)
octoprint.run()
if __name__ == "__main__":
+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"}
+28 -28
View File
@@ -12,35 +12,35 @@ class Daemon:
Usage: subclass the daemon class and override the run() method."""
def __init__(self, pidfile): self.pidfile = pidfile
def daemonize(self):
"""Deamonize class. UNIX double fork mechanism."""
try:
pid = os.fork()
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
except OSError as err:
sys.exit(0)
except OSError as err:
sys.stderr.write('fork #1 failed: {0}\n'.format(err))
sys.exit(1)
# decouple from parent environment
os.chdir('/')
os.setsid()
os.chdir('/')
os.setsid()
os.umask(002)
# do second fork
try:
pid = os.fork()
try:
pid = os.fork()
if pid > 0:
# exit from second parent
sys.exit(0)
except OSError as err:
sys.exit(0)
except OSError as err:
sys.stderr.write('fork #2 failed: {0}\n'.format(err))
sys.exit(1)
sys.exit(1)
# redirect standard file descriptors
sys.stdout.flush()
sys.stderr.flush()
@@ -51,18 +51,14 @@ class Daemon:
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
# write pidfile
pid = str(os.getpid())
with open(self.pidfile,'w+') as f:
f.write(pid + '\n')
# register listener for SIGTERM
signal.signal(signal.SIGTERM, self.term)
def term(self, _signo, _stack_frame):
os.remove(self.pidfile)
sys.exit(0)
def terminated(self):
self.remove_pidfile()
def start(self):
"""Start the daemon."""
@@ -74,13 +70,13 @@ class Daemon:
pid = int(pf.read().strip())
except IOError:
pid = None
if pid:
message = "pidfile {0} already exist. " + \
"Daemon already running?\n"
sys.stderr.write(message.format(self.pidfile))
sys.exit(1)
# Start the daemon
self.daemonize()
self.run()
@@ -94,14 +90,14 @@ class Daemon:
pid = int(pf.read().strip())
except IOError:
pid = None
if not pid:
message = "pidfile {0} does not exist. " + \
"Daemon not running?\n"
sys.stderr.write(message.format(self.pidfile))
return # not an error in a restart
# Try killing the daemon process
# Try killing the daemon process
try:
while 1:
os.kill(pid, signal.SIGTERM)
@@ -122,7 +118,11 @@ class Daemon:
def run(self):
"""You should override this method when you subclass Daemon.
It will be called after the process has been daemonized by
It will be called after the process has been daemonized by
start() or restart()."""
def remove_pidfile(self):
"""Removes the pidfile."""
if os.path.isfile(self.pidfile):
os.remove(self.pidfile)
+15 -5
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"
@@ -83,6 +86,14 @@ class Events(object):
SLICING_DONE = "SlicingDone"
SLICING_FAILED = "SlicingFailed"
SLICING_CANCELLED = "SlicingCancelled"
SLICING_PROFILE_ADDED = "SlicingProfileAdded"
SLICING_PROFILE_MODIFIED = "SlicingProfileModified"
SLICING_PROFILE_DELETED = "SlicingProfileDeleted"
# Printer Profiles
PRINTER_PROFILE_ADDED = "PrinterProfileAdded"
PRINTER_PROFILE_MODIFIED = "PrinterProfileModified"
PRINTER_PROFILE_DELETED = "PrinterProfileDeleted"
# Settings
SETTINGS_UPDATED = "SettingsUpdated"
@@ -104,7 +115,7 @@ class EventManager(object):
self._registeredListeners = collections.defaultdict(list)
self._logger = logging.getLogger(__name__)
self._queue = Queue.PriorityQueue()
self._queue = Queue.Queue()
self._worker = threading.Thread(target=self._work)
self._worker.daemon = True
self._worker.start()
@@ -112,7 +123,7 @@ class EventManager(object):
def _work(self):
try:
while True:
(event, payload) = self._queue.get(True)
event, payload = self._queue.get(True)
eventListeners = self._registeredListeners[event]
self._logger.debug("Firing event: %s (Payload: %r)" % (event, payload))
@@ -141,7 +152,7 @@ class EventManager(object):
payload being a payload object specific to the event.
"""
self._queue.put((event, payload), 0)
self._queue.put((event, payload))
if event == Events.UPDATED_FILES and "type" in payload and payload["type"] == "printables":
# when sending UpdatedFiles with type "printables", also send another event with deprecated type "gcode"
@@ -149,8 +160,7 @@ class EventManager(object):
import copy
legacy_payload = copy.deepcopy(payload)
legacy_payload["type"] = "gcode"
self._queue.put((event, legacy_payload), 0)
self._queue.put((event, legacy_payload))
def subscribe(self, event, callback):
"""
+98 -8
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
@@ -134,6 +175,9 @@ class FileManager(object):
self._progress_plugins = []
self._preprocessor_hooks = dict()
import octoprint.settings
self._recovery_file = os.path.join(octoprint.settings.settings().getBaseFolder("data"), "print_recovery_data.yaml")
def initialize(self):
self.reload_plugins()
@@ -155,7 +199,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
@@ -164,8 +212,8 @@ class FileManager(object):
# we'll use the default printer profile for the backlog since we don't know better
queue_entry = QueueEntry(entry, file_type, storage_type, path, self._printer_profile_manager.get_default())
self._analysis_queue.enqueue(queue_entry, high_priority=False)
counter += 1
if self._analysis_queue.enqueue(queue_entry, high_priority=False):
counter += 1
self._logger.info("Added {counter} items from storage type \"{storage_type}\" to analysis queue".format(**locals()))
def add_storage(self, storage_type, storage_manager):
@@ -236,7 +284,7 @@ class FileManager(object):
import time
start_time = time.time()
eventManager().fire(Events.SLICING_STARTED, {"stl": source_path, "gcode": dest_path, "progressAvailable": slicer.get_slicer_properties()["progress_report"] if slicer else False})
eventManager().fire(Events.SLICING_STARTED, {"stl": source_path, "gcode": dest_path, "progressAvailable": slicer.get_slicer_properties().get("progress_report", False) if slicer else False})
import tempfile
f = tempfile.NamedTemporaryFile(suffix=".gco", delete=False)
@@ -314,7 +362,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)
@@ -364,6 +417,43 @@ class FileManager(object):
# if there's no storage configured where to log the print, we'll just not log it
pass
def save_recovery_data(self, origin, path, pos):
import time
import yaml
from octoprint.util import atomic_write
data = dict(origin=origin,
path=self.path_in_storage(origin, path),
pos=pos,
date=time.time())
try:
with atomic_write(self._recovery_file, max_permissions=0o666) as f:
yaml.safe_dump(data, stream=f, default_flow_style=False, indent=" ", allow_unicode=True)
except:
self._logger.exception("Could not write recovery data to file {}".format(self._recovery_file))
def delete_recovery_data(self):
if not os.path.isfile(self._recovery_file):
return
try:
os.remove(self._recovery_file)
except:
self._logger.exception("Error deleting recovery data file {}".format(self._recovery_file))
def get_recovery_data(self):
if not os.path.isfile(self._recovery_file):
return None
import yaml
try:
with open(self._recovery_file) as f:
data = yaml.safe_load(f)
return data
except:
self._logger.exception("Could not read recovery data from file {}".format(self._recovery_file))
self.delete_recovery_data()
def set_additional_metadata(self, destination, path, key, data, overwrite=False, merge=False):
self._storage(destination).set_additional_metadata(path, key, data, overwrite=overwrite, merge=merge)
+2 -1
View File
@@ -68,9 +68,10 @@ class AnalysisQueue(object):
def enqueue(self, entry, high_priority=False):
if not entry.type in self._queues:
return
return False
self._queues[entry.type].enqueue(entry, high_priority=high_priority)
return True
def pause(self):
for queue in self._queues.values():
+60 -69
View File
@@ -10,9 +10,12 @@ import logging
import os
import pylru
import tempfile
import shutil
import octoprint.filemanager
from octoprint.util import is_hidden_path
class StorageInterface(object):
"""
Interface of storage adapters for OctoPrint.
@@ -309,6 +312,10 @@ class LocalFileStorage(StorageInterface):
self._metadata_cache = pylru.lrucache(10)
from slugify import Slugify
self._slugify = Slugify()
self._slugify.safe_chars = "-_.()[] "
self._old_metadata = None
self._initialize_metadata()
@@ -357,7 +364,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)
@@ -384,7 +391,7 @@ class LocalFileStorage(StorageInterface):
path = self.sanitize_path(path)
else:
path = self.basefolder
return self._list_folder(path, filter=filter, recursive=recursive)
return self._list_folder(path, entry_filter=filter, recursive=recursive)
def add_folder(self, path, ignore_existing=True):
path, name = self.sanitize(path)
@@ -392,7 +399,7 @@ class LocalFileStorage(StorageInterface):
folder_path = os.path.join(path, name)
if os.path.exists(folder_path):
if not ignore_existing:
raise RuntimeError("{sanitized_foldername} does already exist in {virtual_path}".format(**locals()))
raise RuntimeError("{name} does already exist in {path}".format(**locals()))
else:
os.mkdir(folder_path)
@@ -409,7 +416,7 @@ class LocalFileStorage(StorageInterface):
if ".metadata.yaml" in contents:
contents.remove(".metadata.yaml")
if contents and not recursive:
raise RuntimeError("{sanitized_foldername} in {virtual_path} is not empty".format(**locals()))
raise RuntimeError("{name} in {path} is not empty".format(**locals()))
import shutil
shutil.rmtree(folder_path)
@@ -584,24 +591,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)):
@@ -625,27 +614,9 @@ class LocalFileStorage(StorageInterface):
def sanitize_name(self, name):
"""
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 \
Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\``. Otherwise
slugifies the given ``name`` by converting it to ASCII, leaving ``-``, ``_``, ``.``,
``(``, and ``)`` as is.
"""
if name is None:
return None
@@ -653,36 +624,23 @@ class LocalFileStorage(StorageInterface):
if "/" in name or "\\" in name:
raise ValueError("name must not contain / or \\")
import string
valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits)
sanitized_name = ''.join(c for c in name if c in valid_chars)
sanitized_name = sanitized_name.replace(" ", "_")
return sanitized_name
result = self._slugify(name).replace(" ", "_")
if result and result != "." and result != ".." and result[0] == ".":
# hidden files under *nix
result = result[1:]
return result
def sanitize_path(self, path):
"""
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] == ".":
if path[0] == "/":
path = path[1:]
elif path[0] == "." and path[1] == "/":
path = path[2:]
path_elements = path.split("/")
joined_path = self.basefolder
for path_element in path_elements:
@@ -692,6 +650,30 @@ class LocalFileStorage(StorageInterface):
raise ValueError("path not contained in base folder: {path}".format(**locals()))
return path
def _sanitize_entry(self, entry, path, entry_path):
sanitized = self.sanitize_name(entry)
if sanitized != entry:
# entry is not sanitized yet, let's take care of that
sanitized_path = os.path.join(path, sanitized)
sanitized_name, sanitized_ext = os.path.splitext(sanitized)
counter = 1
while os.path.exists(sanitized_path):
counter += 1
sanitized = self.sanitize_name("{}_({}){}".format(sanitized_name, counter, sanitized_ext))
sanitized_path = os.path.join(path, sanitized)
try:
shutil.move(entry_path, sanitized_path)
self._logger.info("Sanitized \"{}\" to \"{}\"".format(entry_path, sanitized_path))
return sanitized, sanitized_path
except:
self._logger.exception("Error while trying to rename \"{}\" to \"{}\", ignoring file".format(entry_path, sanitized_path))
raise
return entry, entry_path
def path_in_storage(self, path):
if isinstance(path, (tuple, list)):
path = self.join_path(*path)
@@ -931,7 +913,10 @@ class LocalFileStorage(StorageInterface):
if metadata_dirty:
self._save_metadata(path, metadata)
def _list_folder(self, path, filter=None, recursive=True):
def _list_folder(self, path, entry_filter=None, recursive=True, **kwargs):
if entry_filter is None:
entry_filter = kwargs.get("filter", None)
metadata = self._get_metadata(path)
if not metadata:
metadata = dict()
@@ -939,12 +924,18 @@ 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
entry_path = os.path.join(path, entry)
try:
entry, entry_path = self._sanitize_entry(entry, path, entry_path)
except:
# error while trying to rename the file, we'll continue here and ignore it
continue
# file handling
if os.path.isfile(entry_path):
file_type = octoprint.filemanager.get_file_type(entry)
@@ -962,7 +953,7 @@ class LocalFileStorage(StorageInterface):
# TODO extract model hash from source if possible to recreate link
if not filter or filter(entry, entry_data):
if not entry_filter or entry_filter(entry, entry_data):
# only add files passing the optional filter
extended_entry_data = dict()
extended_entry_data.update(entry_data)
@@ -977,7 +968,7 @@ class LocalFileStorage(StorageInterface):
# folder recursion
elif os.path.isdir(entry_path) and recursive:
sub_result = self._list_folder(entry_path, filter=filter)
sub_result = self._list_folder(entry_path, entry_filter=entry_filter)
result[entry] = dict(
name=entry,
type="folder",
+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)
+4
View File
@@ -0,0 +1,4 @@
# coding=utf-8
from __future__ import absolute_import
from . import handlers
+83
View File
@@ -0,0 +1,83 @@
# coding=utf-8
from __future__ import absolute_import
import logging.handlers
import os
import re
import time
class CleaningTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):
def __init__(self, *args, **kwargs):
logging.handlers.TimedRotatingFileHandler.__init__(self, *args, **kwargs)
# clean up old files on handler start
if self.backupCount > 0:
for s in self.getFilesToDelete():
os.remove(s)
class SerialLogHandler(logging.handlers.RotatingFileHandler):
_do_rollover = False
_suffix_template = "%Y-%m-%d_%H-%M-%S"
_file_pattern = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$")
@classmethod
def on_open_connection(cls):
cls._do_rollover = True
def __init__(self, *args, **kwargs):
logging.handlers.RotatingFileHandler.__init__(self, *args, **kwargs)
self.cleanupFiles()
def emit(self, record):
logging.handlers.RotatingFileHandler.emit(self, record)
def shouldRollover(self, record):
return self.__class__._do_rollover
def getFilesToDelete(self):
"""
Determine the files to delete when rolling over.
"""
dirName, baseName = os.path.split(self.baseFilename)
fileNames = os.listdir(dirName)
result = []
prefix = baseName + "."
plen = len(prefix)
for fileName in fileNames:
if fileName[:plen] == prefix:
suffix = fileName[plen:]
if self.__class__._file_pattern.match(suffix):
result.append(os.path.join(dirName, fileName))
result.sort()
if len(result) < self.backupCount:
result = []
else:
result = result[:len(result) - self.backupCount]
return result
def cleanupFiles(self):
if self.backupCount > 0:
for path in self.getFilesToDelete():
os.remove(path)
def doRollover(self):
self.__class__._do_rollover = False
if self.stream:
self.stream.close()
self.stream = None
if os.path.exists(self.baseFilename):
# figure out creation date/time to use for file suffix
t = time.localtime(os.stat(self.baseFilename).st_mtime)
dfn = self.baseFilename + "." + time.strftime(self.__class__._suffix_template, t)
if os.path.exists(dfn):
os.remove(dfn)
os.rename(self.baseFilename, dfn)
self.cleanupFiles()
if not self.delay:
self.stream = self._open()
+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, lambda x: x)
)
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:
+9 -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:
@@ -902,6 +902,7 @@ class PluginManager(object):
identifier=name,
plugin_name=plugin.name,
plugin_version=plugin.version,
plugin_info=plugin,
basefolder=os.path.realpath(plugin.location),
logger=logging.getLogger(self.logging_prefix + name),
))
@@ -955,15 +956,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):
+219 -6
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
@@ -779,9 +819,49 @@ class SettingsPlugin(OctoPrintPlugin):
and iterate yourself over all your settings, using the proper retriever methods on the settings manager
to retrieve the data in the correct format.
The default implementation will also replace any paths that have been restricted by your plugin through
:func:`~octoprint.plugin.SettingsPlugin.get_settings_restricted_paths` with ``None`` values where necessary.
Make sure to do your own restriction if you decide to fully overload this method.
:return: the current settings of the plugin, as a dictionary
"""
return self._settings.get([], asdict=True, merged=True)
from flask.ext.login import current_user
data = self._settings.get_all_data()
if self.config_version_key in data:
del data[self.config_version_key]
restricted_paths = self.get_settings_restricted_paths()
def restrict_path_unless(data, path, condition):
if not path:
return
if condition():
return
node = data
if len(path) > 1:
for entry in path[:-1]:
if not entry in node:
return
node = node[entry]
key = path[-1]
if key in node:
node[key] = None
conditions = dict(user=lambda: current_user is not None and not current_user.is_anonymous(),
admin=lambda: current_user is not None and not current_user.is_anonymous() and current_user.is_admin(),
never=lambda: False)
for level, condition in conditions.items():
paths_for_level = restricted_paths.get(level, [])
for path in paths_for_level:
restrict_path_unless(data, path, condition)
return data
def on_settings_save(self, data):
"""
@@ -792,7 +872,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 +881,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):
"""
@@ -816,6 +923,60 @@ class SettingsPlugin(OctoPrintPlugin):
"""
return dict()
def get_settings_restricted_paths(self):
"""
Retrieves the list of paths in the plugin's settings which be restricted on the REST API.
Override this in your plugin's implementation to restrict whether a path should only be returned to logged in
users & admins, only to admins, or never on the REST API.
Return a ``dict`` with the keys ``admin``, ``user``, ``never`` mapping to a list of paths (as tuples or lists of
the path elements) for which to restrict access via the REST API accordingly. Paths returned for the ``admin``
key will only be available on the REST API when access with admin rights, ``user`` will only be available when accessed
as a logged in user. ``never`` will never be returned on the API.
Example:
.. code-block:: python
def get_settings_defaults(self):
return dict(some=dict(admin_only=dict(path="path", foo="foo"),
user_only=dict(path="path", bar="bar")),
another=dict(admin_only=dict(path="path"),
field="field"),
path=dict(to=dict(never=dict(return="return"))))
def get_settings_restricted_path(self):
return dict(admin=[["some", "admin_only", "path], ["another", "admin_only", "path"],
user=[["some", "user_only", "path"],],
never=[["path", "to", "never", "return"],])
# this will make the plugin return settings on the REST API like this for an anonymous user
#
# dict(some=dict(admin_only=dict(path=None, foo="foo"),
# user_only=dict(path=None, bar="bar")),
# another=dict(admin_only=dict(path=None),
# field="field"),
# path=dict(to=dict(never=dict(return=None))))
#
# like this for a logged in user
#
# dict(some=dict(admin_only=dict(path=None, foo="foo"),
# user_only=dict(path="path", bar="bar")),
# another=dict(admin_only=dict(path=None),
# field="field"),
# path=dict(to=dict(never=dict(return=None))))
#
# and like this for an admin user
#
# dict(some=dict(admin_only=dict(path="path", foo="foo"),
# user_only=dict(path="path", bar="bar")),
# another=dict(admin_only=dict(path="path"),
# field="field"),
# path=dict(to=dict(never=dict(return=None))))
"""
return dict()
def get_settings_preprocessors(self):
"""
Retrieves the plugin's preprocessors to use for preprocessing returned or set values prior to returning/setting
@@ -888,6 +1049,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
@@ -954,6 +1158,13 @@ class SlicerPlugin(OctoPrintPlugin):
against slicers running on the same device will result in an error.
progress_report
``True`` if the slicer can report back slicing progress to OctoPrint ``False`` otherwise.
source_file_types
A list of file types this slicer supports as valid origin file types. These are file types as found in the
paths within the extension tree. Plugins may add additional file types through the :ref:`sec-plugins-hook-filemanager-extensiontree` hook.
The system will test source files contains in incoming slicing requests via :meth:`octoprint.filemanager.valid_file_type` against the
targeted slicer's ``source_file_types``.
destination_extension
The possible extensions of slicing result files.
Returns:
dict: A dict describing the slicer as outlined above.
@@ -962,7 +1173,9 @@ class SlicerPlugin(OctoPrintPlugin):
type=None,
name=None,
same_device=True,
progress_report=False
progress_report=False,
source_file_types=["model"],
destination_extensions=["gco", "gcode", "g"]
)
def get_slicer_default_profile(self):
@@ -0,0 +1,356 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"
import octoprint.plugin
import calendar
import codecs
import os
import re
import time
import threading
import feedparser
import flask
from octoprint.server import admin_permission
from octoprint.server.util.flask import restricted_access
from flask.ext.babel import gettext
class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.BlueprintPlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.TemplatePlugin):
def __init__(self):
self._cached_channel_configs = None
self._cached_channel_configs_mutex = threading.RLock()
from slugify import Slugify
self._slugify = Slugify()
self._slugify.safe_chars = "-_."
# StartupPlugin
def on_after_startup(self):
self._fetch_all_channels()
# SettingsPlugin
def get_settings_defaults(self):
return dict(channels=dict(_important=dict(name="Important OctoPrint Announcements",
priority=1,
type="rss",
url="http://octoprint.org/feeds/important.xml",
read_until=1449446400),
_news=dict(name="OctoPrint News",
priority=2,
type="rss",
url="http://octoprint.org/feeds/news.xml"),
_releases=dict(name="OctoPrint Release Announcements",
priority=2,
type="rss",
url="http://octoprint.org/feeds/releases.xml"),
_spotlight=dict(name="OctoPrint Community Spotlights",
priority=2,
type="rss",
url="http://octoprint.org/feeds/spotlight.xml"),
_octopi=dict(name="OctoPi Announcements",
priority=2,
type="rss",
url="http://octoprint.org/feeds/octopi.xml"),
_plugins=dict(name="New Plugins in the Repository",
priority=2,
type="rss",
url="http://plugins.octoprint.org/feed.xml")),
enabled_channels=[],
forced_channels=["_important"],
ttl=6*60,
display_limit=3,
summary_limit=300)
# AssetPlugin
def get_assets(self):
return dict(js=["js/announcements.js"],
less=["less/announcements.less"],
css=["css/announcements.css"])
# Template Plugin
def get_template_configs(self):
return [
dict(type="settings", name=gettext("Announcements"), template="announcements_settings.jinja2", custom_bindings=True),
dict(type="navbar", template="announcements_navbar.jinja2", styles=["display: none"], data_bind="visible: loginState.isAdmin")
]
# Blueprint Plugin
@octoprint.plugin.BlueprintPlugin.route("/channels", methods=["GET"])
@restricted_access
@admin_permission.require(403)
def get_channel_data(self):
from octoprint.settings import valid_boolean_trues
result = dict()
force = "force" in flask.request.values and flask.request.values["force"] in valid_boolean_trues
channel_data = self._fetch_all_channels(force=force)
channel_configs = self._get_channel_configs(force=force)
enabled = self._settings.get(["enabled_channels"])
forced = self._settings.get(["forced_channels"])
for key, data in channel_configs.items():
read_until = channel_configs[key].get("read_until", None)
entries = sorted(self._to_internal_feed(channel_data.get(key, []), read_until=read_until), key=lambda e: e["published"], reverse=True)
unread = len(filter(lambda e: not e["read"], entries))
if read_until is None and entries:
last = entries[0]["published"]
self._mark_read_until(key, last)
result[key] = dict(channel=data["name"],
url=data["url"],
priority=data.get("priority", 2),
enabled=key in enabled or key in forced,
forced=key in forced,
data=entries,
unread=unread)
return flask.jsonify(result)
@octoprint.plugin.BlueprintPlugin.route("/channels/<channel>", methods=["POST"])
@restricted_access
@admin_permission.require(403)
def channel_command(self, channel):
from octoprint.server.util.flask import get_json_command_from_request
from octoprint.server import NO_CONTENT
valid_commands = dict(read=["until"],
toggle=[])
command, data, response = get_json_command_from_request(flask.request, valid_commands=valid_commands)
if response is not None:
return response
if command == "read":
until = data["until"]
self._mark_read_until(channel, until)
elif command == "toggle":
self._toggle(channel)
return NO_CONTENT
# Internal Tools
def _mark_read_until(self, channel, until):
"""Set read_until timestamp of a channel."""
current_read_until = None
channel_data = self._settings.get(["channels", channel], merged=True)
if channel_data:
current_read_until = channel_data.get("read_until", None)
defaults = dict(plugins=dict(announcements=dict(channels=dict())))
defaults["plugins"]["announcements"]["channels"][channel] = dict(read_until=current_read_until)
with self._cached_channel_configs_mutex:
self._settings.set(["channels", channel, "read_until"], until, defaults=defaults)
self._settings.save()
self._cached_channel_configs = None
def _toggle(self, channel):
"""Toggle enable/disabled state of a channel."""
enabled_channels = list(self._settings.get(["enabled_channels"]))
if channel in enabled_channels:
enabled_channels.remove(channel)
else:
enabled_channels.append(channel)
self._settings.set(["enabled_channels"], enabled_channels)
self._settings.save()
def _get_channel_configs(self, force=False):
"""Retrieve all channel configs with sanitized keys."""
with self._cached_channel_configs_mutex:
if self._cached_channel_configs is None or force:
configs = self._settings.get(["channels"], merged=True)
result = dict()
for key, config in configs.items():
if "url" not in config or "name" not in config:
# strip invalid entries
continue
result[self._slugify(key)] = config
self._cached_channel_configs = result
return self._cached_channel_configs
def _get_channel_config(self, key, force=False):
"""Retrieve specific channel config for channel."""
safe_key = self._slugify(key)
return self._get_channel_configs(force=force).get(safe_key)
def _fetch_all_channels(self, force=False):
"""Fetch all channel feeds from cache or network."""
channels = self._get_channel_configs(force=force)
enabled = self._settings.get(["enabled_channels"])
forced = self._settings.get(["forced_channels"])
all_channels = dict()
for key, config in channels.items():
if not key in enabled and not key in forced:
continue
if not "url" in config:
continue
data = self._get_channel_data(key, config, force=force)
if data is not None:
all_channels[key] = data
return all_channels
def _get_channel_data(self, key, config, force=False):
"""Fetch individual channel feed from cache/network."""
data = None
if not force:
# we may use the cache, see if we have something in there
data = self._get_channel_data_from_cache(key, config)
if data is None:
# cache not allowed or empty, fetch from network
data = self._get_channel_data_from_network(key, config)
return data
def _get_channel_data_from_cache(self, key, config):
"""Fetch channel feed from cache."""
channel_path = self._get_channel_cache_path(key)
if os.path.exists(channel_path):
if "ttl" in config and isinstance(config["ttl"], int):
ttl = config["ttl"]
else:
ttl = self._settings.get_int(["ttl"])
ttl *= 60
now = time.time()
if os.stat(channel_path).st_mtime + ttl > now:
d = feedparser.parse(channel_path)
self._logger.debug(u"Loaded channel {} from cache at {}".format(key, channel_path))
return d
return None
def _get_channel_data_from_network(self, key, config):
"""Fetch channel feed from network."""
import requests
url = config["url"]
try:
start = time.time()
r = requests.get(url)
self._logger.info(u"Loaded channel {} from {} in {:.2}s".format(key, config["url"], time.time() - start))
except Exception as e:
self._logger.exception(
u"Could not fetch channel {} from {}: {}".format(key, config["url"], str(e)))
return None
response = r.text
channel_path = self._get_channel_cache_path(key)
with codecs.open(channel_path, mode="w", encoding="utf-8") as f:
f.write(response)
return feedparser.parse(response)
def _to_internal_feed(self, feed, read_until=None):
"""Convert feed to internal data structure."""
result = []
if "entries" in feed:
for entry in feed["entries"]:
internal_entry = self._to_internal_entry(entry, read_until=read_until)
if internal_entry:
result.append(internal_entry)
return result
def _to_internal_entry(self, entry, read_until=None):
"""Convert feed entries to internal data structure."""
published = calendar.timegm(entry["published_parsed"])
read = True
if read_until is not None:
read = published <= read_until
return dict(title=entry["title"],
title_without_tags=_strip_tags(entry["title"]),
summary=entry["summary"],
summary_without_images=_strip_images(entry["summary"]),
published=published,
link=entry["link"],
read=read)
def _get_channel_cache_path(self, key):
"""Retrieve cache path for channel key."""
safe_key = self._slugify(key)
return os.path.join(self.get_plugin_data_folder(), "{}.cache".format(safe_key))
_image_tag_re = re.compile(r'<img.*?/?>')
def _strip_images(text):
return _image_tag_re.sub('', text)
def _strip_tags(text):
"""
>>> _strip_tags(u"<a href='test.html'>Hello world</a>&lt;img src='foo.jpg'&gt;")
u"Hello world&lt;img src='foo.jpg'&gt;"
>>> _strip_tags(u"&#62; &#x3E; Foo")
u'&#62; &#x3E; Foo'
"""
from HTMLParser import HTMLParser
class TagStripper(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self._fed = []
def handle_data(self, data):
self._fed.append(data)
def handle_entityref(self, ref):
self._fed.append("&{};".format(ref))
def handle_charref(self, ref):
self._fed.append("&#{};".format(ref))
def get_data(self):
return "".join(self._fed)
tag_stripper = TagStripper()
tag_stripper.feed(text)
return tag_stripper.get_data()
__plugin_name__ = "Announcement Plugin"
__plugin_implementation__ = AnnouncementPlugin()
@@ -0,0 +1 @@
table td.settings_plugin_announcements_channels_name,table th.settings_plugin_announcements_channels_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_announcements_channels_actions,table th.settings_plugin_announcements_channels_actions{text-align:center;width:80px}table td.settings_plugin_announcements_channels_actions a,table th.settings_plugin_announcements_channels_actions a{text-decoration:none;color:#000}table td.settings_plugin_announcements_channels_actions a.disabled,table th.settings_plugin_announcements_channels_actions a.disabled{color:#ccc;cursor:default}#plugin_announcements_dialog .unread{font-weight:700}#plugin_announcements_dialog article{padding-right:20px}#plugin_announcements_dialog article.read{opacity:.5}#plugin_announcements_dialog article.read:hover{opacity:1}#plugin_announcements_dialog article .actions{background-color:#f5f5f5;border-radius:2px;padding:2px 5px;margin-top:5px}#plugin_announcements_dialog article .actions .markread{float:right}#plugin_announcements_dialog article .actions a{color:#000}
@@ -0,0 +1,304 @@
$(function() {
function AnnouncementsViewModel(parameters) {
var self = this;
self.loginState = parameters[0];
self.settings = parameters[1];
self.channels = new ItemListHelper(
"plugin.announcements.channels",
{
"channel": function (a, b) {
// sorts ascending
if (a["channel"].toLocaleLowerCase() < b["channel"].toLocaleLowerCase()) return -1;
if (a["channel"].toLocaleLowerCase() > b["channel"].toLocaleLowerCase()) return 1;
return 0;
}
},
{
},
"name",
[],
[],
5
);
self.unread = ko.observable();
self.hiddenChannels = [];
self.channelNotifications = {};
self.announcementDialog = undefined;
self.announcementDialogContent = undefined;
self.announcementDialogTabs = undefined;
self.setupTabLink = function(item) {
$("a[data-toggle='tab']", item).on("show", self.resetContentScroll);
};
self.resetContentScroll = function() {
self.announcementDialogContent.scrollTop(0);
};
self.toggleButtonCss = function(data) {
var icon = data.enabled ? "icon-circle" : "icon-circle-blank";
var disabled = (self.enableToggle(data)) ? "" : " disabled";
return icon + disabled;
};
self.toggleButtonTitle = function(data) {
return data.forced ? gettext("Cannot be toggled") : (data.enabled ? gettext("Disable Channel") : gettext("Enable Channel"));
};
self.enableToggle = function(data) {
return !data.forced;
};
self.markRead = function(channel, until) {
if (!self.loginState.isAdmin()) return;
var url = PLUGIN_BASEURL + "announcements/channels/" + channel;
var payload = {
command: "read",
until: until
};
$.ajax({
url: url,
type: "POST",
dataType: "json",
data: JSON.stringify(payload),
contentType: "application/json; charset=UTF-8",
success: function() {
self.retrieveData()
}
})
};
self.toggleChannel = function(channel) {
if (!self.loginState.isAdmin()) return;
var url = PLUGIN_BASEURL + "announcements/channels/" + channel;
var payload = {
command: "toggle"
};
$.ajax({
url: url,
type: "POST",
dataType: "json",
data: JSON.stringify(payload),
contentType: "application/json; charset=UTF-8",
success: function() {
self.retrieveData()
}
})
};
self.refreshAnnouncements = function() {
self.retrieveData(true);
};
self.retrieveData = function(force) {
if (!self.loginState.isAdmin()) return;
var url = PLUGIN_BASEURL + "announcements/channels";
if (force) {
url += "?force=true";
}
$.ajax({
url: url,
type: "GET",
dataType: "json",
success: function(data) {
self.fromResponse(data);
}
});
};
self.fromResponse = function(data) {
var currentTab = $("li.active a", self.announcementDialogTabs).attr("href");
var unread = 0;
var channels = [];
_.each(data, function(value, key) {
value.key = key;
value.last = value.data.length ? value.data[0].published : undefined;
value.count = value.data.length;
unread += value.unread;
channels.push(value);
});
self.channels.updateItems(channels);
self.unread(unread);
self.displayAnnouncements(channels);
self.selectTab(currentTab);
};
self.showAnnouncementDialog = function(channel) {
self.announcementDialogContent.scrollTop(0);
if (!self.announcementDialog.hasClass("in")) {
self.announcementDialog.modal({
minHeight: function() { return Math.max($.fn.modal.defaults.maxHeight() - 80, 250); }
}).css({
width: 'auto',
'margin-left': function() { return -($(this).width() /2); }
});
}
var tab = undefined;
if (channel) {
tab = "#plugin_announcements_dialog_channel_" + channel;
}
self.selectTab(tab);
return false;
};
self.selectTab = function(tab) {
if (tab != undefined) {
if (!_.startsWith(tab, "#")) {
tab = "#" + tab;
}
$('a[href="' + tab + '"]', self.announcementDialogTabs).tab("show");
} else {
$('a:first', self.announcementDialogTabs).tab("show");
}
};
self.displayAnnouncements = function(channels) {
var displayLimit = self.settings.settings.plugins.announcements.display_limit();
var maxLength = self.settings.settings.plugins.announcements.summary_limit();
var cutAfterNewline = function(text) {
text = text.trim();
var firstNewlinePos = text.indexOf("\n");
if (firstNewlinePos > 0) {
text = text.substr(0, firstNewlinePos).trim();
}
return text;
};
var stripParagraphs = function(text) {
if (_.startsWith(text, "<p>")) {
text = text.substr("<p>".length);
}
if (_.endsWith(text, "</p>")) {
text = text.substr(0, text.length - "</p>".length);
}
return text.replace(/<\/p>\s*<p>/ig, "<br>");
};
_.each(channels, function(value) {
var key = value.key;
var channel = value.channel;
var priority = value.priority;
var items = value.data;
if ($.inArray(key, self.hiddenChannels) > -1) {
// channel currently ignored
return;
}
var newItems = _.filter(items, function(entry) { return !entry.read; });
if (newItems.length == 0) {
// no new items at all, we don't display anything for this channel
return;
}
var displayedItems;
if (newItems.length > displayLimit) {
displayedItems = newItems.slice(0, displayLimit);
} else {
displayedItems = newItems;
}
var rest = newItems.length - displayedItems.length;
var text = "<ul>";
_.each(displayedItems, function(item) {
var limitedSummary = stripParagraphs(item.summary_without_images.trim());
if (limitedSummary.length > maxLength) {
limitedSummary = limitedSummary.substr(0, maxLength);
limitedSummary = limitedSummary.substr(0, Math.min(limitedSummary.length, limitedSummary.lastIndexOf(" ")));
limitedSummary += "...";
}
text += "<li><a href='" + item.link + "' target='_blank' rel='noreferrer noopener'>" + cutAfterNewline(item.title) + "</a><br><small>" + formatTimeAgo(item.published) + "</small><p>" + limitedSummary + "</p></li>";
});
text += "</ul>";
if (rest) {
text += gettext(_.sprintf("... and %(rest)d more.", {rest: rest}));
}
var options = {
title: channel,
text: text,
hide: false,
confirm: {
confirm: true,
buttons: [{
text: gettext("Later"),
click: function(notice) {
self.hiddenChannels.push(key);
notice.remove();
}
}, {
text: gettext("Mark read"),
click: function(notice) {
self.markRead(key, value.last);
notice.remove();
}
}, {
text: gettext("Read..."),
addClass: "btn-primary",
click: function(notice) {
self.showAnnouncementDialog(key);
self.markRead(key, value.last);
notice.remove();
}
}]
},
buttons: {
sticker: false,
closer: false
}
};
if (priority == 1) {
options.type = "error";
}
if (self.channelNotifications[key]) {
self.channelNotifications[key].remove();
}
self.channelNotifications[key] = new PNotify(options);
});
};
self.onUserLoggedIn = function() {
self.retrieveData();
};
self.onStartup = function() {
self.announcementDialog = $("#plugin_announcements_dialog");
self.announcementDialogContent = $("#plugin_announcements_dialog_content");
self.announcementDialogTabs = $("#plugin_announcements_dialog_tabs");
}
}
// view model class, parameters for constructor, container to bind to
ADDITIONAL_VIEWMODELS.push([
AnnouncementsViewModel,
["loginStateViewModel", "settingsViewModel"],
["#plugin_announcements_dialog", "#settings_plugin_announcements", "#navbar_plugin_announcements"]
]);
});
@@ -0,0 +1,56 @@
table {
th, td {
&.settings_plugin_announcements_channels_name {
text-overflow: ellipsis;
text-align: left;
}
&.settings_plugin_announcements_channels_actions {
text-align: center;
width: 80px;
a {
text-decoration: none;
color: #000;
&.disabled {
color: #ccc;
cursor: default;
}
}
}
}
}
#plugin_announcements_dialog {
.unread {
font-weight: bold;
}
article {
padding-right: 20px;
&.read {
opacity: 0.5;
}
&.read:hover {
opacity: 1;
}
.actions {
background-color: #f5f5f5;
border-radius: 2px;
padding: 2px 5px;
margin-top: 5px;
.markread {
float: right;
}
a {
color: black;
}
}
}
}
@@ -0,0 +1,45 @@
<div id="plugin_announcements_dialog" class="modal hide fade large" tabindex="-1" role="dialog" aria-labelledby="announcements_dialog_label" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">&times;</button>
<h3 id="announcements_dialog_label">{{ _('Announcements') }}</h3>
</div>
<div class="modal-body">
<div class="full-sized-box">
<div class="tabbable row-fluid">
<div class="span3 scrollable" id="plugin_announcements_dialog_menu">
<ul class="nav nav-list" id="plugin_announcements_dialog_tabs">
<!-- ko foreach: {data: channels.items, afterAdd: setupTabLink} -->
<!-- ko if: $data.enabled || $data.forced -->
<li>
<a data-toggle="tab" target="_blank" data-bind="text: $data.channel + ' (' + $data.unread + '/' + $data.count + ')', attr: {href: '#plugin_announcements_dialog_channel_' + $data.key}, css: {unread: $data.unread}"></a>
</li>
<!-- /ko -->
<!-- /ko -->
</ul>
</div>
<div class="tab-content span9 scrollable" id="plugin_announcements_dialog_content">
<!-- ko foreach: channels.items -->
<!-- ko if: $data.enabled || $data.forced -->
<div class="tab-pane" data-bind="attr: {id: 'plugin_announcements_dialog_channel_' + $data.key}">
<!-- ko foreach: $data.data -->
<article data-bind="css: {read: $data.read}">
<hr data-bind="visible: $index() > 0">
<h3><a data-bind="text: $data.title, attr: {href: $data.link}" target="_blank" rel="noreferrer noopener"></a> <small data-bind="text: formatTimeAgo($data.published), attr: {title: formatDate($data.published)}"></small></h3>
<div class="content" data-bind="html: $data.summary"></div>
<div class="actions">
<span class="articlelink"><small><a data-bind="text: $data.link, attr: {href: $data.link}" target="_blank" rel="noreferrer noopener"></a></small></span>
<span class="markread"><small><a href="javascript:void(0)" data-bind="click: function() { $root.markRead($parent.key, $data.published) }"><i class="icon-eye-open"></i> {{ _('Mark as last read') }}</a></small></span>
</div>
</article>
<!-- /ko -->
</div>
<!-- /ko -->
<!-- /ko -->
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-block" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</button>
</div>
</div>
@@ -0,0 +1,3 @@
<a id="navbar_show_announcements" class="pull-right" href="javascript:void(0)" data-bind="click: function() { showAnnouncementDialog(); }" title="{{ _('Announcements') }}">
<i data-bind="css: {'icon-bell': !unread(), 'icon-bell-alt': unread()}"></i>
</a>
@@ -0,0 +1,34 @@
<h3>{{ _('Configured Channels') }}</h3>
<table class="table table-striped table-hover table-condensed table-hover">
<thead>
<tr>
<th class="settings_plugin_announcements_channels_name">{{ _('Name') }}</th>
<th class="settings_plugin_announcements_channels_actions">{{ _('Actions') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: channels.paginatedItems">
<tr>
<td class="settings_plugin_announcements_channels_name">
<div data-bind="text: channel, css: {muted: !enabled}"></div>
<div><small class="muted" data-bind="text: url">&nbsp;</small></div>
</td>
<td class="settings_plugin_announcements_channels_actions">
<a href="javascript:void(0)" data-bind="css: $root.toggleButtonCss($data), attr: {title: $root.toggleButtonTitle($data)}, enable: $root.enableToggle($data), click: function() { $root.toggleChannel($data.key) }"></a>
</td>
</tr>
</tbody>
</table>
<div class="pagination pagination-mini pagination-centered">
<ul>
<li data-bind="css: {disabled: channels.currentPage() === 0}"><a href="javascript:void(0)" data-bind="click: channels.prevPage">«</a></li>
</ul>
<ul data-bind="foreach: channels.pages">
<li data-bind="css: { active: $data.number === $root.channels.currentPage(), disabled: $data.number === -1 }"><a href="javascript:void(0)" data-bind="text: $data.text, click: function() { $root.channels.changePage($data.number); }"></a></li>
</ul>
<ul>
<li data-bind="css: {disabled: channels.currentPage() === channels.lastPage()}"><a href="javascript:void(0)" data-bind="click: channels.nextPage">»</a></li>
</ul>
</div>
<button class="btn btn-block" data-bind="click: $root.refreshAnnouncements"><i class="icon-refresh"></i> {{ _('Refresh Announcements') }}</button>
+38 -31
View File
@@ -35,11 +35,19 @@ 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):
# setup our custom logger
cura_logging_handler = logging.handlers.RotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="engine"), maxBytes=2*1024*1024)
from octoprint.logging.handlers import CleaningTimedRotatingFileHandler
cura_logging_handler = CleaningTimedRotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="engine"), when="D", backupCount=3)
cura_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
cura_logging_handler.setLevel(logging.DEBUG)
@@ -159,7 +167,9 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
type="cura",
name="CuraEngine",
same_device=True,
progress_report=True
progress_report=True,
source_file_types=["stl"],
destination_extensions=["gco", "gcode", "g"]
)
def get_slicer_default_profile(self):
@@ -184,9 +194,6 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
return octoprint.slicing.SlicingProfile(properties["type"], "unknown", profile_dict, display_name=display_name, description=description)
def save_slicer_profile(self, path, profile, allow_overwrite=True, overrides=None):
if os.path.exists(path) and not allow_overwrite:
raise octoprint.slicing.ProfileAlreadyExists("cura", profile.name)
new_profile = Profile.merge_profile(profile.data, overrides=overrides)
if profile.display_name is not None:
@@ -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", max_permissions=0o666) 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()
+12 -2
View File
@@ -31,6 +31,11 @@ class MachineShapeTypes(object):
SQUARE = "square"
CIRCULAR = "circular"
class RetractionCombingTypes(object):
OFF = "off"
ALL = "all"
NO_SKIN = "no skin"
class GcodeFlavors(object):
REPRAP = "reprap"
REPRAP_VOLUME = "reprap_volume"
@@ -45,7 +50,7 @@ defaults = dict(
wall_thickness=0.8,
solid_layer_thickness=0.6,
print_temperature=[220, 0, 0, 0],
print_bed_temperature=70,
print_bed_temperature=0,
platform_adhesion=PlatformAdhesionTypes.NONE,
filament_diameter=[2.85, 0, 0, 0],
filament_flow=100.0,
@@ -390,6 +395,11 @@ class Profile(object):
"Both": SupportDualTypes.BOTH,
"First extruder": SupportDualTypes.FIRST,
"Second extruder": SupportDualTypes.SECOND
},
retraction_combing={
"Off": RetractionCombingTypes.OFF,
"All": RetractionCombingTypes.ALL,
"No Skin": RetractionCombingTypes.NO_SKIN
}
)
@@ -865,7 +875,7 @@ class Profile(object):
"retractionAmountExtruderSwitch": self.get_microns("retraction_dual_amount"),
"retractionZHop": self.get_microns("retraction_hop"),
"minimalExtrusionBeforeRetraction": self.get_microns("retraction_minimal_extrusion"),
"enableCombing": 1 if self.get_boolean("retraction_combing") else 0,
"enableCombing": 1 if self.get("retraction_combing") == RetractionCombingTypes.ALL else (2 if self.get("retraction_combing") == RetractionCombingTypes.NO_SKIN else 0),
"multiVolumeOverlap": self.get_microns("overlap_dual"),
"objectSink": max(0, self.get_microns("object_sink")),
"minimalLayerTime": self.get_int("cool_min_layer_time"),
@@ -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>
+112 -21
View File
@@ -11,7 +11,7 @@ import octoprint.plugin.core
from octoprint.settings import valid_boolean_trues
from octoprint.server.util.flask import restricted_access
from octoprint.server import admin_permission
from octoprint.server import admin_permission, VERSION
from octoprint.util.pip import PipCaller, UnknownPip
from flask import jsonify, make_response
@@ -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 = []
@@ -64,7 +65,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
##~~ StartupPlugin
def on_startup(self, host, port):
console_logging_handler = logging.handlers.RotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="console"), maxBytes=2*1024*1024)
from octoprint.logging.handlers import CleaningTimedRotatingFileHandler
console_logging_handler = CleaningTimedRotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="console"), when="D", backupCount=3)
console_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
console_logging_handler.setLevel(logging.DEBUG)
@@ -80,13 +82,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
@@ -101,7 +114,20 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
def get_template_configs(self):
return [
dict(type="settings", name=gettext("Plugin Manager"), template="pluginmanager_settings.jinja2", custom_bindings=True)
dict(type="settings", name=gettext("Plugin Manager"), template="pluginmanager_settings.jinja2", custom_bindings=True),
dict(type="about", name="Plugin Licenses", template="pluginmanager_about.jinja2")
]
def get_template_vars(self):
plugins = sorted(self._get_plugins(), key=lambda x: x["name"].lower())
return dict(
all=plugins,
thirdparty=filter(lambda p: not p["bundled"], plugins)
)
def get_template_types(self, template_sorting, template_rules, *args, **kwargs):
return [
("about_thirdparty", dict(), dict(template=lambda x: x + "_about_thirdparty.jinja2"))
]
##~~ BlueprintPlugin
@@ -166,7 +192,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=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():
@@ -181,6 +220,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":
@@ -199,7 +239,7 @@ 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:
@@ -207,6 +247,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
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"
@@ -415,16 +458,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:
@@ -494,7 +550,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)))
@@ -508,13 +564,14 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
return False
current_os = self._get_os()
octoprint_version = self._get_octoprint_version()
if "-" in octoprint_version:
octoprint_version = octoprint_version[:octoprint_version.find("-")]
octoprint_version = self._get_octoprint_version(base=True)
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
@@ -532,12 +589,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._repository_plugins = map(map_repository_entry, repo_data)
return True
def _is_octoprint_compatible(self, octoprint_version_string, compatibility_entries):
def _is_octoprint_compatible(self, octoprint_version, compatibility_entries):
"""
Tests if the current ``octoprint_version`` is compatible to any of the provided ``compatibility_entries``.
"""
octoprint_version = pkg_resources.parse_version(octoprint_version_string)
for octo_compat in compatibility_entries:
if not any(octo_compat.startswith(c) for c in ("<", "<=", "!=", "==", ">=", ">", "~=", "===")):
octo_compat = ">={}".format(octo_compat)
@@ -566,9 +622,42 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
else:
return "unknown"
def _get_octoprint_version(self):
from octoprint._version import get_versions
return get_versions()["version"]
def _get_octoprint_version_string(self):
return VERSION
def _get_octoprint_version(self, base=False):
octoprint_version_string = self._get_octoprint_version_string()
if "-" in octoprint_version_string:
octoprint_version_string = octoprint_version_string[:octoprint_version_string.find("-")]
octoprint_version = pkg_resources.parse_version(octoprint_version_string)
if base:
if isinstance(octoprint_version, tuple):
# old setuptools
base_version = []
for part in octoprint_version:
if part.startswith("*"):
break
base_version.append(part)
base_version.append("*final")
octoprint_version = tuple(base_version)
else:
# new setuptools
octoprint_version = pkg_resources.parse_version(octoprint_version.base_version)
return octoprint_version
def _get_plugins(self):
plugins = self._plugin_manager.plugins
hidden = self._settings.get(["hidden"])
result = []
for name, plugin in plugins.items():
if name in hidden:
continue
result.append(self._to_external_representation(plugin))
return result
def _to_external_representation(self, plugin):
return dict(
@@ -584,7 +673,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"
@@ -599,5 +689,6 @@ def __plugin_load__():
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.server.http.bodysize": __plugin_implementation__.increase_upload_bodysize
"octoprint.server.http.bodysize": __plugin_implementation__.increase_upload_bodysize,
"octoprint.ui.web.templatetypes": __plugin_implementation__.get_template_types
}
@@ -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,12 +77,20 @@ $(function() {
self.loglines = ko.observableArray([]);
self.installedPlugins = ko.observableArray([]);
self.followDependencyLinks = ko.observable(false);
self.pipAvailable = ko.observable(false);
self.pipCommand = ko.observable();
self.pipVersion = ko.observable();
self.pipUseSudo = ko.observable();
self.pipAdditionalArgs = ko.observable();
self.working = ko.observable(false);
self.workingTitle = ko.observable();
self.workingDialog = undefined;
self.workingOutput = undefined;
self.enableManagement = ko.computed(function() {
self.enableManagement = ko.pureComputed(function() {
return !self.printerState.isPrinting();
});
@@ -84,31 +99,35 @@ $(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() {
self.invalidUrl = ko.pureComputed(function() {
var url = self.installUrl();
return url !== undefined && url.trim() != "" && !(_.startsWith(url.toLocaleLowerCase(), "http://") || _.startsWith(url.toLocaleLowerCase(), "https://"));
});
self.enableUrlInstall = ko.computed(function() {
self.enableUrlInstall = ko.pureComputed(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() {
self.invalidArchive = ko.pureComputed(function() {
var name = self.uploadFilename();
return name !== undefined && !(_.endsWith(name.toLocaleLowerCase(), ".zip") || _.endsWith(name.toLocaleLowerCase(), ".tar.gz") || _.endsWith(name.toLocaleLowerCase(), ".tgz") || _.endsWith(name.toLocaleLowerCase(), ".tar"));
});
self.enableArchiveInstall = ko.computed(function() {
self.enableArchiveInstall = ko.pureComputed(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);
};
@@ -0,0 +1,18 @@
<h3>Plugin Licenses</h3>
<ul>
{% for plugin in plugin_pluginmanager_thirdparty %}
<li>{% if plugin.url %}<a href="{{ plugin.url }}" target="_blank" rel="noreferrer noopener">{% endif %}{{ plugin.name }}{% if plugin.url %}</a>{% endif %}: {% if plugin.license %}{{ plugin.license }}{% else %}-{% endif %}</li>
{% endfor %}
</ul>
{% if templates.plugin_pluginmanager_about_thirdparty.order %}
<h3>Licenses of Plugin Dependencies</h3>
{% for key in templates.plugin_pluginmanager_about_thirdparty.order %}
{% set heading, config = templates.plugin_pluginmanager_about_thirdparty.entries[key] %}
<h4>{{ heading }}</h4>
{% include config.template ignore missing %}
{% endfor %}
{% endif %}
@@ -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>
@@ -21,7 +45,7 @@
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled') }}" class="icon-th-large" data-bind="visible: bundled"></i> <i title="Restart needed" class="icon-refresh" data-bind="visible: pending_enable || pending_disable || pending_uninstall"></i> <i title="Uninstalled" class="icon-remove" data-bind="visible: pending_uninstall"></i></div>
<div><small class="muted" data-bind="text: description">&nbsp;</small></div>
<div data-bind="css: {muted: !enabled}">
<small data-bind="visible: url"><i class="icon-home"></i> <a data-bind="attr: {href: url}">{{ _('Homepage') }}</a></small>
<small data-bind="visible: url"><i class="icon-home"></i> <a data-bind="attr: {href: url}" target="_blank" rel="noreferrer noopener">{{ _('Homepage') }}</a></small>
<small data-bind="visible: license"><i class="icon-legal"></i> <span data-bind="text: license"></span></small>
<small data-bind="visible: author"><i class="icon-user"></i> <span data-bind="text: author"></span></small>
<small>&nbsp;</small>
@@ -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>
+377 -76
View File
@@ -12,12 +12,13 @@ import flask
import os
import threading
import time
import hashlib
from . import version_checks, updaters, exceptions, util
from octoprint.server.util.flask import restricted_access
from octoprint.server import admin_permission
from octoprint.server import admin_permission, VERSION, REVISION, BRANCH
from octoprint.util import dict_merge
import octoprint.settings
@@ -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,76 +98,218 @@ 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, max_permissions=0o666) 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
def get_settings_defaults(self):
update_script = os.path.join(self._basefolder, "scripts", "update-octoprint.py")
return {
"checks": {
"octoprint": {
"type": "github_release",
"user": "foosel",
"repo": "OctoPrint",
"update_script": "{{python}} \"{update_script}\" --python=\"{{python}}\" \"{{folder}}\" {{target}}".format(update_script=os.path.join(self._basefolder, "scripts", "update-octoprint.py")),
"restart": "octoprint"
"update_script": "{{python}} \"{update_script}\" --branch={{branch}} --force={{force}} \"{{folder}}\" {{target}}".format(update_script=update_script),
"restart": "octoprint",
"stable_branch": dict(branch="master", name="Stable"),
"prerelease_branches": [dict(branch="rc/maintenance", name="Maintenance RCs"),
dict(branch="rc/devel", name="Devel RCs")]
},
},
"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"]
if "check_providers" in data:
del data["check_providers"]
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)
try:
data["octoprint_method"] = self._get_update_method("octoprint", checks["octoprint"])
except exceptions.UnknownUpdateType:
data["octoprint_method"] = "unknown"
stable_branch = None
prerelease_branches = []
branch_mappings = []
if "stable_branch" in checks["octoprint"]:
branch_mappings.append(checks["octoprint"]["stable_branch"])
stable_branch = checks["octoprint"]["stable_branch"]["branch"]
if "prerelease_branches" in checks["octoprint"]:
for mapping in checks["octoprint"]["prerelease_branches"]:
branch_mappings.append(mapping)
prerelease_branches.append(mapping["branch"])
data["octoprint_branch_mappings"] = branch_mappings
data["octoprint_release_channel"] = stable_branch
if checks["octoprint"].get("prerelease", False):
channel = checks["octoprint"].get("prerelease_channel", BRANCH)
if channel in prerelease_branches:
data["octoprint_release_channel"] = channel
else:
data["octoprint_checkout_folder"] = None
data["octoprint_type"] = None
data["octoprint_branch_mappings"] = []
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 in ("checks", "cache_ttl", "octoprint_checkout_folder", "octoprint_type", "octoprint_release_channel"):
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)
prerelease = check.get("prerelease", False)
prerelease_channel = check.get("prerelease_channel", None)
else:
update_type = checkout_folder = update_folder = prerelease_channel = None
prerelease = False
defaults = dict(
plugins=dict(softwareupdate=dict(
checks=dict(
octoprint=dict(
type=update_type,
checkout_folder=checkout_folder,
update_folder=update_folder,
prerelease=prerelease,
prerelease_channel=prerelease_channel
)
)
))
)
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
if "octoprint_release_channel" in data:
prerelease_branches = self._settings.get(["checks", "octoprint", "prerelease_branches"])
if prerelease_branches and data["octoprint_release_channel"] in [x["branch"] for x in prerelease_branches]:
self._settings.set(["checks", "octoprint", "prerelease"], True, defaults=defaults, force=True)
self._settings.set(["checks", "octoprint", "prerelease_channel"], data["octoprint_release_channel"], defaults=defaults, force=True)
self._refresh_configured_checks = True
else:
self._settings.set(["checks", "octoprint", "prerelease"], False, defaults=defaults, force=True)
self._settings.set(["checks", "octoprint", "prerelease_channel"], None, 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 +323,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 +353,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:
@@ -216,7 +385,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
@restricted_access
def check_for_update(self):
if "check" in flask.request.values:
check_targets = map(str.strip, flask.request.values["check"].split(","))
check_targets = map(lambda x: x.strip(), flask.request.values["check"].split(","))
else:
check_targets = None
@@ -227,7 +396,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
try:
information, update_available, update_possible = self.get_current_versions(check_targets=check_targets, force=force)
return flask.jsonify(dict(status="updatePossible" if update_available and update_possible else "updateAvailable" if update_available else "current", information=information))
return flask.jsonify(dict(status="updatePossible" if update_available and update_possible else "updateAvailable" if update_available else "current",
information=information))
except exceptions.ConfigurationInvalid as e:
flask.make_response("Update not properly configured, can't proceed: %s" % e.message, 500)
@@ -246,7 +416,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
json_data = flask.request.json
if "check" in json_data:
check_targets = map(str.strip, json_data["check"])
check_targets = map(lambda x: x.strip(), json_data["check"])
else:
check_targets = None
@@ -270,8 +440,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 +468,62 @@ 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)
target_information = dict_merge(dict(local=dict(name="unknown", value="unknown"), remote=dict(name="unknown", value="unknown", release_notes=None)), 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"]
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)
release_notes = None
if target_information and target_information["remote"] and target_information["remote"]["value"]:
if "release_notes" in populated_check and populated_check["release_notes"]:
release_notes = populated_check["release_notes"]
elif "release_notes" in target_information["remote"]:
release_notes = target_information["remote"]["release_notes"]
if release_notes:
release_notes = release_notes.format(octoprint_version=VERSION,
target_name=target_information["remote"]["name"],
target_version=target_information["remote"]["value"])
information[target] = dict(updateAvailable=target_update_available,
updatePossible=target_update_possible,
information=target_information,
displayName=populated_check["displayName"],
displayVersion=populated_check["displayVersion"].format(octoprint_version=VERSION, local_name=local_name, local_value=local_value),
check=populated_check,
releaseNotes=release_notes)
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 +546,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 +565,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 +643,12 @@ 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])
restart_command = None
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 +741,83 @@ 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}")
stable_branch = "master"
release_branches = []
if "stable_branch" in check:
release_branches.append(check["stable_branch"]["branch"])
stable_branch = check["stable_branch"]["branch"]
if "prerelease_branches" in check:
release_branches += [x["branch"] for x in check["prerelease_branches"]]
result["released_version"] = not release_branches or BRANCH in release_branches
if check["type"] == "github_commit":
result["current"] = REVISION if REVISION else "unknown"
else:
result["current"] = VERSION
if check["type"] == "github_release" and (check.get("prerelease", None) or BRANCH != stable_branch):
# we are tracking github releases and are either also tracking prerelease OR are currently installed
# from something that is not the stable (master) branch => we need to change some parameters
# we compare versions fully, not just the base so that we see a difference
# between RCs + stable for the same version release
result["force_base"] = False
if check.get("update_script", None):
# if we are using the update_script, we need to set our update_branch and force
# to install the exact version we requested
if check.get("prerelease", None):
# we are tracking prereleases => we want to be on the correct prerelease channel/branch
channel = check.get("prerelease_channel", None)
if channel:
# if we have a release channel, we also set our update_branch here to our release channel
# in case it's not already set
result["update_branch"] = check.get("update_branch", channel)
# we also force our target version in the update
result["force_exact_version"] = True
else:
# we are not tracking prereleases, but aren't on the stable branch either => switch back
# to stable branch on update
result["update_branch"] = check.get("update_branch", stable_branch)
if BRANCH != result.get("prerelease_channel"):
# we force python unequality check here because that will also allow us to
# downgrade on a prerelease channel change (rc/devel => rc/maintenance)
#
# we detect channel changes by comparing the current branch with the target
# branch of the release channel - unequality means we might have to handle
# a downgrade
result["release_compare"] = "python_unequal"
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))
if "pip" in result:
if not "pip_command" in check and self._settings.get(["pip_command"]) is not None:
result["pip_command"] = self._settings.get(["pip_command"])
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 +827,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
@@ -563,22 +841,45 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
else:
raise exceptions.UnknownCheckType()
def _get_update_method(self, target, check, valid_methods=None):
"""
Determines the update method for the given target and check.
If ``valid_methods`` is provided, determine method must be contained
therein to be considered valid.
Raises an ``UnknownUpdateType`` exception if method cannot be determined
or validated.
"""
method = None
if "method" in check:
method = check["method"]
else:
if "update_script" in check:
method = "update_script"
elif "pip" in check:
method = "pip"
elif "python_updater" in check:
method = "python_updated"
if method is None or (valid_methods and not method in valid_methods):
raise exceptions.UnknownUpdateType()
return method
def _get_updater(self, target, check):
"""
Retrieves the updater for the given target and check configuration. Will raise an UnknownUpdateType if updater
cannot be determined.
"""
if "update_script" in check:
return updaters.update_script
elif "pip" in check:
if not "pip_command" in check and self._settings.get(["pip_command"]) is not None:
check["pip_command"] = self._settings.get(["pip_command"])
return updaters.pip
elif "python_updater" in check:
return updaters.python_updater
else:
raise exceptions.UnknownUpdateType()
mapping = dict(update_script=updaters.update_script,
pip=updaters.pip,
python_updater=updaters.python_updater)
method = self._get_update_method(target, check, valid_methods=mapping.keys())
return mapping[method]
__plugin_name__ = "Software Update"
__plugin_author__ = "Gina Häußge"
@@ -71,7 +71,7 @@ def _python(args, cwd, python_executable, sudo=False):
return p.returncode, stdout
def update_source(git_executable, folder, target, force=False):
def _rescue_changes(git_executable, folder):
print(">>> Running: git diff --shortstat")
returncode, stdout = _git(["diff", "--shortstat"], folder, git_executable=git_executable)
if returncode != 0:
@@ -91,11 +91,30 @@ def update_source(git_executable, folder, target, force=False):
with open(patch, "wb") as f:
f.write(stdout)
return True
return False
def update_source(git_executable, folder, target, force=False, branch=None):
if _rescue_changes(git_executable, folder):
print(">>> Running: git reset --hard")
returncode, stdout = _git(["reset", "--hard"], folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Could not update, \"git reset --hard\" failed with returncode %d: %s" % (returncode, stdout))
print(">>> Running: git fetch")
returncode, stdout = _git(["fetch"], folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Could not update, \"git fetch\" failed with returncode %d: %s" % (returncode, stdout))
print(stdout)
if branch is not None and branch.strip() != "":
print(">>> Running: git checkout {}".format(branch))
returncode, stdout = _git(["checkout", branch], folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Could not update, \"git checkout\" failed with returncode %d: %s" % (returncode, stdout))
print(">>> Running: git pull")
returncode, stdout = _git(["pull"], folder, git_executable=git_executable)
if returncode != 0:
@@ -103,7 +122,7 @@ def update_source(git_executable, folder, target, force=False):
print(stdout)
if force:
reset_command = ["reset"]
reset_command = ["reset", "--hard"]
reset_command += [target]
print(">>> Running: git %s" % " ".join(reset_command))
@@ -134,18 +153,24 @@ def install_source(python_executable, folder, user=False, sudo=False):
def parse_arguments():
import argparse
boolean_trues = ["true", "yes", "1"]
boolean_falses = ["false", "no", "0"]
parser = argparse.ArgumentParser(prog="update-octoprint.py")
parser.add_argument("--git", action="store", type=str, dest="git_executable",
help="Specify git executable to use")
parser.add_argument("--python", action="store", type=str, dest="python_executable",
help="Specify python executable to use")
parser.add_argument("--force", action="store_true", dest="force",
help="Set this to force the update to only the specified version (nothing newer)")
parser.add_argument("--force", action="store", type=lambda x: x in boolean_trues,
dest="force", default=False,
help="Set this to true to force the update to only the specified version (nothing newer, nothing older)")
parser.add_argument("--sudo", action="store_true", dest="sudo",
help="Install with sudo")
parser.add_argument("--user", action="store_true", dest="user",
help="Install to the user site directory instead of the general site directory")
parser.add_argument("--branch", action="store", type=str, dest="branch", default=None,
help="Specify the branch to make sure is checked out")
parser.add_argument("folder", type=str,
help="Specify the base folder of the OctoPrint installation to update")
parser.add_argument("target", type=str,
@@ -167,13 +192,12 @@ def main():
python_executable = args.python_executable
folder = args.folder
target = args.target
import os
if not os.access(folder, os.W_OK):
raise RuntimeError("Could not update, base folder is not writable")
update_source(git_executable, folder, target, force=args.force)
update_source(git_executable, folder, args.target, force=args.force, branch=args.branch)
install_source(python_executable, folder, user=args.user, sudo=args.sudo)
if __name__ == "__main__":
@@ -1 +1 @@
td.settings_plugin_softwareupdate_column_update{width:16px}
td.settings_plugin_softwareupdate_column_update{width:16px}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
@@ -7,17 +7,30 @@ $(function() {
self.settings = parameters[2];
self.popup = undefined;
self.forceUpdate = false;
self.updateInProgress = false;
self.waitingForRestart = false;
self.restartTimeout = undefined;
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.config_updateMethod = ko.observable();
self.config_releaseChannel = ko.observable();
self.configurationDialog = $("#settings_plugin_softwareupdate_configurationdialog");
self.confirmationDialog = $("#softwareupdate_confirmation_dialog");
self.config_availableCheckTypes = ko.observableArray([]);
self.config_availableReleaseChannels = ko.observableArray([]);
self.reloadOverlay = $("#reloadui_overlay");
self.versions = new ItemListHelper(
"plugin.softwareupdate.versions",
@@ -39,6 +52,10 @@ $(function() {
5
);
self.availableAndPossible = ko.computed(function() {
return _.filter(self.versions.items(), function(info) { return info.updateAvailable && info.updatePossible; });
});
self.onUserLoggedIn = function() {
self.performCheck();
};
@@ -78,19 +95,43 @@ $(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(),
octoprint_release_channel: self.config_releaseChannel()
}
}
};
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());
var updateMethod = self.settings.settings.plugins.softwareupdate.octoprint_method();
var availableCheckTypes = [];
if (updateMethod == "update_script" || updateMethod == "python") {
availableCheckTypes = [{"key": "github_release", "name": gettext("Release")},
{"key": "git_commit", "name": gettext("Commit")}];
} else {
availableCheckTypes = [];
}
self.config_availableCheckTypes(availableCheckTypes);
var availableReleaseChannels = [];
_.each(self.settings.settings.plugins.softwareupdate.octoprint_branch_mappings(), function(mapping) {
availableReleaseChannels.push({"key": mapping.branch(), "name": gettext(mapping.name() || mapping.branch())});
});
self.config_availableReleaseChannels(availableReleaseChannels);
self.config_updateMethod(updateMethod);
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.config_releaseChannel(self.settings.settings.plugins.softwareupdate.octoprint_release_channel());
};
self.fromCheckResponse = function(data, ignoreSeen, showIfNothingNew) {
@@ -104,28 +145,61 @@ $(function() {
if (!value.hasOwnProperty("displayVersion") || value.displayVersion == "") {
value.displayVersion = value.information.local.name;
}
if (!value.hasOwnProperty("releaseNotes") || value.releaseNotes == "") {
value.releaseNotes = undefined;
}
var fullNameTemplate = gettext("%(name)s: %(version)s");
value.fullNameLocal = _.sprintf(fullNameTemplate, {name: value.displayName, version: value.displayVersion});
var fullNameRemoteVars = {name: value.displayName, version: gettext("unknown")};
if (value.hasOwnProperty("information") && value.information.hasOwnProperty("remote") && value.information.remote.hasOwnProperty("name")) {
fullNameRemoteVars.version = value.information.remote.name;
}
value.fullNameRemote = _.sprintf(fullNameTemplate, fullNameRemoteVars);
versions.push(value);
});
self.versions.updateItems(versions);
if (data.status == "updateAvailable" || data.status == "updatePossible") {
var text = gettext("There are updates available for the following components:");
var octoprint = data.information["octoprint"];
if (octoprint && octoprint.hasOwnProperty("check")) {
var check = octoprint.check;
if (check["released_version"] === false && check["type"] == "github_release") {
self.octoprintUnreleased(true);
} else {
self.octoprintUnreleased(false);
}
text += "<ul>";
var checkoutFolder = (check["checkout_folder"] || "").trim();
var updateFolder = (check["update_folder"] || "").trim();
var needsFolder = check["update_script"] || false;
if (needsFolder && checkoutFolder == "" && updateFolder == "") {
self.octoprintUnconfigured(true);
} else {
self.octoprintUnconfigured(false);
}
}
if (data.status == "updateAvailable" || data.status == "updatePossible") {
var text = "<div class='softwareupdate_notification'>" + gettext("There are updates available for the following components:");
text += "<ul class='icons-ul'>";
_.each(self.versions.items(), function(update_info) {
if (update_info.updateAvailable) {
var displayName = update_info.key;
if (update_info.hasOwnProperty("displayName")) {
displayName = update_info.displayName;
}
text += "<li>" + displayName + (update_info.updatePossible ? " <i class=\"icon-ok\"></i>" : "") + "</li>";
text += "<li>"
+ "<i class='icon-li " + (update_info.updatePossible ? "icon-ok" : "icon-remove")+ "'></i>"
+ "<span class='name' title='" + update_info.fullNameRemote + "'>" + update_info.fullNameRemote + "</span>"
+ (update_info.releaseNotes ? "<a href=\"" + update_info.releaseNotes + "\" target=\"_blank\">" + gettext("Release Notes") + "</a>" : "")
+ "</li>";
}
});
text += "</ul>";
text += "<small>" + gettext("Those components marked with <i class=\"icon-ok\"></i> can be updated directly.") + "</small>";
text += "</div>";
var options = {
title: gettext("Update Available"),
text: text,
@@ -142,7 +216,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\"")
});
}
}, {
@@ -224,7 +298,7 @@ $(function() {
return result;
};
self.performUpdate = function(force) {
self.performUpdate = function(force, items) {
self.updateInProgress = true;
var options = {
@@ -239,12 +313,19 @@ $(function() {
};
self._showPopup(options);
var postData = {
force: (force == true)
};
if (items != undefined) {
postData.check = items;
}
$.ajax({
url: PLUGIN_BASEURL + "softwareupdate/update",
type: "POST",
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify({force: (force == true)}),
data: JSON.stringify(postData),
error: function() {
self.updateInProgress = false;
self._showPopup({
@@ -267,8 +348,6 @@ $(function() {
if (self.updateInProgress) return;
if (!self.loginState.isAdmin()) return;
force = (force == true);
if (self.printerState.isPrinting()) {
self._showPopup({
title: gettext("Can't update while printing"),
@@ -276,18 +355,18 @@ $(function() {
type: "error"
});
} else {
$("#confirmation_dialog .confirmation_dialog_message").text(gettext("This will update your OctoPrint installation and restart the server."));
$("#confirmation_dialog .confirmation_dialog_acknowledge").unbind("click");
$("#confirmation_dialog .confirmation_dialog_acknowledge").click(function(e) {
e.preventDefault();
$("#confirmation_dialog").modal("hide");
self.performUpdate(force);
});
$("#confirmation_dialog").modal("show");
self.forceUpdate = (force == true);
self.confirmationDialog.modal("show");
}
};
self.confirmUpdate = function() {
self.confirmationDialog.modal("hide");
self.performUpdate(self.forceUpdate,
_.map(self.availableAndPossible(), function(info) { return info.key }));
};
self.onServerDisconnect = function() {
if (self.restartTimeout !== undefined) {
clearTimeout(self.restartTimeout);
@@ -298,18 +377,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 +433,7 @@ $(function() {
}
});
self.waitingForRestart = false;
}, 20000);
}, 60000);
break;
}
@@ -447,5 +518,9 @@ $(function() {
}
// view model class, parameters for constructor, container to bind to
ADDITIONAL_VIEWMODELS.push([SoftwareUpdateViewModel, ["loginStateViewModel", "printerStateViewModel", "settingsViewModel"], document.getElementById("settings_plugin_softwareupdate")]);
ADDITIONAL_VIEWMODELS.push([
SoftwareUpdateViewModel,
["loginStateViewModel", "printerStateViewModel", "settingsViewModel"],
["#settings_plugin_softwareupdate", "#softwareupdate_confirmation_dialog"]
]);
});
@@ -1,3 +1,17 @@
td.settings_plugin_softwareupdate_column_update {
width: 16px;
}
}
.softwareupdate_notification {
ul {
margin: 10px 0 10px 25px;
.name {
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
display: block;
}
}
}
@@ -0,0 +1,29 @@
<div id="softwareupdate_confirmation_dialog" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>{{ _('Are you sure you want to update now?') }}</h3>
</div>
<div class="modal-body">
<p>
{{ _('This will update the following components and restart the server:') }}
</p>
<ul>
<!-- ko foreach: availableAndPossible -->
<li>
<span class="name" data-bind="text: fullNameRemote, attr: {title: fullNameRemote}"></span>
<div class="releaseNotes" data-bind="visible: releaseNotes"><a data-bind="attr: {href: releaseNotes}" target="_blank" rel="noreferrer noopener">{{ _('Release Notes') }}</a></div>
</li>
<!-- /ko -->
</ul>
<p>
{{ _('Be sure to read through any linked release notes, especially those for OctoPrint since they might contain important information you need to know <strong>before</strong> upgrading.') }}
</p>
<p>
{{ _('Are you sure you want to proceed?') }}
</p>
</div>
<div class="modal-footer">
<a href="#" class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</a>
<a href="#" class="btn btn-danger" data-bind="click: function() { $root.confirmUpdate(); }">{{ _('Proceed') }}</a>
</div>
</div>
@@ -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,10 +29,11 @@
<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>
{{ _('Available:') }} <span data-bind="text: information.remote.name"></span><br>
<span data-bind="visible: releaseNotes">{{ _('Release Notes:') }} <a data-bind="attr: {href: releaseNotes}, text: releaseNotes" target="_blank" rel="noreferrer noopener"></a></span>
</small>
</td>
</tr>
@@ -44,7 +63,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>
@@ -55,16 +74,23 @@
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Restart Command') }}</label>
<div class="control-group" data-bind="visible: config_updateMethod() == 'update_script' || config_updateMethod() == 'python_updater'">
<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>
<div class="control-group" data-bind="visible: config_availableCheckTypes().length > 0">
<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" data-bind="visible: config_availableCheckTypes().length > 0 && config_checkType() == 'github_release'">
<label class="control-label">{{ _('OctoPrint Release Channel') }}</label>
<div class="controls">
<select data-bind="value: config_releaseChannel, options: config_availableReleaseChannels, optionsText: 'name', optionsValue: 'key'"></select>
<span class="help-inline">{{ _('Make sure you have read <a href="%(url)s" target="_blank" rel="noreferrer noopener">"Using Release Channels"</a> before switching to a release channel other than "Stable"', url="https://github.com/foosel/OctoPrint/wiki/Using-Release-Channels") }}</span>
</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):
@@ -23,9 +33,11 @@ def perform_update(target, check, target_version):
raise ConfigurationInvalid("checkout_folder and update_folder are missing for update target %s, one is needed" % target)
update_script = check["update_script"]
folder = check["update_folder"] if "update_folder" in check else check["checkout_folder"]
pre_update_script = check["pre_update_script"] if "pre_update_script" in check else None
post_update_script = check["post_update_script"] if "post_update_script" in check else None
update_branch = check.get("update_branch", "")
force_exact_version = check.get("force_exact_version", False)
folder = check.get("update_folder", check.get("checkout_folder")) # either should be set, tested above
pre_update_script = check.get("pre_update_script", None)
post_update_script = check.get("post_update_script", None)
update_stdout = ""
update_stderr = ""
@@ -46,7 +58,11 @@ def perform_update(target, check, target_version):
### update
try:
update_command = update_script.format(python=sys.executable, folder=folder, target=target_version)
update_command = update_script.format(python=sys.executable,
folder=folder,
target=target_version,
branch=update_branch,
force="true" if force_exact_version else "false")
logger.debug("Target %s, running update script: %s" % (target, update_command))
returncode, stdout, stderr = execute(update_command, cwd=folder)
@@ -65,7 +65,7 @@ def get_latest(target, check):
if returncode != 0:
return None, True
return_code, base = _git(["merge-base", "@{0}", "@{u}"], checkout_folder)
returncode, base = _git(["merge-base", "@{0}", "@{u}"], checkout_folder)
if returncode != 0:
return None, True
@@ -14,65 +14,218 @@ RELEASE_URL = "https://api.github.com/repos/{user}/{repo}/releases"
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.github_release")
def _get_latest_release(user, repo, include_prerelease=False):
def _filter_out_latest(releases,
sort_key=None,
include_prerelease=False,
prerelease_channel=None):
"""
Filters out the newest of all matching releases.
Tests:
>>> release_1_2_15 = dict(name="1.2.15", tag_name="1.2.15", html_url="some_url", published_at="2016-07-29T19:53:29Z", prerelease=False, draft=False, target_commitish="prerelease")
>>> release_1_2_16rc1 = dict(name="1.2.16rc1", tag_name="1.2.16rc1", html_url="some_url", published_at="2016-08-29T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance")
>>> release_1_2_16rc2 = dict(name="1.2.16rc2", tag_name="1.2.16rc2", html_url="some_url", published_at="2016-08-30T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance")
>>> release_1_2_17rc1 = dict(name="1.2.17rc1", tag_name="1.2.17rc1", html_url="some_url", published_at="2016-08-31T12:00:00Z", prerelease=True, draft=True, target_commitish="rc/maintenance")
>>> release_1_3_0rc1 = dict(name="1.3.0rc1", tag_name="1.3.0rc1", html_url="some_url", published_at="2016-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/devel")
>>> release_1_4_0rc1 = dict(name="1.4.0rc1", tag_name="1.4.0rc1", html_url="some_url", published_at="2017-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/future")
>>> releases = [release_1_2_15, release_1_2_16rc1, release_1_2_16rc2, release_1_2_17rc1, release_1_3_0rc1, release_1_4_0rc1]
>>> _filter_out_latest(releases, include_prerelease=False, prerelease_channel=None)
('1.2.15', '1.2.15', 'some_url')
>>> _filter_out_latest(releases, include_prerelease=True, prerelease_channel="rc/maintenance")
('1.2.16rc2', '1.2.16rc2', 'some_url')
>>> _filter_out_latest(releases, include_prerelease=True, prerelease_channel="rc/devel")
('1.3.0rc1', '1.3.0rc1', 'some_url')
>>> _filter_out_latest(releases, include_prerelease=True, prerelease_channel=None)
('1.4.0rc1', '1.4.0rc1', 'some_url')
>>> _filter_out_latest(releases, include_prerelease=True, prerelease_channel="rc/doesntexist")
('1.2.15', '1.2.15', 'some_url')
>>> _filter_out_latest([release_1_2_17rc1])
(None, None, None)
>>> _filter_out_latest([release_1_2_16rc1, release_1_2_16rc2])
(None, None, None)
"""
nothing = None, None, None
if sort_key is None:
sort_key = lambda release: release.get("published_at", None)
# filter out prereleases and drafts
filter_function = lambda rel: not rel["prerelease"] and not rel["draft"]
if include_prerelease:
if prerelease_channel:
filter_function = lambda rel: not rel["draft"] and (
not rel["prerelease"] or rel["target_commitish"] == prerelease_channel)
else:
filter_function = lambda rel: not rel["draft"]
releases = filter(filter_function, releases)
if not releases:
return nothing
# sort by sort_key
releases = sorted(releases, key=sort_key)
# latest release = last in list
latest = releases[-1]
return latest["name"], latest["tag_name"], latest.get("html_url", None)
def _get_latest_release(user, repo, compare_type,
include_prerelease=False,
prerelease_channel=None,
force_base=True):
nothing = None, None, None
r = requests.get(RELEASE_URL.format(user=user, repo=repo))
from . import log_github_ratelimit
log_github_ratelimit(logger, r)
if not r.status_code == requests.codes.ok:
return None, None
return nothing
releases = r.json()
# filter out prereleases and drafts
if include_prerelease:
releases = filter(lambda rel: not rel["draft"], releases)
# sanitize
required_fields = {"name", "tag_name", "html_url", "draft", "prerelease", "published_at", "target_commitish"}
releases = filter(lambda rel: set(rel.keys()) & required_fields == required_fields,
releases)
comparable_factory = _get_comparable_factory(compare_type,
force_base=force_base)
sort_key = lambda release: comparable_factory(_get_sanitized_version(release["tag_name"]))
return _filter_out_latest(releases,
sort_key=sort_key,
include_prerelease=include_prerelease,
prerelease_channel=prerelease_channel)
def _get_sanitized_version(version_string):
"""
Removes "-..." prefix from version strings.
Tests:
>>> _get_sanitized_version("1.2.15")
'1.2.15'
>>> _get_sanitized_version("1.2.15-dev12")
'1.2.15'
"""
if "-" in version_string:
version_string = version_string[:version_string.find("-")]
return version_string
def _get_base_from_version_tuple(version_tuple):
"""
Reduces version tuple to base version.
Tests:
>>> _get_base_from_version_tuple(("1", "2", "15"))
('1', '2', '15')
>>> _get_base_from_version_tuple(("1", "2", "15", "*", "dev12"))
('1', '2', '15')
"""
base_version = []
for part in version_tuple:
if part.startswith("*"):
break
base_version.append(part)
return tuple(base_version)
def _get_comparable_version_pkg_resources(version_string, force_base=True):
import pkg_resources
version = pkg_resources.parse_version(version_string)
if force_base:
if isinstance(version, tuple):
# old setuptools
version = _get_base_from_version_tuple(version)
else:
# new setuptools
version = pkg_resources.parse_version(version.base_version)
return version
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 _get_sanitized_compare_type(compare_type, custom=None):
if not compare_type in ("python", "python_unequal",
"semantic", "semantic_unequal",
"unequal", "custom") or compare_type == "custom" and custom is None:
compare_type = "python"
return compare_type
def _get_comparable_factory(compare_type, force_base=True):
if compare_type in ("python", "python_unequal"):
return lambda version: _get_comparable_version_pkg_resources(version, force_base=force_base)
elif compare_type in ("semantic", "semantic_unequal"):
return lambda version: _get_comparable_version_semantic(version, force_base=force_base)
else:
releases = filter(lambda rel: not rel["prerelease"] and not rel["draft"], releases)
if not releases:
return None, None
# sort by date
comp = lambda a, b: cmp(a["published_at"], b["published_at"])
releases = sorted(releases, cmp=comp)
# latest release = last in list
latest = releases[-1]
return latest["name"], latest["tag_name"]
return lambda version: version
def _is_current(release_information, compare_type, custom=None):
def _get_comparator(compare_type, custom=None):
if compare_type in ("python", "semantic"):
return lambda a, b: a >= b
elif compare_type == "custom":
return custom
else:
return lambda a, b: a == b
def _is_current(release_information, compare_type, custom=None, force_base=True):
"""
Checks if the provided release information indicates the version being the most current one.
Tests:
>>> _is_current(dict(remote=dict(value=None))
True
>>> _is_current(dict(local=dict(value="1.2.15"), remote=dict(value="1.2.16")))
False
>>> _is_current(dict(local=dict(value="1.2.16dev1"), remote=dict(value="1.2.16dev2")))
True
>>> _is_current(dict(local=dict(value="1.2.16dev1"), remote=dict(value="1.2.16dev2")), force_base=False)
False
>>> _is_current(dict(local=dict(value="1.2.16dev3"), remote=dict(value="1.2.16dev2")), force_base=False)
True
>>> _is_current(dict(local=dict(value="1.2.16dev3"), remote=dict(value="1.2.16dev2")), force_base=False, compare_type="python_unequal")
False
"""
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"
compare_type = _get_sanitized_compare_type(compare_type, custom=custom)
comparable_factory = _get_comparable_factory(compare_type, force_base=force_base)
comparator = _get_comparator(compare_type, custom=custom)
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"])
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"])
return local_version >= remote_version
elif compare_type == "custom":
return custom(release_information["local"], release_information["remote"])
else:
return release_information["local"]["value"] == release_information["remote"]["value"]
return comparator(comparable_factory(sanitized_local),
comparable_factory(sanitized_remote))
except:
logger.exception("Could not check if version is current due to an error, assuming it is")
return True
@@ -82,18 +235,28 @@ 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)
prerelease_channel = check.get("prerelease_channel", None)
force_base = check.get("force_base", True)
compare_type = _get_sanitized_compare_type(check.get("release_compare", "python"),
custom=custom_compare)
remote_name, remote_tag = _get_latest_release(check["user"], check["repo"], include_prerelease=check["prerelease"] == True if "prerelease" in check else False)
compare_type = check["release_compare"] if "release_compare" in check else "python"
remote_name, remote_tag, release_notes = _get_latest_release(check["user"],
check["repo"],
compare_type,
include_prerelease=include_prerelease,
prerelease_channel=prerelease_channel,
force_base=force_base)
information =dict(
local=dict(name=current, value=current),
remote=dict(name=remote_name, value=remote_tag)
remote=dict(name=remote_name, value=remote_tag, release_notes=release_notes)
)
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)
+273 -96
View File
@@ -16,7 +16,7 @@ from serial import SerialTimeoutException
from octoprint.settings import settings
from octoprint.plugin import plugin_manager
class VirtualPrinter():
class VirtualPrinter(object):
command_regex = re.compile("[GM]\d+")
sleep_regex = re.compile("sleep (\d+)")
sleep_after_regex = re.compile("sleep_after ([GM]\d+) (\d+)")
@@ -25,17 +25,19 @@ class VirtualPrinter():
def __init__(self, read_timeout=5.0, write_timeout=10.0):
import logging
self._logger = logging.getLogger("octoprint.plugin.virtual_printer.VirtualPrinter")
self._logger = logging.getLogger("octoprint.plugins.virtual_printer.VirtualPrinter")
self._read_timeout = read_timeout
self._write_timeout = write_timeout
self.incoming = CharCountingQueue(settings().getInt(["devel", "virtualPrinter", "rxBuffer"]), name="RxBuffer")
self._rx_buffer_size = settings().getInt(["devel", "virtualPrinter", "rxBuffer"])
self.incoming = CharCountingQueue(self._rx_buffer_size, name="RxBuffer")
self.outgoing = Queue.Queue()
self.buffered = Queue.Queue(maxsize=settings().getInt(["devel", "virtualPrinter", "commandBuffer"]))
for item in ['start\n', 'Marlin: Virtual Marlin!\n', '\x80\n', 'SD card ok\n']:
self.outgoing.put(item)
self._output(item)
self.currentExtruder = 0
self.temp = [0.0] * settings().getInt(["devel", "virtualPrinter", "numExtruders"])
@@ -61,19 +63,27 @@ class VirtualPrinter():
self._selectedSdFileSize = None
self._selectedSdFilePos = None
self._writingToSd = False
self._writingToSdHandle = None
self._newSdFilePos = None
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"])
self._echoOnM117 = settings().getBoolean(["devel", "virtualPrinter", "echoOnM117"])
self._brokenM29 = settings().getBoolean(["devel", "virtualPrinter", "brokenM29"])
self.currentLine = 0
self.lastN = 0
self._incoming_lock = threading.RLock()
self._debug_awol = False
self._debug_sleep = None
self._sleepAfterNext = dict()
self._sleepAfter = dict()
@@ -83,20 +93,43 @@ class VirtualPrinter():
self._action_hooks = plugin_manager().get_hooks("octoprint.plugin.virtual_printer.custom_action")
self._killed = False
waitThread = threading.Thread(target=self._sendWaitAfterTimeout)
self._triggerResendAt100 = True
self._triggerResendWithTimeoutAt105 = True
self._triggeredResendWithTimeoutAt105 = False
waitThread = threading.Thread(target=self._sendWaitAfterTimeout, name="octoprint.plugins.virtual_printer.wait_thread")
waitThread.start()
readThread = threading.Thread(target=self._processIncoming)
readThread = threading.Thread(target=self._processIncoming, name="octoprint.plugins.virtual_printer.read_thread")
readThread.start()
bufferThread = threading.Thread(target=self._processBuffer)
bufferThread = threading.Thread(target=self._processBuffer, name="octoprint.plugins.virtual_printer.buffer_thread")
bufferThread.start()
def __str__(self):
return "VIRTUAL(read_timeout={read_timeout},write_timeout={write_timeout},options={options})"\
.format(read_timeout=self._read_timeout, write_timeout=self._write_timeout, options=settings().get(["devel", "virtualPrinter"]))
@property
def timeout(self):
return self._read_timeout
@timeout.setter
def timeout(self, value):
self._logger.debug("Setting read timeout to {}s".format(value))
self._read_timeout = value
@property
def write_timeout(self):
return self._write_timeout
@write_timeout.setter
def write_timeout(self, value):
self._logger.debug("Setting write timeout to {}s".format(value))
self._write_timeout = value
def _clearQueue(self, queue):
try:
while queue.get(block=False):
@@ -106,17 +139,26 @@ class VirtualPrinter():
def _processIncoming(self):
next_wait_timeout = time.time() + self._waitInterval
while self.incoming is not None:
buf = ""
while self.incoming is not None and not self._killed:
self._simulateTemps()
try:
data = self.incoming.get(timeout=0.01)
self.incoming.task_done()
except Queue.Empty:
if self._sendWait and time.time() > next_wait_timeout:
self.outgoing.put("wait")
self._output("wait")
next_wait_timeout = time.time() + self._waitInterval
continue
buf += data
if "\n" in buf:
data = buf[:buf.find("\n") + 1]
buf = buf[buf.find("\n") + 1:]
else:
continue
next_wait_timeout = time.time() + self._waitInterval
if data is None:
@@ -130,10 +172,15 @@ class VirtualPrinter():
# strip checksum
if "*" in data:
checksum = int(data[data.rfind("*") + 1:])
data = data[:data.rfind("*")]
if not checksum == self._calculate_checksum(data):
self._triggerResend(expected=self.currentLine + 1)
continue
self.currentLine += 1
elif settings().getBoolean(["devel", "virtualPrinter", "forceChecksum"]):
self.outgoing.put("Error: Missing checksum")
self._output("Error: Missing checksum")
continue
# track N = N + 1
@@ -141,6 +188,10 @@ class VirtualPrinter():
linenumber = int(re.search("N([0-9]+)", data).group(1))
self.lastN = linenumber
self.currentLine = linenumber
self._triggerResendAt100 = True
self._triggerResendWithTimeoutAt105 = True
self._sendOk()
continue
elif data.startswith("N"):
@@ -149,10 +200,18 @@ class VirtualPrinter():
if linenumber != expected:
self._triggerResend(actual=linenumber)
continue
elif self.currentLine == 101:
elif linenumber == 100 and self._triggerResendAt100:
# simulate a resend at line 100
self._triggerResendAt100 = False
self._triggerResend(expected=100)
continue
elif linenumber == 105 and self._triggerResendWithTimeoutAt105 and not self._writingToSd:
# simulate a resend with timeout at line 105
self._triggerResendWithTimeoutAt105 = False
self._triggerResend(expected=105)
self._dont_answer = True
self.lastN = linenumber
continue
else:
self.lastN = linenumber
data = data.split(None, 1)[1].strip()
@@ -160,15 +219,14 @@ class VirtualPrinter():
data += "\n"
# shortcut for writing to SD
if self._writingToSd and not self._selectedSdFile is None and not "M29" in data:
with open(self._selectedSdFile, "a") as f:
f.write(data)
if self._writingToSdHandle is not None and not "M29" in data:
self._writingToSdHandle.write(data)
self._sendOk()
continue
if data.strip() == "version":
from octoprint._version import get_versions
self.outgoing.put("OctoPrint VirtualPrinter v" + get_versions()["version"])
self._output("OctoPrint VirtualPrinter v" + get_versions()["version"])
continue
elif data.startswith("!!DEBUG:"):
self._debugTrigger(data[len("!!DEBUG:"):].strip())
@@ -192,7 +250,7 @@ class VirtualPrinter():
self._listSd()
elif 'M21' in data:
self._sdCardReady = True
self.outgoing.put("SD card ok")
self._output("SD card ok")
elif 'M22' in data:
self._sdCardReady = False
elif 'M23' in data:
@@ -219,26 +277,29 @@ class VirtualPrinter():
elif 'M29' in data:
if self._sdCardReady:
self._finishSdFile()
if self._brokenM29:
continue
elif 'M30' in data:
if self._sdCardReady:
filename = data.split(None, 1)[1].strip()
self._deleteSdFile(filename)
elif "M114" in data:
# send dummy position report
output = "C: X:10.00 Y:3.20 Z:5.20 E:1.24"
output = "X:10.00 Y:3.20 Z:5.20 E:1.24 Count: A:1000 B:320 C:1040"
if not self._okBeforeCommandOutput:
output = "ok " + output
self.outgoing.put(output)
self._output(output)
continue
elif "M117" in data:
# we'll just use this to echo a message, to allow playing around with pause triggers
self.outgoing.put("echo:%s" % re.search("M117\s+(.*)", data).group(1))
if self._echoOnM117:
self._output("echo:%s" % re.search("M117\s+(.*)", data).group(1))
elif "M999" in data:
# mirror Marlin behaviour
self.outgoing.put("Resend: 1")
self._output("Resend: 1")
elif data.startswith("T"):
self.currentExtruder = int(re.search("T(\d+)", data).group(1))
self.outgoing.put("Active Extruder: %d" % self.currentExtruder)
self._output("Active Extruder: %d" % self.currentExtruder)
elif "G20" in data:
self._unitModifier = 1.0 / 2.54
if self._lastX is not None:
@@ -266,9 +327,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)
@@ -285,12 +347,26 @@ class VirtualPrinter():
del self._sleepAfterNext[command]
if interval is not None:
self.outgoing.put("// sleeping for {interval} seconds".format(interval=interval))
self._output("// sleeping for {interval} seconds".format(interval=interval))
time.sleep(interval)
if len(data.strip()) > 0 and not self._okBeforeCommandOutput:
self._sendOk()
self._logger.info("Closing down read loop")
def _calculate_checksum(self, line):
checksum = 0
for c in line:
checksum ^= ord(c)
return checksum
def _kill(self):
if not self._supportM112:
return
self._killed = True
self._output("echo:EMERGENCY SHUTDOWN DETECTED. KILLED.")
def _triggerResend(self, expected=None, actual=None):
with self._incoming_lock:
if expected is None:
@@ -299,20 +375,25 @@ class VirtualPrinter():
self.lastN = expected - 1
if actual is None:
self.outgoing.put("Error: Wrong checksum")
self._output("Error: Wrong checksum")
else:
self.outgoing.put("Error: expected line %d got %d" % (expected, actual))
self._output("Error: expected line %d got %d" % (expected, actual))
self.outgoing.put("Resend:%d" % expected)
self.outgoing.put("ok")
def request_resend():
self._output("Resend:%d" % expected)
self._output("ok")
if settings().getBoolean(["devel", "virtualPrinter", "repetierStyleResends"]):
request_resend()
request_resend()
def _debugTrigger(self, data):
if data == "action_pause":
self.outgoing.put("// action:pause")
self._output("// action:pause")
elif data == "action_resume":
self.outgoing.put("// action:resume")
self._output("// action:resume")
elif data == "action_disconnect":
self.outgoing.put("// action:disconnect")
self._output("// action:disconnect")
elif data == "dont_answer":
self._dont_answer = True
elif data == "trigger_resend_lineno":
@@ -321,6 +402,11 @@ class VirtualPrinter():
self._triggerResend(expected=self.lastN)
elif data == "drop_connection":
self._debug_drop_connection = True
elif data == "maxtemp_error":
self._output("Error: MAXTEMP triggered!")
elif data == "go_awol":
self._output("// Going AWOL")
self._debug_awol = True
else:
try:
sleep_match = VirtualPrinter.sleep_regex.match(data)
@@ -330,28 +416,28 @@ class VirtualPrinter():
if sleep_match is not None:
interval = int(sleep_match.group(1))
self.outgoing.put("// sleeping for {interval} seconds".format(interval=interval))
time.sleep(interval)
self._output("// sleeping for {interval} seconds".format(interval=interval))
self._debug_sleep = interval
elif sleep_after_match is not None:
command = sleep_after_match.group(1)
interval = int(sleep_after_match.group(2))
self._sleepAfter[command] = interval
self.outgoing.put("// going to sleep {interval} seconds after each {command}".format(**locals()))
self._output("// going to sleep {interval} seconds after each {command}".format(**locals()))
elif sleep_after_next_match is not None:
command = sleep_after_next_match.group(1)
interval = int(sleep_after_next_match.group(2))
self._sleepAfterNext[command] = interval
self.outgoing.put("// going to sleep {interval} seconds after next {command}".format(**locals()))
self._output("// going to sleep {interval} seconds after next {command}".format(**locals()))
elif custom_action_match is not None:
action = custom_action_match.group(1)
params = custom_action_match.group(2)
params = params.strip() if params is not None else ""
self.outgoing.put("// action:{action} {params}".format(**locals()).strip())
self._output("// action:{action} {params}".format(**locals()).strip())
except:
pass
def _listSd(self):
self.outgoing.put("Begin file list")
self._output("Begin file list")
if settings().getBoolean(["devel", "virtualPrinter", "extendedSdFileList"]):
items = map(
lambda x: "%s %d" % (x.upper(), os.stat(os.path.join(self._virtualSd, x)).st_size),
@@ -363,20 +449,23 @@ class VirtualPrinter():
os.listdir(self._virtualSd)
)
for item in items:
self.outgoing.put(item)
self.outgoing.put("End file list")
self._output(item)
self._output("End file list")
def _selectSdFile(self, filename):
if filename.startswith("/"):
filename = filename[1:]
file = os.path.join(self._virtualSd, filename.lower())
if not os.path.exists(file) or not os.path.isfile(file):
self.outgoing.put("open failed, File: %s." % filename)
self._output("open failed, File: %s." % filename)
else:
self._selectedSdFile = file
self._selectedSdFileSize = os.stat(file).st_size
self.outgoing.put("File opened: %s Size: %d" % (filename, self._selectedSdFileSize))
self.outgoing.put("File selected")
if settings().getBoolean(["devel", "virtualPrinter", "includeFilenameInOpened"]):
self._output("File opened: %s Size: %d" % (filename, self._selectedSdFileSize))
else:
self._output("File opened")
self._output("File selected")
def _startSdPrint(self):
if self._selectedSdFile is not None:
@@ -393,9 +482,9 @@ class VirtualPrinter():
def _reportSdStatus(self):
if self._sdPrinter is not None and self._sdPrintingSemaphore.is_set:
self.outgoing.put("SD printing byte %d/%d" % (self._selectedSdFilePos, self._selectedSdFileSize))
self._output("SD printing byte %d/%d" % (self._selectedSdFilePos, self._selectedSdFileSize))
else:
self.outgoing.put("Not SD printing")
self._output("Not SD printing")
def _processTemperatureQuery(self):
includeTarget = not settings().getBoolean(["devel", "virtualPrinter", "repetierStyleTargetTemperature"])
@@ -432,7 +521,7 @@ class VirtualPrinter():
if includeOk:
output = "ok " + output
self.outgoing.put(output)
self._output(output)
def _parseHotendCommand(self, line):
tool = 0
@@ -454,7 +543,7 @@ class VirtualPrinter():
if "M109" in line:
self._waitForHeatup("tool%d" % tool)
if settings().getBoolean(["devel", "virtualPrinter", "repetierStyleTargetTemperature"]):
self.outgoing.put("TargetExtr%d:%d" % (tool, self.targetTemp[tool]))
self._output("TargetExtr%d:%d" % (tool, self.targetTemp[tool]))
def _parseBedCommand(self, line):
try:
@@ -465,7 +554,7 @@ class VirtualPrinter():
if "M190" in line:
self._waitForHeatup("bed")
if settings().getBoolean(["devel", "virtualPrinter", "repetierStyleTargetTemperature"]):
self.outgoing.put("TargetBed:%d" % self.bedTargetTemp)
self._output("TargetBed:%d" % self.bedTargetTemp)
def _performMove(self, line):
matchX = re.search("X([0-9.]+)", line)
@@ -516,11 +605,10 @@ class VirtualPrinter():
pass
if duration:
if settings().getBoolean(["devel", "virtualPrinter", "waitOnLongMoves"]):
if duration > self._read_timeout:
slept = 0
while duration - slept > self._read_timeout:
while duration - slept > self._read_timeout and not self._killed:
time.sleep(self._read_timeout)
self.outgoing.put("wait")
slept += self._read_timeout
else:
time.sleep(duration)
@@ -563,58 +651,91 @@ class VirtualPrinter():
if os.path.isfile(file):
os.remove(file)
else:
self.outgoing.put("error writing to file")
self._output("error writing to file")
handle = None
try:
handle = open(file, "w")
except:
self._output("error writing to file")
if handle is not None:
try:
handle.close()
except:
pass
self._writingToSdHandle = handle
self._writingToSd = True
self._selectedSdFile = file
self.outgoing.put("Writing to file: %s" % filename)
self._output("Writing to file: %s" % filename)
def _finishSdFile(self):
try:
self._writingToSdHandle.close()
except:
pass
finally:
self._writingToSdHandle = None
self._writingToSd = False
self._selectedSdFile = None
self._output("Done saving file")
def _sdPrintingWorker(self):
self._selectedSdFilePos = 0
with open(self._selectedSdFile, "r") as f:
for line in iter(f.readline, ""):
# reset position if requested by client
if self._newSdFilePos is not None:
f.seek(self._newSdFilePos)
self._newSdFilePos = None
try:
with open(self._selectedSdFile, "r") as f:
for line in iter(f.readline, ""):
if self._killed:
break
# read current file position
self._selectedSdFilePos = f.tell()
# reset position if requested by client
if self._newSdFilePos is not None:
f.seek(self._newSdFilePos)
self._newSdFilePos = None
# if we are paused, wait for unpausing
self._sdPrintingSemaphore.wait()
# read current file position
self._selectedSdFilePos = f.tell()
# set target temps
if 'M104' in line or 'M109' in line:
self._parseHotendCommand(line)
if 'M140' in line or 'M190' in line:
self._parseBedCommand(line)
# if we are paused, wait for unpausing
self._sdPrintingSemaphore.wait()
time.sleep(settings().getFloat(["devel", "virtualPrinter", "throttle"]))
# set target temps
if 'M104' in line or 'M109' in line:
self._parseHotendCommand(line)
elif 'M140' in line or 'M190' in line:
self._parseBedCommand(line)
elif line.startswith("G0") or line.startswith("G1") or line.startswith("G2") or line.startswith("G3"):
# simulate reprap buffered commands via a Queue with maxsize which internally simulates the moves
self.buffered.put(line)
self._sdPrintingSemaphore.clear()
self._selectedSdFilePos = 0
self._sdPrinter = None
self.outgoing.put("Done printing file")
except AttributeError:
if self.outgoing is not None:
raise
if not self._killed:
self._sdPrintingSemaphore.clear()
self._selectedSdFilePos = 0
self._sdPrinter = None
self._output("Done printing file")
def _waitForHeatup(self, heater):
delta = 1
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:
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:
self._simulateTemps(delta=delta)
self.outgoing.put("B:%0.2f" % self.bedTemp)
time.sleep(delay)
try:
if heater.startswith("tool"):
toolNum = int(heater[len("tool"):])
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._output("T:%0.2f" % self.temp[toolNum])
time.sleep(delay)
elif heater == "bed":
while not self._killed and (self.bedTemp < self.bedTargetTemp - delta or self.bedTemp > self.bedTargetTemp + delta):
self._simulateTemps(delta=delta)
self._output("B:%0.2f" % self.bedTemp)
time.sleep(delay)
except AttributeError:
if self.outgoing is not None:
raise
def _deleteSdFile(self, filename):
if filename.startswith("/"):
@@ -653,47 +774,94 @@ class VirtualPrinter():
continue
self._performMove(line)
self.buffered.task_done()
self._logger.info("Closing down buffer loop")
def _output(self, line):
try:
self.outgoing.put(line)
except:
if self.outgoing is None:
pass
def write(self, data):
if self._debug_awol:
return len(data)
if self._debug_drop_connection:
self._logger.info("Debug drop of connection requested, raising SerialTimeoutException")
raise SerialTimeoutException()
with self._incoming_lock:
if self.incoming is None or self.outgoing is None:
return
return 0
if "M112" in data and self._supportM112:
self._kill()
return len(data)
try:
self.incoming.put(data, timeout=self._write_timeout)
return self.incoming.put(data, timeout=self._write_timeout, partial=True)
except Queue.Full:
self._logger.info("Incoming queue is full, raising SerialTimeoutException")
raise SerialTimeoutException()
def readline(self):
if self._debug_awol:
time.sleep(self._read_timeout)
return ""
if self._debug_drop_connection:
raise SerialTimeoutException()
if self._debug_sleep > 0:
# if we are supposed to sleep, we sleep not longer than the read timeout
# (and then on the next call sleep again if there's time to sleep left)
sleep_for = min(self._debug_sleep, self._read_timeout)
self._debug_sleep -= sleep_for
time.sleep(sleep_for)
if self._debug_sleep > 0:
# we slept the full read timeout, return an empty line
return ""
# otherwise our left over timeout is the read timeout minus what we already
# slept for
timeout = self._read_timeout - sleep_for
else:
# use the full read timeout as timeout
timeout = self._read_timeout
try:
line = self.outgoing.get(timeout=self._read_timeout)
time.sleep(settings().getFloat(["devel", "virtualPrinter", "throttle"]))
# fetch a line from the queue, wait no longer than timeout
line = self.outgoing.get(timeout=timeout)
self.outgoing.task_done()
return line
except Queue.Empty:
# queue empty? return empty line
return ""
def close(self):
self._killed = True
self.incoming = None
self.outgoing = None
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)
self._output("ok %d" % self.lastN)
else:
self.outgoing.put("ok")
self._output("ok")
def _sendWaitAfterTimeout(self, timeout=5):
time.sleep(timeout)
if self.outgoing is not None:
self.outgoing.put("wait")
self._output("wait")
class CharCountingQueue(Queue.Queue):
@@ -702,22 +870,26 @@ class CharCountingQueue(Queue.Queue):
self._size = 0
self._name = name
def put(self, item, block=True, timeout=None):
def put(self, item, block=True, timeout=None, partial=False):
self.not_full.acquire()
try:
item_size = self._len(item)
if not self._will_it_fit(item) and partial:
space_left = self.maxsize - self._qsize()
if space_left:
item = item[:space_left]
if not block:
if self._qsize() + item_size >= self.maxsize:
if not self._will_it_fit(item):
raise Queue.Full
elif timeout is None:
while self._qsize() + item_size >= self.maxsize:
while not self._will_it_fit(item):
self.not_full.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a positive number")
else:
endtime = time.time() + timeout
while self._qsize() + item_size >= self.maxsize:
while not self._will_it_fit(item):
remaining = endtime - time.time()
if remaining <= 0.0:
raise Queue.Full
@@ -726,6 +898,8 @@ class CharCountingQueue(Queue.Queue):
self._put(item)
self.unfinished_tasks += 1
self.not_empty.notify()
return self._len(item)
finally:
self.not_full.release()
@@ -745,3 +919,6 @@ class CharCountingQueue(Queue.Queue):
item = self.queue.popleft()
self._size -= self._len(item)
return item
def _will_it_fit(self, item):
return self.maxsize - self._qsize() >= self._len(item)
+17 -2
View File
@@ -214,7 +214,7 @@ class PrinterInterface(object):
"""
raise NotImplementedError()
def select_file(self, path, sd, printAfterSelect=False):
def select_file(self, path, sd, printAfterSelect=False, pos=None):
"""
Selects the specified ``path`` for printing, specifying if the file is to be found on the ``sd`` or not.
Optionally can also directly start the print after selecting the file.
@@ -236,11 +236,26 @@ class PrinterInterface(object):
"""
raise NotImplementedError()
def pause_print(self):
"""
Pauses the current print job if it is currently running, does nothing otherwise.
"""
raise NotImplementedError()
def resume_print(self):
"""
Resumes the current print job if it is currently paused, does nothing otherwise.
"""
raise NotImplementedError()
def toggle_pause_print(self):
"""
Pauses the current print job if it is currently running or resumes it if it is currently paused.
"""
raise NotImplementedError()
if self.is_printing():
self.pause_print()
elif self.is_paused():
self.resume_print()
def cancel_print(self):
"""
+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", max_permissions=0o666) 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
+273 -74
View File
@@ -17,13 +17,14 @@ import time
from octoprint import util as util
from octoprint.events import eventManager, Events
from octoprint.filemanager import FileDestinations
from octoprint.filemanager import FileDestinations, NoSuchStorage
from octoprint.plugin import plugin_manager, ProgressPlugin
from octoprint.printer import PrinterInterface, PrinterCallback, UnknownScript
from octoprint.printer.estimation import TimeEstimationHelper
from octoprint.settings import settings
from octoprint.util import comm as comm
from octoprint.util import InvariantContainer
from octoprint.util import to_unicode
class Printer(PrinterInterface, comm.MachineComPrintCallback):
@@ -50,11 +51,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._temps = TemperatureHistory(cutoff=settings().getInt(["temperature", "cutoff"])*60)
self._tempBacklog = []
self._latestMessage = None
self._messages = deque([], 300)
self._messageBacklog = []
self._latestLog = None
self._log = deque([], 300)
self._logBacklog = []
@@ -62,11 +61,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._currentZ = None
self._progress = None
self._printTime = None
self._printTimeLeft = None
self._printAfterSelect = False
self._posAfterSelect = None
# sd handling
self._sdPrinting = False
@@ -76,6 +72,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._selectedFile = None
self._timeEstimationData = None
self._timeEstimationStatsWeighingUntil = settings().getFloat(["estimation", "printTime", "statsWeighingUntil"])
self._timeEstimationValidityRange = settings().getFloat(["estimation", "printTime", "validityRange"])
self._timeEstimationForceDumbFromPercent = settings().getFloat(["estimation", "printTime", "forceDumbFromPercent"])
self._timeEstimationForceDumbAfterMin = settings().getFloat(["estimation", "printTime", "forceDumbAfterMin"])
# comm
self._comm = None
@@ -92,7 +92,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
on_update=self._sendCurrentDataCallbacks,
on_add_temperature=self._sendAddTemperatureCallbacks,
on_add_log=self._sendAddLogCallbacks,
on_add_message=self._sendAddMessageCallbacks
on_add_message=self._sendAddMessageCallbacks,
on_get_progress=self._updateProgressDataCallback
)
self._stateMonitor.reset(
state={"text": self.get_state_string(), "flags": self._getStateFlags()},
@@ -193,6 +194,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if self._comm is not None:
self._comm.close()
self._printerProfileManager.select(profile)
from octoprint.logging.handlers import SerialLogHandler
SerialLogHandler.on_open_connection()
self._comm = comm.MachineCom(port, baudrate, callbackObject=self, printerProfileManager=self._printerProfileManager)
def disconnect(self):
@@ -345,14 +350,25 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
factor = self._convert_rate_value(factor, min=75, max=125)
self.commands("M221 S%d" % factor)
def select_file(self, path, sd, printAfterSelect=False):
def select_file(self, path, sd, printAfterSelect=False, pos=None):
if self._comm is None or (self._comm.isBusy() or self._comm.isStreaming()):
self._logger.info("Cannot load file: printer not connected or currently busy")
return
recovery_data = self._fileManager.get_recovery_data()
if recovery_data:
# clean up recovery data if we just selected a different file than is logged in that
expected_origin = FileDestinations.SDCARD if sd else FileDestinations.LOCAL
actual_origin = recovery_data.get("origin", None)
actual_path = recovery_data.get("path", None)
if actual_origin is None or actual_path is None or actual_origin != expected_origin or actual_path != path:
self._fileManager.delete_recovery_data()
self._printAfterSelect = printAfterSelect
self._comm.selectFile("/" + path if sd else path, sd)
self._setProgressData(0, None, None, None)
self._posAfterSelect = pos
self._comm.selectFile("/" + path if sd and not settings().getBoolean(["feature", "sdRelativePath"]) else path, sd)
self._setProgressData(completion=0)
self._setCurrentZ(None)
def unselect_file(self):
@@ -360,10 +376,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
return
self._comm.unselectFile()
self._setProgressData(0, None, None, None)
self._setProgressData(completion=0)
self._setCurrentZ(None)
def start_print(self):
def start_print(self, pos=None):
"""
Starts the currently loaded print job.
Only starts if the printer is connected and operational, not currently printing and a printjob is loaded
@@ -373,33 +389,52 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if self._selectedFile is None:
return
# we are happy if the average of the estimates stays within 60s of the prior one
threshold = settings().getFloat(["estimation", "printTime", "stableThreshold"])
rolling_window = None
threshold = None
countdown = None
if self._selectedFile["sd"]:
# we are interesting in a rolling window of roughly the last 15s, so the number of entries has to be derived
# by that divided by the sd status polling interval
rolling_window = 15 / settings().get(["serial", "timeout", "sdStatus"])
# we are happy if the average of the estimates stays within 60s of the prior one
threshold = 60
# we are happy when one rolling window has been stable
countdown = rolling_window
self._timeEstimationData = TimeEstimationHelper(rolling_window=rolling_window, threshold=threshold, countdown=countdown)
self._timeEstimationData = TimeEstimationHelper(rolling_window=rolling_window,
threshold=threshold,
countdown=countdown)
self._fileManager.delete_recovery_data()
self._lastProgressReport = None
self._setProgressData(completion=0)
self._setCurrentZ(None)
self._comm.startPrint()
self._comm.startPrint(pos=pos)
def toggle_pause_print(self):
def pause_print(self):
"""
Pause the current printjob.
Pause the current printjob.
"""
if self._comm is None:
return
self._comm.setPause(not self._comm.isPaused())
if self._comm.isPaused():
return
self._comm.setPause(True)
def resume_print(self):
"""
Resume the current printjob.
"""
if self._comm is None:
return
if not self._comm.isPaused():
return
self._comm.setPause(False)
def cancel_print(self):
"""
@@ -412,7 +447,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
# reset progress, height, print time
self._setCurrentZ(None)
self._setProgressData(None, None, None, None)
self._setProgressData()
# mark print as failure
if self._selectedFile is not None:
@@ -516,7 +551,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self.refresh_sd_files(blocking=True)
existingSdFiles = map(lambda x: x[0], self._comm.getSdFiles())
remoteName = util.get_dos_filename(filename, existing_filenames=existingSdFiles, extension="gco")
remoteName = util.get_dos_filename(filename,
existing_filenames=existingSdFiles,
extension="gco",
whitelisted_extensions=["gco", "g"])
self._timeEstimationData = TimeEstimationHelper()
self._comm.startFileTransfer(absolutePath, filename, "/" + remoteName)
@@ -556,9 +594,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._currentZ = currentZ
self._stateMonitor.set_current_z(self._currentZ)
def _setState(self, state):
def _setState(self, state, state_string=None):
if state_string is None:
state_string = self.get_state_string()
self._state = state
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
self._stateMonitor.set_state({"text": state_string, "flags": self._getStateFlags()})
def _addLog(self, log):
self._log.append(log)
@@ -582,39 +623,160 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
return result
def _setProgressData(self, progress, filepos, printTime, cleanedPrintTime):
estimatedTotalPrintTime = self._estimateTotalPrintTime(progress, cleanedPrintTime)
totalPrintTime = estimatedTotalPrintTime
def _setProgressData(self, completion=None, filepos=None, printTime=None, printTimeLeft=None):
self._stateMonitor.set_progress(dict(completion=int(completion * 100) if completion is not None else None,
filepos=filepos,
printTime=int(printTime) if printTime is not None else None,
printTimeLeft=int(printTimeLeft) if printTimeLeft is not None else None))
if self._selectedFile and "estimatedPrintTime" in self._selectedFile and self._selectedFile["estimatedPrintTime"]:
def _updateProgressDataCallback(self):
if self._comm is None:
progress = None
filepos = None
printTime = None
cleanedPrintTime = None
else:
progress = self._comm.getPrintProgress()
filepos = self._comm.getPrintFilepos()
printTime = self._comm.getPrintTime()
cleanedPrintTime = self._comm.getCleanedPrintTime()
statisticalTotalPrintTime = None
statisticalTotalPrintTimeType = None
if self._selectedFile and "estimatedPrintTime" in self._selectedFile \
and self._selectedFile["estimatedPrintTime"]:
statisticalTotalPrintTime = self._selectedFile["estimatedPrintTime"]
if progress and cleanedPrintTime:
if estimatedTotalPrintTime is None:
totalPrintTime = statisticalTotalPrintTime
else:
if progress < 0.5:
sub_progress = progress * 2
else:
sub_progress = 1.0
totalPrintTime = (1 - sub_progress) * statisticalTotalPrintTime + sub_progress * estimatedTotalPrintTime
statisticalTotalPrintTimeType = self._selectedFile.get("estimatedPrintTimeType", None)
self._progress = progress
self._printTime = printTime
self._printTimeLeft = totalPrintTime - cleanedPrintTime if (totalPrintTime is not None and cleanedPrintTime is not None) else None
printTimeLeft, printTimeLeftOrigin = self._estimatePrintTimeLeft(progress, printTime, cleanedPrintTime, statisticalTotalPrintTime, statisticalTotalPrintTimeType)
self._stateMonitor.set_progress({
"completion": self._progress * 100 if self._progress is not None else None,
"filepos": filepos,
"printTime": int(self._printTime) if self._printTime is not None else None,
"printTimeLeft": int(self._printTimeLeft) if self._printTimeLeft is not None else None
})
if progress:
if progress is not None:
progress_int = int(progress * 100)
if self._lastProgressReport != progress_int:
self._lastProgressReport = progress_int
self._reportPrintProgressToPlugins(progress_int)
return dict(completion=progress * 100 if progress is not None else None,
filepos=filepos,
printTime=int(printTime) if printTime is not None else None,
printTimeLeft=int(printTimeLeft) if printTimeLeft is not None else None,
printTimeLeftOrigin=printTimeLeftOrigin)
def _estimatePrintTimeLeft(self, progress, printTime, cleanedPrintTime, statisticalTotalPrintTime, statisticalTotalPrintTimeType):
"""
Tries to estimate the print time left for the print job
This is somewhat horrible since accurate print time estimation is pretty much impossible to
achieve, considering that we basically have only two data points (current progress in file and
time needed for that so far - former prints or a file analysis might not have happened or simply
be completely impossible e.g. if the file is stored on the printer's SD card) and
hence can only do a linear estimation of a completely non-linear process. That's a recipe
for inaccurate predictions right there. Yay.
Anyhow, here's how this implementation works. This method gets the current progress in the
printed file (percentage based on bytes read vs total bytes), the print time that elapsed,
the same print time with the heat up times subtracted (if possible) and if available also
some statistical total print time (former prints or a result from the GCODE analysis).
1. First get an "intelligent" estimate based on the :class:`~octoprint.printer.estimation.TimeEstimationHelper`.
That thing tries to detect if the estimation based on our progress and time needed for that becomes
stable over time through a rolling window and only returns a result once that appears to be the
case.
2. If we have any statistical data (former prints or a result from the GCODE analysis)
but no intelligent estimate yet, we'll use that for the next step. Otherwise, up to a certain percentage
in the print we do a percentage based weighing of the statistical data and the intelligent
estimate - the closer to the beginning of the print, the more precedence for the statistical
data, the closer to the cut off point, the more precendence for the intelligent estimate. This
is our preliminary total print time.
3. If the total print time is set, we do a sanity check for it. Based on the total print time
estimate and the time we already spent printing, we calculate at what percentage we SHOULD be
and compare that to the percentage at which we actually ARE. If it's too far off, our total
can't be trusted and we fall back on the dumb estimate. Same if the time we spent printing is
already higher than our total estimate.
4. If we do NOT have a total print time estimate yet but we've been printing for longer than
a configured amount of minutes or are further in the file than a configured percentage, we
also use the dumb estimate for now.
Yes, all this still produces horribly inaccurate results. But we have to do this live during the print and
hence can't produce to much computational overhead, we do not have any insight into the firmware implementation
with regards to planner setup and acceleration settings, we might not even have access to the printed file's
contents and such we need to find something that works "mostly" all of the time without costing too many
resources. Feel free to propose a better solution within the above limitations (and I mean that, this solution
here makes me unhappy).
Args:
progress (float or None): Current percentage in the printed file
printTime (float or None): Print time elapsed so far
cleanedPrintTime (float or None): Print time elapsed minus the time needed for getting up to temperature
(if detectable).
statisticalTotalPrintTime (float or None): Total print time of past prints against same printer profile,
or estimated total print time from GCODE analysis.
statisticalTotalPrintTimeType (str or None): Type of statistical print time, either "average" (total time
of former prints) or "analysis"
Returns:
(2-tuple) estimated print time left or None if not proper estimate could be made at all, origin of estimation
"""
if progress is None or printTime is None or cleanedPrintTime is None:
return None
dumbTotalPrintTime = printTime / progress
estimatedTotalPrintTime = self._estimateTotalPrintTime(progress, cleanedPrintTime)
totalPrintTime = estimatedTotalPrintTime
printTimeLeftOrigin = "estimate"
if statisticalTotalPrintTime is not None:
if estimatedTotalPrintTime is None:
# no estimate yet, we'll use the statistical total
totalPrintTime = statisticalTotalPrintTime
printTimeLeftOrigin = statisticalTotalPrintTimeType
else:
if progress < self._timeEstimationStatsWeighingUntil:
# still inside weighing range, use part stats, part current estimate
sub_progress = progress * (1 / self._timeEstimationStatsWeighingUntil)
if sub_progress > 1.0:
sub_progress = 1.0
printTimeLeftOrigin = "mixed-" + statisticalTotalPrintTimeType
else:
# use only the current estimate
sub_progress = 1.0
printTimeLeftOrigin = "estimate"
# combine
totalPrintTime = (1.0 - sub_progress) * statisticalTotalPrintTime \
+ sub_progress * estimatedTotalPrintTime
printTimeLeft = None
if totalPrintTime is not None:
# sanity check current total print time estimate
assumed_progress = cleanedPrintTime / totalPrintTime
min_progress = progress - self._timeEstimationValidityRange
max_progress = progress + self._timeEstimationValidityRange
if min_progress <= assumed_progress <= max_progress and totalPrintTime > cleanedPrintTime:
# appears sane, we'll use it
printTimeLeft = totalPrintTime - cleanedPrintTime
else:
# too far from the actual progress or negative,
# we use the dumb print time instead
printTimeLeft = dumbTotalPrintTime - cleanedPrintTime
printTimeLeftOrigin = "linear"
else:
printTimeLeftOrigin = "linear"
if progress > self._timeEstimationForceDumbFromPercent or \
cleanedPrintTime >= self._timeEstimationForceDumbAfterMin * 60:
# more than x% or y min printed and still no real estimate, ok, we'll use the dumb variant :/
printTimeLeft = dumbTotalPrintTime - cleanedPrintTime
if printTimeLeft is not None and printTimeLeft < 0:
# shouldn't actually happen, but let's make sure
printTimeLeft = None
return printTimeLeft, printTimeLeftOrigin
def _addTemperatureData(self, temp, bedTemp):
currentTimeUtc = int(time.time())
@@ -644,6 +806,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 +843,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)
@@ -700,9 +864,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if averagePrintTime is not None:
self._selectedFile["estimatedPrintTime"] = averagePrintTime
self._selectedFile["estimatedPrintTimeType"] = "average"
elif estimatedPrintTime is not None:
# TODO apply factor which first needs to be tracked!
self._selectedFile["estimatedPrintTime"] = estimatedPrintTime
self._selectedFile["estimatedPrintTimeType"] = "analysis"
self._stateMonitor.set_job_data({
"file": {
@@ -726,10 +892,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
"messages": list(self._messages)
})
callback.on_printer_send_initial_data(data)
except Exception, err:
import sys
sys.stderr.write("ERROR: %s\n" % str(err))
pass
except:
self._logger.exception("Error while trying to send inital state update")
def _getStateFlags(self):
return {
@@ -748,7 +912,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
"""
Callback method for the comm object, called upon log output.
"""
self._addLog(message)
self._addLog(to_unicode(message, "utf-8", errors="replace"))
def on_comm_temperature_update(self, temp, bedTemp):
self._addTemperatureData(temp, bedTemp)
@@ -759,6 +923,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
"""
oldState = self._state
state_string = None
if self._comm is not None:
state_string = self._comm.getStateString()
# forward relevant state changes to gcode manager
if oldState == comm.MachineCom.STATE_PRINTING:
if self._selectedFile is not None:
@@ -767,22 +935,23 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._analysisQueue.resume() # printing done, put those cpu cycles to good use
elif state == comm.MachineCom.STATE_PRINTING:
self._analysisQueue.pause() # do not analyse files while printing
elif state == comm.MachineCom.STATE_CLOSED or state == comm.MachineCom.STATE_CLOSED_WITH_ERROR:
if state == comm.MachineCom.STATE_CLOSED or state == comm.MachineCom.STATE_CLOSED_WITH_ERROR:
if self._comm is not None:
self._comm = None
self._setProgressData(0, None, None, None)
self._setProgressData(completion=0)
self._setCurrentZ(None)
self._setJobData(None, None, None)
self._setState(state)
self._setState(state, state_string=state_string)
def on_comm_message(self, message):
"""
Callback method for the comm object, called upon message exchanges via serial.
Stores the message in the message buffer, truncates buffer to the last 300 lines.
"""
self._addMessage(message)
self._addMessage(to_unicode(message, "utf-8", errors="replace"))
def on_comm_progress(self):
"""
@@ -790,7 +959,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
Triggers storage of new values for printTime, printTimeLeft and the current progress.
"""
self._setProgressData(self._comm.getPrintProgress(), self._comm.getPrintFilepos(), self._comm.getPrintTime(), self._comm.getCleanedPrintTime())
self._stateMonitor.trigger_progress_update()
def on_comm_z_change(self, newZ):
"""
@@ -816,18 +985,20 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
if self._printAfterSelect:
self.start_print()
self._printAfterSelect = False
self.start_print(pos=self._posAfterSelect)
def on_comm_print_job_done(self):
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), True, self._printerProfileManager.get_current_or_default()["id"])
self._setProgressData(1.0, self._selectedFile["filesize"], self._comm.getPrintTime(), 0)
self._setProgressData(completion=1.0, filepos=self._selectedFile["filesize"], printTime=self._comm.getPrintTime(), printTimeLeft=0)
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
self._fileManager.delete_recovery_data()
def on_comm_file_transfer_started(self, filename, filesize):
self._sdStreaming = True
self._setJobData(filename, filesize, True)
self._setProgressData(0.0, 0, 0, None)
self._setProgressData(completion=0.0, filepos=0, printTime=0)
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
def on_comm_file_transfer_done(self, filename):
@@ -840,20 +1011,28 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._setCurrentZ(None)
self._setJobData(None, None, None)
self._setProgressData(None, None, None, None)
self._setProgressData()
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
def on_comm_force_disconnect(self):
self.disconnect()
def on_comm_record_fileposition(self, origin, name, pos):
try:
self._fileManager.save_recovery_data(origin, name, pos)
except NoSuchStorage:
pass
except:
self._logger.exception("Error while trying to persist print recovery data")
class StateMonitor(object):
def __init__(self, interval=0.5, on_update=None, on_add_temperature=None, on_add_log=None, on_add_message=None):
def __init__(self, interval=0.5, on_update=None, on_add_temperature=None, on_add_log=None, on_add_message=None, on_get_progress=None):
self._interval = interval
self._update_callback = on_update
self._on_add_temperature = on_add_temperature
self._on_add_log = on_add_log
self._on_add_message = on_add_message
self._on_get_progress = on_get_progress
self._state = None
self._job_data = None
@@ -862,16 +1041,24 @@ class StateMonitor(object):
self._current_z = None
self._progress = None
self._progress_dirty = False
self._offsets = {}
self._change_event = threading.Event()
self._state_lock = threading.Lock()
self._progress_lock = threading.Lock()
self._last_update = time.time()
self._worker = threading.Thread(target=self._work)
self._worker.daemon = True
self._worker.start()
def _get_current_progress(self):
if callable(self._on_get_progress):
return self._on_get_progress()
return self._progress
def reset(self, state=None, job_data=None, progress=None, current_z=None):
self.set_state(state)
self.set_job_data(job_data)
@@ -903,9 +1090,16 @@ class StateMonitor(object):
self._job_data = job_data
self._change_event.set()
def trigger_progress_update(self):
with self._progress_lock:
self._progress_dirty = True
self._change_event.set()
def set_progress(self, progress):
self._progress = progress
self._change_event.set()
with self._progress_lock:
self._progress_dirty = False
self._progress = progress
self._change_event.set()
def set_temp_offsets(self, offsets):
self._offsets = offsets
@@ -915,19 +1109,24 @@ class StateMonitor(object):
while True:
self._change_event.wait()
with self._state_lock:
now = time.time()
delta = now - self._last_update
additional_wait_time = self._interval - delta
if additional_wait_time > 0:
time.sleep(additional_wait_time)
now = time.time()
delta = now - self._last_update
additional_wait_time = self._interval - delta
if additional_wait_time > 0:
time.sleep(additional_wait_time)
with self._state_lock:
data = self.get_current_data()
self._update_callback(data)
self._last_update = time.time()
self._change_event.clear()
def get_current_data(self):
with self._progress_lock:
if self._progress_dirty:
self._progress = self._get_current_progress()
self._progress_dirty = False
return {
"state": self._state,
"job": self._job_data,
+487 -101
View File
@@ -7,13 +7,14 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import uuid
from sockjs.tornado import SockJSRouter
from flask import Flask, g, request, session, Blueprint
from flask import Flask, g, request, session, Blueprint, Request, Response
from flask.ext.login import LoginManager, current_user
from flask.ext.principal import Principal, Permission, RoleNeed, identity_loaded, UserNeed
from flask.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
@@ -21,9 +22,11 @@ import logging
import logging.config
import atexit
import signal
import base64
SUCCESS = {}
NO_CONTENT = ("", 204)
NOT_MODIFIED = ("Not Modified", 304)
app = Flask("octoprint")
assets = None
@@ -41,6 +44,7 @@ loginManager = None
pluginManager = None
appSessionManager = None
pluginLifecycleManager = None
preemptiveCache = None
principals = Principal(app)
admin_permission = Permission(RoleNeed("admin"))
@@ -60,6 +64,7 @@ import octoprint.util
import octoprint.filemanager.storage
import octoprint.filemanager.analysis
import octoprint.slicing
from octoprint.server.util.flask import PreemptiveCache
from . import util
@@ -67,8 +72,9 @@ UI_API_KEY = ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes)
versions = octoprint._version.get_versions()
VERSION = versions['version']
BRANCH = versions['branch'] if 'branch' in versions else None
BRANCH = versions.get('branch', None)
DISPLAY_VERSION = "%s (%s branch)" % (VERSION, BRANCH) if BRANCH else VERSION
REVISION = versions.get('full-revision-id', versions.get('full', None))
del versions
LOCALES = []
@@ -80,7 +86,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():
@@ -95,19 +101,19 @@ def load_user(id):
else:
sessionid = None
if userManager is not None:
if userManager.enabled:
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()
#~~ startup code
class Server():
def __init__(self, configfile=None, basedir=None, host="0.0.0.0", port=5000, debug=False, allowRoot=False, logConf=None):
class Server(object):
def __init__(self, configfile=None, basedir=None, host="0.0.0.0", port=5000, debug=False, allowRoot=False, logConf=None, octoprint_daemon=None):
self._configfile = configfile
self._basedir = basedir
self._host = host
@@ -116,6 +122,7 @@ class Server():
self._allowRoot = allowRoot
self._logConf = logConf
self._server = None
self._octoprint_daemon = octoprint_daemon
self._logger = None
@@ -123,6 +130,8 @@ class Server():
self._template_searchpaths = []
self._intermediary_server = None
def run(self):
if not self._allowRoot:
self._check_for_root()
@@ -141,6 +150,7 @@ class Server():
global pluginManager
global appSessionManager
global pluginLifecycleManager
global preemptiveCache
global debug
from tornado.ioloop import IOLoop
@@ -158,7 +168,7 @@ class Server():
util.flask.enable_additional_translations(additional_folders=[s.getBaseFolder("translations")])
# setup app
self._setup_app()
self._setup_app(app)
# setup i18n
self._setup_i18n(app)
@@ -171,6 +181,9 @@ class Server():
sys.excepthook = exception_logger
self._logger.info("Starting OctoPrint %s" % DISPLAY_VERSION)
# start the intermediary server
self._start_intermediary_server(s)
# then initialize the plugin manager
pluginManager = octoprint.plugin.plugin_manager(init=True)
@@ -184,10 +197,17 @@ class Server():
printer = Printer(fileManager, analysisQueue, printerProfileManager)
appSessionManager = util.flask.AppSessionManager()
pluginLifecycleManager = LifecycleManager(pluginManager)
preemptiveCache = PreemptiveCache(os.path.join(s.getBaseFolder("data"), "preemptive_cache_config.yaml"))
# ... and initialize all plugins
def octoprint_plugin_inject_factory(name, implementation):
"""Factory for injections for all OctoPrintPlugins"""
if not isinstance(implementation, octoprint.plugin.OctoPrintPlugin):
# we only care about OctoPrintPlugins
return None
return dict(
plugin_manager=pluginManager,
printer_profile_manager=printerProfileManager,
@@ -198,12 +218,18 @@ class Server():
printer=printer,
app_session_manager=appSessionManager,
plugin_lifecycle_manager=pluginLifecycleManager,
data_folder=os.path.join(settings().getBaseFolder("data"), name)
data_folder=os.path.join(settings().getBaseFolder("data"), name),
preemptive_cache=preemptiveCache
)
def settings_plugin_inject_factory(name, implementation):
"""Factory for additional injections depending on plugin type"""
if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
# we only care about SettingsPlugins
return None
# SettingsPlugin instnances get a PluginSettings instance injected
default_settings = implementation.get_settings_defaults()
get_preprocessors, set_preprocessors = implementation.get_settings_preprocessors()
plugin_settings = octoprint.plugin.plugin_settings(name,
@@ -212,7 +238,9 @@ 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):
"""Take care of migrating and cleaning up any old settings"""
if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
return
@@ -220,11 +248,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 +263,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()
@@ -249,6 +282,8 @@ class Server():
# setup jinja2
self._setup_jinja2()
# make sure plugin lifecycle events relevant for jinja2 are taken care of
def template_enabled(name, plugin):
if plugin.implementation is None or not isinstance(plugin.implementation, octoprint.plugin.TemplatePlugin):
return
@@ -264,7 +299,7 @@ class Server():
self._setup_assets()
# configure timelapse
octoprint.timelapse.configureTimelapse()
octoprint.timelapse.configure_timelapse()
# setup command triggers
events.CommandTrigger(printer)
@@ -272,53 +307,34 @@ class Server():
events.DebugEventListener()
# setup access control
if s.getBoolean(["accessControl", "enabled"]):
userManagerName = s.get(["accessControl", "userManager"])
try:
clazz = octoprint.util.get_class(userManagerName)
userManager = clazz()
except AttributeError, e:
self._logger.exception("Could not instantiate user manager %s, will run with accessControl disabled!" % userManagerName)
userManagerName = s.get(["accessControl", "userManager"])
try:
clazz = octoprint.util.get_class(userManagerName)
userManager = clazz()
except AttributeError as e:
self._logger.exception("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(userManagerName))
userManager = octoprint.users.FilebasedUserManager()
finally:
userManager.enabled = s.getBoolean(["accessControl", "enabled"])
app.wsgi_app = util.ReverseProxied(
app.wsgi_app,
s.get(["server", "reverseProxy", "prefixHeader"]),
s.get(["server", "reverseProxy", "schemeHeader"]),
s.get(["server", "reverseProxy", "hostHeader"]),
s.get(["server", "reverseProxy", "prefixFallback"]),
s.get(["server", "reverseProxy", "schemeFallback"]),
s.get(["server", "reverseProxy", "hostFallback"])
)
secret_key = s.get(["server", "secretKey"])
if not secret_key:
import string
from random import choice
chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
secret_key = "".join(choice(chars) for _ in xrange(32))
s.set(["server", "secretKey"], secret_key)
s.save()
app.secret_key = secret_key
loginManager = LoginManager()
loginManager.session_protection = "strong"
loginManager.user_callback = load_user
if userManager is None:
if not userManager.enabled:
loginManager.anonymous_user = users.DummyUser
principals.identity_loaders.appendleft(users.dummy_identity_loader)
loginManager.init_app(app)
if self._host is None:
self._host = s.get(["server", "host"])
if self._port is None:
self._port = s.getInt(["server", "port"])
app.debug = self._debug
# register API blueprint
self._setup_blueprints()
## Tornado initialization starts here
if self._host is None:
self._host = s.get(["server", "host"])
if self._port is None:
self._port = s.getInt(["server", "port"])
ioloop = IOLoop()
ioloop.install()
@@ -326,16 +342,42 @@ 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.admin_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/([^/]*\.mp[g4])", 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")))
(r"/static/webassets/(.*)", util.tornado.LargeResponseHandler, dict(path=os.path.join(s.getBaseFolder("generated"), "webassets"))),
# online indicators - text file with "online" as content and a transparent gif
(r"/online.txt", util.tornado.StaticDataHandler, dict(data="online\n")),
(r"/online.gif", util.tornado.StaticDataHandler, dict(data=bytes(base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")), content_type="image/gif"))
]
# fetch additional routes from plugins
for name, hook in pluginManager.get_hooks("octoprint.server.http.routes").items():
try:
result = hook(list(server_routes))
@@ -387,10 +429,15 @@ class Server():
self._logger.debug("Adding maximum body size of {size}B for {method} requests to {route})".format(**locals()))
max_body_sizes.append((method, route, size))
self._stop_intermediary_server()
# initialize and bind the server
self._server = util.tornado.CustomHTTPServer(self._tornado_app, max_body_sizes=max_body_sizes, default_max_body_size=s.getInt(["server", "maxSize"]))
self._server.listen(self._port, address=self._host)
eventManager.fire(events.Events.STARTUP)
# auto connect
if s.getBoolean(["serial", "autoconnect"]):
(port, baudrate) = s.get(["serial", "port"]), s.getInt(["serial", "baudrate"])
printer_profile = printerProfileManager.get_default()
@@ -399,7 +446,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()
@@ -435,6 +487,10 @@ class Server():
implementation.on_after_startup()
pluginLifecycleManager.add_callback("enabled", call_on_after_startup)
# when we are through with that we also run our preemptive cache
if settings().getBoolean(["devel", "cache", "preemptive"]):
self._execute_preemptive_flask_caching(preemptiveCache)
import threading
threading.Thread(target=work).start()
ioloop.add_callback(on_after_startup)
@@ -448,6 +504,11 @@ class Server():
observer.join()
octoprint.plugin.call_plugin(octoprint.plugin.ShutdownPlugin,
"on_shutdown")
if self._octoprint_daemon is not None:
self._logger.info("Cleaning up daemon pidfile")
self._octoprint_daemon.terminated()
self._logger.info("Goodbye!")
atexit.register(on_shutdown)
@@ -469,7 +530,8 @@ class Server():
def _create_socket_connection(self, session):
global printer, fileManager, analysisQueue, userManager, eventManager
return util.sockjs.PrinterStateConnection(printer, fileManager, analysisQueue, userManager, eventManager, pluginManager, session)
return util.sockjs.PrinterStateConnection(printer, fileManager, analysisQueue, userManager,
eventManager, pluginManager, session)
def _check_for_root(self):
if "geteuid" in dir(os) and os.geteuid() == 0:
@@ -481,7 +543,7 @@ class Server():
if "l10n" in request.values:
return Locale.negotiate([request.values["l10n"]], LANGUAGES)
if hasattr(g, "identity") and g.identity and userManager is not None:
if hasattr(g, "identity") and g.identity and userManager.enabled:
userid = g.identity.id
try:
user_language = userManager.getUserSetting(userid, ("interface", "language"))
@@ -494,7 +556,7 @@ class Server():
if default_language is not None and not default_language == "_default" and default_language in LANGUAGES:
return Locale.negotiate([default_language], LANGUAGES)
return request.accept_languages.best_match(LANGUAGES)
return Locale.parse(request.accept_languages.best_match(LANGUAGES))
def _setup_logging(self, debug, logConf=None):
defaultConfig = {
@@ -502,6 +564,9 @@ class Server():
"formatters": {
"simple": {
"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
},
"serial": {
"format": "%(asctime)s - %(message)s"
}
},
"handlers": {
@@ -512,18 +577,18 @@ class Server():
"stream": "ext://sys.stdout"
},
"file": {
"class": "logging.handlers.TimedRotatingFileHandler",
"class": "octoprint.logging.handlers.CleaningTimedRotatingFileHandler",
"level": "DEBUG",
"formatter": "simple",
"when": "D",
"backupCount": "1",
"backupCount": 6,
"filename": os.path.join(settings().getBaseFolder("logs"), "octoprint.log")
},
"serialFile": {
"class": "logging.handlers.RotatingFileHandler",
"class": "octoprint.logging.handlers.SerialLogHandler",
"level": "DEBUG",
"formatter": "simple",
"maxBytes": 2 * 1024 * 1024, # let's limit the serial log to 2MB in size
"formatter": "serial",
"backupCount": 3,
"filename": os.path.join(settings().getBaseFolder("logs"), "serial.log")
}
},
@@ -538,6 +603,9 @@ class Server():
},
"tornado.general": {
"level": "INFO"
},
"octoprint.server.util.flask": {
"level": "WARN"
}
},
"root": {
@@ -568,9 +636,42 @@ class Server():
if settings().getBoolean(["serial", "log"]):
# enable debug logging to serial.log
logging.getLogger("SERIAL").setLevel(logging.DEBUG)
logging.getLogger("SERIAL").debug("Enabling serial logging")
def _setup_app(self):
def _setup_app(self, app):
from octoprint.server.util.flask import ReverseProxiedEnvironment, OctoPrintFlaskRequest, OctoPrintFlaskResponse
s = settings()
app.debug = self._debug
secret_key = s.get(["server", "secretKey"])
if not secret_key:
import string
from random import choice
chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
secret_key = "".join(choice(chars) for _ in range(32))
s.set(["server", "secretKey"], secret_key)
s.save()
app.secret_key = secret_key
reverse_proxied = ReverseProxiedEnvironment(
header_prefix=s.get(["server", "reverseProxy", "prefixHeader"]),
header_scheme=s.get(["server", "reverseProxy", "schemeHeader"]),
header_host=s.get(["server", "reverseProxy", "hostHeader"]),
header_server=s.get(["server", "reverseProxy", "serverHeader"]),
header_port=s.get(["server", "reverseProxy", "portHeader"]),
prefix=s.get(["server", "reverseProxy", "prefixFallback"]),
scheme=s.get(["server", "reverseProxy", "schemeFallback"]),
host=s.get(["server", "reverseProxy", "hostFallback"]),
server=s.get(["server", "reverseProxy", "serverFallback"]),
port=s.get(["server", "reverseProxy", "portFallback"])
)
OctoPrintFlaskRequest.environment_wrapper = reverse_proxied
app.request_class = OctoPrintFlaskRequest
app.response_class = OctoPrintFlaskResponse
@app.before_request
def before_request():
g.locale = self._get_locale()
@@ -583,6 +684,9 @@ class Server():
response.headers.add("X-Clacks-Overhead", "GNU Terry Pratchett")
return response
from octoprint.util.jinja import MarkdownFilter
MarkdownFilter(app)
def _setup_i18n(self, app):
global babel
global LOCALES
@@ -610,26 +714,144 @@ class Server():
return self._get_locale()
def _setup_jinja2(self):
import re
app.jinja_env.add_extension("jinja2.ext.do")
app.jinja_env.add_extension("octoprint.util.jinja.trycatch")
def regex_replace(s, find, replace):
return re.sub(find, replace, s)
html_header_regex = re.compile("<h(?P<number>[1-6])>(?P<content>.*?)</h(?P=number)>")
def offset_html_headers(s, offset):
def repl(match):
number = int(match.group("number"))
number += offset
if number > 6:
number = 6
elif number < 1:
number = 1
return "<h{number}>{content}</h{number}>".format(number=number, content=match.group("content"))
return html_header_regex.sub(repl, s)
markdown_header_regex = re.compile("^(?P<hashs>#+)\s+(?P<content>.*)$", flags=re.MULTILINE)
def offset_markdown_headers(s, offset):
def repl(match):
number = len(match.group("hashs"))
number += offset
if number > 6:
number = 6
elif number < 1:
number = 1
return "{hashs} {content}".format(hashs="#" * number, content=match.group("content"))
return markdown_header_regex.sub(repl, s)
html_link_regex = re.compile("<(?P<tag>a.*?)>(?P<content>.*?)</a>")
def externalize_links(text):
def repl(match):
tag = match.group("tag")
if not u"href" in tag:
return match.group(0)
if not u"target=" in tag and not u"rel=" in tag:
tag += u" target=\"_blank\" rel=\"noreferrer noopener\""
content = match.group("content")
return u"<{tag}>{content}</a>".format(tag=tag, content=content)
return html_link_regex.sub(repl, text)
app.jinja_env.filters["regex_replace"] = regex_replace
app.jinja_env.filters["offset_html_headers"] = offset_html_headers
app.jinja_env.filters["offset_markdown_headers"] = offset_markdown_headers
app.jinja_env.filters["externalize_links"] = externalize_links
# 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([
app.jinja_loader,
filesystem_loader
])
loaders = [app.jinja_loader, filesystem_loader]
if octoprint.util.is_running_from_source():
from octoprint.util.jinja import SelectedFileSystemLoader
root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../.."))
allowed = ["AUTHORS.md", "CHANGELOG.md", "SUPPORTERS.md", "THIRDPARTYLICENSES.md"]
loaders.append(SelectedFileSystemLoader(root, allowed, prefix="_data/"))
jinja_loader = jinja2.ChoiceLoader(loaders)
app.jinja_loader = jinja_loader
del jinja2
self._register_template_plugins()
def _execute_preemptive_flask_caching(self, preemptive_cache):
from werkzeug.test import EnvironBuilder
import time
# we clean up entries from our preemptive cache settings that haven't been
# accessed longer than server.preemptiveCache.until days
preemptive_cache_timeout = settings().getInt(["server", "preemptiveCache", "until"])
cutoff_timestamp = time.time() - preemptive_cache_timeout * 24 * 60 * 60
def filter_current_entries(entry):
"""Returns True for entries younger than the cutoff date"""
return "_timestamp" in entry and entry["_timestamp"] > cutoff_timestamp
def filter_http_entries(entry):
"""Returns True for entries targeting http or https."""
return "base_url" in entry \
and entry["base_url"] \
and (entry["base_url"].startswith("http://")
or entry["base_url"].startswith("https://"))
def filter_entries(entry):
"""Combined filter."""
filters = (filter_current_entries,
filter_http_entries)
return all([f(entry) for f in filters])
# filter out all old and non-http entries
cache_data = preemptive_cache.clean_all_data(lambda root, entries: filter(filter_entries, entries))
if not cache_data:
return
def execute_caching():
for route in sorted(cache_data.keys(), key=lambda x: (x.count("/"), x)):
entries = reversed(sorted(cache_data[route], key=lambda x: x.get("_count", 0)))
for kwargs in entries:
plugin = kwargs.get("plugin", None)
additional_request_data = kwargs.get("_additional_request_data", dict())
kwargs = dict((k, v) for k, v in kwargs.items() if not k.startswith("_") and not k == "plugin")
kwargs.update(additional_request_data)
try:
if plugin:
self._logger.info("Preemptively caching {} (plugin {}) for {!r}".format(route, plugin, kwargs))
else:
self._logger.info("Preemptively caching {} for {!r}".format(route, kwargs))
headers = kwargs.get("headers", dict())
headers["X-Preemptive-Record"] = "no"
kwargs["headers"] = headers
builder = EnvironBuilder(**kwargs)
app(builder.get_environ(), lambda *a, **kw: None)
except:
self._logger.exception("Error while trying to preemptively cache {} for {!r}".format(route, kwargs))
# asynchronous caching
import threading
cache_thread = threading.Thread(target=execute_caching, name="Preemptive Cache Worker")
cache_thread.daemon = True
cache_thread.start()
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 +886,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 +936,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 range(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 +1013,11 @@ 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(
dynamic_core_assets = util.flask.collect_core_assets(enable_gcodeviewer=enable_gcodeviewer)
dynamic_plugin_assets = util.flask.collect_plugin_assets(
enable_gcodeviewer=enable_gcodeviewer,
enable_timelapse=enable_timelapse,
preferred_stylesheet=preferred_stylesheet
)
@@ -754,7 +1026,7 @@ class Server():
"js/lib/modernizr.custom.js",
"js/lib/lodash.min.js",
"js/lib/sprintf.min.js",
"js/lib/knockout.js",
"js/lib/knockout-3.4.0.js",
"js/lib/knockout.mapping-latest.js",
"js/lib/babel.js",
"js/lib/avltree.js",
@@ -780,11 +1052,15 @@ class Server():
"js/lib/loglevel.min.js",
"js/lib/sockjs-0.3.4.min.js"
]
js_app = dynamic_assets["js"] + [
"js/app/dataupdater.js",
"js/app/helpers.js",
"js/app/main.js",
]
js_core = dynamic_core_assets["js"] + \
dynamic_plugin_assets["bundled"]["js"] + \
["js/app/dataupdater.js",
"js/app/helpers.js",
"js/app/main.js"]
js_plugins = dynamic_plugin_assets["external"]["js"]
if len(js_plugins) == 0:
js_plugins = ["empty"]
js_app = js_plugins + js_core
css_libs = [
"css/bootstrap.min.css",
@@ -795,13 +1071,21 @@ class Server():
"css/jquery.fileupload-ui.css",
"css/pnotify.min.css"
]
css_app = list(dynamic_assets["css"])
if len(css_app) == 0:
css_app = ["empty"]
css_core = list(dynamic_core_assets["css"]) + list(dynamic_plugin_assets["bundled"]["css"])
if len(css_core) == 0:
css_core = ["empty"]
css_plugins = list(dynamic_plugin_assets["external"]["css"])
if len(css_plugins) == 0:
css_plugins = ["empty"]
css_app = css_core + css_plugins
less_app = list(dynamic_assets["less"])
if len(less_app) == 0:
less_app = ["empty"]
less_core = list(dynamic_core_assets["less"]) + list(dynamic_plugin_assets["bundled"]["less"])
if len(less_core) == 0:
less_core = ["empty"]
less_plugins = list(dynamic_plugin_assets["external"]["less"])
if len(less_plugins) == 0:
less_plugins = ["empty"]
less_app = less_core + less_plugins
from webassets.filter import register_filter, Filter
from webassets.filter.cssrewrite.base import PatternRewriter
@@ -822,7 +1106,7 @@ class Server():
return "{import_with_options}\"{import_url}\";".format(**locals())
class JsDelimiterBundle(Filter):
class JsDelimiterBundler(Filter):
name = "js_delimiter_bundler"
options = {}
def input(self, _in, out, **kwargs):
@@ -830,25 +1114,127 @@ class Server():
out.write("\n;\n")
register_filter(LessImportRewrite)
register_filter(JsDelimiterBundle)
register_filter(JsDelimiterBundler)
# JS
js_libs_bundle = Bundle(*js_libs, output="webassets/packed_libs.js", filters="js_delimiter_bundler")
if settings().getBoolean(["devel", "webassets", "minify"]):
js_core_bundle = Bundle(*js_core, output="webassets/packed_core.js", filters="rjsmin, js_delimiter_bundler")
js_plugins_bundle = Bundle(*js_plugins, output="webassets/packed_plugins.js", filters="rjsmin, js_delimiter_bundler")
js_app_bundle = Bundle(*js_app, output="webassets/packed_app.js", filters="rjsmin, js_delimiter_bundler")
else:
js_core_bundle = Bundle(*js_core, output="webassets/packed_core.js", filters="js_delimiter_bundler")
js_plugins_bundle = Bundle(*js_plugins, output="webassets/packed_plugins.js", filters="js_delimiter_bundler")
js_app_bundle = Bundle(*js_app, output="webassets/packed_app.js", filters="js_delimiter_bundler")
# CSS
css_libs_bundle = Bundle(*css_libs, output="webassets/packed_libs.css")
css_app_bundle = Bundle(*css_app, output="webassets/packed_app.css")
css_core_bundle = Bundle(*css_core, output="webassets/packed_core.css", filters="cssrewrite")
css_plugins_bundle = Bundle(*css_plugins, output="webassets/packed_plugins.css", filters="cssrewrite")
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")
# LESS
less_core_bundle = Bundle(*less_core, output="webassets/packed_core.less", filters="cssrewrite, less_importrewrite")
less_plugins_bundle = Bundle(*less_plugins, output="webassets/packed_plugins.less", filters="cssrewrite, less_importrewrite")
less_app_bundle = Bundle(*less_app, output="webassets/packed_app.less", filters="cssrewrite, less_importrewrite")
# asset registration
assets.register("js_libs", js_libs_bundle)
assets.register("js_core", js_core_bundle)
assets.register("js_plugins", js_plugins_bundle)
assets.register("js_app", js_app_bundle)
assets.register("css_libs", css_libs_bundle)
assets.register("css_core", css_core_bundle)
assets.register("css_plugins", css_plugins_bundle)
assets.register("css_app", css_app_bundle)
assets.register("less_app", all_less_bundle)
assets.register("less_core", less_core_bundle)
assets.register("less_plugins", less_plugins_bundle)
assets.register("less_app", less_app_bundle)
def _start_intermediary_server(self, s):
import BaseHTTPServer
import SimpleHTTPServer
import threading
host = self._host
port = self._port
if host is None:
host = s.get(["server", "host"])
if port is None:
port = s.getInt(["server", "port"])
self._logger.debug("Starting intermediary server on {}:{}".format(host, port))
class IntermediaryServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def __init__(self, rules=None, *args, **kwargs):
if rules is None:
rules = []
self.rules = rules
SimpleHTTPServer.SimpleHTTPRequestHandler.__init__(self, *args, **kwargs)
def do_GET(self):
request_path = self.path
if "?" in request_path:
request_path = request_path[0:request_path.find("?")]
for rule in self.rules:
path, data, content_type = rule
if request_path == path:
self.send_response(200)
if content_type:
self.send_header("Content-Type", content_type)
self.end_headers()
self.wfile.write(data)
break
else:
self.send_response(404)
self.wfile.write("Not found")
base_path = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "static"))
rules = [
("/", ["intermediary.html",], "text/html"),
("/favicon.ico", ["img", "tentacle-20x20.png"], "image/png"),
("/intermediary.gif", bytes(base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")), "image/gif")
]
def contents(args):
path = os.path.join(base_path, *args)
if not os.path.isfile(path):
return ""
with open(path, "rb") as f:
data = f.read()
return data
def process(rule):
if len(rule) == 2:
path, data = rule
content_type = None
else:
path, data, content_type = rule
if isinstance(data, (list, tuple)):
data = contents(data)
return path, data, content_type
rules = map(process, filter(lambda rule: len(rule) == 2 or len(rule) == 3, rules))
self._intermediary_server = BaseHTTPServer.HTTPServer((host, port), lambda *args, **kwargs: IntermediaryServerHandler(rules, *args, **kwargs))
thread = threading.Thread(target=self._intermediary_server.serve_forever)
thread.daemon = True
thread.start()
self._logger.debug("Intermediary server started")
def _stop_intermediary_server(self):
if self._intermediary_server is None:
return
self._logger.debug("Shutting down intermediary server...")
self._intermediary_server.shutdown()
self._intermediary_server.server_close()
self._logger.debug("Intermediary server shut down")
class LifecycleManager(object):
def __init__(self, plugin_manager):
+7 -3
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)
@@ -109,6 +111,7 @@ def firstRunSetup():
"pass2" in request.values.keys() and request.values["pass1"] == request.values["pass2"]:
# configure access control
s().setBoolean(["accessControl", "enabled"], True)
octoprint.server.userManager.enable()
octoprint.server.userManager.addUser(request.values["user"], request.values["pass1"], True, ["user", "admin"])
s().setBoolean(["server", "firstRun"], False)
elif "ac" in request.values.keys() and not request.values["ac"] in valid_boolean_trues:
@@ -118,6 +121,7 @@ def firstRunSetup():
octoprint.server.loginManager.anonymous_user = octoprint.users.DummyUser
octoprint.server.principals.identity_loaders.appendleft(octoprint.users.dummy_identity_loader)
octoprint.server.userManager.disable()
s().save()
return NO_CONTENT
@@ -179,7 +183,7 @@ def performSystemAction():
@api.route("/login", methods=["POST"])
def login():
if octoprint.server.userManager is not None and "user" in request.values.keys() and "pass" in request.values.keys():
if octoprint.server.userManager.enabled and "user" in request.values.keys() and "pass" in request.values.keys():
username = request.values["user"]
password = request.values["pass"]
@@ -194,7 +198,7 @@ def login():
user = octoprint.server.userManager.findUser(username)
if user is not None:
if octoprint.server.userManager.checkPassword(username, password):
if octoprint.server.userManager is not None:
if octoprint.server.userManager.enabled:
user = octoprint.server.userManager.login_user(user)
session["usersession.id"] = user.get_session()
g.user = user
+23 -17
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)
@@ -217,7 +220,7 @@ def uploadGcodeFile(target):
done = True
else:
filename = fileProcessingFinished(added_file, fileManager.path_on_disk(FileDestinations.LOCAL, added_file), target)
done = True
done = not sd
if userdata is not None:
# upload included userdata, add this now to the metadata
@@ -322,25 +325,28 @@ def gcodeFileCommand(filename, target):
except octoprint.slicing.UnknownSlicer as e:
return make_response("Slicer {slicer} is not available".format(slicer=e.slicer), 400)
if not octoprint.filemanager.valid_file_type(filename, type="stl"):
return make_response("Cannot slice {filename}, not an STL file".format(**locals()), 415)
if not any([octoprint.filemanager.valid_file_type(filename, type=source_file_type) for source_file_type in slicer_instance.get_slicer_properties().get("source_file_types", ["model"])]):
return make_response("Cannot slice {filename}, not a model file".format(**locals()), 415)
if slicer_instance.get_slicer_properties()["same_device"] and (printer.is_printing() or printer.is_paused()):
if slicer_instance.get_slicer_properties().get("same_device", True) and (printer.is_printing() or printer.is_paused()):
# slicer runs on same device as OctoPrint, slicing while printing is hence disabled
return make_response("Cannot slice on {slicer} while printing due to performance reasons".format(**locals()), 409)
if "gcode" in data and data["gcode"]:
gcode_name = data["gcode"]
if "destination" in data and data["destination"]:
destination = data["destination"]
del data["destination"]
elif "gcode" in data and data["gcode"]:
destination = data["gcode"]
del data["gcode"]
else:
import os
name, _ = os.path.splitext(filename)
gcode_name = name + ".gco"
destination = name + "." + slicer_instance.get_slicer_properties().get("destination_extensions", ["gco", "gcode", "g"])[0]
# prohibit overwriting the file that is currently being printed
currentOrigin, currentFilename = _getCurrentFile()
if currentFilename == gcode_name and currentOrigin == target and (printer.is_printing() or printer.is_paused()):
make_response("Trying to slice into file that is currently being printed: %s" % gcode_name, 409)
if currentFilename == destination and currentOrigin == target and (printer.is_printing() or printer.is_paused()):
make_response("Trying to slice into file that is currently being printed: %s" % destination, 409)
if "profile" in data.keys() and data["profile"]:
profile = data["profile"]
@@ -388,24 +394,24 @@ def gcodeFileCommand(filename, target):
printer.select_file(filenameToSelect, sd, print_after_slicing)
try:
fileManager.slice(slicer, target, filename, target, gcode_name,
fileManager.slice(slicer, target, filename, target, destination,
profile=profile,
printer_profile_id=printerProfile,
position=position,
overrides=overrides,
callback=slicing_done,
callback_args=(target, gcode_name, select_after_slicing, print_after_slicing))
callback_args=(target, destination, select_after_slicing, print_after_slicing))
except octoprint.slicing.UnknownProfile:
return make_response("Profile {profile} doesn't exist".format(**locals()), 400)
files = {}
location = url_for(".readGcodeFile", target=target, filename=gcode_name, _external=True)
location = url_for(".readGcodeFile", target=target, filename=destination, _external=True)
result = {
"name": gcode_name,
"name": destination,
"origin": FileDestinations.LOCAL,
"refs": {
"resource": location,
"download": url_for("index", _external=True) + "downloads/files/" + target + "/" + gcode_name
"download": url_for("index", _external=True) + "downloads/files/" + target + "/" + destination
}
}
+10 -2
View File
@@ -43,7 +43,15 @@ def controlJob():
elif command == "pause":
if not activePrintjob:
return make_response("Printer is neither printing nor paused, 'pause' command cannot be performed", 409)
printer.toggle_pause_print()
action = data.get("action", "toggle")
if action == "toggle":
printer.toggle_pause_print()
elif action == "pause":
printer.pause_print()
elif action == "resume":
printer.resume_print()
else:
return make_response("Unknown action '{}', allowed values for action parameter are 'pause', 'resume' and 'toggle'".format(action), 400)
elif command == "cancel":
if not activePrintjob:
return make_response("Printer is neither printing nor paused, 'cancel' command cannot be performed", 409)
@@ -58,4 +66,4 @@ def jobState():
"job": currentData["job"],
"progress": currentData["progress"],
"state": currentData["state"]["text"]
})
})
+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
+46 -2
View File
@@ -64,11 +64,14 @@ def getSettings():
"waitForStart": s.getBoolean(["feature", "waitForStartOnConnect"]),
"alwaysSendChecksum": s.getBoolean(["feature", "alwaysSendChecksum"]),
"sdSupport": s.getBoolean(["feature", "sdSupport"]),
"sdRelativePath": s.getBoolean(["feature", "sdRelativePath"]),
"sdAlwaysAvailable": s.getBoolean(["feature", "sdAlwaysAvailable"]),
"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"],
@@ -83,7 +86,16 @@ def getSettings():
"timeoutSdStatus": s.getFloat(["serial", "timeout", "sdStatus"]),
"log": s.getBoolean(["serial", "log"]),
"additionalPorts": s.get(["serial", "additionalPorts"]),
"longRunningCommands": s.get(["serial", "longRunningCommands"])
"longRunningCommands": s.get(["serial", "longRunningCommands"]),
"checksumRequiringCommands": s.get(["serial", "checksumRequiringCommands"]),
"helloCommand": s.get(["serial", "helloCommand"]),
"ignoreErrorsFromFirmware": s.getBoolean(["serial", "ignoreErrorsFromFirmware"]),
"disconnectOnErrors": s.getBoolean(["serial", "disconnectOnErrors"]),
"triggerOkForM29": s.getBoolean(["serial", "triggerOkForM29"]),
"supportResendsWithoutOk": s.getBoolean(["serial", "supportResendsWithoutOk"]),
"maxTimeoutsIdle": s.getInt(["serial", "maxCommunicationTimeouts", "idle"]),
"maxTimeoutsPrinting": s.getInt(["serial", "maxCommunicationTimeouts", "printing"]),
"maxTimeoutsLong": s.getInt(["serial", "maxCommunicationTimeouts", "long"])
},
"folder": {
"uploads": s.getBaseFolder("uploads"),
@@ -111,6 +123,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"])
}
}
}
@@ -194,11 +217,14 @@ def setSettings():
if "waitForStart" in data["feature"].keys(): s.setBoolean(["feature", "waitForStartOnConnect"], data["feature"]["waitForStart"])
if "alwaysSendChecksum" in data["feature"].keys(): s.setBoolean(["feature", "alwaysSendChecksum"], data["feature"]["alwaysSendChecksum"])
if "sdSupport" in data["feature"].keys(): s.setBoolean(["feature", "sdSupport"], data["feature"]["sdSupport"])
if "sdRelativePath" in data["feature"].keys(): s.setBoolean(["feature", "sdRelativePath"], data["feature"]["sdRelativePath"])
if "sdAlwaysAvailable" in data["feature"].keys(): s.setBoolean(["feature", "sdAlwaysAvailable"], data["feature"]["sdAlwaysAvailable"])
if "swallowOkAfterResend" in data["feature"].keys(): s.setBoolean(["feature", "swallowOkAfterResend"], data["feature"]["swallowOkAfterResend"])
if "repetierTargetTemp" in data["feature"].keys(): s.setBoolean(["feature", "repetierTargetTemp"], data["feature"]["repetierTargetTemp"])
if "externalHeatupDetection" in data["feature"].keys(): s.setBoolean(["feature", "externalHeatupDetection"], data["feature"]["externalHeatupDetection"])
if "keyboardControl" in data["feature"].keys(): s.setBoolean(["feature", "keyboardControl"], data["feature"]["keyboardControl"])
if "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"])
@@ -211,6 +237,15 @@ def setSettings():
if "timeoutSdStatus" in data["serial"].keys(): s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"])
if "additionalPorts" in data["serial"] and isinstance(data["serial"]["additionalPorts"], (list, tuple)): s.set(["serial", "additionalPorts"], data["serial"]["additionalPorts"])
if "longRunningCommands" in data["serial"] and isinstance(data["serial"]["longRunningCommands"], (list, tuple)): s.set(["serial", "longRunningCommands"], data["serial"]["longRunningCommands"])
if "checksumRequiringCommands" in data["serial"] and isinstance(data["serial"]["checksumRequiringCommands"], (list, tuple)): s.set(["serial", "checksumRequiringCommands"], data["serial"]["checksumRequiringCommands"])
if "helloCommand" in data["serial"]: s.set(["serial", "helloCommand"], data["serial"]["helloCommand"])
if "ignoreErrorsFromFirmware" in data["serial"]: s.setBoolean(["serial", "ignoreErrorsFromFirmware"], data["serial"]["ignoreErrorsFromFirmware"])
if "disconnectOnErrors" in data["serial"]: s.setBoolean(["serial", "disconnectOnErrors"], data["serial"]["disconnectOnErrors"])
if "triggerOkForM29" in data["serial"]: s.setBoolean(["serial", "triggerOkForM29"], data["serial"]["triggerOkForM29"])
if "supportResendsWithoutOk" in data["serial"]: s.setBoolean(["serial", "supportResendsWithoutOk"], data["serial"]["supportResendsWithoutOk"])
if "maxTimeoutsIdle" in data["serial"]: s.setInt(["serial", "maxCommunicationTimeouts", "idle"], data["serial"]["maxTimeoutsIdle"])
if "maxTimeoutsPrinting" in data["serial"]: s.setInt(["serial", "maxCommunicationTimeouts", "printing"], data["serial"]["maxTimeoutsPrinting"])
if "maxTimeoutsLong" in data["serial"]: s.setInt(["serial", "maxCommunicationTimeouts", "long"], data["serial"]["maxTimeoutsLong"])
oldLog = s.getBoolean(["serial", "log"])
if "log" in data["serial"].keys(): s.setBoolean(["serial", "log"], data["serial"]["log"])
@@ -248,6 +283,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
+16 -3
View File
@@ -14,11 +14,13 @@ from octoprint.server.api import api, NO_CONTENT
from octoprint.settings import settings as s, valid_boolean_trues
from octoprint.slicing import UnknownSlicer, SlicerNotConfigured, ProfileAlreadyExists, UnknownProfile
from octoprint.slicing import UnknownSlicer, SlicerNotConfigured, ProfileAlreadyExists, UnknownProfile, CouldNotDeleteProfile
@api.route("/slicing", methods=["GET"])
def slicingListAll():
from octoprint.filemanager import get_extensions
default_slicer = s().get(["slicing", "defaultSlicer"])
if "configured" in request.values and request.values["configured"] in valid_boolean_trues:
@@ -30,12 +32,21 @@ def slicingListAll():
for slicer in slicers:
try:
slicer_impl = slicingManager.get_slicer(slicer, require_configured=False)
extensions = set()
for source_file_type in slicer_impl.get_slicer_properties().get("source_file_types", ["model"]):
extensions = extensions.union(get_extensions(source_file_type))
result[slicer] = dict(
key=slicer,
displayName=slicer_impl.get_slicer_properties()["name"],
default=default_slicer == slicer,
configured = slicer_impl.is_slicer_configured(),
profiles=_getSlicingProfilesData(slicer)
configured=slicer_impl.is_slicer_configured(),
profiles=_getSlicingProfilesData(slicer),
extensions=dict(
source=list(extensions),
destination=slicer_impl.get_slicer_properties().get("destination_extensions", ["gco", "gcode", "g"])
)
)
except (UnknownSlicer, SlicerNotConfigured):
# this should never happen
@@ -147,6 +158,8 @@ def slicingDelSlicerProfile(slicer, name):
slicingManager.delete_profile(slicer, name)
except UnknownSlicer:
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
except CouldNotDeleteProfile as e:
return make_response("Could not delete profile {profile} for slicer {slicer}: {cause}".format(profile=name, slicer=slicer, cause=str(e.cause)), 500)
return NO_CONTENT
+47 -15
View File
@@ -14,10 +14,12 @@ import octoprint.timelapse
import octoprint.util as util
from octoprint.settings import settings, valid_boolean_trues
from octoprint.server import admin_permission
from octoprint.server.util.flask import redirect_to_tornado, restricted_access
from octoprint.server import admin_permission, printer
from octoprint.server.util.flask import redirect_to_tornado, restricted_access, get_json_command_from_request
from octoprint.server.api import api
from octoprint.server import NO_CONTENT
#~~ timelapse handling
@@ -29,24 +31,27 @@ 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()
files = octoprint.timelapse.get_finished_timelapses()
for file in files:
file["url"] = url_for("index") + "downloads/timelapse/" + file["name"]
return jsonify({
"config": config,
"files": files
})
result = dict(config=config,
files=files)
if "unrendered" in request.values and request.values["unrendered"] in valid_boolean_trues:
result.update(unrendered=octoprint.timelapse.get_unrendered_timelapses())
return jsonify(result)
@api.route("/timelapse/<filename>", methods=["GET"])
@@ -57,7 +62,7 @@ def downloadTimelapse(filename):
@api.route("/timelapse/<filename>", methods=["DELETE"])
@restricted_access
def deleteTimelapse(filename):
if util.is_allowed_file(filename, {"mpg"}):
if util.is_allowed_file(filename, ["mpg", "mpeg", "mp4"]):
timelapse_folder = settings().getBaseFolder("timelapse")
full_path = os.path.realpath(os.path.join(timelapse_folder, filename))
if full_path.startswith(timelapse_folder) and os.path.exists(full_path):
@@ -65,6 +70,33 @@ def deleteTimelapse(filename):
return getTimelapseData()
@api.route("/timelapse/unrendered/<name>", methods=["DELETE"])
@restricted_access
def deleteUnrenderedTimelapse(name):
octoprint.timelapse.delete_unrendered_timelapse(name)
return NO_CONTENT
@api.route("/timelapse/unrendered/<name>", methods=["POST"])
@restricted_access
def processUnrenderedTimelapseCommand(name):
# valid file commands, dict mapping command name to mandatory parameters
valid_commands = {
"render": []
}
command, data, response = get_json_command_from_request(request, valid_commands)
if response is not None:
return response
if command == "render":
if printer.is_printing() or printer.is_paused():
return make_response("Printer is currently printing, cannot render timelapse", 409)
octoprint.timelapse.render_unrendered_timelapse(name)
return NO_CONTENT
@api.route("/timelapse", methods=["POST"])
@restricted_access
def setTimelapseConfig():
@@ -114,9 +146,9 @@ def setTimelapseConfig():
return make_response("Invalid value for interval: %d" % interval)
if admin_permission.can() and "save" in request.values and request.values["save"] in valid_boolean_trues:
octoprint.timelapse.configureTimelapse(config, True)
octoprint.timelapse.configure_timelapse(config, True)
else:
octoprint.timelapse.configureTimelapse(config)
octoprint.timelapse.configure_timelapse(config)
return getTimelapseData()
+10 -10
View File
@@ -23,7 +23,7 @@ from octoprint.server.util.flask import restricted_access
@restricted_access
@admin_permission.require(403)
def getUsers():
if userManager is None:
if not userManager.enabled:
return jsonify(SUCCESS)
return jsonify({"users": userManager.getAllUsers()})
@@ -33,7 +33,7 @@ def getUsers():
@restricted_access
@admin_permission.require(403)
def addUser():
if userManager is None:
if not userManager.enabled:
return jsonify(SUCCESS)
if not "application/json" in request.headers["Content-Type"]:
@@ -62,7 +62,7 @@ def addUser():
@api.route("/users/<username>", methods=["GET"])
@restricted_access
def getUser(username):
if userManager is None:
if not userManager.enabled:
return jsonify(SUCCESS)
if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()):
@@ -79,7 +79,7 @@ def getUser(username):
@restricted_access
@admin_permission.require(403)
def updateUser(username):
if userManager is None:
if not userManager.enabled:
return jsonify(SUCCESS)
user = userManager.findUser(username)
@@ -110,7 +110,7 @@ def updateUser(username):
@restricted_access
@admin_permission.require(http_exception=403)
def removeUser(username):
if userManager is None:
if not userManager.enabled:
return jsonify(SUCCESS)
try:
@@ -123,7 +123,7 @@ def removeUser(username):
@api.route("/users/<username>/password", methods=["PUT"])
@restricted_access
def changePasswordForUser(username):
if userManager is None:
if not userManager.enabled:
return jsonify(SUCCESS)
if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()):
@@ -151,7 +151,7 @@ def changePasswordForUser(username):
@api.route("/users/<username>/settings", methods=["GET"])
@restricted_access
def getSettingsForUser(username):
if userManager is None:
if not userManager.enabled:
return jsonify(SUCCESS)
if current_user is None or current_user.is_anonymous() or (current_user.get_name() != username and not current_user.is_admin()):
@@ -165,7 +165,7 @@ def getSettingsForUser(username):
@api.route("/users/<username>/settings", methods=["PATCH"])
@restricted_access
def changeSettingsForUser(username):
if userManager is None:
if not userManager.enabled:
return jsonify(SUCCESS)
if current_user is None or current_user.is_anonymous() or (current_user.get_name() != username and not current_user.is_admin()):
@@ -185,7 +185,7 @@ def changeSettingsForUser(username):
@api.route("/users/<username>/apikey", methods=["DELETE"])
@restricted_access
def deleteApikeyForUser(username):
if userManager is None:
if not userManager.enabled:
return jsonify(SUCCESS)
if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()):
@@ -201,7 +201,7 @@ def deleteApikeyForUser(username):
@api.route("/users/<username>/apikey", methods=["POST"])
@restricted_access
def generateApikeyForUser(username):
if userManager is None:
if not userManager.enabled:
return jsonify(SUCCESS)
if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()):
+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()
+23 -86
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.
@@ -108,7 +120,7 @@ def get_user_for_apikey(apikey):
if apikey == settings().get(["api", "key"]) or octoprint.server.appSessionManager.validate(apikey):
# master key or an app session key was used
return ApiUser()
elif octoprint.server.userManager is not None:
elif octoprint.server.userManager.enabled:
# user key might have been used
return octoprint.server.userManager.findUser(apikey=apikey)
return None
@@ -131,90 +143,15 @@ def get_api_key(request):
return None
#~~ reverse proxy compatible WSGI middleware
def get_plugin_hash():
from octoprint.plugin import plugin_manager
plugin_signature = lambda impl: "{}:{}".format(impl._identifier, impl._plugin_version)
template_plugins = map(plugin_signature, plugin_manager().get_implementations(octoprint.plugin.TemplatePlugin))
asset_plugins = map(plugin_signature, plugin_manager().get_implementations(octoprint.plugin.AssetPlugin))
ui_plugins = sorted(set(template_plugins + asset_plugins))
class ReverseProxied(object):
"""
Wrap the application in this middleware and configure the
front-end server to add these headers, to let you quietly bind
this to a URL other than / and to an HTTP scheme that is
different than what is used locally.
In nginx:
.. code-block:: none
location /myprefix {
proxy_pass http://192.168.0.1:5001;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Scheme $scheme;
proxy_set_header X-Script-Name /myprefix;
}
Alternatively define prefix and scheme via config.yaml:
.. code-block:: yaml
server:
baseUrl: /myprefix
scheme: http
:param app: the WSGI application
:param header_script_name: the HTTP header in the wsgi environment from which to determine the prefix
:param header_scheme: the HTTP header in the wsgi environment from which to determine the scheme
:param header_host: the HTTP header in the wsgi environment from which to determine the host for which to generate external URLs
:param base_url: the prefix to use as fallback if headers are not set
:param scheme: the scheme to use as fallback if headers are not set
:param host: the host to use as fallback if headers are not set
"""
def __init__(self, app, header_prefix="x-script-name", header_scheme="x-scheme", header_host="x-forwarded-host", base_url="", scheme="", host=""):
self.app = app
# headers for prefix & scheme & host, converted to conform to WSGI format
to_wsgi_format = lambda header: "HTTP_" + header.upper().replace("-", "_")
self._header_prefix = to_wsgi_format(header_prefix)
self._header_scheme = to_wsgi_format(header_scheme)
self._header_host = to_wsgi_format(header_host)
# fallback prefix & scheme & host from config
self._fallback_prefix = base_url
self._fallback_scheme = scheme
self._fallback_host = host
def __call__(self, environ, start_response):
# determine prefix
prefix = environ.get(self._header_prefix, "")
if not prefix:
prefix = self._fallback_prefix
# rewrite SCRIPT_NAME and if necessary also PATH_INFO based on prefix
if prefix:
environ["SCRIPT_NAME"] = prefix
path_info = environ["PATH_INFO"]
if path_info.startswith(prefix):
environ["PATH_INFO"] = path_info[len(prefix):]
# determine scheme
scheme = environ.get(self._header_scheme, "")
if not scheme:
scheme = self._fallback_scheme
# rewrite wsgi.url_scheme based on scheme
if scheme:
environ["wsgi.url_scheme"] = scheme
# determine host
host = environ.get(self._header_host, "")
if not host:
host = self._fallback_host
# rewrite host header based on host
if host:
environ["HTTP_HOST"] = host
# call wrapped app with rewritten environment
return self.app(environ, start_response)
import hashlib
plugin_hash = hashlib.sha1()
plugin_hash.update(",".join(ui_plugins))
return plugin_hash.hexdigest()
+662 -30
View File
@@ -14,18 +14,20 @@ import flask.ext.assets
import webassets.updater
import webassets.utils
import functools
import contextlib
import time
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 +124,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 +156,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,17 +188,249 @@ 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
#~~ WSGI environment wrapper for reverse proxying
class ReverseProxiedEnvironment(object):
@staticmethod
def to_header_candidates(values):
if values is None:
return []
if not isinstance(values, (list, tuple)):
values = [values]
to_wsgi_format = lambda header: "HTTP_" + header.upper().replace("-", "_")
return map(to_wsgi_format, values)
def __init__(self,
header_prefix=None,
header_scheme=None,
header_host=None,
header_server=None,
header_port=None,
prefix=None,
scheme=None,
host=None,
server=None,
port=None):
# sensible defaults
if header_prefix is None:
header_prefix = ["x-script-name"]
if header_scheme is None:
header_scheme = ["x-forwarded-proto", "x-scheme"]
if header_host is None:
header_host = ["x-forwarded-host"]
if header_server is None:
header_server = ["x-forwarded-server"]
if header_port is None:
header_port = ["x-forwarded-port"]
# header candidates
self._headers_prefix = self.to_header_candidates(header_prefix)
self._headers_scheme = self.to_header_candidates(header_scheme)
self._headers_host = self.to_header_candidates(header_host)
self._headers_server = self.to_header_candidates(header_server)
self._headers_port = self.to_header_candidates(header_port)
# fallback prefix & scheme & host from config
self._fallback_prefix = prefix
self._fallback_scheme = scheme
self._fallback_host = host
self._fallback_server = server
self._fallback_port = port
def __call__(self, environ):
def retrieve_header(header_type):
candidates = getattr(self, "_headers_" + header_type, [])
fallback = getattr(self, "_fallback_" + header_type, None)
for candidate in candidates:
value = environ.get(candidate, None)
if value is not None:
return value
else:
return fallback
def host_to_server_and_port(host, scheme):
if host is None:
return None, None
if ":" in host:
server, port = host.split(":", 1)
else:
server = host
port = "443" if scheme == "https" else "80"
return server, port
# determine prefix
prefix = retrieve_header("prefix")
if prefix is not None:
environ["SCRIPT_NAME"] = prefix
path_info = environ["PATH_INFO"]
if path_info.startswith(prefix):
environ["PATH_INFO"] = path_info[len(prefix):]
# determine scheme
scheme = retrieve_header("scheme")
if scheme is not None and "," in scheme:
# Scheme might be something like "https,https" if doubly-reverse-proxied
# without stripping original scheme header first, make sure to only use
# the first entry in such a case. See #1391.
scheme, _ = map(lambda x: x.strip(), scheme.split(",", 1))
if scheme is not None:
environ["wsgi.url_scheme"] = scheme
# determine host
url_scheme = environ["wsgi.url_scheme"]
host = retrieve_header("host")
if host is not None:
# if we have a host, we take server_name and server_port from it
server, port = host_to_server_and_port(host, url_scheme)
environ["HTTP_HOST"] = host
environ["SERVER_NAME"] = server
environ["SERVER_PORT"] = port
elif environ.get("HTTP_HOST", None) is not None:
# if we have a Host header, we use that and make sure our server name and port properties match it
host = environ["HTTP_HOST"]
server, port = host_to_server_and_port(host, url_scheme)
environ["SERVER_NAME"] = server
environ["SERVER_PORT"] = port
else:
# else we take a look at the server and port headers and if we have
# something there we derive the host from it
# determine server - should usually not be used
server = retrieve_header("server")
if server is not None:
environ["SERVER_NAME"] = server
# determine port - should usually not be used
port = retrieve_header("port")
if port is not None:
environ["SERVER_PORT"] = port
# reconstruct host header
if url_scheme == "http" and environ["SERVER_PORT"] == "80" or url_scheme == "https" and environ["SERVER_PORT"] == "443":
# default port for scheme, can be skipped
environ["HTTP_HOST"] = environ["SERVER_NAME"]
else:
environ["HTTP_HOST"] = environ["SERVER_NAME"] + ":" + environ["SERVER_PORT"]
# call wrapped app with rewritten environment
return environ
#~~ request and response versions
from werkzeug.wrappers import cached_property
class OctoPrintFlaskRequest(flask.Request):
environment_wrapper = staticmethod(lambda x: x)
def __init__(self, environ, *args, **kwargs):
# apply environment wrapper to provided WSGI environment
flask.Request.__init__(self, self.environment_wrapper(environ), *args, **kwargs)
@cached_property
def cookies(self):
# strip cookie_suffix from all cookies in the request, return result
cookies = flask.Request.cookies.__get__(self)
result = dict()
desuffixed = dict()
for key, value in cookies.items():
if key.endswith(self.cookie_suffix):
desuffixed[key[:-len(self.cookie_suffix)]] = value
else:
result[key] = value
result.update(desuffixed)
return result
@cached_property
def server_name(self):
"""Short cut to the request's server name header"""
return self.environ.get("SERVER_NAME")
@cached_property
def server_port(self):
"""Short cut to the request's server port header"""
return self.environ.get("SERVER_PORT")
@cached_property
def cookie_suffix(self):
"""
Request specific suffix for set and read cookies
We need this because cookies are not port-specific and we don't want to overwrite our
session and other cookies from one OctoPrint instance on our machine with those of another
one who happens to listen on the same address albeit a different port.
"""
return "_P" + self.server_port
class OctoPrintFlaskResponse(flask.Response):
def set_cookie(self, key, *args, **kwargs):
# restrict cookie path to script root
kwargs["path"] = flask.request.script_root + kwargs.get("path", "/")
# add request specific cookie suffix to name
flask.Response.set_cookie(self, key + flask.request.cookie_suffix, *args, **kwargs)
def delete_cookie(self, key, path='/', domain=None):
flask.Response.delete_cookie(self, key, path=path, domain=domain)
# we also still might have a cookie left over from before we started prefixing, delete that manually
# without any pre processing (no path prefix, no key suffix)
flask.Response.set_cookie(self, key, expires=0, max_age=0, path=path, domain=domain)
#~~ passive login helper
def passive_login():
if octoprint.server.userManager is not None:
if octoprint.server.userManager.enabled:
user = octoprint.server.userManager.login_user(flask.ext.login.current_user)
else:
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,42 +454,136 @@ 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._mutex = threading.RLock()
self._cache = {}
self._bypassed = set()
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:
with self._mutex:
self._cache.pop(key, None)
def get(self, key):
import pickle
now = time.time()
with self._mutex:
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
with self._mutex:
self._prune()
self._cache[key] = (self.calculate_timeout(timeout=timeout),
pickle.dumps(value, pickle.HIGHEST_PROTOCOL))
if key in self._bypassed:
self._bypassed.remove(key)
def add(self, key, value, timeout=None):
with self._mutex:
self.set(key, value, timeout=None)
self._cache.setdefault(key, self._cache[key])
def delete(self, key):
with self._mutex:
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
with self._mutex:
return len(self._cache) > self._threshold
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, value):
return self.set(key, value)
def __delitem__(self, key):
return self.delete(key)
def __contains__(self, key):
with self._mutex:
return key in self._cache
def set_bypassed(self, key):
with self._mutex:
self._bypassed.add(key)
def is_bypassed(self, key):
with self._mutex:
return key in self._bypassed
_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):
logger = logging.getLogger(__name__)
cache_key = key()
# bypass the cache if "unless" condition is true
if callable(unless) and unless():
logger.debug("Cache for {path} bypassed, calling wrapped function".format(path=flask.request.path))
_cache.set_bypassed(cache_key)
return f(*args, **kwargs)
# also bypass the cache if it's disabled completely
if not settings().getBoolean(["devel", "cache", "enabled"]):
logger.debug("Cache for {path} disabled, calling wrapped function".format(path=flask.request.path))
_cache.set_bypassed(cache_key)
return f(*args, **kwargs)
cache_key = key()
rv = _cache.get(cache_key)
# only take the value from the cache if we are not required to refresh it from the wrapped function
if not callable(refreshif) or not refreshif():
rv = _cache.get(cache_key)
if rv is not None:
logger.debug("Serving entry for {path} from cache".format(path=flask.request.path))
return rv
if rv is not None and (not callable(refreshif) or not refreshif(rv)):
logger.debug("Serving entry for {path} from cache".format(path=flask.request.path))
if not "X-From-Cache" in rv.headers:
rv.headers["X-From-Cache"] = "true"
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} (key: {key}), bypassed".format(path=flask.request.path, key=cache_key))
_cache.set_bypassed(cache_key)
return rv
# store it in the cache
_cache.set(cache_key, rv, timeout=timeout)
@@ -253,9 +593,270 @@ def cached(timeout=5 * 60, key=lambda: "view/%s" % flask.request.path, unless=No
return decorator
def is_in_cache(key=lambda: "view:%s" % flask.request.path):
if callable(key):
key = key()
return key in _cache
def is_cache_bypassed(key=lambda: "view:%s" % flask.request.path):
if callable(key):
key = key()
return _cache.is_bypassed(key)
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
class PreemptiveCache(object):
def __init__(self, cachefile):
self.cachefile = cachefile
self._lock = threading.RLock()
self._logger = logging.getLogger(__name__ + "." + self.__class__.__name__)
def record(self, data, unless=None, root=None):
if callable(unless) and unless():
return
entry_data = data
if callable(entry_data):
entry_data = entry_data()
if entry_data is not None:
if root is None:
from flask import request
root = request.path
self.add_data(root, entry_data)
def has_record(self, data, root=None):
if callable(data):
data = data()
if data is None:
return False
if root is None:
from flask import request
root = request.path
all_data = self.get_data(root)
for existing in all_data:
if self._compare_data(data, existing):
return True
return False
def clean_all_data(self, cleanup_function):
assert callable(cleanup_function)
with self._lock:
all_data = self.get_all_data()
for root, entries in all_data.items():
old_count = len(entries)
entries = cleanup_function(root, entries)
if not entries:
del all_data[root]
self._logger.debug("Removed root {} from preemptive cache".format(root))
elif len(entries) < old_count:
all_data[root] = entries
self._logger.debug("Removed {} entries from preemptive cache for root {}".format(old_count - len(entries), root))
self.set_all_data(all_data)
return all_data
def get_all_data(self):
import yaml
cache_data = None
with self._lock:
try:
with open(self.cachefile, "r") as f:
cache_data = yaml.safe_load(f)
except IOError as e:
import errno
if e.errno != errno.ENOENT:
raise
except:
self._logger.exception("Error while reading {}".format(self.cachefile))
if cache_data is None:
cache_data = dict()
return cache_data
def get_data(self, root):
cache_data = self.get_all_data()
return cache_data.get(root, dict())
def set_all_data(self, data):
from octoprint.util import atomic_write
import yaml
with self._lock:
try:
with atomic_write(self.cachefile, "wb", max_permissions=0o666) as handle:
yaml.safe_dump(data, handle,default_flow_style=False, indent=" ", allow_unicode=True)
except:
self._logger.exception("Error while writing {}".format(self.cachefile))
def set_data(self, root, data):
with self._lock:
all_data = self.get_all_data()
all_data[root] = data
self.set_all_data(all_data)
def add_data(self, root, data):
def split_matched_and_unmatched(entry, entries):
matched = []
unmatched = []
for e in entries:
if self._compare_data(e, entry):
matched.append(e)
else:
unmatched.append(e)
return matched, unmatched
with self._lock:
cache_data = self.get_all_data()
if not root in cache_data:
cache_data[root] = []
existing, other = split_matched_and_unmatched(data, cache_data[root])
def get_newest(entries):
result = None
for entry in entries:
if "_timestamp" in entry and (result is None or ("_timestamp" in entry and result["_timestamp"] < entry["_timestamp"])):
result = entry
return result
to_persist = get_newest(existing)
if not to_persist:
import copy
to_persist = copy.deepcopy(data)
to_persist["_timestamp"] = time.time()
to_persist["_count"] = 1
self._logger.info("Adding entry for {} and {!r}".format(root, to_persist))
else:
to_persist["_timestamp"] = time.time()
to_persist["_count"] = to_persist.get("_count", 0) + 1
self._logger.debug("Updating timestamp and counter for {} and {!r}".format(root, data))
self.set_data(root, [to_persist] + other)
def _compare_data(self, a, b):
from octoprint.util import dict_filter
def strip_ignored(d):
return dict_filter(d, lambda k, v: not k.startswith("_"))
return set(strip_ignored(a).items()) == set(strip_ignored(b).items())
def preemptively_cached(cache, data, unless=None):
def decorator(f):
@functools.wraps(f)
def decorated_function(*args, **kwargs):
cache.record(data, unless=unless)
return f(*args, **kwargs)
return decorated_function
return decorator
def etagged(etag):
def decorator(f):
@functools.wraps(f)
def decorated_function(*args, **kwargs):
rv = f(*args, **kwargs)
if isinstance(rv, flask.Response):
result = etag
if callable(result):
result = result(rv)
if result:
rv.set_etag(result)
return rv
return decorated_function
return decorator
def lastmodified(date):
def decorator(f):
@functools.wraps(f)
def decorated_function(*args, **kwargs):
rv = f(*args, **kwargs)
if not "Last-Modified" in rv.headers:
result = date
if callable(result):
result = result(rv)
if not isinstance(result, basestring):
from werkzeug.http import http_date
result = http_date(result)
if result:
rv.headers["Last-Modified"] = result
return rv
return decorated_function
return decorator
def conditional(condition, met):
def decorator(f):
@functools.wraps(f)
def decorated_function(*args, **kwargs):
if callable(condition) and condition():
# condition has been met, return met-response
rv = met
if callable(met):
rv = met()
return rv
# condition hasn't been met, call decorated function
return f(*args, **kwargs)
return decorated_function
return decorator
def check_etag(etag):
return flask.request.method in ("GET", "HEAD") and \
flask.request.if_none_match and \
etag in flask.request.if_none_match
def check_lastmodified(lastmodified):
return flask.request.method in ("GET", "HEAD") and \
flask.request.if_modified_since and \
lastmodified >= flask.request.if_modified_since
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
@@ -354,7 +955,7 @@ def restricted_access(func):
@functools.wraps(func)
def decorated_view(*args, **kwargs):
# if OctoPrint hasn't been set up yet, abort
if settings().getBoolean(["server", "firstRun"]) and (octoprint.server.userManager is None or not octoprint.server.userManager.hasBeenCustomized()):
if settings().getBoolean(["server", "firstRun"]) and settings().getBoolean(["accessControl", "enabled"]) and (octoprint.server.userManager is None or not octoprint.server.userManager.hasBeenCustomized()):
return flask.make_response("OctoPrint isn't setup yet", 403)
apikey = octoprint.server.util.get_api_key(flask.request)
@@ -454,7 +1055,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
@@ -532,10 +1134,8 @@ class SettingsCheckUpdater(webassets.updater.BaseUpdater):
cache_value = webassets.utils.hash_func(json.dumps(settings().effective_yaml))
ctx.cache.set(cache_key, cache_value)
##~~ plugin assets collector
def collect_plugin_assets(enable_gcodeviewer=True, enable_timelapse=True, preferred_stylesheet="css"):
supported_stylesheets = ("css", "less")
##~~ core assets collector
def collect_core_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
assets = dict(
js=[],
css=[],
@@ -555,9 +1155,11 @@ 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'
'js/app/viewmodels/usersettings.js',
'js/app/viewmodels/about.js'
]
if enable_gcodeviewer:
assets["js"] += [
@@ -566,33 +1168,63 @@ 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')
elif preferred_stylesheet == "css":
assets["css"].append('css/octoprint.css')
return assets
##~~ plugin assets collector
def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
logger = logging.getLogger(__name__ + ".collect_plugin_assets")
supported_stylesheets = ("css", "less")
assets = dict(bundled=dict(js=[], css=[], less=[]),
external=dict(js=[], css=[], less=[]))
asset_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.AssetPlugin)
for implementation in asset_plugins:
name = implementation._identifier
all_assets = implementation.get_assets()
is_bundled = implementation._plugin_info.bundled
asset_key = "bundled" if is_bundled else "external"
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"]:
assets["js"].append('plugin/{name}/{asset}'.format(**locals()))
if not asset_exists("js", asset):
continue
assets[asset_key]["js"].append('plugin/{name}/{asset}'.format(**locals()))
if preferred_stylesheet in all_assets:
for asset in all_assets[preferred_stylesheet]:
assets[preferred_stylesheet].append('plugin/{name}/{asset}'.format(**locals()))
if not asset_exists(preferred_stylesheet, asset):
continue
assets[asset_key][preferred_stylesheet].append('plugin/{name}/{asset}'.format(**locals()))
else:
for stylesheet in supported_stylesheets:
if not stylesheet in all_assets:
continue
for asset in all_assets[stylesheet]:
assets[stylesheet].append('plugin/{name}/{asset}'.format(**locals()))
if not asset_exists(stylesheet, asset):
continue
assets[asset_key][stylesheet].append('plugin/{name}/{asset}'.format(**locals()))
break
return assets
+61 -9
View File
@@ -12,6 +12,9 @@ import time
import octoprint.timelapse
import octoprint.server
import octoprint.events
import octoprint.plugin
from octoprint.events import Events
import octoprint.printer
@@ -39,6 +42,12 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.
self._remoteAddress = None
self._throttleFactor = 1
self._lastCurrent = 0
self._baseRateLimit = 0.5
self._emit_mutex = threading.RLock()
def _getRemoteAddress(self, info):
forwardedFor = info.headers.get("X-Forwarded-For")
if forwardedFor is not None:
@@ -59,24 +68,41 @@ 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)
octoprint.timelapse.registerCallback(self)
octoprint.timelapse.register_callback(self)
self._pluginManager.register_message_receiver(self.on_plugin_message)
self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": self._remoteAddress})
for event in octoprint.events.all_events():
self._eventManager.subscribe(event, self._onEvent)
octoprint.timelapse.notifyCallbacks(octoprint.timelapse.current)
octoprint.timelapse.notify_callbacks(octoprint.timelapse.current)
# This is a horrible hack for now to allow displaying a notification that a render job is still
# active in the backend on a fresh connect of a client. This needs to be substituted with a proper
# job management for timelapse rendering, analysis stuff etc that also gets cancelled when prints
# start and so on.
#
# For now this is the easiest way though to at least inform the user that a timelapse is still ongoing.
#
# TODO remove when central job management becomes available and takes care of this for us
if octoprint.timelapse.current_render_job is not None:
self._emit("event", {"type": Events.MOVIE_RENDERING, "payload": octoprint.timelapse.current_render_job})
def on_close(self):
self._logger.info("Client connection closed: %s" % self._remoteAddress)
self._printer.unregister_callback(self)
self._fileManager.unregister_slicingprogress_callback(self)
octoprint.timelapse.unregisterCallback(self)
octoprint.timelapse.unregister_callback(self)
self._pluginManager.unregister_message_receiver(self.on_plugin_message)
self._eventManager.fire(Events.CLIENT_CLOSED, {"remoteAddress": self._remoteAddress})
@@ -84,9 +110,31 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.
self._eventManager.unsubscribe(event, self._onEvent)
def on_message(self, message):
pass
try:
import json
message = json.loads(message)
except:
self._logger.warn("Invalid JSON received from client {}, ignoring: {!r}".format(self._remoteAddress, message))
return
if "throttle" in message:
try:
throttle = int(message["throttle"])
if throttle < 1:
raise ValueError()
except ValueError:
self._logger.warn("Got invalid throttle factor from client {}, ignoring: {!r}".format(self._remoteAddress, message["throttle"]))
else:
self._throttleFactor = throttle
self._logger.debug("Set throttle factor for client {} to {}".format(self._remoteAddress, self._throttleFactor))
def on_printer_send_current_data(self, data):
# make sure we rate limit the updates according to our throttle factor
now = time.time()
if now < self._lastCurrent + self._baseRateLimit * self._throttleFactor:
return
self._lastCurrent = now
# add current temperature, log and message backlogs to sent data
with self._temperatureBacklogMutex:
temperatures = self._temperatureBacklog
@@ -151,7 +199,11 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.
self.sendEvent(event, payload)
def _emit(self, type, payload):
try:
self.send({type: payload})
except Exception as e:
self._logger.warn("Could not send message to client %s: %s" % (self._remoteAddress, str(e)))
with self._emit_mutex:
try:
self.send({type: payload})
except Exception as e:
if self._logger.isEnabledFor(logging.DEBUG):
self._logger.exception("Could not send message to client {}".format(self._remoteAddress))
else:
self._logger.warn("Could not send message to client {}: {}".format(self._remoteAddress, e))
+151 -17
View File
@@ -104,18 +104,22 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
true
------WebKitFormBoundarypYiSUx63abAmhT5C
Content-Disposition: form-data; name="file.path"
Content-Type: text/plain; charset=utf-8
/tmp/tmpzupkro
------WebKitFormBoundarypYiSUx63abAmhT5C
Content-Disposition: form-data; name="file.name"
Content-Type: text/plain; charset=utf-8
test.gcode
------WebKitFormBoundarypYiSUx63abAmhT5C
Content-Disposition: form-data; name="file.content_type"
Content-Type: text/plain; charset=utf-8
application/octet-stream
------WebKitFormBoundarypYiSUx63abAmhT5C
Content-Disposition: form-data; name="file.size"
Content-Type: text/plain; charset=utf-8
349182
------WebKitFormBoundarypYiSUx63abAmhT5C--
@@ -141,6 +145,9 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
if suffix_type in self._suffixes and suffix is not None:
self._suffixes[suffix_type] = suffix
# multipart boundary
self._multipart_boundary = None
# Parts, files and values will be stored here
self._parts = dict()
self._files = []
@@ -177,7 +184,7 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
if self.is_multipart():
if not self._bytes_left:
# we don't support requests without a content-length
raise tornado.web.HTTPError(400, reason="No Content-Length supplied")
raise tornado.web.HTTPError(400, log_message="No Content-Length supplied")
# extract the multipart boundary
fields = self._content_type.split(";")
@@ -190,7 +197,14 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
self._multipart_boundary = tornado.escape.utf8(v)
break
else:
self._multipart_boundary = None
# RFC2046 section 5.1 (as referred to from RFC 7578) defines the boundary
# parameter as mandatory for multipart requests:
#
# The only mandatory global parameter for the "multipart" media type is
# the boundary parameter, which consists of 1 to 70 characters [...]
#
# So no boundary? 400 Bad Request
raise tornado.web.HTTPError(400, log_message="No multipart boundary supplied")
else:
self._fallback(self.request, b"")
self._finished = True
@@ -245,7 +259,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)
@@ -272,9 +286,19 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
header = header[header_check:]
# convert to dict
header = tornado.httputil.HTTPHeaders.parse(header.decode("utf-8"))
try:
header = tornado.httputil.HTTPHeaders.parse(header.decode("utf-8"))
except UnicodeDecodeError:
try:
header = tornado.httputil.HTTPHeaders.parse(header.decode("iso-8859-1"))
except:
# looks like we couldn't decode something here neither as UTF-8 nor ISO-8859-1
self._logger.warn("Could not decode multipart headers in request, should be either UTF-8 or ISO-8859-1")
self.send_error(400)
return
disp_header = header.get("Content-Disposition", "")
disposition, disp_params = tornado.httputil._parse_header(disp_header)
disposition, disp_params = _parse_header(disp_header, strip_quotes=False)
if disposition != "form-data":
self._logger.warn("Got a multipart header without form-data content disposition, ignoring that one")
@@ -283,7 +307,22 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
self._logger.warn("Got a multipart header without name, ignoring that one")
return
self._current_part = self._on_part_start(disp_params["name"], header.get("Content-Type", None), filename=disp_params["filename"] if "filename" in disp_params else None)
filename = disp_params.get("filename*", None) # RFC 5987 header present?
if filename is not None:
try:
filename = _extended_header_value(filename)
except:
# parse error, this is not RFC 5987 compliant after all
self._logger.warn("extended filename* value {!r} is not RFC 5987 compliant".format(filename))
self.send_error(400)
return
else:
# no filename* header, just strip quotes from filename header then and be done
filename = _strip_value_quotes(disp_params.get("filename", None))
self._current_part = self._on_part_start(_strip_value_quotes(disp_params["name"]),
header.get("Content-Type", None),
filename=filename)
def _on_part_start(self, name, content_type, filename=None):
"""
@@ -322,7 +361,7 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
file=handle)
else:
return dict(name=tornado.escape.utf8(name), content_type=content_type, data=b"")
return dict(name=tornado.escape.utf8(name), content_type=tornado.escape.utf8(content_type), data=b"")
def _on_part_data(self, part, data):
"""
@@ -357,16 +396,28 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
"""
self._new_body = b""
for name, part in self._parts.iteritems():
for name, part in self._parts.items():
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())
for n, p in fields.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.items())
for n, p in fields.items():
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"Content-Type: text/plain; charset=utf-8\r\n"
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"]
@@ -419,6 +470,47 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
options = _handle_method
def _parse_header(line, strip_quotes=True):
parts = tornado.httputil._parseparam(';' + line)
key = next(parts)
pdict = {}
for p in parts:
i = p.find('=')
if i >= 0:
name = p[:i].strip().lower()
value = p[i + 1:].strip()
if strip_quotes:
value = _strip_value_quotes(value)
pdict[name] = value
return key, pdict
def _strip_value_quotes(value):
if not value:
return value
if len(value) >= 2 and value[0] == value[-1] == '"':
value = value[1:-1]
value = value.replace('\\\\', '\\').replace('\\"', '"')
return value
def _extended_header_value(value):
if not value:
return value
if value.lower().startswith("iso-8859-1'") or value.lower().startswith("utf-8'"):
# RFC 5987 section 3.2
from urllib import unquote
encoding, _, value = value.split("'", 2)
return unquote(octoprint.util.to_str(value, encoding="iso-8859-1")).decode(encoding)
else:
# no encoding provided, strip potentially present quotes and call it a day
return octoprint.util.to_unicode(_strip_value_quotes(value), encoding="utf-8")
class WsgiInputContainer(object):
"""
A WSGI container for use with Tornado that allows supplying the request body to be used for ``wsgi.input`` in the
@@ -506,7 +598,7 @@ class WsgiInputContainer(object):
# determine the request_body to supply as wsgi.input
if body is not None:
if isinstance(body, (bytes, str)):
if isinstance(body, (bytes, str, unicode)):
request_body = io.BytesIO(tornado.escape.utf8(body))
else:
request_body = body
@@ -757,6 +849,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 +859,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 +888,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 +915,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 +925,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 +975,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)
@@ -887,6 +1008,19 @@ class UrlForwardHandler(tornado.web.RequestHandler):
return "%s%s" % (self._basename, extension)
class StaticDataHandler(tornado.web.RequestHandler):
def initialize(self, data="", content_type="text/plain"):
self.data = data
self.content_type = content_type
def get(self, *args, **kwargs):
self.set_status(200)
self.set_header("Content-Type", self.content_type)
self.write(self.data)
self.flush()
self.finish()
#~~ Factory method for creating Flask access validation wrappers from the Tornado request context
@@ -924,4 +1058,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)
+344 -80
View File
@@ -6,30 +6,102 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import os
import datetime
from collections import defaultdict
from flask import request, g, url_for, make_response, render_template, send_from_directory, redirect
from flask import request, g, url_for, make_response, render_template, send_from_directory, redirect, abort
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, preemptiveCache, \
NOT_MODIFIED
from octoprint.settings import settings
from octoprint.filemanager import get_all_extensions
import re
import base64
from . import util
import logging
_logger = logging.getLogger(__name__)
@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))
def index():
_valid_id_re = re.compile("[a-z_]+")
_valid_div_re = re.compile("[a-zA-Z_-]+")
def _preemptive_unless(base_url=None):
if base_url is None:
base_url = request.url_root
cache_disabled = not settings().getBoolean(["devel", "cache", "preemptive"]) \
or base_url in settings().get(["server", "preemptiveCache", "exceptions"]) \
or not (base_url.startswith("http://") or base_url.startswith("https://"))
recording_disabled = request.headers.get("X-Preemptive-Record", "yes") == "no"
return cache_disabled or recording_disabled
def _preemptive_data(path=None, base_url=None):
if path is None:
path = request.path
if base_url is None:
base_url = request.url_root
return dict(path=path,
base_url=base_url,
query_string="l10n={}".format(g.locale.language) if g.locale else "en")
def _cache_key(url=None, locale=None):
if url is None:
url = request.base_url
if locale is None:
locale = g.locale.language if g.locale else "en"
return "view:{}:{}".format(url, locale)
@app.route("/cached.gif")
def in_cache():
url = request.base_url.replace("/cached.gif", "/")
path = request.path.replace("/cached.gif", "/")
key = _cache_key(url)
data = _preemptive_data(path=path)
response = make_response(bytes(base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")))
response.headers["Content-Type"] = "image/gif"
if _preemptive_unless(base_url=url) or not preemptiveCache.has_record(data, root=path):
_logger.info("Preemptive cache not active for path {} and data {!r}, signaling as cached".format(path, data))
return response
elif util.flask.is_in_cache(key):
_logger.info("Found path {} in cache (key: {}), signaling as cached".format(path, key))
return response
elif util.flask.is_cache_bypassed(key):
_logger.info("Path {} was bypassed from cache (key: {}), signaling as cached".format(path, key))
return response
else:
_logger.debug("Path {} not yet cached (key: {}), signaling as missing".format(path, key))
return abort(404)
@app.route("/")
@util.flask.preemptively_cached(cache=preemptiveCache,
data=_preemptive_data,
unless=_preemptive_unless)
@util.flask.conditional(lambda: _check_etag_and_lastmodified_for_index(), NOT_MODIFIED)
@util.flask.cached(timeout=-1,
refreshif=lambda cached: _validate_cache_for_index(cached),
key=_cache_key,
unless_response=lambda response: util.flask.cache_check_response_headers(response))
@util.flask.etagged(lambda _: _compute_etag_for_index())
@util.flask.lastmodified(lambda _: _compute_date_for_index())
def index():
#~~ a bunch of settings
enable_gcodeviewer = settings().getBoolean(["gcodeViewer", "enabled"])
enable_timelapse = (settings().get(["webcam", "snapshot"]) and settings().get(["webcam", "ffmpeg"]))
enable_systemmenu = settings().get(["system"]) is not None and settings().get(["system", "actions"]) is not None and len(settings().get(["system", "actions"])) > 0
enable_accesscontrol = userManager is not None
enable_systemmenu = settings().get(["system"]) is not None and settings().get(["system", "actions"]) is not None
enable_accesscontrol = userManager.enabled
preferred_stylesheet = settings().get(["devel", "stylesheet"])
locales = dict((l.language, dict(language=l.language, display=l.display_name, english=l.english_name)) for l in LOCALES)
@@ -44,6 +116,7 @@ def index():
tab=dict(div=lambda x: "tab_plugin_" + x, template=lambda x: x + "_tab.jinja2", to_entry=lambda data: (data["name"], data)),
settings=dict(div=lambda x: "settings_plugin_" + x, template=lambda x: x + "_settings.jinja2", to_entry=lambda data: (data["name"], data)),
usersettings=dict(div=lambda x: "usersettings_plugin_" + x, template=lambda x: x + "_usersettings.jinja2", to_entry=lambda data: (data["name"], data)),
about=dict(div=lambda x: "about_plugin_" + x, template=lambda x: x + "_about.jinja2", to_entry=lambda data: (data["name"], data)),
generic=dict(template=lambda x: x + ".jinja2", to_entry=lambda data: data)
)
@@ -54,6 +127,7 @@ def index():
tab=dict(add="append", key="name"),
settings=dict(add="custom_append", key="name", custom_add_entries=lambda missing: dict(section_plugins=(gettext("Plugins"), None)), custom_add_order=lambda missing: ["section_plugins"] + missing),
usersettings=dict(add="append", key="name"),
about=dict(add="append", key="name"),
generic=dict(add="append", key=None)
)
@@ -109,7 +183,7 @@ def index():
# sidebar
templates["sidebar"]["entries"]= dict(
connection=(gettext("Connection"), dict(template="sidebar/connection.jinja2", _div="connection", icon="signal", styles_wrapper=["display: none"], data_bind="visible: loginState.isAdmin")),
connection=(gettext("Connection"), dict(template="sidebar/connection.jinja2", _div="connection", icon="signal", styles_wrapper=["display: none"], data_bind="visible: loginState.isUser")),
state=(gettext("State"), dict(template="sidebar/state.jinja2", _div="state", icon="info-sign")),
files=(gettext("Files"), dict(template="sidebar/files.jinja2", _div="files", icon="list", classes_content=["overflow_visible"], template_header="sidebar/files_header.jinja2"))
)
@@ -148,6 +222,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))
@@ -160,6 +235,17 @@ def index():
interface=(gettext("Interface"), dict(template="dialogs/usersettings/interface.jinja2", _div="usersettings_interface", custom_bindings=False)),
)
# about dialog
templates["about"]["entries"] = dict(
about=("About OctoPrint", dict(template="dialogs/about/about.jinja2", _div="about_about", custom_bindings=False)),
license=("OctoPrint License", dict(template="dialogs/about/license.jinja2", _div="about_license", custom_bindings=False)),
thirdparty=("Third Party Licenses", dict(template="dialogs/about/thirdparty.jinja2", _div="about_thirdparty", custom_bindings=False)),
authors=("Authors", dict(template="dialogs/about/authors.jinja2", _div="about_authors", custom_bindings=False)),
changelog=("Changelog", dict(template="dialogs/about/changelog.jinja2", _div="about_changelog", custom_bindings=False)),
supporters=("Supporters", dict(template="dialogs/about/supporters.jinja2", _div="about_sponsors", custom_bindings=False))
)
# extract data from template plugins
template_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin)
@@ -170,17 +256,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 +313,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,30 +351,40 @@ def index():
#~~ prepare full set of template vars for rendering
now = datetime.datetime.utcnow()
first_run = settings().getBoolean(["server", "firstRun"]) and userManager.enabled and not userManager.hasBeenCustomized()
render_kwargs = dict(
webcamStream=settings().get(["webcam", "stream"]),
enableTemperatureGraph=settings().get(["feature", "temperatureGraph"]),
enableAccessControl=userManager is not None,
enableAccessControl=userManager.enabled,
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,
templates=templates,
pluginNames=plugin_names,
locales=locales
locales=locales,
now=now,
supportedExtensions=map(lambda ext: ".{}".format(ext), get_all_extensions())
)
render_kwargs.update(plugin_vars)
#~~ render!
return render_template(
response = make_response(render_template(
"index.jinja2",
**render_kwargs
)
))
if first_run:
response = util.flask.add_non_caching_response_headers(response)
return response
def _process_template_configs(name, implementation, configs, rules):
@@ -302,11 +423,14 @@ 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))
return includes
def _process_template_config(name, implementation, rule, config=None, counter=1):
if "mandatory" in rule:
for mandatory in rule["mandatory"]:
@@ -326,6 +450,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 +464,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
@@ -345,76 +473,23 @@ def _process_template_config(name, implementation, rule, config=None, counter=1)
return data
@app.route("/robots.txt")
@util.flask.cached(timeout=-1)
def robotsTxt():
return send_from_directory(app.static_folder, "robots.txt")
@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.conditional(lambda: _check_etag_and_lastmodified_for_i18n(), NOT_MODIFIED)
@util.flask.etagged(lambda _: _compute_etag_for_i18n(request.view_args["locale"], request.view_args["domain"]))
@util.flask.lastmodified(lambda _: _compute_date_for_i18n(request.view_args["locale"], request.view_args["domain"]))
def localeJs(locale, domain):
messages = dict()
plural_expr = None
if locale != "en":
from flask import _request_ctx_stack
from babel.messages.pofile import read_po
def messages_from_po(base_path, locale, domain):
path = os.path.join(base_path, locale)
if not os.path.isdir(path):
return None, None
path = os.path.join(path, "LC_MESSAGES", "{domain}.po".format(**locals()))
if not os.path.isfile(path):
return None, None
messages = dict()
with file(path) as f:
catalog = read_po(f, locale=locale, domain=domain)
for message in catalog:
message_id = message.id
if isinstance(message_id, (list, tuple)):
message_id = message_id[0]
messages[message_id] = message.string
return messages, catalog.plural_expr
user_base_path = os.path.join(settings().getBaseFolder("translations"))
user_plugin_path = os.path.join(user_base_path, "_plugins")
# plugin translations
plugins = octoprint.plugin.plugin_manager().enabled_plugins
for name, plugin in plugins.items():
dirs = [os.path.join(user_plugin_path, name), os.path.join(plugin.location, 'translations')]
for dirname in dirs:
if not os.path.isdir(dirname):
continue
plugin_messages, _ = messages_from_po(dirname, locale, domain)
if plugin_messages is not None:
messages = octoprint.util.dict_merge(messages, plugin_messages)
_logger.debug("Using translation folder {dirname} for locale {locale} of plugin {name}".format(**locals()))
break
else:
_logger.debug("No translations for locale {locale} for plugin {name}".format(**locals()))
# core translations
ctx = _request_ctx_stack.top
base_path = os.path.join(ctx.app.root_path, "translations")
dirs = [user_base_path, base_path]
for dirname in dirs:
core_messages, plural_expr = messages_from_po(dirname, locale, domain)
if core_messages is not None:
messages = octoprint.util.dict_merge(messages, core_messages)
_logger.debug("Using translation folder {dirname} for locale {locale} of core translations".format(**locals()))
break
else:
_logger.debug("No core translations for locale {locale}".format(**locals()))
messages, plural_expr = _get_translations(locale, domain)
catalog = dict(
messages=messages,
@@ -432,3 +507,192 @@ def plugin_assets(name, filename):
return redirect(url_for("plugin." + name + ".static", filename=filename))
def _compute_etag_for_index(files=None, lastmodified=None):
if files is None:
files = _files_for_index()
if lastmodified is None:
lastmodified = _compute_date(files)
if lastmodified and not isinstance(lastmodified, basestring):
from werkzeug.http import http_date
lastmodified = http_date(lastmodified)
from octoprint import __version__
from octoprint.server import UI_API_KEY
import hashlib
hash = hashlib.sha1()
hash.update(__version__)
hash.update(UI_API_KEY)
hash.update(",".join(sorted(files)))
if lastmodified:
hash.update(lastmodified)
return hash.hexdigest()
def _compute_etag_for_i18n(locale, domain, files=None, lastmodified=None):
if files is None:
files = _get_all_translationfiles(locale, domain)
if lastmodified is None:
lastmodified = _compute_date(files)
if lastmodified and not isinstance(lastmodified, basestring):
from werkzeug.http import http_date
lastmodified = http_date(lastmodified)
import hashlib
hash = hashlib.sha1()
hash.update(",".join(sorted(files)))
if lastmodified:
hash.update(lastmodified)
return hash.hexdigest()
def _compute_date_for_i18n(locale, domain):
return _compute_date(_get_all_translationfiles(locale, domain))
def _compute_date_for_index():
return _compute_date(_files_for_index())
def _validate_cache_for_index(cached):
no_cache_headers = util.flask.cache_check_headers()
refresh_flag = "_refresh" in request.values
etag_different = _compute_etag_for_index() != cached.get_etag()[0]
return no_cache_headers or refresh_flag or etag_different
def _files_for_index():
"""
Collects all paths of files that the index page depends on.
The relevant files are:
* all jinja2 templates: they might be used within the index page, so
any changes here change the rendering outcome
* all defined assets: if one of them changes, the webassets bundle will
be regenerated and hence the URL included in the cached page won't be
valid anymore
* all translation files used for our current locale: if any of those change
we also need to re-render
"""
templates = _get_all_templates()
assets = _get_all_assets()
translations = _get_all_translationfiles(g.locale.language if g.locale else "en", "messages")
return sorted(set(templates + assets + translations))
def _compute_date(files):
from datetime import datetime
timestamps = map(lambda path: os.stat(path).st_mtime, files) + [0] if files else []
max_timestamp = max(*timestamps) if timestamps else None
if max_timestamp:
# we set the micros to 0 since microseconds are not speced for HTTP
max_timestamp = datetime.fromtimestamp(max_timestamp).replace(microsecond=0)
return max_timestamp
def _check_etag_and_lastmodified_for_index():
files = _files_for_index()
lastmodified = _compute_date(files)
lastmodified_ok = util.flask.check_lastmodified(lastmodified)
etag_ok = util.flask.check_etag(_compute_etag_for_index(files, lastmodified))
return etag_ok and lastmodified_ok
def _check_etag_and_lastmodified_for_i18n():
locale = request.view_args["locale"]
domain = request.view_args["domain"]
etag_ok = util.flask.check_etag(_compute_etag_for_i18n(request.view_args["locale"], request.view_args["domain"]))
lastmodified = _compute_date_for_i18n(locale, domain)
lastmodified_ok = lastmodified is None or util.flask.check_lastmodified(lastmodified)
return etag_ok and lastmodified_ok
def _get_all_templates():
from octoprint.util.jinja import get_all_template_paths
return get_all_template_paths(app.jinja_loader)
def _get_all_assets():
from octoprint.util.jinja import get_all_asset_paths
return get_all_asset_paths(app.jinja_env.assets_environment)
def _get_all_translationfiles(locale, domain):
from flask import _request_ctx_stack
def get_po_path(basedir, locale, domain):
path = os.path.join(basedir, locale)
if not os.path.isdir(path):
return None
path = os.path.join(path, "LC_MESSAGES", "{domain}.po".format(**locals()))
if not os.path.isfile(path):
return None
return path
po_files = []
user_base_path = os.path.join(settings().getBaseFolder("translations"))
user_plugin_path = os.path.join(user_base_path, "_plugins")
# plugin translations
plugins = octoprint.plugin.plugin_manager().enabled_plugins
for name, plugin in plugins.items():
dirs = [os.path.join(user_plugin_path, name), os.path.join(plugin.location, 'translations')]
for dirname in dirs:
if not os.path.isdir(dirname):
continue
po_file = get_po_path(dirname, locale, domain)
if po_file:
po_files.append(po_file)
break
# core translations
ctx = _request_ctx_stack.top
base_path = os.path.join(ctx.app.root_path, "translations")
dirs = [user_base_path, base_path]
for dirname in dirs:
po_file = get_po_path(dirname, locale, domain)
if po_file:
po_files.append(po_file)
break
return po_files
def _get_translations(locale, domain):
from babel.messages.pofile import read_po
from octoprint.util import dict_merge
messages = dict()
plural_expr = None
def messages_from_po(path, locale, domain):
messages = dict()
with file(path) as f:
catalog = read_po(f, locale=locale, domain=domain)
for message in catalog:
message_id = message.id
if isinstance(message_id, (list, tuple)):
message_id = message_id[0]
messages[message_id] = message.string
return messages, catalog.plural_expr
po_files = _get_all_translationfiles(locale, domain)
for po_file in po_files:
po_messages, plural_expr = messages_from_po(po_file, locale, domain)
if po_messages is not None:
messages = dict_merge(messages, po_messages)
return messages, plural_expr
+172 -55
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
@@ -44,7 +46,7 @@ def settings(init=False, basedir=None, configfile=None):
(False, default). If this is set to True and the plugin manager has already been initialized, a :class:`ValueError`
will be raised. The same will happen if the plugin manager has not yet been initialized and this is set to
False.
basedir (str): Path of the base directoy for all of OctoPrint's settings, log files, uploads etc. If not set
basedir (str): Path of the base directory for all of OctoPrint's settings, log files, uploads etc. If not set
the default will be used: ``~/.octoprint`` on Linux, ``%APPDATA%/OctoPrint`` on Windows and
``~/Library/Application Support/OctoPrint`` on MacOS.
configfile (str): Path of the configuration file (``config.yaml``) to work on. If not set the default will
@@ -82,8 +84,23 @@ default_settings = {
"temperature": 5,
"sdStatus": 1
},
"maxCommunicationTimeouts": {
"idle": 2,
"printing": 5,
"long": 5
},
"maxWritePasses": 5,
"additionalPorts": [],
"longRunningCommands": ["G4", "G28", "G29", "G30", "G32"]
"longRunningCommands": ["G4", "G28", "G29", "G30", "G32", "M400", "M226"],
"checksumRequiringCommands": ["M110"],
"helloCommand": "M110 N0",
"disconnectOnErrors": True,
"ignoreErrorsFromFirmware": False,
"logResends": True,
"supportResendsWithoutOk": False,
# command specific flags
"triggerOkForM29": True
},
"server": {
"host": "0.0.0.0",
@@ -91,12 +108,16 @@ default_settings = {
"firstRun": True,
"secretKey": None,
"reverseProxy": {
"prefixHeader": "X-Script-Name",
"schemeHeader": "X-Scheme",
"hostHeader": "X-Forwarded-Host",
"prefixFallback": "",
"schemeFallback": "",
"hostFallback": ""
"prefixHeader": None,
"schemeHeader": None,
"hostHeader": None,
"serverHeader": None,
"portHeader": None,
"prefixFallback": None,
"schemeFallback": None,
"hostFallback": None,
"serverFallback": None,
"portFallback": None
},
"uploads": {
"maxSize": 1 * 1024 * 1024 * 1024, # 1GB
@@ -104,6 +125,19 @@ 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
},
"preemptiveCache": {
"exceptions": [],
"until": 7
}
},
"webcam": {
"stream": None,
@@ -120,7 +154,8 @@ default_settings = {
"options": {},
"postRoll": 0,
"fps": 25
}
},
"cleanTmpAfterDays": 7
},
"gcodeViewer": {
"enabled": True,
@@ -137,12 +172,16 @@ default_settings = {
"sendChecksumWithUnknownCommands": False,
"unknownCommandsNeedAck": False,
"sdSupport": True,
"sdRelativePath": False,
"sdAlwaysAvailable": False,
"swallowOkAfterResend": True,
"repetierTargetTemp": False,
"externalHeatupDetection": True,
"supportWait": True,
"keyboardControl": True
"keyboardControl": True,
"pollWatched": False,
"ignoreIdenticalResends": False,
"identicalResendsCountdown": 7
},
"folder": {
"uploads": None,
@@ -181,15 +220,16 @@ default_settings = {
"defaultLanguage": "_default",
"components": {
"order": {
"navbar": ["settings", "systemmenu", "login"],
"navbar": ["settings", "systemmenu", "login", "plugin_announcements"],
"sidebar": ["connection", "state", "files"],
"tab": ["temperature", "control", "gcodeviewer", "terminal", "timelapse"],
"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", "plugin_announcements"
],
"usersettings": ["access", "interface"],
"about": ["about", "supporters", "authors", "changelog", "license", "thirdparty", "plugin_pluginmanager"],
"generic": []
},
"disabled": {
@@ -239,16 +279,27 @@ 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 %}"
}
}
},
"estimation": {
"printTime": {
"statsWeighingUntil": 0.5,
"validityRange": 0.15,
"forceDumbFromPercent": 0.3,
"forceDumbAfterMin": 30,
"stableThreshold": 60
}
},
"devel": {
"stylesheet": "css",
"cache": {
"enabled": True
"enabled": True,
"preemptive": True
},
"webassets": {
"minify": False,
@@ -262,6 +313,7 @@ default_settings = {
"okWithLinenumber": False,
"numExtruders": 1,
"includeCurrentToolInTemps": True,
"includeFilenameInOpened": True,
"movementSpeed": {
"x": 6000,
"y": 6000,
@@ -270,6 +322,7 @@ default_settings = {
},
"hasBed": True,
"repetierStyleTargetTemperature": False,
"repetierStyleResends": False,
"okBeforeCommandOutput": False,
"smoothieTemperatureReporting": False,
"extendedSdFileList": False,
@@ -279,7 +332,10 @@ default_settings = {
"txBuffer": 40,
"commandBuffer": 4,
"sendWait": True,
"waitInterval": 1.0
"waitInterval": 1.0,
"supportM112": True,
"echoOnM117": True,
"brokenM29": True
}
}
}
@@ -288,6 +344,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 +381,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 +445,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 +539,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):
@@ -599,6 +666,7 @@ class Settings(object):
printer_parameters = self._config["printerParameters"]
if "movementSpeed" in printer_parameters or "invertAxes" in printer_parameters:
dirty = True
default_profile["axes"] = dict(x=dict(), y=dict(), z=dict(), e=dict())
if "movementSpeed" in printer_parameters:
for axis in ("x", "y", "z", "e"):
@@ -612,6 +680,7 @@ class Settings(object):
del self._config["printerParameters"]["invertedAxes"]
if "numExtruders" in printer_parameters or "extruderOffsets" in printer_parameters:
dirty = True
if not "extruder" in default_profile:
default_profile["extruder"] = dict()
@@ -627,6 +696,7 @@ class Settings(object):
del self._config["printerParameters"]["extruderOffsets"]
if "bedDimensions" in printer_parameters:
dirty = True
bed_dimensions = printer_parameters["bedDimensions"]
if not "volume" in default_profile:
default_profile["volume"] = dict()
@@ -643,8 +713,6 @@ class Settings(object):
default_profile["volume"]["depth"] = bed_dimensions["y"]
del self._config["printerParameters"]["bedDimensions"]
dirty = True
if dirty:
if not "printerProfiles" in self._config:
self._config["printerProfiles"] = dict()
@@ -773,11 +841,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", permissions=0o600, max_permissions=0o666) 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 +862,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
@@ -805,14 +879,14 @@ class Settings(object):
while len(path) > 1:
key = path.pop(0)
if key in config and key in defaults:
if key in config:
config = config[key]
defaults = defaults[key]
defaults = defaults.get(key, dict())
elif incl_defaults and key in defaults:
config = {}
defaults = defaults[key]
else:
return None
raise NoSuchSettingsPath()
if preprocessors and isinstance(preprocessors, dict) and key in preprocessors:
preprocessors = preprocessors[key]
@@ -836,7 +910,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 +928,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 +965,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 +976,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 +1030,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 +1086,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 +1104,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 +1117,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 +1147,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", max_permissions=0o666) as f:
f.write(script)
def _default_basedir(applicationName):
+35 -7
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
@@ -398,7 +407,18 @@ class SlicingManager(object):
profile.description = description
path = self.get_profile_path(slicer, name)
is_overwrite = os.path.exists(path)
if is_overwrite and not allow_overwrite:
raise ProfileAlreadyExists(slicer, profile.name)
self._save_profile_to_path(slicer, path, profile, overrides=overrides, allow_overwrite=allow_overwrite)
payload = dict(slicer=slicer,
profile=name)
event = octoprint.events.Events.SLICING_PROFILE_MODIFIED if is_overwrite else octoprint.events.Events.SLICING_PROFILE_ADDED
octoprint.events.eventManager().fire(event, payload)
return profile
def _temporary_profile(self, slicer, name=None, overrides=None):
@@ -427,6 +447,7 @@ class SlicingManager(object):
Raises:
~octoprint.slicing.exceptions.UnknownSlicer: The slicer ``slicer`` is unknown.
~octoprint.slicing.exceptions.CouldNotDeleteProfile: There was an error while deleting the profile.
"""
if not slicer in self.registered_slicers:
@@ -436,10 +457,17 @@ class SlicingManager(object):
raise ValueError("name must be set")
try:
path = self.get_profile_path(slicer, name, must_exist=True)
except UnknownProfile:
return
os.remove(path)
try:
path = self.get_profile_path(slicer, name, must_exist=True)
except UnknownProfile:
return
os.remove(path)
except ProfileException as e:
raise e
except Exception as e:
raise CouldNotDeleteProfile(slicer, name, cause=e)
else:
octoprint.events.eventManager().fire(octoprint.events.Events.SLICING_PROFILE_DELETED, dict(slicer=slicer, profile=name))
def all_profiles(self, slicer, require_configured=False):
"""
@@ -470,7 +498,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 +559,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)
+13
View File
@@ -105,3 +105,16 @@ class ProfileAlreadyExists(ProfileException):
def __init__(self, slicer, profile, *args, **kwargs):
ProfileException.__init__(self, slicer, profile, *args, **kwargs)
self.message = "Profile {profile} for slicer {slicer} already exists".format(profile=profile, slicer=slicer)
class CouldNotDeleteProfile(ProfileException):
"""
Raised if there is an unexpected error trying to delete a known profile.
"""
def __init__(self, slicer, profile, cause=None, *args, **kwargs):
ProfileException.__init__(self, slicer, profile, *args, **kwargs)
self.cause = cause
if cause:
self.message = "Could not delete profile {profile} for slicer {slicer}: {cause}".format(profile=profile, slicer=slicer, cause=str(cause))
else:
self.message = "Could not delete profile {profile} for slicer {slicer}".format(profile=profile, slicer=slicer)
+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,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
@@ -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;
+13 -6
View File
@@ -104,8 +104,11 @@ GCODE.ui = (function(){
if(!Modernizr.webworkers)fatal.push("<li>Your browser doesn't seem to support HTML5 Web Workers, this application won't work without it.</li>");
if(!Modernizr.svg)fatal.push("<li>Your browser doesn't seem to support HTML5 SVG, this application won't work without it.</li>");
var errorList = document.getElementById("errorList");
if(fatal.length>0){
document.getElementById('errorList').innerHTML = '<ul>' + fatal.join('') + '</ul>';
if (errorList) {
errorList.innerHTML = '<ul>' + fatal.join('') + '</ul>';
}
console.log("Initialization failed: unsupported browser.")
return false;
}
@@ -117,8 +120,10 @@ GCODE.ui = (function(){
if(!Modernizr.draganddrop)warnings.push("<li>Your browser doesn't seem to support HTML5 Drag'n'Drop, Drop area will not work.</li>");
if(warnings.length>0){
document.getElementById('errorList').innerHTML = '<ul>' + wanings.join('') + '</ul>';
console.log("Initialization succeeded with warnings.")
if (errorList) {
errorList.innerHTML = '<ul>' + warnings.join('') + '</ul>';
}
console.log("Initialization succeeded with warnings.", warnings);
}
return true;
};
@@ -138,12 +143,12 @@ GCODE.ui = (function(){
init: function(options){
if (options) setOptions(options);
if (!options.container) {
return;
return false;
}
var capabilitiesResult = checkCapabilities();
if (!capabilitiesResult) {
return;
return false;
}
setProgress("", 0);
@@ -159,6 +164,8 @@ GCODE.ui = (function(){
toolOffsets: options.toolOffsets
});
GCODE.renderer.render(0, 0);
return true;
},
clear: function() {
@@ -196,4 +203,4 @@ GCODE.ui = (function(){
switchCommands(layerNum, first, last);
}
}
}());
}());
+259
View File
@@ -0,0 +1,259 @@
<html>
<head>
<title>OctoPrint is still starting</title>
<style>
body {
margin: 0;
font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 20px;
color: #333333;
background-color: #ffffff;
}
#startup-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 10000;
display: block;
}
.background {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.wrapper {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.wrapper .outer {
display: table;
width: 100%;
height: 100%;
}
.wrapper .outer .inner {
display: table-cell;
vertical-align: middle;
}
.wrapper .outer .inner .content {
text-align: center;
}
.green {
color: #169300;
}
.red {
color: #990000;
}
.pulsate3 {
-webkit-animation: pulsate 3s ease-out;
-webkit-animation-iteration-count: infinite;
opacity: 0.5;
}
.pulsate1 {
-webkit-animation: pulsate 1s ease-out;
-webkit-animation-iteration-count: infinite;
opacity: 0.5;
}
@-webkit-keyframes pulsate {
0% {
opacity: 0.5;
}
50% {
opacity: 1.0;
}
100% {
opacity: 0.5;
}
}
</style>
<script>
if (!String.prototype.endsWith) {
String.prototype.endsWith = function(searchString, position) {
var subjectString = this.toString();
if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
position = subjectString.length;
}
position -= searchString.length;
var lastIndex = subjectString.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
}
function ping(url, timeout, callback) {
var img = new Image();
var calledBack = false;
var urlToUse = url;
var postfix = "_=" + Date.now();
if (url.indexOf("?") > -1) {
urlToUse += "&" + postfix;
} else {
urlToUse += "?" + postfix;
}
console.log("Pinging " + url);
img.onload = function() {
callback("load");
calledBack = true;
};
img.onerror = function() {
if (!calledBack) {
callback("error");
calledBack = true;
}
};
img.src = urlToUse;
setTimeout(function() {
if (!calledBack) {
callback("timeout");
calledBack = true;
}
}, timeout);
}
window.onload = function() {
var intervals = [1, 1, 2, 3, 5, 8];
var timeout = 1500;
var baseUrl = window.location.href;
var currentQuery = "";
var currentFragment = "";
if (baseUrl.indexOf("#") > -1) {
currentFragment = baseUrl.substring(baseUrl.indexOf("#"));
baseUrl = baseUrl.substring(0, baseUrl.indexOf("#"));
}
if (baseUrl.indexOf("?") > -1) {
currentQuery = baseUrl.substring(baseUrl.indexOf("?"));
baseUrl = baseUrl.substring(0, baseUrl.indexOf("?"));
}
if (baseUrl.indexOf("/static") > -1) {
baseUrl = baseUrl.substring(0, baseUrl.indexOf("/static"));
}
if (baseUrl[baseUrl.length - 1] != "/") {
baseUrl += "/";
}
var indexCachedUrl = baseUrl + "cached.gif";
var serverOnlineUrl = baseUrl + "online.gif";
var backendOnlineUrl = baseUrl + "intermediary.gif";
var serverTimeout;
var cachedTimeout;
var message = window.document.getElementById("message");
var indexCached = false;
var indexCachedCallback = function(result) {
if (result == "load") {
if (indexCached) {
return;
}
// our cached.gif loaded, so the index is cached now, let's reload
indexCached = true;
message.className = "pulsate1 green";
message.innerText = "OctoPrint server ready, reloading page...";
var reloadUrl = baseUrl + currentQuery + currentFragment;
if (reloadUrl == window.location.href) {
window.location.reload(false);
} else {
window.location.href = reloadUrl;
}
} else {
// cached.gif still not available, let's look at it again in a second
cachedTimeout = setTimeout(function() {
ping(indexCachedUrl, timeout, indexCachedCallback);
}, 1000)
}
};
var serverIsOnline = false;
var serverOnlineCallback = function(result) {
if (result == "load") {
// our online.gif loaded, so the server is up, let's wait for it to become ready
serverIsOnline = true;
ping(indexCachedUrl, timeout, indexCachedCallback);
} else {
// online.gif still not available, let's look at it again later
var interval = 10;
if (intervals.length) {
interval = intervals.shift();
}
serverTimeout = setTimeout(function() {
ping(serverOnlineUrl, timeout, serverOnlineCallback);
}, interval * 1000)
}
};
var backendOfflineCounter = 0;
var backendOnlineCallback = function(result) {
if (serverIsOnline) {
return;
}
if (result == "load") {
setTimeout(function() {
ping(backendOnlineUrl, timeout, backendOnlineCallback);
}, 1000);
return;
}
backendOfflineCounter++;
if (backendOfflineCounter > 15) {
if (serverTimeout) {
window.clearTimeout(serverTimeout);
}
if (cachedTimeout) {
window.clearTimeout(cachedTimeout);
}
message.className = "red";
message.innerHTML = "Looks like something went wrong during startup, the server is gone again. You should check <code>octoprint.log</code>.";
} else {
setTimeout(function() {
ping(backendOnlineUrl, timeout, backendOnlineCallback);
}, 1000);
}
};
ping(backendOnlineUrl, timeout, backendOnlineCallback);
ping(serverOnlineUrl, timeout, serverOnlineCallback);
}
</script>
</head>
<body>
<div id="startup-overlay">
<div class="background"></div>
<div class="wrapper">
<div class="outer">
<div class="inner">
<div class="content">
<h1 id="message" class="pulsate3">OctoPrint is still starting up, please wait...</h1>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
+92 -58
View File
@@ -11,15 +11,21 @@ function DataUpdater(allViewModels) {
self._pluginHash = undefined;
self.reloadOverlay = $("#reloadui_overlay");
$("#reloadui_overlay_reload").click(function() { location.reload(true); });
self._throttleFactor = 1;
self._baseProcessingLimit = 500.0;
self._lastProcessingTimes = [];
self._lastProcessingTimesSize = 20;
self.connect = function() {
self._connectCallback = undefined;
self.connect = function(callback) {
var options = {};
if (SOCKJS_DEBUG) {
options["debug"] = true;
}
self._connectCallback = callback;
self._socket = new SockJS(SOCKJS_URI, undefined, options);
self._socket.onopen = self._onconnect;
self._socket.onclose = self._onclose;
@@ -32,6 +38,30 @@ function DataUpdater(allViewModels) {
self.connect();
};
self.increaseThrottle = function() {
self.setThrottle(self._throttleFactor + 1);
};
self.decreaseThrottle = function() {
if (self._throttleFactor <= 1) {
return;
}
self.setThrottle(self._throttleFactor - 1);
};
self.setThrottle = function(throttle) {
self._throttleFactor = throttle;
self._send("throttle", self._throttleFactor);
log.debug("DataUpdater: New SockJS throttle factor:", self._throttleFactor, " new processing limit:", self._baseProcessingLimit * self._throttleFactor);
};
self._send = function(message, data) {
var payload = {};
payload[message] = data;
self._socket.send(JSON.stringify(payload));
};
self._onconnect = function() {
self._autoReconnecting = false;
self._autoReconnectTrial = 0;
@@ -51,7 +81,8 @@ function DataUpdater(allViewModels) {
}
if (viewModel.hasOwnProperty("onServerDisconnect")) {
if (!viewModel.onServerDisconnect()) {
var result = viewModel.onServerDisconnect();
if (result !== undefined && !result) {
handled = true;
}
}
@@ -86,7 +117,8 @@ function DataUpdater(allViewModels) {
}
if (viewModel.hasOwnProperty("onServerDisconnect")) {
if (!viewModel.onServerDisconnect()) {
var result = viewModel.onServerDisconnect();
if (result !== undefined && !result) {
handled = true;
}
}
@@ -108,9 +140,7 @@ function DataUpdater(allViewModels) {
var data = e.data[prop];
var gcodeUploadProgress = $("#gcode_upload_progress");
var gcodeUploadProgressBar = $(".bar", gcodeUploadProgress);
var start = new Date().getTime();
switch (prop) {
case "connected": {
// update the current UI API key and send it with any request
@@ -122,6 +152,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;
@@ -130,7 +161,9 @@ function DataUpdater(allViewModels) {
if ($("#offline_overlay").is(":visible")) {
hideOfflineOverlay();
_.each(self.allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onDataUpdaterReconnect")) {
if (viewModel.hasOwnProperty("onServerReconnect")) {
viewModel.onServerReconnect();
} else if (viewModel.hasOwnProperty("onDataUpdaterReconnect")) {
viewModel.onDataUpdaterReconnect();
}
});
@@ -138,10 +171,25 @@ function DataUpdater(allViewModels) {
if ($('#tabs li[class="active"] a').attr("href") == "#control") {
$("#webcam_image").attr("src", CONFIG_WEBCAM_STREAM + "?" + new Date().getTime());
}
} else {
_.each(self.allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onServerConnect")) {
viewModel.onServerConnect();
}
});
}
if (oldVersion != VERSION || (oldPluginHash != undefined && oldPluginHash != self._pluginHash)) {
self.reloadOverlay.show();
showReloadOverlay();
}
self.setThrottle(1);
log.info("Connected to the server");
if (self._connectCallback) {
self._connectCallback();
self._connectCallback = undefined;
}
break;
@@ -163,8 +211,6 @@ function DataUpdater(allViewModels) {
break;
}
case "slicingProgress": {
gcodeUploadProgressBar.text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: Math.round(data["progress"])}));
_.each(self.allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onSlicingProgress")) {
viewModel.onSlicingProgress(data["slicer"], data["model_path"], data["machinecode_path"], data["progress"]);
@@ -175,56 +221,25 @@ function DataUpdater(allViewModels) {
case "event": {
var type = data["type"];
var payload = data["payload"];
var html = "";
log.debug("Got event " + type + " with payload: " + JSON.stringify(payload));
if (type == "MovieRendering") {
new PNotify({title: gettext("Rendering timelapse"), text: _.sprintf(gettext("Now rendering timelapse %(movie_basename)s"), payload)});
} else if (type == "MovieDone") {
new PNotify({title: gettext("Timelapse ready"), text: _.sprintf(gettext("New timelapse %(movie_basename)s is done rendering."), payload)});
} 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});
} else if (type == "SlicingStarted") {
gcodeUploadProgress.addClass("progress-striped").addClass("active");
gcodeUploadProgressBar.css("width", "100%");
if (payload.progressAvailable) {
gcodeUploadProgressBar.text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: 0}));
} else {
gcodeUploadProgressBar.text(gettext("Slicing ..."));
if (type == "PrintCancelled") {
if (payload.firmwareError) {
new PNotify({
title: gettext("Unhandled communication error"),
text: _.sprintf(gettext("There was an unhandled error while talking to the printer. Due to that the ongoing print job was cancelled. Error: %(firmwareError)s"), payload),
type: "error",
hide: false
});
}
} else if (type == "SlicingDone") {
gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
gcodeUploadProgressBar.css("width", "0%");
gcodeUploadProgressBar.text("");
new PNotify({title: gettext("Slicing done"), text: _.sprintf(gettext("Sliced %(stl)s to %(gcode)s, took %(time).2f seconds"), payload), type: "success"});
} else if (type == "SlicingCancelled") {
gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
gcodeUploadProgressBar.css("width", "0%");
gcodeUploadProgressBar.text("");
} else if (type == "SlicingFailed") {
gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
gcodeUploadProgressBar.css("width", "0%");
gcodeUploadProgressBar.text("");
html = _.sprintf(gettext("Could not slice %(stl)s to %(gcode)s: %(reason)s"), payload);
new PNotify({title: gettext("Slicing failed"), text: html, type: "error", hide: false});
} else if (type == "TransferStarted") {
gcodeUploadProgress.addClass("progress-striped").addClass("active");
gcodeUploadProgressBar.css("width", "100%");
gcodeUploadProgressBar.text(gettext("Streaming ..."));
} else if (type == "TransferDone") {
gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
gcodeUploadProgressBar.css("width", "0%");
gcodeUploadProgressBar.text("");
} else if (type == "Error") {
new PNotify({
title: gettext("Streaming done"),
text: _.sprintf(gettext("Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds"), payload),
type: "success"
title: gettext("Unhandled communication error"),
text: _.sprintf(gettext("There was an unhandled error while talking to the printer. Due to that OctoPrint disconnected. Error: %(error)s"), payload),
type: "error",
hide: false
});
gcodeFilesViewModel.requestData(payload.remote, "sdcard");
}
var legacyEventHandlers = {
@@ -264,8 +279,27 @@ function DataUpdater(allViewModels) {
})
}
}
var end = new Date().getTime();
var difference = end - start;
while (self._lastProcessingTimes.length >= self._lastProcessingTimesSize) {
self._lastProcessingTimes.shift();
}
self._lastProcessingTimes.push(difference);
var processingLimit = self._throttleFactor * self._baseProcessingLimit;
if (difference > processingLimit) {
self.increaseThrottle();
log.debug("We are slow (" + difference + " > " + processingLimit + "), reducing refresh rate");
} else if (self._throttleFactor > 1) {
var maxProcessingTime = Math.max.apply(null, self._lastProcessingTimes);
var lowerProcessingLimit = (self._throttleFactor - 1) * self._baseProcessingLimit;
if (maxProcessingTime < lowerProcessingLimit) {
self.decreaseThrottle();
log.debug("We are fast (" + maxProcessingTime + " < " + lowerProcessingLimit + "), increasing refresh rate");
}
}
}
};
self.connect();
}
+161 -4
View File
@@ -228,7 +228,7 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
return;
var filters = self.currentFilters();
filters.pop(filter);
filters = _.without(filters, filter);
self.currentFilters(filters);
self._saveCurrentFiltersToLocalStorage();
@@ -333,9 +333,37 @@ 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";
if (seconds < 1) return "00:00:00";
var s = seconds % 60;
var m = (seconds % 3600) / 60;
@@ -345,8 +373,7 @@ function formatDuration(seconds) {
}
function formatFuzzyEstimation(seconds, base) {
if (!seconds) return "-";
if (seconds < 0) return "-";
if (!seconds || seconds < 1) return "-";
var m;
if (base != undefined) {
@@ -359,6 +386,118 @@ function formatFuzzyEstimation(seconds, base) {
return m.fromNow(true);
}
function formatFuzzyPrintTime(totalSeconds) {
/**
* Formats a print time estimate in a very fuzzy way.
*
* Accuracy decreases the higher the estimation is:
*
* * less than 30s: "a couple of seconds"
* * 30s to a minute: "less than a minute"
* * 1 to 30min: rounded to full minutes, above 30s is minute + 1 ("27 minutes", "2 minutes")
* * 30min to 40min: "40 minutes"
* * 40min to 50min: "50 minutes"
* * 50min to 1h: "1 hour"
* * 1 to 12h: rounded to half hours, 15min to 45min is ".5", above that hour + 1 ("4 hours", "2.5 hours")
* * 12 to 24h: rounded to full hours, above 30min is hour + 1, over 23.5h is "1 day"
* * Over a day: rounded to half days, 8h to 16h is ".5", above that days + 1 ("1 day", "4 days", "2.5 days")
*/
if (!totalSeconds || totalSeconds < 1) return "-";
var d = moment.duration(totalSeconds, "seconds");
var seconds = d.seconds();
var minutes = d.minutes();
var hours = d.hours();
var days = d.asDays();
var replacements = {
days: days,
hours: hours,
minutes: minutes,
seconds: seconds,
totalSeconds: totalSeconds
};
var text = "-";
if (days >= 1) {
// days
if (hours >= 16) {
replacements.days += 1;
text = gettext("%(days)d days");
} else if (hours >= 8 && hours < 16) {
text = gettext("%(days)d.5 days");
} else {
if (days == 1) {
text = gettext("%(days)d day");
} else {
text = gettext("%(days)d days");
}
}
} else if (hours >= 1) {
// only hours
if (hours < 12) {
if (minutes < 15) {
// less than .15 => .0
if (hours == 1) {
text = gettext("%(hours)d hour");
} else {
text = gettext("%(hours)d hours");
}
} else if (minutes >= 15 && minutes < 45) {
// between .25 and .75 => .5
text = gettext("%(hours)d.5 hours");
} else {
// over .75 => hours + 1
replacements.hours += 1;
text = gettext("%(hours)d hours");
}
} else {
if (hours == 23 && minutes > 30) {
// over 23.5 hours => 1 day
text = gettext("1 day");
} else {
if (minutes > 30) {
// over .5 => hours + 1
replacements.hours += 1;
}
text = gettext("%(hours)d hours");
}
}
} else if (minutes >= 1) {
// only minutes
if (minutes < 2) {
if (seconds < 30) {
text = gettext("a minute");
} else {
text = gettext("2 minutes");
}
} else if (minutes < 30) {
if (seconds > 30) {
replacements.minutes += 1;
}
text = gettext("%(minutes)d minutes");
} else if (minutes <= 40) {
text = gettext("40 minutes");
} else if (minutes <= 50) {
text = gettext("50 minutes");
} else {
text = gettext("1 hour");
}
} else {
// only seconds
if (seconds < 30) {
text = gettext("a couple of seconds");
} else {
text = gettext("less than a minute");
}
}
return _.sprintf(text, replacements);
}
function formatDate(unixTimestamp) {
if (!unixTimestamp) return "-";
return moment.unix(unixTimestamp).format(gettext(/* L10N: Date format */ "YYYY-MM-DD HH:mm"));
@@ -448,6 +587,10 @@ function showConfirmationDialog(message, onacknowledge) {
confirmationDialog.modal("show");
}
function showReloadOverlay() {
$("#reloadui_overlay").show();
}
function commentableLinesToArray(lines) {
return splitTextToArray(lines, "\n", true, function(item) {return !_.startsWith(item, "#")});
}
@@ -461,3 +604,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);
}
}
})
};
Loaded 100 of 191 files, more files were not shown because too many files have changed in this diff. Show more