Compare commits

..
173 Commits
Author SHA1 Message Date
Gina Häußge 1d0657a8eb Preparing release of 1.2.18 2016-11-30 11:24:50 +01:00
Gina Häußge ec04364b47 Preparing release of 1.2.18rc1 2016-11-22 12:47:29 +01:00
Gina Häußge a88cd9fcfc Copy settings in on_settings_load so we don't mutate them 2016-11-21 13:44:26 +01:00
Gina Häußge 59e4394cdd Allow type specific default values for restricted settings
See #1567
2016-11-21 13:43:53 +01:00
Gina Häußge bc82a18a03 Merge branch 'rc/maintenance' into maintenance 2016-11-08 15:25:05 +01:00
Gina Häußge 6976ac9edd Preparing release of 1.2.17 2016-11-08 11:31:16 +01:00
Gina Häußge 2952b2622e Do not hiccup on ipv6 addresses in the HTTP Host header
Fixed port extraction. Now supports hostname, hostname + port,
ipv4, ipv4 + port, ipv6, ipv6 + port

Fixes #1571
2016-11-07 16:17:16 +01:00
Gina Häußge 7efdeced62 Merge branch 'rc/maintenance' into maintenance 2016-10-17 14:23:43 +02: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 696904bc49 Support M1{09|90} R<temp> in virtual printer too 2016-10-17 10:41:39 +02:00
Gina Häußge cd578dc2e1 Checking M109/M190 for R should actually check for R and not S
Thanks @FHeilmann
2016-10-17 10:29:16 +02:00
Gina Häußge e15956883a Add support for R parameter in M109/M190 2016-10-14 18:19:08 +02:00
Gina Häußge 3f8dde75d5 Persist settings after changing default printer profile
Fixes #1541
2016-10-14 16:23:47 +02:00
Gina Häußge bc5044b125 Fix target temperature propagation from comm layer
When setting the tracked target temperature from a sent temperature
command, the changes in tracked temperature were not propagated
from the comm layer to registered callbacks.

But since the standard printer also didn't make a copy of the mutable
dict of tool temperatures, those were in fact updated even without
propagation in the printer implementation when the values in the
comm layer got updated, whereas the bed temperature - an immutable
tupel - was not.

Two wrongs sometimes do in fact make a right. In this case that led
to target temperature changes on the tools immediately reflecting
in printer.get_current_temperatures after the command was sent,
but changes to the bed target taking until the next M105 response
to propagate.

Decoupling the data structures and adding propagation commands
to the comm layer solves this issue.

Fixes #1543
2016-10-14 16:01:03 +02:00
Gina Häußge c863562d12 Limit cura profile importer to .ini files and clarified support again 2016-10-14 11:58:39 +02:00
Gina Häußge 27fb397681 ffmpeg: Only modify the -framerate parameter for setting video fps
-r only allows a limited set of target framerates according to the mpeg2
 standard, but -framerate allows to specify how long each frame should
 be shown, giving us full control over "virtual" fps without causing errors
 when the user selects a non-standard frame rate
2016-10-13 19:23:15 +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
91 changed files with 7161 additions and 2441 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
+32 -13
View File
@@ -1,27 +1,41 @@
Please read the "guidelines for contributing" that are linked ^-- just
up there. Also read the FAQ: https://github.com/foosel/OctoPrint/wiki/FAQ.
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). Mark requests with
a [Request] prefix in the title please. Fully fill out the bug reporting
template for bug reports.
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.]
[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?
@@ -29,7 +43,7 @@ with which to reproduce the problem.]
#### Branch & Commit or Version of OctoPrint
[Can be found in the lower left corner of the web interface.]
[Can be found in the lower left corner of the web interface. ALWAYS INCLUDE.]
#### Printer model & used firmware incl. version
@@ -41,12 +55,17 @@ with which to reproduce the problem.]
#### Link to octoprint.log
[On gist.github.com or pastebin.com. Always include and never truncate.]
[On gist.github.com or pastebin.com. ALWAYS INCLUDE and never truncate.]
#### 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.]
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
+6 -6
View File
@@ -7,20 +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, prerelease and rc shall not use the lookup table, only tags
# master and rc shall not use the lookup table, only tags
master
rc/.*
prerelease
rc
# neither should disconnected checkouts, e.g. 'git checkout <tag>'
HEAD
\(detached.*
# maintenance is currently the branch for preparation of maintenance release 1.2.13
# maintenance is currently the branch for preparation of maintenance release 1.2.17
# so are any fix/... and improve/... branches
maintenance 1.2.13 685ce16c85eea9c4f11586ea99c9a84aca382bd4 pep440-dev
fix/.* 1.2.13 685ce16c85eea9c4f11586ea99c9a84aca382bd4 pep440-dev
improve/.* 1.2.13 685ce16c85eea9c4f11586ea99c9a84aca382bd4 pep440-dev
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 198d3450d94be1a2 pep440-dev
+1
View File
@@ -61,6 +61,7 @@ date of first contribution):
* ["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
+137 -1
View File
@@ -1,12 +1,148 @@
# OctoPrint Changelog
## 1.2.18 (2016-11-30)
### Improvements
* Allow arbitrary frame rates for creating timelapses. Before, the entered fps value was also directly used as frame rate for the actual video, which could cause problems with any frame rates not specified in the MPEG2 standard. Now OctoPrint will use a standard frame rate for the rendered video and render the timelapse stills into the finished movie with the configured frame rate.
* Limited Cura profile importer to `.ini` files and clarified the supported versions
* Add support for the `R` parameter for `M109` and `M190`
### Bug fixes
* [#1541](https://github.com/foosel/OctoPrint/issues/1541) - Fix selecting the printer profile to use by default
* [#1543](https://github.com/foosel/OctoPrint/issues/1543) - Fix target temperature propagation from communication layer
* [#1567](https://github.com/foosel/OctoPrint/issues/1567) - Fix issue with restricted settings getting parsed to the wrong data structure in the frontend if loaded anonymously first.
* [#1571](https://github.com/foosel/OctoPrint/issues/1571) - Fix parsing of port number from HTTP Host header for IPv6 addresses
* Fix issue with settings restriction causing internal settings defaults to be changed.
### More information
* [Commits](https://github.com/foosel/OctoPrint/compare/1.2.17...1.2.18)
* Release Candidates:
* [1.2.18rc1](https://github.com/foosel/OctoPrint/releases/tag/1.2.18rc1)
## 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 looking staying uninitialized until a connection to a printer was established.
* 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))
+44 -29
View File
@@ -63,10 +63,11 @@ available for the maintainers to directly start tackling that problem.
## How to file a bug report
If you encounter an issue with OctoPrint, you are welcome to
[submit a bug report](https://goo.gl/GzkGv9).
[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*. Thank you! :)
following section *completely* and also follow the instructions in the
"new issue" form. Thank you! :)
### What should I do before submitting a bug report?
@@ -85,7 +86,7 @@ following section *completely*. Thank you! :)
might have installed**. Report any issues with those in their corresponding
bug tracker (probably linked to from the plugin's homepage).
Finally, **this is also not the right issue tracker if you are running an
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.
@@ -123,17 +124,21 @@ following section *completely*. Thank you! :)
### What should I include in a bug report?
Always use the following template (you can remove what's within `[...]`, that's
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.]
[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?
@@ -141,7 +146,7 @@ only provided here as some additional information for you), **even if only addin
#### Branch & Commit or Version of OctoPrint
[Can be found in the lower left corner of the web interface.]
[Can be found in the lower left corner of the web interface. ALWAYS INCLUDE.]
#### Printer model & used firmware incl. version
@@ -153,12 +158,17 @@ only provided here as some additional information for you), **even if only addin
#### Link to octoprint.log
[On gist.github.com or pastebin.com. Always include and never truncate.]
[On gist.github.com or pastebin.com. ALWAYS INCLUDE and never truncate.]
#### 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.]
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
@@ -171,7 +181,8 @@ only provided here as some additional information for you), **even if only addin
I have read the FAQ.
Copy-paste this template **completely**. Do not skip any lines!
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?
@@ -195,15 +206,16 @@ more information is needed.
One is contained in the **"Terminal" tab** within OctoPrint's UI and is a log
of the last 300 lines of communication with the printer. Please copy-paste
this somewhere (disable auto scroll to make copying the contents easier) -
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. Please
copy-paste this to pastebin or gist as well and include a link in your bug
`~/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
@@ -299,14 +311,9 @@ 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>`
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`).
* `prerelease`: This branch is only used during the short period where a
future release has "graduated" from the `maintenance` branch and is already
tagged, but still marked on Github as a pre-release. This is mostly used for
update testing just before new releases. Version number follows the scheme
`x.y.z` (e.g. `1.2.9`), just like the `master` branch.
* `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
@@ -314,7 +321,7 @@ There are three main branches in OctoPrint:
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`
`<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
@@ -322,8 +329,16 @@ There are three main branches in OctoPrint:
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 an OctoPrint version
of `x.y.z` (e.g. `1.3.0.dev123`).
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:
@@ -334,9 +349,6 @@ Those usually have one of the following prefixes:
`maintenance` and `devel` branches.
* `dev/...` or `feature/...`: New functionality under development that is to be merged
into the `devel` branch.
* `rc`: A branch similar in nature to the `prerelease` branch, only that it will be
used to provide current release candidates of the next stable version to be derived
from 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.
@@ -376,6 +388,9 @@ the local version identifier to allow for an exact determination of the active c
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
+2 -4
View File
@@ -4,8 +4,6 @@ recursive-include src/octoprint/plugins *
recursive-include src/octoprint/translations *
include versioneer.py
include src/octoprint/_version.py
include AUTHORS.md
include CHANGELOG.md
include LICENSE
include README.md
include requirements.txt
include *.md
exclude CONTRIBUTING.md
+8 -16
View File
@@ -1,5 +1,4 @@
OctoPrint
=========
# OctoPrint
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).
@@ -22,8 +21,7 @@ might be of more interest for you. You might also want to subscribe to [the mail
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
------------
## 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
@@ -31,15 +29,14 @@ 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 as it is about OctoPrint or its documentation the way it is, please help
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
Installation instructions for installing from source for different operating
systems can be found [on the wiki](https://github.com/foosel/OctoPrint/wiki#assorted-guides).
@@ -66,8 +63,7 @@ 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
------------
## Dependencies
OctoPrint depends on a couple of python modules to do its job. Those are automatically installed when installing
OctoPrint via `setup.py`:
@@ -78,8 +74,7 @@ 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 via
@@ -118,8 +113,7 @@ 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
@@ -130,9 +124,7 @@ A comprehensive overview of all available configuration settings can be found
Please note that the most commonly used configuration settings can also easily
be edited from OctoPrint's settings dialog.
Special Thanks
--------------
## Special Thanks
The development of OctoPrint is sponsored and maintained by [BQ](http://www.bq.com/).
Cross-browser testing services are kindly provided by [BrowserStack](http://www.browserstack.com/).
Profiling is done with the help of [PyVmMonitor](http://www.pyvmmonitor.com).
+30 -23
View File
@@ -1,4 +1,4 @@
# Supporters
# Supporters
Development of this version of OctoPrint wouldn't have been possible without
[financial support by the community](http://octoprint.org/support-octoprint/) -
@@ -7,60 +7,67 @@ thanks to everyone who contributed!
## Patreon Patrons
* 3D Moniak
* alephobjects
* Aleph Objects, Inc.
* Andrew Moorby
* Arnljot Arntsen
* Aurelio Bernal Ramírez
* Aurelio Bernal
* Bart Zudell
* Boris Hussein
* Brad Jackson
* Brad Mooneyham
* Brent Fiegle
* Brian E. Tyler
* Charles Mitchell
* Christopher Day
* Christian Petropolis
* COLLE+McVOY
* CreativeTools
* COLLE+McVOY
* CreativeTools
* D Brian Kimmel
* DeltaMaker 3D Printers
* Doug Johnson
* E3D BigBox
* Erik de Bruijn
* Ernesto Martinez
* Exovite
* Exovite
* Frank Sander
* georgeroblesjr
* Gregor Luetolf
* Gary Deen
* Gary N McKinney
* George Robles
* J. Eckert
* Jason Galarneau
* Joe Korzeniewski
* Joshua Gregory
* Josh Daniels
* Joshua David Gregory
* Kaile Riser
* Kale Stedman
* Kevin Freeheart
* Kyle Gress
* Kazuhiro Ogura
* Lamin Kivelä
* M Khorakiwala
* Makespace Madrid
* Mark Lane
* Mark Qvist
* Mark Walker
* Masayoshi Mitsui
* Michael McDargh
* Miguel Angel Salmeron
* Mikey
* Michael Aumock
* Michael McDargh Sr
* Miles Flavel
* Mohammed Khorakiwala
* Noe Ruiz
* Paul Generes
* Patrick McGinnis
* Peter Grace
* Peter Schmehl
* PRINT3Dforum.com
* Robert Gusek
* Roger Strolz
* Roy Cortes
* Samer Najia
* SD3D
* SD3D
* SeeMeCNC
* Shane Ekerbicer
* Simon
* Simon Hallam
* Stefan Krister
* stefi davis
* Stephane Schittly
* Steven Pearson
* Sven Mueller
* Terrance Shaw
* Thomas Hatley
* Thomas Sanladerer
* Trent Shumay
and 734 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
and 989 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
+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
=====================
+67 -9
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.
@@ -50,6 +71,23 @@ 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
@@ -77,14 +115,15 @@ Issue a job command
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
@@ -94,7 +133,26 @@ Issue a job command
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
@@ -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...
+116 -3
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
@@ -629,8 +705,24 @@ Use the following settings to configure the serial connection to the printer:
# 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
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:
@@ -725,6 +817,27 @@ Use the following settings to configure the server:
# Command to shut down the system OctoPrint is running on, defaults to being unset
systemShutdownCommand: sudo shutdown -h now
# 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::
+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.
+24 -24
View File
@@ -15,26 +15,26 @@ 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.1",
"PyYAML==3.10",
"Flask-Login==0.2.2",
"Flask-Principal==0.3.5",
"Flask-Babel==0.9",
"Flask-Assets==0.10",
"Flask-Markdown==0.3",
"pyserial==2.7",
"netaddr==0.7.17",
"watchdog==0.8.3",
"sarge==0.1.4",
"netifaces==0.10",
"pylru==1.0.9",
"rsa==3.2",
"pkginfo==1.2.1",
"requests==2.7.0",
"semantic_version==2.4.2",
"psutil==3.2.1",
"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"
]
@@ -44,12 +44,12 @@ 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",
@@ -59,7 +59,7 @@ EXTRA_REQUIRES = dict(
# Dependencies for developing OctoPrint plugins
plugins=[
"cookiecutter"
"cookiecutter>=1.4,<1.5"
]
)
+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
+4 -4
View File
@@ -212,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):
@@ -284,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)
@@ -427,7 +427,7 @@ class FileManager(object):
pos=pos,
date=time.time())
try:
with atomic_write(self._recovery_file) as f:
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))
+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():
+50 -9
View File
@@ -10,6 +10,7 @@ import logging
import os
import pylru
import tempfile
import shutil
import octoprint.filemanager
@@ -313,7 +314,7 @@ class LocalFileStorage(StorageInterface):
from slugify import Slugify
self._slugify = Slugify()
self._slugify.safe_chars = "-_.() "
self._slugify.safe_chars = "-_.()[] "
self._old_metadata = None
self._initialize_metadata()
@@ -390,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)
@@ -398,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)
@@ -415,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)
@@ -623,7 +624,11 @@ class LocalFileStorage(StorageInterface):
if "/" in name or "\\" in name:
raise ValueError("name must not contain / or \\")
return self._slugify(name).replace(" ", "_")
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):
"""
@@ -631,8 +636,11 @@ class LocalFileStorage(StorageInterface):
relative path elements (e.g. ``..``) and sanitizes folder names using :func:`sanitize_name`. Final path is the
absolute path including leading ``basefolder`` path.
"""
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:
@@ -642,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)
@@ -881,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()
@@ -895,6 +930,12 @@ class LocalFileStorage(StorageInterface):
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)
@@ -912,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)
@@ -927,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",
+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()
+1
View File
@@ -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),
))
+122 -2
View File
@@ -819,11 +819,68 @@ 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 either the provided
default value (if one was provided), an empty dictionary (as fallback for restricted dictionaries), an
empty list (as fallback for restricted lists) or ``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
"""
data = self._settings.get_all_data()
from flask.ext.login import current_user
import copy
data = copy.deepcopy(self._settings.get_all_data(merged=True))
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]
default_value_available = False
default_value = None
if isinstance(key, (list, tuple)):
# key, default_value tuple
key, default_value = key
default_value_available = True
if key in node:
if default_value_available:
if callable(default_value):
default_value = default_value()
node[key] = default_value
else:
if isinstance(node[key], dict):
node[key] = dict()
elif isinstance(node[key], (list, tuple)):
node[key] = []
else:
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):
@@ -886,6 +943,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
@@ -1067,6 +1178,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.
@@ -1075,7 +1193,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):
+6 -3
View File
@@ -46,7 +46,8 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
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)
@@ -166,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):
@@ -389,7 +392,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
def _save_profile(self, path, profile, allow_overwrite=True):
import yaml
with octoprint.util.atomic_write(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):
@@ -77,7 +77,7 @@
<div class="input-prepend">
<span class="btn fileinput-button">
<span>{{ _('Browse...') }}</span>
<input id="settings-cura-import" type="file" name="file" data-url="{{ url_for("plugin.cura.import_cura_profile") }}">
<input id="settings-cura-import" type="file" name="file" data-url="{{ url_for("plugin.cura.import_cura_profile") }}" accept=".ini">
</span>
<span class="add-on" data-bind="text: fileName"></span>
</div>
@@ -111,10 +111,10 @@
</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.
You can import your existing profile <code>.ini</code> files from <strong>Cura 15.04.x or older</strong>
here. Anything but those are <strong>not supported</strong>. That especiallymeans that <code>.json</code>
profiles from Cura 15.06.x and <code>.curaprofile</code> profiles from Cura 2.x will not work, and neither
will custom Cura profile formats that third party tools like e.g. Repetier create.
{% endtrans %}</small>
</div>
<div class="modal-footer">
@@ -65,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)
+145 -18
View File
@@ -18,7 +18,7 @@ from . import version_checks, updaters, exceptions, util
from octoprint.server.util.flask import restricted_access
from octoprint.server import admin_permission, VERSION, REVISION
from octoprint.server import admin_permission, VERSION, REVISION, BRANCH
from octoprint.util import dict_merge
import octoprint.settings
@@ -129,7 +129,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
octoprint_version = get_versions()["version"]
self._version_cache["__version"] = octoprint_version
with atomic_write(self._version_cache_path) as file_obj:
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)
self._version_cache_dirty = False
@@ -138,14 +138,18 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
#~~ 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")]
},
},
"pip_command": None,
@@ -159,6 +163,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
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"]:
@@ -168,15 +175,40 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
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):
for key in self.get_settings_defaults():
if key == "checks" or key == "cache_ttl" or key == "octoprint_checkout_folder" or key == "octoprint_type":
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])
@@ -191,6 +223,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
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(
@@ -198,7 +235,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
octoprint=dict(
type=update_type,
checkout_folder=checkout_folder,
update_folder=update_folder
update_folder=update_folder,
prerelease=prerelease,
prerelease_channel=prerelease_channel
)
)
))
@@ -214,6 +253,17 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
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 4
@@ -346,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)
@@ -593,6 +644,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
# one of our updates requires a restart of either type "octoprint" or "environment". Let's see if
# we can actually perform that
restart_command = None
if restart_type == "octoprint":
restart_command = self._settings.global_get(["server", "commands", "serverRestartCommand"])
elif restart_type == "environment":
@@ -700,18 +752,70 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
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"):
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):
@@ -737,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__":
@@ -21,14 +21,14 @@ $(function() {
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 = [
{"key": "github_release", "name": gettext("Release")},
{"key": "git_commit", "name": gettext("Commit")}
];
self.config_availableCheckTypes = ko.observableArray([]);
self.config_availableReleaseChannels = ko.observableArray([]);
self.reloadOverlay = $("#reloadui_overlay");
@@ -97,7 +97,8 @@ $(function() {
softwareupdate: {
cache_ttl: parseInt(self.config_cacheTtl()),
octoprint_checkout_folder: self.config_checkoutFolder(),
octoprint_type: self.config_checkType()
octoprint_type: self.config_checkType(),
octoprint_release_channel: self.config_releaseChannel()
}
}
};
@@ -109,9 +110,28 @@ $(function() {
};
self._copyConfig = function() {
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) {
@@ -145,7 +165,7 @@ $(function() {
var octoprint = data.information["octoprint"];
if (octoprint && octoprint.hasOwnProperty("check")) {
var check = octoprint.check;
if (BRANCH != "master" && check["type"] == "github_release") {
if (check["released_version"] === false && check["type"] == "github_release") {
self.octoprintUnreleased(true);
} else {
self.octoprintUnreleased(false);
@@ -153,8 +173,8 @@ $(function() {
var checkoutFolder = (check["checkout_folder"] || "").trim();
var updateFolder = (check["update_folder"] || "").trim();
var checkType = check["type"] || "";
if ((checkType == "github_release" || checkType == "git_commit") && checkoutFolder == "" && updateFolder == "") {
var needsFolder = check["update_script"] || false;
if (needsFolder && checkoutFolder == "" && updateFolder == "") {
self.octoprintUnconfigured(true);
} else {
self.octoprintUnconfigured(false);
@@ -342,7 +362,7 @@ $(function() {
};
self.confirmUpdate = function() {
self.confirmationDialog.hide();
self.confirmationDialog.modal("hide");
self.performUpdate(self.forceUpdate,
_.map(self.availableAndPossible(), function(info) { return info.key }));
};
@@ -74,18 +74,25 @@
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="control-group">
<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_checkoutFolder">
</div>
</div>
<div class="control-group">
<div class="control-group" data-bind="visible: config_availableCheckTypes().length > 0">
<label class="control-label">{{ _('OctoPrint version tracking') }}</label>
<div class="controls">
<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">
<label class="control-label">{{ _('Version cache TTL') }}</label>
<div class="controls">
@@ -33,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 = ""
@@ -56,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)
@@ -14,7 +14,69 @@ 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))
@@ -27,36 +89,55 @@ def _get_latest_release(user, repo, include_prerelease=False):
releases = r.json()
# sanitize
required_fields = {"name", "tag_name", "html_url", "draft", "prerelease", "published_at"}
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)
# filter out prereleases and drafts
if include_prerelease:
releases = filter(lambda rel: not rel["draft"], releases)
else:
releases = filter(lambda rel: not rel["prerelease"] and not rel["draft"],
releases)
comparable_factory = _get_comparable_factory(compare_type,
force_base=force_base)
sort_key = lambda release: comparable_factory(_get_sanitized_version(release["tag_name"]))
if not releases:
return nothing
# sort by date
comp = lambda a, b: cmp(a.get("published_at", None), b["published_at"])
releases = sorted(releases, cmp=comp)
# latest release = last in list
latest = releases[-1]
return latest["name"], latest["tag_name"], latest.get("html_url", None)
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
@@ -65,12 +146,7 @@ def _get_comparable_version_pkg_resources(version_string, force_base=True):
if force_base:
if isinstance(version, tuple):
# old setuptools
base_version = []
for part in version:
if part.startswith("*"):
break
base_version.append(part)
version = tuple(base_version)
version = _get_base_from_version_tuple(version)
else:
# new setuptools
version = pkg_resources.parse_version(version.base_version)
@@ -90,32 +166,66 @@ def _get_comparable_version_semantic(version_string, force_base=True):
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:
return lambda version: version
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":
local_version = _get_comparable_version_pkg_resources(sanitized_local, force_base=force_base)
remote_version = _get_comparable_version_pkg_resources(sanitized_remote, force_base=force_base)
return local_version >= remote_version
elif compare_type == "semantic":
local_version = _get_comparable_version_semantic(sanitized_local, force_base=force_base)
remote_version = _get_comparable_version_semantic(sanitized_remote, force_base=force_base)
return local_version >= remote_version
elif compare_type == "custom":
return custom(sanitized_local, sanitized_remote)
else:
return sanitized_local == sanitized_remote
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
@@ -127,12 +237,17 @@ def get_latest(target, check, custom_compare=None):
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, release_notes = _get_latest_release(check["user"],
check["repo"],
include_prerelease=include_prerelease)
compare_type = check["release_compare"] if "release_compare" in check else "python"
compare_type,
include_prerelease=include_prerelease,
prerelease_channel=prerelease_channel,
force_base=force_base)
information =dict(
local=dict(name=current, value=current),
+181 -77
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"])
@@ -80,6 +82,8 @@ class VirtualPrinter():
self._incoming_lock = threading.RLock()
self._debug_awol = False
self._debug_sleep = None
self._sleepAfterNext = dict()
self._sleepAfter = dict()
@@ -95,19 +99,37 @@ class VirtualPrinter():
self._triggerResendWithTimeoutAt105 = True
self._triggeredResendWithTimeoutAt105 = False
waitThread = threading.Thread(target=self._sendWaitAfterTimeout)
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):
@@ -117,17 +139,26 @@ class VirtualPrinter():
def _processIncoming(self):
next_wait_timeout = time.time() + self._waitInterval
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:
@@ -149,7 +180,7 @@ class VirtualPrinter():
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
@@ -195,7 +226,7 @@ class VirtualPrinter():
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())
@@ -206,10 +237,12 @@ class VirtualPrinter():
#print "Send: %s" % (data.rstrip())
if 'M104' in data or 'M109' in data:
self._parseHotendCommand(data)
wait = support_r = 'M109' in data
self._parseHotendCommand(data, wait=wait, support_r=support_r)
if 'M140' in data or 'M190' in data:
self._parseBedCommand(data)
wait = support_r = 'M190' in data
self._parseBedCommand(data, wait=wait, support_r=support_r)
if 'M105' in data:
self._processTemperatureQuery()
@@ -219,7 +252,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:
@@ -257,18 +290,18 @@ class VirtualPrinter():
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
if self._echoOnM117:
self.outgoing.put("echo:%s" % re.search("M117\s+(.*)", data).group(1))
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:
@@ -316,12 +349,14 @@ 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:
@@ -332,7 +367,7 @@ class VirtualPrinter():
if not self._supportM112:
return
self._killed = True
self.outgoing.put("echo:EMERGENCY SHUTDOWN DETECTED. KILLED.")
self._output("echo:EMERGENCY SHUTDOWN DETECTED. KILLED.")
def _triggerResend(self, expected=None, actual=None):
with self._incoming_lock:
@@ -342,13 +377,13 @@ 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))
def request_resend():
self.outgoing.put("Resend:%d" % expected)
self.outgoing.put("ok")
self._output("Resend:%d" % expected)
self._output("ok")
if settings().getBoolean(["devel", "virtualPrinter", "repetierStyleResends"]):
request_resend()
@@ -356,11 +391,11 @@ class VirtualPrinter():
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":
@@ -370,7 +405,10 @@ class VirtualPrinter():
elif data == "drop_connection":
self._debug_drop_connection = True
elif data == "maxtemp_error":
self.outgoing.put("Error: MAXTEMP triggered!")
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)
@@ -380,28 +418,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),
@@ -413,20 +451,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:
@@ -443,9 +484,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"])
@@ -482,9 +523,10 @@ class VirtualPrinter():
if includeOk:
output = "ok " + output
self.outgoing.put(output)
self._output(output)
def _parseHotendCommand(self, line):
def _parseHotendCommand(self, line, wait=False, support_r=False):
only_wait_if_higher = True
tool = 0
toolMatch = re.search('T([0-9]+)', line)
if toolMatch:
@@ -499,23 +541,34 @@ class VirtualPrinter():
try:
self.targetTemp[tool] = float(re.search('S([0-9]+)', line).group(1))
except:
pass
if support_r:
try:
self.targetTemp[tool] = float(re.search('R([0-9]+)', line).group(1))
only_wait_if_higher = False
except:
pass
if "M109" in line:
self._waitForHeatup("tool%d" % tool)
if wait:
self._waitForHeatup("tool%d" % tool, only_wait_if_higher)
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):
def _parseBedCommand(self, line, wait=False, support_r=False):
only_wait_if_higher = True
try:
self.bedTargetTemp = float(re.search('S([0-9]+)', line).group(1))
except:
pass
if support_r:
try:
self.bedTargetTemp = float(re.search('R([0-9]+)', line).group(1))
only_wait_if_higher = False
except:
pass
if "M190" in line:
self._waitForHeatup("bed")
if wait:
self._waitForHeatup("bed", only_wait_if_higher)
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)
@@ -566,10 +619,13 @@ class VirtualPrinter():
pass
if duration:
slept = 0
while duration - slept > self._read_timeout and not self._killed:
time.sleep(self._read_timeout)
slept += self._read_timeout
if duration > self._read_timeout:
slept = 0
while duration - slept > self._read_timeout and not self._killed:
time.sleep(self._read_timeout)
slept += self._read_timeout
else:
time.sleep(duration)
def _setPosition(self, line):
matchX = re.search("X([0-9.]+)", line)
@@ -609,13 +665,13 @@ 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.outgoing.put("error writing to file")
self._output("error writing to file")
if handle is not None:
try:
handle.close()
@@ -624,7 +680,7 @@ class VirtualPrinter():
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:
@@ -635,7 +691,7 @@ class VirtualPrinter():
self._writingToSdHandle = None
self._writingToSd = False
self._selectedSdFile = None
self.outgoing.put("Done saving file")
self._output("Done saving file")
def _sdPrintingWorker(self):
self._selectedSdFilePos = 0
@@ -673,23 +729,23 @@ class VirtualPrinter():
self._sdPrintingSemaphore.clear()
self._selectedSdFilePos = 0
self._sdPrinter = None
self.outgoing.put("Done printing file")
self._output("Done printing file")
def _waitForHeatup(self, heater):
def _waitForHeatup(self, heater, only_wait_if_higher):
delta = 1
delay = 1
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):
while not self._killed and (self.temp[toolNum] < self.targetTemp[toolNum] - delta or (not only_wait_if_higher and self.temp[toolNum] > self.targetTemp[toolNum] + delta)):
self._simulateTemps(delta=delta)
self.outgoing.put("T:%0.2f" % self.temp[toolNum])
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):
while not self._killed and (self.bedTemp < self.bedTargetTemp - delta or (not only_wait_if_higher and self.bedTemp > self.bedTargetTemp + delta)):
self._simulateTemps(delta=delta)
self.outgoing.put("B:%0.2f" % self.bedTemp)
self._output("B:%0.2f" % self.bedTemp)
time.sleep(delay)
except AttributeError:
if self.outgoing is not None:
@@ -732,34 +788,73 @@ 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
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)
# 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):
@@ -773,14 +868,14 @@ class VirtualPrinter():
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):
@@ -789,22 +884,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
@@ -813,6 +912,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()
@@ -832,3 +933,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)
+16 -1
View 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):
"""
+2 -1
View File
@@ -228,6 +228,7 @@ class PrinterProfileManager(object):
if make_default:
settings().set(["printerProfiles", "default"], identifier)
settings().save()
if self._current is not None and self._current["id"] == identifier:
self.select(identifier)
@@ -332,7 +333,7 @@ class PrinterProfileManager(object):
from octoprint.util import atomic_write
import yaml
try:
with atomic_write(path, "wb") as f:
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:
self._logger.exception("Error while trying to save profile %s" % profile["id"])
+177 -37
View File
@@ -24,6 +24,7 @@ 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 = []
@@ -73,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
@@ -191,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):
@@ -285,7 +292,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
def set_temperature(self, heater, value):
if not PrinterInterface.valid_heater_regex.match(heater):
raise ValueError("heater must match \"tool[0-9]+\" or \"bed\": {heater}".format(type=heater))
raise ValueError("heater must match \"tool[0-9]+\" or \"bed\": {heater}".format(heater=heater))
if not isinstance(value, (int, long, float)) or value < 0:
raise ValueError("value must be a valid number >= 0: {value}".format(value=value))
@@ -360,7 +367,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._printAfterSelect = printAfterSelect
self._posAfterSelect = pos
self._comm.selectFile("/" + path if sd else path, sd)
self._comm.selectFile("/" + path if sd and not settings().getBoolean(["feature", "sdRelativePath"]) else path, sd)
self._setProgressData(completion=0)
self._setCurrentZ(None)
@@ -382,20 +389,21 @@ 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()
@@ -404,14 +412,29 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._setCurrentZ(None)
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):
"""
@@ -571,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)
@@ -615,22 +641,14 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
printTime = self._comm.getPrintTime()
cleanedPrintTime = self._comm.getCleanedPrintTime()
estimatedTotalPrintTime = self._estimateTotalPrintTime(progress, cleanedPrintTime)
totalPrintTime = estimatedTotalPrintTime
if self._selectedFile and "estimatedPrintTime" in self._selectedFile and self._selectedFile["estimatedPrintTime"]:
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)
printTimeLeft = totalPrintTime - cleanedPrintTime if (totalPrintTime is not None and cleanedPrintTime is not None) else None
printTimeLeft, printTimeLeftOrigin = self._estimatePrintTimeLeft(progress, printTime, cleanedPrintTime, statisticalTotalPrintTime, statisticalTotalPrintTimeType)
if progress is not None:
progress_int = int(progress * 100)
@@ -641,7 +659,124 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
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)
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())
@@ -729,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": {
@@ -755,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 {
@@ -777,10 +912,10 @@ 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)
self._addTemperatureData(copy.deepcopy(temp), copy.deepcopy(bedTemp))
def on_comm_state_change(self, state):
"""
@@ -788,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:
@@ -805,14 +944,14 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
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):
"""
@@ -846,6 +985,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
if self._printAfterSelect:
self._printAfterSelect = False
self.start_print(pos=self._posAfterSelect)
def on_comm_print_job_done(self):
+152 -85
View File
@@ -7,12 +7,11 @@ __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 flaskext.markdown import Markdown
from babel import Locale
from watchdog.observers import Observer
from watchdog.observers.polling import PollingObserver
@@ -169,7 +168,7 @@ class Server(object):
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)
@@ -200,9 +199,15 @@ class Server(object):
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,
@@ -218,8 +223,13 @@ class Server(object):
)
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,
@@ -229,6 +239,8 @@ class Server(object):
return dict(settings=plugin_settings)
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
@@ -270,6 +282,8 @@ class Server(object):
# 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
@@ -297,31 +311,12 @@ class Server(object):
try:
clazz = octoprint.util.get_class(userManagerName)
userManager = clazz()
except AttributeError, e:
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
@@ -330,18 +325,16 @@ class Server(object):
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()
@@ -358,7 +351,7 @@ class Server(object):
allow_client_caching=False
)
additional_mime_types=dict(mime_type_guesser=mime_type_guesser)
admin_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))
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):
@@ -383,6 +376,8 @@ class Server(object):
(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))
@@ -436,10 +431,13 @@ class Server(object):
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()
@@ -532,7 +530,8 @@ class Server(object):
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:
@@ -565,6 +564,9 @@ class Server(object):
"formatters": {
"simple": {
"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
},
"serial": {
"format": "%(asctime)s - %(message)s"
}
},
"handlers": {
@@ -575,18 +577,18 @@ class Server(object):
"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")
}
},
@@ -634,9 +636,42 @@ class Server(object):
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()
@@ -649,7 +684,8 @@ class Server(object):
response.headers.add("X-Clacks-Overhead", "GNU Terry Pratchett")
return response
Markdown(app)
from octoprint.util.jinja import MarkdownFilter
MarkdownFilter(app)
def _setup_i18n(self, app):
global babel
@@ -681,6 +717,7 @@ class Server(object):
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)
@@ -737,32 +774,10 @@ class Server(object):
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"]
class SourceRootFilesystemLoader(jinja2.FileSystemLoader):
def __init__(self, template_filter, prefix, *args, **kwargs):
jinja2.FileSystemLoader.__init__(self, *args, **kwargs)
self._filter = template_filter
if not prefix.endswith("/"):
prefix += "/"
self._prefix = prefix
def get_source(self, environment, template):
if not template.startswith(self._prefix):
raise jinja2.TemplateNotFound(template)
template = template[len(self._prefix):]
if not self._filter(template):
raise jinja2.TemplateNotFound(template)
return jinja2.FileSystemLoader.get_source(self, environment, template)
def list_templates(self):
templates = jinja2.FileSystemLoader.list_templates(self)
return map(lambda t: self._prefix + t, filter(self._filter, templates))
loaders.append(SourceRootFilesystemLoader(lambda t: t in allowed, "_data/", root))
loaders.append(SelectedFileSystemLoader(root, allowed, prefix="_data/"))
jinja_loader = jinja2.ChoiceLoader(loaders)
app.jinja_loader = jinja_loader
@@ -778,10 +793,25 @@ class Server(object):
preemptive_cache_timeout = settings().getInt(["server", "preemptiveCache", "until"])
cutoff_timestamp = time.time() - preemptive_cache_timeout * 24 * 60 * 60
def filter_old_entries(entry):
def filter_current_entries(entry):
"""Returns True for entries younger than the cutoff date"""
return "_timestamp" in entry and entry["_timestamp"] > cutoff_timestamp
cache_data = preemptive_cache.clean_all_data(lambda root, entries: filter(filter_old_entries, entries))
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
@@ -793,17 +823,23 @@ class Server(object):
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)
with preemptive_cache.disable_access_logging():
app(builder.get_environ(), lambda *a, **kw: None)
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
@@ -932,7 +968,7 @@ class Server(object):
# that might be caused by the user still having the folder open somewhere, let's try again after
# waiting a bit
import time
for n in xrange(3):
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:
@@ -979,7 +1015,8 @@ class Server(object):
enable_gcodeviewer = settings().getBoolean(["gcodeViewer", "enabled"])
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,
preferred_stylesheet=preferred_stylesheet
)
@@ -1015,11 +1052,15 @@ class Server(object):
"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",
@@ -1030,13 +1071,21 @@ class Server(object):
"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
@@ -1057,7 +1106,7 @@ class Server(object):
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):
@@ -1065,24 +1114,42 @@ class Server(object):
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_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="cssrewrite, 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
+17 -14
View File
@@ -220,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
@@ -325,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"]
@@ -391,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"]
})
})
+9 -1
View File
@@ -64,6 +64,7 @@ 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"]),
@@ -91,7 +92,10 @@ def getSettings():
"ignoreErrorsFromFirmware": s.getBoolean(["serial", "ignoreErrorsFromFirmware"]),
"disconnectOnErrors": s.getBoolean(["serial", "disconnectOnErrors"]),
"triggerOkForM29": s.getBoolean(["serial", "triggerOkForM29"]),
"supportResendsWithoutOk": s.getBoolean(["serial", "supportResendsWithoutOk"])
"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"),
@@ -213,6 +217,7 @@ 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"])
@@ -238,6 +243,9 @@ def setSettings():
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"])
+13 -2
View File
@@ -19,6 +19,8 @@ from octoprint.slicing import UnknownSlicer, SlicerNotConfigured, ProfileAlready
@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
-89
View File
@@ -155,92 +155,3 @@ def get_plugin_hash():
plugin_hash = hashlib.sha1()
plugin_hash.update(",".join(ui_plugins))
return plugin_hash.hexdigest()
#~~ reverse proxy compatible WSGI middleware
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)
+356 -44
View File
@@ -219,6 +219,251 @@ def fix_webassets_filtertool():
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)
@staticmethod
def valid_ip(address):
import netaddr
try:
netaddr.IPAddress(address)
return True
except:
return False
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
default_port = "443" if scheme == "https" else "80"
host = host.strip()
if ":" in host:
# we might have an ipv6 address here, or a port, or both
if host[0] == "[":
# that looks like an ipv6 address with port, e.g. [fec1::1]:80
address_end = host.find("]")
if address_end == -1:
# no ], that looks like a seriously broken address
return None, None
# extract server ip, skip enclosing [ and ]
server = host[1:address_end]
tail = host[address_end + 1:]
# now check if there's also a port
if len(tail) and tail[0] == ":":
# port included as well
port = tail[1:]
else:
# no port, use default one
port = default_port
elif self.__class__.valid_ip(host):
# ipv6 address without port
server = host
port = default_port
else:
# ipv4 address with port
server, port = host.rsplit(":", 1)
else:
server = host
port = default_port
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:
server_name_component = environ["SERVER_NAME"]
if ":" in server_name_component and self.__class__.valid_ip(server_name_component):
# this is an ipv6 address, we need to wrap that in [ and ] before appending the port
server_name_component = "[" + server_name_component + "]"
environ["HTTP_HOST"] = server_name_component + ":" + 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():
@@ -269,7 +514,9 @@ class LessSimpleCache(BaseCache):
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
@@ -278,27 +525,35 @@ class LessSimpleCache(BaseCache):
now = time.time()
for idx, (key, (expires, _)) in enumerate(self._cache.items()):
if expires is not None and expires <= now or idx % 3 == 0:
self._cache.pop(key, None)
with self._mutex:
self._cache.pop(key, None)
def get(self, key):
import pickle
now = time.time()
expires, value = self._cache.get(key, (0, None))
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
self._prune()
self._cache[key] = (self.calculate_timeout(timeout=timeout),
pickle.dumps(value, pickle.HIGHEST_PROTOCOL))
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):
self.set(key, value, timeout=None)
self._cache.setdefault(key, self._cache[key])
with self._mutex:
self.set(key, value, timeout=None)
self._cache.setdefault(key, self._cache[key])
def delete(self, key):
self._cache.pop(key, None)
with self._mutex:
self._cache.pop(key, None)
def calculate_timeout(self, timeout=None):
if timeout is None:
@@ -310,7 +565,29 @@ class LessSimpleCache(BaseCache):
def over_threshold(self):
if self._threshold is None:
return False
return len(self._cache) > self._threshold
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()
@@ -320,17 +597,20 @@ def cached(timeout=5 * 60, key=lambda: "view:%s" % flask.request.path, unless=No
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
@@ -346,7 +626,8 @@ def cached(timeout=5 * 60, key=lambda: "view:%s" % flask.request.path, unless=No
# do not store if the "unless_response" condition is true
if callable(unless_response) and unless_response(rv):
logger.debug("Not caching result for {path}, bypassed".format(path=flask.request.path))
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
@@ -358,6 +639,16 @@ 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
@@ -386,9 +677,8 @@ class PreemptiveCache(object):
self._lock = threading.RLock()
self._logger = logging.getLogger(__name__ + "." + self.__class__.__name__)
self._log_access = True
def record(self, data, unless=None):
def record(self, data, unless=None, root=None):
if callable(unless) and unless():
return
@@ -397,15 +687,28 @@ class PreemptiveCache(object):
entry_data = entry_data()
if entry_data is not None:
from flask import request
self.add_data(request.path, entry_data)
if root is None:
from flask import request
root = request.path
self.add_data(root, entry_data)
@contextlib.contextmanager
def disable_access_logging(self):
with self._lock:
self._log_access = False
yield
self._log_access = True
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)
@@ -420,7 +723,7 @@ class PreemptiveCache(object):
self._logger.debug("Removed root {} from preemptive cache".format(root))
elif len(entries) < old_count:
all_data[root] = entries
self._logger.debug("Removed {} from preemptive cache for root {}".format(old_count - len(entries), root))
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
@@ -455,7 +758,7 @@ class PreemptiveCache(object):
with self._lock:
try:
with atomic_write(self.cachefile, "wb") as handle:
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))
@@ -467,20 +770,12 @@ class PreemptiveCache(object):
self.set_all_data(all_data)
def add_data(self, root, data):
from octoprint.util import dict_filter
def strip_ignored(d):
return dict_filter(d, lambda k, v: not k.startswith("_"))
def compare(a, b):
return set(strip_ignored(a).items()) == set(strip_ignored(b).items())
def split_matched_and_unmatched(entry, entries):
matched = []
unmatched = []
for e in entries:
if compare(e, entry):
if self._compare_data(e, entry):
matched.append(e)
else:
unmatched.append(e)
@@ -509,15 +804,21 @@ class PreemptiveCache(object):
to_persist["_timestamp"] = time.time()
to_persist["_count"] = 1
self._logger.info("Adding entry for {} and {!r}".format(root, to_persist))
elif self._log_access:
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))
else:
self._logger.debug("Not updating timestamp and counter for {} and {!r}, currently flagged as disabled".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):
@@ -879,12 +1180,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, preferred_stylesheet="css"):
logger = logging.getLogger(__name__ + ".collect_plugin_assets")
supported_stylesheets = ("css", "less")
##~~ core assets collector
def collect_core_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
assets = dict(
js=[],
css=[],
@@ -923,9 +1220,24 @@ def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
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
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()
@@ -943,13 +1255,13 @@ def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
for asset in all_assets["js"]:
if not asset_exists("js", asset):
continue
assets["js"].append('plugin/{name}/{asset}'.format(**locals()))
assets[asset_key]["js"].append('plugin/{name}/{asset}'.format(**locals()))
if preferred_stylesheet in all_assets:
for asset in all_assets[preferred_stylesheet]:
if not asset_exists(preferred_stylesheet, asset):
continue
assets[preferred_stylesheet].append('plugin/{name}/{asset}'.format(**locals()))
assets[asset_key][preferred_stylesheet].append('plugin/{name}/{asset}'.format(**locals()))
else:
for stylesheet in supported_stylesheets:
if not stylesheet in all_assets:
@@ -958,7 +1270,7 @@ def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
for asset in all_assets[stylesheet]:
if not asset_exists(stylesheet, asset):
continue
assets[stylesheet].append('plugin/{name}/{asset}'.format(**locals()))
assets[asset_key][stylesheet].append('plugin/{name}/{asset}'.format(**locals()))
break
return assets
+7 -1
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
@@ -200,4 +203,7 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.
try:
self.send({type: payload})
except Exception as e:
self._logger.warn("Could not send message to client %s: %s" % (self._remoteAddress, str(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))
+91 -10
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
@@ -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,7 +396,7 @@ 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
if not "path" in part:
@@ -371,11 +410,12 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
if "content_type" in part:
parameters["content_type"] = part["content_type"]
fields = dict((self._suffixes[key], value) for (key, value) in parameters.iteritems())
for n, p in fields.iteritems():
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 += b"%s\r\n" % p
elif "data" in part:
@@ -430,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
@@ -517,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
+60 -5
View File
@@ -9,7 +9,7 @@ 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
@@ -20,6 +20,7 @@ from octoprint.settings import settings
from octoprint.filemanager import get_all_extensions
import re
import base64
from . import util
@@ -29,14 +30,68 @@ _logger = logging.getLogger(__name__)
_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=lambda: dict(path=request.path, base_url=request.url_root, query_string="l10n={}".format(g.locale.language) if g.locale else "en"),
unless=lambda: request.url_root in settings().get(["server", "preemptiveCache", "exceptions"]))
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=lambda: "view:{}:{}".format(request.base_url, g.locale.language if g.locale else "en"),
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())
@@ -530,7 +585,7 @@ def _files_for_index():
def _compute_date(files):
from datetime import datetime
timestamps = map(lambda path: os.stat(path).st_mtime, files)
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
+35 -13
View File
@@ -46,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
@@ -84,6 +84,12 @@ default_settings = {
"temperature": 5,
"sdStatus": 1
},
"maxCommunicationTimeouts": {
"idle": 2,
"printing": 5,
"long": 5
},
"maxWritePasses": 5,
"additionalPorts": [],
"longRunningCommands": ["G4", "G28", "G29", "G30", "G32", "M400", "M226"],
"checksumRequiringCommands": ["M110"],
@@ -102,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
@@ -162,6 +172,7 @@ default_settings = {
"sendChecksumWithUnknownCommands": False,
"unknownCommandsNeedAck": False,
"sdSupport": True,
"sdRelativePath": False,
"sdAlwaysAvailable": False,
"swallowOkAfterResend": True,
"repetierTargetTemp": False,
@@ -275,6 +286,15 @@ default_settings = {
}
}
},
"estimation": {
"printTime": {
"statsWeighingUntil": 0.5,
"validityRange": 0.15,
"forceDumbFromPercent": 0.3,
"forceDumbAfterMin": 30,
"stableThreshold": 60
}
},
"devel": {
"stylesheet": "css",
"cache": {
@@ -293,6 +313,7 @@ default_settings = {
"okWithLinenumber": False,
"numExtruders": 1,
"includeCurrentToolInTemps": True,
"includeFilenameInOpened": True,
"movementSpeed": {
"x": 6000,
"y": 6000,
@@ -645,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"):
@@ -658,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()
@@ -673,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()
@@ -689,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()
@@ -821,7 +843,7 @@ class Settings(object):
from octoprint.util import atomic_write
try:
with atomic_write(self._configfile, "wb", prefix="octoprint-config-", suffix=".yaml") as configFile:
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:
@@ -857,9 +879,9 @@ 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]
@@ -1132,7 +1154,7 @@ class Settings(object):
path, _ = os.path.split(filename)
if not os.path.exists(path):
os.makedirs(path)
with atomic_write(filename, "wb") as f:
with atomic_write(filename, "wb", max_permissions=0o666) as f:
f.write(script)
def _default_basedir(applicationName):
+1 -1
View File
@@ -1 +1 @@
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
+44 -7
View File
@@ -136,33 +136,67 @@
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 reload
// our online.gif loaded, so the server is up, let's wait for it to become ready
serverIsOnline = true;
message.className = "pulsate1 green";
message.innerText = "OctoPrint server online, reloading page...";
window.location = baseUrl;
ping(indexCachedUrl, timeout, indexCachedCallback);
} else {
// online.gif still not available, let's look at
var interval = 15;
// online.gif still not available, let's look at it again later
var interval = 10;
if (intervals.length) {
interval = intervals.shift();
}
@@ -186,10 +220,13 @@
}
backendOfflineCounter++;
if (backendOfflineCounter > 10) {
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>.";
+2 -45
View File
@@ -140,9 +140,6 @@ 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": {
@@ -214,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"]);
@@ -226,48 +221,10 @@ 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 == "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 ..."));
}
} 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("");
new PNotify({
title: gettext("Streaming done"),
text: _.sprintf(gettext("Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds"), payload),
type: "success"
});
} else if (type == "PrintCancelled") {
if (type == "PrintCancelled") {
if (payload.firmwareError) {
new PNotify({
title: gettext("Unhandled communication error"),
@@ -279,7 +236,7 @@ function DataUpdater(allViewModels) {
} else if (type == "Error") {
new PNotify({
title: gettext("Unhandled communication error"),
text: _.sprintf(gettext("The was an unhandled error while talking to the printer. Due to that OctoPrint disconnected. Error: %(error)s"), payload),
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
});
+115 -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();
@@ -363,7 +363,7 @@ function bytesFromSize(size) {
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;
@@ -373,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) {
@@ -387,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"));
+38
View File
@@ -348,6 +348,44 @@ $(function() {
}
};
ko.bindingHandlers.copyWidth = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var node = ko.bindingHandlers.copyWidth._getReferenceNode(element, valueAccessor);
ko.bindingHandlers.copyWidth._setWidth(node, element);
},
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var node = ko.bindingHandlers.copyWidth._getReferenceNode(element, valueAccessor);
ko.bindingHandlers.copyWidth._setWidth(node, element);
},
_setWidth: function(node, element) {
var width = node.width();
if (!width) return;
if ($(element).width() == width) return;
element.style.width = width + "px";
},
_getReferenceNode: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (!value) return;
var parts = value.split(" ");
var node = $(element);
while (parts.length > 0) {
var part = parts.shift();
if (part == ":parent") {
node = node.parent();
} else {
var selector = part;
if (parts.length > 0) {
selector += " " + parts.join(" ");
}
node = $(selector, node);
break;
}
}
return node;
}
};
ko.bindingHandlers.contextMenu = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var val = ko.utils.unwrapObservable(valueAccessor());
+153 -36
View File
@@ -58,6 +58,10 @@ $(function() {
self.localTarget = undefined;
self.sdTarget = undefined;
self.uploadProgressText = ko.observable();
self._uploadInProgress = false;
// initialize list helper
self.listHelper = new ItemListHelper(
"gcodeFiles",
@@ -145,22 +149,26 @@ $(function() {
self.isSdReady(data.flags.sdReady);
};
self._otherRequestInProgress = false;
self._otherRequestInProgress = undefined;
self._filenameToFocus = undefined;
self._locationToFocus = undefined;
self.requestData = function(filenameToFocus, locationToFocus) {
if (self._otherRequestInProgress) return;
self._filenameToFocus = self._filenameToFocus || filenameToFocus;
self._locationToFocus = self._locationToFocus || locationToFocus;
if (self._otherRequestInProgress !== undefined) {
return self._otherRequestInProgress
}
self._otherRequestInProgress = true;
$.ajax({
return self._otherRequestInProgress = $.ajax({
url: API_BASEURL + "files",
method: "GET",
dataType: "json",
success: function(response) {
self.fromResponse(response, filenameToFocus, locationToFocus);
self._otherRequestInProgress = false;
},
error: function() {
self._otherRequestInProgress = false;
}
dataType: "json"
}).done(function(response) {
self.fromResponse(response, self._filenameToFocus, self._locationToFocus);
}).always(function() {
self._otherRequestInProgress = undefined;
self._filenameToFocus = undefined;
self._locationToFocus = undefined;
});
};
@@ -179,8 +187,19 @@ $(function() {
}
var entryElement = self.getEntryElement({name: filenameToFocus, origin: locationToFocus});
if (entryElement) {
// scroll to uploaded element
var entryOffset = entryElement.offsetTop;
$(".gcode_files").slimScroll({ scrollTo: entryOffset + "px" });
$(".gcode_files").slimScroll({
scrollTo: entryOffset + "px"
});
// highlight uploaded element
var element = $(entryElement);
element.on("webkitAnimationEnd oanimationend msAnimationEnd animationend", function(e) {
// remove highlight class again
element.removeClass("highlight");
});
element.addClass("highlight");
}
}
@@ -298,7 +317,7 @@ $(function() {
};
self.enableSlicing = function(data) {
return self.loginState.isUser() && self.slicing.enableSlicingDialog();
return self.loginState.isUser() && self.slicing.enableSlicingDialog() && self.slicing.enableSlicingDialogForFile(data.name);
};
self.enableAdditionalData = function(data) {
@@ -330,12 +349,12 @@ $(function() {
}
}
}
output += gettext("Estimated Print Time") + ": " + formatDuration(data["gcodeAnalysis"]["estimatedPrintTime"]) + "<br>";
output += gettext("Estimated print time") + ": " + formatFuzzyPrintTime(data["gcodeAnalysis"]["estimatedPrintTime"]) + "<br>";
}
if (data["prints"] && data["prints"]["last"]) {
output += gettext("Last Printed") + ": " + formatTimeAgo(data["prints"]["last"]["date"]) + "<br>";
output += gettext("Last printed") + ": " + formatTimeAgo(data["prints"]["last"]["date"]) + "<br>";
if (data["prints"]["last"]["lastPrintTime"]) {
output += gettext("Last Print Time") + ": " + formatDuration(data["prints"]["last"]["lastPrintTime"]);
output += gettext("Last print time") + ": " + formatDuration(data["prints"]["last"]["lastPrintTime"]);
}
}
return output;
@@ -421,15 +440,71 @@ $(function() {
};
self.onEventUpdatedFiles = function(payload) {
if (payload.type == "gcode") {
self.requestData();
if (self._uploadInProgress) {
return;
}
if (payload.type !== "gcode") {
return;
}
self.requestData();
};
self.onEventSlicingStarted = function(payload) {
self.uploadProgress
.addClass("progress-striped")
.addClass("active");
self.uploadProgressBar.css("width", "100%");
if (payload.progressAvailable) {
self.uploadProgressText(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: 0}));
} else {
self.uploadProgressText(gettext("Slicing ..."));
}
};
self.onSlicingProgress = function(slicer, modelPath, machinecodePath, progress) {
self.uploadProgressText(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: Math.round(progress)}));
};
self.onEventSlicingCancelled = function(payload) {
self.uploadProgress
.removeClass("progress-striped")
.removeClass("active");
self.uploadProgressBar
.css("width", "0%");
self.uploadProgressText("");
};
self.onEventSlicingDone = function(payload) {
self.uploadProgress
.removeClass("progress-striped")
.removeClass("active");
self.uploadProgressBar
.css("width", "0%");
self.uploadProgressText("");
new PNotify({
title: gettext("Slicing done"),
text: _.sprintf(gettext("Sliced %(stl)s to %(gcode)s, took %(time).2f seconds"), payload),
type: "success"
});
self.requestData();
};
self.onEventSlicingFailed = function(payload) {
self.uploadProgress
.removeClass("progress-striped")
.removeClass("active");
self.uploadProgressBar
.css("width", "0%");
self.uploadProgressText("");
var 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});
};
self.onEventMetadataAnalysisFinished = function(payload) {
self.requestData();
};
@@ -438,7 +513,29 @@ $(function() {
self.requestData();
};
self.onEventTransferStarted = function(payload) {
self.uploadProgress
.addClass("progress-striped")
.addClass("active");
self.uploadProgressBar
.css("width", "100%");
self.uploadProgressText(gettext("Streaming ..."));
};
self.onEventTransferDone = function(payload) {
self.uploadProgress
.removeClass("progress-striped")
.removeClass("active");
self.uploadProgressBar
.css("width", "0");
self.uploadProgressText("");
new PNotify({
title: gettext("Streaming done"),
text: _.sprintf(gettext("Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds"), payload),
type: "success"
});
self.requestData(payload.remote, "sdcard");
};
@@ -456,8 +553,10 @@ $(function() {
url: API_BASEURL + "files/local",
dataType: "json",
dropZone: enable ? self.localTarget : null,
submit: self._handleUploadStart,
done: self._handleUploadDone,
fail: self._handleUploadFail,
always: self._handleUploadAlways,
progressall: self._handleUploadProgress
};
self.uploadButton.fileupload(options);
@@ -468,8 +567,10 @@ $(function() {
url: API_BASEURL + "files/sdcard",
dataType: "json",
dropZone: enable ? self.sdTarget : null,
submit: self._handleUploadStart,
done: self._handleUploadDone,
fail: self._handleUploadFail,
always: self._handleUploadAlways,
progressall: self._handleUploadProgress
};
self.sdUploadButton.fileupload(options);
@@ -485,6 +586,11 @@ $(function() {
}
};
self._handleUploadStart = function(e, data) {
self._uploadInProgress = true;
return true;
};
self._handleUploadDone = function(e, data) {
var filename = undefined;
var location = undefined;
@@ -495,24 +601,32 @@ $(function() {
filename = data.result.files.local.name;
location = "local";
}
self.requestData(filename, location);
self.requestData(filename, location)
.done(function() {
if (data.result.done) {
self.uploadProgressBar
.css("width", "0%");
self.uploadProgressText("");
self.uploadProgress
.removeClass("progress-striped")
.removeClass("active");
}
});
if (_.endsWith(filename.toLowerCase(), ".stl")) {
self.slicing.show(location, filename);
}
if (data.result.done) {
self.uploadProgressBar
.css("width", "0%")
.text("");
self.uploadProgress
.removeClass("progress-striped")
.removeClass("active");
}
};
self._handleUploadFail = function(e, data) {
var error = "<p>" + gettext("Could not upload the file. Make sure that it is a GCODE file and has the extension \".gcode\" or \".gco\" or that it is an STL file with the extension \".stl\".") + "</p>";
var extensions = _.map(SUPPORTED_EXTENSIONS, function(extension) {
return extension.toLowerCase();
}).sort();
extensions = extensions.join(", ");
var error = "<p>"
+ _.sprintf(gettext("Could not upload the file. Make sure that it is a valid file with one of these extensions: %(extensions)s"),
{extensions: extensions})
+ "</p>";
error += pnotifyAdditionalInfo("<pre>" + data.jqXHR.responseText + "</pre>");
new PNotify({
title: "Upload failed",
@@ -521,26 +635,29 @@ $(function() {
hide: false
});
self.uploadProgressBar
.css("width", "0%")
.text("");
.css("width", "0%");
self.uploadProgressText("");
self.uploadProgress
.removeClass("progress-striped")
.removeClass("active");
};
self._handleUploadAlways = function(e, data) {
self._uploadInProgress = false;
};
self._handleUploadProgress = function(e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
self.uploadProgressBar
.css("width", progress + "%")
.text(gettext("Uploading ..."));
.css("width", progress + "%");
self.uploadProgressText(gettext("Uploading ..."));
if (progress >= 100) {
self.uploadProgress
.addClass("progress-striped")
.addClass("active");
self.uploadProgressBar
.text(gettext("Saving ..."));
self.uploadProgressText(gettext("Saving ..."));
}
};
@@ -435,7 +435,7 @@ $(function() {
} else {
var output = [];
output.push(gettext("Model size") + ": " + model.width.toFixed(2) + "mm &times; " + model.depth.toFixed(2) + "mm &times; " + model.height.toFixed(2) + "mm");
output.push(gettext("Estimated total print time") + ": " + formatDuration(model.printTime));
output.push(gettext("Estimated total print time") + ": " + formatFuzzyPrintTime(model.printTime));
output.push(gettext("Estimated layer height") + ": " + model.layerHeight.toFixed(2) + gettext("mm"));
output.push(gettext("Layer count") + ": " + model.layersPrinted.toFixed(0) + " " + gettext("printed") + ", " + model.layersTotal.toFixed(0) + " " + gettext("visited"));
@@ -462,17 +462,17 @@ $(function() {
var output = [];
output.push(gettext("Layer number") + ": " + (layer.number + 1));
output.push(gettext("Layer height") + " (mm): " + layer.height);
output.push(gettext("GCODE commands in layer") + ": " + layer.commands);
output.push(gettext("GCODE commands") + ": " + layer.commands);
if (layer.filament != undefined) {
if (layer.filament.length == 1) {
output.push(gettext("Filament used by layer") + ": " + layer.filament[0].toFixed(2) + "mm");
output.push(gettext("Filament") + ": " + layer.filament[0].toFixed(2) + "mm");
} else {
for (var i = 0; i < layer.filament.length; i++) {
output.push(gettext("Filament used by layer") + " (" + gettext("Tool") + " " + i + "): " + layer.filament[i].toFixed(2) + "mm");
output.push(gettext("Filament") + " (" + gettext("Tool") + " " + i + "): " + layer.filament[i].toFixed(2) + "mm");
}
}
}
output.push(gettext("Print time for layer") + ": " + formatDuration(layer.printTime));
output.push(gettext("Estimated print time") + ": " + formatDuration(layer.printTime));
self.ui_layerInfo(output.join("<br>"));
@@ -30,6 +30,7 @@ $(function() {
self.filepos = ko.observable(undefined);
self.printTime = ko.observable(undefined);
self.printTimeLeft = ko.observable(undefined);
self.printTimeLeftOrigin = ko.observable(undefined);
self.sd = ko.observable(undefined);
self.timelapse = ko.observable(undefined);
@@ -51,9 +52,9 @@ $(function() {
self.estimatedPrintTimeString = ko.pureComputed(function() {
if (self.lastPrintTime())
return formatDuration(self.lastPrintTime());
return formatFuzzyPrintTime(self.lastPrintTime());
if (self.estimatedPrintTime())
return formatDuration(self.estimatedPrintTime());
return formatFuzzyPrintTime(self.estimatedPrintTime());
return "-";
});
self.byteString = ko.pureComputed(function() {
@@ -77,10 +78,54 @@ $(function() {
if (!self.printTime() || !(self.isPrinting() || self.isPaused())) {
return "-";
} else {
return gettext("Calculating...");
return gettext("Still stabilizing...");
}
} else {
return formatFuzzyEstimation(self.printTimeLeft());
return formatFuzzyPrintTime(self.printTimeLeft());
}
});
self.printTimeLeftOriginString = ko.pureComputed(function() {
var value = self.printTimeLeftOrigin();
switch (value) {
case "linear": {
return gettext("Based on a linear approximation (very low accuracy, especially at the beginning of the print)");
}
case "analysis": {
return gettext("Based on the estimate from analysis of file (medium accuracy)");
}
case "mixed-analysis": {
return gettext("Based on a mix of estimate from analysis and calculation (medium accuracy)");
}
case "average": {
return gettext("Based on the average total of past prints of this model with the same printer profile (usually good accuracy)");
}
case "mixed-average": {
return gettext("Based on a mix of average total from past prints and calculation (usually good accuracy)");
}
case "estimate": {
return gettext("Based on the calculated estimate (best accuracy)");
}
default: {
return "";
}
}
});
self.printTimeLeftOriginClass = ko.pureComputed(function() {
var value = self.printTimeLeftOrigin();
switch (value) {
default:
case "linear": {
return "text-error";
}
case "analysis":
case "mixed-analysis": {
return "text-warning";
}
case "average":
case "mixed-average":
case "estimate": {
return "text-success";
}
}
});
self.progressString = ko.pureComputed(function() {
@@ -88,6 +133,12 @@ $(function() {
return 0;
return self.progress();
});
self.progressBarString = ko.pureComputed(function() {
if (!self.progress()) {
return "";
}
return _.sprintf("%d%%", self.progress());
});
self.pauseString = ko.pureComputed(function() {
if (self.isPaused())
return gettext("Continue");
@@ -191,6 +242,7 @@ $(function() {
self.filepos(data.filepos);
self.printTime(data.printTime);
self.printTimeLeft(data.printTimeLeft);
self.printTimeLeftOrigin(data.printTimeLeftOrigin);
};
self._processZData = function(data) {
@@ -223,21 +275,41 @@ $(function() {
};
self.pause = function() {
self._jobCommand("pause");
self.onlyPause = function() {
self.pause("pause");
};
self.onlyResume = function() {
self.pause("resume");
};
self.pause = function(action) {
action = action || "toggle";
self._jobCommand("pause", {"action": action});
};
self.cancel = function() {
self._jobCommand("cancel");
};
self._jobCommand = function(command, callback) {
self._jobCommand = function(command, payload, callback) {
if (arguments.length == 1) {
payload = {};
callback = undefined;
} else if (arguments.length == 2 && typeof payload === "function") {
callback = payload;
payload = {};
}
var data = _.extend(payload, {});
data.command = command;
$.ajax({
url: API_BASEURL + "job",
type: "POST",
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify({command: command}),
data: JSON.stringify(data),
success: function(response) {
if (callback != undefined) {
callback();
@@ -116,6 +116,7 @@ $(function() {
self.feature_waitForStart = ko.observable(undefined);
self.feature_alwaysSendChecksum = ko.observable(undefined);
self.feature_sdSupport = ko.observable(undefined);
self.feature_sdRelativePath = ko.observable(undefined);
self.feature_sdAlwaysAvailable = ko.observable(undefined);
self.feature_swallowOkAfterResend = ko.observable(undefined);
self.feature_repetierTargetTemp = ko.observable(undefined);
@@ -143,6 +144,9 @@ $(function() {
self.serial_disconnectOnErrors = ko.observable(undefined);
self.serial_triggerOkForM29 = ko.observable(undefined);
self.serial_supportResendsWithoutOk = ko.observable(undefined);
self.serial_maxTimeoutsIdle = ko.observable(undefined);
self.serial_maxTimeoutsPrinting = ko.observable(undefined);
self.serial_maxTimeoutsLong = ko.observable(undefined);
self.folder_uploads = ko.observable(undefined);
self.folder_timelapse = ko.observable(undefined);
@@ -463,6 +467,9 @@ $(function() {
self.serial_disconnectOnErrors(response.serial.disconnectOnErrors);
self.serial_triggerOkForM29(response.serial.triggerOkForM29);
self.serial_supportResendsWithoutOk(response.serial.supportResendsWithoutOk);
self.serial_maxTimeoutsIdle(response.serial.maxTimeoutsIdle);
self.serial_maxTimeoutsPrinting(response.serial.maxTimeoutsPrinting);
self.serial_maxTimeoutsLong(response.serial.maxTimeoutsLong);
self.folder_uploads(response.folder.uploads);
self.folder_timelapse(response.folder.timelapse);
@@ -555,7 +562,10 @@ $(function() {
"ignoreErrorsFromFirmware": self.serial_ignoreErrorsFromFirmware(),
"disconnectOnErrors": self.serial_disconnectOnErrors(),
"triggerOkForM29": self.serial_triggerOkForM29(),
"supportResendsWithoutOk": self.serial_supportResendsWithoutOk()
"supportResendsWithoutOk": self.serial_supportResendsWithoutOk(),
"maxTimeoutsIdle": self.serial_maxTimeoutsIdle(),
"maxTimeoutsPrinting": self.serial_maxTimeoutsPrinting(),
"maxTimeoutsLong": self.serial_maxTimeoutsLong()
},
"folder": {
"uploads": self.folder_uploads(),
+166 -95
View File
@@ -5,14 +5,15 @@ $(function() {
self.loginState = parameters[0];
self.printerProfiles = parameters[1];
self.file = ko.observable(undefined);
self.target = undefined;
self.file = undefined;
self.data = undefined;
self.defaultSlicer = undefined;
self.defaultProfile = undefined;
self.gcodeFilename = ko.observable();
self.destinationFilename = ko.observable();
self.gcodeFilename = self.destinationFilename; // TODO: for backwards compatiblity, mark deprecated ASAP
self.title = ko.observable();
self.slicer = ko.observable();
@@ -21,91 +22,16 @@ $(function() {
self.profiles = ko.observableArray();
self.printerProfile = ko.observable();
self.configured_slicers = ko.pureComputed(function() {
return _.filter(self.slicers(), function(slicer) {
return slicer.configured;
});
});
self.afterSlicingOptions = [
{"value": "none", "text": gettext("Do nothing")},
{"value": "select", "text": gettext("Select for printing")},
{"value": "print", "text": gettext("Start printing")}
];
self.afterSlicing = ko.observable("none");
self.show = function(target, file, force) {
if (!self.enableSlicingDialog() && !force) {
return;
self.slicersForFile = function(file) {
if (file === undefined) {
return [];
}
self.requestData();
self.target = target;
self.file = file;
self.title(_.sprintf(gettext("Slicing %(filename)s"), {filename: self.file}));
self.gcodeFilename(self.file.substr(0, self.file.lastIndexOf(".")));
self.printerProfile(self.printerProfiles.currentProfile());
self.afterSlicing("none");
$("#slicing_configuration_dialog").modal("show");
};
self.slicer.subscribe(function(newValue) {
self.profilesForSlicer(newValue);
});
self.enableSlicingDialog = ko.pureComputed(function() {
return self.configured_slicers().length > 0;
});
self.enableSliceButton = ko.pureComputed(function() {
return self.gcodeFilename() != undefined
&& self.gcodeFilename().trim() != ""
&& self.slicer() != undefined
&& self.profile() != undefined;
});
self.requestData = function(callback) {
$.ajax({
url: API_BASEURL + "slicing",
type: "GET",
dataType: "json",
success: function(data) {
self.fromResponse(data);
if (callback !== undefined) {
callback();
}
}
});
};
self.fromResponse = function(data) {
self.data = data;
var selectedSlicer = undefined;
self.slicers.removeAll();
_.each(_.values(data), function(slicer) {
var name = slicer.displayName;
if (name == undefined) {
name = slicer.key;
}
if (slicer.default && slicer.configured) {
selectedSlicer = slicer.key;
}
self.slicers.push({
key: slicer.key,
name: name,
configured: slicer.configured
return _.filter(self.configuredSlicers(), function(slicer) {
return _.any(slicer.sourceExtensions, function(extension) {
return _.endsWith(file.toLowerCase(), "." + extension.toLowerCase());
});
});
if (selectedSlicer != undefined) {
self.slicer(selectedSlicer);
self.profilesForSlicer(selectedSlicer);
}
self.defaultSlicer = selectedSlicer;
};
self.profilesForSlicer = function(key) {
@@ -135,19 +61,164 @@ $(function() {
})
});
if (selectedProfile != undefined) {
self.profile(selectedProfile);
}
self.profile(selectedProfile);
self.defaultProfile = selectedProfile;
};
self.resetProfiles = function() {
self.profiles.removeAll();
self.profile(undefined);
};
self.configuredSlicers = ko.pureComputed(function() {
return _.filter(self.slicers(), function(slicer) {
return slicer.configured;
});
});
self.matchingSlicers = ko.computed(function() {
var slicers = self.slicersForFile(self.file());
var containsSlicer = function(key) {
return _.any(slicers, function(slicer) {
return slicer.key == key;
});
};
var current = self.slicer();
if (!containsSlicer(current)) {
if (self.defaultSlicer !== undefined && containsSlicer(self.defaultSlicer)) {
self.slicer(self.defaultSlicer);
} else {
self.slicer(undefined);
self.resetProfiles();
}
} else {
self.profilesForSlicer(self.slicer());
}
return slicers;
});
self.afterSlicingOptions = [
{"value": "none", "text": gettext("Do nothing")},
{"value": "select", "text": gettext("Select for printing")},
{"value": "print", "text": gettext("Start printing")}
];
self.afterSlicing = ko.observable("none");
self.show = function(target, file, force) {
if (!self.enableSlicingDialog() && !force) {
return;
}
self.requestData();
self.target = target;
self.file(file);
self.title(_.sprintf(gettext("Slicing %(filename)s"), {filename: self.file()}));
self.destinationFilename(self.file().substr(0, self.file().lastIndexOf(".")));
self.printerProfile(self.printerProfiles.currentProfile());
self.afterSlicing("none");
$("#slicing_configuration_dialog").modal("show");
};
self.slicer.subscribe(function(newValue) {
if (newValue === undefined) {
self.resetProfiles();
} else {
self.profilesForSlicer(newValue);
}
});
self.enableSlicingDialog = ko.pureComputed(function() {
return self.configuredSlicers().length > 0;
});
self.enableSlicingDialogForFile = function(file) {
return self.slicersForFile(file).length > 0;
};
self.enableSliceButton = ko.pureComputed(function() {
return self.destinationFilename() != undefined
&& self.destinationFilename().trim() != ""
&& self.slicer() != undefined
&& self.profile() != undefined;
});
self.requestData = function(callback) {
$.ajax({
url: API_BASEURL + "slicing",
type: "GET",
dataType: "json",
success: function(data) {
self.fromResponse(data);
if (callback !== undefined) {
callback();
}
}
});
};
self.destinationExtension = ko.pureComputed(function() {
var fallback = "???";
if (self.slicer() === undefined) {
return fallback;
}
var slicer = self.data[self.slicer()];
if (slicer === undefined) {
return fallback;
}
var extensions = slicer.extensions;
if (extensions === undefined) {
return fallback;
}
var destinationExtensions = extensions.destination;
if (destinationExtensions === undefined || !destinationExtensions.length) {
return fallback;
}
return destinationExtensions[0] || fallback;
});
self.fromResponse = function(data) {
self.data = data;
var selectedSlicer = undefined;
self.slicers.removeAll();
_.each(_.values(data), function(slicer) {
var name = slicer.displayName;
if (name == undefined) {
name = slicer.key;
}
if (slicer.default && slicer.configured) {
selectedSlicer = slicer.key;
}
var props = {
key: slicer.key,
name: name,
configured: slicer.configured,
sourceExtensions: slicer.extensions.source,
destinationExtensions: slicer.extensions.destination
};
self.slicers.push(props);
});
self.defaultSlicer = selectedSlicer;
};
self.slice = function() {
var gcodeFilename = self._sanitize(self.gcodeFilename());
if (!_.endsWith(gcodeFilename.toLowerCase(), ".gco")
&& !_.endsWith(gcodeFilename.toLowerCase(), ".gcode")
&& !_.endsWith(gcodeFilename.toLowerCase(), ".g")) {
gcodeFilename = gcodeFilename + ".gco";
var destinationFilename = self._sanitize(self.destinationFilename());
var destinationExtensions = self.data[self.slicer()] && self.data[self.slicer()].extensions && self.data[self.slicer()].extensions.destination
? self.data[self.slicer()].extensions.destination
: ["???"];
if (!_.any(destinationExtensions, function(extension) {
return _.endsWith(destinationFilename.toLowerCase(), "." + extension.toLowerCase());
})) {
destinationFilename = destinationFilename + "." + destinationExtensions[0];
}
var data = {
@@ -155,7 +226,7 @@ $(function() {
slicer: self.slicer(),
profile: self.profile(),
printerProfile: self.printerProfile(),
gcode: gcodeFilename
destination: destinationFilename
};
if (self.afterSlicing() == "print") {
@@ -165,7 +236,7 @@ $(function() {
}
$.ajax({
url: API_BASEURL + "files/" + self.target + "/" + self.file,
url: API_BASEURL + "files/" + self.target + "/" + self.file(),
type: "POST",
dataType: "json",
contentType: "application/json; charset=UTF-8",
@@ -174,7 +245,7 @@ $(function() {
$("#slicing_configuration_dialog").modal("hide");
self.gcodeFilename(undefined);
self.destinationFilename(undefined);
self.slicer(self.defaultSlicer);
self.profile(self.defaultProfile);
};
@@ -68,6 +68,20 @@ $(function() {
});
};
self.generateApikey = function() {
if (!CONFIG_ACCESS_CONTROL) return;
self.users.generateApikey(self.currentUser().name, function(response) {
self.access_apikey(response.apikey);
});
};
self.deleteApikey = function() {
if (!CONFIG_ACCESS_CONTROL) return;
self.users.deleteApikey(self.currentUser().name, function() {
self.access_apikey(undefined);
});
};
self.updateSettings = function(username, settings, callback) {
if (!CONFIG_ACCESS_CONTROL) return;
+17 -9
View File
@@ -1,9 +1,17 @@
//
// LESS - Leaner CSS v1.3.3
// http://lesscss.org
//
// Copyright (c) 2009-2013, Alexis Sellier
// Licensed under the Apache 2.0 License.
//
(function(e,t){function n(t){return e.less[t.split("/")[1]]}function f(){r.env==="development"?(r.optimization=0,r.watchTimer=setInterval(function(){r.watchMode&&g(function(e,t,n,r,i){t&&S(t.toCSS(),r,i.lastModified)})},r.poll)):r.optimization=3}function m(){var e=document.getElementsByTagName("style");for(var t=0;t<e.length;t++)e[t].type.match(p)&&(new r.Parser({filename:document.location.href.replace(/#.*$/,""),dumpLineNumbers:r.dumpLineNumbers})).parse(e[t].innerHTML||"",function(n,r){var i=r.toCSS(),s=e[t];s.type="text/css",s.styleSheet?s.styleSheet.cssText=i:s.innerHTML=i})}function g(e,t){for(var n=0;n<r.sheets.length;n++)w(r.sheets[n],e,t,r.sheets.length-(n+1))}function y(e,t){var n=b(e),r=b(t),i,s,o,u,a="";if(n.hostPart!==r.hostPart)return"";s=Math.max(r.directories.length,n.directories.length);for(i=0;i<s;i++)if(r.directories[i]!==n.directories[i])break;u=r.directories.slice(i),o=n.directories.slice(i);for(i=0;i<u.length-1;i++)a+="../";for(i=0;i<o.length-1;i++)a+=o[i]+"/";return a}function b(e,t){var n=/^((?:[a-z-]+:)?\/\/(?:[^\/\?#]*\/)|([\/\\]))?((?:[^\/\\\?#]*[\/\\])*)([^\/\\\?#]*)([#\?].*)?$/,r=e.match(n),i={},s=[],o,u;if(!r)throw new Error("Could not parse sheet href - '"+e+"'");if(!r[1]||r[2]){u=t.match(n);if(!u)throw new Error("Could not parse page url - '"+t+"'");r[1]=u[1],r[2]||(r[3]=u[3]+r[3])}if(r[3]){s=r[3].replace("\\","/").split("/");for(o=0;o<s.length;o++)s[o]===".."&&o>0&&(s.splice(o-1,2),o-=2)}return i.hostPart=r[1],i.directories=s,i.path=r[1]+s.join("/"),i.fileUrl=i.path+(r[4]||""),i.url=i.fileUrl+(r[5]||""),i}function w(t,n,i,s){var o=t.contents||{},u=t.files||{},a=b(t.href,e.location.href),f=a.url,c=l&&l.getItem(f),h=l&&l.getItem(f+":timestamp"),p={css:c,timestamp:h},d;r.relativeUrls?r.rootpath?t.entryPath?d=b(r.rootpath+y(a.path,t.entryPath)).path:d=r.rootpath:d=a.path:r.rootpath?d=r.rootpath:t.entryPath?d=t.entryPath:d=a.path,x(f,t.type,function(e,l){v+=e.replace(/@import .+?;/ig,"");if(!i&&p&&l&&(new Date(l)).valueOf()===(new Date(p.timestamp)).valueOf())S(p.css,t),n(null,null,e,t,{local:!0,remaining:s},f);else try{o[f]=e,(new r.Parser({optimization:r.optimization,paths:[a.path],entryPath:t.entryPath||a.path,mime:t.type,filename:f,rootpath:d,relativeUrls:t.relativeUrls,contents:o,files:u,dumpLineNumbers:r.dumpLineNumbers})).parse(e,function(r,i){if(r)return k(r,f);try{n(r,i,e,t,{local:!1,lastModified:l,remaining:s},f),N(document.getElementById("less-error-message:"+E(f)))}catch(r){k(r,f)}})}catch(c){k(c,f)}},function(e,t){throw new Error("Couldn't load "+t+" ("+e+")")})}function E(e){return e.replace(/^[a-z]+:\/\/?[^\/]+/,"").replace(/^\//,"").replace(/\.[a-zA-Z]+$/,"").replace(/[^\.\w-]+/g,"-").replace(/\./g,":")}function S(e,t,n){var r,i=t.href||"",s="less:"+(t.title||E(i));if((r=document.getElementById(s))===null){r=document.createElement("style"),r.type="text/css",t.media&&(r.media=t.media),r.id=s;var o=t&&t.nextSibling||null;(o||document.getElementsByTagName("head")[0]).parentNode.insertBefore(r,o)}if(r.styleSheet)try{r.styleSheet.cssText=e}catch(u){throw new Error("Couldn't reassign styleSheet.cssText.")}else(function(e){r.childNodes.length>0?r.firstChild.nodeValue!==e.nodeValue&&r.replaceChild(e,r.firstChild):r.appendChild(e)})(document.createTextNode(e));if(n&&l){C("saving "+i+" to cache.");try{l.setItem(i,e),l.setItem(i+":timestamp",n)}catch(u){C("failed to save")}}}function x(e,t,n,i){function a(t,n,r){t.status>=200&&t.status<300?n(t.responseText,t.getResponseHeader("Last-Modified")):typeof r=="function"&&r(t.status,e)}var s=T(),u=o?r.fileAsync:r.async;typeof s.overrideMimeType=="function"&&s.overrideMimeType("text/css"),s.open("GET",e,u),s.setRequestHeader("Accept",t||"text/x-less, text/css; q=0.9, */*; q=0.5"),s.send(null),o&&!r.fileAsync?s.status===0||s.status>=200&&s.status<300?n(s.responseText):i(s.status,e):u?s.onreadystatechange=function(){s.readyState==4&&a(s,n,i)}:a(s,n,i)}function T(){if(e.XMLHttpRequest)return new XMLHttpRequest;try{return new ActiveXObject("MSXML2.XMLHTTP.3.0")}catch(t){return C("browser doesn't support AJAX."),null}}function N(e){return e&&e.parentNode.removeChild(e)}function C(e){r.env=="development"&&typeof console!="undefined"&&console.log("less: "+e)}function k(e,t){var n="less-error-message:"+E(t),i='<li><label>{line}</label><pre class="{class}">{content}</pre></li>',s=document.createElement("div"),o,u,a=[],f=e.filename||t,l=f.match(/([^\/]+(\?.*)?)$/)[1];s.id=n,s.className="less-error-message",u="<h3>"+(e.message||"There is an error in your .less file")+"</h3>"+'<p>in <a href="'+f+'">'+l+"</a> ";var c=function(e,t,n){e.extract[t]&&a.push(i.replace(/\{line\}/,parseInt(e.line)+(t-1)).replace(/\{class\}/,n).replace(/\{content\}/,e.extract[t]))};e.stack?u+="<br/>"+e.stack.split("\n").slice(1).join("<br/>"):e.extract&&(c(e,0,""),c(e,1,"line"),c(e,2,""),u+="on line "+e.line+", column "+(e.column+1)+":</p>"+"<ul>"+a.join("")+"</ul>"),s.innerHTML=u,S([".less-error-message ul, .less-error-message li {","list-style-type: none;","margin-rigLine truncated
:"#9acd32"}}(n("./tree")),function(e){e.Alpha=function(e){this.value=e},e.Alpha.prototype={toCSS:function(){return"alpha(opacity="+(this.value.toCSS?this.value.toCSS():this.value)+")"},eval:function(e){return this.value.eval&&(this.value=this.value.eval(e)),this}}}(n("../tree")),function(e){e.Anonymous=function(e){this.value=e.value||e},e.Anonymous.prototype={toCSS:function(){return this.value},eval:function(){return this},compare:function(e){if(!e.toCSS)return-1;var t=this.toCSS(),n=e.toCSS();return t===n?0:t<n?-1:1}}}(n("../tree")),function(e){e.Assignment=function(e,t){this.key=e,this.value=t},e.Assignment.prototype={toCSS:function(){return this.key+"="+(this.value.toCSS?this.value.toCSS():this.value)},eval:function(t){return this.value.eval?new e.Assignment(this.key,this.value.eval(t)):this}}}(n("../tree")),function(e){e.Call=function(e,t,n,r){this.name=e,this.args=t,this.index=n,this.filename=r},e.Call.prototype={eval:function(t){var n=this.args.map(function(e){return e.eval(t)}),r;if(this.name in e.functions)try{r=e.functions[this.name].apply(e.functions,n);if(r!=null)return r}catch(i){throw{type:i.type||"Runtime",message:"error evaluating function `"+this.name+"`"+(i.message?": "+i.message:""),index:this.index,filename:this.filename}}return new e.Anonymous(this.name+"("+n.map(function(e){return e.toCSS(t)}).join(", ")+")")},toCSS:function(e){return this.eval(e).toCSS()}}}(n("../tree")),function(e){e.Color=function(e,t){Array.isArray(e)?this.rgb=e:e.length==6?this.rgb=e.match(/.{2}/g).map(function(e){return parseInt(e,16)}):this.rgb=e.split("").map(function(e){return parseInt(e+e,16)}),this.alpha=typeof t=="number"?t:1},e.Color.prototype={eval:function(){return this},toCSS:function(){return this.alpha<1?"rgba("+this.rgb.map(function(e){return Math.round(e)}).concat(this.alpha).join(", ")+")":"#"+this.rgb.map(function(e){return e=Math.round(e),e=(e>255?255:e<0?0:e).toString(16),e.length===1?"0"+e:e}).join("")},operate:function(t,n){var r=[];n instanceof e.Color||(n=n.toColor());for(var i=0;i<3;i++)r[i]=e.operate(t,this.rgb[i],n.rgb[i]);return new e.Color(r,this.alpha+n.alpha)},toHSL:function(){var e=this.rgb[0]/255,t=this.rgb[1]/255,n=this.rgb[2]/255,r=this.alpha,i=Math.max(e,t,n),s=Math.min(e,t,n),o,u,a=(i+s)/2,f=i-s;if(i===s)o=u=0;else{u=a>.5?f/(2-i-s):f/(i+s);switch(i){case e:o=(t-n)/f+(t<n?6:0);break;case t:o=(n-e)/f+2;break;case n:o=(e-t)/f+4}o/=6}return{h:o*360,s:u,l:a,a:r}},toARGB:function(){var e=[Math.round(this.alpha*255)].concat(this.rgb);return"#"+e.map(function(e){return e=Math.round(e),e=(e>255?255:e<0?0:e).toString(16),e.length===1?"0"+e:e}).join("")},compare:function(e){return e.rgb?e.rgb[0]===this.rgb[0]&&e.rgb[1]===this.rgb[1]&&e.rgb[2]===this.rgb[2]&&e.alpha===this.alpha?0:-1:-1}}}(n("../tree")),function(e){e.Comment=function(e,t){this.value=e,this.silent=!!t},e.Comment.prototype={toCSS:function(e){return e.compress?"":this.value},eval:function(){return this}}}(n("../tree")),function(e){e.Condition=function(e,t,n,r,i){this.op=e.trim(),this.lvalue=t,this.rvalue=n,this.index=r,this.negate=i},e.Condition.prototype.eval=function(e){var t=this.lvalue.eval(e),n=this.rvalue.eval(e),r=this.index,i,i=function(e){switch(e){case"and":return t&&n;case"or":return t||n;default:if(t.compare)i=t.compare(n);else{if(!n.compare)throw{type:"Type",message:"Unable to perform comparison",index:r};i=n.compare(t)}switch(i){case-1:return e==="<"||e==="=<";case 0:return e==="="||e===">="||e==="=<";case 1:return e===">"||e===">="}}}(this.op);return this.negate?!i:i}}(n("../tree")),function(e){e.Dimension=function(e,t){this.value=parseFloat(e),this.unit=t||null},e.Dimension.prototype={eval:function(){return this},toColor:function(){return new e.Color([this.value,this.value,this.value])},toCSS:function(){var e=this.value+this.unit;return e},operate:function(t,n){return new e.Dimension(e.operate(t,this.value,n.value),this.unit||n.unit)},compare:function(t){return t instanceof e.Dimension?t.value>this.value?-1:t.value<this.value?1:t.unit&&this.unit!==t.unit?-1:0:-1}}}(n("../tree")),function(e){e.Directive=function(t,n){this.name=t,Array.isArray(n)?(this.ruleset=new e.Ruleset([],n),this.ruleset.allowImports=!0):this.value=n},e.Directive.prototype={toCSS:function(e,t){return this.ruleset?(this.ruleset.root=!0,this.name+(t.compress?"{":" {\n ")+this.ruleset.toCSS(e,t).trim().replace(/\n/g,"\n ")+(t.compress?"}":"\n}\n")):this.name+" "+this.value.toCSS()+";\n"},eval:function(t){var n=this;return this.ruleset&&(t.frames.unshift(this),n=new e.Directive(this.name),n.ruleset=this.ruleset.eval(t),t.frames.shift()),n},variable:function(t){return e.Ruleset.prototype.variable.call(this.ruleset,t)},find:function(){return e.Ruleset.prototype.find.apply(this.ruleset,arguments)},rulesets:function(){return e.Ruleset.prototype.rulesets.apply(this.ruleset)}}}(n("../tree")),function(e){e.Element=function(t,n,r){this.combinator=t instanceof e.Combinator?t:new e.Combinator(t),typeof n=="string"?this.value=n.trim():n?this.value=n:thisLine truncated
/*!
* Less - Leaner CSS v2.7.1
* http://lesscss.org
*
* Copyright (c) 2009-2016, Alexis Sellier <self@cloudhead.net>
* Licensed under the Apache-2.0 License.
*
*/
/** * @license Apache-2.0
*/
!function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,b.less=a()}}(function(){return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;d.length>g;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("./utils").addDataAttr,e=a("./browser");b.exports=function(a,b){d(b,e.currentScript(a)),void 0===b.isFileProtocol&&(b.isFileProtocol=/^(file|(chrome|safari)(-extension)?|resource|qrc|app):/.test(a.location.protocol)),b.async=b.async||!1,b.fileAsync=b.fileAsync||!1,b.poll=b.poll||(b.isFileProtocol?1e3:1500),b.env=b.env||("127.0.0.1"==a.location.hostname||"0.0.0.0"==a.location.hostname||"localhost"==a.location.hostname||a.location.port&&a.location.port.length>0||b.isFileProtocol?"development":"production");var c=/!dumpLineNumbers:(comments|mediaquery|all)/.exec(a.location.hash);c&&(b.dumpLineNumbers=c[1]),void 0===b.useFileCache&&(b.useFileCache=!0),void 0===b.onReady&&(b.onReady=!0)}},{"./browser":3,"./utils":10}],2:[function(a,b,c){function d(a){a.filename&&console.warn(a),e.async||h.removeChild(i)}a("promise/polyfill.js");var e=window.less||{};a("./add-default-options")(window,e);var f=b.exports=a("./index")(window,e);window.less=f;var g,h,i;e.onReady&&(/!watch/.test(window.location.hash)&&f.watch(),e.async||(g="body { display: none !important }",h=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style"),i.type="text/css",i.styleSheet?i.styleSheet.cssText=g:i.appendChild(document.createTextNode(g)),h.appendChild(i)),f.registerStylesheetsImmediately(),f.pageLoadFinished=f.refresh("development"===f.env).then(d,d))},{"./add-default-options":1,"./index":8,"promise/polyfill.js":97}],3:[function(a,b,c){var d=a("./utils");b.exports={createCSS:function(a,b,c){var e=c.href||"",f="less:"+(c.title||d.extractId(e)),g=a.getElementById(f),h=!1,i=a.createElement("style");i.setAttribute("type","text/css"),c.media&&i.setAttribute("media",c.media),i.id=f,i.styleSheet||(i.appendChild(a.createTextNode(b)),h=null!==g&&g.childNodes.length>0&&i.childNodes.length>0&&g.firstChild.nodeValue===i.firstChild.nodeValue);var j=a.getElementsByTagName("head")[0];if(null===g||h===!1){var k=c&&c.nextSibling||null;k?k.parentNode.insertBefore(i,k):j.appendChild(i)}if(g&&h===!1&&g.parentNode.removeChild(g),i.styleSheet)try{i.styleSheet.cssText=b}catch(l){throw new Error("Couldn't reassign styleSheet.cssText.")}},currentScript:function(a){var b=a.document;return b.currentScript||function(){var a=b.getElementsByTagName("script");return a[a.length-1]}()}}},{"./utils":10}],4:[function(a,b,c){b.exports=function(a,b,c){var d=null;if("development"!==b.env)try{d="undefined"==typeof a.localStorage?null:a.localStorage}catch(e){}return{setCSS:function(a,b,e,f){if(d){c.info("saving "+a+" to cache.");try{d.setItem(a,f),d.setItem(a+":timestamp",b),e&&d.setItem(a+":vars",JSON.stringify(e))}catch(g){c.error('failed to save "'+a+'" to local storage for caching.')}}},getCSS:function(a,b,c){var e=d&&d.getItem(a),f=d&&d.getItem(a+":timestamp"),g=d&&d.getItem(a+":vars");return c=c||{},f&&b.lastModified&&new Date(b.lastModified).valueOf()===new Date(f).valueOf()&&(!c&&!g||JSON.stringify(c)===g)?e:void 0}}}},{}],5:[function(a,b,c){var d=a("./utils"),e=a("./browser");b.exports=function(a,b,c){function f(b,f){var g,h,i="less-error-message:"+d.extractId(f||""),j='<li><label>{line}</label><pre class="{class}">{content}</pre></li>',k=a.document.createElement("div"),l=[],m=b.filename||f,n=m.match(/([^\/]+(\?.*)?)$/)[1];k.id=i,k.className="less-error-message",h="<h3>"+(b.type||"Syntax")+"Error: "+(b.message||"There is an error in your .less file")+'</h3><p>in <a href="'+m+'">'+n+"</a> ";var o=function(a,b,c){void 0!==a.extract[b]&&l.push(j.replace(/\{line\}/,(parseInt(a.line,10)||0)+(b-1)).replace(/\{class\}/,c).replace(/\{content\}/,a.extract[b]))};b.extract&&(o(b,0,""),o(b,1,"line"),o(b,2,""),h+="on line "+b.line+", column "+(b.column+1)+":</p><ul>"+l.join("")+"</ul>"),b.stack&&(b.extract||c.logLevel>=4)&&(h+="<br/>Stack Trace</br />"+b.stack.split("\n").slice(1).join("<br/>")),k.innerHTML=h,e.createCSS(a.document,[".less-error-message ul, .less-error-message li {","list-style-type: none;","margin-right: 15px;","padding: 4px 0;","margin: 0;","}",".less-error-message label {","font-size: 12px;","margin-right: 15px;","padding: 4px 0;","color: #cc7777;","}",".less-error-message pre {","color: #dd6666;","padding: 4px 0;","margin: 0;","display: inline-block;","}",".less-error-message pre.line {","cLine truncated
}})},{"../tree/anonymous":46,"../tree/javascript":63,"../tree/quoted":73,"./function-registry":22}],28:[function(a,b,c){b.exports=function(b){var c=a("../tree/dimension"),d=a("../tree/color"),e=a("../tree/expression"),f=a("../tree/quoted"),g=a("../tree/url"),h=a("./function-registry");h.add("svg-gradient",function(a){function b(){throw{type:"Argument",message:"svg-gradient expects direction, start_color [start_position], [color position,]..., end_color [end_position] or direction, color list"}}var h,i,j,k,l,m,n,o,p="linear",q='x="0" y="0" width="1" height="1"',r={compress:!1},s=a.toCSS(r);switch(2==arguments.length?(2>arguments[1].value.length&&b(),h=arguments[1].value):3>arguments.length?b():h=Array.prototype.slice.call(arguments,1),s){case"to bottom":i='x1="0%" y1="0%" x2="0%" y2="100%"';break;case"to right":i='x1="0%" y1="0%" x2="100%" y2="0%"';break;case"to bottom right":i='x1="0%" y1="0%" x2="100%" y2="100%"';break;case"to top right":i='x1="0%" y1="100%" x2="100%" y2="0%"';break;case"ellipse":case"ellipse at center":p="radial",i='cx="50%" cy="50%" r="75%"',q='x="-50" y="-50" width="101" height="101"';break;default:throw{type:"Argument",message:"svg-gradient direction must be 'to bottom', 'to right', 'to bottom right', 'to top right' or 'ellipse at center'"}}for(j='<?xml version="1.0" ?><svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none"><'+p+'Gradient id="gradient" gradientUnits="userSpaceOnUse" '+i+">",k=0;h.length>k;k+=1)h[k]instanceof e?(l=h[k].value[0],m=h[k].value[1]):(l=h[k],m=void 0),l instanceof d&&((0===k||k+1===h.length)&&void 0===m||m instanceof c)||b(),n=m?m.toCSS(r):0===k?"0%":"100%",o=l.alpha,j+='<stop offset="'+n+'" stop-color="'+l.toRGB()+'"'+(1>o?' stop-opacity="'+o+'"':"")+"/>";return j+="</"+p+"Gradient><rect "+q+' fill="url(#gradient)" /></svg>',j=encodeURIComponent(j),j="data:image/svg+xml,"+j,new g(new f("'"+j+"'",j,!1,this.index,this.currentFileInfo),this.index,this.currentFileInfo)})}},{"../tree/color":50,"../tree/dimension":56,"../tree/expression":59,"../tree/quoted":73,"../tree/url":80,"./function-registry":22}],29:[function(a,b,c){var d=a("../tree/keyword"),e=a("../tree/detached-ruleset"),f=a("../tree/dimension"),g=a("../tree/color"),h=a("../tree/quoted"),i=a("../tree/anonymous"),j=a("../tree/url"),k=a("../tree/operation"),l=a("./function-registry"),m=function(a,b){return a instanceof b?d.True:d.False},n=function(a,b){if(void 0===b)throw{type:"Argument",message:"missing the required second argument to isunit."};if(b="string"==typeof b.value?b.value:b,"string"!=typeof b)throw{type:"Argument",message:"Second argument to isunit should be a unit or a string."};return a instanceof f&&a.unit.is(b)?d.True:d.False},o=function(a){var b=Array.isArray(a.value)?a.value:Array(a);return b};l.addMultiple({isruleset:function(a){return m(a,e)},iscolor:function(a){return m(a,g)},isnumber:function(a){return m(a,f)},isstring:function(a){return m(a,h)},iskeyword:function(a){return m(a,d)},isurl:function(a){return m(a,j)},ispixel:function(a){return n(a,"px")},ispercentage:function(a){return n(a,"%")},isem:function(a){return n(a,"em")},isunit:n,unit:function(a,b){if(!(a instanceof f))throw{type:"Argument",message:"the first argument to unit must be a number"+(a instanceof k?". Have you forgotten parenthesis?":"")};return b=b?b instanceof d?b.value:b.toCSS():"",new f(a.value,b)},"get-unit":function(a){return new i(a.unit)},extract:function(a,b){return b=b.value-1,o(a)[b]},length:function(a){return new f(o(a).length)}})},{"../tree/anonymous":46,"../tree/color":50,"../tree/detached-ruleset":55,"../tree/dimension":56,"../tree/keyword":65,"../tree/operation":71,"../tree/quoted":73,"../tree/url":80,"./function-registry":22}],30:[function(a,b,c){var d=a("./contexts"),e=a("./parser/parser"),f=a("./plugins/function-importer");b.exports=function(a){var b=function(a,b){this.rootFilename=b.filename,this.paths=a.paths||[],this.contents={},this.contentsIgnoredChars={},this.mime=a.mime,this.error=null,this.context=a,this.queue=[],this.files={}};return b.prototype.push=function(b,c,g,h,i){var j=this;this.queue.push(b);var k=function(a,c,d){j.queue.splice(j.queue.indexOf(b),1);var e=d===j.rootFilename;h.optional&&a?i(null,{rules:[]},!1,null):(j.files[d]=c,a&&!j.error&&(j.error=a),i(a,c,e,d))},l={relativeUrls:this.context.relativeUrls,entryPath:g.entryPath,rootpath:g.rootpath,rootFilename:g.rootFilename},m=a.getFileManager(b,g.currentDirectory,this.context,a);if(!m)return void k({message:"Could not find a file-manager for "+b});c&&(b=m.tryAppendExtension(b,h.plugin?".js":".less"));var n=function(a){var b=a.filename,c=a.contents.replace(/^\uFEFF/,"");l.currentDirectory=m.getPath(b),l.relativeUrls&&(l.rootpath=m.join(j.context.rootpath||"",m.pathDiff(l.currentDirectory,l.entryPath)),!m.isPathAbsolute(l.rootpath)&&m.alwaysMakePathsAbsolute()&&(l.rootpath=m.join(l.entryPath,l.rootpath))),l.filename=b;var i=new d.Parse(j.context);i.processImports=Line truncated
f={add:function(a,b){g[a]=b},addMultiple:function(a){Object.keys(a).forEach(function(b){g[b]=a[b]})}};try{c=new Function("functions","tree","fileInfo",a),c(f,e,this.fileInfo)}catch(h){b(new d({message:"Plugin evaluation error: '"+h.name+": "+h.message.replace(/["]/g,"'")+"'",filename:this.fileInfo.filename}),null)}b(null,{functions:g})}},{"../less-error":32,"../tree":62}],41:[function(a,b,c){var d;b.exports=function(b,c,e){var f=function(b,e,g){if("function"==typeof e&&(g=e,e={}),!g){d||(d="undefined"==typeof Promise?a("promise"):Promise);var h=this;return new d(function(a,c){f.call(h,b,e,function(b,d){b?c(b):a(d)})})}this.parse(b,e,function(a,b,d,e){if(a)return g(a);var f;try{var h=new c(b,d);f=h.toCSS(e)}catch(a){return g(a)}g(null,f)})};return f}},{promise:void 0}],42:[function(a,b,c){b.exports=function(a,b){var c=function(a){this.options=a};return c.prototype.toCSS=function(b,c,d){var e=new a({contentsIgnoredCharsMap:d.contentsIgnoredChars,rootNode:b,contentsMap:d.contents,sourceMapFilename:this.options.sourceMapFilename,sourceMapURL:this.options.sourceMapURL,outputFilename:this.options.sourceMapOutputFilename,sourceMapBasepath:this.options.sourceMapBasepath,sourceMapRootpath:this.options.sourceMapRootpath,outputSourceFiles:this.options.outputSourceFiles,sourceMapGenerator:this.options.sourceMapGenerator,sourceMapFileInline:this.options.sourceMapFileInline}),f=e.toCSS(c);return this.sourceMap=e.sourceMap,this.sourceMapURL=e.sourceMapURL,this.options.sourceMapInputFilename&&(this.sourceMapInputFilename=e.normalizeFilename(this.options.sourceMapInputFilename)),f+this.getCSSAppendage()},c.prototype.getCSSAppendage=function(){var a=this.sourceMapURL;if(this.options.sourceMapFileInline){if(void 0===this.sourceMap)return"";a="data:application/json;base64,"+b.encodeBase64(this.sourceMap)}return a?"/*# sourceMappingURL="+a+" */":""},c.prototype.getExternalSourceMap=function(){return this.sourceMap},c.prototype.setExternalSourceMap=function(a){this.sourceMap=a},c.prototype.isInline=function(){return this.options.sourceMapFileInline},c.prototype.getSourceMapURL=function(){return this.sourceMapURL},c.prototype.getOutputFilename=function(){return this.options.sourceMapOutputFilename},c.prototype.getInputFilename=function(){return this.sourceMapInputFilename},c}},{}],43:[function(a,b,c){b.exports=function(a){var b=function(b){this._css=[],this._rootNode=b.rootNode,this._contentsMap=b.contentsMap,this._contentsIgnoredCharsMap=b.contentsIgnoredCharsMap,b.sourceMapFilename&&(this._sourceMapFilename=b.sourceMapFilename.replace(/\\/g,"/")),this._outputFilename=b.outputFilename,this.sourceMapURL=b.sourceMapURL,b.sourceMapBasepath&&(this._sourceMapBasepath=b.sourceMapBasepath.replace(/\\/g,"/")),b.sourceMapRootpath?(this._sourceMapRootpath=b.sourceMapRootpath.replace(/\\/g,"/"),"/"!==this._sourceMapRootpath.charAt(this._sourceMapRootpath.length-1)&&(this._sourceMapRootpath+="/")):this._sourceMapRootpath="",this._outputSourceFiles=b.outputSourceFiles,this._sourceMapGeneratorConstructor=a.getSourceMapGenerator(),this._lineNumber=0,this._column=0};return b.prototype.normalizeFilename=function(a){return a=a.replace(/\\/g,"/"),this._sourceMapBasepath&&0===a.indexOf(this._sourceMapBasepath)&&(a=a.substring(this._sourceMapBasepath.length),"\\"!==a.charAt(0)&&"/"!==a.charAt(0)||(a=a.substring(1))),(this._sourceMapRootpath||"")+a},b.prototype.add=function(a,b,c,d){if(a){var e,f,g,h,i;if(b){var j=this._contentsMap[b.filename];this._contentsIgnoredCharsMap[b.filename]&&(c-=this._contentsIgnoredCharsMap[b.filename],0>c&&(c=0),j=j.slice(this._contentsIgnoredCharsMap[b.filename])),j=j.substring(0,c),f=j.split("\n"),h=f[f.length-1]}if(e=a.split("\n"),g=e[e.length-1],b)if(d)for(i=0;e.length>i;i++)this._sourceMapGenerator.addMapping({generated:{line:this._lineNumber+i+1,column:0===i?this._column:0},original:{line:f.length+i,column:0===i?h.length:0},source:this.normalizeFilename(b.filename)});else this._sourceMapGenerator.addMapping({generated:{line:this._lineNumber+1,column:this._column},original:{line:f.length,column:h.length},source:this.normalizeFilename(b.filename)});1===e.length?this._column+=g.length:(this._lineNumber+=e.length-1,this._column=g.length),this._css.push(a)}},b.prototype.isEmpty=function(){return 0===this._css.length},b.prototype.toCSS=function(a){if(this._sourceMapGenerator=new this._sourceMapGeneratorConstructor({file:this._outputFilename,sourceRoot:null}),this._outputSourceFiles)for(var b in this._contentsMap)if(this._contentsMap.hasOwnProperty(b)){var c=this._contentsMap[b];this._contentsIgnoredCharsMap[b]&&(c=c.slice(this._contentsIgnoredCharsMap[b])),this._sourceMapGenerator.setSourceContent(this.normalizeFilename(b),c)}if(this._rootNode.genCSS(a,this),this._css.length>0){var d,e=JSON.stringify(this._sourceMapGenerator.toJSON());this.sourceMapURL?d=this.sourceMapURL:this._sourceMapFilename&&(d=this._sourceMapFilename),this.sourceMapURL=d,this.sourceMap=e}return this._css.join("")},b}},{}],44:[function(a,b,c){var dLine truncated
this._setVisibilityToReplacement(C),Array.prototype.push.apply(u,C)}catch(D){throw{message:D.message,index:this.index,filename:this.currentFileInfo.filename,stack:D.stack}}if(v)return u}throw n?{type:"Runtime",message:"No matching definition was found for `"+this.format(t)+"`",index:this.index,filename:this.currentFileInfo.filename}:{type:"Name",message:this.selector.toCSS().trim()+" is undefined",index:this.index,filename:this.currentFileInfo.filename}},h.prototype._setVisibilityToReplacement=function(a){var b,c;if(this.blocksVisibility())for(b=0;a.length>b;b++)c=a[b],c.addVisibilityBlock()},h.prototype.format=function(a){return this.selector.toCSS().trim()+"("+(a?a.map(function(a){var b="";return a.name&&(b+=a.name+":"),b+=a.value.toCSS?a.value.toCSS():"???"}).join(", "):"")+")"},b.exports=h},{"../functions/default":20,"./mixin-definition":68,"./node":70,"./selector":77}],68:[function(a,b,c){var d=a("./selector"),e=a("./element"),f=a("./ruleset"),g=a("./rule"),h=a("./expression"),i=a("../contexts"),j=function(a,b,c,f,g,h,i){this.name=a,this.selectors=[new d([new e(null,a,this.index,this.currentFileInfo)])],this.params=b,this.condition=f,this.variadic=g,this.arity=b.length,this.rules=c,this._lookups={};var j=[];this.required=b.reduce(function(a,b){return!b.name||b.name&&!b.value?a+1:(j.push(b.name),a)},0),this.optionalParameters=j,this.frames=h,this.copyVisibilityInfo(i),this.allowRoot=!0};j.prototype=new f,j.prototype.type="MixinDefinition",j.prototype.evalFirst=!0,j.prototype.accept=function(a){this.params&&this.params.length&&(this.params=a.visitArray(this.params)),this.rules=a.visitArray(this.rules),this.condition&&(this.condition=a.visit(this.condition))},j.prototype.evalParams=function(a,b,c,d){var e,j,k,l,m,n,o,p,q=new f(null,null),r=this.params.slice(0),s=0;if(b.frames&&b.frames[0]&&b.frames[0].functionRegistry&&(q.functionRegistry=b.frames[0].functionRegistry.inherit()),b=new i.Eval(b,[q].concat(b.frames)),c)for(c=c.slice(0),s=c.length,k=0;s>k;k++)if(j=c[k],n=j&&j.name){for(o=!1,l=0;r.length>l;l++)if(!d[l]&&n===r[l].name){d[l]=j.value.eval(a),q.prependRule(new g(n,j.value.eval(a))),o=!0;break}if(o){c.splice(k,1),k--;continue}throw{type:"Runtime",message:"Named argument for "+this.name+" "+c[k].name+" not found"}}for(p=0,k=0;r.length>k;k++)if(!d[k]){if(j=c&&c[p],n=r[k].name)if(r[k].variadic){for(e=[],l=p;s>l;l++)e.push(c[l].value.eval(a));q.prependRule(new g(n,new h(e).eval(a)))}else{if(m=j&&j.value)m=m.eval(a);else{if(!r[k].value)throw{type:"Runtime",message:"wrong number of arguments for "+this.name+" ("+s+" for "+this.arity+")"};m=r[k].value.eval(b),q.resetCache()}q.prependRule(new g(n,m)),d[k]=m}if(r[k].variadic&&c)for(l=p;s>l;l++)d[l]=c[l].value.eval(a);p++}return q},j.prototype.makeImportant=function(){var a=this.rules?this.rules.map(function(a){return a.makeImportant?a.makeImportant(!0):a}):this.rules,b=new j(this.name,this.params,a,this.condition,this.variadic,this.frames);return b},j.prototype.eval=function(a){return new j(this.name,this.params,this.rules,this.condition,this.variadic,this.frames||a.frames.slice(0))},j.prototype.evalCall=function(a,b,c){var d,e,j=[],k=this.frames?this.frames.concat(a.frames):a.frames,l=this.evalParams(a,new i.Eval(a,k),b,j);return l.prependRule(new g("@arguments",new h(j).eval(a))),d=this.rules.slice(0),e=new f(null,d),e.originalRuleset=this,e=e.eval(new i.Eval(a,[this,l].concat(k))),c&&(e=e.makeImportant()),e},j.prototype.matchCondition=function(a,b){return!this.condition||this.condition.eval(new i.Eval(b,[this.evalParams(b,new i.Eval(b,this.frames?this.frames.concat(b.frames):b.frames),a,[])].concat(this.frames||[]).concat(b.frames)))},j.prototype.matchArgs=function(a,b){var c,d=a&&a.length||0,e=this.optionalParameters,f=a?a.reduce(function(a,b){return e.indexOf(b.name)<0?a+1:a},0):0;if(this.variadic){if(this.required-1>f)return!1}else{if(this.required>f)return!1;if(d>this.params.length)return!1}c=Math.min(f,this.arity);for(var g=0;c>g;g++)if(!this.params[g].name&&!this.params[g].variadic&&a[g].value.eval(b).toCSS()!=this.params[g].value.eval(b).toCSS())return!1;return!0},b.exports=j},{"../contexts":11,"./element":58,"./expression":59,"./rule":74,"./ruleset":76,"./selector":77}],69:[function(a,b,c){var d=a("./node"),e=a("./operation"),f=a("./dimension"),g=function(a){this.value=a};g.prototype=new d,g.prototype.type="Negative",g.prototype.genCSS=function(a,b){b.add("-"),this.value.genCSS(a,b)},g.prototype.eval=function(a){return a.isMathOn()?new e("*",[new f(-1),this.value]).eval(a):new g(this.value.eval(a))},b.exports=g},{"./dimension":56,"./node":70,"./operation":71}],70:[function(a,b,c){var d=function(){};d.prototype.toCSS=function(a){var b=[];return this.genCSS(a,{add:function(a,c,d){b.push(a)},isEmpty:function(){return 0===b.length}}),b.join("")},d.prototype.genCSS=function(a,b){b.add(this.value)},d.prototype.accept=function(a){this.value=a.visit(this.value)},d.prototype.eval=function(){return this},d.prototype._operate=function(a,b,c,d){switch(b){caLine truncated
this.variableImports.push(a)},d.prototype.tryRun=function(){this._currentDepth++;try{for(;;){for(;this.imports.length>0;){var a=this.imports[0];if(!a.isReady)return;this.imports=this.imports.slice(1),a.callback.apply(null,a.args)}if(0===this.variableImports.length)break;var b=this.variableImports[0];this.variableImports=this.variableImports.slice(1),b()}}finally{this._currentDepth--}0===this._currentDepth&&this._onSequencerEmpty&&this._onSequencerEmpty()},b.exports=d},{}],86:[function(a,b,c){var d=a("../contexts"),e=a("./visitor"),f=a("./import-sequencer"),g=function(a,b){this._visitor=new e(this),this._importer=a,this._finish=b,this.context=new d.Eval,this.importCount=0,this.onceFileDetectionMap={},this.recursionDetector={},this._sequencer=new f(this._onSequencerEmpty.bind(this))};g.prototype={isReplacing:!1,run:function(a){try{this._visitor.visit(a)}catch(b){this.error=b}this.isFinished=!0,this._sequencer.tryRun()},_onSequencerEmpty:function(){this.isFinished&&this._finish(this.error)},visitImport:function(a,b){var c=a.options.inline;if(!a.css||c){var e=new d.Eval(this.context,this.context.frames.slice(0)),f=e.frames[0];this.importCount++,a.isVariableImport()?this._sequencer.addVariableImport(this.processImportNode.bind(this,a,e,f)):this.processImportNode(a,e,f)}b.visitDeeper=!1},processImportNode:function(a,b,c){var d,e=a.options.inline;try{d=a.evalForImport(b)}catch(f){f.filename||(f.index=a.index,f.filename=a.currentFileInfo.filename),a.css=!0,a.error=f}if(!d||d.css&&!e)this.importCount--,this.isFinished&&this._sequencer.tryRun();else{d.options.multiple&&(b.importMultiple=!0);for(var g=void 0===d.css,h=0;c.rules.length>h;h++)if(c.rules[h]===a){c.rules[h]=d;break}var i=this.onImported.bind(this,d,b),j=this._sequencer.addImport(i);this._importer.push(d.getPath(),g,d.currentFileInfo,d.options,j)}},onImported:function(a,b,c,d,e,f){c&&(c.filename||(c.index=a.index,c.filename=a.currentFileInfo.filename),this.error=c);var g=this,h=a.options.inline,i=a.options.plugin,j=a.options.optional,k=e||f in g.recursionDetector;if(b.importMultiple||(a.skip=k?!0:function(){return f in g.onceFileDetectionMap?!0:(g.onceFileDetectionMap[f]=!0,!1)}),!f&&j&&(a.skip=!0),d&&(a.root=d,a.importedFilename=f,!h&&!i&&(b.importMultiple||!k))){g.recursionDetector[f]=!0;var l=this.context;this.context=b;try{this._visitor.visit(d)}catch(c){this.error=c}this.context=l}g.importCount--,g.isFinished&&g._sequencer.tryRun()},visitRule:function(a,b){"DetachedRuleset"===a.value.type?this.context.frames.unshift(a):b.visitDeeper=!1},visitRuleOut:function(a){"DetachedRuleset"===a.value.type&&this.context.frames.shift()},visitDirective:function(a,b){this.context.frames.unshift(a)},visitDirectiveOut:function(a){this.context.frames.shift()},visitMixinDefinition:function(a,b){this.context.frames.unshift(a)},visitMixinDefinitionOut:function(a){this.context.frames.shift()},visitRuleset:function(a,b){this.context.frames.unshift(a)},visitRulesetOut:function(a){this.context.frames.shift()},visitMedia:function(a,b){this.context.frames.unshift(a.rules[0])},visitMediaOut:function(a){this.context.frames.shift()}},b.exports=g},{"../contexts":11,"./import-sequencer":85,"./visitor":91}],87:[function(a,b,c){var d={Visitor:a("./visitor"),ImportVisitor:a("./import-visitor"),MarkVisibleSelectorsVisitor:a("./set-tree-visibility-visitor"),ExtendVisitor:a("./extend-visitor"),JoinSelectorVisitor:a("./join-selector-visitor"),ToCSSVisitor:a("./to-css-visitor")};b.exports=d},{"./extend-visitor":84,"./import-visitor":86,"./join-selector-visitor":88,"./set-tree-visibility-visitor":89,"./to-css-visitor":90,"./visitor":91}],88:[function(a,b,c){var d=a("./visitor"),e=function(){this.contexts=[[]],this._visitor=new d(this)};e.prototype={run:function(a){return this._visitor.visit(a)},visitRule:function(a,b){b.visitDeeper=!1},visitMixinDefinition:function(a,b){b.visitDeeper=!1},visitRuleset:function(a,b){var c,d=this.contexts[this.contexts.length-1],e=[];this.contexts.push(e),a.root||(c=a.selectors,c&&(c=c.filter(function(a){return a.getIsOutput()}),a.selectors=c.length?c:c=null,c&&a.joinSelectors(e,d,c)),c||(a.rules=null),a.paths=e)},visitRulesetOut:function(a){this.contexts.length=this.contexts.length-1},visitMedia:function(a,b){var c=this.contexts[this.contexts.length-1];a.rules[0].root=0===c.length||c[0].multiMedia},visitDirective:function(a,b){var c=this.contexts[this.contexts.length-1];a.rules&&a.rules.length&&(a.rules[0].root=a.isRooted||0===c.length||null)}},b.exports=e},{"./visitor":91}],89:[function(a,b,c){var d=function(a){this.visible=a};d.prototype.run=function(a){this.visit(a)},d.prototype.visitArray=function(a){if(!a)return a;var b,c=a.length;for(b=0;c>b;b++)this.visit(a[b]);return a},d.prototype.visit=function(a){return a?a.constructor===Array?this.visitArray(a):!a.blocksVisibility||a.blocksVisibility()?a:(this.visible?a.ensureVisibility():a.ensureInvisibility(),a.accept(this),a):a},b.exports=d},{}],90:[function(a,b,c){var d=a("../tree"),e=a("./visitor"),f=function(Line truncated
+74
View File
@@ -513,6 +513,14 @@ ul.dropdown-menu li a {
}
}
/** State sidebar panel */
#state_wrapper {
hr {
margin: 5px 0;
}
}
/** GCODE file manager */
#files {
@@ -552,6 +560,20 @@ ul.dropdown-menu li a {
.additionalInfo {
padding-bottom: @line-height + 2px;
}
@highlight-color: yellow;
@keyframes highlightframes {
0% {
background: @highlight-color;
}
100% {
background: transparent;
}
}
&.highlight {
animation: highlightframes 2s;
}
}
}
@@ -1040,3 +1062,55 @@ _::-webkit-full-page-media, _:future, :root .full-sized-box {
input[type=number] {
text-align: right;
}
// Progress bars with text
//
// .progress-text-front will also need to have the full width of the enclosing
// progress wrapper applied (e.g. via copyWidth knockout binding)
.progress-text,
.progress-text-centered {
position: relative;
.progress-text-front,
.progress-text-back {
white-space: nowrap;
}
.progress-text-front {
box-sizing: border-box;
padding: 0 10px;
width: 100%;
display: block;
}
.progress-text-back {
position: absolute;
font-size: 12px;
line-height: 20px;
display: block;
box-sizing: border-box;
text-align: center;
padding: 0 10px;
}
.bar {
position: absolute;
overflow: hidden;
}
}
.progress-text-centered {
.progress-text-front {
position: absolute;
font-size: 12px;
line-height: 20px;
display: block;
text-align: center;
color: #fff;
}
.progress-text-back {
width: 100%;
}
}
+1 -1
View File
@@ -38,7 +38,7 @@
class="tab-pane {% if mark_active %}active{% set mark_active = False %}{% endif %} {% if classes_content in data %}{{ data.classes_content|join(' ') }}{% elif classes in data %}{{ data.classes|join(' ') }}{% endif %}"
{% if "styles_content" in data %} style="{{ data.styles_content|join(', ') }}" {% elif styles in data %} style="{{ data.styles|join(', ') }}" {% endif %}
>
{% include data.template ignore missing %}
{% try "There was an error with the template {filename} at line number {lineno}: {exception}" %}{% include data.template ignore missing %}{% endtry %}
</div>
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
{% endif %}
@@ -38,7 +38,7 @@
class="tab-pane {% if mark_active %}active{% set mark_active = False %}{% endif %} {% if classes_content in data %}{{ data.classes_content|join(' ') }}{% elif classes in data %}{{ data.classes|join(' ') }}{% endif %}"
{% if "styles_content" in data %} style="{{ data.styles_content|join(', ') }}" {% elif styles in data %} style="{{ data.styles|join(', ') }}" {% endif %}
>
{% include data.template ignore missing %}
{% try "There was an error with the template {filename} at line number {lineno}: {exception}" %}{% include data.template ignore missing %}{% endtry %}
</div>
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
{% endif %}
@@ -34,6 +34,13 @@
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_sdRelativePath" id="settings-sdRelativePath"> {{ _('Select SD files by relative path') }} <span class="label">{{ _('RepRap Firmware') }}</span>
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
@@ -126,6 +126,24 @@
<input type="checkbox" data-bind="checked: serial_supportResendsWithoutOk" id="settings-supportResendsWithoutOk"> {{ _('Simulate an additional `ok` for resend requests') }}
</label>
</div>
<div class="control-group" title="{{ _('Maximum consecutive communication timeouts while idle. More than this and the printer will be considered to be gone. Set to 0 to disable.') }}">
<label class="control-label" for="settings-serialMaxTimeoutsIdle">{{ _('Max. consecutive timeouts while idle') }}</label>
<div class="controls">
<input type="number" min="0" class="input-mini text-right" id="settings-serialMaxTimeoutsIdle" data-bind="value: serial_maxTimeoutsIdle">
</div>
</div>
<div class="control-group" title="{{ _('Maximum consecutive communication timeouts while printing. More than this and the printer will be considered to be gone. Set to 0 to disable.') }}">
<label class="control-label" for="settings-serialMaxTimeoutsPrinting">{{ _('Max. consecutive timeouts while printing') }}</label>
<div class="controls">
<input type="number" min="0" class="input-mini text-right" id="settings-serialMaxTimeoutsPrinting" data-bind="value: serial_maxTimeoutsPrinting">
</div>
</div>
<div class="control-group" title="{{ _('Maximum consecutive communication timeouts while a long running command is active. More than this and the printer will be considered to be gone. Set to 0 to disable.') }}">
<label class="control-label" for="settings-serialMaxTimeoutsLong">{{ _('Max. consecutive timeouts during long running commands') }}</label>
<div class="controls">
<input type="number" min="0" class="input-mini text-right" id="settings-serialMaxTimeoutsLong" data-bind="value: serial_maxTimeoutsLong">
</div>
</div>
</div>
</div>
@@ -13,7 +13,7 @@
<div class="control-group">
<label class="control-label">{{ _('Slicer') }}</label>
<div class="controls">
<select data-bind="options: configured_slicers, optionsText: 'name', optionsValue: 'key', optionsCaption: '{{ _('Select a slicer...') }}', value: slicer, valueAllowUnset: true"></select>
<select data-bind="options: matchingSlicers, optionsText: 'name', optionsValue: 'key', optionsCaption: '{{ _('Select a slicer...') }}', value: slicer, valueAllowUnset: true"></select>
</div>
</div>
<div class="control-group">
@@ -29,11 +29,11 @@
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('GCode Filename') }}</label>
<label class="control-label">{{ _('Output Filename') }}</label>
<div class="controls">
<div class="input-append">
<input type="text" data-bind="value: gcodeFilename">
<span class="add-on">.gco</span>
<input type="text" data-bind="value: destinationFilename">
<span class="add-on" data-bind="text: '.' + destinationExtension()"></span>
</div>
</div>
</div>
@@ -35,7 +35,7 @@
class="tab-pane {% if mark_active %}active{% set mark_active = False %}{% endif %} {% if classes_content in data %}{{ data.classes_content|join(' ') }}{% elif classes in data %}{{ data.classes|join(' ') }}{% endif %}"
{% if "styles_content" in data %} style="{{ data.styles_content|join(', ') }}" {% elif styles in data %} style="{{ data.styles|join(', ') }}" {% endif %}
>
{% include data.template ignore missing %}
{% try "There was an error with the template {filename} at line number {lineno}: {exception}" %}{% include data.template ignore missing %}{% endtry %}
</div>
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
{% endif %}
@@ -25,8 +25,8 @@
<div class="controls">
<div class="input-append">
<input type="text" class="input-block-level uneditable-input" id="userSettings-access_apikey" data-bind="value: access_apikey, valueUpdate: 'input', attr: {placeholder: '{{ _('N/A') }}'}">
<a class="btn" title="Generate new Apikey" data-bind="click: function() { users.confirmGenerateApikey(); }"><i class="icon-refresh"></i></a>
<a class="btn btn-danger" title="Delete Apikey" data-bind="click: function() { users.confirmDeleteApikey(); }"><i class="icon-trash"></i></a>
<a class="btn" title="Generate new Apikey" data-bind="click: generateApikey"><i class="icon-refresh"></i></a>
<a class="btn btn-danger" title="Delete Apikey" data-bind="click: deleteApikey"><i class="icon-trash"></i></a>
</div>
</div>
+5 -5
View File
@@ -31,7 +31,7 @@
{% if "classes" in data %}class="{{ data.classes|join(' ') }}"{% endif %}
{% if "styles" in data %}style="{{ data.styles|join(', ') }}"{% endif %}
>
{% include data.template ignore missing %}
{% try "There was an error with the template {filename} at line number {lineno}: {exception}" %}{% include data.template ignore missing %}{% endtry %}
</li>
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
{% endfor %}
@@ -58,7 +58,7 @@
{% if "icon" in data %}<i class="icon-{{ data.icon }}"></i> {% endif %}{{ entry|e }}
</a>
{% if "template_header" in data %}
{% include data.template_header ignore missing %}
{% try "There was an error with the template {filename} at line number {lineno}: {exception}" %}{% include data.template_header ignore missing %}{% endtry %}
{% endif %}
</div>
<div id="{{ data._div }}"
@@ -66,7 +66,7 @@
{% if "styles_content" in data %} style="{{ data.styles_content|join(', ') }}" {% elif "styles" in data %} style="{{ data.styles|join(', ') }}"{% endif %}
>
<div class="accordion-inner">
{% include data.template ignore missing %}
{% try "There was an error with the template {filename} at line number {lineno}: {exception}" %}{% include data.template ignore missing %}{% endtry %}
</div>
</div>
</div>
@@ -102,7 +102,7 @@
{% if "data_bind" in data %}data-bind="{{ data.data_bind }}"{% endif %}
{% if "styles_content" in data %} style="{{ data.styles_content|join(', ') }}" {% elif "styles" in data %} style="{{ data.styles|join(', ') }}" {% endif %}
>
{% include data.template ignore missing %}
{% try "There was an error with the template {filename} at line number {lineno}: {exception}" %}{% include data.template ignore missing %}{% endtry %}
</div>
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
{% endfor %}
@@ -142,7 +142,7 @@
<!-- Generic plugin template files -->
{% for key in templates.generic.order %}
{% set data = templates.generic.entries[key] %}
{% include data.template ignore missing %}
{% try "<!-- There was an error with the template {filename} at line number {lineno}: {exception} -->" %}{% include data.template ignore missing %}{% endtry %}
{% endfor %}
<!-- End of generic plugin template files -->
@@ -29,6 +29,7 @@
var BRANCH = "{{ branch|e }}";
var LOCALE = "{{ g.locale|e }}";
var AVAILABLE_LOCALES = {{ locales|tojson }};
var SUPPORTED_EXTENSIONS = {{ supportedExtensions|tojson }};
var OCTOPRINT_VIEWMODELS = [];
var ADDITIONAL_VIEWMODELS = [];
+4 -11
View File
@@ -1,11 +1,4 @@
{% assets "js_libs" %}
<script type="text/javascript" src="{{ ASSET_URL }}"></script>
{% endassets %}
{% assets "js_app" %}
<script type="text/javascript" src="{{ ASSET_URL }}"></script>
{% endassets %}
{% if g.locale %}
<script type="text/javascript" src="{{ url_for('localeJs', locale=g.locale, domain='messages') }}"></script>
{% endif %}
{% assets "js_libs" %}<script type="text/javascript" src="{{ ASSET_URL }}"></script>{% endassets %}
{% assets "js_plugins" %}<script type="text/javascript" src="{{ ASSET_URL }}"></script>{% endassets %}
{% assets "js_core" %}<script type="text/javascript" src="{{ ASSET_URL }}"></script>{% endassets %}
{% if g.locale %}<script type="text/javascript" src="{{ url_for('localeJs', locale=g.locale, domain='messages') }}"></script>{% endif %}
+5 -2
View File
@@ -57,8 +57,11 @@
</span>
{% endif %}
</div>
<div id="gcode_upload_progress" class="progress" style="width: 100%;">
<div class="bar" style="width: 0%"></div>
<div id="gcode_upload_progress" class="progress progress-text-centered">
<span class="progress-text-back" data-bind="text: uploadProgressText"></span>
<div class="bar">
<span class="progress-text-front" data-bind="copyWidth: ':parent :parent :parent :parent form', text: uploadProgressText"></span>
</div>
</div>
<div>
<small class="muted">{{ _('Hint: You can also drag and drop files on this page to upload them.') }}</small>
+17 -11
View File
@@ -1,20 +1,26 @@
{{ _('Machine State') }}: <strong data-bind="text: stateString"></strong><br>
{{ _('File') }}: <strong data-bind="text: filename"></strong>&nbsp;<strong data-bind="visible: sd">(SD)</strong><br>
{{ _('Timelapse') }}: <strong data-bind="text: timelapseString"></strong><br>
<span title="{{ _('Current printer state') }}">{{ _('State') }}</span>: <strong data-bind="text: stateString"></strong><br>
<hr>
<span title="{{ _('Name of file currently selected for printing') }}">{{ _('File') }}</span>: <strong data-bind="text: filename"></strong>&nbsp;<strong data-bind="visible: sd">(SD)</strong><br>
<span title="{{ _('Current timelapse configuration') }}">{{ _('Timelapse') }}</span>: <strong data-bind="text: timelapseString"></strong><br>
<!-- ko foreach: filament -->
<span data-bind="text: 'Filament (' + name() + '): '"></span><strong data-bind="text: formatFilament(data())"></strong><br>
<span data-bind="text: 'Filament (' + name() + '): ', title: 'Filament usage for ' + name()"></span><strong data-bind="text: formatFilament(data())"></strong><br>
<!-- /ko -->
{{ _('Approx. Total Print Time') }}: <strong data-bind="text: estimatedPrintTimeString"></strong><br>
{{ _('Print Time') }}: <strong data-bind="text: printTimeString"></strong><br>
{{ _('Print Time Left') }}: <strong data-bind="text: printTimeLeftString"></strong><br>
{{ _('Printed') }}: <strong data-bind="text: byteString"></strong><br>
<span title="{{ _('Estimated total print time base on statical analysis or past prints') }}">{{ _('Approx. Total Print Time') }}</span>: <strong data-bind="text: estimatedPrintTimeString"></strong><br>
<hr>
<span title="{{ _('Total print time so far') }}">{{ _('Print Time') }}</span>: <strong data-bind="text: printTimeString"></strong><br>
<span title="{{ _('Estimated time until the print job is done. This is only an estimate and accuracy depends heavily on various factors!') }}">{{ _('Print Time Left') }}</span>: <strong data-bind="text: printTimeLeftString"></strong> <span id="state_printtimeleft_popover" style="display: none" data-bind="visible: printTimeLeftOrigin, attr: {title: printTimeLeftOriginString}, css: printTimeLeftOriginClass">&#9679;</span><br>
<span title="{{ _('Bytes printed vs total bytes of file') }}">{{ _('Printed') }}</span>: <strong data-bind="text: byteString"></strong><br>
<div class="progress">
<div class="bar" id="job_progressBar" data-bind="style: { width: progressString() + '%' }"></div>
<div class="progress progress-text-centered">
<span class="progress-text-back" data-bind="text: progressBarString()"></span>
<div class="bar" id="job_progressBar" data-bind="style: {width: progressString() + '%'}">
<span class="progress-text-front" data-bind="copyWidth: ':parent :parent', text: progressBarString()"></span>
</div>
</div>
<div class="row-fluid print-control" style="display: none;" data-bind="visible: loginState.isUser">
<button class="btn btn-primary span4" data-bind="click: print, enable: enablePrint, css: {'btn-danger': isPaused()}, attr: {title: titlePrintButton}" id="job_print"><i class="icon-white" data-bind="css: {'icon-print': !isPaused(), 'icon-undo': isPaused()}"></i> <span data-bind="text: (isPaused() ? '{{ _('Restart') }}' : '{{ _('Print') }}')">{{ _('Print') }}</span></button>
<button class="btn span4" id="job_pause" data-bind="click: pause, enable: enablePause, css: {active: isPaused()}, attr: {title: titlePauseButton}"><i data-bind="css: {'icon-pause': !isPaused(), 'icon-play': isPaused()}"></i> <span data-bind="visible: !isPaused()">{{ _('Pause') }}</span><span data-bind="visible: isPaused()">{{ _('Resume') }}</span></button>
<button class="btn span4" id="job_pause" data-bind="click: function() { isPaused() ? onlyResume() : onlyPause(); }, enable: enablePause, css: {active: isPaused()}, attr: {title: titlePauseButton}"><i data-bind="css: {'icon-pause': !isPaused(), 'icon-play': isPaused()}"></i> <span data-bind="visible: !isPaused()">{{ _('Pause') }}</span><span data-bind="visible: isPaused()">{{ _('Resume') }}</span></button>
<button class="btn span4" id="job_cancel" data-bind="click: cancel, enable: enableCancel" title="{{ _('Cancels the print job') }}"><i class="icon-stop"></i> {{ _('Cancel') }}</button>
</div>
+5 -12
View File
@@ -1,13 +1,6 @@
{% assets "css_libs" %}
<link href="{{ ASSET_URL }}" rel="stylesheet" media="screen">
{% endassets %}
{% assets "css_app" %}
<link href="{{ ASSET_URL }}" rel="stylesheet" media="screen">
{% endassets %}
{% assets "less_app" %}
<link href="{{ ASSET_URL }}" rel="stylesheet/less" type="text/css" media="screen">
{% endassets %}
{% assets "css_libs" %}<link href="{{ ASSET_URL }}" rel="stylesheet" media="screen">{% endassets %}
{% assets "css_core" %}<link href="{{ ASSET_URL }}" rel="stylesheet" media="screen">{% endassets %}
{% assets "css_plugins" %}<link href="{{ ASSET_URL }}" rel="stylesheet" media="screen">{% endassets %}
{% assets "less_core" %}<link href="{{ ASSET_URL }}" rel="stylesheet/less" type="text/css" media="screen">{% endassets %}
{% assets "less_plugins" %}<link href="{{ ASSET_URL }}" rel="stylesheet/less" type="text/css" media="screen">{% endassets %}
<script src="{{ url_for('static', filename='js/lib/less.min.js') }}" type="text/javascript"></script>
@@ -5,8 +5,11 @@
<input id="gcode_slider_commands" type="text" style="width: 554px">
</div>
<div class="progress" >
<div class="bar" style="width: 0%;" data-bind="text: ui_progress_text, style: { width: ui_progress_percentage() + '%' }"></div>
<div class="progress progress-text-centered">
<span class="progress-text-back" data-bind="text: ui_progress_text"></span>
<div class="bar" style="width: 0;" data-bind="style: { width: ui_progress_percentage() + '%' }">
<span class="progress-text-front" data-bind="copyWidth: ':parent :parent', text: ui_progress_text"></span>
</div>
</div>
<div class="row-fluid">
@@ -14,7 +17,7 @@
<h1>{{ _('Model info') }}</h1>
<p data-bind="html: ui_modelInfo"></p>
<h1>Layer info</h1>
<h1>{{ _('Layer info') }}</h1>
<p data-bind="html: ui_layerInfo"></p>
</div>
<div class="span5">
@@ -59,7 +62,13 @@
</div>
<div class="muted">
<small>{{ _('Note that the time estimates in this tab are calculated by the GCODE viewer in your browser and might differ from the values calculated by the server that are displayed in the "State" and "Files" panels in the sidebar due to slightly different implementations.') }}</small>
<small>{% trans %}
Note that the time and usage values in this tab are <strong>estimated</strong> by the GCODE viewer in your
browser and might differ from the values <strong>estimated</strong> by the server that are displayed in the
"State" and "Files" panels in the sidebar due to slightly different implementations. Also note that these
<strong>estimated</strong> values may be inaccurate since they can also take information present in the
GCODE file into account.
{% endtrans %}</small>
</div>
</div>
<div data-bind="visible: waitForApproval">
+2 -1
View File
@@ -1,4 +1,5 @@
# 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'
@@ -735,7 +736,7 @@ class TimelapseRenderJob(object):
command = [
ffmpeg, '-framerate', str(fps), '-loglevel', 'error', '-i', '"{}"'.format(input), '-vcodec', 'mpeg2video',
'-threads', str(threads), '-pix_fmt', 'yuv420p', '-r', str(fps), '-y', '-b', str(bitrate),
'-threads', str(threads), '-pix_fmt', 'yuv420p', '-r', "25", '-y', '-b', str(bitrate),
'-f', 'vob']
filter_string = cls._create_filter_string(hflip=hflip,
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -234,7 +234,7 @@ class FilebasedUserManager(UserManager):
"settings": user._settings
}
with atomic_write(self._userfile, "wb") as f:
with atomic_write(self._userfile, "wb", permissions=0o600, max_permissions=0o666) as f:
yaml.safe_dump(data, f, default_flow_style=False, indent=" ", allow_unicode=True)
self._dirty = False
self._load()
+8 -1
View File
@@ -1,4 +1,6 @@
# coding=utf-8
from __future__ import absolute_import
"""
This module bundles commonly used utility methods or helper classes that are used in multiple places withing
OctoPrint's source code.
@@ -693,12 +695,17 @@ def address_for_client(host, port):
@contextlib.contextmanager
def atomic_write(filename, mode="w+b", prefix="tmp", suffix=""):
def atomic_write(filename, mode="w+b", prefix="tmp", suffix="", permissions=0o644, max_permissions=0o777):
if os.path.exists(filename):
permissions |= os.stat(filename).st_mode
permissions &= max_permissions
temp_config = tempfile.NamedTemporaryFile(mode=mode, prefix=prefix, suffix=suffix, delete=False)
try:
yield temp_config
finally:
temp_config.close()
os.chmod(temp_config.name, permissions)
shutil.move(temp_config.name, filename)
+196 -61
View File
@@ -48,6 +48,7 @@ regex_float = re.compile(regex_float_pattern)
regexes_parameters = dict(
floatP=re.compile("(^|[^A-Za-z])[Pp](?P<value>%s)" % regex_float_pattern),
floatR=re.compile("(^|[^A-Za-z])[Rr](?P<value>%s)" % regex_float_pattern),
floatS=re.compile("(^|[^A-Za-z])[Ss](?P<value>%s)" % regex_float_pattern),
floatZ=re.compile("(^|[^A-Za-z])[Zz](?P<value>%s)" % regex_float_pattern),
intN=re.compile("(^|[^A-Za-z])[Nn](?P<value>%s)" % regex_int_pattern),
@@ -236,6 +237,16 @@ class MachineCom(object):
except:
pass
self._consecutive_timeouts = 0
self._consecutive_timeout_maximums = dict()
for key, value in settings().get(["serial", "maxCommunicationTimeouts"], merged=True, asdict=True).items():
try:
self._consecutive_timeout_maximums[key] = int(value)
except:
pass
self._max_write_passes = settings().getInt(["serial", "maxWritePasses"])
self._hello_command = settings().get(["serial", "helloCommand"])
self._trigger_ok_for_m29 = settings().getBoolean(["serial", "triggerOkForM29"])
@@ -322,6 +333,10 @@ class MachineCom(object):
def __del__(self):
self.close()
@property
def _active(self):
return self._monitoring_active and self._send_queue_active
##~~ internal state management
def _changeState(self, newState):
@@ -386,11 +401,11 @@ class MachineCom(object):
if self._state == self.STATE_PAUSED:
return "Paused"
if self._state == self.STATE_CLOSED:
return "Closed"
return "Offline"
if self._state == self.STATE_ERROR:
return "Error: %s" % (self.getErrorString())
if self._state == self.STATE_CLOSED_WITH_ERROR:
return "Error: %s" % (self.getErrorString())
return "Offline: %s" % (self.getErrorString())
if self._state == self.STATE_TRANSFERING_FILE:
return "Transfering file to SD"
return "?%d?" % (self._state)
@@ -566,15 +581,17 @@ class MachineCom(object):
if not processed:
cmd = process_gcode_line(cmd)
if not cmd:
return
return False
if self.isPrinting() and not self.isSdFileSelected():
try:
self._command_queue.put((cmd, cmd_type), item_type=cmd_type)
return True
except TypeAlreadyInQueue as e:
self._logger.debug("Type already in command queue: " + e.type)
return False
elif self.isOperational() or force:
self._sendCommand(cmd, cmd_type=cmd_type)
return self._sendCommand(cmd, cmd_type=cmd_type)
def sendGcodeScript(self, scriptName, replacements=None):
context = dict()
@@ -921,6 +938,8 @@ class MachineCom(object):
disable_external_heatup_detection = not settings().getBoolean(["feature", "externalHeatupDetection"])
self._consecutive_timeouts = 0
#Open the serial port.
if not self._openSerial():
return
@@ -956,6 +975,7 @@ class MachineCom(object):
if line is None:
break
if line.strip() is not "":
self._consecutive_timeouts = 0
self._timeout = get_new_timeout("communication", self._timeout_intervals)
##~~ debugging output handling
@@ -1120,12 +1140,16 @@ class MachineCom(object):
elif 'File opened' in line and not self._ignore_select:
# answer to M23, at least on Marlin, Repetier and Sprinter: "File opened:%s Size:%d"
match = regex_sdFileOpened.search(line)
if match:
name = match.group("name")
size = int(match.group("size"))
else:
name = "Unknown"
size = 0
if self._sdFileToSelect:
name = self._sdFileToSelect
self._sdFileToSelect = None
else:
name = match.group("name")
self._currentFile = PrintingSdFileInformation(name, int(match.group("size")))
self._currentFile = PrintingSdFileInformation(name, size)
elif 'File selected' in line:
if self._ignore_select:
self._ignore_select = False
@@ -1165,13 +1189,7 @@ class MachineCom(object):
self._handle_ok()
##~~ Message handling
elif line != '' \
and not line.startswith("ok") \
and not line.startswith("wait") \
and not line.startswith('Resend:') \
and line != 'echo:Unknown command:""\n' \
and self.isOperational():
self._callback.on_comm_message(line)
self._callback.on_comm_message(line)
##~~ Parsing for feedback commands
if feedback_controls and feedback_matcher and not "_all" in feedback_errors:
@@ -1232,6 +1250,7 @@ class MachineCom(object):
elif line.startswith("ok"):
self._onConnected()
elif time.time() > self._timeout:
self._log("There was a timeout while trying to connect to the printer")
self.close()
except:
@@ -1240,8 +1259,8 @@ class MachineCom(object):
errorMsg = "See octoprint.log for details"
self._log(errorMsg)
self._errorValue = errorMsg
self._changeState(self.STATE_ERROR)
eventManager().fire(Events.ERROR, {"error": self.getErrorString()})
self.close(is_error=True)
self._log("Connection closed, closing down monitor")
def _handle_ok(self):
@@ -1255,10 +1274,7 @@ class MachineCom(object):
self._currentTool = self._formerTool
self._formerTool = None
if self._heatupWaitStartTime:
self._heatupWaitTimeLost = self._heatupWaitTimeLost + (time.time() - self._heatupWaitStartTime)
self._heatupWaitStartTime = None
self._heating = False
self._finish_heatup()
if not self._state in (self.STATE_PRINTING, self.STATE_OPERATIONAL, self.STATE_PAUSED):
return
@@ -1274,32 +1290,93 @@ class MachineCom(object):
return
def _handle_timeout(self):
if self._state not in (self.STATE_PRINTING,):
return
if self._long_running_command:
self._logger.debug("Ran into a communication timeout, but a command known to be a long runner is currently active")
if self._state not in (self.STATE_PRINTING,
self.STATE_PAUSED,
self.STATE_OPERATIONAL):
return
general_message = "Configure long running commands or increase communication timeout if that happens regularly on specific commands or long moves."
if self._resendActive:
self._log("Communication timeout while printing and during an active resend, resending same line again to trigger response from printer. " + general_message)
self._resendSameCommand()
self._clear_to_send.set()
# figure out which consecutive timeout maximum we have to use
if self._long_running_command:
consecutive_max = self._consecutive_timeout_maximums.get("long", 0)
elif self._state in (self.STATE_PRINTING,):
consecutive_max = self._consecutive_timeout_maximums.get("printing", 0)
else:
self._log("Communication timeout while printing, trying to trigger response from printer. " + general_message)
self._sendCommand("M105", cmd_type="temperature")
consecutive_max = self._consecutive_timeout_maximums.get("idle", 0)
# now increment the timeout counter
self._consecutive_timeouts += 1
self._logger.debug("Now at {} consecutive timeouts".format(self._consecutive_timeouts))
if 0 < consecutive_max < self._consecutive_timeouts:
# too many consecutive timeouts, we give up
message = "No response from printer after {} consecutive communication timeouts, considering it dead.".format(consecutive_max + 1)
self._logger.info(message)
self._log(message + " " + general_message)
self._errorValue = "Too many consecutive timeouts, printer still connected and alive?"
eventManager().fire(Events.ERROR, {"error": self._errorValue})
self.close(is_error=True)
elif self._resendActive:
# resend active, resend same command instead of triggering a new one
message = "Communication timeout during an active resend, resending same line again to trigger response from printer."
self._logger.info(message)
self._log(message + " " + general_message)
if self._resendSameCommand():
self._clear_to_send.set()
elif self._heating:
# blocking heatup active, consider that finished
message = "Timeout while in an active heatup, considering heatup to be over."
self._logger.info(message)
self._finish_heatup()
elif self._long_running_command:
# long running command active, ignore timeout
self._logger.debug("Ran into a communication timeout, but a command known to be a long runner is currently active")
elif self._state in (self.STATE_PRINTING, self.STATE_PAUSED):
# printing, try to tickle the printer
message = "Communication timeout while printing, trying to trigger response from printer."
self._logger.info(message)
self._log(message + " " + general_message)
if self._sendCommand("M105", cmd_type="temperature"):
self._clear_to_send.set()
elif self._clear_to_send.blocked():
# timeout while idle and no oks left, let's try to tickle the printer
message = "Communication timeout while idle, trying to trigger response from printer."
self._logger.info(message)
self._log(message + " " + general_message)
self._clear_to_send.set()
return
def _finish_heatup(self):
if self._heatupWaitStartTime:
self._heatupWaitTimeLost = self._heatupWaitTimeLost + (time.time() - self._heatupWaitStartTime)
self._heatupWaitStartTime = None
self._heating = False
def _continue_sending(self):
if self._state == self.STATE_PRINTING:
if not self._sendFromQueue() and not self.isSdPrinting():
self._sendNext()
elif self._state == self.STATE_OPERATIONAL or self._state == self.STATE_PAUSED:
self._sendFromQueue()
while self._active:
if self._state == self.STATE_OPERATIONAL or self._state == self.STATE_PAUSED or self.isSdPrinting():
# just send stuff from the command queue and be done with it
return self._sendFromQueue()
elif self._state == self.STATE_PRINTING:
# we are printing, we really want to send either something from the command
# queue or the next line from our file, so we only return here if we actually DO
# send something
if self._sendFromQueue():
# we found something in the queue to send
return True
elif self._sendNext():
# we sent the next line from the file
return True
self._logger.debug("No command sent on ok while printing, doing another iteration")
def _process_registered_message(self, line, feedback_matcher, feedback_controls, feedback_errors):
feedback_match = feedback_matcher.search(line)
@@ -1594,10 +1671,24 @@ class MachineCom(object):
def _sendNext(self):
with self._sendNextLock:
line = self._getNext()
if line is not None:
self._sendCommand(line)
while self._active:
# we loop until we've actually enqueued a line for sending
if self._state != self.STATE_PRINTING:
# we are no longer printing, return false
return False
line = self._getNext()
if line is None:
# end of file, return false
return False
result = self._sendCommand(line)
self._callback.on_comm_progress()
if result:
# line sent, return true
return True
self._logger.debug("Command \"{}\" from file not enqueued, doing another iteration".format(line))
def _handleResendRequest(self, line):
try:
@@ -1685,7 +1776,7 @@ class MachineCom(object):
self._handle_ok()
def _resendSameCommand(self):
self._resendNextCommand(again=True)
return self._resendNextCommand(again=True)
def _resendNextCommand(self, again=False):
self._lastCommError = None
@@ -1706,7 +1797,7 @@ class MachineCom(object):
cmd = self._lastLines[-self._resendDelta]
lineNumber = self._currentLine - self._resendDelta
self._enqueue_for_sending(cmd, linenumber=lineNumber)
result = self._enqueue_for_sending(cmd, linenumber=lineNumber)
self._resendDelta -= 1
if self._resendDelta <= 0:
@@ -1714,6 +1805,8 @@ class MachineCom(object):
self._lastResendNumber = None
self._currentResendCount = 0
return result
def _sendCommand(self, cmd, cmd_type=None):
# Make sure we are only handling one sending job at a time
with self._sendingLock:
@@ -1734,11 +1827,11 @@ class MachineCom(object):
eventManager().fire(gcodeToEvent[gcode])
# actually enqueue the command for sending
self._enqueue_for_sending(cmd, command_type=cmd_type)
self._process_command_phase("queued", cmd, cmd_type, gcode=gcode)
return True
if self._enqueue_for_sending(cmd, command_type=cmd_type):
self._process_command_phase("queued", cmd, cmd_type, gcode=gcode)
return True
else:
return False
##~~ send loop handling
@@ -1754,8 +1847,10 @@ class MachineCom(object):
try:
self._send_queue.put((command, linenumber, command_type), item_type=command_type)
return True
except TypeAlreadyInQueue as e:
self._logger.debug("Type already in send queue: " + e.type)
return False
def _send_loop(self):
"""
@@ -1929,24 +2024,56 @@ class MachineCom(object):
return
self._log("Send: " + str(cmd))
try:
self._serial.write(cmd + '\n')
except serial.SerialTimeoutException:
self._log("Serial timeout while writing to serial port, trying again.")
cmd += "\n"
written = 0
passes = 0
while written < len(cmd):
to_send = cmd[written:]
old_written = written
try:
self._serial.write(cmd + '\n')
result = self._serial.write(to_send)
if result is None or not isinstance(result, int):
# probably some plugin not returning the written bytes, assuming all of them
written += len(cmd)
else:
written += result
except serial.SerialTimeoutException:
self._log("Serial timeout while writing to serial port, trying again.")
try:
result = self._serial.write(to_send)
if result is None or not isinstance(result, int):
# probably some plugin not returning the written bytes, assuming all of them
written += len(cmd)
else:
written += result
except:
if not self._connection_closing:
self._logger.exception("Unexpected error while writing to serial port")
self._log("Unexpected error while writing to serial port: %s" % (get_exception_string()))
self._errorValue = get_exception_string()
self.close(is_error=True)
break
except:
if not self._connection_closing:
self._logger.exception("Unexpected error while writing to serial port")
self._log("Unexpected error while writing to serial port: %s" % (get_exception_string()))
self._errorValue = get_exception_string()
self.close(is_error=True)
except:
if not self._connection_closing:
self._logger.exception("Unexpected error while writing to serial port")
self._log("Unexpected error while writing to serial port: %s" % (get_exception_string()))
self._errorValue = get_exception_string()
self.close(is_error=True)
break
if old_written == written:
# nothing written this pass
passes += 1
if passes > self._max_write_passes:
# nothing written in max consecutive passes, we give up
message = "Could not write anything to the serial port in {} tries, something appears to be wrong with the printer communication".format(self._max_write_passes)
self._logger.error(message)
self._log(message)
self._errorValue = "Could not write to serial port"
self.close(is_error=True)
break
##~~ command handlers
@@ -1995,7 +2122,7 @@ class MachineCom(object):
return None, # Don't send bed commands if we don't have a heated bed
_gcode_M190_queuing = _gcode_M140_queuing
def _gcode_M104_sent(self, cmd, cmd_type=None, wait=False):
def _gcode_M104_sent(self, cmd, cmd_type=None, wait=False, support_r=False):
toolNum = self._currentTool
toolMatch = regexes_parameters["intT"].search(cmd)
@@ -2007,6 +2134,9 @@ class MachineCom(object):
self._currentTool = toolNum
match = regexes_parameters["floatS"].search(cmd)
if not match and support_r:
match = regexes_parameters["floatR"].search(cmd)
if match:
try:
target = float(match.group("value"))
@@ -2015,11 +2145,15 @@ class MachineCom(object):
self._temp[toolNum] = (actual, target)
else:
self._temp[toolNum] = (None, target)
self._callback.on_comm_temperature_update(self._temp, self._bedTemp)
except ValueError:
pass
def _gcode_M140_sent(self, cmd, cmd_type=None, wait=False):
def _gcode_M140_sent(self, cmd, cmd_type=None, wait=False, support_r=False):
match = regexes_parameters["floatS"].search(cmd)
if not match and support_r:
match = regexes_parameters["floatR"].search(cmd)
if match:
try:
target = float(match.group("value"))
@@ -2028,6 +2162,7 @@ class MachineCom(object):
self._bedTemp = (actual, target)
else:
self._bedTemp = (None, target)
self._callback.on_comm_temperature_update(self._temp, self._bedTemp)
except ValueError:
pass
@@ -2035,13 +2170,13 @@ class MachineCom(object):
self._heatupWaitStartTime = time.time()
self._long_running_command = True
self._heating = True
self._gcode_M104_sent(cmd, cmd_type, wait=True)
self._gcode_M104_sent(cmd, cmd_type, wait=True, support_r=True)
def _gcode_M190_sent(self, cmd, cmd_type=None):
self._heatupWaitStartTime = time.time()
self._long_running_command = True
self._heating = True
self._gcode_M140_sent(cmd, cmd_type, wait=True)
self._gcode_M140_sent(cmd, cmd_type, wait=True, support_r=True)
def _gcode_M110_sending(self, cmd, cmd_type=None):
newLineNumber = None
+141 -57
View File
@@ -14,6 +14,107 @@ import logging
from octoprint.settings import settings
class Vector3D(object):
"""
3D vector value
Supports addition, subtraction and multiplication with a scalar value (float, int) as well as calculating the
length of the vector.
Examples:
>>> a = Vector3D(1.0, 1.0, 1.0)
>>> b = Vector3D(4.0, 4.0, 4.0)
>>> a + b == Vector3D(5.0, 5.0, 5.0)
True
>>> b - a == Vector3D(3.0, 3.0, 3.0)
True
>>> abs(a - b) == Vector3D(3.0, 3.0, 3.0)
True
>>> a * 2 == Vector3D(2.0, 2.0, 2.0)
True
>>> a * 2 == 2 * a
True
>>> a.length == math.sqrt(a.x ** 2 + a.y ** 2 + a.z ** 2)
True
>>> copied_a = Vector3D(a)
>>> a == copied_a
True
>>> copied_a.x == a.x and copied_a.y == a.y and copied_a.z == a.z
True
"""
def __init__(self, *args, **kwargs):
self.x = kwargs.get("x", 0.0)
self.y = kwargs.get("y", 0.0)
self.z = kwargs.get("z", 0.0)
if len(args) == 3:
self.x = args[0]
self.y = args[1]
self.z = args[2]
elif len(args) == 1:
# copy constructor
other = args[0]
if not isinstance(other, Vector3D):
raise ValueError("Object to copy must be a Vector3D instance")
self.x = other.x
self.y = other.y
self.z = other.z
@property
def length(self):
return math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z)
def __add__(self, other):
if isinstance(other, Vector3D):
return Vector3D(self.x + other.x,
self.y + other.y,
self.z + other.z)
elif isinstance(other, (tuple, list)) and len(other) == 3:
return Vector3D(self.x + other[0],
self.y + other[1],
self.z + other[2])
else:
raise ValueError("other must be a Vector3D instance or a list or tuple of length 3")
def __sub__(self, other):
if isinstance(other, Vector3D):
return Vector3D(self.x - other.x,
self.y - other.y,
self.z - other.z)
elif isinstance(other, (tuple, list)) and len(other) == 3:
return Vector3D(self.x - other[0],
self.y - other[1],
self.z - other[2])
else:
raise ValueError("other must be a Vector3D instance or a list or tuple")
def __mul__(self, other):
if isinstance(other, (int, float)):
return Vector3D(self.x * other,
self.y * other,
self.z * other)
else:
raise ValueError("other must be a float or int value")
def __rmul__(self, other):
return self.__mul__(other)
def __abs__(self):
return Vector3D(abs(self.x), abs(self.y), abs(self.z))
def __eq__(self, other):
if not isinstance(other, Vector3D):
return False
return self.x == other.x and self.y == other.y and self.z == other.z
def __str__(self):
return "Vector3D(x={}, y={}, z={}, length={})".format(self.x, self.y, self.z, self.length)
class AnalysisAborted(Exception):
pass
@@ -46,8 +147,8 @@ class gcode(object):
def _load(self, gcodeFile, printer_profile, throttle=None):
filePos = 0
readBytes = 0
pos = [0.0, 0.0, 0.0]
posOffset = [0.0, 0.0, 0.0]
pos = Vector3D(0.0, 0.0, 0.0)
posOffset = Vector3D(0.0, 0.0, 0.0)
currentE = [0.0]
totalExtrusion = [0.0]
maxExtrusion = [0.0]
@@ -56,10 +157,10 @@ class gcode(object):
absoluteE = True
scale = 1.0
posAbs = True
feedRateXY = min(printer_profile["axes"]["x"]["speed"], printer_profile["axes"]["y"]["speed"])
if feedRateXY == 0:
feedrate = min(printer_profile["axes"]["x"]["speed"], printer_profile["axes"]["y"]["speed"])
if feedrate == 0:
# some somewhat sane default if axes speeds are insane...
feedRateXY = 2000
feedrate = 2000
offsets = printer_profile["extruder"]["offsets"]
for line in gcodeFile:
@@ -117,56 +218,39 @@ class gcode(object):
z = getCodeFloat(line, 'Z')
e = getCodeFloat(line, 'E')
f = getCodeFloat(line, 'F')
oldPos = pos
pos = pos[:]
if posAbs:
if x is not None:
pos[0] = x * scale + posOffset[0]
if y is not None:
pos[1] = y * scale + posOffset[1]
if z is not None:
pos[2] = z * scale + posOffset[2]
else:
if x is not None:
pos[0] += x * scale
if y is not None:
pos[1] += y * scale
if z is not None:
pos[2] += z * scale
if f is not None and f != 0:
feedRateXY = f
moveType = 'move'
oldPos = pos
newPos = Vector3D(x if x is not None else pos.x,
y if y is not None else pos.y,
z if z is not None else pos.z)
if posAbs:
pos = newPos * scale + posOffset
else:
pos += newPos * scale
if f is not None and f != 0:
feedrate = f
if e is not None:
if absoluteE:
# make sure e is relative
e -= currentE[currentExtruder]
if e > 0.0:
moveType = 'extrude'
if e < 0.0:
moveType = 'retract'
totalExtrusion[currentExtruder] += e
currentE[currentExtruder] += e
if totalExtrusion[currentExtruder] > maxExtrusion[currentExtruder]:
maxExtrusion[currentExtruder] = totalExtrusion[currentExtruder]
maxExtrusion[currentExtruder] = max(maxExtrusion[currentExtruder],
totalExtrusion[currentExtruder])
else:
e = 0.0
if x is not None or y is not None or z is not None:
diffX = oldPos[0] - pos[0]
diffY = oldPos[1] - pos[1]
totalMoveTimeMinute += math.sqrt(diffX * diffX + diffY * diffY) / feedRateXY
elif moveType == "extrude":
diffX = oldPos[0] - pos[0]
diffY = oldPos[1] - pos[1]
time1 = math.sqrt(diffX * diffX + diffY * diffY) / feedRateXY
time2 = abs(e / feedRateXY)
totalMoveTimeMinute += max(time1, time2)
elif moveType == "retract":
totalMoveTimeMinute += abs(e / feedRateXY)
# move time in x, y, z, will be 0 if no movement happened
moveTimeXYZ = abs((oldPos - pos).length / feedrate)
# time needed for extruding, will be 0 if no extrusion happened
extrudeTime = abs(e / feedrate)
# time to add is maximum of both
totalMoveTimeMinute += max(moveTimeXYZ, extrudeTime)
if moveType == 'move' and oldPos[2] != pos[2]:
if oldPos[2] > pos[2] and abs(oldPos[2] - pos[2]) > 5.0 and pos[2] < 1.0:
oldPos[2] = 0.0
elif G == 4: #Delay
S = getCodeFloat(line, 'S')
if S is not None:
@@ -182,17 +266,17 @@ class gcode(object):
x = getCodeFloat(line, 'X')
y = getCodeFloat(line, 'Y')
z = getCodeFloat(line, 'Z')
center = [0.0,0.0,0.0]
center = Vector3D(0.0, 0.0, 0.0)
if x is None and y is None and z is None:
pos = center
else:
pos = pos[:]
pos = Vector3D(pos)
if x is not None:
pos[0] = center[0]
pos.x = center.x
if y is not None:
pos[1] = center[1]
pos.y = center.y
if z is not None:
pos[2] = center[2]
pos.z = center.z
elif G == 90: #Absolute position
posAbs = True
elif G == 91: #Relative position
@@ -205,11 +289,11 @@ class gcode(object):
if e is not None:
currentE[currentExtruder] = e
if x is not None:
posOffset[0] = pos[0] - x
posOffset.x = pos.x - x
if y is not None:
posOffset[1] = pos[1] - y
posOffset.y = pos.y - y
if z is not None:
posOffset[2] = pos[2] - z
posOffset.z = pos.z - z
elif M is not None:
if M == 82: #Absolute E
@@ -221,13 +305,13 @@ class gcode(object):
if T > settings().getInt(["gcodeAnalysis", "maxExtruders"]):
self._logger.warn("GCODE tried to select tool %d, that looks wrong, ignoring for GCODE analysis" % T)
else:
posOffset[0] -= offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0
posOffset[1] -= offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0
posOffset.x -= offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0
posOffset.y -= offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0
currentExtruder = T
posOffset[0] += offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0
posOffset[1] += offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0
posOffset.x += offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0
posOffset.y += offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0
if len(currentE) <= currentExtruder:
for i in range(len(currentE), currentExtruder + 1):
+100
View File
@@ -4,8 +4,11 @@ from __future__ import absolute_import
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
import os
from jinja2 import nodes
from jinja2.ext import Extension
from jinja2.loaders import FileSystemLoader, PrefixLoader, ChoiceLoader, \
TemplateNotFound, split_template_path
@@ -51,6 +54,32 @@ class FilteredFileSystemLoader(FileSystemLoader):
return all(filter_results)
class SelectedFileSystemLoader(FileSystemLoader):
def __init__(self, searchpath, files, prefix=None, **kwargs):
FileSystemLoader.__init__(self, searchpath, **kwargs)
self.files = files
if prefix is not None and not prefix.endswith("/"):
prefix += "/"
self.prefix = prefix
def get_source(self, environment, template):
if not template.startswith(self.prefix):
raise TemplateNotFound(template)
template = template[len(self.prefix):]
if not template in self.files:
raise TemplateNotFound(template)
return FileSystemLoader.get_source(self, environment, template)
def list_templates(self):
return [self._prefixed(f) for f in self.files if any(map(lambda folder: os.path.exists(os.path.join(folder, f)), self.searchpath))]
def _prefixed(self, name):
return self.prefix + name if self.prefix else name
def get_all_template_paths(loader):
def walk_folder(folder):
files = []
@@ -68,6 +97,12 @@ def get_all_template_paths(loader):
result += walk_folder(folder)
return filter(loader.path_filter, result)
elif isinstance(loader, SelectedFileSystemLoader):
result = []
for folder in loader.searchpath:
result += filter(lambda x: os.path.exists(f), [os.path.join(folder, f) for f in loader.files])
return result
elif isinstance(loader, FileSystemLoader):
result = []
for folder in loader.searchpath:
@@ -106,3 +141,68 @@ def get_all_asset_paths(env):
# intentionally ignored
pass
return result
class ExceptionHandlerExtension(Extension):
tags = {"try"}
def __init__(self, environment):
super(ExceptionHandlerExtension, self).__init__(environment)
self._logger = logging.getLogger(__name__)
def parse(self, parser):
token = parser.stream.next()
lineno = token.lineno
filename = parser.name
error = parser.parse_expression()
args = [error, nodes.Const(filename), nodes.Const(lineno)]
try:
body = parser.parse_statements(["name:endtry"], drop_needle=True)
node = nodes.CallBlock(self.call_method("_handle_body", args),
[], [], body).set_lineno(lineno)
except Exception as e:
# that was expected
self._logger.exception("Caught exception while parsing template")
node = nodes.CallBlock(self.call_method("_handle_error", [nodes.Const(self._format_error(error, e, filename, lineno))]),
[], [], []).set_lineno(lineno)
return node
def _handle_body(self, error, filename, lineno, caller):
try:
return caller()
except Exception as e:
self._logger.exception("Caught exception while compiling template {filename} at line {lineno}".format(**locals()))
error_string = self._format_error(error, e, filename, lineno)
return error_string if error_string else ""
def _handle_error(self, error, caller):
return error if error else ""
def _format_error(self, error, exception, filename, lineno):
if not error:
return ""
try:
return error.format(exception=exception, filename=filename, lineno=lineno)
except:
self._logger.exception("Error while compiling exception output for template {filename} at line {lineno}".format(**locals()))
return "Unknown error"
trycatch = ExceptionHandlerExtension
class MarkdownFilter(object):
def __init__(self, app, **markdown_options):
self._markdown_options = markdown_options
app.jinja_env.filters.setdefault("markdown", self)
def __call__(self, stream):
from jinja2 import Markup
from markdown import Markdown
# Markdown is not thread safe
markdown = Markdown(**self._markdown_options)
return Markup(markdown.convert(stream))
+11
View File
@@ -0,0 +1,11 @@
# coding=utf-8
"""
Unit tests for ``octoprint.server``.
"""
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"
+10
View File
@@ -0,0 +1,10 @@
# coding=utf-8
"""
Unit tests for ``octoprint.server.util``.
"""
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"
+592
View File
@@ -0,0 +1,592 @@
# coding=utf-8
"""
Unit tests for ``octoprint.server.util.flask``.
"""
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 unittest
import mock
from ddt import ddt, data, unpack
from octoprint.server.util.flask import ReverseProxiedEnvironment, OctoPrintFlaskRequest, OctoPrintFlaskResponse
standard_environ = {
"HTTP_HOST": "localhost:5000",
"SERVER_NAME": "localhost",
"SERVER_PORT": "5000",
"SCRIPT_NAME": "",
"PATH_INFO": "/",
"wsgi.url_scheme": "http"
}
@ddt
class ReverseProxiedEnvironmentTest(unittest.TestCase):
@data(
# defaults
({},
{}),
# prefix set, path info not prefixed
({
"HTTP_X_SCRIPT_NAME": "/octoprint",
"PATH_INFO": "/static/online.gif"
}, {
"SCRIPT_NAME": "/octoprint"
}),
# prefix set, path info prefixed
({
"HTTP_X_SCRIPT_NAME": "/octoprint",
"PATH_INFO": "/octoprint/static/online.gif",
}, {
"SCRIPT_NAME": "/octoprint",
"PATH_INFO": "/static/online.gif"
}),
# host set
({
"HTTP_X_FORWARDED_HOST": "example.com"
}, {
"HTTP_HOST": "example.com",
"SERVER_NAME": "example.com",
"SERVER_PORT": "80"
}),
# host set with port
({
"HTTP_X_FORWARDED_HOST": "example.com:1234"
}, {
"HTTP_HOST": "example.com:1234",
"SERVER_NAME": "example.com",
"SERVER_PORT": "1234"
}),
# host and scheme set
({
"HTTP_X_FORWARDED_HOST": "example.com",
"HTTP_X_FORWARDED_PROTO": "https"
}, {
"HTTP_HOST": "example.com",
"SERVER_NAME": "example.com",
"SERVER_PORT": "443",
"wsgi.url_scheme": "https"
}),
# host and scheme 2 set
({
"HTTP_X_FORWARDED_HOST": "example.com",
"HTTP_X_SCHEME": "https"
}, {
"HTTP_HOST": "example.com",
"SERVER_NAME": "example.com",
"SERVER_PORT": "443",
"wsgi.url_scheme": "https"
}),
# host, server and port headers set -> only host wins
({
"HTTP_X_FORWARDED_HOST": "example.com",
"HTTP_X_FORWARDED_SERVER": "example2.com",
"HTTP_X_FORWARDED_PORT": "444",
"HTTP_X_FORWARDED_PROTO": "https"
}, {
"HTTP_HOST": "example.com",
"SERVER_NAME": "example.com",
"SERVER_PORT": "443",
"wsgi.url_scheme": "https"
}),
# host set, server and port differ -> updated, standard port
({
"HTTP_HOST": "example.com",
"wsgi.url_scheme": "https",
"SERVER_NAME": "localhost",
"SERVER_PORT": "80"
}, {
"HTTP_HOST": "example.com",
"SERVER_NAME": "example.com",
"SERVER_PORT": "443",
}),
# host set, server and port differ -> updated, non standard port
({
"HTTP_HOST": "example.com:444",
"wsgi.url_scheme": "https",
"SERVER_NAME": "localhost",
"SERVER_PORT": "80"
}, {
"HTTP_HOST": "example.com:444",
"SERVER_NAME": "example.com",
"SERVER_PORT": "444",
}),
# multiple scheme entries -> only use first one
({
"HTTP_X_FORWARDED_PROTO": "https,http",
}, {
"wsgi.url_scheme": "https"
}),
# host = none (should never happen but you never know) -> server & port used for reconstruction
({
"HTTP_HOST": None,
"HTTP_X_FORWARDED_SERVER": "example.com",
"HTTP_X_FORWARDED_PORT": "80"
}, {
"HTTP_HOST": "example.com",
"SERVER_NAME": "example.com",
"SERVER_PORT": "80"
}),
# host = none, default port -> server & port used for reconstruction (ipv4)
({
"HTTP_HOST": None,
"SERVER_NAME": "127.0.0.1",
"SERVER_PORT": "80"
}, {
"HTTP_HOST": "127.0.0.1",
"SERVER_NAME": "127.0.0.1",
"SERVER_PORT": "80"
}),
# host = none, non standard port -> server & port used for reconstruction (ipv4)
({
"HTTP_HOST": None,
"SERVER_NAME": "127.0.0.1",
"SERVER_PORT": "444"
}, {
"HTTP_HOST": "127.0.0.1:444",
"SERVER_NAME": "127.0.0.1",
"SERVER_PORT": "444"
}),
# host = none, default port -> server & port used for reconstruction (ipv6)
({
"HTTP_HOST": None,
"SERVER_NAME": "fec1::1",
"SERVER_PORT": "80"
}, {
"HTTP_HOST": "fec1::1",
"SERVER_NAME": "fec1::1",
"SERVER_PORT": "80"
}),
# host = none, non standard port -> server & port used for reconstruction (ipv6)
({
"HTTP_HOST": None,
"SERVER_NAME": "fec1::1",
"SERVER_PORT": "444"
}, {
"HTTP_HOST": "[fec1::1]:444",
"SERVER_NAME": "fec1::1",
"SERVER_PORT": "444"
}),
# host set, server and port not, default port -> server & port derived from host (ipv4)
({
"HTTP_HOST": "127.0.0.1",
"SERVER_NAME": None,
"SERVER_PORT": None
}, {
"HTTP_HOST": "127.0.0.1",
"SERVER_NAME": "127.0.0.1",
"SERVER_PORT": "80"
}),
# host set, server and port not, non standard port -> server & port derived from host (ipv4)
({
"HTTP_HOST": "127.0.0.1:444",
"SERVER_NAME": None,
"SERVER_PORT": None
}, {
"HTTP_HOST": "127.0.0.1:444",
"SERVER_NAME": "127.0.0.1",
"SERVER_PORT": "444"
}),
# host set, server and port not, default port -> server & port derived from host (ipv6)
({
"HTTP_HOST": "fec1::1",
"SERVER_NAME": None,
"SERVER_PORT": None
}, {
"HTTP_HOST": "fec1::1",
"SERVER_NAME": "fec1::1",
"SERVER_PORT": "80"
}),
# host set, server and port not, non standard port -> server & port derived from host (ipv6)
({
"HTTP_HOST": "[fec1::1]:444",
"SERVER_NAME": None,
"SERVER_PORT": None
}, {
"HTTP_HOST": "[fec1::1]:444",
"SERVER_NAME": "fec1::1",
"SERVER_PORT": "444"
}),
)
@unpack
def test_stock(self, environ, expected):
reverse_proxied = ReverseProxiedEnvironment()
merged_environ = dict(standard_environ)
merged_environ.update(environ)
actual = reverse_proxied(merged_environ)
merged_expected = dict(standard_environ)
merged_expected.update(environ)
merged_expected.update(expected)
self.assertDictEqual(merged_expected, actual)
@data(
# server and port headers set -> host derived with port
({
"SERVER_NAME": "example2.com",
"SERVER_PORT": "444",
"HTTP_X_FORWARDED_PROTO": "https"
}, {
"HTTP_HOST": "example2.com:444",
"SERVER_NAME": "example2.com",
"SERVER_PORT": "444",
"wsgi.url_scheme": "https"
}),
# server and port headers set, standard port -> host derived, no port
({
"SERVER_NAME": "example.com",
"SERVER_PORT": "80",
}, {
"HTTP_HOST": "example.com",
"SERVER_NAME": "example.com",
"SERVER_PORT": "80",
}),
# server and port forwarded headers set -> host derived with port
({
"HTTP_X_FORWARDED_SERVER": "example2.com",
"HTTP_X_FORWARDED_PORT": "444",
"HTTP_X_FORWARDED_PROTO": "https"
}, {
"HTTP_HOST": "example2.com:444",
"SERVER_NAME": "example2.com",
"SERVER_PORT": "444",
"wsgi.url_scheme": "https"
}),
# server and port forwarded headers set, standard port -> host derived, no port
({
"HTTP_X_FORWARDED_SERVER": "example.com",
"HTTP_X_FORWARDED_PORT": "80",
}, {
"HTTP_HOST": "example.com",
"SERVER_NAME": "example.com",
"SERVER_PORT": "80",
}),
)
@unpack
def test_nohost(self, environ, expected):
reverse_proxied = ReverseProxiedEnvironment()
merged_environ = dict(standard_environ)
merged_environ.update(environ)
del merged_environ["HTTP_HOST"]
actual = reverse_proxied(merged_environ)
merged_expected = dict(standard_environ)
merged_expected.update(environ)
merged_expected.update(expected)
self.assertDictEqual(merged_expected, actual)
@data(
# prefix overridden
({
"prefix": "fallback_prefix"
}, {
}, {
"SCRIPT_NAME": "fallback_prefix",
}),
# scheme overridden
({
"scheme": "https"
}, {
}, {
"wsgi.url_scheme": "https"
}),
# host overridden, default port
({
"host": "example.com"
}, {
}, {
"HTTP_HOST": "example.com",
"SERVER_NAME": "example.com",
"SERVER_PORT": "80"
}),
# host overridden, included port
({
"host": "example.com:81"
}, {
}, {
"HTTP_HOST": "example.com:81",
"SERVER_NAME": "example.com",
"SERVER_PORT": "81"
}),
# prefix not really overridden, forwarded headers take precedence
({
"prefix": "/octoprint"
}, {
"HTTP_X_SCRIPT_NAME": ""
}, {
}),
# scheme not really overridden, forwarded headers take precedence
({
"scheme": "https"
}, {
"HTTP_X_FORWARDED_PROTO": "http"
}, {
}),
# scheme 2 not really overridden, forwarded headers take precedence
({
"scheme": "https"
}, {
"HTTP_X_SCHEME": "http"
}, {
}),
# host not really overridden, forwarded headers take precedence
({
"host": "example.com:444"
}, {
"HTTP_X_FORWARDED_HOST": "localhost:5000"
}, {
}),
# server not really overridden, forwarded headers take precedence
({
"server": "example.com"
}, {
"HTTP_X_FORWARDED_SERVER": "localhost"
}, {
}),
# port not really overridden, forwarded headers take precedence
({
"port": "444"
}, {
"HTTP_X_FORWARDED_PORT": "5000"
}, {
}),
# server and port not really overridden, Host header wins
({
"server": "example.com",
"port": "80"
}, {
}, {
})
)
@unpack
def test_fallbacks(self, fallbacks, environ, expected):
reverse_proxied = ReverseProxiedEnvironment(**fallbacks)
merged_environ = dict(standard_environ)
merged_environ.update(environ)
actual = reverse_proxied(merged_environ)
merged_expected = dict(standard_environ)
merged_expected.update(environ)
merged_expected.update(expected)
self.assertDictEqual(merged_expected, actual)
@data(
# server overridden
({
"server": "example.com"
}, {
}, {
"HTTP_HOST": "example.com:5000",
"SERVER_NAME": "example.com",
"SERVER_PORT": "5000"
}),
# port overridden, standard port
({
"port": "80"
}, {
}, {
"HTTP_HOST": "localhost",
"SERVER_PORT": "80"
}),
# port overridden, non standard port
({
"port": "81"
}, {
}, {
"HTTP_HOST": "localhost:81",
"SERVER_PORT": "81"
}),
# server and port overridden, default port
({
"server": "example.com",
"port": "80"
}, {
}, {
"HTTP_HOST": "example.com",
"SERVER_NAME": "example.com",
"SERVER_PORT": "80"
}),
# server and port overridden, non default port
({
"server": "example.com",
"port": "81"
}, {
}, {
"HTTP_HOST": "example.com:81",
"SERVER_NAME": "example.com",
"SERVER_PORT": "81"
}),
)
@unpack
def test_fallbacks_nohost(self, fallbacks, environ, expected):
reverse_proxied = ReverseProxiedEnvironment(**fallbacks)
merged_environ = dict(standard_environ)
merged_environ.update(environ)
del merged_environ["HTTP_HOST"]
actual = reverse_proxied(merged_environ)
merged_expected = dict(standard_environ)
merged_expected.update(environ)
merged_expected.update(expected)
self.assertDictEqual(merged_expected, actual)
def test_header_config_ok(self):
result = ReverseProxiedEnvironment.to_header_candidates(["prefix-header1", "prefix-header2"])
self.assertEquals(result, ["HTTP_PREFIX_HEADER1", "HTTP_PREFIX_HEADER2"])
def test_header_config_string(self):
result = ReverseProxiedEnvironment.to_header_candidates("prefix-header")
self.assertEquals(result, ["HTTP_PREFIX_HEADER"])
def test_header_config_none(self):
result = ReverseProxiedEnvironment.to_header_candidates(None)
self.assertEquals(result, [])
##~~
class OctoPrintFlaskRequestTest(unittest.TestCase):
def setUp(self):
self.orig_environment_wrapper = OctoPrintFlaskRequest.environment_wrapper
def tearDown(self):
OctoPrintFlaskRequest.environment_wrapper = staticmethod(self.orig_environment_wrapper)
def test_environment_wrapper(self):
def environment_wrapper(environ):
environ.update({
"TEST": "yes"
})
return environ
OctoPrintFlaskRequest.environment_wrapper = staticmethod(environment_wrapper)
request = OctoPrintFlaskRequest(standard_environ)
self.assertTrue("TEST" in request.environ)
def test_server_name(self):
request = OctoPrintFlaskRequest(standard_environ)
self.assertEquals("localhost", request.server_name)
def test_server_port(self):
request = OctoPrintFlaskRequest(standard_environ)
self.assertEquals("5000", request.server_port)
def test_cookie_suffix(self):
request = OctoPrintFlaskRequest(standard_environ)
self.assertEquals("_P5000", request.cookie_suffix)
def test_cookies(self):
environ = dict(standard_environ)
environ["HTTP_COOKIE"] = "postfixed_P5000=postfixed_value; " \
"postfixed_wrong_P5001=postfixed_wrong_value; " \
"unpostfixed=unpostfixed_value; " \
"both_P5000=both_postfixed_value; " \
"both=both_unpostfixed_value;"
request = OctoPrintFlaskRequest(environ)
cookies = request.cookies
self.assertDictEqual({"postfixed": u"postfixed_value",
"postfixed_wrong_P5001": u"postfixed_wrong_value",
"unpostfixed": u"unpostfixed_value",
"both": u"both_postfixed_value"},
cookies)
##~~
@ddt
class OctoPrintFlaskResponseTest(unittest.TestCase):
@data([None, None],
["/subfolder/", None],
[None, "/some/other/script/root"],
["/subfolder/", "/some/other/script/root"])
@unpack
def test_cookie_set_and_delete(self, path, scriptroot):
environ = dict(standard_environ)
if scriptroot is not None:
environ.update(dict(SCRIPT_NAME=scriptroot))
request = OctoPrintFlaskRequest(environ)
if path:
expected_path = path
else:
expected_path = "/"
if scriptroot:
expected_path = scriptroot + expected_path
if path is not None:
kwargs = dict(path=path)
else:
kwargs = dict()
with mock.patch("flask.request", new=request):
response = OctoPrintFlaskResponse()
# test set_cookie
with mock.patch("flask.Response.set_cookie") as set_cookie_mock:
response.set_cookie("some_key", "some_value", **kwargs)
set_cookie_mock.assert_called_once_with(response, "some_key_P5000", "some_value", path=expected_path)
# test delete_cookie
with mock.patch("flask.Response.delete_cookie") as delete_cookie_mock:
response.delete_cookie("some_key", "some_value", **kwargs)
delete_cookie_mock.assert_called_once_with(response, "some_key_P5000", "some_value", path=expected_path)
+95
View File
@@ -0,0 +1,95 @@
# coding=utf-8
"""
Unit tests for ``octoprint.server.util.tornado``.
"""
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 unittest
import mock
from ddt import ddt, data, unpack
##~~ _parse_header
@ddt
class ParseHeaderTest(unittest.TestCase):
@data(
("form-data; filename=test.gco", "form-data", dict(filename="test.gco")),
("form-data; filename=\"test.gco\"", "form-data", dict(filename="test.gco")),
("form-data; filename=test\\\\.gco", "form-data", dict(filename="test\\\\.gco")),
("form-data; filename=\"test\\\\.gco\"", "form-data", dict(filename="test\\.gco"))
)
@unpack
def test_parse_header_strip_quotes(self, value, expected_key, expected_dict):
from octoprint.server.util.tornado import _parse_header
actual_key, actual_dict = _parse_header(value)
self.assertEqual(expected_key, actual_key)
self.assertDictEqual(expected_dict, actual_dict)
@data(
("form-data; filename=test.gco", "form-data", dict(filename="test.gco")),
("form-data; filename=\"test.gco\"", "form-data", dict(filename="\"test.gco\"")),
("form-data; filename=test\\\\.gco", "form-data", dict(filename="test\\\\.gco")),
("form-data; filename=\"test\\\\.gco\"", "form-data", dict(filename="\"test\\\\.gco\"")),
("form-data; filename=iso-8859-1'en'test.gco", "form-data", dict(filename="iso-8859-1'en'test.gco"))
)
@unpack
def test_parse_header_leave_quotes(self, value, expected_key, expected_dict):
from octoprint.server.util.tornado import _parse_header
actual_key, actual_dict = _parse_header(value, strip_quotes=False)
self.assertEqual(expected_key, actual_key)
self.assertDictEqual(expected_dict, actual_dict)
##~~ _strip_value_quotes
@ddt
class StripValueQuotesTest(unittest.TestCase):
@data(
("", ""),
(None, None),
('"test.gco"', "test.gco"),
('"test".gco', '"test".gco'),
("test\\\\.gco", "test\\\\.gco"),
('"test\\\\.gco"', "test\\.gco")
)
@unpack
def test_strip_value_quotes(self, value, expected):
from octoprint.server.util.tornado import _strip_value_quotes
actual = _strip_value_quotes(value)
self.assertEqual(expected, actual)
##~~ _extended_header_value
@ddt
class ExtendedHeaderValueTest(unittest.TestCase):
@data(
(u"", u""),
(None, None),
(u'"quoted-string"', u"quoted-string"),
(u'"qüöted-string"', u"qüöted-string"),
(u"iso-8859-1'en'%A3%20rates", u"£ rates"),
(u"UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", u"£ and € rates"),
('"quoted-string"', u"quoted-string"),
('"qüöted-string"', u"qüöted-string"),
("iso-8859-1'en'%A3%20rates", u"£ rates"),
("UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", u"£ and € rates")
)
@unpack
def test_extended_header_value(self, value, expected):
from octoprint.server.util.tornado import _extended_header_value
actual = _extended_header_value(value)
self.assertEqual(expected, actual)
+100 -4
View File
@@ -83,13 +83,16 @@ class TestAtomicWrite(unittest.TestCase):
@mock.patch("shutil.move")
@mock.patch("tempfile.NamedTemporaryFile")
def test_atomic_write(self, mock_tempfile, mock_move):
@mock.patch("os.chmod")
@mock.patch("os.path.exists")
def test_atomic_write(self, mock_exists, mock_chmod, mock_tempfile, mock_move):
"""Tests the regular basic "good" case."""
# setup
mock_file = mock.MagicMock()
mock_file.name = "tempfile.tmp"
mock_tempfile.return_value = mock_file
mock_exists.return_value = False
# test
with octoprint.util.atomic_write("somefile.yaml") as f:
@@ -99,11 +102,14 @@ class TestAtomicWrite(unittest.TestCase):
mock_tempfile.assert_called_once_with(mode="w+b", prefix="tmp", suffix="", delete=False)
mock_file.write.assert_called_once_with("test")
mock_file.close.assert_called_once_with()
mock_chmod.assert_called_once_with("tempfile.tmp", 0o644)
mock_move.assert_called_once_with("tempfile.tmp", "somefile.yaml")
@mock.patch("shutil.move")
@mock.patch("tempfile.NamedTemporaryFile")
def test_atomic_write_error_on_write(self, mock_tempfile, mock_move):
@mock.patch("os.chmod")
@mock.patch("os.path.exists")
def test_atomic_write_error_on_write(self, mock_exists, mock_chmod, mock_tempfile, mock_move):
"""Tests the error case where something in the wrapped code fails."""
# setup
@@ -111,6 +117,7 @@ class TestAtomicWrite(unittest.TestCase):
mock_file.name = "tempfile.tmp"
mock_file.write.side_effect = RuntimeError()
mock_tempfile.return_value = mock_file
mock_exists.return_value = False
# test
try:
@@ -124,16 +131,20 @@ class TestAtomicWrite(unittest.TestCase):
mock_tempfile.assert_called_once_with(mode="w+b", prefix="tmp", suffix="", delete=False)
mock_file.close.assert_called_once_with()
self.assertFalse(mock_move.called)
self.assertFalse(mock_chmod.called)
@mock.patch("shutil.move")
@mock.patch("tempfile.NamedTemporaryFile")
def test_atomic_write_error_on_move(self, mock_tempfile, mock_move):
@mock.patch("os.chmod")
@mock.patch("os.path.exists")
def test_atomic_write_error_on_move(self, mock_exists, mock_chmod, mock_tempfile, mock_move):
"""Tests the error case where the final move fails."""
# setup
mock_file = mock.MagicMock()
mock_file.name = "tempfile.tmp"
mock_tempfile.return_value = mock_file
mock_move.side_effect = RuntimeError()
mock_exists.return_value = False
# test
try:
@@ -147,16 +158,20 @@ class TestAtomicWrite(unittest.TestCase):
mock_tempfile.assert_called_once_with(mode="w+b", prefix="tmp", suffix="", delete=False)
mock_file.close.assert_called_once_with()
self.assertTrue(mock_move.called)
self.assertTrue(mock_chmod.called)
@mock.patch("shutil.move")
@mock.patch("tempfile.NamedTemporaryFile")
def test_atomic_write_parameters(self, mock_tempfile, mock_move):
@mock.patch("os.chmod")
@mock.patch("os.path.exists")
def test_atomic_write_parameters(self, mock_exists, mock_chmod, mock_tempfile, mock_move):
"""Tests that the open parameters are propagated properly."""
# setup
mock_file = mock.MagicMock()
mock_file.name = "tempfile.tmp"
mock_tempfile.return_value = mock_file
mock_exists.return_value = False
# test
with octoprint.util.atomic_write("somefile.yaml", mode="w", prefix="foo", suffix="bar") as f:
@@ -165,6 +180,87 @@ class TestAtomicWrite(unittest.TestCase):
# assert
mock_tempfile.assert_called_once_with(mode="w", prefix="foo", suffix="bar", delete=False)
mock_file.close.assert_called_once_with()
mock_chmod.assert_called_once_with("tempfile.tmp", 0o644)
mock_move.assert_called_once_with("tempfile.tmp", "somefile.yaml")
@mock.patch("shutil.move")
@mock.patch("tempfile.NamedTemporaryFile")
@mock.patch("os.chmod")
@mock.patch("os.path.exists")
def test_atomic_custom_permissions(self, mock_exists, mock_chmod, mock_tempfile, mock_move):
"""Tests that custom permissions may be set."""
# setup
mock_file = mock.MagicMock()
mock_file.name = "tempfile.tmp"
mock_tempfile.return_value = mock_file
mock_exists.return_value = False
# test
with octoprint.util.atomic_write("somefile.yaml", permissions=0o755) as f:
f.write("test")
# assert
mock_tempfile.assert_called_once_with(mode="w+b", prefix="tmp", suffix="", delete=False)
mock_file.close.assert_called_once_with()
mock_chmod.assert_called_once_with("tempfile.tmp", 0o755)
mock_move.assert_called_once_with("tempfile.tmp", "somefile.yaml")
@mock.patch("shutil.move")
@mock.patch("tempfile.NamedTemporaryFile")
@mock.patch("os.chmod")
@mock.patch("os.path.exists")
@mock.patch("os.stat")
def test_atomic_permissions_combined(self, mock_stat, mock_exists, mock_chmod, mock_tempfile, mock_move):
"""Tests that the permissions of an existing file are combined with the requested permissions."""
# setup
mock_file = mock.MagicMock()
mock_file.name = "tempfile.tmp"
mock_tempfile.return_value = mock_file
mock_exists.return_value = True
mock_stat_result = mock.MagicMock()
mock_stat_result.st_mode = 0o666
mock_stat.return_value = mock_stat_result
# test
with octoprint.util.atomic_write("somefile.yaml", permissions=0o755) as f:
f.write("test")
# assert
mock_tempfile.assert_called_once_with(mode="w+b", prefix="tmp", suffix="", delete=False)
mock_file.close.assert_called_once_with()
mock_chmod.assert_called_once_with("tempfile.tmp", 0o777) # 0o755 | 0o666
mock_move.assert_called_once_with("tempfile.tmp", "somefile.yaml")
@mock.patch("shutil.move")
@mock.patch("tempfile.NamedTemporaryFile")
@mock.patch("os.chmod")
@mock.patch("os.path.exists")
@mock.patch("os.stat")
def test_atomic_permissions_limited(self, mock_stat, mock_exists, mock_chmod, mock_tempfile, mock_move):
"""Tests that max_permissions limit the combined file permissions."""
# setup
mock_file = mock.MagicMock()
mock_file.name = "tempfile.tmp"
mock_tempfile.return_value = mock_file
mock_exists.return_value = True
mock_stat_result = mock.MagicMock()
mock_stat_result.st_mode = 0o755
mock_stat.return_value = mock_stat_result
# test
with octoprint.util.atomic_write("somefile.yaml", permissions=0o600, max_permissions=0o666) as f:
f.write("test")
# assert
mock_tempfile.assert_called_once_with(mode="w+b", prefix="tmp", suffix="", delete=False)
mock_file.close.assert_called_once_with()
mock_chmod.assert_called_once_with("tempfile.tmp", 0o644) # (0o600 | 0o755) & 0o666 = 0o755 & 0o666
mock_move.assert_called_once_with("tempfile.tmp", "somefile.yaml")
Binary file not shown.
File diff suppressed because it is too large. Load diff
+393 -245
View File
File diff suppressed because it is too large. Load diff